Compare commits

..
Author SHA1 Message Date
joshua 9086b549a8 Merge branch 'docs/release-contracts-1.18-hub-2.22' 2026-11-25 16:28:43 +02:00
joshuaandClaude Opus 5.5 154bb94da7 docs: contracts 1.18.0 and Hub 2.22.0 released; Website status
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:28:42 +02:00
joshua 312c32c6cb Merge branch 'feat/storage-request' 2026-11-25 16:18:48 +02:00
joshuaandClaude Opus 5.5 283e75737d contracts 1.18.0 + website: Get more storage
contracts: hub.storageRequestSchema and its reply, a sample and JSON
Schemas. Website: an Owner or Admin asks for more 5 GB steps under
Media library (signed to the Hub); the heartbeat reports the licence's
storage limit, so the Hub emails the church at 80% and when full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:18:46 +02:00
joshua 53e5de3f14 Merge branch 'feat/website-settings-seo' 2026-11-25 15:30:29 +02:00
joshuaandClaude Opus 5.5 085265392e feat(website): church details, settings, audit log, search engine data, safer editing
Church details saved through Accounts' church.update (live at once).
Settings: Search Console and Bing codes, Coming soon line, menu order.
Audit log and recent edits. A made share image, Event / VideoObject /
PodcastEpisode / BreadcrumbList structured data, permanent redirects
from old page addresses. Saves refused when someone else saved in
between; Ministry leaders' events; templates previewed with the
church's own content before choosing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:30:27 +02:00
joshua d8ed238042 Merge branch 'feat/website-event-feed' 2026-11-25 14:37:43 +02:00
52 changed files with 1238 additions and 108 deletions
+10
View File
@@ -2,6 +2,16 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## contracts@1.18.0 - 2026-11-25
"Get more storage" for the Church Website (WEBSITE-1.0-PLAN §10, decision 12), with Hub 2.22.0.
Additive: products on 1.17.0 keep working.
- **`hub.storageRequestSchema` / `storageRequestResponseSchema`**: a Website asks the Hub for more
5 GB steps (`POST /api/installs/storage-request`, signed as the heartbeat), with what it uses,
its limit and who asked. `hub.STORAGE_STEP_BYTES`. New sample `hub-storage-request.json` and
JSON Schemas `hub-storage-request`, `hub-storage-request-response`.
## events@3.7.0 + @crosscode/ui 0.3.0 - 2026-11-24
Cross Events' public pages use the church's brand style and the shared footer (WEBSITE-1.0-PLAN §9).
+21
View File
@@ -79,6 +79,27 @@
skipped, and the last good copy kept when a fetch fails. Admin → **Linked products**: Connect,
Disconnect, Show events from, Publish my events, Check now. Accounts' signed `church.changed` now
fetches the church profile again at once.
- **Church details** (§2, decision 10): the church's name, colours, fonts and corners, logo,
service times, contact and social links, saved through Accounts' `church.update` as the signed-in
admin; live at once on all the church's sites (not drafts), refused when someone changed them in
between.
- **Settings** (§10): Google Search Console and Bing verification codes (shown on the home page),
the Coming soon line, and the menu's order. **Audit log** for Owners and Admins; **recent edits**
on the dashboard.
- **Search engines** (§11): a share image made from the church's colours and name for pages without
their own; `Event` structured data on the Website's own event pages, `VideoObject` /
`PodcastEpisode` for messages, `BreadcrumbList` on every page but home; a page's old address
sends people on to the new one (permanent redirect) once published.
- **Two editors at once** (§4): a save that someone else's save overtook is refused, saying who, and
nothing is overwritten. **A Ministry leader's events**: an event can belong to a ministry; its
Ministry leader adds and changes it, an Editor publishes it. **Choose your template** with the
church's own content: each template can be previewed on the real site before it's chosen.
- A simple event with an outside link still has its own page here, with a "More information"
button (its address in the event feed).
- **Get more storage** (§10, decision 12; contracts 1.18.0, Hub 2.22.0): an Owner or Admin asks
under Media library (5 GB steps); the request goes to the Hub, which emails Cross Code, and the
new limit arrives with a heartbeat. The heartbeat now reports the licence's storage limit, so the
Hub emails the church at 80% and when it's full.
- The admin page signs people in and out; `/auth/problem` explains a refused sign-in.
- **The church's export** (`scripts/export-church.ts`): `export.json` in
`crosscode.church-export/1` with its `website` part, for `crosscode export` and uninstall.
@@ -1,4 +1,4 @@
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §8, §10).
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §6, §8, §10).
-- CreateSchema
CREATE SCHEMA IF NOT EXISTS "public";
@@ -137,6 +137,7 @@ CREATE TABLE "SimpleEvent" (
"description" TEXT,
"imageId" TEXT,
"link" TEXT,
"ministryId" TEXT,
"cancelled" BOOLEAN NOT NULL DEFAULT false,
"publishedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
@@ -195,6 +196,15 @@ CREATE TABLE "SiteVersion" (
CONSTRAINT "SiteVersion_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SlugHistory" (
"slug" TEXT NOT NULL,
"pageId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SlugHistory_pkey" PRIMARY KEY ("slug")
);
-- CreateTable
CREATE TABLE "PreviewLink" (
"id" TEXT NOT NULL,
+10
View File
@@ -171,6 +171,8 @@ model SimpleEvent {
description String?
imageId String?
link String?
/// A ministry's event: its Ministry leader can add and edit it; an Editor publishes it (§10).
ministryId String?
cancelled Boolean @default(false)
publishedAt DateTime?
updatedAt DateTime @updatedAt
@@ -230,6 +232,14 @@ model SiteVersion {
publishedAt DateTime @default(now())
}
/// A page's earlier address (§6: "Slug changes get a 301 to the new slug"). Published versions
/// send it to wherever the page is now.
model SlugHistory {
slug String @id
pageId String
createdAt DateTime @default(now())
}
/// A shared preview link (§4): the token is stored hashed, expires after 7 days or when revoked.
model PreviewLink {
id String @id @default(uuid())
+52
View File
@@ -0,0 +1,52 @@
/**
* The church's shared details from the Website's admin (WEBSITE-1.0-PLAN §2, decision 10): name,
* colours, brand style (fonts, corners), logo, service times, contact and social links. Accounts
* owns them; the Website saves them through Accounts' `church.update` with the admin as `actor`.
* They aren't drafts: they go live at once on every one of the church's sites, and the screens
* say so. `ifUpdatedAt` refuses a save when someone changed the profile in between.
*/
import { churchEditableSchema, type Church } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { accounts } from '../auth/accounts.js';
import { churchChanged, churchProfile } from '../church/profile.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
type Who = { id: string; role: string };
const patchSchema = churchEditableSchema.extend({ branding: churchEditableSchema.shape.branding.partial() }).partial();
export async function getChurch(ctx: Ctx) {
churchChanged(ctx);
const church = await churchProfile(ctx);
const linked = !!(await ctx.db.productLink.findFirst({ where: { product: 'accounts' } }));
return { church, linked };
}
export async function saveChurch(ctx: Ctx, body: unknown, by: Who): Promise<Church> {
const b = (body ?? {}) as { church?: unknown; ifUpdatedAt?: unknown };
const parsed = patchSchema.safeParse(b.church);
if (!parsed.success) {
const fields: Record<string, string> = {};
for (const i of parsed.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some details need another look.', fields);
}
if (!Object.keys(parsed.data).length) throw new ApiError(400, 'VALIDATION', 'Nothing to change.');
type Reply = { church: Church };
let reply: Reply;
try {
reply = await (await accounts(ctx)).request<Reply>({
type: 'church.update', actor: by.id, church: parsed.data as never,
...(typeof b.ifUpdatedAt === 'string' ? { ifUpdatedAt: b.ifUpdatedAt } : {}),
});
} catch (e) {
const err = e as { code?: string; message?: string; status?: number };
if (err.code === 'PROFILE_CHANGED') throw new ApiError(409, 'PROFILE_CHANGED', 'Someone changed your church\'s details while you were editing. Your changes weren\'t saved: reload to see theirs, then make yours again.');
if (err.code === 'NOT_ALLOWED') throw new ApiError(403, 'NOT_ALLOWED', 'Accounts doesn\'t know you as someone who signs in to this website yet. Sign out and in again, then try once more.');
if (err instanceof ApiError) throw err;
throw new ApiError(err.status && err.status < 500 ? 400 : 502, err.code ?? 'ACCOUNTS_ERROR', err.message ?? 'Accounts didn\'t take the change.');
}
churchChanged(ctx);
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'church_details_changed', targetType: 'church', targetId: null, metadata: { fields: Object.keys(parsed.data) } });
return reply.church;
}
+24 -1
View File
@@ -29,6 +29,19 @@ function check<T>(schema: z.ZodType<T>, body: unknown): T {
return r.data;
}
/**
* Two editors at once (§4): a save says when its form was loaded (`ifUpdatedAt`). If someone else
* saved the same thing since, nothing is overwritten and the editor is told who.
*/
export async function notChangedSince(ctx: Ctx, row: { updatedAt: Date; updatedBy: string | null }, body: unknown, by: Who) {
const given = (body as { ifUpdatedAt?: unknown } | null)?.ifUpdatedAt;
if (typeof given !== 'string') return;
const since = new Date(given);
if (!Number.isFinite(since.getTime()) || row.updatedAt.getTime() <= since.getTime() || row.updatedBy === by.id) return;
const other = row.updatedBy ? await ctx.db.websiteUser.findUnique({ where: { id: row.updatedBy } }) : null;
throw new ApiError(409, 'CHANGED_SINCE', `${other?.name ?? 'Someone else'} changed this while you were editing, so your changes weren't saved. Reload to see theirs, then make yours again.`);
}
// ─── Design ───────────────────────────────────────────────────────────────────
export async function getDesign(ctx: Ctx) {
@@ -114,8 +127,14 @@ async function slugFree(ctx: Ctx, slug: string, except?: string) {
export async function savePage(ctx: Ctx, id: string, body: unknown, by: Who) {
const page = await getPage(ctx, id);
const patch = check(pagePatch, body);
await notChangedSince(ctx, page, body, by);
if (page.kind === 'home') delete patch.slug;
if (patch.slug && patch.slug !== page.slug) await slugFree(ctx, patch.slug, id);
if (patch.slug && patch.slug !== page.slug) {
await slugFree(ctx, patch.slug, id);
// The old address keeps working: it sends people on to the new one once published.
await ctx.db.slugHistory.upsert({ where: { slug: page.slug }, create: { slug: page.slug, pageId: id }, update: { pageId: id } });
await ctx.db.slugHistory.deleteMany({ where: { slug: patch.slug } });
}
await ctx.db.page.update({ where: { id }, data: { ...patch, updatedBy: by.id } });
return getPage(ctx, id);
}
@@ -152,6 +171,7 @@ export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, bo
if (page.kind !== 'home' || !SECTION_TYPES.includes(type as SectionType)) throw new ApiError(400, 'VALIDATION', 'That isn\'t a homepage section.');
const data = check(schemaFor(type), (body as { data?: unknown })?.data);
const existing = page.sections.find((s) => s.type === type);
if (existing) await notChangedSince(ctx, existing, body, by);
if (existing) await ctx.db.section.update({ where: { id: existing.id }, data: { data: data as never, updatedBy: by.id } });
else await ctx.db.section.create({ data: { pageId, type, position: SECTION_TYPES.indexOf(type as SectionType), data: data as never, updatedBy: by.id } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
@@ -177,6 +197,7 @@ export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, bod
const s = page.sections.find((x) => x.id === sectionId);
if (!s) throw new ApiError(404, 'NOT_FOUND', 'That block doesn\'t exist.');
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 } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
@@ -236,6 +257,7 @@ export async function saveMinistry(ctx: Ctx, id: string | null, body: unknown, b
if (id) {
const row = await ctx.db.ministry.findUnique({ where: { id } });
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That ministry doesn\'t exist.');
await notChangedSince(ctx, row, body, by);
return ctx.db.ministry.update({ where: { id }, data });
}
const last = await ctx.db.ministry.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
@@ -256,6 +278,7 @@ export async function saveLeader(ctx: Ctx, id: string | null, body: unknown, by:
if (id) {
const row = await ctx.db.leader.findUnique({ where: { id } });
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That person isn\'t on the team.');
await notChangedSince(ctx, row, body, by);
return ctx.db.leader.update({ where: { id }, data });
}
const last = await ctx.db.leader.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
+17 -3
View File
@@ -12,6 +12,7 @@ import { youtubeId, spotifyEmbed } from '../site/content.js';
import { mediaUrl } from '../site/snapshot.js';
import { getSource, setSource, syncYoutube, uniqueSlug } from '../site/youtube.js';
import { markRemoved, notifyLinks } from '../feed/feed.js';
import { notChangedSince } from './content.js';
type Who = { id: string; role: string };
@@ -120,6 +121,7 @@ const eventSchema = z.object({
location: optional(500),
description: optional(8000),
imageId: z.string().uuid().nullable().default(null),
ministryId: z.string().uuid().nullable().default(null),
link: z.string().trim().max(500).nullable().default(null).refine((v) => !v || /^https:\/\//.test(v), 'An https:// address').transform((v) => v || null),
}).refine((e) => !e.endsAt || new Date(e.endsAt) >= new Date(e.startsAt), { message: 'It ends before it starts', path: ['endsAt'] });
@@ -128,15 +130,27 @@ export async function listEvents(ctx: Ctx) {
const urls = new Map(media.map((m) => [m.id, mediaUrl(m.filename)]));
return rows.map((e) => ({
id: e.id, slug: e.slug, title: e.title, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null, allDay: e.allDay, location: e.location,
description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, link: e.link, cancelled: e.cancelled, published: e.publishedAt !== null,
description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, link: e.link, ministryId: e.ministryId,
cancelled: e.cancelled, published: e.publishedAt !== null, updatedAt: e.updatedAt.toISOString(),
}));
}
const OWN_ONLY = "You can add and change your own ministry's events only.";
export async function saveEvent(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const e = check(eventSchema, body);
const data = { title: e.title, startsAt: new Date(e.startsAt), endsAt: e.endsAt ? new Date(e.endsAt) : null, allDay: e.allDay, location: e.location, description: e.description, imageId: e.imageId, link: e.link, timezone: ctx.config.timezone, updatedBy: by.id };
// A Ministry leader's events are their ministry's (§10); an Editor publishes them.
const leader = by.role === 'ministry_leader' ? await ctx.db.websiteUser.findUnique({ where: { id: by.id } }) : null;
if (leader && (!leader.ministryId || e.ministryId !== leader.ministryId)) throw new ApiError(403, 'FORBIDDEN', OWN_ONLY);
const data = {
title: e.title, startsAt: new Date(e.startsAt), endsAt: e.endsAt ? new Date(e.endsAt) : null, allDay: e.allDay, location: e.location, description: e.description,
imageId: e.imageId, link: e.link, ministryId: e.ministryId, timezone: ctx.config.timezone, updatedBy: by.id,
};
if (id) {
if (!(await ctx.db.simpleEvent.findUnique({ where: { id } }))) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
if (leader && row.ministryId !== leader.ministryId) throw new ApiError(403, 'FORBIDDEN', OWN_ONLY);
await notChangedSince(ctx, row, body, by);
const saved = await ctx.db.simpleEvent.update({ where: { id }, data });
// A live event changed: the church's other sites fetch it now.
if (saved.publishedAt) void notifyLinks(ctx, [id]).catch(() => {});
+29 -2
View File
@@ -17,6 +17,7 @@ import { defaultUploadDir } from '../demo/demoChurch.js';
import { INCLUDED_STORAGE_BYTES } from '../hub/client.js';
import { hubPublicKey, verifyToken } from '../hub/licence.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { mediaUrl } from '../site/snapshot.js';
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
@@ -82,7 +83,7 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.');
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. To get more (5 GB at a time), contact Cross Code; everything already uploaded keeps showing.');
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 base = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}`;
@@ -92,7 +93,7 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
const bytes = made.files.reduce((t, f) => t + f.bytes, 0);
if (s.usedBytes + bytes > s.limitBytes) {
await Promise.all(made.files.map((f) => fs.rm(path.join(dir, path.dirname(base), f.name), { force: true })));
throw new ApiError(409, 'STORAGE_FULL', 'That photo doesn\'t fit in the storage that\'s left, so it wasn\'t added. To get more (5 GB at a time), contact Cross Code.');
throw new ApiError(409, 'STORAGE_FULL', 'That photo doesn\'t fit in the storage that\'s left, so it wasn\'t added. An Owner or Admin can get more under Media library.');
}
const filename = `${base}.${made.main.ext}`;
const row = await ctx.db.mediaAsset.create({
@@ -145,3 +146,29 @@ export async function processImage(body: Buffer, kind: Kind, basePath: string) {
}
return { main, width, height, sizes, files };
}
type StorageAsk = { at: string; steps: number; limitAtRequest: number };
/** The open "Get more storage" request, if any: open until the limit goes up. */
export async function storageRequestStatus(ctx: Ctx, limitBytes: number): Promise<StorageAsk | null> {
const ask = await ctx.settings.json<StorageAsk | null>('storage_request', null);
return ask && limitBytes <= ask.limitAtRequest ? ask : null;
}
/** "Get more storage": asks the Hub (Cross Code adds it to the licence and is paid R20 a month per step). */
export async function requestMoreStorage(ctx: Ctx, steps: number, by: { id: string; role: string }) {
if (!Number.isInteger(steps) || steps < 1 || steps > 10) throw new ApiError(400, 'VALIDATION', 'Ask for 1 to 10 steps of 5 GB.', { steps: '1 to 10' });
const s = await storage(ctx);
const user = await ctx.db.websiteUser.findUnique({ where: { id: by.id } });
const { requestStorage } = await import('../hub/client.js');
let reply;
try {
reply = await requestStorage(ctx, steps, user?.name ?? null, { usedBytes: s.usedBytes, limitBytes: s.limitBytes });
} catch (e) {
const err = e as { message?: string; code?: string; status?: number };
throw new ApiError(err.status && err.status < 500 ? err.status : 502, err.code ?? 'HUB_ERROR', err.message ?? 'The Hub could not take the request. Try again later.');
}
await ctx.settings.set('storage_request', JSON.stringify({ at: reply.requestedAt, steps: reply.steps, limitAtRequest: s.limitBytes } satisfies StorageAsk));
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'storage_requested', targetType: 'storage', targetId: null, metadata: { steps } });
return { ...reply, request: await storageRequestStatus(ctx, s.limitBytes) };
}
+25 -8
View File
@@ -15,12 +15,14 @@ import { TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_VARIANTS } from '../sit
import { changes, discard, restore } from '../site/workingCopy.js';
import * as content from './content.js';
import * as people from './people.js';
import * as church from './church.js';
import * as settings from './settings.js';
import * as happenings from './happenings.js';
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 { MAX_UPLOAD_BYTES, storage, upload } from './media.js';
import { MAX_UPLOAD_BYTES, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
const who = (req: Request) => ({ id: req.signed!.user.id, role: req.signed!.user.role });
@@ -37,19 +39,21 @@ export function adminRouter(ctx: Ctx) {
/** The dashboard: pending changes, the last publish, storage, and the setup checklist (§10). */
r.get('/overview', handle(async () => {
const [pending, last, s, church, design, pages, ministries] = await Promise.all([
const [pending, last, s, profile, design, pages, ministries, recent] = await Promise.all([
changes(ctx), ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' } }), storage(ctx), churchProfile(ctx),
ctx.db.siteDesign.findUnique({ where: { id: 1 } }), content.listPages(ctx), content.listMinistries(ctx),
ctx.db.siteDesign.findUnique({ where: { id: 1 } }), content.listPages(ctx), content.listMinistries(ctx), settings.auditLog(ctx, { take: 12 }),
]);
const palette = church ? buildPalette(church.branding.colours.primary, church.branding.colours.accent) : null;
const palette = profile ? buildPalette(profile.branding.colours.primary, profile.branding.colours.accent) : null;
return {
pending: pending.length,
/** Recent edits (§10): the audit log without sign-ins. */
recent: recent.filter((e) => !/^(Signed|Was refused)/.test(e.action)).slice(0, 5),
lastPublished: last ? { number: last.number, at: last.publishedAt.toISOString() } : null,
storage: s,
colourNotes: palette?.notes ?? [],
checklist: [
{ key: 'template', label: 'Choose your template', done: !!design, href: '/admin/template' },
{ key: 'profile', label: 'Add your service times and address (your church profile in Accounts)', done: !!church && church.serviceTimes.length > 0 && !!church.contact.address, href: null },
{ key: 'profile', label: 'Add your service times and address', done: !!profile && profile.serviceTimes.length > 0 && !!profile.contact.address, href: '/admin/church' },
{ key: 'pages', label: 'Write your home page and Plan your visit', done: pages.some((p) => p.kind === 'visit'), href: '/admin/pages' },
{ key: 'ministries', label: 'Add your ministries', done: ministries.length > 0, href: '/admin/ministries' },
{ key: 'publish', label: 'Preview and publish', done: !!last, href: '/admin/publish' },
@@ -92,10 +96,13 @@ export function adminRouter(ctx: Ctx) {
// ─── Media library and storage ───
r.get('/media', handle(async () => {
const rows = await ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } });
return { storage: await storage(ctx), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes })) };
const s = await storage(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 })) };
}));
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_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))));
r.put('/media/:id', editor, json, handle(async (req) => {
const alt = String(req.body?.alt ?? '').trim().slice(0, 500);
const m = await ctx.db.mediaAsset.update({ where: { id: param(req, 'id') }, data: { alt } }).catch(() => null);
@@ -112,8 +119,10 @@ export function adminRouter(ctx: Ctx) {
r.put('/messages-youtube', editor, json, handle((req) => happenings.saveYoutube(ctx, req.body, who(req))));
r.post('/messages-youtube/sync', editor, handle(() => syncYoutube(ctx)));
r.get('/events', handle(() => happenings.listEvents(ctx)));
r.post('/events', editor, json, handle((req) => happenings.saveEvent(ctx, null, req.body, who(req))));
r.put('/events/:id', editor, json, handle((req) => happenings.saveEvent(ctx, param(req, 'id'), req.body, who(req))));
// An Editor, or a Ministry leader for their own ministry's events (checked in saveEvent).
const eventWriter = requireRole(ctx, 'ministry_leader');
r.post('/events', eventWriter, json, handle((req) => happenings.saveEvent(ctx, null, req.body, who(req))));
r.put('/events/:id', eventWriter, json, handle((req) => happenings.saveEvent(ctx, param(req, 'id'), req.body, who(req))));
r.post('/events/:id/state', editor, json, handle(async (req) => {
const b = req.body ?? {};
await happenings.setEventState(ctx, param(req, 'id'), { ...(typeof b.published === 'boolean' ? { published: b.published } : {}), ...(typeof b.cancelled === 'boolean' ? { cancelled: b.cancelled } : {}) }, who(req));
@@ -121,6 +130,14 @@ export function adminRouter(ctx: Ctx) {
}));
r.delete('/events/:id', editor, handle(async (req) => { await happenings.deleteEvent(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
// ─── The church's shared details (through Accounts, live at once), settings, audit log ───
r.get('/church', handle(() => church.getChurch(ctx)));
r.put('/church', editor, json, handle((req) => church.saveChurch(ctx, req.body, who(req))));
r.get('/settings', handle(() => settings.getSettings(ctx)));
r.put('/settings', editor, json, handle((req) => settings.saveSettings(ctx, req.body, who(req))));
r.put('/pages-order', editor, json, handle((req) => settings.orderPages(ctx, req.body, who(req))));
r.get('/audit', requireRole(ctx, 'admin'), handle((req) => settings.auditLog(ctx, { before: typeof req.query.before === 'string' ? req.query.before : undefined })));
// ─── Linked products and the event feed (§8, §9) ───
r.get('/links', handle(async () => {
const [listed, links, publishing] = await Promise.all([linkedProducts(ctx), ctx.db.productLink.findMany(), publishOn(ctx)]);
@@ -0,0 +1,93 @@
/**
* The site's own settings (WEBSITE-1.0-PLAN §10, "Settings"), live at once (they aren't the site's
* design): the Coming soon line (§5), and the search engines' verification codes (ROADMAP-v3 §11:
* Google Search Console and Bing Webmaster Tools), shown as `<meta>` tags on the home page. Also the
* menu's order, and the audit log.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
/** What the search engines give: the content of their meta tag, or the whole tag pasted in. */
const code = z.string().trim().max(300)
.transform((v) => (/content="([^"]+)"/.exec(v)?.[1] ?? v).trim())
.refine((v) => v === '' || /^[\w-]{6,100}$/.test(v), 'The code from the search engine (letters, numbers, - and _)');
const schema = z.object({
comingSoonText: z.string().trim().max(300).optional(),
googleVerification: code.optional(),
bingVerification: code.optional(),
});
export type SiteSettings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null };
export async function getSettings(ctx: Ctx): Promise<SiteSettings> {
const [coming, google, bing] = await Promise.all([ctx.settings.get('coming_soon_text'), ctx.settings.get('google_verification'), ctx.settings.get('bing_verification')]);
return { comingSoonText: coming || 'Our new website is on its way.', googleVerification: google || null, bingVerification: bing || null };
}
export async function saveSettings(ctx: Ctx, body: unknown, by: { id: string; role: string }) {
const r = schema.safeParse(body);
if (!r.success) {
const fields: Record<string, string> = {};
for (const i of r.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some settings need another look.', fields);
}
const s = r.data;
await ctx.settings.setMany({
...(s.comingSoonText !== undefined ? { coming_soon_text: s.comingSoonText || null } : {}),
...(s.googleVerification !== undefined ? { google_verification: s.googleVerification || null } : {}),
...(s.bingVerification !== undefined ? { bing_verification: s.bingVerification || null } : {}),
});
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'settings_changed', targetType: 'settings', targetId: null, metadata: { fields: Object.keys(s) } });
return getSettings(ctx);
}
/** The menu's order: pages in the order given (§10, "Navigation"). A draft, like any page change. */
export async function orderPages(ctx: Ctx, body: unknown, by: { id: string }) {
const ids = z.array(z.string().uuid()).max(200).safeParse((body as { ids?: unknown } | null)?.ids);
if (!ids.success) throw new ApiError(400, 'VALIDATION', 'Give the pages in order.');
const pages = await ctx.db.page.findMany({ where: { archivedAt: null } });
const known = new Set(pages.map((p) => p.id));
if (ids.data.some((id) => !known.has(id))) throw new ApiError(400, 'VALIDATION', "That isn't one of the site's pages.");
for (const [n, id] of ids.data.entries()) {
const p = pages.find((x) => x.id === id)!;
if (p.position !== n + 1) await ctx.db.page.update({ where: { id }, data: { position: n + 1, updatedBy: by.id } });
}
return { ok: true };
}
const ACTIONS: Record<string, string> = {
site_published: 'Published the site', change_discarded: 'Discarded a change', version_restored: 'Restored a version',
preview_link_created: 'Made a preview link', preview_link_revoked: 'Stopped a preview link',
first_owner_signed_in: 'Signed in as the first Owner', admin_signed_in: 'Signed in', admin_signed_out: 'Signed out',
admin_sign_in_refused: 'Was refused sign-in (no role here)', website_user_added: 'Gave someone access',
website_user_role_changed: "Changed someone's role", website_user_removed: "Removed someone's access",
website_user_deleted: 'An account was deleted in Accounts', message_published: 'Published a message',
message_unpublished: 'Took a message off the site', message_deleted: 'Removed a message',
youtube_source_set: 'Set the YouTube channel or playlist', event_changed: 'Changed an event', event_deleted: 'Removed an event',
church_details_changed: "Changed the church's details", settings_changed: 'Changed the settings',
product_link_connected: 'Connected a product', product_link_disconnected: 'Disconnected a product', storage_requested: 'Asked for more storage',
};
const ROLE_ACTORS: Record<string, string> = { system: 'The site itself', linked_product: 'A linked product', accounts: 'Accounts' };
/** The audit log (§4: "an audit log of who changed what"), newest first. */
export async function auditLog(ctx: Ctx, opts: { before?: string; take?: number } = {}) {
const take = Math.min(200, Math.max(1, opts.take ?? 100));
const before = opts.before ? new Date(opts.before) : null;
const where = before && Number.isFinite(before.getTime()) ? { createdAt: { lt: before } } : {};
const rows = await ctx.db.auditLog.findMany({ where, orderBy: { createdAt: 'desc' }, take });
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
return rows.map((r) => {
const meta = (r.metadata ?? {}) as Record<string, unknown>;
const detail = [meta.title, meta.label, meta.note].find((x) => typeof x === 'string') as string | undefined;
return {
at: r.createdAt.toISOString(),
who: (r.actorId && names.get(r.actorId)) || ROLE_ACTORS[r.actorRole] || 'Someone',
action: ACTIONS[r.action] ?? r.action.replace(/_/g, ' '),
detail: detail ?? null,
};
});
}
+5 -1
View File
@@ -14,6 +14,7 @@
*/
import path from 'node:path';
import express from 'express';
import { websiteTemplateSchema } from '@crosscode/contracts';
import type { Ctx } from './context.js';
import { authRouter } from './auth/routes.js';
import { adminRouter } from './admin/routes.js';
@@ -53,7 +54,10 @@ export function createApp(ctx: Ctx) {
if (!signed && !(await previewTokenValid(ctx, req.get('x-preview-token')))) throw new ApiError(401, 'NO_PREVIEW', 'This preview has ended, or you need to sign in.');
res.set('Cache-Control', 'no-store');
res.set('X-Robots-Tag', 'noindex, nofollow');
return { ...(await previewContent(ctx)), preview: { by: signed ? 'admin' : 'link', canPublish: !!signed && atLeast(signed.user.role, 'editor') } };
// An admin trying a template on (Template and style): the content in it, nothing saved.
const t = websiteTemplateSchema.safeParse(req.get('x-preview-template'));
const asTemplate = signed && t.success ? t.data : undefined;
return { ...(await previewContent(ctx, { asTemplate })), preview: { by: signed ? 'admin' : 'link', canPublish: !!signed && atLeast(signed.user.role, 'editor') && !asTemplate, template: asTemplate ?? null } };
}));
site.get('/content', handle(async (_req, res) => {
// Short: Publish shows within a minute even where a proxy caches.
+20 -2
View File
@@ -14,6 +14,7 @@ import { appVersion } from '../lib/version.js';
import { connectAccountsIfListed } from '../links/connect.js';
import { keyPair, saveLinkedProducts } from '../links/store.js';
import { hubPublicKey, verifyToken } from './licence.js';
import { storage } from '../admin/media.js';
export const PROTOCOL_VERSION = 2;
const TIMEOUT_MS = 15000;
@@ -81,7 +82,7 @@ export async function stats(ctx: Ctx) {
ctx.db.simpleEvent.count({ where: { startsAt: { gte: now }, publishedAt: { not: null } } }),
ctx.db.importedEvent.count({ where: { startsAt: { gte: now } } }),
ctx.db.websiteUser.count({ where: { role: { not: 'viewer' } } }),
ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }),
storage(ctx),
]);
return {
// Until pages are published one by one, "published" is whether the site has been (0 or 1+ versions).
@@ -89,7 +90,9 @@ export async function stats(ctx: Ctx) {
messages: { total, last30d },
events: { upcomingSimple, imported },
editors,
storage: { usedBytes: media._sum.bytes ?? 0, includedBytes: INCLUDED_STORAGE_BYTES },
// The limit the licence gives (5 GB plus steps bought): the Hub emails the church's admin at
// 80% and 100% (decision 12).
storage: { usedBytes: media.usedBytes, includedBytes: media.limitBytes },
};
}
@@ -196,3 +199,18 @@ export function startHeartbeats(ctx: Ctx): () => void {
timer.unref?.();
return () => clearInterval(timer);
}
/**
* "Get more storage" (WEBSITE-1.0-PLAN §10, decision 12; contracts 1.18.0): asks the Hub for more
* 5 GB steps. The Hub emails Cross Code; the new limit arrives with a later heartbeat answer.
*/
export async function requestStorage(ctx: Ctx, steps: number, requestedBy: string | null, now: { usedBytes: number; limitBytes: number }) {
const installId = await ctx.settings.get('hub_install_id');
const secret = await ctx.settings.get('hub_install_secret');
if (!installId || !secret) throw new HubError('This site isn\'t connected to the Hub yet, so it can\'t ask for more storage.', 'NOT_CONNECTED', 503);
const body = hub.storageRequestSchema.parse({ protocolVersion: PROTOCOL_VERSION, steps, usedBytes: now.usedBytes, limitBytes: now.limitBytes, requestedBy });
const data = await post(ctx, '/api/installs/storage-request', body, { installId, secret });
const reply = hub.storageRequestResponseSchema.safeParse(data);
if (!reply.success) throw new HubError('The Hub answered in a way this site doesn\'t understand.', 'BAD_REPLY', 502);
return reply.data;
}
+14 -6
View File
@@ -21,6 +21,10 @@ export type SiteEvent = {
image: Image | null;
/** The event's page: on this site, or at its origin (Cross Events, for registering). */
url: string;
/** The Website's own events: their page here is /events/<slug> (`url` may be their outside link). */
slug: string | null;
/** 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;
};
@@ -44,6 +48,8 @@ type Common = {
palette: Palette;
/** The shared brand style, else what the template suggests (§3). */
style: { fontPairing: string; corners: string };
/** Search engines' verification codes, for the home page's meta tags (§11). */
verification: { google: string | null; bing: string | null };
};
export type SiteContent =
@@ -116,14 +122,14 @@ async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
};
const own: SiteEvent[] = simple.map((e) => ({
title: e.title, summary: e.description ? e.description.slice(0, 200) : null, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null,
allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, from: 'website', registration: null,
allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, slug: e.slug, link: e.link, from: 'website', registration: null,
}));
const copies: SiteEvent[] = imported.flatMap((row) => {
const e = row.data as unknown as CrosscodeEvent;
if (!e?.title || (e.endsAt ? new Date(e.endsAt) < now : new Date(e.startsAt) < now)) return [];
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, from: e.origin.product,
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,
} satisfies SiteEvent];
});
@@ -137,17 +143,19 @@ export async function siteContent(ctx: Ctx): Promise<SiteContent> {
}
/** The preview (§4): the working copy as it would look published, whatever was published before. */
export async function previewContent(ctx: Ctx): Promise<SiteContent> {
const [church, snapshot] = await Promise.all([churchProfile(ctx), buildSnapshot(ctx)]);
export async function previewContent(ctx: Ctx, opts: { asTemplate?: WebsiteTemplate } = {}): Promise<SiteContent> {
const [church, snapshot] = await Promise.all([churchProfile(ctx), buildSnapshot(ctx, opts)]);
return contentFrom(ctx, church, { number: 0, publishedAt: ctx.now(), snapshot });
}
async function contentFrom(ctx: Ctx, church: Church | null, published: { number: number; publishedAt: Date; snapshot: Snapshot } | null): Promise<SiteContent> {
const [google, bing] = await Promise.all([ctx.settings.get('google_verification'), ctx.settings.get('bing_verification')]);
const verification = { google: google || null, bing: bing || null };
if (!published) {
const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } });
const template = (design?.template ?? 'heritage') as WebsiteTemplate;
return {
mode: 'coming-soon', template, church, ...brandFor(church, template),
mode: 'coming-soon', template, church, ...brandFor(church, template), verification,
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
};
}
@@ -158,5 +166,5 @@ async function contentFrom(ctx: Ctx, church: Church | null, published: { number:
return [p.path, headerIsTransparent(template, snapshot.design.style.header, hero)];
}));
const [messages, events] = await Promise.all([liveMessages(ctx), liveEvents(ctx)]);
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), messages, events };
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), verification, messages, events };
}
+18 -4
View File
@@ -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, type SectionType, type SiteDesign } from './variants.js';
import { defaultDesign, isVariant, SECTION_TYPES, switchTemplate, type SectionType, type SiteDesign } from './variants.js';
export const SNAPSHOT_VERSION = 1;
@@ -44,6 +44,8 @@ export type Snapshot = {
leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[];
/** Every image the sections refer to, by media id. */
media: Record<string, Image>;
/** Earlier page addresses (without the /) and the path each page has now: a permanent redirect. */
redirects: Record<string, string>;
/** The working copy's rows at publish time: Restore and Discard copy from here (§4). */
source: Source;
};
@@ -117,9 +119,20 @@ export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source
}
/** The working copy as a snapshot (what Publish saves, and what the preview shows). */
export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
const [w, media] = await Promise.all([readWorkingCopy(ctx), ctx.db.mediaAsset.findMany()]);
return snapshotFrom(toSource(w), media);
export async function buildSnapshot(ctx: Ctx, opts: { asTemplate?: WebsiteTemplate } = {}): Promise<Snapshot> {
const [w, media, history] = await Promise.all([readWorkingCopy(ctx), ctx.db.mediaAsset.findMany(), ctx.db.slugHistory.findMany()]);
const source = toSource(w);
// "Choose your template" (ROADMAP-v3 §6): the church's own content in another template, as a
// switch would make it, without saving anything.
if (opts.asTemplate) source.design = switchTemplate(cleanDesign(source.design), opts.asTemplate).design;
const snap = snapshotFrom(source, media);
const pathOf = new Map(w.pages.map((p) => [p.id, p.kind === 'home' ? '/' : `/${p.slug}`]));
const live = new Set(w.pages.map((p) => p.slug));
for (const h of history) {
const to = pathOf.get(h.pageId);
if (to && !live.has(h.slug)) snap.redirects[h.slug] = to;
}
return snap;
}
export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
@@ -169,6 +182,7 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
ministries: source.ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
leaders: source.leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
media: used,
redirects: {},
source,
};
}
@@ -0,0 +1,87 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
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 { harness, SITE } from './support/harness.js';
async function site() {
const h = await harness({ linked: false });
const people = { ann: '00000000-0000-4000-8000-00000000000a', ben: '00000000-0000-4000-8000-00000000000b', lee: '00000000-0000-4000-8000-00000000000c' };
const kids = await h.db.ministry.create({ data: { slug: 'kids', name: 'Kids' } });
const youth = await h.db.ministry.create({ data: { slug: 'youth', name: 'Youth' } });
await h.db.websiteUser.create({ data: { id: people.ann, name: 'Ann', email: 'ann@hope.test', role: 'editor' } });
await h.db.websiteUser.create({ data: { id: people.ben, name: 'Ben', email: 'ben@hope.test', role: 'editor' } });
await h.db.websiteUser.create({ data: { id: people.lee, name: 'Lee', email: 'lee@hope.test', role: 'ministry_leader', ministryId: kids.id } });
for (const [k, id] of Object.entries(people)) await h.db.session.create({ data: { tokenHash: hashToken(k), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const as = (who: keyof typeof people) => (m: 'get' | 'post' | 'put', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', `ccw_session=${who}`).set('Origin', SITE);
return b ? r.send(b) : r;
};
return { ...h, as, kids, youth };
}
describe('two editors at once (§4)', () => {
it("doesn't overwrite someone else's save, and says who", async () => {
const { as, db } = await site();
const page = await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About' } });
const loaded = (await as('ann')('get', `/pages/${page.id}`)).body.updatedAt;
await new Promise((r) => setTimeout(r, 5));
assert.equal((await as('ben')('put', `/pages/${page.id}`, { title: "Ben's title", ifUpdatedAt: loaded })).status, 200);
const ann = await as('ann')('put', `/pages/${page.id}`, { title: "Ann's title", ifUpdatedAt: loaded });
assert.equal(ann.status, 409);
assert.match(ann.body.error.message, /^Ben changed this/);
assert.equal((await as('ann')('get', `/pages/${page.id}`)).body.title, "Ben's title");
// Her own earlier save never blocks her.
const fresh = (await as('ann')('get', `/pages/${page.id}`)).body.updatedAt;
assert.equal((await as('ann')('put', `/pages/${page.id}`, { title: 'One', ifUpdatedAt: fresh })).status, 200);
assert.equal((await as('ann')('put', `/pages/${page.id}`, { title: 'Two', ifUpdatedAt: fresh })).status, 200);
});
});
describe("a Ministry leader's events (§10)", () => {
it('adds and changes their own ministry\'s events only, and an Editor publishes them', async () => {
const { as, kids, youth } = await site();
const startsAt = new Date(Date.now() + 864e5).toISOString();
assert.equal((await as('lee')('post', '/events', { title: 'Youth night', startsAt, ministryId: youth.id })).status, 403);
assert.equal((await as('lee')('post', '/events', { title: 'No ministry', startsAt })).status, 403);
const mine = await as('lee')('post', '/events', { title: 'Kids party', startsAt, ministryId: kids.id });
assert.equal(mine.status, 200);
assert.equal((await as('lee')('put', `/events/${mine.body.id}`, { title: 'Kids party!', startsAt, ministryId: kids.id })).status, 200);
assert.equal((await as('lee')('post', `/events/${mine.body.id}/state`, { published: true })).status, 403);
const other = await as('ann')('post', '/events', { title: 'Picnic', startsAt });
assert.equal((await as('lee')('put', `/events/${other.body.id}`, { title: 'Mine now', startsAt, ministryId: kids.id })).status, 403);
assert.equal((await as('ann')('post', `/events/${mine.body.id}/state`, { published: true })).status, 200);
});
});
describe('choosing a template with the church\'s own content', () => {
it('previews the content in another template without saving anything', async () => {
const { ctx, db, as, app } = await site();
await db.siteDesign.create({ data: { id: 1, template: 'heritage', variants: {}, home: [], style: {} } });
const c = await previewContent(ctx, { asTemplate: 'bold' });
assert.equal(c.mode === 'published' && c.snapshot.design.template, 'bold');
assert.equal((await as('ann')('get', '/design')).body.design.template, 'heritage', 'nothing saved');
const viaHeader = await request(app).get('/api/v1/site/preview').set('Cookie', 'ccw_session=ann').set('x-preview-template', 'clean');
assert.equal(viaHeader.body.snapshot.design.template, 'clean');
assert.equal(viaHeader.body.preview.canPublish, false, 'no publishing from a try-on');
});
});
describe('an address that changed (§6)', () => {
it('sends the old address on to the new one once published', async () => {
const { ctx, db, as } = await site();
const page = await db.page.create({ data: { kind: 'custom', slug: 'youth-camp', title: 'Youth camp' } });
await as('ann')('put', `/pages/${page.id}`, { slug: 'camp' });
await as('ann')('put', `/pages/${page.id}`, { slug: 'summer-camp' });
await publish(ctx, { id: 'x', role: 'system' });
const c = await siteContent(ctx);
assert.deepEqual(c.mode === 'published' && c.snapshot.redirects, { 'youth-camp': '/summer-camp', camp: '/summer-camp' });
// A new page taking an old address wins over its redirect.
await db.page.create({ data: { kind: 'custom', slug: 'camp', title: 'Camp info' } });
await publish(ctx, { id: 'x', role: 'system' });
const after = await siteContent(ctx);
assert.deepEqual(after.mode === 'published' && after.snapshot.redirects, { 'youth-camp': '/summer-camp' });
});
});
@@ -0,0 +1,70 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { siteContent } from '../src/site/content.js';
import { harness, SITE } from './support/harness.js';
async function site(role: 'owner' | 'editor' | 'viewer' = 'owner') {
const h = await harness();
const id = '00000000-0000-4000-8000-000000000001';
await h.db.websiteUser.create({ data: { id, name: 'Sam', email: 'sam@hope.test', role } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const go = (m: 'get' | 'post' | 'put', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
return { ...h, go, id };
}
describe("the church's shared details, saved through Accounts (decision 10)", () => {
it('sends only what changed, as the signed-in admin', async () => {
const { go, fake, id } = await site();
const r = await go('put', '/church', { church: { serviceTimes: [{ day: 'sunday', time: '09:30', label: 'Morning', campus: null, note: null }] }, ifUpdatedAt: '2026-11-25T08:00:00.000Z' });
assert.equal(r.status, 200);
const sent = fake.requests.at(-1)!;
assert.equal(sent.type, 'church.update');
assert.equal(sent.actor, id);
assert.deepEqual(Object.keys(sent.church!), ['serviceTimes']);
});
it('says so when someone changed the profile in between, and checks the fields first', async () => {
const { go } = await site();
const stale = await go('put', '/church', { church: { name: 'Hope' }, ifUpdatedAt: '2000-01-01T00:00:00.000Z' });
assert.equal(stale.body.error.code, 'PROFILE_CHANGED');
const bad = await go('put', '/church', { church: { contact: { email: null, phone: '012 345', whatsapp: null, address: null } } });
assert.equal(bad.status, 400);
assert.ok(bad.body.error.fields['contact.phone']);
});
it("is an Editor's job, not a Viewer's", async () => {
const { go } = await site('viewer');
assert.equal((await go('put', '/church', { church: { name: 'X' } })).status, 403);
});
});
describe('settings, the menu and the audit log', () => {
it('takes a verification code, or the whole meta tag, and the site shows it', async () => {
const { go, ctx } = await site();
const r = await go('put', '/settings', { googleVerification: '<meta name="google-site-verification" content="abc123XYZ_-" />', bingVerification: 'B1NGcode99', comingSoonText: 'Opening at Easter.' });
assert.equal(r.status, 200);
assert.equal(r.body.googleVerification, 'abc123XYZ_-');
const c = await siteContent(ctx);
assert.deepEqual(c.verification, { google: 'abc123XYZ_-', bing: 'B1NGcode99' });
assert.equal(c.mode === 'coming-soon' && c.comingSoonText, 'Opening at Easter.');
assert.equal((await go('put', '/settings', { googleVerification: '<script>' })).status, 400);
});
it('orders the menu, and the audit log says who did what', async () => {
const { go, db } = await site();
const a = await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About', position: 1 } });
const b = await db.page.create({ data: { kind: 'give', slug: 'give', title: 'Give', position: 2 } });
assert.equal((await go('put', '/pages-order', { ids: [b.id, a.id] })).status, 200);
assert.deepEqual((await go('get', '/pages')).body.map((p: { slug: string }) => p.slug), ['give', 'about']);
await go('put', '/settings', { comingSoonText: 'Soon.' });
const log = (await go('get', '/audit')).body;
assert.deepEqual([log[0].who, log[0].action], ['Sam', 'Changed the settings']);
const overview = (await go('get', '/overview')).body;
assert.equal(overview.recent[0].action, 'Changed the settings');
});
});
@@ -0,0 +1,74 @@
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import express from 'express';
import request from 'supertest';
import { hub } from '@crosscode/contracts';
import { hashToken } from '../src/lib/crypto.js';
import { stats } from '../src/hub/client.js';
import { harness, SITE } from './support/harness.js';
const SECRET = 'install-secret-0123456789abcdef0123456789';
const closers: (() => Promise<unknown>)[] = [];
after(async () => { for (const c of closers) await c(); });
/** The Hub: checks the install's signature as installApi.js does, and records what it's asked. */
async function fakeHub() {
const asked: { installId: string; body: unknown }[] = [];
const app = express();
app.post('/api/installs/storage-request', express.text({ type: () => true }), (req, res) => {
const ts = String(req.get('X-Hub-Timestamp'));
const expected = crypto.createHmac('sha256', SECRET).update(`${ts}.${req.body}`).digest('hex');
if (req.get('X-Hub-Signature') !== expected) return res.status(401).json({ code: 'BAD_SIGNATURE', message: 'no' });
const body = JSON.parse(req.body);
if (!hub.storageRequestSchema.safeParse(body).success) return res.status(400).json({ code: 'INVALID_REQUEST', message: 'no' });
asked.push({ installId: String(req.get('X-Hub-Install')), body });
return res.status(201).json({ requestedAt: new Date().toISOString(), steps: body.steps, alreadyRequested: asked.length > 1 });
});
const server = http.createServer(app);
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
closers.push(() => new Promise((r) => server.close(r)));
return { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, asked };
}
async function site(role: 'owner' | 'editor') {
const fake = await fakeHub();
const h = await harness({ env: { HUB_URL: fake.url } });
await h.ctx.settings.set('hub_install_secret', SECRET);
const id = '00000000-0000-4000-8000-000000000001';
await h.db.websiteUser.create({ data: { id, name: 'Pastor Sam', email: 'sam@hope.test', role } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const go = (m: 'get' | 'post', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
return { ...h, fake, go };
}
describe('Get more storage (decision 12)', () => {
it('asks the Hub, signed, with who asked and what is used; shows the request open until the limit goes up', async () => {
const { go, fake, db } = await site('owner');
await db.mediaAsset.create({ data: { filename: 'a.jpg', mime: 'image/jpeg', bytes: 4_500_000_000 } });
const r = await go('post', '/storage-request', { steps: 2 });
assert.equal(r.status, 200);
assert.equal(fake.asked.length, 1);
assert.deepEqual(fake.asked[0]!.body, { protocolVersion: 2, steps: 2, usedBytes: 4_500_000_000, limitBytes: 5 * 1024 ** 3, requestedBy: 'Pastor Sam' });
const media = (await go('get', '/media')).body;
assert.equal(media.request.steps, 2);
assert.equal((await go('post', '/storage-request', { steps: 11 })).status, 400);
});
it('is an Owner\'s or Admin\'s to ask (it costs the church)', async () => {
const { go } = await site('editor');
assert.equal((await go('post', '/storage-request', { steps: 1 })).status, 403);
});
it('reports the licence\'s limit in the heartbeat, so the Hub can email at 80% and 100%', async () => {
const { ctx } = await site('owner');
const s = await stats(ctx);
assert.equal(s.storage.includedBytes, 5 * 1024 ** 3);
assert.ok(hub.websiteStatsSchema.safeParse(s).success);
});
});
@@ -21,7 +21,7 @@ export type FakeAccounts = {
next: Partial<IdentityClaims> & { sub: string };
started: { returnTo: string; requireTwoFactor: boolean }[];
/** Requests to Accounts (people.ensure, …). */
requests: { type: string; email?: string; actor?: string | null }[];
requests: { type: string; email?: string; actor?: string | null; church?: Record<string, unknown> }[];
};
export function claims(over: Partial<IdentityClaims> & { sub: string }): IdentityClaims {
@@ -66,8 +66,13 @@ function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
}
},
/** people.ensure: the same sub for the same email; "new@…" is a new account. */
request: async (input: { type: string; email?: string; actor?: string | null }) => {
request: async (input: { type: string; email?: string; actor?: string | null; church?: Record<string, unknown>; ifUpdatedAt?: string }) => {
fake.requests.push(input);
if (input.type === 'church.update') {
// An old ifUpdatedAt: someone saved in between.
if (input.ifUpdatedAt === '2000-01-01T00:00:00.000Z') throw Object.assign(new Error('changed'), { code: 'PROFILE_CHANGED', status: 409 });
return { schema: 'crosscode.identity-request/1', church: { name: 'Hope', ...input.church } };
}
if (input.type !== 'people.ensure') throw new Error(`not faked: ${input.type}`);
const hex = Buffer.from(input.email ?? '').toString('hex').padEnd(12, '0').slice(0, 12);
return { schema: 'crosscode.identity-request/1', sub: `22222222-2222-4222-8222-${hex}`, created: input.email?.startsWith('new@') ?? false, emailSent: true };
+5 -3
View File
@@ -107,13 +107,13 @@ test("restore an older version, then publish it", async ({ page, context }) => {
test("switch template in the preview, and back, without losing anything", async ({ page, context }) => {
await signIn(context);
await page.goto("/admin/template");
await page.getByRole("button", { name: /^Bold/ }).click();
await page.getByRole("button", { name: "Use Bold" }).click();
await expect(page.getByText("Switched to Bold.")).toBeVisible();
await page.goto("/preview/start");
await expect(page.locator("html")).toHaveAttribute("data-template", "bold");
await expect(page.getByRole("heading", { level: 1, name: "A home for everyone on the hill" })).toBeVisible();
await page.goto("/admin/template");
await page.getByRole("button", { name: /^Heritage/ }).click();
await page.getByRole("button", { name: "Use Heritage" }).click();
await expect(page.getByText("Switched to Heritage.")).toBeVisible();
await page.goto("/admin/publish");
await expect(page.getByText("Nothing waiting to be published")).toBeVisible();
@@ -148,8 +148,10 @@ test("an event added and published shows on the site at once (its own Publish)",
});
test("the admin's screens are accessible", async ({ page, context }) => {
// Thirteen screens, each checked by axe.
test.setTimeout(240_000);
await signIn(context, "owner");
for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/messages", "/admin/events", "/admin/linked", "/admin/media", "/admin/publish", "/admin/people"]) {
for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/messages", "/admin/events", "/admin/linked", "/admin/media", "/admin/publish", "/admin/settings", "/admin/people", "/admin/audit"]) {
await page.goto(path);
await expect(page.getByRole("heading", { level: 1 })).toBeVisible();
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
+37
View File
@@ -71,3 +71,40 @@ test("robots.txt keeps the admin out; the sitemap lists the pages", async ({ pag
expect(sitemap).toContain("/visit</loc>");
expect(sitemap).not.toContain("/admin");
});
test("structured data on event and other pages, a made share image, the verification codes, a moved page", async ({ page }) => {
const backend = "http://127.0.0.1:5310";
await page.request.post(`${backend}/test/demo?template=heritage`);
await page.goto("/events");
const ld = (await page.locator('script[type="application/ld+json"]').allTextContents()).map((t) => JSON.parse(t));
expect(ld.some((x) => x["@type"] === "BreadcrumbList")).toBeTruthy();
await page.getByRole("link", { name: "Family picnic" }).first().click();
await expect(page.getByRole("heading", { level: 1, name: "Family picnic" })).toBeVisible();
const eventLd = (await page.locator('script[type="application/ld+json"]').allTextContents()).map((t) => JSON.parse(t));
const ev = eventLd.find((x) => x["@type"] === "Event");
expect(ev.name).toBe("Family picnic");
expect(ev.location["@type"]).toBe("Place");
// Pages without their own photo share a made image.
await page.goto("/visit");
const og = await page.locator('meta[property="og:image"]').getAttribute("content");
expect(og).toContain("/share-image?t=");
const img = await page.request.get(new URL(og!).pathname + new URL(og!).search);
expect(img.status()).toBe(200);
expect(img.headers()["content-type"]).toBe("image/png");
// An admin sets the codes and moves a page; the old address goes on to the new one.
const { cookie } = await (await page.request.post(`${backend}/test/session?role=editor`)).json();
const headers = { Cookie: `ccw_session=${cookie.value}`, Origin: "http://localhost:3310", "Content-Type": "application/json" };
await page.request.put("/api/v1/admin/settings", { headers, data: { googleVerification: "googleCode123", bingVerification: "bingCode456" } });
const pages = await (await page.request.get("/api/v1/admin/pages", { headers })).json();
const visit = pages.find((p: { kind: string }) => p.kind === "visit");
expect((await page.request.put(`/api/v1/admin/pages/${visit.id}`, { headers, data: { slug: "first-visit" } })).ok()).toBeTruthy();
expect((await page.request.post("/api/v1/admin/publish", { headers, data: {} })).ok()).toBeTruthy();
const moved = await page.request.get("/visit", { maxRedirects: 0 });
expect([301, 308]).toContain(moved.status());
expect(moved.headers().location).toContain("/first-visit");
await page.goto("/");
expect(await page.locator('meta[name="google-site-verification"]').getAttribute("content")).toBe("googleCode123");
expect(await page.locator('meta[name="msvalidate.01"]').getAttribute("content")).toBe("bingCode456");
});
@@ -34,7 +34,9 @@ export function ListEditor({ path, fields, nameKey, subKey, addLabel, canAdd }:
const { busy, message, fields: errors, run } = useAction();
if (!data) return <Loading error={error} />;
const save = (id: string | null, v: Record<string, unknown>) => run(async () => {
const body = Object.fromEntries(fields.map((f) => [f.key, v[f.key] ?? null]));
const row = id ? data.find((r) => r.id === id) : null;
// When the form was loaded: someone else's save in between isn't overwritten (§4).
const body = { ...Object.fromEntries(fields.map((f) => [f.key, v[f.key] ?? null])), ...(row?.updatedAt ? { ifUpdatedAt: row.updatedAt } : {}) };
await api(id ? `${path}/${id}` : path, { method: id ? "PUT" : "POST", body });
setEditing(null);
await reload();
@@ -9,6 +9,7 @@ import { cx, useAdmin } from "./ui";
const NAV = [
{ href: "/admin", label: "Dashboard" },
{ href: "/admin/template", label: "Template and style" },
{ href: "/admin/church", label: "Church details" },
{ href: "/admin/pages", label: "Pages" },
{ href: "/admin/ministries", label: "Ministries" },
{ href: "/admin/leaders", label: "Leadership" },
@@ -17,7 +18,9 @@ const NAV = [
{ href: "/admin/linked", label: "Linked products" },
{ href: "/admin/media", label: "Media library" },
{ href: "/admin/publish", label: "Publish and history" },
{ href: "/admin/settings", label: "Settings" },
{ href: "/admin/people", label: "People", managers: true },
{ href: "/admin/audit", label: "Audit log", managers: true },
];
export function AdminShell({ user, children }: { user: { name: string; role: string }; children: React.ReactNode }) {
+1 -1
View File
@@ -82,7 +82,7 @@ export function ImagePicker({ value, onChange, label }: { value: string | null;
</div>
<div className="mt-6 border-t border-gray-200 pt-4">
<h3 className="mb-2 font-semibold">Upload a new one</h3>
{data?.storage.full && <Notice tone="warning">Your storage is full, so uploads have stopped. To get more (5 GB at a time), contact Cross Code.</Notice>}
{data?.storage.full && <Notice tone="warning">Your storage is full, so uploads have stopped. An Owner or Admin can get more under Media library.</Notice>}
<Uploader disabled={data?.storage.full} onUploaded={(m) => { reload(); onChange(m.id); setOpen(false); }} />
</div>
</div>
+14 -5
View File
@@ -1,7 +1,7 @@
import type { Metadata } from "next";
import { notFound, redirect } from "next/navigation";
import { notFound, permanentRedirect, redirect } from "next/navigation";
import { loadContent } from "@/site/load";
import { churchLd, pageMetadata } from "@/site/meta";
import { breadcrumbLd, churchLd, messagesLd, pageMetadata } from "@/site/meta";
import { PageView } from "@/site/PageView";
import { Shell } from "@/site/Shell";
@@ -23,11 +23,20 @@ export default async function SitePage({ params }: Props) {
const { c, page } = await find(slug);
// Before the first publish every address shows Coming soon, on the home page.
if (c.mode !== "published") redirect("/");
if (!page) notFound();
const ld = page.kind === "contact" ? churchLd(c, page.path) : null;
if (!page) {
// A page's earlier address: on to where it is now, permanently (§6).
const moved = c.snapshot.redirects?.[slug];
if (moved) permanentRedirect(moved);
notFound();
}
const lds = [
breadcrumbLd(c, [{ name: page.title, path: page.path }]),
page.kind === "contact" ? churchLd(c, page.path) : null,
page.kind === "messages" ? messagesLd(c, c.messages) : null,
].filter((x): x is string => !!x);
return (
<Shell site={c} path={page.path}>
{ld && <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: ld }} />}
{lds.map((ld, i) => <script key={i} type="application/ld+json" dangerouslySetInnerHTML={{ __html: ld }} />)}
<PageView page={page} site={c} />
</Shell>
);
@@ -0,0 +1,43 @@
"use client";
/** The audit log (§4, §10): who changed what, and when. Owners and Admins see it. */
import { useState } from "react";
import { api } from "@/admin/api";
import { Btn, Loading, Panel, Title, useAdmin, when } from "@/admin/ui";
type Entry = { at: string; who: string; action: string; detail: string | null };
export default function Audit() {
const first = useAdmin<Entry[]>("/audit");
const [more, setMore] = useState<Entry[]>([]);
const [done, setDone] = useState(false);
if (!first.data) return <Loading error={first.error} />;
const all = [...first.data, ...more];
return (
<>
<Title sub="Who changed what, newest first.">Audit log</Title>
<Panel>
{all.length === 0 && <p className="text-gray-600">Nothing yet.</p>}
<table className="w-full text-left text-sm">
<thead className="text-gray-600"><tr><th className="py-2 pr-4 font-medium">When</th><th className="py-2 pr-4 font-medium">Who</th><th className="py-2 font-medium">What</th></tr></thead>
<tbody className="divide-y divide-gray-200">
{all.map((e, i) => (
<tr key={`${e.at}-${i}`}>
<td className="whitespace-nowrap py-2 pr-4 text-gray-600">{when(e.at)}</td>
<td className="py-2 pr-4">{e.who}</td>
<td className="py-2">{e.action}{e.detail && <span className="text-gray-600">: {e.detail}</span>}</td>
</tr>
))}
</tbody>
</table>
{!done && all.length >= 100 && (
<Btn className="mt-4" onClick={async () => {
const next = await api<Entry[]>(`/audit?before=${encodeURIComponent(all.at(-1)!.at)}`);
if (!next.length) setDone(true);
setMore([...more, ...next]);
}}>Show older</Btn>
)}
</Panel>
</>
);
}
@@ -0,0 +1,127 @@
"use client";
/**
* Church details (§2, decision 10): the facts every one of the church's sites shows (name, colours,
* fonts and corners, logo, service times, contact, social links). They belong to the church's
* Accounts and are saved there; they're not drafts: they change on all its sites at once.
*/
import { useState } from "react";
import type { Church } from "@crosscode/contracts";
import { api, canEdit } from "@/admin/api";
import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
const DAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
const PAIRINGS: [string, string][] = [["", "Your template's choice"], ["classic", "Classic"], ["scholarly", "Scholarly"], ["editorial", "Editorial"], ["impact", "Impact"], ["contemporary", "Contemporary"], ["friendly", "Friendly"], ["warm", "Warm"], ["modern", "Modern"]];
const NETWORKS = ["facebook", "instagram", "youtube", "tiktok", "x", "spotify", "whatsapp-channel", "other"];
type ServiceTime = Church["serviceTimes"][number];
type Social = Church["social"][number];
type Address = NonNullable<Church["contact"]["address"]>;
export default function ChurchDetails() {
const me = useAdmin<{ user: { role: string } }>("/me");
const { data, error, reload } = useAdmin<{ church: Church | null; linked: boolean }>("/church");
const { busy, message, fields, run } = useAction();
const [edit, setEdit] = useState<Partial<Church> & { logoMediaId?: string | null } | null>(null);
if (!data || !me.data) return <Loading error={error ?? me.error} />;
if (!data.church) return <><Title>Church details</Title><Notice tone="warning">{data.linked ? "Your church's details can't be read from Accounts right now. Try again in a minute." : "This website isn't linked to your church's Accounts yet. It links by itself within 15 minutes of being installed."}</Notice></>;
const c: Church = { ...data.church, ...edit } as Church;
const editor = canEdit(me.data.user.role);
const set = (patch: Partial<Church>) => setEdit({ ...edit, ...patch });
const times = c.serviceTimes;
const setTime = (i: number, t: Partial<ServiceTime>) => set({ serviceTimes: times.map((x, j) => (j === i ? { ...x, ...t } : x)) });
const address: Address = c.contact.address ?? { line1: "", line2: null, suburb: null, city: "", province: null, postalCode: null, country: "ZA", geo: null };
const setAddress = (a: Partial<Address>) => set({ contact: { ...c.contact, address: { ...address, ...a } } });
const save = () => run(async () => {
// The media id only picks the logo here; Accounts keeps its address.
const changes = { ...(edit ?? {}) };
delete changes.logoMediaId;
await api("/church", { method: "PUT", body: { church: changes, ifUpdatedAt: data.church!.updatedAt } });
setEdit(null);
await reload();
}, "Saved: all your church's sites show it now.");
const err = (k: string) => fields[k];
return (
<>
<Title sub="These show on all your church's sites (this website, Cross Events, the sign-in pages). Changes here go live straight away: they aren't drafts."
actions={editor && edit && <><Btn onClick={() => setEdit(null)}>Undo</Btn><Btn kind="primary" busy={busy} onClick={save}>Save for all your sites</Btn></>}>
Church details
</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<fieldset disabled={!editor} className="space-y-6">
<Panel title="Name and look">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Church name" error={err("name")}><input className={inputClass} value={c.name} maxLength={200} onChange={(e) => set({ name: e.target.value })} /></Field>
<Field label="Short name" hint="For tight spaces." error={err("shortName")}><input className={inputClass} value={c.shortName ?? ""} maxLength={30} onChange={(e) => set({ shortName: e.target.value || null })} /></Field>
<Field label="Main colour" error={err("branding.colours.primary")}><input type="color" className="h-10 w-20" value={c.branding.colours.primary} onChange={(e) => set({ branding: { ...c.branding, colours: { ...c.branding.colours, primary: e.target.value } } })} /></Field>
<Field label="Accent colour"><input type="color" className="h-10 w-20" value={c.branding.colours.accent ?? "#999999"} onChange={(e) => set({ branding: { ...c.branding, colours: { ...c.branding.colours, accent: e.target.value } } })} /></Field>
<Field label="Fonts" hint="Shared by all your sites. Your template suggests some.">
<select className={inputClass} value={c.branding.style?.fontPairing ?? ""} onChange={(e) => set({ branding: { ...c.branding, style: { fontPairing: (e.target.value || null) as never, corners: c.branding.style?.corners ?? null } } })}>
{PAIRINGS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
</select>
</Field>
<Field label="Corners">
<select className={inputClass} value={c.branding.style?.corners ?? ""} onChange={(e) => set({ branding: { ...c.branding, style: { fontPairing: c.branding.style?.fontPairing ?? null, corners: (e.target.value || null) as never } } })}>
<option value="">Your template&apos;s choice</option><option value="sharp">Sharp</option><option value="soft">Soft</option><option value="round">Round</option>
</select>
</Field>
<div className="sm:col-span-2">
{c.branding.logoUrl && <img src={c.branding.logoUrl} alt="Your logo" className="mb-2 h-12 w-auto" />}
<ImagePicker label="Logo (a photo from the media library)" value={edit?.logoMediaId ?? null}
onChange={(id) => run(async () => {
if (!id) return set({ branding: { ...c.branding, logoUrl: null }, logoMediaId: null } as never);
const media = await api<{ items: { id: string; url: string }[] }>("/media");
const url = media.items.find((m) => m.id === id)?.url;
set({ branding: { ...c.branding, logoUrl: url ? `${window.location.origin}${url}` : null }, logoMediaId: id } as never);
})} />
</div>
</div>
</Panel>
<Panel title="Service times">
<ul className="space-y-3">
{times.map((t, i) => (
<li key={i} className="grid gap-2 sm:grid-cols-[8rem_7rem_1fr_1fr_auto]">
<select aria-label="Day" className={inputClass} value={t.day} onChange={(e) => setTime(i, { day: e.target.value as ServiceTime["day"] })}>{DAYS.map((d) => <option key={d} value={d}>{d[0]!.toUpperCase() + d.slice(1)}</option>)}</select>
<input aria-label="Time" type="time" className={inputClass} value={t.time} onChange={(e) => setTime(i, { time: e.target.value })} />
<input aria-label="Name (e.g. Morning service)" placeholder="E.g. Morning service" className={inputClass} value={t.label ?? ""} maxLength={100} onChange={(e) => setTime(i, { label: e.target.value || null })} />
<input aria-label="Note" placeholder="E.g. Kids church during the service" className={inputClass} value={t.note ?? ""} maxLength={300} onChange={(e) => setTime(i, { note: e.target.value || null })} />
<Btn kind="danger" onClick={() => set({ serviceTimes: times.filter((_, j) => j !== i) })}>Remove</Btn>
</li>
))}
</ul>
{err("serviceTimes") && <p className="mt-2 text-xs text-red-700">{err("serviceTimes")}</p>}
<Btn className="mt-3" onClick={() => set({ serviceTimes: [...times, { day: "sunday", time: "09:00", label: null, campus: null, note: null }] })}>Add a service time</Btn>
</Panel>
<Panel title="Contact and address">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Email" error={err("contact.email")}><input type="email" className={inputClass} value={c.contact.email ?? ""} onChange={(e) => set({ contact: { ...c.contact, email: e.target.value || null } })} /></Field>
<Field label="Phone" hint="With the country code: +27125550123" error={err("contact.phone")}><input className={inputClass} value={c.contact.phone ?? ""} onChange={(e) => set({ contact: { ...c.contact, phone: e.target.value.replace(/\s+/g, "") || null } })} /></Field>
<Field label="WhatsApp" hint="With the country code" error={err("contact.whatsapp")}><input className={inputClass} value={c.contact.whatsapp ?? ""} onChange={(e) => set({ contact: { ...c.contact, whatsapp: e.target.value.replace(/\s+/g, "") || null } })} /></Field>
<div />
<Field label="Street address" error={err("contact.address.line1")}><input className={inputClass} value={address.line1} onChange={(e) => setAddress({ line1: e.target.value })} /></Field>
<Field label="Suburb"><input className={inputClass} value={address.suburb ?? ""} onChange={(e) => setAddress({ suburb: e.target.value || null })} /></Field>
<Field label="City" error={err("contact.address.city")}><input className={inputClass} value={address.city} onChange={(e) => setAddress({ city: e.target.value })} /></Field>
<Field label="Postal code"><input className={inputClass} value={address.postalCode ?? ""} onChange={(e) => setAddress({ postalCode: e.target.value || null })} /></Field>
</div>
</Panel>
<Panel title="Social links">
<ul className="space-y-2">
{c.social.map((s, i) => (
<li key={i} className="grid gap-2 sm:grid-cols-[12rem_1fr_auto]">
<select aria-label="Network" className={inputClass} value={s.network} onChange={(e) => set({ social: c.social.map((x, j) => (j === i ? { ...x, network: e.target.value as Social["network"] } : x)) })}>{NETWORKS.map((n) => <option key={n} value={n}>{n}</option>)}</select>
<input aria-label="Address" className={inputClass} value={s.url} onChange={(e) => set({ social: c.social.map((x, j) => (j === i ? { ...x, url: e.target.value } : x)) })} />
<Btn kind="danger" onClick={() => set({ social: c.social.filter((_, j) => j !== i) })}>Remove</Btn>
</li>
))}
</ul>
{err("social") && <p className="mt-2 text-xs text-red-700">{err("social")}</p>}
<Btn className="mt-3" onClick={() => set({ social: [...c.social, { network: "facebook", url: "https://" }] })}>Add a link</Btn>
</Panel>
</fieldset>
</>
);
}
@@ -3,15 +3,20 @@
/**
* Simple events (§8): title, date and time, place, description, a photo and an optional link (a
* sign-up form elsewhere, say). Registrations and payments are Cross Events'. Each publishes on its
* own (decision 9). Events from Cross Events show on the site by themselves once it's linked.
* own (decision 9). An event can belong to a ministry: its Ministry leader can add and change it,
* and an Editor publishes it (§10). Events from Cross Events show on the site by themselves.
*/
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
type Ev = { id: string; slug: string; title: string; startsAt: string; endsAt: string | null; allDay: boolean; location: string | null; description: string | null; imageId: string | null; image: string | null; link: string | null; cancelled: boolean; published: boolean };
type Form = { title: string; date: string; time: string; endDate: string; endTime: string; allDay: boolean; location: string; description: string; imageId: string | null; link: string };
type Ev = {
id: string; slug: string; title: string; startsAt: string; endsAt: string | null; allDay: boolean; location: string | null; description: string | null;
imageId: string | null; image: string | null; link: string | null; ministryId: string | null; cancelled: boolean; published: boolean; updatedAt: string;
};
type Form = { title: string; date: string; time: string; endDate: string; endTime: string; allDay: boolean; location: string; description: string; imageId: string | null; link: string; ministryId: string | null };
type Me = { user: { role: string; ministryId: string | null } };
/** "2026-12-05" + "18:30" in the browser's time zone (the church's, for its admins) → ISO with offset. */
const iso = (date: string, time: string) => (date ? new Date(`${date}T${time || "00:00"}`).toISOString() : null);
@@ -22,7 +27,7 @@ const local = (s: string | null) => {
return { d: `${x.getFullYear()}-${p(x.getMonth() + 1)}-${p(x.getDate())}`, t: `${p(x.getHours())}:${p(x.getMinutes())}` };
};
function EventForm({ initial, onSave, onCancel }: { initial: Form; onSave: (body: object) => Promise<unknown>; onCancel: () => void }) {
function EventForm({ initial, ministries, fixedMinistry, onSave, onCancel }: { initial: Form; ministries: { id: string; name: string }[]; fixedMinistry: string | null; onSave: (body: object) => Promise<unknown>; onCancel: () => void }) {
const [v, setV] = useState(initial);
const { busy, message, fields, run } = useAction();
const set = (k: keyof Form, x: unknown) => setV({ ...v, [k]: x });
@@ -39,11 +44,19 @@ function EventForm({ initial, onSave, onCancel }: { initial: Form; onSave: (body
<Field label="Where" error={fields.location}><input className={inputClass} value={v.location} maxLength={500} onChange={(e) => set("location", e.target.value)} /></Field>
<Field label="About it" error={fields.description}><textarea className={inputClass} rows={4} value={v.description} maxLength={8000} onChange={(e) => set("description", e.target.value)} /></Field>
<Field label="Link (optional)" hint="A sign-up form or more information elsewhere: https://…" error={fields.link}><input className={inputClass} value={v.link} onChange={(e) => set("link", e.target.value)} /></Field>
{!fixedMinistry && ministries.length > 0 && (
<Field label="Ministry (optional)" hint="Its Ministry leader can then change it too.">
<select className={inputClass} value={v.ministryId ?? ""} onChange={(e) => set("ministryId", e.target.value || null)}>
<option value="">None</option>
{ministries.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
</select>
</Field>
)}
<ImagePicker label="Photo" value={v.imageId} onChange={(id) => set("imageId", id)} />
<div className="flex gap-2">
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave({
title: v.title, startsAt: iso(v.date, v.allDay ? "00:00" : v.time), endsAt: v.endDate ? iso(v.endDate, v.allDay ? "23:59" : v.endTime) : null,
allDay: v.allDay, location: v.location || null, description: v.description || null, imageId: v.imageId, link: v.link || null,
allDay: v.allDay, location: v.location || null, description: v.description || null, imageId: v.imageId, link: v.link || null, ministryId: fixedMinistry ?? v.ministryId,
}))}>Save</Btn>
<Btn onClick={onCancel}>Cancel</Btn>
</div>
@@ -52,31 +65,41 @@ function EventForm({ initial, onSave, onCancel }: { initial: Form; onSave: (body
);
}
const empty: Form = { title: "", date: "", time: "10:00", endDate: "", endTime: "", allDay: false, location: "", description: "", imageId: null, link: "" };
const empty: Form = { title: "", date: "", time: "10:00", endDate: "", endTime: "", allDay: false, location: "", description: "", imageId: null, link: "", ministryId: null };
export default function Events() {
const me = useAdmin<{ user: { role: string } }>("/me");
const me = useAdmin<Me>("/me");
const { data, error, reload } = useAdmin<Ev[]>("/events");
const ministries = useAdmin<{ id: string; name: string }[]>("/ministries");
const [editing, setEditing] = useState<string | null>(null);
const { busy, message, run } = useAction();
if (!data || !me.data) return <Loading error={error ?? me.error} />;
const editor = canEdit(me.data.user.role);
const leaderOf = me.data.user.role === "ministry_leader" ? me.data.user.ministryId : null;
const mayWrite = (e: Ev | null) => editor || (!!leaderOf && (!e || e.ministryId === leaderOf));
const nameOf = (id: string | null) => ministries.data?.find((m) => m.id === id)?.name;
const toForm = (e: Ev): Form => {
const s = local(e.startsAt);
const f = local(e.endsAt);
return { title: e.title, date: s.d, time: s.t, endDate: f.d, endTime: f.t, allDay: e.allDay, location: e.location ?? "", description: e.description ?? "", imageId: e.imageId, link: e.link ?? "" };
return { title: e.title, date: s.d, time: s.t, endDate: f.d, endTime: f.t, allDay: e.allDay, location: e.location ?? "", description: e.description ?? "", imageId: e.imageId, link: e.link ?? "", ministryId: e.ministryId };
};
const state = (e: Ev, change: object, done: string) => run(async () => { await api(`/events/${e.id}/state`, { body: change }); await reload(); }, done);
const form = (e: Ev | null) => (
<EventForm initial={e ? toForm(e) : { ...empty, ministryId: leaderOf }} ministries={ministries.data ?? []} fixedMinistry={leaderOf} onCancel={() => setEditing(null)}
onSave={async (b) => {
await api(e ? `/events/${e.id}` : "/events", { method: e ? "PUT" : "POST", body: e ? { ...b, ifUpdatedAt: e.updatedAt } : b });
setEditing(null);
await reload();
}} />
);
return (
<>
<Title sub="Simple events made here. Events with registration and payment belong in Cross Events; they show here by themselves once it's linked.">Events</Title>
<Title sub={leaderOf ? `You can add and change ${nameOf(leaderOf) ?? "your ministry"}'s events; an editor publishes them.` : "Simple events made here. Events with registration and payment belong in Cross Events; they show here by themselves once it's linked."}>Events</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6">
{editor && (
{mayWrite(null) && (
<Panel title="Add an event">
{editing === "new"
? <EventForm initial={empty} onCancel={() => setEditing(null)} onSave={async (b) => { await api("/events", { body: b }); setEditing(null); await reload(); }} />
: <Btn kind="primary" onClick={() => setEditing("new")}>Add an event</Btn>}
{editing === "new" ? form(null) : <Btn kind="primary" onClick={() => setEditing("new")}>Add an event</Btn>}
</Panel>
)}
<Panel title="Your events">
@@ -84,23 +107,23 @@ export default function Events() {
<ul className="divide-y divide-gray-200">
{data.map((e) => (
<li key={e.id} className="py-3">
{editing === e.id ? (
<EventForm initial={toForm(e)} onCancel={() => setEditing(null)} onSave={async (b) => { await api(`/events/${e.id}`, { method: "PUT", body: b }); setEditing(null); await reload(); }} />
) : (
{editing === e.id ? form(e) : (
<div className="flex flex-wrap items-center gap-4">
<div className="min-w-0 flex-1">
<p className="font-medium">{e.title}</p>
<p className="text-sm text-gray-600">{when(e.startsAt)}{e.location && ` · ${e.location}`}</p>
<p className="text-sm text-gray-600">{when(e.startsAt)}{e.location && ` · ${e.location}`}{e.ministryId && nameOf(e.ministryId) && ` · ${nameOf(e.ministryId)}`}</p>
<p className="text-xs">{e.cancelled ? <span className="text-red-700">Cancelled</span> : e.published ? <span className="text-green-800">On the site</span> : <span className="text-gray-500">Not published</span>}</p>
</div>
{editor && (
<div className="flex flex-wrap gap-2">
<Btn onClick={() => setEditing(e.id)}>Edit</Btn>
<Btn busy={busy} onClick={() => state(e, { published: !e.published }, e.published ? "Taken off the site." : "On the site now.")}>{e.published ? "Unpublish" : "Publish"}</Btn>
<Btn busy={busy} onClick={() => state(e, { cancelled: !e.cancelled }, e.cancelled ? "Back on." : "Cancelled: it's off the site.")}>{e.cancelled ? "Not cancelled" : "Cancel it"}</Btn>
<Btn kind="danger" busy={busy} onClick={() => run(async () => { await api(`/events/${e.id}`, { method: "DELETE" }); await reload(); }, "Removed.")}>Remove</Btn>
</div>
)}
<div className="flex flex-wrap gap-2">
{mayWrite(e) && <Btn onClick={() => setEditing(e.id)}>Edit</Btn>}
{editor && (
<>
<Btn busy={busy} onClick={() => state(e, { published: !e.published }, e.published ? "Taken off the site." : "On the site now.")}>{e.published ? "Unpublish" : "Publish"}</Btn>
<Btn busy={busy} onClick={() => state(e, { cancelled: !e.cancelled }, e.cancelled ? "Back on." : "Cancelled: it's off the site.")}>{e.cancelled ? "Not cancelled" : "Cancel it"}</Btn>
<Btn kind="danger" busy={busy} onClick={() => run(async () => { await api(`/events/${e.id}`, { method: "DELETE" }); await reload(); }, "Removed.")}>Remove</Btn>
</>
)}
</div>
</div>
)}
</li>
@@ -3,14 +3,17 @@
import { useState } from "react";
import { api } from "@/admin/api";
import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
/** The media library (§10): uploads, what each photo shows (alt text), and storage used. */
export default function Media() {
const { data, error, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>("/media");
const { data, error, reload } = useAdmin<{ storage: Storage; request: { at: string; steps: number } | null; items: MediaItem[] }>("/media");
const me = useAdmin<{ user: { role: string } }>("/me");
const [alts, setAlts] = useState<Record<string, string>>({});
const [steps, setSteps] = useState(1);
const { busy, message, run } = useAction();
if (!data) return <Loading error={error} />;
const manager = ["owner", "admin"].includes(me.data?.user.role ?? "");
const s = data.storage;
return (
<>
@@ -38,7 +41,22 @@ export default function Media() {
<div className="space-y-6">
<Panel title="Storage">
<StorageMeter s={s} />
{s.percent >= 80 && <div className="mt-3"><Notice tone={s.full ? "error" : "warning"}>{s.full ? "Storage is full: uploads have stopped until more storage is added." : "Storage is nearly full."} More comes in 5 GB steps (R20 a month each): contact Cross Code.</Notice></div>}
{s.percent >= 80 && <div className="mt-3"><Notice tone={s.full ? "error" : "warning"}>{s.full ? "Storage is full: uploads have stopped until more storage is added." : "Storage is nearly full."} Everything already uploaded keeps showing.</Notice></div>}
<div className="mt-4 border-t border-gray-200 pt-4">
<h3 className="font-semibold">Get more storage</h3>
<p className="mt-1 text-sm text-gray-600">In steps of 5 GB, R20 a month each, added to your church&apos;s account.</p>
{data.request ? (
<div className="mt-3"><Notice tone="info">You asked for {data.request.steps * 5} GB more on {when(data.request.at)}. Cross Code adds it to your account; uploads work again within a minute of that.</Notice></div>
) : manager ? (
<div className="mt-3 flex flex-wrap items-center gap-2">
<label className="text-sm" htmlFor="steps">Add</label>
<select id="steps" className={`${inputClass} w-28`} value={steps} onChange={(e) => setSteps(Number(e.target.value))}>
{[1, 2, 3, 4].map((n) => <option key={n} value={n}>{n * 5} GB</option>)}
</select>
<Btn kind="primary" busy={busy} onClick={() => run(async () => { await api("/storage-request", { body: { steps } }); await reload(); }, "Asked: Cross Code will add it.")}>Ask for it</Btn>
</div>
) : <p className="mt-2 text-sm text-gray-600">Your website&apos;s Owner or an Admin can ask for it.</p>}
</div>
</Panel>
<Panel title="Upload a photo">
{s.full ? <Notice tone="warning">Uploads have stopped: your storage is full.</Notice> : <Uploader onUploaded={() => reload()} />}
@@ -10,6 +10,7 @@ type Overview = {
storage: Storage;
colourNotes: string[];
checklist: { key: string; label: string; done: boolean; href: string | null }[];
recent: { at: string; who: string; action: string; detail: string | null }[];
};
/** The dashboard (§10): the setup checklist, what's waiting to be published, storage. */
@@ -37,6 +38,13 @@ export default function Dashboard() {
<p>{data.pending} {data.pending === 1 ? "change" : "changes"}. <Link href="/admin/publish" className="font-semibold text-brand-text underline-offset-4 hover:underline">Review and publish</Link></p>
) : <p className="text-gray-600">Nothing: the site shows everything you&apos;ve done.</p>}
</Panel>
<Panel title="Recent edits">
{data.recent.length === 0 ? <p className="text-gray-600">None yet.</p> : (
<ul className="space-y-2 text-sm">
{data.recent.map((e, i) => <li key={i}><span className="font-medium">{e.who}</span> {e.action.charAt(0).toLowerCase() + e.action.slice(1)}{e.detail && <>: {e.detail}</>} <span className="text-gray-500">({when(e.at)})</span></li>)}
</ul>
)}
</Panel>
<Panel title="Storage"><StorageMeter s={data.storage} /></Panel>
{data.colourNotes.length > 0 && (
<Notice tone="info"><p className="font-semibold">About your colours</p><ul className="mt-1 list-disc pl-5">{data.colourNotes.map((n) => <li key={n}>{n}</li>)}</ul></Notice>
@@ -12,8 +12,8 @@ import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields";
import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown> };
type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; sections: Section[] };
type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown>; updatedAt: string };
type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; updatedAt: string; sections: Section[] };
const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"];
const LISTS: Record<string, string> = {
@@ -55,7 +55,7 @@ export default function EditPage() {
if (!page) return <Loading error={error} />;
const f = { ...page, ...form };
const saveDetails = () => details.run(async () => {
const p = await api<PageData>(`/pages/${id}`, { method: "PUT", body: { title: f.title, slug: f.slug, seoTitle: f.seoTitle, description: f.description, navLabel: f.navLabel, inNav: f.inNav, imageId: f.imageId } });
const p = await api<PageData>(`/pages/${id}`, { method: "PUT", body: { title: f.title, slug: f.slug, seoTitle: f.seoTitle, description: f.description, navLabel: f.navLabel, inNav: f.inNav, imageId: f.imageId, ifUpdatedAt: page.updatedAt } });
setData(p);
setForm(null);
}, "Saved as a draft.");
@@ -97,7 +97,7 @@ export default function EditPage() {
{HOME_ORDER.map((type) => {
const s = page.sections.find((x) => x.type === type);
const spec = SECTION_FIELDS[type]!;
return <SectionEditor key={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data } }))} />;
return <SectionEditor key={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data, ifUpdatedAt: s?.updatedAt } }))} />;
})}
</>
) : (
@@ -108,7 +108,7 @@ export default function EditPage() {
if (!spec) return null;
return (
<SectionEditor key={s.id} title={`${spec.name}${s.hidden ? " (hidden)" : ""}`} fields={spec.fields} initial={s.data}
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data } }))}
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data, ifUpdatedAt: s.updatedAt } }))}
extra={<>
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "up" })} disabled={i === 0} aria-label="Move up">↑</Btn>
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "down" })} disabled={i === page.sections.length - 1} aria-label="Move down">↓</Btn>
@@ -0,0 +1,69 @@
"use client";
/**
* Settings (§10): the Coming soon line, search engine verification (live at once), and the menu's
* order (a draft, published with the site).
*/
import Link from "next/link";
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
type Settings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null };
type PageRow = { id: string; kind: string; title: string; inNav: boolean };
export default function SettingsPage() {
const me = useAdmin<{ user: { role: string } }>("/me");
const settings = useAdmin<Settings>("/settings");
const pages = useAdmin<PageRow[]>("/pages");
const [form, setForm] = useState<Partial<Settings>>({});
const { busy, message, fields, run } = useAction();
if (!settings.data || !pages.data || !me.data) return <Loading error={settings.error ?? pages.error} />;
const editor = canEdit(me.data.user.role);
const s = { ...settings.data, ...form };
const menu = pages.data.filter((p) => p.kind !== "home");
const move = (i: number, d: -1 | 1) => run(async () => {
const list = [...menu];
[list[i], list[i + d]] = [list[i + d]!, list[i]!];
await api("/pages-order", { method: "PUT", body: { ids: list.map((p) => p.id) } });
await pages.reload();
}, "Saved as a draft: publish to change the menu.");
return (
<>
<Title sub="How your site is found, and its menu.">Settings</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<fieldset disabled={!editor} className="space-y-6">
<Panel title="Search engines">
<p className="mb-3 text-sm text-gray-600">To see how people find your site, add it to Google Search Console and Bing Webmaster Tools. They give you a code to prove the site is yours: paste it here (the whole tag is fine), save, then press Verify there. This goes live straight away.</p>
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Google Search Console code" error={fields.googleVerification}><input className={inputClass} value={s.googleVerification ?? ""} onChange={(e) => setForm({ ...form, googleVerification: e.target.value })} /></Field>
<Field label="Bing Webmaster Tools code" error={fields.bingVerification}><input className={inputClass} value={s.bingVerification ?? ""} onChange={(e) => setForm({ ...form, bingVerification: e.target.value })} /></Field>
</div>
<p className="mt-3 text-sm text-gray-600">A Google Business Profile helps people find your church on Google Maps: set one up at business.google.com with the same address as your church details.</p>
</Panel>
<Panel title="Coming soon">
<Field label="The line under “Coming soon”" hint="Shown until you first publish your site." error={fields.comingSoonText}>
<input className={inputClass} value={s.comingSoonText} maxLength={300} onChange={(e) => setForm({ ...form, comingSoonText: e.target.value })} />
</Field>
</Panel>
{editor && Object.keys(form).length > 0 && (
<Btn kind="primary" busy={busy} onClick={() => run(async () => { settings.setData(await api<Settings>("/settings", { method: "PUT", body: form })); setForm({}); }, "Saved.")}>Save settings</Btn>
)}
<Panel title="Menu order">
<p className="mb-3 text-sm text-gray-600">Pages in the menu, in this order. Which pages show is set on each page (<Link href="/admin/pages" className="underline">Pages</Link>).</p>
<ul className="divide-y divide-gray-200">
{menu.map((p, i) => (
<li key={p.id} className="flex items-center justify-between gap-3 py-2">
<span>{p.title}{!p.inNav && <span className="text-sm text-gray-500"> (not in the menu)</span>}</span>
<span className="flex gap-1">
<Btn onClick={() => move(i, -1)} disabled={busy || i === 0} aria-label={`Move ${p.title} up`}>↑</Btn>
<Btn onClick={() => move(i, 1)} disabled={busy || i === menu.length - 1} aria-label={`Move ${p.title} down`}>↓</Btn>
</span>
</li>
))}
</ul>
</Panel>
</fieldset>
</>
);
}
@@ -64,12 +64,16 @@ export default function TemplatePage() {
<Panel title="Template">
<div className="grid gap-3 sm:grid-cols-2">
{TEMPLATES.map((t) => (
<button key={t.id} type="button" disabled={busy} onClick={() => t.id !== design.template && save({ template: t.id }, `Switched to ${t.name}. Your own choices are kept; the rest moved to ${t.name}'s defaults.`)}
aria-pressed={t.id === design.template}
className={cx("rounded-lg border-2 p-4 text-left", t.id === design.template ? "border-brand bg-brand-tint" : "border-gray-200 hover:border-gray-400")}>
<div key={t.id} className={cx("rounded-lg border-2 p-4", t.id === design.template ? "border-brand bg-brand-tint" : "border-gray-200")}>
<span className="block font-semibold">{t.name}{t.id === design.template && " (in use)"}</span>
<span className="mt-1 block text-sm text-gray-600">{t.text}</span>
</button>
{t.id !== design.template && (
<div className="mt-3 flex flex-wrap gap-2">
<a href={`/preview/start?template=${t.id}`} className="rounded-md border border-gray-300 bg-white px-3 py-1.5 text-sm font-semibold hover:bg-gray-50">Preview with your content</a>
<Btn busy={busy} onClick={() => save({ template: t.id }, `Switched to ${t.name}. Your own choices are kept; the rest moved to ${t.name}'s defaults.`)}>Use {t.name}</Btn>
</div>
)}
</div>
))}
</div>
</Panel>
@@ -2,21 +2,26 @@ import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { loadPublished } from "@/site/load";
import { fmtDate, fmtTime, Img } from "@/site/parts";
import { siteBase } from "@/site/meta";
import { breadcrumbLd, eventLd, shareImage, siteBase } from "@/site/meta";
import { Shell } from "@/site/Shell";
type Props = { params: Promise<{ slug: string }> };
async function find(slug: string) {
const site = await loadPublished();
const event = site?.events.find((e) => e.from === "website" && e.url === `/events/${slug}`) ?? null;
const event = site?.events.find((e) => e.from === "website" && e.slug === slug) ?? null;
return { site, event };
}
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { site, event } = await find((await params).slug);
if (!site || !event) return { robots: { index: false } };
return { metadataBase: siteBase(site), title: event.title, description: event.summary ?? undefined, alternates: { canonical: event.url } };
const path = `/events/${event.slug}`;
const image = event.image && !event.image.url.endsWith(".svg") ? { url: event.image.url, alt: event.image.alt } : { url: shareImage(event.title), width: 1200, height: 630, alt: event.title };
return {
metadataBase: siteBase(site), title: event.title, description: event.summary ?? undefined, alternates: { canonical: path },
openGraph: { type: "website", title: event.title, description: event.summary ?? undefined, url: path, images: [image] }, twitter: { card: "summary_large_image" },
};
}
/** A simple event made in the Website (§8). Cross Events' own events link to Cross Events instead. */
@@ -25,8 +30,11 @@ export default async function EventPage({ params }: Props) {
if (!site || !event) notFound();
const zone = site.church?.timezone ?? "Africa/Johannesburg";
const events = site.snapshot.pages.find((p) => p.kind === "events");
const path = `/events/${event.slug}`;
const lds = [eventLd(site, { ...event, url: path }), breadcrumbLd(site, [...(events ? [{ name: events.title, path: events.path }] : []), { name: event.title, path }])];
return (
<Shell site={site} path={event.url}>
<Shell site={site} path={path}>
{lds.map((ld, i) => <script key={i} type="application/ld+json" dangerouslySetInnerHTML={{ __html: ld }} />)}
<article className="cc-section">
<div className="cc-wrap grid gap-10 md:grid-cols-2">
<Img image={event.image} priority />
@@ -35,7 +43,8 @@ export default async function EventPage({ params }: Props) {
<h1 className="cc-h1 mt-2">{event.title}</h1>
{event.location && <p className="cc-muted mt-3 text-lg">{event.location}</p>}
{event.summary && <p className="cc-prose mt-6">{event.summary}</p>}
{events && <a href={events.path} className="cc-link mt-8 inline-block font-semibold">All events</a>}
{event.link && <a href={event.link} rel="noopener" className="cc-btn mt-8">More information</a>}
{events && <a href={events.path} className="cc-link mt-8 block font-semibold">All events</a>}
</div>
</div>
</article>
+4 -1
View File
@@ -13,7 +13,10 @@ export async function generateMetadata(): Promise<Metadata> {
return { title: { absolute: c.church ? `${c.church.name}: coming soon` : "Coming soon" }, robots: { index: false, follow: true } };
}
const home = c.snapshot.pages.find((p) => p.kind === "home");
return home ? pageMetadata(c, home) : {};
// Search Console and Bing Webmaster Tools look for their code on the home page (Settings).
const v = c.verification;
const verification = v && (v.google || v.bing) ? { verification: { ...(v.google ? { google: v.google } : {}), ...(v.bing ? { other: { "msvalidate.01": v.bing } } : {}) } } : {};
return home ? { ...pageMetadata(c, home), ...verification } : verification;
}
export default async function Home() {
@@ -3,8 +3,10 @@ import { NextResponse, type NextRequest } from "next/server";
/** Leaves the preview: an admin goes back to editing, someone with a shared link to the live site. */
export function GET(request: NextRequest) {
const admin = request.cookies.get("ccw_preview")?.value === "admin";
const to = admin ? (request.nextUrl.searchParams.get("published") ? "/admin/publish" : "/admin") : "/";
const trying = !!request.cookies.get("ccw_preview_template")?.value;
const to = admin ? (request.nextUrl.searchParams.get("published") ? "/admin/publish" : trying ? "/admin/template" : "/admin") : "/";
const res = NextResponse.redirect(new URL(to, request.url), 303);
res.cookies.delete("ccw_preview");
res.cookies.delete("ccw_preview_template");
return res;
}
@@ -7,6 +7,11 @@ import { NextResponse, type NextRequest } from "next/server";
*/
export function GET(request: NextRequest) {
const res = NextResponse.redirect(new URL("/", request.url), 303);
res.cookies.set("ccw_preview", "admin", { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/" });
const opts = { httpOnly: true, sameSite: "lax" as const, secure: process.env.NODE_ENV === "production", path: "/" };
res.cookies.set("ccw_preview", "admin", opts);
// "Choose your template": the church's own content in another template, nothing saved.
const template = request.nextUrl.searchParams.get("template");
if (template && /^(heritage|bold|community|clean)$/.test(template)) res.cookies.set("ccw_preview_template", template, opts);
else res.cookies.delete("ccw_preview_template");
return res;
}
@@ -0,0 +1,29 @@
import { ImageResponse } from "next/og";
import type { NextRequest } from "next/server";
import { loadContent } from "@/site/load";
/**
* The share image for a page without its own (ROADMAP-v3 §11: "Pages without their own image get a
* share image generated from the church's logo and colours"): 1200 × 630, the church's colour, its
* name and the page's title. `?t=` is the title (only shown, never trusted for anything else).
*/
export async function GET(request: NextRequest) {
const c = await loadContent();
const title = (request.nextUrl.searchParams.get("t") ?? "").slice(0, 90);
const name = c.church?.name ?? "Our church";
const rgb = (triple: string) => `rgb(${triple.split(" ").join(",")})`;
const logo = c.church?.branding.logoUrl;
return new ImageResponse(
(
<div style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column", justifyContent: "space-between", padding: 72, background: rgb(c.palette.brand), color: rgb(c.palette.onBrand) }}>
<div style={{ display: "flex", alignItems: "center", gap: 24 }}>
{logo && /^https:\/\//.test(logo) && !logo.endsWith(".svg") ? <img src={logo} alt="" height={88} style={{ borderRadius: 12, background: "white", padding: 8 }} /> : null}
<div style={{ fontSize: 40, fontWeight: 700 }}>{name}</div>
</div>
<div style={{ display: "flex", fontSize: title.length > 40 ? 64 : 80, fontWeight: 800, lineHeight: 1.1 }}>{title || name}</div>
<div style={{ display: "flex", height: 12, width: 220, background: rgb(c.palette.accent), borderRadius: 6 }} />
</div>
),
{ width: 1200, height: 630, headers: { "Cache-Control": "public, max-age=3600" } },
);
}
+1 -1
View File
@@ -14,6 +14,6 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const at = (path: string) => new URL(path, base).toString();
return [
...c.snapshot.pages.map((p) => ({ url: at(p.path), changeFrequency: "weekly" as const, priority: p.kind === "home" ? 1 : 0.7 })),
...c.events.filter((e) => e.from === "website" && e.url.startsWith("/")).map((e) => ({ url: at(e.url), changeFrequency: "weekly" as const, priority: 0.5 })),
...c.events.filter((e) => e.from === "website" && e.slug).map((e) => ({ url: at(`/events/${e.slug}`), changeFrequency: "weekly" as const, priority: 0.5 })),
];
}
@@ -7,7 +7,7 @@
*/
import { useEffect, useState } from "react";
export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admin" | "link"; canPublish: boolean }; size?: "phone" | "tablet" | "desktop" }) {
export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admin" | "link"; canPublish: boolean; template?: string | null }; size?: "phone" | "tablet" | "desktop" }) {
const [inFrame, setInFrame] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -38,7 +38,7 @@ export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admi
return (
<div className="bg-gray-900 font-sans text-sm text-white" role="region" aria-label="Preview">
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-4 py-2">
<p><strong>Preview</strong> · {preview.by === "admin" ? "your changes, not live yet" : "not live yet"}</p>
<p><strong>Preview</strong> · {preview.template ? `your content in the ${preview.template[0]!.toUpperCase()}${preview.template.slice(1)} template (nothing saved)` : preview.by === "admin" ? "your changes, not live yet" : "not live yet"}</p>
<div className="flex items-center gap-1" aria-label="Width">
{width("phone", "Phone", "/preview/frame?size=phone")}
{width("tablet", "Tablet", "/preview/frame?size=tablet")}
@@ -47,7 +47,7 @@ export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admi
<div className="flex items-center gap-3">
{error && <span role="alert" className="text-amber-300">{error}</span>}
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- a route handler that clears the preview cookie: a full page load, not a client navigation */}
<a href="/preview/exit" className="underline-offset-4 hover:underline">{preview.by === "admin" ? "Back to editing" : "Leave the preview"}</a>
<a href="/preview/exit" className="underline-offset-4 hover:underline">{preview.template ? "Back to choosing" : preview.by === "admin" ? "Back to editing" : "Leave the preview"}</a>
{preview.canPublish && (
<button type="button" onClick={publish} disabled={busy} className="rounded bg-white px-3 py-1.5 font-semibold text-gray-900 disabled:opacity-60">{busy ? "Publishing…" : "Publish"}</button>
)}
+1
View File
@@ -30,6 +30,7 @@ export const loadContent = cache(async (): Promise<SiteContent> => {
headers: {
...(session ? { Cookie: `ccw_session=${encodeURIComponent(session)}` } : {}),
...(preview !== "admin" ? { "x-preview-token": preview } : {}),
...(jar.get("ccw_preview_template")?.value ? { "x-preview-template": jar.get("ccw_preview_template")!.value } : {}),
},
});
if (res.ok) return (await res.json()) as SiteContent;
+68 -9
View File
@@ -1,10 +1,13 @@
/**
* Search engine basics on every page (ROADMAP-v3 §11): a unique title and description, a
* canonical address, Open Graph with an image, and the church's JSON-LD on home and contact.
* Search engine basics on every page (ROADMAP-v3 §11, WEBSITE-1.0-PLAN §6): a unique title and
* description, a canonical address, Open Graph with an image (the page's own, else one made from
* the church's colours, logo and name: app/share-image), and schema.org JSON-LD: `Church` on home
* and contact, `Event` on the Website's own event pages, `VideoObject` / `PodcastEpisode` for
* messages, and `BreadcrumbList` on every page but home.
*/
import type { Metadata } from "next";
import { churchJsonLd, jsonLdString, pageMeta } from "@crosscode/seo";
import type { Page, Published } from "./types";
import type { Page, Published, SiteEvent, SiteMessage } from "./types";
export function siteBase(site: Published): URL | undefined {
try {
@@ -14,24 +17,80 @@ export function siteBase(site: Published): URL | undefined {
}
}
const abs = (site: Published, path: string) => {
const base = siteBase(site);
return base ? new URL(path, base).toString() : path;
};
/** The made share image for a title. */
export const shareImage = (title: string) => `/share-image?t=${encodeURIComponent(title.slice(0, 90))}`;
export function pageMetadata(site: Published, page: Page): Metadata {
const name = site.church?.name ?? "Church";
const meta = pageMeta({ title: page.kind === "home" ? null : page.seoTitle || page.title, description: page.description, fallbackDescription: `${name}: ${page.title}` });
const firstImage = page.image ?? Object.values(site.snapshot.media)[0] ?? null;
const image = firstImage?.url.endsWith(".svg") ? null : firstImage;
const own = page.image && !page.image.url.endsWith(".svg") ? page.image : null;
const title = page.kind === "home" ? name : page.title;
return {
metadataBase: siteBase(site),
title: page.kind === "home" ? { absolute: page.seoTitle || name } : meta.title,
description: meta.description,
alternates: { canonical: page.path },
openGraph: { type: "website", siteName: name, title: page.kind === "home" ? name : page.title, description: meta.description, url: page.path, locale: "en_ZA", ...(image ? { images: [{ url: image.url, alt: image.alt }] } : site.church?.branding.logoUrl ? { images: [site.church.branding.logoUrl] } : {}) },
twitter: { card: image ? "summary_large_image" : "summary" },
openGraph: {
type: "website", siteName: name, title, description: meta.description, url: page.path, locale: "en_ZA",
images: [own ? { url: own.url, alt: own.alt } : { url: shareImage(title), width: 1200, height: 630, alt: title }],
},
twitter: { card: "summary_large_image" },
};
}
/** `<script type="application/ld+json">` contents for the church (home and contact pages). */
export function churchLd(site: Published, path: string): string | null {
if (!site.church) return null;
const base = siteBase(site);
return jsonLdString(churchJsonLd(site.church, base ? { url: new URL(path, base).toString() } : {}));
return jsonLdString(churchJsonLd(site.church, siteBase(site) ? { url: abs(site, path) } : {}));
}
/** Home › … › this page. */
export function breadcrumbLd(site: Published, trail: { name: string; path: string }[]): string {
const items = [{ name: site.church?.name ?? "Home", path: "/" }, ...trail];
return jsonLdString({
"@context": "https://schema.org",
"@type": "BreadcrumbList",
itemListElement: items.map((x, i) => ({ "@type": "ListItem", position: i + 1, name: x.name, item: abs(site, x.path) })),
});
}
/** A simple event of the Website's own (events from Cross Events have theirs at the origin). */
export function eventLd(site: Published, e: SiteEvent): string {
const a = site.church?.contact.address;
const place = e.location || a
? { "@type": "Place", name: e.location ?? site.church?.name, ...(a ? { address: { "@type": "PostalAddress", streetAddress: [a.line1, a.line2].filter(Boolean).join(", "), addressLocality: a.city, postalCode: a.postalCode ?? undefined, addressCountry: a.country } } : {}) }
: undefined;
return jsonLdString({
"@context": "https://schema.org",
"@type": "Event",
name: e.title,
startDate: e.startsAt,
...(e.endsAt ? { endDate: e.endsAt } : {}),
eventStatus: "https://schema.org/EventScheduled",
eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
...(place ? { location: place } : {}),
...(e.summary ? { description: e.summary } : {}),
...(e.image ? { image: [abs(site, e.image.url)] } : {}),
url: abs(site, e.url),
organizer: { "@type": "Organization", name: site.church?.name, url: abs(site, "/") },
});
}
/** The messages on the Messages page: a VideoObject (YouTube) or PodcastEpisode (Spotify) each. */
export function messagesLd(site: Published, messages: SiteMessage[]): string | null {
if (!messages.length) return null;
return jsonLdString({
"@context": "https://schema.org",
"@graph": messages.slice(0, 20).map((m) => {
const description = [m.speaker, m.passage, m.series].filter(Boolean).join(" · ") || m.title;
return m.source === "spotify"
? { "@type": "PodcastEpisode", name: m.title, datePublished: m.date.slice(0, 10), description, url: m.url }
: { "@type": "VideoObject", name: m.title, uploadDate: m.date, description, ...(m.thumbnail ? { thumbnailUrl: [m.thumbnail] } : {}), ...(m.embedUrl ? { embedUrl: m.embedUrl.replace("?autoplay=1", "") } : {}), contentUrl: m.url };
}),
});
}
+6 -2
View File
@@ -38,6 +38,8 @@ export type Snapshot = {
ministries: { slug: string; name: string; summary: string | null; body: string | null; image: Image | null }[];
leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[];
media: Record<string, Image>;
/** Earlier page addresses and where each page is now (§6). */
redirects?: Record<string, string>;
};
export type Palette = { brand: string; brandDark: string; onBrand: string; brandText: string; brandTint: string; accent: string; onAccent: string; notes: string[] };
@@ -51,6 +53,8 @@ export type SiteEvent = {
location: string | null;
image: Image | null;
url: string;
slug: string | null;
link: string | null;
from: "website" | "events" | "app";
registration: { status: string; priceFromCents: number | null } | null;
};
@@ -68,7 +72,7 @@ export type SiteMessage = {
thumbnail: string | null;
};
type Common = { church: Church | null; palette: Palette; style: { fontPairing: string; corners: string } };
type Common = { church: Church | null; palette: Palette; style: { fontPairing: string; corners: string }; verification?: { google: string | null; bing: string | null } };
export type ComingSoon = Common & { mode: "coming-soon"; template: Template; comingSoonText: string };
@@ -80,7 +84,7 @@ export type Published = Common & {
messages: SiteMessage[];
events: SiteEvent[];
/** Only when previewing the working copy (§4). */
preview?: { by: "admin" | "link"; canPublish: boolean };
preview?: { by: "admin" | "link"; canPublish: boolean; template?: string | null };
};
export type SiteContent = ComingSoon | Published;
+2 -2
View File
@@ -34,7 +34,7 @@ every release).
| 3 | Accounts 1.0.0 | **Released, rolled out and tested** (now `accounts@1.6.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)) |
| 4 | Cross Events 3.0.0: sign-in through Accounts | **Released, rolled out and tested** (now `events@3.7.0`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Churches sign in through their Accounts; crosscode-site `v1.6.0` deployed |
| 4+ | Running it: jobs from the dashboard, styled emails, .env from the Hub, sign-in health, the nightly people check; then frp config and one-product uninstalls, and the Hub's popups, pickers and port list | **Released, deployed and tested** 2026-11-20 and 2026-11-23 (below) |
| 5 | Church Website 1.0.0 | **Planned** 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) (all decisions confirmed). Font pairings confirmed 2026-11-24, section variants per template 2026-11-25 (§3). `contracts@1.17.0`, `accounts@1.7.0` and `events@3.7.0` released 2026-11-24, Hub `v2.21.0` 2026-11-25 (the Hub deployed 2026-11-25; the others not rolled out yet); `website@1.0.0` next |
| 5 | Church Website 1.0.0 | **Being built** (planned 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) , all decisions confirmed). Font pairings confirmed 2026-11-24, section variants per template 2026-11-25 (§3). `contracts@1.17.0`, `accounts@1.7.0` and `events@3.7.0` released 2026-11-24, Hub `v2.21.0` 2026-11-25 (the Hub deployed 2026-11-25; the others not rolled out yet). `contracts@1.18.0` and Hub `v2.22.0` (Get more storage) released 2026-11-25, not deployed. `apps/website` being built (0.1.0); `website@1.0.0` next |
| 6–7 | App 1.0.0 → App 1.x | Not started |
## Released 2026-11-23
@@ -102,7 +102,7 @@ out").
[WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md): decisions all confirmed 2026-11-21. Font pairings
confirmed 2026-11-24 (§3). Order: ~~contracts 1.17.0~~ → ~~Accounts 1.7.0~~ (both released 2026-11-24; Accounts
ships with contracts because it answers the new `church.update`) → ~~Events 3.7.0~~ (shared fonts and footer; released 2026-11-24) → ~~Hub 2.21.0~~ (released
and deployed 2026-11-25; the plan said 2.13.0) → **`website@1.0.0`** (being built in `apps/website` since 2026-11-25: signing in, the four templates and public site, the admin with preview, publish and restore, people and roles, messages with the YouTube feed, simple events, responsive photo sizes without metadata, the event feed both ways; next: Get more storage, Lighthouse, the VM test) → Hope Family Church → a second
and deployed 2026-11-25; the plan said 2.13.0) → **`website@1.0.0`** (being built in `apps/website` since 2026-11-25: signing in, the four templates and public site, the admin with preview, publish and restore, people and roles, messages with the YouTube feed, simple events, responsive photo sizes without metadata, the event feed both ways, church details through Accounts, settings, audit log, search engine data and redirects, Get more storage (with `contracts@1.18.0` and Hub `v2.22.0`, released 2026-11-25, Hub not deployed); next: screenshot comparison, Lighthouse, axe on every variant, a real-Postgres run, the release checks and the VM test) → Hope Family Church → a second
church → crosscode-site 1.7.0.
Done (confirmed by Joshua 2026-11-25): `hope-events` is archived, and every FastPanel site set up
before Hub 2.10.0, and the Hub's own site, has `location ^~ /api/`.
+11 -5
View File
@@ -1,6 +1,6 @@
# Versions — the latest release of everything
Last updated: 2026-11-24. Taken from the git tags, which is what a release is here (branch → merge →
Last updated: 2026-11-25. Taken from the git tags, which is what a release is here (branch → merge →
tag → push, see [HANDOVER.md](./HANDOVER.md) "Releasing"). **Update this file with every release.**
"Released" means tagged and pushed. Whether a release is **deployed** or rolled out is recorded
@@ -13,8 +13,8 @@ separately below; the two often differ.
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.0** | `events@3.7.0` | 2026-11-24 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.7.0** | `accounts@1.7.0` | 2026-11-24 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.5.0** | `agent@1.5.0` | 2026-11-23 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.17.0** | `contracts@1.17.0` | 2026-11-24 |
| Cross Code Hub | `events-hub` | **2.21.0** | `v2.21.0` | 2026-11-25 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.18.0** | `contracts@1.18.0` | 2026-11-25 |
| Cross Code Hub | `events-hub` | **2.22.0** | `v2.22.0` | 2026-11-25 |
| crosscode.co.za | `crosscode-site` | **1.6.1** | `v1.6.1` | 2026-11-23 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-23 (last change: uninstall, export and purge one product of a church) |
@@ -29,7 +29,7 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
| `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) |
| Website | `apps/website` | 0.1.0 (phase 5, being built: skeleton 2026-11-25; backend and frontend workspaces) |
| Website | `apps/website` | 0.1.0 (phase 5, being built; `website@1.0.0` after the Lighthouse, real-Postgres and VM runs. Built so far: signing in through Accounts, the four templates and public site, the admin with drafts, preview, publish and restore, people and roles, messages with the YouTube feed, simple events, the event feed both ways, church details, settings, audit log, search engine data, Get more storage; HANDOVER "Next up") |
| App | `apps/app` | 0.0.0 (not started, phase 6) |
These shared packages ship inside the apps that use them, from the same checkout, so they don't
@@ -37,12 +37,18 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for
- **Contracts 1.18.0 + Hub 2.22.0 (2026-11-25):** "Get more storage" for the Church Website (WEBSITE-1.0-PLAN
§10, decision 12). Contracts: `hub.storageRequestSchema` and its reply. Hub: `POST
/api/installs/storage-request` (shown on the install, Joshua emailed once, closed when the licence
gets more extra storage steps), and the church emailed once at 80% and once when full, from the
Website's heartbeat. The Hub vendors contracts 1.18.0. No migration. **Not deployed yet** (the Hub
still runs 2.21.0 below); nothing uses it until the Website is installed.
- **Hub 2.21.0 (2026-11-25):** New install offers the Church Website (Accounts first, at
`accounts.<its address>`); the FastPanel email sends a `www.` site's bare domain to `www.` with a
301. Extra Website storage is bought in 5 GB steps on the licence (Edit → Extra storage), sent to
the site as its limit (`limits.storageBytes`) and billed on the steps bought, no longer on usage.
Vendors contracts 1.17.0. **Migration:** `Licence.extraStorageSteps`. "Get more storage" comes
with the Website (contracts 1.18.0). **Deployed 2026-11-25.**
with the Website (contracts 1.18.0, Hub 2.22.0). **Deployed 2026-11-25.**
- **Events 3.7.0 (2026-11-24):** the public pages use the church's fonts, corners and the shared
church footer from its profile in Accounts (`GET /api/v2/church`, kept 10 minutes), with links to
its other sites in the header; `church.changed` from Accounts is now accepted (it answered 404
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/contracts",
"version": "1.17.0",
"version": "1.18.0",
"description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads",
"license": "UNLICENSED",
"type": "commonjs",
@@ -0,0 +1,7 @@
{
"protocolVersion": 2,
"steps": 1,
"usedBytes": 5100000000,
"limitBytes": 5368709120,
"requestedBy": "Pastor Sam"
}
@@ -0,0 +1,25 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-storage-request-response.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"requestedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"steps": {
"type": "integer",
"minimum": 1,
"maximum": 10
},
"alreadyRequested": {
"type": "boolean"
}
},
"required": [
"requestedAt",
"steps",
"alreadyRequested"
]
}
@@ -0,0 +1,44 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-storage-request.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"protocolVersion": {
"type": "number",
"const": 2
},
"steps": {
"type": "integer",
"minimum": 1,
"maximum": 10
},
"usedBytes": {
"type": "integer",
"minimum": 0,
"maximum": 9007199254740991
},
"limitBytes": {
"type": "integer",
"minimum": 0,
"maximum": 9007199254740991
},
"requestedBy": {
"anyOf": [
{
"type": "string",
"maxLength": 200
},
{
"type": "null"
}
]
}
},
"required": [
"protocolVersion",
"steps",
"usedBytes",
"limitBytes",
"requestedBy"
]
}
@@ -35,6 +35,8 @@ function contracts(c) {
"hub-update-request-response": c.hub.updateRequestResponseSchema,
"hub-update-request-cancel": c.hub.updateRequestCancelSchema,
"hub-update-request-cancel-response": c.hub.updateRequestCancelResponseSchema,
"hub-storage-request": c.hub.storageRequestSchema,
"hub-storage-request-response": c.hub.storageRequestResponseSchema,
"hub-ai-status-request": c.hub.aiStatusRequestSchema,
"hub-ai-status": c.hub.aiStatusSchema,
"hub-ai-complete-request": c.hub.aiCompleteRequestSchema,
+30
View File
@@ -294,6 +294,36 @@ export const updateRequestResponseSchema = z.object({
export const updateRequestCancelSchema = z.object({ protocolVersion });
export const updateRequestCancelResponseSchema = z.object({ cancelled: z.boolean() });
// ---------------------------------------------------------------------------------------------
// More storage (contracts 1.18.0, WEBSITE-1.0-PLAN §10, decision 12): a Website's admin presses
// "Get more storage". `POST /api/installs/storage-request`, signed as the heartbeat. The Hub records
// it and emails Joshua; he adds the steps to the licence, and the new limit reaches the site with
// the next heartbeat answer (`limits.storageBytes`). Asking again while a request is open changes
// its number of steps; nobody is emailed twice for the same request.
// ---------------------------------------------------------------------------------------------
/** One step is 5 GB (ROADMAP-v3 §10: R20 a month each). */
export const STORAGE_STEP_BYTES = 5 * 1024 ** 3;
export const storageRequestSchema = z.object({
protocolVersion,
/** How many 5 GB steps to add. */
steps: z.int().min(1).max(10),
/** What the site uses and may use now, for the email. */
usedBytes: z.int().nonnegative(),
limitBytes: z.int().nonnegative(),
/** Who asked (their name in the Website's admin), for the email. */
requestedBy: z.string().trim().max(200).nullable(),
});
export type StorageRequest = z.infer<typeof storageRequestSchema>;
export const storageRequestResponseSchema = z.object({
requestedAt: dateTimeSchema,
steps: z.int().min(1).max(10),
alreadyRequested: z.boolean(),
});
export type StorageRequestResponse = z.infer<typeof storageRequestResponseSchema>;
// ---------------------------------------------------------------------------------------------
// AI (as v1; usage is recorded per product on the Hub, the cap stays per customer)
// ---------------------------------------------------------------------------------------------
@@ -34,6 +34,7 @@ const SAMPLE_SCHEMA: Record<string, string> = {
"hub-heartbeat-app.json": "hub-heartbeat-request",
"hub-heartbeat-accounts.json": "hub-heartbeat-request",
"hub-heartbeat-response.json": "hub-heartbeat-response",
"hub-storage-request.json": "hub-storage-request",
"hub-licence-payload.json": "hub-licence-payload",
"hub-licence-payload-website.json": "hub-licence-payload",
"church-export.json": "church-export",
+1
View File
@@ -40,6 +40,7 @@ const SCHEMAS: Record<string, z.ZodType> = {
"hub-register-response.json": hub.registerResponseSchema,
"hub-heartbeat-events.json": hub.heartbeatRequestSchema,
"hub-heartbeat-website.json": hub.heartbeatRequestSchema,
"hub-storage-request.json": hub.storageRequestSchema,
"hub-heartbeat-app.json": hub.heartbeatRequestSchema,
"hub-heartbeat-accounts.json": hub.heartbeatRequestSchema,
"hub-heartbeat-response.json": hub.heartbeatResponseSchema,