Events 2.4.0 backend: protocol v2, Linked products, the event feed

- Hub client: register and heartbeat on protocol v2 with the site's
  Ed25519 key (sent on the heartbeat until the Hub has it); falls back to
  v1 for a day if the Hub refuses v2, so the licence always refreshes.
- crosscode.link/1 Connect / Disconnect, both directions, trusted through
  the Hub's cached linkedProducts (ProductLink, LinkNonce).
- GET /api/feed/v1/events from FeedEntry (go-live, closing and selling
  out are changes; deactivated events go in deleted), event.changed to
  connected products, and showing their events (ImportedEvent).
- /api/v2/linked-products, /api/v2/linked-events; /events/:id/full gains
  crosscodeEvent and priceRangeCents for the JSON-LD.
- Contracts: FEED_PATHS, typesVersions for @crosscode/contracts/signing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 12:24:29 +02:00
co-authored by Claude Opus 5.5
parent 390b80e56e
commit 8a930d07c6
30 changed files with 5874 additions and 17 deletions
+244
View File
@@ -0,0 +1,244 @@
/**
* An event as `crosscode.event/1` (docs/EVENTS-2.4-PLAN.md §3): what the feed publishes and what
* the event page's JSON-LD is built from (@crosscode/seo).
*
* `buildCrosscodeEvent` is pure (the event, what's left of each ticket and the site's details in,
* the payload out) so it can be tested without a database; `loadForFeed` reads what it needs.
*
* Never in here: the event's contact person, kids check-in and volunteer tickets, staff prices,
* the attendee form. Only what the public event page already shows.
*/
import type { CrosscodeEvent } from '@crosscode/contracts';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS utils */
const sessionsUtil = require('../utils/sessions') as {
activeSessions<S extends { cancelledAt?: Date | string | null; startsAt: Date | string }>(sessions: S[]): S[];
registrationClosesAt(event: object, sessions: object[]): Date;
isPickOption(event: object, option: object): boolean;
};
const { publicOptions } = require('../utils/volunteers') as { publicOptions<O>(event: object): O[] };
const { getEffectiveUnitPrice } = require('../utils/pricing') as { getEffectiveUnitPrice(option: object, ref: Date | null, at: Date): number };
/* eslint-enable @typescript-eslint/no-require-imports */
export type FeedContext = {
/** This install's Hub id (origin.installId). */
installId: string;
/** The site's address, without a trailing slash. */
baseUrl: string;
timezone: string;
/** Campuses switched on (otherwise every event is for the whole church). */
campusesOn: boolean;
now: Date;
};
export type FeedOption = {
id: string;
price: number;
isMainTicket: boolean;
stockLimit: number;
sessionMode?: string;
earlyBirdTiers?: { deadline: Date | string; price: number; order?: number | null }[];
variants?: { price: number | null }[];
};
export type FeedEventRow = {
id: string;
title: string;
description: string | null;
startDate: Date;
endDate: Date;
goLiveAt: Date | null;
registrationDeadline: Date | null;
picture: string | null;
location: string | null;
requiresRegistration: boolean;
waitlistEnabled: boolean;
scheduleType: string;
attendanceMode: string;
lateJoinEnabled: boolean;
lateJoinUntilSessionId: string | null;
kidsOptionId?: string | null;
volunteerOptionId?: string | null;
campus: { slug: string; name: string } | null;
series: { id: string; name: string } | null;
sessions: { id: string; label: string | null; startsAt: Date; endsAt: Date; location: string | null; cancelledAt: Date | null }[];
eventOptions: FeedOption[];
};
/** Places left per option (`null` = no limit). Missing options count as unlimited. */
export type Availability = Map<string, number | null>;
export type BuiltEvent = {
event: CrosscodeEvent;
/** The event's own lowest and highest current prices, for its JSON-LD (`null` when free). */
priceRangeCents: { lowCents: number; highCents: number } | null;
};
const cut = (s: string | null | undefined, max: number): string | null => {
const t = String(s ?? '').trim();
return t ? (t.length > max ? `${t.slice(0, max - 1)}…` : t) : null;
};
/** "/uploads/…" (as stored) → an absolute address on the site, served under /api (2.2.0). */
export function absolute(baseUrl: string, raw: string | null | undefined): string | null {
const v = String(raw ?? '').trim();
if (!v) return null;
if (/^https?:\/\//i.test(v)) return v;
const path = v.startsWith('/') ? v : `/${v}`;
return `${baseUrl}${/^\/uploads\//.test(path) ? `/api${path}` : path}`;
}
/**
* Plain text as markdown that reads the same: markdown characters escaped, line breaks kept
* (Events descriptions are plain text shown with their line breaks).
*/
export function plainToMarkdown(text: string | null | undefined): string | null {
const t = String(text ?? '').replace(/\r\n?/g, '\n').trim();
if (!t) return null;
const lines = t.split('\n').map((line) => line
.replace(/[\\`*_[\]<>|~]/g, (c) => `\\${c}`)
// A line that would start a heading, a list, a quote or a numbered list.
.replace(/^(\s*)([#>+-])/, '$1\\$2')
.replace(/^(\s*\d+)([.)])(\s)/, '$1\\$2$3'));
// A hard break between lines of the same paragraph (two spaces), blank lines stay paragraphs.
return lines.map((l, i) => (i < lines.length - 1 && l.trim() && lines[i + 1]!.trim() ? `${l} ` : l)).join('\n').slice(0, 20000);
}
/** Today's price of each ticket (early-bird when one is open, else each variant's or the base price), in rand. */
function currentPrices(options: FeedOption[], 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;
}
prices.push(getEffectiveUnitPrice(o, null, now));
}
return prices.filter((p) => Number.isFinite(p) && p >= 0);
}
function registration(row: FeedEventRow, options: FeedOption[], available: Availability, ctx: FeedContext, pageUrl: string): CrosscodeEvent['registration'] {
const closes = sessionsUtil.registrationClosesAt(row, row.sessions);
const closesAt = closes && Number.isFinite(closes.getTime()) ? closes.toISOString() : null;
if (!row.requiresRegistration) {
// Contact-only events: no tickets; the description says how to take part.
return { mode: 'contact', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null };
}
const main = options.filter((o) => o.isMainTicket);
const priced = main.length > 0 ? main : options;
const prices = currentPrices(priced, ctx.now).map((p) => Math.round(p * 100));
const low = prices.length > 0 ? Math.min(...prices) : 0;
let status: CrosscodeEvent['registration']['status'] = 'open';
if (row.goLiveAt && ctx.now < row.goLiveAt) status = 'not_open';
else if (closesAt && ctx.now >= new Date(closesAt)) status = 'closed';
else if (main.length > 0 && main.every((o) => o.stockLimit > 0 && (available.get(o.id) ?? 1) <= 0)) status = row.waitlistEnabled ? 'waitlist' : 'full';
return {
mode: 'origin',
url: pageUrl,
status,
opensAt: row.goLiveAt && ctx.now < row.goLiveAt ? row.goLiveAt.toISOString() : null,
closesAt,
priceFrom: low > 0 ? { amountCents: low, currency: 'ZAR' } : null,
};
}
export function buildCrosscodeEvent(row: FeedEventRow, available: Availability, ctx: FeedContext): BuiltEvent {
const pageUrl = `${ctx.baseUrl}/events/${row.id}`;
const options = publicOptions<FeedOption>(row);
const live = sessionsUtil.activeSessions(row.sessions);
const multi = row.scheduleType === 'sessions' && row.sessions.length > 0;
// startsAt / endsAt are the first start and last end of the sessions that still run.
const startsAt = multi && live.length > 0 ? live[0]!.startsAt : row.startDate;
const endsAt = multi && live.length > 0 ? live.reduce((m, s) => (s.endsAt > m ? s.endsAt : m), live[0]!.endsAt) : row.endDate;
const place = cut(row.location, 200);
const online = place && /^https?:\/\//i.test(place) ? place : null;
const reg = registration(row, options, available, ctx, pageUrl);
const priced = options.filter((o) => o.isMainTicket).length > 0 ? options.filter((o) => o.isMainTicket) : options;
const prices = currentPrices(priced, ctx.now).map((p) => Math.round(p * 100));
const priceRangeCents = row.requiresRegistration && prices.some((p) => p > 0) ? { lowCents: Math.min(...prices), highCents: Math.max(...prices) } : null;
const event: CrosscodeEvent = {
schema: 'crosscode.event/1',
id: row.id,
origin: { product: 'events', installId: ctx.installId, url: pageUrl },
status: 'published',
// The feed puts the time it last changed here (feed/entries.ts).
updatedAt: ctx.now.toISOString(),
title: cut(row.title, 200) ?? 'Event',
summary: null,
description: plainToMarkdown(row.description),
imageUrl: absolute(ctx.baseUrl, row.picture),
timezone: ctx.timezone,
startsAt: new Date(startsAt).toISOString(),
endsAt: new Date(endsAt).toISOString(),
allDay: false,
sessions: multi
? [...row.sessions]
.sort((a, b) => new Date(a.startsAt).getTime() - new Date(b.startsAt).getTime())
.slice(0, 500)
.map((s) => ({
id: s.id,
label: cut(s.label, 200),
startsAt: new Date(s.startsAt).toISOString(),
endsAt: new Date(s.endsAt).toISOString(),
location: cut(s.location, 300),
cancelled: !!s.cancelledAt,
}))
: [],
location: place ? (online ? { name: null, address: null, onlineUrl: online } : { name: place, address: null, onlineUrl: null }) : null,
campus: ctx.campusesOn && row.campus ? { slug: row.campus.slug, name: cut(row.campus.name, 200) ?? row.campus.slug } : null,
series: row.series ? { id: row.series.id, name: cut(row.series.name, 200) ?? 'Series' } : null,
tags: [],
registration: reg,
};
return { event, priceRangeCents };
}
/** What `loadForFeed` selects (and the e2e/unit fixtures build). */
export const FEED_EVENT_SELECT = {
id: true, title: true, description: true, startDate: true, endDate: true, goLiveAt: true, registrationDeadline: true,
picture: true, location: true, requiresRegistration: true, waitlistEnabled: true, scheduleType: true, attendanceMode: true,
lateJoinEnabled: true, lateJoinUntilSessionId: true, kidsOptionId: true, volunteerOptionId: true, updatedAt: true,
campus: { select: { slug: true, name: true } },
series: { select: { id: true, name: true } },
sessions: { select: { id: true, label: true, startsAt: true, endsAt: true, location: true, cancelledAt: true } },
eventOptions: { select: { id: true, price: true, isMainTicket: true, stockLimit: true, sessionMode: true, earlyBirdTiers: true, variants: { select: { price: true } } } },
} as const;
/**
* Places left on each limited main ticket. "Pick sessions" tickets have places per session; they
* count as sold out only when every session that still runs is.
*/
export async function availabilityFor(row: FeedEventRow): Promise<Availability> {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { takenCount } = require('../utils/stock') as { takenCount(where: object): Promise<number> };
const out: Availability = new Map();
for (const o of publicOptions<FeedOption>(row)) {
if (!o.isMainTicket || !(o.stockLimit > 0)) continue;
if (sessionsUtil.isPickOption(row, o)) {
let left = 0;
for (const s of sessionsUtil.activeSessions(row.sessions)) left += Math.max(0, o.stockLimit - await takenCount({ eventOptionId: o.id, sessionId: s.id }));
out.set(o.id, left);
} else {
out.set(o.id, Math.max(0, o.stockLimit - await takenCount({ eventOptionId: o.id })));
}
}
return out;
}
/**
* One event as `crosscode.event/1`, for its own page's JSON-LD (whether or not it's public: a
* hidden event's page is reachable by its link). `null` when there's no such event.
*/
export async function crosscodeEventFor(eventId: string, now = new Date()): Promise<BuiltEvent | null> {
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { feedContext } = require('./context') as typeof import('./context');
/* eslint-enable @typescript-eslint/no-require-imports */
const row = (await prisma.event.findUnique({ where: { id: eventId }, select: FEED_EVENT_SELECT })) as FeedEventRow | null;
if (!row) return null;
return buildCrosscodeEvent(row, await availabilityFor(row), await feedContext(now));
}