Events 2.4.0 frontend, deploy and docs: Linked products, linked events, seo
- Site settings → Linked products (Connect, Show events from, Publish my events), help, command palette. - Events from linked products on /events, the home and campus pages, and /events/linked/<product>/<id> (markdown with HTML off, canonical to the origin, no JSON-LD, not in the sitemap). - Event page JSON-LD from @crosscode/seo; lib/eventSchema.ts removed. - Readiness check for linked products' sync; e2e spec with a fake Church Website (not run yet: needs the e2e Postgres). - crosscode: install and build the shared packages Events uses first (an older tag still builds as before); scripts/tests/events.bats. - Release notes, changelogs, handovers, hub-protocol.md, and the plan's "Changes while building". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,6 +2,33 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## events@2.4.0, contracts@1.4.0 - unreleased
|
||||
|
||||
Phase 2 (docs/EVENTS-2.4-PLAN.md): protocol v2, Linked products, the event feed and
|
||||
`packages/seo`. With Hub 2.2.0 (events-hub). Not tagged yet: the e2e run and the VM test come first.
|
||||
|
||||
### Events (2.4.0)
|
||||
|
||||
- Protocol v2 with the site's own Ed25519 key, Settings → Linked products with Connect, the public
|
||||
event feed (`/api/feed/v1/events`) and `event.changed`, and events from linked products on the
|
||||
public pages. Details in `apps/events/CHANGELOG.md`.
|
||||
|
||||
### Contracts (1.4.0)
|
||||
|
||||
- `crosscode.link/1` (`link.connect`, `link.connected`, `link.disconnect`) with `signLink` /
|
||||
`verifyLink`, PEM helpers, link secrets and nonces; `LINK_PATHS`, `FEED_PATHS`.
|
||||
- The v2 heartbeat can carry `publicKey`; the reply's `publicKeyStatus` (`saved` / `matches` /
|
||||
`mismatch`).
|
||||
- `typesVersions` for `@crosscode/contracts/signing` (older `moduleResolution`).
|
||||
|
||||
### packages/seo (new)
|
||||
|
||||
- `eventJsonLd`, `churchJsonLd`, `canonicalUrl`, `pageMeta`, `jsonLdString` (ROADMAP-v3 §11).
|
||||
|
||||
### Scripts
|
||||
|
||||
- `crosscode` (Events): installs and builds the shared packages Events uses before it.
|
||||
|
||||
## events@2.3.1 - 2026-11-18
|
||||
|
||||
- Next.js 16.4.6 (security advisories for 16.2.0–16.4.4; Events wasn't exposed). Also brings
|
||||
|
||||
@@ -5,6 +5,47 @@ All notable changes to this project are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [2.4.0] - unreleased
|
||||
|
||||
Protocol v2, Linked products, the event feed and `packages/seo` (ROADMAP-v3 phase 2,
|
||||
docs/EVENTS-2.4-PLAN.md). Needs Hub 2.2.0 for the move to protocol v2 (against an older Hub it keeps
|
||||
working on v1 and Linked products stays empty). contracts 1.4.0.
|
||||
|
||||
### Added
|
||||
|
||||
- **Protocol v2** (`src/hub/client.js`): register and heartbeat send `product: "events"`; the site
|
||||
makes an Ed25519 key pair once (`src/links/store.ts`, `hub_private_key` encrypted) and sends its
|
||||
public key on the heartbeat until the Hub answers `publicKeyStatus: saved | matches`. Installs
|
||||
registered with v1 move over without their licence key. The reply's `linkedProducts` is cached
|
||||
(`hub_linked_products`). A Hub that refuses a v2 body gets the same heartbeat as v1, and v1 is
|
||||
used for a day (`hub_v1_until`), so the licence always refreshes. Update requests and AI calls
|
||||
stay v1.
|
||||
- **Linked products** (Site settings → Linked products; `/api/v2/linked-products`): the church's
|
||||
other products from the Hub, **Connect** / **Disconnect** (`crosscode.link/1` over
|
||||
`POST /api/links/v1/connect` and `/disconnect`, both directions, Ed25519-signed and checked
|
||||
against the Hub-listed key, replays refused via `LinkNonce`), per-link **Show events from** and
|
||||
the site's **Publish my events** (`feed_publish`). Audit log: `product_link_connected`,
|
||||
`product_link_disconnected`, `feed_publish_toggled`, `feed_show_toggled`.
|
||||
- **The event feed** `GET /api/feed/v1/events?updatedSince=` (`crosscode.event-feed/1`, public, no
|
||||
personal information) built from `FeedEntry` (`src/feed/entries.ts`): going live, closing and
|
||||
selling out are changes even though no `Event` row changes; deactivated events go in `deleted`;
|
||||
ended events drop out after 30 days without a tombstone. Refreshed by the `feed` job (every 5
|
||||
minutes), a few seconds after writes to events, tickets and registrations (`config/db.js`), and
|
||||
before answering when older than a minute. Changes are announced with `event.changed`
|
||||
(`LINK_HEADERS`, one retry after a minute; the 15-minute poll catches the rest).
|
||||
- **Showing linked products' events** (`src/feed/sync.ts`, `ImportedEvent`): fetched every 15
|
||||
minutes (`feed-sync`) and on a valid `POST /api/feed/v1/changed` (`feed-sync-link` task); only
|
||||
events whose origin matches the link; the last good copy stays when a source is down. Shown on
|
||||
/events, the home page and campus pages, each with its page `/events/linked/<product>/<id>`
|
||||
(markdown with HTML off, canonical link to the origin, no JSON-LD, not in the sitemap).
|
||||
`/api/v2/linked-events`.
|
||||
- **`@crosscode/seo`** (`packages/seo`): the event page's JSON-LD now comes from
|
||||
`crosscode.event/1` (`crosscodeEvent` and `priceRangeCents` on `/events/:id/full`);
|
||||
`frontend/src/lib/eventSchema.ts` is gone. The price range now covers main tickets only (an add-on
|
||||
used to set the lowest price).
|
||||
- Readiness: "Events from linked products are up to date".
|
||||
- `FEED_JOBS_ENABLED` (default `true`). Migration `20261120120000_linked_products`.
|
||||
|
||||
## [2.3.1] - 2026-11-18
|
||||
|
||||
### Security
|
||||
|
||||
@@ -12,6 +12,16 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 2.4.0
|
||||
|
||||
- **Ready for the Church Website and App.** When your church has them, your events can show on
|
||||
them and theirs here, with registration and payments still in Cross Events. Nothing changes until
|
||||
you have them: Site settings → Linked products then lists them, with a Connect button.
|
||||
- **Publish my events** (on by default) shares your public events with your connected products,
|
||||
exactly as they appear on your events page. Hidden events and anyone's details are never shared.
|
||||
- **Better search results for your events**: Google gets each event's real dates, place and the
|
||||
price range of its main tickets, from the same data every Cross Code product uses.
|
||||
|
||||
## 2.3.1
|
||||
|
||||
- **Maintenance update.** An update to the framework the site is built on, with its latest security
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@crosscode/seo": "*",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
|
||||
@@ -91,6 +91,13 @@ async function readiness(now = new Date(), db = prisma) {
|
||||
lastBackup ? `Last backup ${new Date(lastBackup).toLocaleString('en-ZA')}` : 'No backups found on this server.',
|
||||
'/dashboard/admin/settings?tab=backups');
|
||||
|
||||
// Linked products (2.4.0): a product whose events are shown here, but that hasn't answered for a day.
|
||||
const shown = await (db.productLink?.findMany({ where: { showEvents: true }, select: { url: true, lastGoodAt: true, lastSyncError: true, connectedAt: true } }) ?? Promise.resolve([])).catch(() => []);
|
||||
const stale = shown.filter(l => l.lastSyncError && now - new Date(l.lastGoodAt || l.connectedAt) > DAY);
|
||||
add('linked_sync', 'Events from linked products are up to date', stale.length === 0,
|
||||
stale.length ? `Not fetched for over a day: ${stale.map(l => l.url).join(', ')}. Their last events keep showing.` : `${shown.length} product${shown.length === 1 ? '' : 's'} fetched in the last day`,
|
||||
'/dashboard/admin/settings?tab=linked', shown.length > 0);
|
||||
|
||||
const applicable = checks.filter(c => c.applies);
|
||||
const passed = applicable.filter(c => c.ok).length;
|
||||
return { score: applicable.length ? Math.round((passed / applicable.length) * 100) : 0, passed, total: applicable.length, checks };
|
||||
|
||||
@@ -484,3 +484,37 @@ describe('protocol v2 heartbeat', () => {
|
||||
expect(await store.publicKeyStatus()).toBe('saved');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── The event page's JSON-LD (@crosscode/seo, replacing frontend/src/lib/eventSchema.ts) ──
|
||||
|
||||
describe('event JSON-LD from crosscode.event/1', () => {
|
||||
test('matches what the event page sent before 2.4.0, with the price range from main tickets only', () => {
|
||||
const { eventJsonLd } = require('@crosscode/seo');
|
||||
const row = eventRow({ id: '00000000-0000-4000-8000-0000000000aa' });
|
||||
const built = buildCrosscodeEvent(row, new Map(), ctx());
|
||||
// As the page calls it (events/[id]/page.tsx).
|
||||
const ld = eventJsonLd({ ...built.event, description: row.description }, {
|
||||
pageUrl: `https://events.hope.test/events/${row.id}`,
|
||||
organizer: { name: 'Hope Family Church', url: 'https://events.hope.test' },
|
||||
priceRange: built.priceRangeCents,
|
||||
offerUrl: `https://events.hope.test/register/${row.id}`,
|
||||
validFrom: row.goLiveAt.toISOString(),
|
||||
});
|
||||
expect(ld).toEqual({
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'Event',
|
||||
name: 'Youth Camp',
|
||||
description: row.description,
|
||||
startDate: row.startDate.toISOString(),
|
||||
endDate: row.endDate.toISOString(),
|
||||
eventStatus: 'https://schema.org/EventScheduled',
|
||||
eventAttendanceMode: 'https://schema.org/OfflineEventAttendanceMode',
|
||||
location: { '@type': 'Place', name: 'Camp Wartburg', address: 'Camp Wartburg' },
|
||||
image: ['https://events.hope.test/api/uploads/camp.jpg'],
|
||||
url: `https://events.hope.test/events/${row.id}`,
|
||||
organizer: { '@type': 'Organization', name: 'Hope Family Church', url: 'https://events.hope.test' },
|
||||
// Before 2.4.0 the add-on T-shirt (R120) made this 120.00–450.00.
|
||||
offers: { '@type': 'AggregateOffer', lowPrice: '300.00', highPrice: '450.00', priceCurrency: 'ZAR', availability: 'https://schema.org/InStock', url: `https://events.hope.test/register/${row.id}`, validFrom: row.goLiveAt.toISOString() },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -145,6 +145,26 @@ Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026
|
||||
- `backend/src/hub/client.js` `connectFromEnv()`: a site the Hub installed registers by itself on
|
||||
first start from `HUB_LICENCE_KEY`.
|
||||
|
||||
## Where Linked products and the feed live (2.4.0)
|
||||
|
||||
Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md).
|
||||
|
||||
- **Protocol v2**: `backend/src/hub/client.js` (`heartbeatBody`, the v1 fallback `hub_v1_until`).
|
||||
The key pair and the Hub's list of the church's products: `backend/src/links/store.ts`.
|
||||
- **Connect** (`crosscode.link/1`): `backend/src/links/connect.ts` (both directions),
|
||||
`links/http.ts` (calls to siblings: public addresses only, like webhooks), `links/routes.ts`
|
||||
(`/api/feed/v1/*`, `/api/links/v1/*`, mounted in `app.js` before the JSON parser).
|
||||
- **The feed**: `backend/src/feed/build.ts` (an Event as `crosscode.event/1`, also for the event
|
||||
page's JSON-LD), `feed/entries.ts` (`FeedEntry`, refresh, `changedSoon` from `config/db.js`),
|
||||
`feed/notify.ts` (`event.changed`), `feed/sync.ts` (fetching linked products' events into
|
||||
`ImportedEvent`). Jobs `feed`, `feed-sync`; task `feed-sync-link`.
|
||||
- **Screens**: `frontend/src/components/admin/LinkedProductsTab.tsx` (Site settings → Linked
|
||||
products), `components/events/LinkedEventCard.tsx`, `lib/linkedEvents.ts`,
|
||||
`app/events/linked/[product]/[id]/page.tsx`. API: `backend/src/v2/resources/linkedProducts.ts`.
|
||||
- **Tests**: `backend/tests/linkedProducts.test.js` (in-memory database:
|
||||
`tests/support/fakeFeedDb.js`), `e2e/linked-products.spec.ts` (a fake Church Website on
|
||||
localhost:5198).
|
||||
|
||||
## Working on this repo
|
||||
|
||||
- **Release routine:** branch `feat/<name>` → commit → bump with
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import http from "http";
|
||||
import path from "path";
|
||||
import crypto from "crypto";
|
||||
import { test, expect, loginAs, seed, API } from "./fixtures";
|
||||
|
||||
// Linked products and the event feed (2.4.0, docs/EVENTS-2.4-PLAN.md §8). A fake Church Website
|
||||
// runs on localhost: the test tells the site the Hub listed it (as a heartbeat would), an admin
|
||||
// connects it and shows its events, and its event appears on /events with its own page whose
|
||||
// canonical link points back to the website. Also: this site's own feed, and its event JSON-LD.
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- the backend's own modules, as prepare-db.js uses them */
|
||||
const backend = path.join(__dirname, "..", "backend");
|
||||
const { Client } = require(require.resolve("pg", { paths: [backend] }));
|
||||
const { e2eDatabaseUrl } = require("./support/db-url");
|
||||
const signing = require(require.resolve("@crosscode/contracts/signing", { paths: [backend] }));
|
||||
const { eventFeedSchema } = require(require.resolve("@crosscode/contracts", { paths: [backend] }));
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const WEBSITE_PORT = 5198;
|
||||
const WEBSITE_URL = `http://localhost:${WEBSITE_PORT}`;
|
||||
const WEBSITE_ID = "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02";
|
||||
const EVENTS_ID = "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c";
|
||||
const EVENT_ID = "6e5d4c3b-2a19-4807-b6f5-e4d3c2b1a090";
|
||||
const websiteKey = signing.generateEd25519();
|
||||
const websitePem = signing.ed25519PublicToPem(websiteKey.publicKey);
|
||||
|
||||
async function sql<T = Record<string, unknown>>(text: string, values: unknown[] = []): Promise<T[]> {
|
||||
const client = new Client({ connectionString: e2eDatabaseUrl() });
|
||||
await client.connect();
|
||||
try {
|
||||
return (await client.query(text, values)).rows as T[];
|
||||
} finally {
|
||||
await client.end();
|
||||
}
|
||||
}
|
||||
const setSetting = (key: string, value: string) =>
|
||||
sql(`INSERT INTO "AppSetting" (key, value, "updatedAt") VALUES ($1, $2, now()) ON CONFLICT (key) DO UPDATE SET value = $2, "updatedAt" = now()`, [key, value]);
|
||||
|
||||
function websiteEvent() {
|
||||
const starts = new Date(Date.now() + 10 * 24 * 3600e3);
|
||||
return {
|
||||
schema: "crosscode.event/1",
|
||||
id: EVENT_ID,
|
||||
origin: { product: "website", installId: WEBSITE_ID, url: `${WEBSITE_URL}/events/carols-by-candlelight` },
|
||||
status: "published",
|
||||
updatedAt: new Date().toISOString(),
|
||||
title: "Carols by Candlelight",
|
||||
summary: null,
|
||||
description: "Bring a **blanket** and the family.\n\n<script>alert(1)</script>No booking needed.",
|
||||
imageUrl: null,
|
||||
timezone: "Africa/Johannesburg",
|
||||
startsAt: starts.toISOString(),
|
||||
endsAt: new Date(starts.getTime() + 2 * 3600e3).toISOString(),
|
||||
allDay: false,
|
||||
sessions: [],
|
||||
location: { name: "Church lawn", address: null, onlineUrl: null },
|
||||
campus: null,
|
||||
series: null,
|
||||
tags: ["christmas"],
|
||||
registration: { mode: "contact", url: null, status: "open", opensAt: null, closesAt: null, priceFrom: null },
|
||||
};
|
||||
}
|
||||
|
||||
test.describe.serial("linked products and the event feed", () => {
|
||||
let server: http.Server;
|
||||
const connects: Record<string, unknown>[] = [];
|
||||
|
||||
test.beforeAll(async () => {
|
||||
server = http.createServer((req, res) => {
|
||||
let body = "";
|
||||
req.on("data", c => { body += c; });
|
||||
req.on("end", async () => {
|
||||
const send = (status: number, json: unknown) => res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(json));
|
||||
if (req.method === "POST" && req.url === "/api/links/v1/connect") {
|
||||
const m = JSON.parse(body);
|
||||
connects.push(m);
|
||||
// The website checks Cross Events' message with the key the Hub listed for it.
|
||||
const [row] = await sql<{ value: string }>(`SELECT value FROM "AppSetting" WHERE key = 'hub_public_key'`);
|
||||
if (!row || !signing.verifyLink(m, row.value).ok) return send(401, { message: "Bad signature", code: "BAD_SIGNATURE" });
|
||||
return send(200, signing.signLink({
|
||||
schema: "crosscode.link/1", type: "link.connected",
|
||||
from: { product: "website", installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID },
|
||||
inReplyTo: m.nonce, issuedAt: new Date().toISOString(), nonce: crypto.randomBytes(18).toString("base64url"),
|
||||
}, websiteKey.privateKeyPem));
|
||||
}
|
||||
if (req.method === "GET" && req.url?.startsWith("/api/feed/v1/events")) {
|
||||
return send(200, { schema: "crosscode.event-feed/1", generatedAt: new Date().toISOString(), events: [websiteEvent()], deleted: [] });
|
||||
}
|
||||
if (req.method === "POST" && req.url === "/api/links/v1/disconnect") return send(200, { schema: "crosscode.link/1", type: "link.disconnected" });
|
||||
return send(404, { message: "Not here", code: "NOT_FOUND" });
|
||||
});
|
||||
});
|
||||
await new Promise<void>(resolve => server.listen(WEBSITE_PORT, resolve));
|
||||
// What a v2 heartbeat would have stored: this site's Hub id and the church's other products.
|
||||
await setSetting("hub_install_id", EVENTS_ID);
|
||||
await setSetting("hub_linked_products", JSON.stringify([{ product: "website", installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: websitePem }]));
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await sql(`DELETE FROM "ProductLink"`);
|
||||
await sql(`DELETE FROM "FeedEntry"`);
|
||||
await sql(`DELETE FROM "AppSetting" WHERE key IN ('hub_install_id', 'hub_linked_products', 'feed_publish')`);
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
});
|
||||
|
||||
test("an admin connects the Church Website and shows its events", async ({ page }) => {
|
||||
await loginAs(page, "admin");
|
||||
await page.goto("/dashboard/admin/settings?tab=linked");
|
||||
const row = page.getByTestId("linked-website");
|
||||
await expect(row).toContainText("Church Website");
|
||||
await expect(row).toContainText("Not connected");
|
||||
await row.getByRole("button", { name: "Connect" }).click();
|
||||
await expect(page.getByRole("status")).toContainText("Connected to Church Website.");
|
||||
expect(connects).toHaveLength(1);
|
||||
expect(connects[0]).toMatchObject({ type: "link.connect", from: { product: "events", installId: EVENTS_ID }, to: { installId: WEBSITE_ID } });
|
||||
|
||||
await row.getByLabel(/Show events from Church Website/).check();
|
||||
await expect(page.getByRole("status")).toContainText("events are fetched");
|
||||
await expect(row).toContainText("1 event");
|
||||
});
|
||||
|
||||
test("its event is on /events, with its own page pointing back to the website", async ({ page }) => {
|
||||
await page.goto("/events");
|
||||
const card = page.getByTestId("linked-event-card").filter({ hasText: "Carols by Candlelight" });
|
||||
await expect(card).toContainText("From the Church Website");
|
||||
await card.getByRole("link", { name: "View details" }).click();
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/events/linked/website/${EVENT_ID}$`));
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Carols by Candlelight");
|
||||
await expect(page.locator('link[rel="canonical"]')).toHaveAttribute("href", `${WEBSITE_URL}/events/carols-by-candlelight`);
|
||||
await expect(page.locator("strong", { hasText: "blanket" })).toBeVisible();
|
||||
// HTML in the description is dropped, never run.
|
||||
expect(await page.locator("main script").count()).toBe(0);
|
||||
expect(await page.locator('script[type="application/ld+json"]').count()).toBe(0);
|
||||
|
||||
const sitemap = await (await page.request.get("/sitemap.xml")).text();
|
||||
expect(sitemap).not.toContain("/events/linked/");
|
||||
});
|
||||
|
||||
test("this site's own feed and event JSON-LD", async ({ page, request }) => {
|
||||
const res = await request.get(`${API}/api/feed/v1/events`);
|
||||
expect(res.status()).toBe(200);
|
||||
const feed = await res.json();
|
||||
expect(eventFeedSchema.safeParse(feed).success).toBe(true);
|
||||
const ids = feed.events.map((e: { id: string }) => e.id);
|
||||
expect(ids).toContain(seed().events.free);
|
||||
expect(ids).not.toContain(EVENT_ID);
|
||||
expect(JSON.stringify(feed)).not.toMatch(/@e2e\.test/);
|
||||
|
||||
await page.goto(`/events/${seed().events.free}`);
|
||||
const ld = JSON.parse(await page.locator('script[type="application/ld+json"]').innerText());
|
||||
expect(ld).toMatchObject({ "@context": "https://schema.org", "@type": "Event", url: expect.stringContaining(`/events/${seed().events.free}`) });
|
||||
});
|
||||
|
||||
test("disconnecting removes its events", async ({ page }) => {
|
||||
await loginAs(page, "admin");
|
||||
await page.goto("/dashboard/admin/settings?tab=linked");
|
||||
page.once("dialog", d => d.accept());
|
||||
await page.getByTestId("linked-website").getByRole("button", { name: "Disconnect" }).click();
|
||||
await expect(page.getByRole("status")).toContainText("Disconnected from Church Website.");
|
||||
await page.goto("/events");
|
||||
await expect(page.getByTestId("linked-event-card")).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,8 @@ import { notFound } from "next/navigation";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { EventCard } from "@/components/events/EventCard";
|
||||
import { LinkedEventCard } from "@/components/events/LinkedEventCard";
|
||||
import { fetchLinkedEvents, mergeByStart } from "@/lib/linkedEvents";
|
||||
import { ApiImage } from "@/components/shared/ApiImage";
|
||||
import { apiFetchListForPrerender, ApiError } from "@/lib/api";
|
||||
import { mapsSearchUrl } from "@/lib/maps";
|
||||
@@ -42,13 +44,17 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s
|
||||
const campus = await loadCampus(slug);
|
||||
if (!campus) notFound();
|
||||
|
||||
const events = await apiFetchListForPrerender<Event>(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } });
|
||||
const [events, linked] = await Promise.all([
|
||||
apiFetchListForPrerender<Event>(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } }),
|
||||
fetchLinkedEvents(campus.slug),
|
||||
]);
|
||||
// A server component renders once per request (or revalidation): this is that render's time.
|
||||
// eslint-disable-next-line react-hooks/purity
|
||||
const now = Date.now();
|
||||
const upcoming = (events || [])
|
||||
.filter(e => e.cashupStatus !== "closed" && new Date(e.endDate || e.startDate).getTime() > now)
|
||||
.sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime());
|
||||
const items = mergeByStart(upcoming, linked, e => e.nextSession?.startsAt || e.startDate);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
@@ -79,14 +85,16 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s
|
||||
|
||||
<h2 className="text-xl font-semibold text-gray-900 mb-1">Upcoming events</h2>
|
||||
<p className="text-sm text-gray-500 mb-6">Events at {campus.name}, and church-wide events for every campus.</p>
|
||||
{upcoming.length === 0 ? (
|
||||
{items.length === 0 ? (
|
||||
<div className="text-center py-16 border rounded-xl bg-gray-50">
|
||||
<CalendarX className="w-8 h-8 text-gray-300 mx-auto mb-2" />
|
||||
<p className="text-gray-500 text-sm">No upcoming events at {campus.name} right now — check back soon.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
|
||||
{upcoming.map(event => <EventCard key={event.id} event={event} />)}
|
||||
{items.map(item => item.kind === "own"
|
||||
? <EventCard key={item.event.id} event={item.event} />
|
||||
: <LinkedEventCard key={item.event.key} item={item.event} />)}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
|
||||
@@ -8,7 +8,7 @@ import { ApiError, resolveToApiOrigin } from "@/lib/api";
|
||||
import { apiV2Raw, apiV2Data } from "@/lib/apiV2";
|
||||
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles } from "lucide-react";
|
||||
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles, Link2 } from "lucide-react";
|
||||
import { ColorPickerField } from "@/components/admin/ColorPickerField";
|
||||
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
|
||||
import { BackupsTab } from "@/components/admin/BackupsTab";
|
||||
@@ -17,6 +17,7 @@ import { PaymentsTab } from "@/components/admin/PaymentsTab";
|
||||
import { LicenceTab } from "@/components/admin/LicenceTab";
|
||||
import { WebhooksTab } from "@/components/admin/WebhooksTab";
|
||||
import { AiTab } from "@/components/admin/AiTab";
|
||||
import { LinkedProductsTab } from "@/components/admin/LinkedProductsTab";
|
||||
import { CampusesTab } from "@/components/admin/CampusesTab";
|
||||
import { extractDominantColors } from "@/lib/extractColors";
|
||||
import { mapsSearchUrl } from "@/lib/maps";
|
||||
@@ -25,7 +26,7 @@ import { BackLink } from "@/components/shared/BackLink";
|
||||
import { uploadImage } from "@/lib/eventSetup";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
|
||||
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence" | "ai";
|
||||
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "backups" | "jobs" | "licence" | "ai";
|
||||
|
||||
const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
|
||||
{ id: "organisation", label: "Organisation", icon: Building2 },
|
||||
@@ -37,6 +38,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
|
||||
{ id: "whatsapp", label: "WhatsApp", icon: MessageCircle },
|
||||
{ id: "payments", label: "Payments", icon: CreditCard },
|
||||
{ id: "webhooks", label: "Webhooks", icon: Webhook },
|
||||
{ id: "linked", label: "Linked products", icon: Link2 },
|
||||
{ id: "backups", label: "Backups", icon: DatabaseBackup },
|
||||
{ id: "jobs", label: "Background jobs", icon: Timer },
|
||||
{ id: "licence", label: "Licence", icon: KeyRound },
|
||||
@@ -718,6 +720,7 @@ function SiteSettingsPageInner() {
|
||||
{/* ── Backups ───────────────────────────────────────────────────────── */}
|
||||
{activeTab === "backups" && <BackupsTab active={activeTab === "backups"} />}
|
||||
{activeTab === "webhooks" && <WebhooksTab active={activeTab === "webhooks"} />}
|
||||
{activeTab === "linked" && <LinkedProductsTab active={activeTab === "linked"} />}
|
||||
{activeTab === "jobs" && <JobsTab active={activeTab === "jobs"} />}
|
||||
{activeTab === "licence" && <LicenceTab active={activeTab === "licence"} />}
|
||||
{activeTab === "ai" && <AiTab active={activeTab === "ai"} />}
|
||||
|
||||
@@ -54,6 +54,9 @@ type Event = {
|
||||
attendanceMode?: "whole" | "pick";
|
||||
sessions?: EventSession[];
|
||||
registrationClosesAt?: string;
|
||||
// 2.4.0: the event as crosscode.event/1, what its schema.org JSON-LD is built from (@crosscode/seo).
|
||||
crosscodeEvent?: CrosscodeEvent | null;
|
||||
priceRangeCents?: { lowCents: number; highCents: number } | null;
|
||||
lateJoin?: LateJoinInfo | null;
|
||||
series?: EventSeriesRef | null;
|
||||
nextInSeries?: NextInSeries | null;
|
||||
@@ -69,7 +72,8 @@ import { isPickOption, latePrice, registrationClosesAt, scheduleSummary } from "
|
||||
import { SessionSchedule } from "@/components/events/SessionSchedule";
|
||||
import { appUrl, appName } from "@/lib/siteConfig";
|
||||
import { getServerSettings } from "@/lib/serverSettings";
|
||||
import { eventJsonLd, jsonLdString } from "@/lib/eventSchema";
|
||||
import { eventJsonLd, jsonLdString } from "@crosscode/seo";
|
||||
import type { CrosscodeEvent } from "@crosscode/contracts";
|
||||
|
||||
// Tiered low-stock threshold: larger events use a smaller percentage.
|
||||
// Math.round avoids Math.ceil inflating the threshold (e.g. ceil(1.5)=2 made
|
||||
@@ -188,16 +192,21 @@ export default async function EventDetailPage({ params }: { params: Promise<{ id
|
||||
|
||||
const settings = await getServerSettings();
|
||||
const siteUrl = appUrl.replace(/\/$/, "");
|
||||
const jsonLd = eventJsonLd(event, {
|
||||
pageUrl: `${siteUrl}/events/${event.id}`,
|
||||
imageUrl: event.picture ? resolveToApiOrigin(event.picture) : null,
|
||||
organizerName: settings.org_name || appName,
|
||||
siteUrl,
|
||||
});
|
||||
// schema.org Event (Google's event results), from the same crosscode.event/1 the feed publishes.
|
||||
// The description goes in as the plain text it is (the feed's copy is escaped for markdown).
|
||||
const jsonLd = event.crosscodeEvent
|
||||
? eventJsonLd({ ...event.crosscodeEvent, description: event.description || null }, {
|
||||
pageUrl: `${siteUrl}/events/${event.id}`,
|
||||
organizer: { name: settings.org_name || appName, url: siteUrl },
|
||||
priceRange: event.priceRangeCents ?? undefined,
|
||||
offerUrl: `${siteUrl}/register/${event.id}`,
|
||||
validFrom: event.goLiveAt || null,
|
||||
})
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLdString(jsonLd) }} />
|
||||
{jsonLd && <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLdString(jsonLd) }} />}
|
||||
<Navbar />
|
||||
<main className="flex-1 py-8 px-4 max-w-6xl mx-auto w-full">
|
||||
<FunnelTracker eventId={event.id} stage="view" />
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import { ArrowLeft, Calendar, ExternalLink, MapPin, Video } from "lucide-react";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { ApiImage } from "@/components/shared/ApiImage";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { apiV2Data } from "@/lib/apiV2";
|
||||
import { formatDateTimeRange } from "@/lib/date";
|
||||
import { fromLabel, type LinkedEvent } from "@/lib/linkedEvents";
|
||||
|
||||
export const revalidate = 60;
|
||||
|
||||
type Linked = LinkedEvent & { lastSyncedAt: string | null };
|
||||
type Params = { params: Promise<{ product: string; id: string }> };
|
||||
|
||||
async function load(product: string, id: string): Promise<Linked | null> {
|
||||
if (product !== "website" && product !== "app") return null;
|
||||
try {
|
||||
return (await apiV2Data("get", "/linked-events/{product}/{id}", { params: { product, id }, nextOptions: { next: { revalidate } } })) as unknown as Linked;
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && (e.status === 404 || e.status === 400)) return null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** The description's first paragraph as plain text, for the meta description. */
|
||||
const plain = (md: string | null) => (md || "").split(/\n\s*\n/)[0]!.replace(/\\([\\`*_[\]<>|~#+.!()-])/g, "$1").replace(/[*_`]/g, "").trim().slice(0, 200);
|
||||
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const { product, id } = await params;
|
||||
const item = await load(product, id);
|
||||
if (!item) return {};
|
||||
const e = item.event;
|
||||
const description = e.summary || plain(e.description) || `${e.title} — ${formatDateTimeRange(e.startsAt, e.endsAt)}`;
|
||||
return {
|
||||
title: e.title,
|
||||
description,
|
||||
// A copy: search engines are pointed at the event's own page, so they see one event, not two
|
||||
// (ROADMAP-v3 §11, "Imported events"). It isn't in this site's sitemap either.
|
||||
alternates: { canonical: e.origin.url },
|
||||
openGraph: { title: e.title, description, type: "website", url: e.origin.url, ...(e.imageUrl ? { images: [{ url: e.imageUrl }] } : {}) },
|
||||
twitter: { card: "summary_large_image", title: e.title, description, ...(e.imageUrl ? { images: [e.imageUrl] } : {}) },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An event from another of the church's products (2.4.0): shown read-only, with the way to take
|
||||
* part at the product it comes from. No schema.org JSON-LD here; its own page carries it.
|
||||
*/
|
||||
export default async function LinkedEventPage({ params }: Params) {
|
||||
const { product, id } = await params;
|
||||
const item = await load(product, id);
|
||||
if (!item) notFound();
|
||||
const e = item.event;
|
||||
const r = e.registration;
|
||||
const live = e.sessions.filter(s => !s.cancelled);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<Navbar />
|
||||
<main className="flex-1 py-8 px-4 max-w-4xl mx-auto w-full">
|
||||
<Link href="/events" className="inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 mb-4">
|
||||
<ArrowLeft className="w-4 h-4" /> All events
|
||||
</Link>
|
||||
{e.imageUrl && <ApiImage src={e.imageUrl} alt={e.title} className="w-full max-h-96 object-cover rounded-2xl mb-6" />}
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-brand-700">{fromLabel(item)}</p>
|
||||
<h1 className="text-3xl font-bold text-gray-900 mt-1">{e.title}</h1>
|
||||
{e.status === "cancelled" && <p className="mt-2 inline-block rounded-full bg-red-50 px-3 py-1 text-sm font-medium text-red-700">Cancelled</p>}
|
||||
|
||||
<div className="mt-4 space-y-2 text-gray-700">
|
||||
<p className="flex items-center gap-2"><Calendar className="w-4 h-4 shrink-0 text-gray-400" /> {formatDateTimeRange(e.startsAt, e.endsAt)}</p>
|
||||
{(e.location?.name || e.location?.address) && (
|
||||
<p className="flex items-center gap-2"><MapPin className="w-4 h-4 shrink-0 text-gray-400" /> {[e.location?.name, e.location?.address].filter(Boolean).join(", ")}</p>
|
||||
)}
|
||||
{e.location?.onlineUrl && (
|
||||
<p className="flex items-center gap-2"><Video className="w-4 h-4 shrink-0 text-gray-400" /> <a href={e.location.onlineUrl} rel="noopener nofollow" className="text-brand-700 underline">Join online</a></p>
|
||||
)}
|
||||
{e.campus && <p className="text-sm text-gray-500">{e.campus.name}</p>}
|
||||
</div>
|
||||
|
||||
{live.length > 1 && (
|
||||
<div className="mt-6">
|
||||
<h2 className="font-semibold text-gray-900 mb-2">Dates</h2>
|
||||
<ul className="space-y-1 text-sm text-gray-700">
|
||||
{live.map(s => <li key={s.id}>{s.label ? `${s.label}: ` : ""}{formatDateTimeRange(s.startsAt, s.endsAt)}{s.location ? ` · ${s.location}` : ""}</li>)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{e.description && (
|
||||
<div className="prose prose-sm max-w-none mt-6 text-gray-700">
|
||||
{/* Markdown with HTML switched off (crosscode.event/1): raw HTML is dropped, links open as plain links. */}
|
||||
<ReactMarkdown skipHtml components={{ a: ({ href, children }) => <a href={href} rel="noopener nofollow ugc" className="text-brand-700 underline">{children}</a> }}>
|
||||
{e.description}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-8 rounded-xl border p-4 bg-gray-50">
|
||||
{(r.mode === "origin" || r.mode === "external") && r.url ? (
|
||||
<a href={r.url} rel="noopener" className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-5 py-2.5 text-white font-medium hover:bg-brand-700">
|
||||
Register <ExternalLink className="w-4 h-4" aria-hidden />
|
||||
</a>
|
||||
) : r.mode === "contact" ? (
|
||||
<p className="text-sm text-gray-700">No booking here: see the details above for how to take part.</p>
|
||||
) : (
|
||||
<p className="text-sm text-gray-700">No booking needed.</p>
|
||||
)}
|
||||
<p className="mt-3 text-sm text-gray-600">
|
||||
This event is run through the {item.productName}.{" "}
|
||||
<a href={e.origin.url} rel="noopener" className="text-brand-700 underline">See it there</a> for the latest details.
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { EventsGrid } from "@/components/events/EventsGrid";
|
||||
import { apiFetchListForPrerender } from "@/lib/api";
|
||||
import { fetchLinkedEvents } from "@/lib/linkedEvents";
|
||||
import { Calendar } from "lucide-react";
|
||||
|
||||
export const revalidate = 60;
|
||||
@@ -32,7 +33,10 @@ type Event = {
|
||||
};
|
||||
|
||||
export default async function EventsPage() {
|
||||
const events = await apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } });
|
||||
const [events, linked] = await Promise.all([
|
||||
apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } }),
|
||||
fetchLinkedEvents(),
|
||||
]);
|
||||
// A server component renders once per request (or revalidation): this is that render's time.
|
||||
// eslint-disable-next-line react-hooks/purity
|
||||
const now = Date.now();
|
||||
@@ -53,10 +57,10 @@ export default async function EventsPage() {
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900">All Events</h1>
|
||||
<p className="text-sm text-gray-500">{sorted.length} upcoming event{sorted.length === 1 ? "" : "s"}</p>
|
||||
<p className="text-sm text-gray-500">{sorted.length + linked.length} upcoming event{sorted.length + linked.length === 1 ? "" : "s"}</p>
|
||||
</div>
|
||||
</div>
|
||||
<EventsGrid events={sorted} />
|
||||
<EventsGrid events={sorted} linked={linked} />
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import Link from "next/link";
|
||||
import { EventCard } from "@/components/events/EventCard";
|
||||
import { LinkedEventCard } from "@/components/events/LinkedEventCard";
|
||||
import { fetchLinkedEvents, mergeByStart } from "@/lib/linkedEvents";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { JoinUsButton } from "@/components/home/JoinUsButton";
|
||||
@@ -48,9 +50,10 @@ async function getOrgName(): Promise<string> {
|
||||
}
|
||||
|
||||
export default async function HomePage() {
|
||||
const [events, displayName] = await Promise.all([
|
||||
const [events, displayName, linked] = await Promise.all([
|
||||
apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } }),
|
||||
getOrgName(),
|
||||
fetchLinkedEvents(),
|
||||
]);
|
||||
// A server component renders once per request (or revalidation): this is that render's time.
|
||||
// eslint-disable-next-line react-hooks/purity
|
||||
@@ -60,6 +63,8 @@ export default async function HomePage() {
|
||||
return !isNaN(t) && t > now;
|
||||
});
|
||||
const sorted = [...upcoming].sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime());
|
||||
// With events from the church's other products (Linked products), by date.
|
||||
const items = mergeByStart(sorted, linked, e => e.nextSession?.startsAt || e.startDate);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
@@ -72,10 +77,10 @@ export default async function HomePage() {
|
||||
<div className="absolute -bottom-24 -left-24 w-96 h-96 rounded-full bg-brand-100/40 blur-3xl" />
|
||||
</div>
|
||||
<div className="relative max-w-2xl mx-auto px-4">
|
||||
{sorted.length > 0 && (
|
||||
{items.length > 0 && (
|
||||
<div className="inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-full bg-white border border-brand-200 text-brand-700 shadow-sm mb-5">
|
||||
<CalendarCheck className="w-3.5 h-3.5" />
|
||||
{sorted.length} upcoming event{sorted.length === 1 ? "" : "s"}
|
||||
{items.length} upcoming event{items.length === 1 ? "" : "s"}
|
||||
</div>
|
||||
)}
|
||||
<h1 className="text-4xl sm:text-5xl font-bold mb-4 text-gray-900">Welcome to {displayName}</h1>
|
||||
@@ -98,16 +103,16 @@ export default async function HomePage() {
|
||||
<ArrowRight className="w-3.5 h-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
{sorted.length === 0 ? (
|
||||
{items.length === 0 ? (
|
||||
<div className="text-center py-12 border rounded-xl bg-gray-50">
|
||||
<CalendarCheck className="w-8 h-8 text-gray-300 mx-auto mb-2" />
|
||||
<p className="text-gray-500 text-sm">No upcoming events right now — check back soon.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
|
||||
{sorted.slice(0, 3).map(event => (
|
||||
<EventCard key={event.id} event={event} />
|
||||
))}
|
||||
{items.slice(0, 3).map(item => item.kind === "own"
|
||||
? <EventCard key={item.event.id} event={item.event} />
|
||||
: <LinkedEventCard key={item.event.key} item={item.event} />)}
|
||||
</div>
|
||||
)}
|
||||
<div className="text-center mt-8 sm:hidden">
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Link2, RefreshCw } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiV2, type V2Result } from "@/lib/apiV2";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Overview = V2Result<"/linked-products", "get">["data"];
|
||||
type Product = Overview["products"][number];
|
||||
|
||||
const when = (iso: string | null) =>
|
||||
iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "never";
|
||||
|
||||
/** "2 hours ago", for "last synced". */
|
||||
function ago(iso: string | null): string {
|
||||
if (!iso) return "never";
|
||||
const mins = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
|
||||
if (mins < 1) return "just now";
|
||||
if (mins < 60) return `${mins} minute${mins === 1 ? "" : "s"} ago`;
|
||||
const hours = Math.round(mins / 60);
|
||||
if (hours < 48) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
|
||||
return `${Math.round(hours / 24)} days ago`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Site settings → Linked products (2.4.0): the church's other Cross Code products (as the Hub
|
||||
* lists them), Connect / Disconnect, "Show events from" each, and "Publish my events".
|
||||
*/
|
||||
export function LinkedProductsTab({ active }: { active: boolean }) {
|
||||
const { token } = useAuth();
|
||||
const [data, setData] = useState<Overview | null>(null);
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || !token) return;
|
||||
let alive = true;
|
||||
apiV2("get", "/linked-products", { authToken: token })
|
||||
.then(({ data: d }) => { if (alive) setData(d); })
|
||||
.catch(e => { if (alive) setMsg({ ok: false, text: errorMessage(e) || "Could not load linked products." }); });
|
||||
return () => { alive = false; };
|
||||
}, [active, token]);
|
||||
|
||||
const run = async (key: string, call: () => Promise<{ data: Overview }>, ok: string | ((d: Overview) => string)) => {
|
||||
setBusy(key);
|
||||
setMsg(null);
|
||||
try {
|
||||
const { data: d } = await call();
|
||||
setData(d);
|
||||
setMsg({ ok: true, text: typeof ok === "function" ? ok(d) : ok });
|
||||
} catch (e) {
|
||||
setMsg({ ok: false, text: errorMessage(e) || "That didn't work." });
|
||||
}
|
||||
setBusy(null);
|
||||
};
|
||||
|
||||
if (!token) return null;
|
||||
if (!data) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
|
||||
const auth = { authToken: token };
|
||||
|
||||
const connect = (p: Product) => run(`c:${p.installId}`, () => apiV2("post", "/linked-products/{installId}/connect", { ...auth, params: { installId: p.installId } }), `Connected to ${p.name}.`);
|
||||
const disconnect = (p: Product) => {
|
||||
if (!window.confirm(`Disconnect ${p.name}? Its events stop showing here, and this site's events stop showing there.`)) return;
|
||||
run(`d:${p.installId}`, () => apiV2("post", "/linked-products/{installId}/disconnect", { ...auth, params: { installId: p.installId } }) as Promise<{ data: Overview & { otherSideTold: boolean; problem: string | null } }>,
|
||||
(d) => {
|
||||
const r = d as Overview & { otherSideTold?: boolean; problem?: string | null };
|
||||
return r.otherSideTold ? `Disconnected from ${p.name}.` : `Disconnected here. ${p.name} couldn't be told (${r.problem || "not reachable"}); disconnect it there too.`;
|
||||
});
|
||||
};
|
||||
const showEvents = (p: Product, on: boolean) => run(`s:${p.installId}`, () => apiV2("put", "/linked-products/{installId}", { ...auth, params: { installId: p.installId }, body: { showEvents: on } }),
|
||||
on ? `${p.name}'s events are fetched and shown on your events pages.` : `${p.name}'s events are no longer shown here.`);
|
||||
const syncNow = (p: Product) => run(`y:${p.installId}`, () => apiV2("post", "/linked-products/{installId}/sync", { ...auth, params: { installId: p.installId } }), "Fetched.");
|
||||
const publish = (on: boolean) => run("publish", () => apiV2("put", "/linked-products/settings", { ...auth, body: { publishEvents: on } }),
|
||||
on ? "Your events are published for your other products." : "Your events are no longer published.");
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="flex items-center gap-2 text-lg font-semibold"><Link2 className="h-5 w-5 text-brand-600" aria-hidden /> Linked products</h2>
|
||||
<p className="mt-1 text-sm text-gray-600">
|
||||
Your church's other Cross Code products, such as the Church Website and Church App. Connect them to show your events there, and theirs here.
|
||||
Registrations and payments always stay in Cross Events.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{msg && <p role="status" className={`text-sm ${msg.ok ? "text-green-700" : "text-red-700"}`}>{msg.text}</p>}
|
||||
|
||||
{!data.hubConnected && (
|
||||
<div className="rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">This site isn't connected to the Hub yet (Settings → Licence), so it doesn't know your other products.</div>
|
||||
)}
|
||||
{data.hubConnected && data.keyMismatch && (
|
||||
<div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
|
||||
The Hub has a different key for this site, so your other products can't check that messages really come from it. This happens after a server is rebuilt: ask your provider to clear the site's key on the Hub.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border p-4">
|
||||
<label className="flex items-start gap-3">
|
||||
<input type="checkbox" className="mt-1" checked={data.publishEvents} disabled={busy === "publish"} onChange={e => publish(e.target.checked)} />
|
||||
<span>
|
||||
<span className="text-sm font-medium">Publish my events</span>
|
||||
<span className="block text-sm text-gray-600">Your public events, as they appear on your events page, for your connected products to show. Never anyone's details.</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{data.hubConnected && data.products.length === 0 && (
|
||||
<div className="rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">
|
||||
Your church has no other Cross Code products yet. When it has (for example the{" "}
|
||||
<a href="https://crosscode.co.za" className="text-brand-700 underline" target="_blank" rel="noopener noreferrer">Church Website</a>), it shows here within 15 minutes.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data.products.length > 0 && (
|
||||
<ul className="space-y-3">
|
||||
{data.products.map(p => (
|
||||
<li key={p.installId} className="rounded-lg border p-4" data-testid={`linked-${p.product}`}>
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<div className="font-medium">{p.name}</div>
|
||||
<a href={p.url} target="_blank" rel="noopener noreferrer" className="text-sm text-brand-700 underline">{p.url.replace(/^https?:\/\//, "")}</a>
|
||||
<div className="mt-1 text-sm text-gray-600">
|
||||
{p.link
|
||||
? <>Connected {when(p.link.connectedAt)}{p.link.connectedBy ? ` by ${p.link.connectedBy}` : ` by ${p.name}`}</>
|
||||
: "Not connected"}
|
||||
{!p.listed && <span className="ml-1 text-amber-800">· no longer listed by the Hub</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{p.link ? (
|
||||
<button type="button" className="rounded-lg border px-3 py-1.5 text-sm hover:bg-gray-50 disabled:opacity-50" disabled={!!busy} onClick={() => disconnect(p)}>Disconnect</button>
|
||||
) : (
|
||||
<button type="button" className="rounded-lg bg-brand-600 px-3 py-1.5 text-sm text-white hover:bg-brand-700 disabled:opacity-50" disabled={!!busy || !p.listed} onClick={() => connect(p)}>
|
||||
{busy === `c:${p.installId}` ? "Connecting…" : "Connect"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{p.link && p.publishesEvents && (
|
||||
<div className="mt-3 border-t pt-3">
|
||||
<label className="flex items-start gap-3">
|
||||
<input type="checkbox" className="mt-1" checked={p.link.showEvents} disabled={!!busy} onChange={e => showEvents(p, e.target.checked)} />
|
||||
<span>
|
||||
<span className="text-sm font-medium">Show events from {p.name}</span>
|
||||
<span className="block text-sm text-gray-600">Its events appear on your events pages, marked as coming from it, with a link to their page there.</span>
|
||||
</span>
|
||||
</label>
|
||||
{p.link.showEvents && (
|
||||
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-gray-600">
|
||||
<span>{p.link.importedEvents} event{p.link.importedEvents === 1 ? "" : "s"} · last synced {ago(p.link.lastGoodAt)}</span>
|
||||
<button type="button" className="inline-flex items-center gap-1 text-brand-700 underline disabled:opacity-50" disabled={!!busy} onClick={() => syncNow(p)}>
|
||||
<RefreshCw className="h-3.5 w-3.5" aria-hidden /> Fetch now
|
||||
</button>
|
||||
{p.link.lastSyncError && <span className="w-full text-amber-800">Last try ({ago(p.link.lastSyncAt)}): {p.link.lastSyncError}. The events from the last good fetch keep showing.</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,12 +3,14 @@
|
||||
import React, { useState } from "react";
|
||||
import { CalendarX } from "lucide-react";
|
||||
import { EventCard } from "@/components/events/EventCard";
|
||||
import { LinkedEventCard } from "@/components/events/LinkedEventCard";
|
||||
import { mergeByStart, type LinkedEvent } from "@/lib/linkedEvents";
|
||||
import { CampusFilter } from "@/components/shared/CampusFilter";
|
||||
import { useCampuses } from "@/hooks/useCampuses";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
|
||||
type GridEvent = React.ComponentProps<typeof EventCard>["event"] & { campusId?: string | null };
|
||||
type GridEvent = React.ComponentProps<typeof EventCard>["event"] & { campusId?: string | null; nextSession?: { startsAt: string } | null };
|
||||
|
||||
// The visitor's campus choice, kept in this browser (like the cookie choice).
|
||||
const STORAGE_KEY = "hope_events_campus";
|
||||
@@ -23,8 +25,10 @@ function store(value: string) {
|
||||
/**
|
||||
* The public events grid with a campus filter (while campuses are on). A campus shows its own
|
||||
* events plus church-wide ones. Starts on the visitor's last choice, else their home campus.
|
||||
* Events from linked products (2.4.0) are mixed in by date; a campus also shows linked events for
|
||||
* no campus or for a campus this site doesn't have.
|
||||
*/
|
||||
export function EventsGrid({ events }: { events: GridEvent[] }) {
|
||||
export function EventsGrid({ events, linked = [] }: { events: GridEvent[]; linked?: LinkedEvent[] }) {
|
||||
const { enabled, campuses } = useCampuses();
|
||||
const { user } = useAuth();
|
||||
const [campus, setCampus] = useState("");
|
||||
@@ -39,20 +43,28 @@ export function EventsGrid({ events }: { events: GridEvent[] }) {
|
||||
|
||||
const choose = (value: string) => { setCampus(value); store(value); };
|
||||
const shown = enabled && campus ? events.filter(e => !e.campusId || e.campusId === campus) : events;
|
||||
const chosenSlug = campuses.find(c => c.id === campus)?.slug;
|
||||
const slugs = new Set(campuses.map(c => c.slug));
|
||||
const shownLinked = enabled && campus
|
||||
? linked.filter(l => !l.event.campus || !slugs.has(l.event.campus.slug) || l.event.campus.slug === chosenSlug)
|
||||
: linked;
|
||||
const items = mergeByStart(shown, shownLinked, e => e.nextSession?.startsAt || e.startDate);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-6">
|
||||
<CampusFilter value={campus} onChange={choose} id="events-campus" />
|
||||
</div>
|
||||
{shown.length === 0 ? (
|
||||
{items.length === 0 ? (
|
||||
<div className="text-center py-16 border rounded-xl bg-gray-50">
|
||||
<CalendarX className="w-8 h-8 text-gray-300 mx-auto mb-2" />
|
||||
<p className="text-gray-500 text-sm">{events.length ? "No events at this campus right now — try another campus." : "No events available right now — check back soon."}</p>
|
||||
<p className="text-gray-500 text-sm">{events.length + linked.length ? "No events at this campus right now — try another campus." : "No events available right now — check back soon."}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
|
||||
{shown.map(event => <EventCard key={event.id} event={event} />)}
|
||||
{items.map(item => item.kind === "own"
|
||||
? <EventCard key={item.event.id} event={item.event} />
|
||||
: <LinkedEventCard key={item.event.key} item={item.event} />)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Calendar, ExternalLink, MapPin } from "lucide-react";
|
||||
import { ApiImage } from "@/components/shared/ApiImage";
|
||||
import { formatDateTimeRange } from "@/lib/date";
|
||||
import { fromLabel, linkedEventPath, type LinkedEvent } from "@/lib/linkedEvents";
|
||||
|
||||
/** The first paragraph of a markdown description as plain text, for a card. */
|
||||
function teaser(e: LinkedEvent["event"]): string {
|
||||
const text = e.summary || (e.description || "").split(/\n\s*\n/)[0] || "";
|
||||
return text.replace(/\\([\\`*_[\]<>|~#+.!()-])/g, "$1").replace(/[*_`]/g, "").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* A card for an event from another of the church's products (Website, App): like EventCard, with
|
||||
* a "From the Church Website" label. Details open its page here; registering happens where it comes from.
|
||||
*/
|
||||
export function LinkedEventCard({ item }: { item: LinkedEvent }) {
|
||||
const e = item.event;
|
||||
const r = e.registration;
|
||||
const place = e.location?.name || e.location?.address || (e.location?.onlineUrl ? "Online" : null);
|
||||
const action = r.mode === "origin" ? "Register" : r.mode === "external" ? "Register" : null;
|
||||
|
||||
return (
|
||||
<div className="relative border rounded-xl overflow-hidden shadow-sm hover:shadow-md hover:border-brand-200 transition" data-testid="linked-event-card">
|
||||
<a href={linkedEventPath(item)} className="block">
|
||||
{e.imageUrl ? (
|
||||
<ApiImage src={e.imageUrl} alt={e.title} className="h-48 w-full object-cover" />
|
||||
) : (
|
||||
<div className="h-48 w-full bg-brand-50 flex items-center justify-center">
|
||||
<Calendar className="w-10 h-10 text-brand-200" />
|
||||
</div>
|
||||
)}
|
||||
<div className="p-4">
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-brand-700">{fromLabel(item)}</p>
|
||||
<h3 className="text-lg font-semibold hover:underline">{e.title}</h3>
|
||||
{e.campus && <p className="text-xs text-gray-500 mt-0.5">{e.campus.name}</p>}
|
||||
<p className="text-sm text-gray-500 flex items-center gap-1.5 mt-1">
|
||||
<Calendar className="w-3.5 h-3.5 shrink-0" />
|
||||
{formatDateTimeRange(e.startsAt, e.endsAt)}
|
||||
</p>
|
||||
{place && (
|
||||
<p className="text-sm text-gray-500 flex items-center gap-1.5 mt-1">
|
||||
<MapPin className="w-3.5 h-3.5 shrink-0" />
|
||||
<span className="truncate">{place}</span>
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-gray-600 mt-2 line-clamp-2">{teaser(e)}</p>
|
||||
</div>
|
||||
</a>
|
||||
<div className="px-4 pb-4 flex gap-2">
|
||||
<a href={linkedEventPath(item)} className="flex-1 text-center text-sm text-gray-700 border rounded-lg py-2 hover:bg-gray-50 transition-colors">
|
||||
View details
|
||||
</a>
|
||||
{action && r.url && (
|
||||
<a href={r.url} rel="noopener" className="flex-1 inline-flex items-center justify-center gap-1 text-center text-sm text-white bg-brand-600 rounded-lg py-2 hover:bg-brand-700 transition-colors">
|
||||
{action} <ExternalLink className="w-3.5 h-3.5" aria-hidden />
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from "react";
|
||||
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, LayoutDashboard, Timer, Play, CreditCard, ArrowUpDown, KeyRound, ArrowUpCircle, MapPinned, Archive, Users, BellOff, Megaphone, Webhook, Send, BookOpen } from "lucide-react";
|
||||
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, LayoutDashboard, Timer, Play, CreditCard, ArrowUpDown, KeyRound, ArrowUpCircle, MapPinned, Archive, Users, BellOff, Megaphone, Webhook, Send, BookOpen, Link2 } from "lucide-react";
|
||||
import { GuideItem } from "@/components/shared/GuideItem";
|
||||
import type { HelpContent } from "./types";
|
||||
|
||||
@@ -174,6 +174,27 @@ export const siteSettingsHelpContent: HelpContent = {
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "linked",
|
||||
label: "Linked products",
|
||||
icon: Link2,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<p>Your church's other Cross Code products, such as the Church Website and the Church App. The Hub lists them here by itself (within 15 minutes of a new one being set up).</p>
|
||||
<div className="space-y-4">
|
||||
<GuideItem icon={Link2} title="Connect" tone="brand">
|
||||
"Connect" sets up a secure link with that product, so your events can show there and theirs here. Either side can connect or disconnect; the other side shows who did it.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Megaphone} title="Publish my events" tone="green">
|
||||
On by default: your connected products can show your public events, as they appear on your events page, with a link back here to register. Hidden events, people's details and children's details are never shared. Registrations and payments always stay in Cross Events.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Send} title="Show events from a product" tone="gray">
|
||||
Tick it to show that product's events on your events pages, marked as coming from it. They're fetched every 15 minutes (straight away when they change), and can only be changed where they come from. If that product can't be reached, its last events keep showing and this tab says when it last synced.
|
||||
</GuideItem>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "jobs",
|
||||
label: "Background jobs",
|
||||
|
||||
@@ -62,7 +62,7 @@ export const COMMAND_PAGES: CommandPage[] = [
|
||||
// Settings
|
||||
...([
|
||||
["organisation", "Organisation"], ["campuses", "Campuses"], ["branding", "Branding"], ["notifications", "Notifications"],
|
||||
["email", "Email"], ["legal", "Legal"], ["whatsapp", "WhatsApp"], ["payments", "Payments"], ["webhooks", "Webhooks"],
|
||||
["email", "Email"], ["legal", "Legal"], ["whatsapp", "WhatsApp"], ["payments", "Payments"], ["webhooks", "Webhooks"], ["linked", "Linked products"],
|
||||
["backups", "Backups"], ["jobs", "Background jobs"], ["licence", "Licence & updates"], ["ai", "AI helpers"],
|
||||
] as const).map(([tab, label]): CommandPage => ({ group: "Settings", label: `Settings: ${label}`, href: `/dashboard/admin/settings?tab=${tab}`, roles: ADM, keywords: "site settings" })),
|
||||
// Reports — every report in the catalogue
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
// schema.org Event data for an event page, so Google can show the event with its date,
|
||||
// venue and ticket link (event rich results / "events near me").
|
||||
// Checked with https://search.google.com/test/rich-results
|
||||
|
||||
type SchemaOption = {
|
||||
price: number;
|
||||
stockLimit?: number;
|
||||
availableCount?: number;
|
||||
earlyBirdTiers?: { deadline: string; price: number }[];
|
||||
variants?: { price: number | null; stockLimit?: number; availableCount?: number }[];
|
||||
};
|
||||
|
||||
export type SchemaEvent = {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
goLiveAt?: string;
|
||||
picture?: string;
|
||||
location?: string | null;
|
||||
requiresRegistration?: boolean;
|
||||
eventOptions?: SchemaOption[];
|
||||
};
|
||||
|
||||
/** Today's price of each ticket (early-bird when one is open, else the variant/base price). */
|
||||
function currentPrices(options: SchemaOption[], now: Date): number[] {
|
||||
const prices: number[] = [];
|
||||
for (const o of options) {
|
||||
if (o.variants && o.variants.length > 0) {
|
||||
for (const v of o.variants) prices.push(v.price ?? o.price);
|
||||
continue;
|
||||
}
|
||||
const open = (o.earlyBirdTiers || []).filter((t) => now < new Date(t.deadline)).map((t) => t.price);
|
||||
prices.push(open.length > 0 ? Math.min(...open) : o.price);
|
||||
}
|
||||
return prices.filter((p) => Number.isFinite(p));
|
||||
}
|
||||
|
||||
export function eventJsonLd(
|
||||
event: SchemaEvent,
|
||||
{ pageUrl, imageUrl, organizerName, siteUrl }: { pageUrl: string; imageUrl: string | null; organizerName: string; siteUrl: string },
|
||||
) {
|
||||
const now = new Date();
|
||||
const options = event.eventOptions || [];
|
||||
const limited = options.filter((o) => (o.stockLimit ?? 0) > 0);
|
||||
const soldOut = limited.length > 0 && limited.every((o) => o.availableCount !== undefined && o.availableCount <= 0);
|
||||
|
||||
// Contact-only events (requiresRegistration false) have no tickets to offer.
|
||||
let offers: Record<string, unknown> | undefined;
|
||||
if (event.requiresRegistration !== false) {
|
||||
const prices = options.length > 0 ? currentPrices(options, now) : [0];
|
||||
const low = Math.min(...prices);
|
||||
const high = Math.max(...prices);
|
||||
offers = {
|
||||
"@type": low === high ? "Offer" : "AggregateOffer",
|
||||
...(low === high ? { price: low.toFixed(2) } : { lowPrice: low.toFixed(2), highPrice: high.toFixed(2) }),
|
||||
priceCurrency: "ZAR",
|
||||
availability: soldOut ? "https://schema.org/SoldOut" : "https://schema.org/InStock",
|
||||
url: `${siteUrl}/register/${event.id}`,
|
||||
...(event.goLiveAt ? { validFrom: new Date(event.goLiveAt).toISOString() } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Event",
|
||||
name: event.title,
|
||||
...(event.description ? { description: event.description.slice(0, 5000) } : {}),
|
||||
startDate: new Date(event.startDate).toISOString(),
|
||||
endDate: new Date(event.endDate).toISOString(),
|
||||
eventStatus: "https://schema.org/EventScheduled",
|
||||
eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
|
||||
...(event.location ? { location: { "@type": "Place", name: event.location, address: event.location } } : {}),
|
||||
...(imageUrl ? { image: [imageUrl] } : {}),
|
||||
url: pageUrl,
|
||||
organizer: { "@type": "Organization", name: organizerName, url: siteUrl },
|
||||
...(offers ? { offers } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** JSON for a <script type="application/ld+json">, safe against "</script>" in event text. */
|
||||
export function jsonLdString(data: unknown): string {
|
||||
return JSON.stringify(data).replace(/</g, "\\u003c");
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { CrosscodeEvent } from "@crosscode/contracts";
|
||||
import { apiFetchListForPrerender } from "@/lib/api";
|
||||
|
||||
/**
|
||||
* Events from the church's other products (2.4.0, Settings → Linked products → Show events from):
|
||||
* read-only copies as `crosscode.event/1`, each with its own page here (/events/linked/…) that
|
||||
* points search engines and visitors to the product it comes from.
|
||||
*/
|
||||
export type LinkedEvent = {
|
||||
key: string;
|
||||
product: "website" | "app";
|
||||
productName: string;
|
||||
event: CrosscodeEvent;
|
||||
};
|
||||
|
||||
/** Upcoming linked events for a public page. Never fails the page: no events if the API can't answer. */
|
||||
export async function fetchLinkedEvents(campus?: string): Promise<LinkedEvent[]> {
|
||||
const query = campus ? `?campus=${encodeURIComponent(campus)}` : "";
|
||||
try {
|
||||
return await apiFetchListForPrerender<LinkedEvent>(`/api/v2/linked-events${query}`, { nextOptions: { next: { revalidate: 60 } } });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** This site's page for a linked event. */
|
||||
export const linkedEventPath = (e: LinkedEvent) => `/events/linked/${e.product}/${e.event.id}`;
|
||||
|
||||
/** "From the Church Website". */
|
||||
export const fromLabel = (e: LinkedEvent) => `From the ${e.productName}`;
|
||||
|
||||
/** Our events and linked ones in one list by start time. `startOf` gives our events' start. */
|
||||
export function mergeByStart<T>(ours: T[], linked: LinkedEvent[], startOf: (e: T) => string): ({ kind: "own"; event: T } | { kind: "linked"; event: LinkedEvent })[] {
|
||||
const all = [
|
||||
...ours.map((event) => ({ kind: "own" as const, event, at: new Date(startOf(event)).getTime() })),
|
||||
...linked.map((event) => ({ kind: "linked" as const, event, at: new Date(event.event.startsAt).getTime() })),
|
||||
];
|
||||
return all.sort((a, b) => a.at - b.at).map((x) => (x.kind === "own" ? { kind: "own" as const, event: x.event } : { kind: "linked" as const, event: x.event }));
|
||||
}
|
||||
+40
-3
@@ -1,7 +1,10 @@
|
||||
# Cross Events 2.4.0 — protocol v2, Linked products, the event feed and `packages/seo`
|
||||
|
||||
Phase **2** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§4, §5 "Sibling discovery", §9, §11; decisions
|
||||
5, 20). Written 2026-11-18. **Not started.**
|
||||
5, 20). Written 2026-11-18. **Built 2026-11-18** on branches (contracts 1.4.0 and Events 2.4.0 on
|
||||
`feat/events-2.4` here, Hub 2.2.0 on `feat/link-public-key`, crosscode-site on
|
||||
`feat/linked-products`); not tagged yet. The decisions below were taken as proposed. Where the
|
||||
build differs from this plan, see [Changes while building](#changes-while-building).
|
||||
|
||||
**What 2.4.0 is:** Cross Events becomes a full member of a church stack. It reports to the Hub as
|
||||
`product: "events"` (protocol v2), shows the church's other products under **Settings → Linked
|
||||
@@ -35,8 +38,9 @@ sample feeds (§8). It's ready for the Website (phase 4) without another Events
|
||||
8. [What changes in each repo](#7-what-changes-in-each-repo)
|
||||
9. [Testing](#8-testing)
|
||||
10. [Releasing and rolling it out](#9-releasing-and-rolling-it-out)
|
||||
11. [Decisions](#decisions)
|
||||
12. [Still open](#still-open)
|
||||
11. [Changes while building](#changes-while-building)
|
||||
12. [Decisions](#decisions)
|
||||
13. [Still open](#still-open)
|
||||
|
||||
---
|
||||
|
||||
@@ -365,6 +369,39 @@ Order, each with its CHANGELOG entry and `npm run check` first:
|
||||
4. crosscode-site `v1.4.0`, deployed.
|
||||
5. Each church updated through the Hub (a scheduled update, ROLLOUT-1.0 §5).
|
||||
|
||||
## Changes while building
|
||||
|
||||
1. **A different public key never fails the heartbeat** (§1 said `409 PUBLIC_KEY_MISMATCH`): the
|
||||
heartbeat also refreshes the licence, so failing it could lock a church out after 30 days. The
|
||||
Hub keeps the saved key, answers `publicKeyStatus: "mismatch"` and opens an alert on the
|
||||
install; the site keeps sending its key until it gets `saved` or `matches`, so it's saved
|
||||
right after Joshua clears the old one. Events shows the mismatch on Linked products.
|
||||
2. **Update requests and AI calls stay on protocol 1** (every Hub accepts them); only register and
|
||||
heartbeat move to v2. A Hub that refuses a v2 body (`UNSUPPORTED_PROTOCOL` or
|
||||
`INVALID_REQUEST`) gets the same heartbeat again as v1, and v1 is used for a day. The v2
|
||||
health fills in what v1 could leave empty (`jobs`, `pendingMigrations`), and the body is
|
||||
checked against the contract before it's sent.
|
||||
3. **`event.changed` is tried once more after a minute, then left to the 15-minute poll** (§3
|
||||
said the webhooks' 1 min … 12 h schedule): retrying longer than the poll interval adds nothing.
|
||||
4. **The feed is also refreshed before it's served** when the last refresh is over a minute old,
|
||||
so it's right even with the jobs switched off (e2e, `FEED_JOBS_ENABLED=false`).
|
||||
5. **Imported events must come from that link's install** (`origin.installId` and `product`),
|
||||
so one product can't publish events as another. Others are skipped and counted.
|
||||
6. **JSON-LD**: `organizer` stays an `Organization` (the snapshot rule allowed only additions);
|
||||
`Church` JSON-LD is in `@crosscode/seo` for the Website. The price range is now from main
|
||||
tickets only (before, an add-on such as a T-shirt could set the lowest price). The description
|
||||
goes in as plain text, not the feed's markdown-escaped copy.
|
||||
7. **The deploy builds the shared packages**: `scripts/products/events.sh` installs and builds
|
||||
`packages/contracts` and `packages/seo` before Events when the checkout's Events uses them
|
||||
(an older tag still builds as before; `scripts/tests/events.bats`).
|
||||
8. **`FEED_JOBS_ENABLED`** (optional, default `true`) switches the `feed` and `feed-sync` jobs,
|
||||
like the other job flags (in `.env.example` and SETTINGS.md, not the env templates).
|
||||
9. The readiness check is on the existing readiness page; contracts 1.4.0 also adds
|
||||
`FEED_PATHS` and `typesVersions` (so `@crosscode/contracts/signing` has types under the
|
||||
Events backend's `moduleResolution: node`).
|
||||
10. **Not run yet:** the e2e spec (`e2e/linked-products.spec.ts`, needs the e2e Postgres) and the
|
||||
VM test (§8): this machine has neither Postgres nor WSL. Both before tagging.
|
||||
|
||||
## Decisions
|
||||
|
||||
Proposed in this plan, to confirm before building:
|
||||
|
||||
+4
-5
@@ -28,7 +28,7 @@ for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)).
|
||||
| 1b | Cross Events 2.2.0: moved here as `apps/events`, the `crosscode` script | **Released** 2026-11-17 (`events@2.2.0`, with AI use in tokens and the backend under `/api`). **VM tested 2026-11-17** (EVENTS-2.2-PLAN §6, all passing after fixes). **Not rolled out:** servers still run `hope-events` `v2.1.1` until each install is adopted |
|
||||
| 1c | Cross Events 2.3.x: authenticator app 2FA (TOTP + recovery codes) | **Released** 2026-11-17 (`events@2.3.0`). **`events@2.3.1`** 2026-11-18: Next.js 16.4.6 (security advisories for 16.2.0–16.4.4), so roll out 2.3.1, not 2.3.0. crosscode-site `v1.3.0` lists it (merged and tagged, **not deployed**) |
|
||||
| 1d | Agent 1.0.x + Hub 2.1.x (+ contracts 1.3.0) | **Released** 2026-11-17 (`agent@1.0.0`, `contracts@1.3.0`, Hub `v2.1.0`). **VM tested** end to end (AGENT-1.0-PLAN §13: joins, installs behind frp, scheduled / batch / missed updates, uninstall with export and purge, forged and replayed jobs). 2026-11-18: **`agent@1.0.1`** (the agent answers status on the central server itself) and Hub **`v2.1.1`** (adopt passes the church's address; Link takes the short name as a name). **Not rolled out**: use agent 1.0.1 and Hub 2.1.1 |
|
||||
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Planned** 2026-11-18: [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md), with six decisions to confirm before building. Events keeps speaking protocol 1 until then |
|
||||
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Built** 2026-11-18 ([EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md), decisions taken as proposed, "Changes while building" there): `feat/events-2.4` here, `feat/link-public-key` in events-hub, `feat/linked-products` in crosscode-site. Unit tests pass. **Not tagged:** the e2e spec and the VM test haven't run (no Postgres on the dev machine) |
|
||||
| 3–7 | Accounts 1.0.0 → Website 1.0.0 → Events 3.0.0 → App 1.0.0 → App 1.x | Not started |
|
||||
|
||||
## Next up
|
||||
@@ -40,10 +40,9 @@ for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)).
|
||||
onto the monorepo) → a throwaway New install to prove FASTPANEL, DNS and Let's Encrypt.
|
||||
2. **Deploy crosscode-site `v1.3.0`** (secure sign-in in the features and the brochure).
|
||||
3. **Archive `hope-events`** once every install reports 2.2.0 or later (EVENTS-2.2-PLAN §7).
|
||||
4. **Cross Events 2.4.0** (phase 2): confirm the decisions in
|
||||
[EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md), then build it in its order (contracts 1.4.0 →
|
||||
Hub 2.2.0 → Events 2.4.0 → crosscode-site 1.4.0). It can be built during the rollout; releasing
|
||||
it needs Hub 2.2.0 deployed.
|
||||
4. **Cross Events 2.4.0** (phase 2) is built on branches: run `npm run test:e2e` in `apps/events`
|
||||
(with the e2e Postgres) and the VM test in EVENTS-2.4-PLAN §8, then merge and release in its
|
||||
order (contracts 1.4.0 → Hub 2.2.0, deployed → Events 2.4.0 → crosscode-site 1.4.0).
|
||||
|
||||
## The VM test (2026-11-17)
|
||||
|
||||
|
||||
+1
-1
@@ -616,7 +616,7 @@ Planned in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). In short:
|
||||
| 1b | **Cross Events 2.2.0** | **Moves into the monorepo** as `apps/events`, with its git history (merged in, not copied); its packages become workspaces; the **`crosscode` script** (`deploy`, `status`, `install`, `adopt`; §8) replaces `scripts/deploy.sh` and `scripts/install.sh`; every install moved with `crosscode adopt`; `hope-events` archived. Planned with no feature changes; two small ones were added on 2026-11-17 (decided by Joshua): **AI use shown in tokens**, never rand, outside the Hub (needs Hub 2.0.1), and **everything the backend serves under `/api`**, so a site and its API share one address and one proxy rule. **Tagged 2026-11-17, before the VM testing; VM tested the same day** | Before more products, so every product is released and deployed the same way from the start |
|
||||
| 1c | **Cross Events 2.3.0** | **Authenticator app 2FA** (TOTP) next to email and WhatsApp, with recovery codes; admins can see which method each staff account uses. **Released 2026-11-17** (`events@2.3.0`) | Independent and useful now; the Accounts migration later carries it over |
|
||||
| 1d | **Agent 1.0.0 + Hub 2.1.0** (contracts 1.3.0) | **Server agent** on every server (polls only, signed jobs, runs the `crosscode` script); Hub: Servers page with stats and alerts, server configuration, frp port list, New install with a choice of server, scheduled / emergency / batch updates with notice to the church, uninstall with an encrypted JSON export, emailed reports. [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). **Released 2026-11-17** after the VM test; rollout in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md) | Right after 1b (it runs the `crosscode` script), so every new church from then on is installed from the Hub. Can run alongside 1c |
|
||||
| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events. **Planned 2026-11-18:** [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md) (also needs contracts 1.4.0 and Hub 2.2.0, for a public key in the v2 heartbeat) | Small; ready for when the Website exists |
|
||||
| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events. **Planned and built 2026-11-18:** [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md) (also needs contracts 1.4.0 and Hub 2.2.0, for a public key in the v2 heartbeat); not tagged yet | Small; ready for when the Website exists |
|
||||
| 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script | The Website is built on it from day one |
|
||||
| 4 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats | More churches need a website than an app; it also covers the "website only" case |
|
||||
| 5 | **Cross Events 3.0.0** | Sign-in moves to Accounts; user migration keeping password hashes; migration guide | Breaking change, so a major version, after Accounts is proven on the Website |
|
||||
|
||||
+21
-3
@@ -332,6 +332,24 @@ what's needed) until the church's install of that product runs that version or l
|
||||
**AI.** The monthly cap and markup are the church's, shared by all its installs: a call from any of
|
||||
them counts what all of them used this month.
|
||||
|
||||
**Moving an install to v2** (e.g. Cross Events 2.4.0): register again with `protocolVersion: 2`,
|
||||
the product and a public key (same licence and address: same install id, new secret), then send v2
|
||||
heartbeats. Nothing on the Hub needs changing.
|
||||
**Moving an install to v2** (e.g. Cross Events 2.4.0, Hub 2.2.0+): an install that registered with
|
||||
v1 just starts sending v2 heartbeats, with its Ed25519 public key (PEM) in `publicKey`. It doesn't
|
||||
need its licence key again (Cross Events never stored it). The heartbeat is already signed with the
|
||||
install secret, so the Hub knows whose key it is. The reply says what happened in
|
||||
`publicKeyStatus`:
|
||||
|
||||
| `publicKeyStatus` | Meaning |
|
||||
|-------------------|---------|
|
||||
| `saved` | The Hub had no key for the install and saved this one; the church's other installs list it from their next heartbeat |
|
||||
| `matches` | The Hub already has this key (line endings and surrounding whitespace don't count) |
|
||||
| `mismatch` | The Hub has a **different** key and keeps it: an alert opens on the install, and Joshua can **Clear public key** on its page (two-factor again) when the server was restored or rebuilt; the next heartbeat then saves the new key |
|
||||
|
||||
A key problem never fails the heartbeat: the licence keeps refreshing whatever happens to the key.
|
||||
An install keeps sending `publicKey` until it gets `saved` or `matches`. A Hub before 2.2.0 ignores
|
||||
the field (no `publicKeyStatus`), so the install isn't listed to its siblings until the Hub is
|
||||
updated. Registering again with `protocolVersion: 2`, the product and a public key (same licence
|
||||
and address: same install id, new secret) also works, as before.
|
||||
|
||||
**Connecting two installs** (Settings → Linked products → Connect) is between the installs, not
|
||||
through the Hub: `crosscode.link/1` in `@crosscode/contracts` (`src/link.ts`), with each side
|
||||
checking the other against the `linkedProducts` it has cached from the Hub.
|
||||
|
||||
Generated
+1
@@ -90,6 +90,7 @@
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@crosscode/seo": "*",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
|
||||
@@ -31,10 +31,27 @@ events_backup() {
|
||||
.catch(e => { console.error(" Backup failed: " + e.message); process.exit(1); });'
|
||||
}
|
||||
|
||||
# Only this app's workspaces, never the other products'. --include=dev: the TypeScript and Next
|
||||
# builds need type and build packages even where NODE_ENV=production.
|
||||
# The shared packages this checkout's Events uses (from 2.4.0: contracts and seo), built before it.
|
||||
# Only the ones in the checkout, so going back to an older tag still installs and builds.
|
||||
events_shared_packages() {
|
||||
local p
|
||||
for p in packages/contracts packages/seo; do
|
||||
if [ -f "$1/$p/package.json" ] && grep -q "\"@crosscode/${p#packages/}\"" "$1/apps/events/backend/package.json" "$1/apps/events/frontend/package.json" 2>/dev/null; then
|
||||
printf '%s\n' "$p"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Only this app's workspaces (and the shared packages it uses), never the other products'.
|
||||
# --include=dev: the TypeScript and Next builds need type and build packages even where
|
||||
# NODE_ENV=production; --include-workspace-root for the packages' build tool (tsup).
|
||||
events_install_deps() {
|
||||
run_as "$2" "$1" npm ci --include=dev --no-audit --no-fund -w apps/events/backend -w apps/events/frontend
|
||||
local -a shared=() ws=()
|
||||
local p
|
||||
mapfile -t shared < <(events_shared_packages "$1")
|
||||
for p in "${shared[@]}"; do ws+=(-w "$p"); done
|
||||
if [ "${#shared[@]}" -gt 0 ]; then ws+=(--include-workspace-root); fi
|
||||
run_as "$2" "$1" npm ci --include=dev --no-audit --no-fund "${ws[@]}" -w apps/events/backend -w apps/events/frontend
|
||||
}
|
||||
|
||||
events_migrate() {
|
||||
@@ -47,6 +64,10 @@ events_pending_migrations() {
|
||||
}
|
||||
|
||||
events_build() {
|
||||
local p
|
||||
while IFS= read -r p; do
|
||||
run_as "$2" "$1/$p" npm run build || return 1
|
||||
done < <(events_shared_packages "$1")
|
||||
run_as "$2" "$(events_app "$1")/backend" npm run build &&
|
||||
run_as "$2" "$(events_app "$1")/frontend" npm run build
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env bats
|
||||
# Cross Events' hooks that don't need a server: which shared packages a checkout builds first
|
||||
# (contracts and seo from 2.4.0), and that an older checkout (2.3.x) builds without them.
|
||||
# Run with `npm run test:scripts`.
|
||||
|
||||
setup() {
|
||||
# shellcheck source=../products/events.sh
|
||||
source "$BATS_TEST_DIRNAME/../products/events.sh"
|
||||
TMP="$BATS_TEST_TMPDIR"
|
||||
CALLS="$TMP/calls"
|
||||
: > "$CALLS"
|
||||
# Record what would run, as the app user, instead of running it.
|
||||
run_as() { local user="$1" dir="$2"; shift 2; echo "$user|${dir#"$TMP"/}|$*" >> "$CALLS"; }
|
||||
}
|
||||
|
||||
checkout() {
|
||||
local dir="$TMP/$1"; shift
|
||||
mkdir -p "$dir/apps/events/backend" "$dir/apps/events/frontend" "$dir/packages/contracts" "$dir/packages/seo"
|
||||
echo '{"name":"@crosscode/contracts"}' > "$dir/packages/contracts/package.json"
|
||||
echo '{"name":"@crosscode/seo"}' > "$dir/packages/seo/package.json"
|
||||
printf '{"dependencies":{%s}}' "$1" > "$dir/apps/events/backend/package.json"
|
||||
printf '{"dependencies":{%s}}' "$2" > "$dir/apps/events/frontend/package.json"
|
||||
}
|
||||
|
||||
@test "2.4.0: contracts and seo are installed and built before Events" {
|
||||
checkout new '"@crosscode/contracts":"*"' '"@crosscode/contracts":"*","@crosscode/seo":"*"'
|
||||
run events_shared_packages "$TMP/new"
|
||||
[ "$output" = $'packages/contracts\npackages/seo' ]
|
||||
|
||||
events_install_deps "$TMP/new" hope
|
||||
grep -qx 'hope|new|npm ci --include=dev --no-audit --no-fund -w packages/contracts -w packages/seo --include-workspace-root -w apps/events/backend -w apps/events/frontend' "$CALLS"
|
||||
|
||||
: > "$CALLS"
|
||||
events_build "$TMP/new" hope
|
||||
[ "$(cut -d'|' -f2 "$CALLS" | tr '\n' ' ')" = "new/packages/contracts new/packages/seo new/apps/events/backend new/apps/events/frontend " ]
|
||||
}
|
||||
|
||||
@test "2.3.x (no shared packages used): installed and built as before" {
|
||||
checkout old '' ''
|
||||
run events_shared_packages "$TMP/old"
|
||||
[ -z "$output" ]
|
||||
events_install_deps "$TMP/old" hope
|
||||
grep -qx 'hope|old|npm ci --include=dev --no-audit --no-fund -w apps/events/backend -w apps/events/frontend' "$CALLS"
|
||||
: > "$CALLS"
|
||||
events_build "$TMP/old" hope
|
||||
[ "$(cut -d'|' -f2 "$CALLS" | tr '\n' ' ')" = "old/apps/events/backend old/apps/events/frontend " ]
|
||||
}
|
||||
|
||||
@test "a failing package build stops before Events is built" {
|
||||
checkout new '"@crosscode/contracts":"*"' ''
|
||||
run_as() { echo "${2#"$TMP"/}" >> "$CALLS"; [[ "$2" != */packages/contracts ]]; }
|
||||
run events_build "$TMP/new" hope
|
||||
[ "$status" -ne 0 ]
|
||||
[ "$(cat "$CALLS")" = "new/packages/contracts" ]
|
||||
}
|
||||
Reference in New Issue
Block a user