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:
@@ -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 }));
|
||||
}
|
||||
Reference in New Issue
Block a user