app: announcements, devotionals and events' screens; @crosscode/seo 1.1.0 (APP-1.0-PLAN §5-§7)
Public pages: Home with today's devotional, the latest announcements (pinned first) and what's on; Announcements and each one's page (markdown without HTML, a button, Article JSON-LD; members-only ones ask for a sign-in and are noindex); Devotional (the passage in full with its copyright line, Read in YouVersion, the prayer), each day's page, the archive by month and the Acknowledgements; Events and each one's page (Register on the Events site for Cross Events', a canonical to the origin, Event JSON-LD on the App's own). A sitemap of the public pages, named in robots.txt. Admin: Announcements (schedule, end, pin, campus, who sees it, also send it), Events (simple events, Linked products: publish and show events from), and Devotionals (Cross Code's or our own, Sync now, a month's days, writing, the CSV import with its preview, keep or replace days already filled). @crosscode/seo 1.1.0: articleJsonLd. The backend gives the App's own address and the sitemap's list, and a simple event's crosscode.event/1 for its page. Checked in a browser on a throwaway PostgreSQL: the pages for a visitor, the JSON-LD, a members-only announcement asking for a sign-in, the sitemap, a Content admin publishing an announcement and a Devotional writer saving one; no page errors. 94 backend tests, 19 seo tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { requireModule } from "@/lib/module";
|
||||
import { backendGet } from "@/lib/prayerServer";
|
||||
|
||||
export const metadata: Metadata = { title: "Acknowledgements" };
|
||||
|
||||
type Translation = { id: string; name: string; acknowledgement: string; disclaimer: string | null };
|
||||
|
||||
/** Each quoted Bible translation's full notice, in its publisher's own words (APP-1.0-PLAN §6, contracts 1.22.0). */
|
||||
export default async function Acknowledgements() {
|
||||
await requireModule("devotionals");
|
||||
const data = await backendGet<{ translations: Translation[] }>("/api/v1/devotionals/acknowledgements");
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">Acknowledgements</h1>
|
||||
<p className="cca-muted">The Bible translations the App's devotionals quote.</p>
|
||||
{(data?.translations ?? []).map((t) => (
|
||||
<section key={t.id} className="cca-card space-y-2">
|
||||
<h2 className="cca-h2">{t.name} ({t.id})</h2>
|
||||
<p className="text-sm">{t.acknowledgement}</p>
|
||||
{t.disclaimer && <p className="text-sm text-gray-700">{t.disclaimer}</p>}
|
||||
</section>
|
||||
))}
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { AdminAnnouncements } from "@/components/admin/AdminAnnouncements";
|
||||
import { requireAdmin } from "@/lib/admin";
|
||||
|
||||
export const metadata: Metadata = { title: "Announcements · Admin", robots: { index: false, follow: false } };
|
||||
|
||||
/** Announcements in the admin (APP-1.0-PLAN §5, §10): Content admins, Owner and Church admin. */
|
||||
export default async function AdminAnnouncementsPage() {
|
||||
const { app } = await requireAdmin(["content_admin"], "announcements");
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 px-4 py-10">
|
||||
<div>
|
||||
<Link href="/admin" className="text-sm text-gray-600 underline-offset-4 hover:underline">← Dashboard</Link>
|
||||
<h1 className="mt-1 text-2xl font-semibold">Announcements</h1>
|
||||
</div>
|
||||
<AdminAnnouncements timezone={app.timezone} campuses={(app.church?.campuses ?? []).map((c) => ({ slug: c.slug, name: c.name }))} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { AdminDevotionals } from "@/components/admin/AdminDevotionals";
|
||||
import { churchToday, requireAdmin } from "@/lib/admin";
|
||||
|
||||
export const metadata: Metadata = { title: "Devotionals · Admin", robots: { index: false, follow: false } };
|
||||
|
||||
/** Devotionals in the admin (APP-1.0-PLAN §6, §10): Devotional writers, Owner and Church admin. */
|
||||
export default async function AdminDevotionalsPage() {
|
||||
const { app } = await requireAdmin(["devotional_writer"], "devotionals");
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 px-4 py-10">
|
||||
<div>
|
||||
<Link href="/admin" className="text-sm text-gray-600 underline-offset-4 hover:underline">← Dashboard</Link>
|
||||
<h1 className="mt-1 text-2xl font-semibold">Devotionals</h1>
|
||||
</div>
|
||||
<AdminDevotionals today={churchToday(app.timezone)} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { AdminEvents } from "@/components/admin/AdminEvents";
|
||||
import { churchToday, requireAdmin } from "@/lib/admin";
|
||||
|
||||
export const metadata: Metadata = { title: "Events · Admin", robots: { index: false, follow: false } };
|
||||
|
||||
/** Events in the admin (APP-1.0-PLAN §7, §10): Content admins, Owner and Church admin. */
|
||||
export default async function AdminEventsPage() {
|
||||
const { app } = await requireAdmin(["content_admin"], "events");
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 px-4 py-10">
|
||||
<div>
|
||||
<Link href="/admin" className="text-sm text-gray-600 underline-offset-4 hover:underline">← Dashboard</Link>
|
||||
<h1 className="mt-1 text-2xl font-semibold">Events</h1>
|
||||
</div>
|
||||
<AdminEvents today={churchToday(app.timezone)} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -101,6 +101,11 @@ export default async function Admin() {
|
||||
House of Prayer: the week, who prays when, rules, campaigns, testimonies<span aria-hidden>›</span>
|
||||
</Link>
|
||||
)}
|
||||
{([["announcements", "/admin/announcements", "Announcements", ["content_admin"]], ["events", "/admin/events", "Events and Linked products", ["content_admin"]], ["devotionals", "/admin/devotionals", "Devotionals: Cross Code's or our own, the CSV import", ["devotional_writer"]]] as const).map(([module, href, label, roles]) =>
|
||||
o?.modules.includes(module) && me.activeRoles.some((r) => ["owner", "church_admin", ...roles].includes(r)) ? (
|
||||
<Link key={href} href={href} className="cca-card flex items-center justify-between font-semibold">{label}<span aria-hidden>›</span></Link>
|
||||
) : null,
|
||||
)}
|
||||
{o?.modules.includes("prayer-requests") && me.activeRoles.some((r) => ["owner", "church_admin", "prayer_coordinator", "pastoral_care"].includes(r)) && (
|
||||
<Link href="/admin/requests" className="cca-card flex items-center justify-between font-semibold">
|
||||
Prayer requests: approval, escalations, replies, settings<span aria-hidden>›</span>
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink } from "lucide-react";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import { AnnouncementJsonLd } from "@/components/content/Article";
|
||||
import { SignInFor } from "@/components/content/SignInFor";
|
||||
import { plain, type Announcement } from "@/lib/content";
|
||||
import { loadOne } from "@/lib/contentServer";
|
||||
import { loadApp } from "@/lib/load";
|
||||
import { requireModule } from "@/lib/module";
|
||||
import { truncate } from "@/lib/text";
|
||||
|
||||
type Props = { params: Promise<{ slug: string }> };
|
||||
const load = async (slug: string) => (/^[a-z0-9-]{1,80}$/.test(slug) ? loadOne<Announcement>(`/api/v1/announcements/${slug}`, "announcement") : null);
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const a = await load((await params).slug);
|
||||
if (!a || a === "signin") return { title: "Announcement", robots: { index: false, follow: false } };
|
||||
return {
|
||||
title: a.title,
|
||||
description: truncate(plain(a.body), 155),
|
||||
...(a.membersOnly ? { robots: { index: false, follow: false } } : { alternates: { canonical: `/announcements/${a.slug}` }, openGraph: { title: a.title, ...(a.imageUrl ? { images: [a.imageUrl] } : {}) } }),
|
||||
};
|
||||
}
|
||||
|
||||
/** One announcement (APP-1.0-PLAN §5): public ones are pages of their own; members-only ones ask for a sign-in. */
|
||||
export default async function AnnouncementPage({ params }: Props) {
|
||||
await requireModule("announcements");
|
||||
const { slug } = await params;
|
||||
const [a, app] = await Promise.all([load(slug), loadApp()]);
|
||||
if (!a) notFound();
|
||||
if (a === "signin") {
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">Announcement</h1>
|
||||
<SignInFor what="announcement" returnTo={`/announcements/${slug}`} />
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
const published = new Intl.DateTimeFormat("en-ZA", { timeZone: app.timezone, day: "numeric", month: "long", year: "numeric" }).format(new Date(a.publishedAt));
|
||||
return (
|
||||
<AppShell>
|
||||
<article className="space-y-4">
|
||||
{a.imageUrl && <img src={a.imageUrl} alt="" className="w-full rounded-cc object-cover" />}
|
||||
<header className="space-y-1">
|
||||
<h1 className="cca-h1">{a.title}</h1>
|
||||
<p className="cca-muted">{published}{a.membersOnly ? " · for members" : ""}</p>
|
||||
</header>
|
||||
<Markdown>{a.body}</Markdown>
|
||||
{a.button && (
|
||||
<a href={a.button.url} className="cca-btn w-full" target="_blank" rel="noopener noreferrer">
|
||||
{a.button.label}<ExternalLink className="h-4 w-4" aria-hidden />
|
||||
</a>
|
||||
)}
|
||||
</article>
|
||||
<AnnouncementJsonLd a={a} app={app} />
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { AnnouncementCard } from "@/components/content/Cards";
|
||||
import { loadAnnouncements } from "@/lib/contentServer";
|
||||
import { loadApp } from "@/lib/load";
|
||||
import { requireModule } from "@/lib/module";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const app = await loadApp();
|
||||
return { title: "Announcements", description: `News from ${app.church?.name ?? "the church"}.` };
|
||||
}
|
||||
|
||||
/** Announcements (APP-1.0-PLAN §5): pinned first, then the newest. Members see the members-only ones too. */
|
||||
export default async function Announcements() {
|
||||
await requireModule("announcements");
|
||||
const list = await loadAnnouncements();
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">Announcements</h1>
|
||||
{list.length ? (
|
||||
<div className="space-y-3">{list.map((a) => <AnnouncementCard key={a.slug} a={a} />)}</div>
|
||||
) : (
|
||||
<p className="cca-muted">No announcements right now.</p>
|
||||
)}
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { DevotionalJsonLd } from "@/components/content/Article";
|
||||
import { DevotionalView } from "@/components/content/DevotionalView";
|
||||
import { SignInFor } from "@/components/content/SignInFor";
|
||||
import { plain, type Devotional } from "@/lib/content";
|
||||
import { loadOne } from "@/lib/contentServer";
|
||||
import { loadApp } from "@/lib/load";
|
||||
import { requireModule } from "@/lib/module";
|
||||
import { truncate } from "@/lib/text";
|
||||
|
||||
type Props = { params: Promise<{ date: string }> };
|
||||
const load = async (date: string) => (/^\d{4}-\d{2}-\d{2}$/.test(date) ? loadOne<Devotional>(`/api/v1/devotionals/${date}`, "devotional") : null);
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const d = await load((await params).date);
|
||||
if (!d || d === "signin") return { title: "Devotional", robots: { index: false, follow: false } };
|
||||
return { title: d.title, description: truncate(`${d.passage.reference}: ${plain(d.body)}`, 155), ...(d.membersOnly ? { robots: { index: false, follow: false } } : { alternates: { canonical: `/devotional/${d.date}` } }) };
|
||||
}
|
||||
|
||||
/** One day's devotional (APP-1.0-PLAN §6), from the archive or the link in its email or WhatsApp. */
|
||||
export default async function DevotionalOn({ params }: Props) {
|
||||
await requireModule("devotionals");
|
||||
const { date } = await params;
|
||||
const [d, app] = await Promise.all([load(date), loadApp()]);
|
||||
if (!d) notFound();
|
||||
return (
|
||||
<AppShell>
|
||||
{d === "signin" ? (
|
||||
<>
|
||||
<h1 className="cca-h1">Devotional</h1>
|
||||
<SignInFor what="devotional" returnTo={`/devotional/${date}`} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<DevotionalView d={d} />
|
||||
<DevotionalJsonLd d={d} app={app} />
|
||||
</>
|
||||
)}
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { loadApp } from "@/lib/load";
|
||||
import { requireModule } from "@/lib/module";
|
||||
import { dayName } from "@/lib/prayer";
|
||||
import { backendGet } from "@/lib/prayerServer";
|
||||
|
||||
export const metadata: Metadata = { title: "Devotionals: the archive" };
|
||||
|
||||
type Day = { date: string; title: string; reference: string; membersOnly: boolean };
|
||||
|
||||
const shift = (month: string, n: number) => {
|
||||
const [y, m] = month.split("-").map(Number);
|
||||
const d = new Date(Date.UTC(y!, m! - 1 + n, 1));
|
||||
return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
/** The archive by month (APP-1.0-PLAN §6), with today's always first. */
|
||||
export default async function Archive({ searchParams }: { searchParams: Promise<{ month?: string }> }) {
|
||||
await requireModule("devotionals");
|
||||
const app = await loadApp();
|
||||
const thisMonth = new Intl.DateTimeFormat("en-CA", { timeZone: app.timezone, year: "numeric", month: "2-digit" }).format(new Date()).slice(0, 7);
|
||||
const q = (await searchParams).month;
|
||||
const month = q && /^\d{4}-(0[1-9]|1[0-2])$/.test(q) && q <= thisMonth ? q : thisMonth;
|
||||
const data = await backendGet<{ days: Day[] }>(`/api/v1/devotionals?month=${month}`);
|
||||
const label = new Intl.DateTimeFormat("en-ZA", { month: "long", year: "numeric", timeZone: "UTC" }).format(new Date(`${month}-15T12:00:00Z`));
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">Devotionals</h1>
|
||||
<Link href="/devotional" className="cca-btn w-full">Today's devotional</Link>
|
||||
<nav className="flex items-center justify-between gap-2" aria-label="Months">
|
||||
<Link href={`/devotional/archive?month=${shift(month, -1)}`} className="cca-btn-quiet !min-h-10">Earlier</Link>
|
||||
<h2 className="cca-h2">{label}</h2>
|
||||
{month < thisMonth ? <Link href={`/devotional/archive?month=${shift(month, 1)}`} className="cca-btn-quiet !min-h-10">Later</Link> : <span className="w-16" aria-hidden />}
|
||||
</nav>
|
||||
{data?.days.length ? (
|
||||
<ul className="cca-card divide-y divide-gray-100 !p-0">
|
||||
{data.days.map((d) => (
|
||||
<li key={d.date}>
|
||||
<Link href={`/devotional/${d.date}`} className="block px-4 py-3 hover:bg-gray-50">
|
||||
<span className="block text-xs font-semibold uppercase text-gray-600">{dayName(d.date, { weekday: "short", day: "numeric", month: "short" })}{d.membersOnly ? " · members" : ""}</span>
|
||||
<span className="block font-semibold">{d.title}</span>
|
||||
<span className="block text-sm text-gray-700">{d.reference}</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="cca-muted">No devotionals this month.</p>
|
||||
)}
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +1,38 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { ComingSoon } from "@/components/ComingSoon";
|
||||
import { DevotionalJsonLd } from "@/components/content/Article";
|
||||
import { DevotionalView } from "@/components/content/DevotionalView";
|
||||
import { plain } from "@/lib/content";
|
||||
import { loadToday } from "@/lib/contentServer";
|
||||
import { loadApp } from "@/lib/load";
|
||||
import { requireModule } from "@/lib/module";
|
||||
import { truncate } from "@/lib/text";
|
||||
|
||||
export const metadata: Metadata = { title: "Devotional" };
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const d = await loadToday();
|
||||
if (!d) return { title: "Devotional" };
|
||||
return { title: d.title, description: truncate(`${d.passage.reference}: ${plain(d.body)}`, 155), ...(d.membersOnly ? { robots: { index: false, follow: false } } : { alternates: { canonical: `/devotional/${d.date}` } }) };
|
||||
}
|
||||
|
||||
/** Today's devotional and the archive (APP-1.0-PLAN §6). */
|
||||
/** Today's devotional (APP-1.0-PLAN §6): from midnight in the church's timezone; the most recent when today has none. */
|
||||
export default async function Devotional() {
|
||||
await requireModule("devotionals");
|
||||
const [d, app] = await Promise.all([loadToday(), loadApp()]);
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">Devotional</h1>
|
||||
<ComingSoon title="Today">Today's Bible passage and devotional will show here, with Read in YouVersion.</ComingSoon>
|
||||
{d ? (
|
||||
<>
|
||||
{!d.today && <p className="cca-muted">There's no devotional for today yet. Here's the latest one.</p>}
|
||||
<DevotionalView d={d} />
|
||||
<DevotionalJsonLd d={d} app={app} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h1 className="cca-h1">Devotional</h1>
|
||||
<section className="cca-card space-y-2"><p>There are no devotionals yet. They'll show here each morning.</p><Link href="/" className="cca-btn-quiet">Back home</Link></section>
|
||||
</>
|
||||
)}
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { MapPin } from "lucide-react";
|
||||
import { eventJsonLd, jsonLdString } from "@crosscode/seo";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { RegisterButton } from "@/components/content/Cards";
|
||||
import { eventWhen, type EventItem } from "@/lib/content";
|
||||
import { loadOne } from "@/lib/contentServer";
|
||||
import { loadApp } from "@/lib/load";
|
||||
import { requireModule } from "@/lib/module";
|
||||
import { truncate } from "@/lib/text";
|
||||
|
||||
type Props = { params: Promise<{ key: string }> };
|
||||
const load = async (key: string) => (/^[a-z0-9-]{1,120}$/.test(key) ? loadOne<EventItem>(`/api/v1/events/${key}`, "event") : null);
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const e = await load((await params).key);
|
||||
if (!e || e === "signin") return { title: "Event" };
|
||||
return {
|
||||
title: e.title,
|
||||
description: truncate(e.summary ?? e.description ?? eventWhen(e), 155),
|
||||
// An imported event points search engines at its origin (§7): one event, not one per product.
|
||||
alternates: { canonical: e.canonical ?? `/events/${e.key}` },
|
||||
...(e.imageUrl ? { openGraph: { title: e.title, images: [e.imageUrl] } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** One event (APP-1.0-PLAN §7): Cross Events' show "Register on the Events site"; registering and paying stay there. */
|
||||
export default async function EventPage({ params }: Props) {
|
||||
await requireModule("events");
|
||||
const [e, app] = await Promise.all([load((await params).key), loadApp()]);
|
||||
if (!e || e === "signin") notFound();
|
||||
return (
|
||||
<AppShell>
|
||||
<article className="space-y-4">
|
||||
{e.imageUrl && <img src={e.imageUrl} alt="" className="w-full rounded-cc object-cover" />}
|
||||
<header className="space-y-1">
|
||||
<h1 className={`cca-h1 ${e.cancelled ? "line-through" : ""}`}>{e.title}</h1>
|
||||
{e.cancelled && <p className="font-semibold text-red-700">This event is cancelled.</p>}
|
||||
<p className="font-medium">{eventWhen(e)}</p>
|
||||
{e.location && <p className="flex items-center gap-1 text-gray-700"><MapPin className="h-4 w-4" aria-hidden />{e.location}</p>}
|
||||
</header>
|
||||
<RegisterButton e={e} />
|
||||
{e.description && <p className="whitespace-pre-line">{e.description}</p>}
|
||||
{e.source !== "app" && <p className="cca-muted">From the church's {e.source === "events" ? "Events site" : "website"}.</p>}
|
||||
</article>
|
||||
{/* Only the origin's page carries the Event JSON-LD (packages/seo). */}
|
||||
{e.crosscode && app.church && (
|
||||
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLdString(eventJsonLd(e.crosscode, { pageUrl: `${app.url}/events/${e.key}`, organizer: { name: app.church.name, url: app.church.links.website ?? app.url } })) }} />
|
||||
)}
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +1,27 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { ComingSoon } from "@/components/ComingSoon";
|
||||
import { EventCard } from "@/components/content/Cards";
|
||||
import { loadEvents } from "@/lib/contentServer";
|
||||
import { loadApp } from "@/lib/load";
|
||||
import { requireModule } from "@/lib/module";
|
||||
|
||||
export const metadata: Metadata = { title: "Events" };
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const app = await loadApp();
|
||||
return { title: "Events", description: `What's on at ${app.church?.name ?? "the church"}.` };
|
||||
}
|
||||
|
||||
/** Events (APP-1.0-PLAN §7): the App's simple events and those from Cross Events and the Website. */
|
||||
/** Events (APP-1.0-PLAN §7): the App's simple events and those from Cross Events and the Website, in date order. */
|
||||
export default async function Events() {
|
||||
await requireModule("events");
|
||||
const events = await loadEvents();
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">Events</h1>
|
||||
<ComingSoon title="What's on">The church's events will show here.</ComingSoon>
|
||||
{events.length ? (
|
||||
<div className="space-y-3">{events.map((e) => <EventCard key={e.key} e={e} />)}</div>
|
||||
) : (
|
||||
<p className="cca-muted">Nothing is planned yet. Events will show here.</p>
|
||||
)}
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -46,4 +46,12 @@ h1, h2, h3 {
|
||||
.cca-h1 { @apply font-heading text-2xl font-semibold text-gray-900; }
|
||||
.cca-h2 { @apply font-heading text-lg font-semibold text-gray-900; }
|
||||
.cca-muted { @apply text-sm text-gray-600; }
|
||||
/* Markdown from announcements and devotionals. */
|
||||
.cca-prose { @apply space-y-3 leading-relaxed; }
|
||||
.cca-prose a { @apply font-medium text-brand-text underline underline-offset-2; }
|
||||
.cca-prose ul { @apply list-disc space-y-1 pl-5; }
|
||||
.cca-prose ol { @apply list-decimal space-y-1 pl-5; }
|
||||
.cca-prose h1, .cca-prose h2, .cca-prose h3 { @apply font-heading text-lg font-semibold; }
|
||||
.cca-prose blockquote { @apply border-l-4 border-brand-tint pl-3 italic text-gray-700; }
|
||||
.cca-prose strong { @apply font-semibold; }
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { ComingSoon } from "@/components/ComingSoon";
|
||||
import Link from "next/link";
|
||||
import { AnnouncementCard, DevotionalCard, EventCard } from "@/components/content/Cards";
|
||||
import { InstallCard } from "@/components/InstallCard";
|
||||
import { CampaignCard } from "@/components/prayer/CampaignCard";
|
||||
import { PrayerHomeCard } from "@/components/prayer/PrayerHomeCard";
|
||||
import { firstName, greeting, loadApp, loadMe } from "@/lib/load";
|
||||
import { loadCampaign, loadDay, loadMyPrayer } from "@/lib/prayerServer";
|
||||
import { loadAnnouncements, loadEvents, loadToday } from "@/lib/contentServer";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const app = await loadApp();
|
||||
@@ -23,6 +25,11 @@ export default async function Home() {
|
||||
const on = new Set(app.modules);
|
||||
const prayer = on.has("house-of-prayer");
|
||||
const [day, campaign, mine] = prayer ? await Promise.all([loadDay(), loadCampaign(), me ? loadMyPrayer() : null]) : [null, null, null];
|
||||
const [devotional, announcements, events] = await Promise.all([
|
||||
on.has("devotionals") ? loadToday() : null,
|
||||
on.has("announcements") ? loadAnnouncements(2) : [],
|
||||
on.has("events") ? loadEvents(3) : [],
|
||||
]);
|
||||
const name = app.church?.name ?? "your church";
|
||||
return (
|
||||
<AppShell>
|
||||
@@ -32,8 +39,19 @@ export default async function Home() {
|
||||
<InstallCard name={app.shortName} />
|
||||
{campaign && <CampaignCard campaign={campaign} compact />}
|
||||
{day && <PrayerHomeCard day={day} mine={mine} />}
|
||||
{on.has("devotionals") && <ComingSoon title="Today's devotional">Today's Bible passage and devotional will show here.</ComingSoon>}
|
||||
{on.has("announcements") && <ComingSoon title="Announcements">News from {name} will show here.</ComingSoon>}
|
||||
{devotional && <DevotionalCard d={devotional} />}
|
||||
{announcements.length > 0 && (
|
||||
<section className="space-y-3" aria-labelledby="news">
|
||||
<div className="flex items-end justify-between"><h2 id="news" className="cca-h2">News</h2><Link href="/announcements" className="text-sm font-semibold text-brand-text underline-offset-4 hover:underline">All</Link></div>
|
||||
{announcements.map((a) => <AnnouncementCard key={a.slug} a={a} />)}
|
||||
</section>
|
||||
)}
|
||||
{events.length > 0 && (
|
||||
<section className="space-y-3" aria-labelledby="whats-on">
|
||||
<div className="flex items-end justify-between"><h2 id="whats-on" className="cca-h2">What's on</h2><Link href="/events" className="text-sm font-semibold text-brand-text underline-offset-4 hover:underline">All events</Link></div>
|
||||
{events.map((e) => <EventCard key={e.key} e={e} />)}
|
||||
</section>
|
||||
)}
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { loadApp } from "@/lib/load";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Public content is indexed; the member's pages, the admin, prayer and the API never are
|
||||
// (APP-1.0-PLAN §4, §11; ROADMAP-v3 §11). The sitemap grows with the public modules.
|
||||
export default function robots(): MetadataRoute.Robots {
|
||||
return { rules: [{ userAgent: "*", allow: "/", disallow: ["/admin", "/me", "/prayer", "/auth", "/offline", "/api"] }] };
|
||||
// (APP-1.0-PLAN §4, §11; ROADMAP-v3 §11). The sitemap lists the public pages (sitemap.ts).
|
||||
export default async function robots(): Promise<MetadataRoute.Robots> {
|
||||
const app = await loadApp();
|
||||
return { rules: [{ userAgent: "*", allow: "/", disallow: ["/admin", "/me", "/prayer", "/auth", "/offline", "/api"] }], sitemap: `${app.url}/sitemap.xml` };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { api, loadApp } from "@/lib/load";
|
||||
|
||||
// Built on request (cached 10 minutes): at build time the backend isn't there to list anything.
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Listing = { announcements: { slug: string; updatedAt: string }[]; devotionals: { date: string; updatedAt: string }[]; events: { key: string; updatedAt: string }[] };
|
||||
|
||||
/**
|
||||
* The public pages (ROADMAP-v3 §11; APP-1.0-PLAN §5–§7): Home, the modules' lists, public
|
||||
* announcements, devotionals of the last year and the App's own events. Never prayer, members-only
|
||||
* items or events imported from the church's other sites (their origin lists them).
|
||||
*/
|
||||
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
const app = await loadApp();
|
||||
let listing: Listing = { announcements: [], devotionals: [], events: [] };
|
||||
try {
|
||||
const res = await fetch(`${api}/api/v1/sitemap`, { next: { revalidate: 600 } });
|
||||
if (res.ok) listing = (await res.json()) as Listing;
|
||||
} catch {
|
||||
// The backend is starting: the lists alone for now.
|
||||
}
|
||||
const on = new Set(app.modules);
|
||||
const url = (path: string) => `${app.url}${path}`;
|
||||
return [
|
||||
{ url: url("/"), changeFrequency: "daily", priority: 1 },
|
||||
...(on.has("announcements") ? [{ url: url("/announcements"), changeFrequency: "daily" as const }] : []),
|
||||
...(on.has("devotionals") ? [{ url: url("/devotional"), changeFrequency: "daily" as const }, { url: url("/devotional/archive"), changeFrequency: "daily" as const }, { url: url("/acknowledgements") }] : []),
|
||||
...(on.has("events") ? [{ url: url("/events"), changeFrequency: "daily" as const }] : []),
|
||||
...listing.announcements.map((a) => ({ url: url(`/announcements/${a.slug}`), lastModified: a.updatedAt })),
|
||||
...listing.devotionals.map((d) => ({ url: url(`/devotional/${d.date}`), lastModified: d.updatedAt })),
|
||||
...listing.events.map((e) => ({ url: url(`/events/${e.key}`), lastModified: e.updatedAt })),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import ReactMarkdown from "react-markdown";
|
||||
|
||||
/**
|
||||
* Announcements' and devotionals' text (APP-1.0-PLAN §5, §6): markdown without HTML (react-markdown
|
||||
* never renders raw HTML), links to other sites opening in a new tab, and only http(s) and mailto/tel links.
|
||||
*/
|
||||
export function Markdown({ children, className = "" }: { children: string; className?: string }) {
|
||||
return (
|
||||
<div className={`cca-prose ${className}`}>
|
||||
<ReactMarkdown
|
||||
skipHtml
|
||||
urlTransform={(url) => (/^(https?:|mailto:|tel:|\/|#)/i.test(url) ? url : "")}
|
||||
components={{
|
||||
a: ({ href, children: text }) => {
|
||||
const external = !!href && /^https?:/i.test(href);
|
||||
return <a href={href} {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}>{text}</a>;
|
||||
},
|
||||
img: () => null,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { adminCall, Field, fromLocalInput, input, Notice, Panel, toLocalInput, type Msg } from "./kit";
|
||||
|
||||
type Row = {
|
||||
id: string; slug: string; title: string; body: string; imageUrl: string | null; buttonLabel: string | null; buttonUrl: string | null; campus: string | null;
|
||||
audience: "everyone" | "members"; pinned: boolean; publishAt: string | null; endsAt: string | null; sendEmail: boolean; sendWhatsApp: boolean; sentAt: string | null;
|
||||
state: "draft" | "scheduled" | "live" | "ended";
|
||||
};
|
||||
type Form = Omit<Row, "id" | "slug" | "sentAt" | "state"> & { id?: string; when: "now" | "later" | "draft" };
|
||||
|
||||
const STATE = { draft: "Draft", scheduled: "Scheduled", live: "Live", ended: "Ended" } as const;
|
||||
const blank = (): Form => ({ title: "", body: "", imageUrl: null, buttonLabel: null, buttonUrl: null, campus: null, audience: "everyone", pinned: false, publishAt: null, endsAt: null, sendEmail: false, sendWhatsApp: false, when: "now" });
|
||||
|
||||
/**
|
||||
* Announcements in the admin (APP-1.0-PLAN §5): write, schedule, pin, end, who sees it, a campus,
|
||||
* a button, and "also send it" by email or WhatsApp (sent once, at the publish time, to members who
|
||||
* chose announcements).
|
||||
*/
|
||||
export function AdminAnnouncements({ timezone, campuses }: { timezone: string; campuses: { slug: string; name: string }[] }) {
|
||||
const [rows, setRows] = useState<Row[]>([]);
|
||||
const [form, setForm] = useState<Form | null>(null);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
const [version, setVersion] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
adminCall<{ announcements: Row[] }>("GET", "/announcements").then((r) => (r.ok ? setRows(r.data.announcements) : setMsg({ kind: "error", text: r.error })));
|
||||
}, [version]);
|
||||
|
||||
const edit = (a: Row) => {
|
||||
setErrors({});
|
||||
setForm({ ...a, when: !a.publishAt ? "draft" : a.state === "scheduled" ? "later" : "now" });
|
||||
};
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!form) return;
|
||||
const { id, when, ...f } = form;
|
||||
const body = {
|
||||
...f,
|
||||
imageUrl: f.imageUrl || null, buttonLabel: f.buttonLabel || null, buttonUrl: f.buttonUrl || null, campus: f.campus || null,
|
||||
publishAt: when === "draft" ? null : when === "later" ? f.publishAt : (id && f.publishAt) || undefined,
|
||||
endsAt: f.endsAt || null,
|
||||
};
|
||||
const r = await adminCall<{ id: string }>(id ? "PUT" : "POST", id ? `/announcements/${id}` : "/announcements", body);
|
||||
if (!r.ok) {
|
||||
setErrors(r.fields ?? {});
|
||||
setMsg({ kind: "error", text: r.error });
|
||||
return;
|
||||
}
|
||||
setMsg({ kind: "ok", text: when === "draft" ? "Saved as a draft." : when === "later" ? "Scheduled." : "Published." });
|
||||
setForm(null);
|
||||
setVersion((v) => v + 1);
|
||||
}
|
||||
|
||||
async function remove(a: Row) {
|
||||
if (!window.confirm(`Delete "${a.title}"?`)) return;
|
||||
const r = await adminCall("DELETE", `/announcements/${a.id}`);
|
||||
setMsg(r.ok ? { kind: "ok", text: "Deleted." } : { kind: "error", text: r.error });
|
||||
setVersion((v) => v + 1);
|
||||
}
|
||||
|
||||
const set = <K extends keyof Form>(k: K, v: Form[K]) => setForm((f) => (f ? { ...f, [k]: v } : f));
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<Notice msg={msg} />
|
||||
{form ? (
|
||||
<Panel title={form.id ? "Change the announcement" : "New announcement"}>
|
||||
<form onSubmit={save} className="space-y-4">
|
||||
<Field label="Title" error={errors.title}><input required maxLength={160} value={form.title} onChange={(e) => set("title", e.target.value)} className={input} /></Field>
|
||||
<Field label="Text" error={errors.body} hint="Markdown: **bold**, *italics*, lists and [links](https://…). No HTML."><textarea required rows={8} maxLength={20000} value={form.body} onChange={(e) => set("body", e.target.value)} className={input} /></Field>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<Field label="Image address (optional)" error={errors.imageUrl}><input type="url" value={form.imageUrl ?? ""} onChange={(e) => set("imageUrl", e.target.value)} className={input} /></Field>
|
||||
<Field label="Button words (optional)" error={errors.buttonLabel}><input maxLength={40} value={form.buttonLabel ?? ""} onChange={(e) => set("buttonLabel", e.target.value)} className={input} placeholder="Sign up" /></Field>
|
||||
<Field label="Button link" error={errors.buttonUrl}><input type="url" value={form.buttonUrl ?? ""} onChange={(e) => set("buttonUrl", e.target.value)} className={input} /></Field>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<Field label="Who sees it">
|
||||
<select value={form.audience} onChange={(e) => set("audience", e.target.value as Form["audience"])} className={input}>
|
||||
<option value="everyone">Everyone (a public page)</option>
|
||||
<option value="members">Signed-in members only</option>
|
||||
</select>
|
||||
</Field>
|
||||
{campuses.length > 0 && (
|
||||
<Field label="Campus" error={errors.campus}>
|
||||
<select value={form.campus ?? ""} onChange={(e) => set("campus", e.target.value || null)} className={input}>
|
||||
<option value="">Every campus</option>
|
||||
{campuses.map((c) => <option key={c.slug} value={c.slug}>{c.name}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<label className="flex items-center gap-2 self-end pb-2 text-sm font-medium"><input type="checkbox" checked={form.pinned} onChange={(e) => set("pinned", e.target.checked)} />Pin it to the top</label>
|
||||
</div>
|
||||
<fieldset className="grid gap-4 sm:grid-cols-3">
|
||||
<legend className="mb-1 text-sm font-semibold">When</legend>
|
||||
<Field label="Publish">
|
||||
<select value={form.when} onChange={(e) => set("when", e.target.value as Form["when"])} className={input}>
|
||||
<option value="now">Now</option><option value="later">Later</option><option value="draft">Not yet (a draft)</option>
|
||||
</select>
|
||||
</Field>
|
||||
{form.when === "later" && <Field label="On" error={errors.publishAt}><input type="datetime-local" required value={toLocalInput(form.publishAt, timezone)} onChange={(e) => set("publishAt", fromLocalInput(e.target.value, timezone))} className={input} /></Field>}
|
||||
<Field label="Hide it after (optional)" error={errors.endsAt}><input type="datetime-local" value={toLocalInput(form.endsAt, timezone)} onChange={(e) => set("endsAt", fromLocalInput(e.target.value, timezone))} className={input} /></Field>
|
||||
</fieldset>
|
||||
<fieldset className="space-y-1">
|
||||
<legend className="text-sm font-semibold">Also send it, at the publish time, to members who chose announcements</legend>
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.sendEmail} onChange={(e) => set("sendEmail", e.target.checked)} />By email</label>
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.sendWhatsApp} onChange={(e) => set("sendWhatsApp", e.target.checked)} />By WhatsApp</label>
|
||||
</fieldset>
|
||||
<div className="flex gap-2"><button className="cca-btn">Save</button><button type="button" className="cca-btn-quiet" onClick={() => setForm(null)}>Cancel</button></div>
|
||||
</form>
|
||||
</Panel>
|
||||
) : (
|
||||
<Panel title="Announcements" aside={<button className="cca-btn !min-h-9" onClick={() => { setErrors({}); setForm(blank()); }}>New announcement</button>}>
|
||||
{rows.length ? (
|
||||
<ul className="divide-y divide-gray-100">
|
||||
{rows.map((a) => (
|
||||
<li key={a.id} className="flex flex-wrap items-center justify-between gap-2 py-3 text-sm">
|
||||
<div>
|
||||
<p className="font-medium">{a.title}{a.pinned ? " (pinned)" : ""}</p>
|
||||
<p className="text-gray-600">{STATE[a.state]}{a.audience === "members" ? " · members only" : ""}{a.campus ? ` · ${campuses.find((c) => c.slug === a.campus)?.name ?? a.campus}` : ""}{a.sentAt ? " · sent" : a.sendEmail || a.sendWhatsApp ? " · will be sent" : ""}</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
{a.state === "live" && <a href={`/announcements/${a.slug}`} className="font-medium text-gray-700 hover:underline">View</a>}
|
||||
<button className="font-medium text-brand-text hover:underline" onClick={() => edit(a)}>Edit</button>
|
||||
<button className="font-medium text-red-700 hover:underline" onClick={() => remove(a)}>Delete</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : <p className="text-sm text-gray-600">No announcements yet.</p>}
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { adminCall, Field, input, Notice, Panel, type Msg } from "./kit";
|
||||
|
||||
type Status = { source: "crosscode" | "church"; crosscode: { syncedAt: string | null; error: string | null; lastDay: string | null }; translations: { id: string; name: string }[] };
|
||||
type Day = { id: string; date: string; title: string; reference: string; body: string; prayer: string | null; author: string | null; membersOnly: boolean; passage: { translation: string; text: string } };
|
||||
type Form = { id?: string; date: string; title: string; reference: string; translation: string; passageText: string; body: string; prayer: string; author: string; membersOnly: boolean };
|
||||
type Preview = { fileError: string | null; valid: number; imported: number; replaced: number; skipped: number; rows: { line: number; date: string | null; title: string | null; errors: { column: string | null; message: string }[]; warnings: { message: string }[]; taken: boolean }[] };
|
||||
|
||||
const blank = (date: string): Form => ({ date, title: "", reference: "", translation: "BSB", passageText: "", body: "", prayer: "", author: "", membersOnly: false });
|
||||
const shiftMonth = (month: string, n: number) => {
|
||||
const [y, m] = month.split("-").map(Number);
|
||||
const d = new Date(Date.UTC(y!, m! - 1 + n, 1));
|
||||
return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Devotionals in the admin (APP-1.0-PLAN §6): which ones the App shows (Cross Code's from the Hub,
|
||||
* or the church's own), Sync now, a month's days of either, writing the church's own, and the CSV
|
||||
* import (the same columns and checks as the Hub's), with a preview first.
|
||||
*/
|
||||
export function AdminDevotionals({ today }: { today: string }) {
|
||||
const [status, setStatus] = useState<Status | null>(null);
|
||||
const [month, setMonth] = useState(today.slice(0, 7));
|
||||
const [view, setView] = useState<"church" | "crosscode">("church");
|
||||
const [days, setDays] = useState<Day[]>([]);
|
||||
const [form, setForm] = useState<Form | null>(null);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
const [csv, setCsv] = useState<{ text: string; name: string } | null>(null);
|
||||
const [preview, setPreview] = useState<Preview | null>(null);
|
||||
const [taken, setTaken] = useState<"skip" | "replace">("skip");
|
||||
const [version, setVersion] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
adminCall<Status>("GET", "/devotionals/settings").then((r) => {
|
||||
if (!r.ok) return;
|
||||
setStatus(r.data);
|
||||
setView((v) => (version === 0 ? r.data.source : v));
|
||||
});
|
||||
}, [version]);
|
||||
useEffect(() => {
|
||||
adminCall<{ devotionals: Day[] }>("GET", `/devotionals?month=${month}&source=${view}`).then((r) => r.ok && setDays(r.data.devotionals));
|
||||
}, [month, view, version]);
|
||||
|
||||
const set = <K extends keyof Form>(k: K, v: Form[K]) => setForm((f) => (f ? { ...f, [k]: v } : f));
|
||||
|
||||
async function setSource(source: "crosscode" | "church") {
|
||||
const r = await adminCall<Status>("PUT", "/devotionals/settings", { source });
|
||||
if (r.ok) { setStatus(r.data); setView(source); setMsg({ kind: "ok", text: source === "crosscode" ? "The App now shows Cross Code's devotionals." : "The App now shows the church's own devotionals." }); }
|
||||
else setMsg({ kind: "error", text: r.error });
|
||||
}
|
||||
|
||||
async function sync() {
|
||||
const r = await adminCall<{ saved: number; from: string; to: string }>("POST", "/devotionals/sync");
|
||||
setMsg(r.ok ? { kind: "ok", text: `Fetched ${r.data.saved} days (${r.data.from} to ${r.data.to}).` } : { kind: "error", text: r.error });
|
||||
setVersion((v) => v + 1);
|
||||
}
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!form) return;
|
||||
const { id, ...f } = form;
|
||||
const r = await adminCall<{ warnings: string[] }>(id ? "PUT" : "POST", id ? `/devotionals/${id}` : "/devotionals", { ...f, prayer: f.prayer || null, author: f.author || null });
|
||||
if (!r.ok) { setErrors(r.fields ?? {}); setMsg({ kind: "error", text: r.error }); return; }
|
||||
setMsg({ kind: "ok", text: r.data.warnings.length ? `Saved. ${r.data.warnings.join(" ")}` : "Saved." });
|
||||
setForm(null);
|
||||
setVersion((v) => v + 1);
|
||||
}
|
||||
|
||||
async function remove(d: Day) {
|
||||
if (!window.confirm(`Delete the devotional for ${d.date}?`)) return;
|
||||
const r = await adminCall("DELETE", `/devotionals/${d.id}`);
|
||||
setMsg(r.ok ? { kind: "ok", text: "Deleted." } : { kind: "error", text: r.error });
|
||||
setVersion((v) => v + 1);
|
||||
}
|
||||
|
||||
async function runImport(final: boolean) {
|
||||
if (!csv) return;
|
||||
const r = await adminCall<Preview>("POST", `/devotionals/import?preview=${final ? "false" : "true"}&taken=${taken}`, csv.text, "text/csv");
|
||||
if (!r.ok) return setMsg({ kind: "error", text: r.error });
|
||||
if (final) {
|
||||
setMsg({ kind: "ok", text: `Imported ${r.data.imported}, replaced ${r.data.replaced}, skipped ${r.data.skipped}.` });
|
||||
setCsv(null);
|
||||
setPreview(null);
|
||||
setVersion((v) => v + 1);
|
||||
} else setPreview(r.data);
|
||||
}
|
||||
|
||||
const label = new Intl.DateTimeFormat("en-ZA", { month: "long", year: "numeric", timeZone: "UTC" }).format(new Date(`${month}-15T12:00:00Z`));
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<Notice msg={msg} />
|
||||
{status && (
|
||||
<Panel title="Which devotionals the App shows">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{(["crosscode", "church"] as const).map((s) => (
|
||||
<label key={s} className={`flex cursor-pointer gap-3 rounded-md border p-3 text-sm ${status.source === s ? "border-brand bg-brand-tint" : "border-gray-200"}`}>
|
||||
<input type="radio" name="source" checked={status.source === s} onChange={() => setSource(s)} className="mt-1" />
|
||||
<span>
|
||||
<span className="block font-semibold">{s === "crosscode" ? "From Cross Code" : "Our own"}</span>
|
||||
<span className="block text-gray-700">{s === "crosscode" ? "Written by Cross Code, the same for every church that chooses them; fetched each night." : "Written by the church's Devotional writers, here or from a CSV."}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{status.source === "crosscode" && (
|
||||
<div className="mt-3 flex flex-wrap items-center justify-between gap-2 text-sm">
|
||||
<p className="text-gray-700">
|
||||
{status.crosscode.error ? `Last fetch failed: ${status.crosscode.error}` : status.crosscode.syncedAt ? `Fetched ${new Date(status.crosscode.syncedAt).toLocaleString("en-ZA")}.` : "Not fetched yet."}
|
||||
{status.crosscode.lastDay && ` Days up to ${status.crosscode.lastDay}.`}
|
||||
</p>
|
||||
<button className="cca-btn-quiet !min-h-9" onClick={sync}>Sync now</button>
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-3 text-xs text-gray-600">Only the free translations ({status.translations.map((t) => t.name).join(", ")}) can be quoted; the others need their publisher's written permission. The passage is shown in full with its copyright line, and Read in YouVersion.</p>
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
{form ? (
|
||||
<Panel title={form.id ? `The devotional for ${form.date}` : "New devotional"}>
|
||||
<form onSubmit={save} className="space-y-4">
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<Field label="Day" error={errors.date}><input type="date" required value={form.date} onChange={(e) => set("date", e.target.value)} className={input} /></Field>
|
||||
<Field label="Passage" error={errors.reference} hint="e.g. John 15:1-5"><input required maxLength={100} value={form.reference} onChange={(e) => set("reference", e.target.value)} className={input} /></Field>
|
||||
<Field label="Translation" error={errors.translation}>
|
||||
<select value={form.translation} onChange={(e) => set("translation", e.target.value)} className={input}>
|
||||
{(status?.translations ?? [{ id: "BSB", name: "Berean Standard Bible" }, { id: "KJV", name: "King James Version" }]).map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
<Field label="The passage's text" error={errors.passageText} hint="Copied exactly from the translation. Quote the passage the devotional is about, not whole chapters."><textarea required rows={4} value={form.passageText} onChange={(e) => set("passageText", e.target.value)} className={input} /></Field>
|
||||
<Field label="Title" error={errors.title}><input required maxLength={200} value={form.title} onChange={(e) => set("title", e.target.value)} className={input} /></Field>
|
||||
<Field label="The devotional" error={errors.body} hint="Markdown: **bold**, *italics*, lists. No HTML."><textarea required rows={10} value={form.body} onChange={(e) => set("body", e.target.value)} className={input} /></Field>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="A prayer (optional)" error={errors.prayer}><textarea rows={3} value={form.prayer} onChange={(e) => set("prayer", e.target.value)} className={input} /></Field>
|
||||
<Field label="Author (optional)" error={errors.author}><input maxLength={200} value={form.author} onChange={(e) => set("author", e.target.value)} className={input} /></Field>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm font-medium"><input type="checkbox" checked={form.membersOnly} onChange={(e) => set("membersOnly", e.target.checked)} />Only for signed-in members</label>
|
||||
<div className="flex gap-2"><button className="cca-btn">Save</button><button type="button" className="cca-btn-quiet" onClick={() => setForm(null)}>Cancel</button></div>
|
||||
</form>
|
||||
</Panel>
|
||||
) : (
|
||||
<Panel
|
||||
title={`${view === "church" ? "Our devotionals" : "Cross Code's devotionals"}: ${label}`}
|
||||
aside={
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<select value={view} onChange={(e) => setView(e.target.value as typeof view)} className="min-h-9 rounded-md border border-gray-300 px-2 text-sm" aria-label="Whose devotionals">
|
||||
<option value="church">Ours</option><option value="crosscode">Cross Code's</option>
|
||||
</select>
|
||||
<button className="cca-btn-quiet !min-h-9" onClick={() => setMonth(shiftMonth(month, -1))}>Earlier</button>
|
||||
<button className="cca-btn-quiet !min-h-9" onClick={() => setMonth(shiftMonth(month, 1))}>Later</button>
|
||||
{view === "church" && <button className="cca-btn !min-h-9" onClick={() => { setErrors({}); setForm(blank(today)); }}>New devotional</button>}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{days.length ? (
|
||||
<ul className="divide-y divide-gray-100">
|
||||
{days.map((d) => (
|
||||
<li key={d.id} className="flex flex-wrap items-center justify-between gap-2 py-2.5 text-sm">
|
||||
<div>
|
||||
<p className="font-medium">{d.date} · {d.title}</p>
|
||||
<p className="text-gray-600">{d.reference} ({d.passage.translation}){d.membersOnly ? " · members only" : ""}</p>
|
||||
</div>
|
||||
{view === "church" && (
|
||||
<div className="flex gap-3">
|
||||
<button className="font-medium text-brand-text hover:underline" onClick={() => { setErrors({}); setForm({ id: d.id, date: d.date, title: d.title, reference: d.reference, translation: d.passage.translation, passageText: d.passage.text, body: d.body, prayer: d.prayer ?? "", author: d.author ?? "", membersOnly: d.membersOnly }); }}>Edit</button>
|
||||
<button className="font-medium text-red-700 hover:underline" onClick={() => remove(d)}>Delete</button>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : <p className="text-sm text-gray-600">None this month.</p>}
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
{!form && view === "church" && (
|
||||
<Panel title="Import a CSV" aside={<a href="/api/v1/admin/devotionals/template" className="text-sm font-medium text-brand-text hover:underline">Download the template</a>}>
|
||||
<p className="mb-3 text-sm text-gray-600">Columns: date, title, passage, translation, passage_text, body, prayer, author. Up to 800 rows. Nothing changes until you import after the preview.</p>
|
||||
<input
|
||||
type="file"
|
||||
accept=".csv,text/csv"
|
||||
aria-label="The CSV file"
|
||||
onChange={async (e) => {
|
||||
const f = e.target.files?.[0];
|
||||
setPreview(null);
|
||||
setCsv(f ? { text: await f.text(), name: f.name } : null);
|
||||
}}
|
||||
className="text-sm"
|
||||
/>
|
||||
{csv && !preview && <button className="cca-btn-quiet ml-2 !min-h-9" onClick={() => runImport(false)}>Check it</button>}
|
||||
{preview && (
|
||||
<div className="mt-4 space-y-3">
|
||||
{preview.fileError ? <Notice msg={{ kind: "error", text: preview.fileError }} /> : (
|
||||
<>
|
||||
<p className="text-sm">{preview.valid} of {preview.rows.length} rows can be imported{preview.rows.some((r) => r.taken) ? `; ${preview.rows.filter((r) => r.taken).length} are for days already filled` : ""}.</p>
|
||||
<div className="max-h-72 overflow-y-auto rounded-md border border-gray-200">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead className="sticky top-0 bg-gray-50 text-gray-600"><tr><th className="px-2 py-1">Line</th><th>Day</th><th>Title</th><th>Check</th></tr></thead>
|
||||
<tbody>
|
||||
{preview.rows.map((r) => (
|
||||
<tr key={r.line} className="border-t border-gray-100 align-top">
|
||||
<td className="px-2 py-1 tabular-nums">{r.line}</td><td>{r.date ?? "—"}</td><td>{r.title ?? "—"}</td>
|
||||
<td className={r.errors.length ? "text-red-700" : r.warnings.length || r.taken ? "text-amber-700" : "text-green-700"}>
|
||||
{r.errors.length ? r.errors.map((e) => `${e.column ? `${e.column}: ` : ""}${e.message}`).join("; ") : [...r.warnings.map((w) => w.message), ...(r.taken ? ["The day already has one"] : [])].join("; ") || "OK"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{preview.rows.some((r) => r.taken) && (
|
||||
<fieldset className="flex flex-wrap gap-4 text-sm">
|
||||
<legend className="sr-only">Days already filled</legend>
|
||||
<label className="flex items-center gap-2"><input type="radio" checked={taken === "skip"} onChange={() => setTaken("skip")} />Keep the days already filled</label>
|
||||
<label className="flex items-center gap-2"><input type="radio" checked={taken === "replace"} onChange={() => setTaken("replace")} />Replace them</label>
|
||||
</fieldset>
|
||||
)}
|
||||
<button className="cca-btn" disabled={!preview.valid} onClick={() => runImport(true)}>Import {preview.valid} {preview.valid === 1 ? "row" : "rows"}</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { adminCall, Field, input, Notice, Panel, type Msg } from "./kit";
|
||||
|
||||
type Row = {
|
||||
id: string; slug: string; title: string; date: string; startTime: string | null; endDate: string | null; endTime: string | null; location: string | null;
|
||||
description: string | null; imageUrl: string | null; link: string | null; published: boolean; cancelled: boolean; startsAt: string;
|
||||
};
|
||||
type Form = Omit<Row, "id" | "slug" | "startsAt"> & { id?: string };
|
||||
type FeedLink = { installId: string; product: string; url: string; showEvents: boolean; lastSyncAt: string | null; lastGoodAt: string | null; lastSyncError: string | null };
|
||||
|
||||
const PRODUCT = { events: "Cross Events", website: "the Website" } as Record<string, string>;
|
||||
const blank = (today: string): Form => ({ title: "", date: today, startTime: "09:00", endDate: null, endTime: null, location: null, description: null, imageUrl: null, link: null, published: true, cancelled: false });
|
||||
|
||||
/**
|
||||
* Events in the admin (APP-1.0-PLAN §7): the App's simple events (title, when, where, description,
|
||||
* image, an optional link) and Linked products: publish the App's events to the church's other
|
||||
* sites, and show theirs (Cross Events' with Register on the Events site).
|
||||
*/
|
||||
export function AdminEvents({ today }: { today: string }) {
|
||||
const [rows, setRows] = useState<Row[]>([]);
|
||||
const [feed, setFeed] = useState<{ publish: boolean; links: FeedLink[] } | null>(null);
|
||||
const [form, setForm] = useState<Form | null>(null);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
const [version, setVersion] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
adminCall<{ events: Row[] }>("GET", "/events").then((r) => r.ok && setRows(r.data.events));
|
||||
adminCall<{ publish: boolean; links: FeedLink[] }>("GET", "/events/feed").then((r) => r.ok && setFeed(r.data));
|
||||
}, [version]);
|
||||
|
||||
const set = <K extends keyof Form>(k: K, v: Form[K]) => setForm((f) => (f ? { ...f, [k]: v } : f));
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!form) return;
|
||||
const { id, ...f } = form;
|
||||
const allDay = !f.startTime;
|
||||
const body = { ...f, endDate: f.endDate || null, endTime: allDay ? null : f.endTime || null, location: f.location || null, description: f.description || null, imageUrl: f.imageUrl || null, link: f.link || null };
|
||||
const r = await adminCall(id ? "PUT" : "POST", id ? `/events/${id}` : "/events", body);
|
||||
if (!r.ok) {
|
||||
setErrors(r.fields ?? {});
|
||||
setMsg({ kind: "error", text: r.error });
|
||||
return;
|
||||
}
|
||||
setMsg({ kind: "ok", text: f.published ? "Saved; the church's other sites are told." : "Saved as a draft." });
|
||||
setForm(null);
|
||||
setVersion((v) => v + 1);
|
||||
}
|
||||
|
||||
async function remove(row: Row) {
|
||||
if (!window.confirm(`Delete "${row.title}"? It leaves the church's other sites too.`)) return;
|
||||
const r = await adminCall("DELETE", `/events/${row.id}`);
|
||||
setMsg(r.ok ? { kind: "ok", text: "Deleted." } : { kind: "error", text: r.error });
|
||||
setVersion((v) => v + 1);
|
||||
}
|
||||
|
||||
async function feedChange(body: object) {
|
||||
const r = await adminCall("PUT", "/events/feed", body);
|
||||
setMsg(r.ok ? { kind: "ok", text: "Saved." } : { kind: "error", text: r.error });
|
||||
setVersion((v) => v + 1);
|
||||
}
|
||||
|
||||
const upcoming = rows.filter((r) => r.date >= today);
|
||||
const past = rows.filter((r) => r.date < today);
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<Notice msg={msg} />
|
||||
{form ? (
|
||||
<Panel title={form.id ? "Change the event" : "New event"}>
|
||||
<form onSubmit={save} className="space-y-4">
|
||||
<Field label="Title" error={errors.title}><input required maxLength={200} value={form.title} onChange={(e) => set("title", e.target.value)} className={input} /></Field>
|
||||
<div className="grid gap-4 sm:grid-cols-4">
|
||||
<Field label="Date" error={errors.date}><input type="date" required value={form.date} onChange={(e) => set("date", e.target.value)} className={input} /></Field>
|
||||
<Field label="Starts" error={errors.startTime} hint="Empty for all day"><input type="time" value={form.startTime ?? ""} onChange={(e) => set("startTime", e.target.value || null)} className={input} /></Field>
|
||||
<Field label="Ends on (optional)" error={errors.endDate}><input type="date" value={form.endDate ?? ""} min={form.date} onChange={(e) => set("endDate", e.target.value || null)} className={input} /></Field>
|
||||
{form.startTime && <Field label="Ends at" error={errors.endTime}><input type="time" value={form.endTime ?? ""} onChange={(e) => set("endTime", e.target.value || null)} className={input} /></Field>}
|
||||
</div>
|
||||
<Field label="Where" error={errors.location}><input maxLength={200} value={form.location ?? ""} onChange={(e) => set("location", e.target.value)} className={input} /></Field>
|
||||
<Field label="Description" error={errors.description}><textarea rows={5} maxLength={10000} value={form.description ?? ""} onChange={(e) => set("description", e.target.value)} className={input} /></Field>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="Image address (optional)" error={errors.imageUrl}><input type="url" value={form.imageUrl ?? ""} onChange={(e) => set("imageUrl", e.target.value)} className={input} /></Field>
|
||||
<Field label="More info link (optional)" error={errors.link}><input type="url" value={form.link ?? ""} onChange={(e) => set("link", e.target.value)} className={input} /></Field>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-6 text-sm font-medium">
|
||||
<label className="flex items-center gap-2"><input type="checkbox" checked={form.published} onChange={(e) => set("published", e.target.checked)} />Published</label>
|
||||
<label className="flex items-center gap-2"><input type="checkbox" checked={form.cancelled} onChange={(e) => set("cancelled", e.target.checked)} />Cancelled</label>
|
||||
</div>
|
||||
<p className="text-xs text-gray-600">Events that need registration or payment belong in Cross Events; the App shows them with Register on the Events site.</p>
|
||||
<div className="flex gap-2"><button className="cca-btn">Save</button><button type="button" className="cca-btn-quiet" onClick={() => setForm(null)}>Cancel</button></div>
|
||||
</form>
|
||||
</Panel>
|
||||
) : (
|
||||
<Panel title="The App's events" aside={<button className="cca-btn !min-h-9" onClick={() => { setErrors({}); setForm(blank(today)); }}>New event</button>}>
|
||||
{[["Coming up", upcoming], ["Past", past]].map(([label, list]) => (list as Row[]).length > 0 && (
|
||||
<div key={label as string} className="mb-4">
|
||||
<h3 className="mb-1 text-sm font-semibold text-gray-600">{label as string}</h3>
|
||||
<ul className="divide-y divide-gray-100">
|
||||
{(list as Row[]).map((row) => (
|
||||
<li key={row.id} className="flex flex-wrap items-center justify-between gap-2 py-2.5 text-sm">
|
||||
<div>
|
||||
<p className="font-medium">{row.title}{row.cancelled ? " (cancelled)" : ""}</p>
|
||||
<p className="text-gray-600">{row.date}{row.startTime ? ` ${row.startTime}` : " all day"}{row.location ? ` · ${row.location}` : ""}{row.published ? "" : " · draft"}</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<button className="font-medium text-brand-text hover:underline" onClick={() => { setErrors({}); setForm(row); }}>Edit</button>
|
||||
<button className="font-medium text-red-700 hover:underline" onClick={() => remove(row)}>Delete</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
{!rows.length && <p className="text-sm text-gray-600">No events of the App's own yet.</p>}
|
||||
</Panel>
|
||||
)}
|
||||
{feed && !form && (
|
||||
<Panel title="Linked products" aside={<button className="cca-btn-quiet !min-h-9" onClick={async () => { const r = await adminCall("POST", "/events/feed/sync"); setMsg(r.ok ? { kind: "ok", text: "Fetched." } : { kind: "error", text: r.error }); setVersion((v) => v + 1); }}>Fetch now</button>}>
|
||||
<label className="flex items-center gap-2 text-sm font-medium"><input type="checkbox" checked={feed.publish} onChange={(e) => feedChange({ publish: e.target.checked })} />Publish the App's events to the church's other sites</label>
|
||||
{feed.links.length ? (
|
||||
<ul className="mt-4 space-y-2">
|
||||
{feed.links.map((l) => (
|
||||
<li key={l.installId} className="rounded-md border border-gray-200 p-3 text-sm">
|
||||
<label className="flex items-center gap-2 font-medium"><input type="checkbox" checked={l.showEvents} onChange={(e) => feedChange({ showEvents: { [l.installId]: e.target.checked } })} />Show events from {PRODUCT[l.product] ?? l.product} ({l.url})</label>
|
||||
<p className="mt-1 text-xs text-gray-600">{l.lastSyncError ? `Last fetch: ${l.lastSyncError}` : l.lastGoodAt ? `Up to date (${new Date(l.lastGoodAt).toLocaleString("en-ZA")})` : "Not fetched yet"}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : <p className="mt-3 text-sm text-gray-600">No Cross Events or Website is linked yet. Linking is done from the Hub.</p>}
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Small pieces every admin screen of the App shares (the Website's and Events' admin look, APP-1.0-PLAN
|
||||
* decision 9): the API call with its error, panels, notices and inputs. The side menu comes with §10.
|
||||
*/
|
||||
import { errorMessage } from "@/lib/prayer";
|
||||
|
||||
export type Msg = { kind: "ok" | "error"; text: string } | null;
|
||||
|
||||
export async function adminCall<T>(method: string, path: string, body?: object | string, contentType?: string): Promise<{ ok: true; data: T } | { ok: false; error: string; fields?: Record<string, string> }> {
|
||||
try {
|
||||
const res = await fetch(`/api/v1/admin${path}`, {
|
||||
method,
|
||||
headers: body === undefined ? undefined : { "Content-Type": contentType ?? "application/json" },
|
||||
body: body === undefined ? undefined : typeof body === "string" ? body : JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) {
|
||||
const copy = res.clone();
|
||||
let fields: Record<string, string> | undefined;
|
||||
try {
|
||||
fields = ((await copy.json()) as { error?: { fields?: Record<string, string> } }).error?.fields;
|
||||
} catch {
|
||||
fields = undefined;
|
||||
}
|
||||
return { ok: false, error: await errorMessage(res), fields };
|
||||
}
|
||||
return { ok: true, data: (await res.json()) as T };
|
||||
} catch {
|
||||
return { ok: false, error: "The App's server can't be reached. Please try again." };
|
||||
}
|
||||
}
|
||||
|
||||
export function Panel({ title, children, aside }: { title: string; children: React.ReactNode; aside?: React.ReactNode }) {
|
||||
return (
|
||||
<section className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm">
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="text-lg font-semibold">{title}</h2>
|
||||
{aside}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function Notice({ msg }: { msg: Msg }) {
|
||||
if (!msg) return null;
|
||||
return <p role={msg.kind === "error" ? "alert" : "status"} className={`rounded-md p-3 text-sm ${msg.kind === "error" ? "bg-red-50 text-red-800" : "bg-green-50 text-green-800"}`}>{msg.text}</p>;
|
||||
}
|
||||
|
||||
export const input = "mt-1 block min-h-10 w-full rounded-md border border-gray-300 px-2 py-1.5 text-sm";
|
||||
|
||||
/** A labelled field with its error under it. */
|
||||
export function Field({ label, error, children, hint, className = "" }: { label: string; error?: string; hint?: string; children: React.ReactNode; className?: string }) {
|
||||
return (
|
||||
<label className={`block text-sm font-medium ${className}`}>
|
||||
{label}
|
||||
{children}
|
||||
{hint && <span className="mt-1 block text-xs font-normal text-gray-500">{hint}</span>}
|
||||
{error && <span className="mt-1 block text-xs font-normal text-red-700">{error}</span>}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
/** An ISO instant as the value of an `<input type="datetime-local">` in the church's timezone, and back. */
|
||||
export function toLocalInput(iso: string | null, tz: string): string {
|
||||
if (!iso) return "";
|
||||
const p = Object.fromEntries(new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(new Date(iso)).map((x) => [x.type, x.value]));
|
||||
return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}`;
|
||||
}
|
||||
|
||||
/** `YYYY-MM-DDTHH:MM` in `tz` to an ISO instant (two passes for the offset). */
|
||||
export function fromLocalInput(value: string, tz: string): string | null {
|
||||
if (!value) return null;
|
||||
const guess = Date.parse(`${value}:00Z`);
|
||||
const offset = (t: number) => Date.parse(`${toLocalInput(new Date(t).toISOString(), tz)}:00Z`) - Math.floor(t / 60000) * 60000;
|
||||
const first = guess - offset(guess);
|
||||
return new Date(guess - offset(first)).toISOString();
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { articleJsonLd, jsonLdString, type ArticleJsonLdInput } from "@crosscode/seo";
|
||||
import { plain, type Announcement, type Devotional } from "@/lib/content";
|
||||
import type { AppInfo } from "@/lib/load";
|
||||
import { truncate } from "@/lib/text";
|
||||
|
||||
/** Article JSON-LD for a public devotional or announcement (APP-1.0-PLAN §11); never on members-only pages. */
|
||||
export function ArticleJsonLd(props: ArticleJsonLdInput) {
|
||||
return <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLdString(articleJsonLd(props)) }} />;
|
||||
}
|
||||
|
||||
const publisherOf = (app: AppInfo) => ({ name: app.church!.name, url: app.church!.links.website ?? app.url, logoUrl: app.church!.branding.logoUrl });
|
||||
|
||||
export function DevotionalJsonLd({ d, app }: { d: Devotional; app: AppInfo }) {
|
||||
if (d.membersOnly || !app.church) return null;
|
||||
return (
|
||||
<ArticleJsonLd
|
||||
url={`${app.url}/devotional/${d.date}`} headline={d.title} datePublished={d.date} dateModified={d.updatedAt} author={d.author} about={d.passage.reference}
|
||||
description={truncate(plain(d.body), 155)} publisher={publisherOf(app)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function AnnouncementJsonLd({ a, app }: { a: Announcement; app: AppInfo }) {
|
||||
if (a.membersOnly || !app.church) return null;
|
||||
return (
|
||||
<ArticleJsonLd
|
||||
url={`${app.url}/announcements/${a.slug}`} headline={a.title} datePublished={a.publishedAt} dateModified={a.updatedAt} imageUrl={a.imageUrl}
|
||||
description={truncate(plain(a.body), 155)} publisher={publisherOf(app)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import Link from "next/link";
|
||||
import { BookOpen, ExternalLink, MapPin, Pin } from "lucide-react";
|
||||
import { dateTile, eventWhen, plain, type Announcement, type Devotional, type EventItem } from "@/lib/content";
|
||||
import { truncate } from "@/lib/text";
|
||||
|
||||
/** An announcement in a list (Home, Announcements): pinned ones say so. */
|
||||
export function AnnouncementCard({ a }: { a: Announcement }) {
|
||||
return (
|
||||
<Link href={`/announcements/${a.slug}`} className="cca-card block space-y-2 hover:border-brand">
|
||||
{a.imageUrl && <img src={a.imageUrl} alt="" className="-mx-4 -mt-4 mb-2 h-36 w-[calc(100%+2rem)] max-w-none rounded-t-cc object-cover" />}
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<h3 className="cca-h2">{a.title}</h3>
|
||||
{a.pinned && <Pin className="mt-1 h-4 w-4 shrink-0 text-brand-text" aria-label="Pinned" />}
|
||||
</div>
|
||||
<p className="cca-muted">{truncate(plain(a.body), 140)}</p>
|
||||
{a.membersOnly && <p className="text-xs font-semibold text-gray-600">Members only</p>}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/** One event in a list: the date tile, title, when and where, and where it comes from. */
|
||||
export function EventCard({ e }: { e: EventItem }) {
|
||||
const tile = dateTile(e.startsAt, e.timezone);
|
||||
return (
|
||||
<Link href={`/events/${e.key}`} className="cca-card flex gap-3 hover:border-brand">
|
||||
<div className="flex h-14 w-14 shrink-0 flex-col items-center justify-center rounded-cc bg-brand-tint text-brand-text" aria-hidden>
|
||||
<span className="text-xl font-semibold leading-none">{tile.day}</span>
|
||||
<span className="text-xs font-semibold">{tile.month}</span>
|
||||
</div>
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<h3 className={`font-semibold ${e.cancelled ? "line-through" : ""}`}>{e.title}</h3>
|
||||
<p className="text-sm text-gray-700">{eventWhen(e)}</p>
|
||||
{e.location && <p className="flex items-center gap-1 text-sm text-gray-600"><MapPin className="h-3.5 w-3.5" aria-hidden />{e.location}</p>}
|
||||
{e.cancelled ? <p className="text-sm font-semibold text-red-700">Cancelled</p> : e.source === "events" && <p className="text-xs text-gray-500">Register on the Events site</p>}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/** Home's devotional card: the title, the passage, the first lines. */
|
||||
export function DevotionalCard({ d }: { d: Devotional }) {
|
||||
return (
|
||||
<Link href={d.today ? "/devotional" : `/devotional/${d.date}`} className="cca-card block space-y-2 hover:border-brand">
|
||||
<p className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-brand-text"><BookOpen className="h-3.5 w-3.5" aria-hidden />{d.today ? "Today's devotional" : "The latest devotional"}</p>
|
||||
<h2 className="cca-h2">{d.title}</h2>
|
||||
<p className="text-sm font-medium text-gray-700">{d.passage.reference} ({d.passage.translation})</p>
|
||||
<p className="cca-muted">{truncate(plain(d.passage.text), 140)}</p>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Register on the Events site" (or More info): a link out, never a registration here (§7). */
|
||||
export function RegisterButton({ e }: { e: EventItem }) {
|
||||
if (!e.registration || e.cancelled) return null;
|
||||
return (
|
||||
<a href={e.registration.url} className="cca-btn w-full" target="_blank" rel="noopener noreferrer">
|
||||
{e.registration.label}<ExternalLink className="h-4 w-4" aria-hidden />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import Link from "next/link";
|
||||
import { BookOpen, ExternalLink } from "lucide-react";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import type { Devotional } from "@/lib/content";
|
||||
import { dayName } from "@/lib/prayer";
|
||||
|
||||
/**
|
||||
* A devotional in full (APP-1.0-PLAN §6, decision 5; mockup "Devotional"): the passage above it,
|
||||
* quoted in full with its translation and copyright line (and the publisher's disclaimer where
|
||||
* there is one), **Read in YouVersion**, the devotional, the prayer, the author.
|
||||
*/
|
||||
export function DevotionalView({ d }: { d: Devotional }) {
|
||||
return (
|
||||
<article className="space-y-4">
|
||||
<header className="space-y-1">
|
||||
<p className="text-sm font-semibold uppercase tracking-wide text-brand-text">{dayName(d.date)}</p>
|
||||
<h1 className="cca-h1">{d.title}</h1>
|
||||
{d.author && <p className="cca-muted">{d.author}</p>}
|
||||
</header>
|
||||
<section className="cca-card space-y-3 bg-brand-tint" aria-labelledby="passage">
|
||||
<h2 id="passage" className="flex items-center gap-2 font-semibold"><BookOpen className="h-4 w-4" aria-hidden />{d.passage.reference} <span className="font-normal text-gray-700">({d.passage.translationName})</span></h2>
|
||||
<blockquote className="whitespace-pre-line font-heading text-lg leading-relaxed">{d.passage.text}</blockquote>
|
||||
<a href={d.passage.youVersionUrl} className="cca-btn-quiet" target="_blank" rel="noopener noreferrer">
|
||||
Read in YouVersion<ExternalLink className="h-4 w-4" aria-hidden />
|
||||
</a>
|
||||
<p className="text-xs text-gray-600">{d.passage.copyright}</p>
|
||||
{d.passage.disclaimer && <p className="text-xs text-gray-600">{d.passage.disclaimer}</p>}
|
||||
</section>
|
||||
<Markdown>{d.body}</Markdown>
|
||||
{d.prayer && (
|
||||
<section className="cca-card space-y-1" aria-labelledby="prayer">
|
||||
<h2 id="prayer" className="font-semibold">Prayer</h2>
|
||||
<p className="whitespace-pre-line italic">{d.prayer}</p>
|
||||
</section>
|
||||
)}
|
||||
<nav className="flex flex-wrap gap-x-4 gap-y-2 text-sm font-semibold text-brand-text" aria-label="More devotionals">
|
||||
<Link href={`/devotional/archive?month=${d.date.slice(0, 7)}`} className="underline-offset-4 hover:underline">The archive</Link>
|
||||
<Link href="/acknowledgements" className="underline-offset-4 hover:underline">Acknowledgements</Link>
|
||||
</nav>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { signInHref } from "@/lib/links";
|
||||
|
||||
/** What a members-only page shows to someone signed out. */
|
||||
export function SignInFor({ what, returnTo }: { what: string; returnTo: string }) {
|
||||
return (
|
||||
<section className="cca-card space-y-3">
|
||||
<p>This {what} is for the church's members. Sign in to read it.</p>
|
||||
<a href={signInHref(returnTo)} className="cca-btn">Sign in</a>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { loadApp, loadMe, type AppModule, type Role } from "./load";
|
||||
|
||||
const FULL: Role[] = ["owner", "church_admin"];
|
||||
|
||||
/**
|
||||
* An admin page's gate (APP-1.0-PLAN §10): one of `roles` (or Owner / Church admin) with a 2FA
|
||||
* sign-in, else the dashboard (which explains); "not found" while the module is off.
|
||||
*/
|
||||
export async function requireAdmin(roles: Role[], module?: AppModule) {
|
||||
const [me, app] = await Promise.all([loadMe(), loadApp()]);
|
||||
if (!me || !me.mfa || !me.member.roles.some((r) => FULL.includes(r) || roles.includes(r))) redirect("/admin");
|
||||
if (module && !app.modules.includes(module)) notFound();
|
||||
return { me, app };
|
||||
}
|
||||
|
||||
/** Today in the church's timezone (YYYY-MM-DD). */
|
||||
export const churchToday = (tz: string) => new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date());
|
||||
@@ -0,0 +1,69 @@
|
||||
/** Announcements, devotionals and events: shapes and formatting (backend/src/content, events). Server and client. */
|
||||
import type { CrosscodeEvent } from "@crosscode/contracts";
|
||||
|
||||
export type Announcement = {
|
||||
slug: string;
|
||||
title: string;
|
||||
body: string;
|
||||
imageUrl: string | null;
|
||||
button: { label: string; url: string } | null;
|
||||
campus: string | null;
|
||||
membersOnly: boolean;
|
||||
pinned: boolean;
|
||||
publishedAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type Devotional = {
|
||||
id: string;
|
||||
date: string;
|
||||
source: "crosscode" | "church";
|
||||
title: string;
|
||||
passage: { reference: string; text: string; translation: string; translationName: string; copyright: string; disclaimer: string | null; youVersionUrl: string };
|
||||
body: string;
|
||||
prayer: string | null;
|
||||
author: string | null;
|
||||
membersOnly: boolean;
|
||||
updatedAt: string;
|
||||
/** Only on "today": false when it's the most recent of an earlier day. */
|
||||
today?: boolean;
|
||||
};
|
||||
|
||||
export type EventItem = {
|
||||
key: string;
|
||||
source: "app" | "events" | "website";
|
||||
title: string;
|
||||
startsAt: string;
|
||||
endsAt: string;
|
||||
allDay: boolean;
|
||||
timezone: string;
|
||||
location: string | null;
|
||||
summary: string | null;
|
||||
description: string | null;
|
||||
imageUrl: string | null;
|
||||
cancelled: boolean;
|
||||
registration: { label: string; url: string } | null;
|
||||
canonical: string | null;
|
||||
crosscode?: CrosscodeEvent;
|
||||
};
|
||||
|
||||
/** "Saturday 12 December, 09:00–15:00" (or across days, or all day), in the event's timezone. */
|
||||
export function eventWhen(e: Pick<EventItem, "startsAt" | "endsAt" | "allDay" | "timezone">): string {
|
||||
const day = (iso: string) => new Intl.DateTimeFormat("en-ZA", { timeZone: e.timezone, weekday: "long", day: "numeric", month: "long" }).format(new Date(iso));
|
||||
const time = (iso: string) => new Intl.DateTimeFormat("en-GB", { timeZone: e.timezone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(new Date(iso));
|
||||
const sameDay = day(e.startsAt) === day(e.endsAt);
|
||||
if (e.allDay) return sameDay ? day(e.startsAt) : `${day(e.startsAt)} – ${day(e.endsAt)}`;
|
||||
return sameDay ? `${day(e.startsAt)}, ${time(e.startsAt)}–${time(e.endsAt)}` : `${day(e.startsAt)}, ${time(e.startsAt)} – ${day(e.endsAt)}, ${time(e.endsAt)}`;
|
||||
}
|
||||
|
||||
/** The date tile: "12" and "DEC". */
|
||||
export function dateTile(iso: string, tz: string): { day: string; month: string } {
|
||||
const d = new Date(iso);
|
||||
return {
|
||||
day: new Intl.DateTimeFormat("en-ZA", { timeZone: tz, day: "numeric" }).format(d),
|
||||
month: new Intl.DateTimeFormat("en-ZA", { timeZone: tz, month: "short" }).format(d).toUpperCase(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Plain text from markdown, for a meta description or a card's summary. */
|
||||
export const plain = (md: string) => md.replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[#*_>`~-]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
@@ -0,0 +1,25 @@
|
||||
import { cookies } from "next/headers";
|
||||
import type { Announcement, Devotional, EventItem } from "./content";
|
||||
import { api, SESSION_COOKIE } from "./load";
|
||||
import { backendGet } from "./prayerServer";
|
||||
|
||||
/** Server-side loaders, with the member's session so members-only content shows to them. */
|
||||
export const loadAnnouncements = async (take?: number) => ((await backendGet<{ announcements: Announcement[] }>("/api/v1/announcements"))?.announcements ?? []).slice(0, take);
|
||||
export const loadToday = async () => (await backendGet<{ devotional: Devotional | null }>("/api/v1/devotionals/today"))?.devotional ?? null;
|
||||
export const loadEvents = async (take?: number) => ((await backendGet<{ events: EventItem[] }>("/api/v1/events"))?.events ?? []).slice(0, take);
|
||||
|
||||
/**
|
||||
* One item by its address: the item, `"signin"` when it's for members only and nobody is signed in,
|
||||
* or null when there's none. A backend 401 is the members-only answer.
|
||||
*/
|
||||
export async function loadOne<T>(path: string, key: string): Promise<T | "signin" | null> {
|
||||
const session = (await cookies()).get(SESSION_COOKIE)?.value;
|
||||
try {
|
||||
const res = await fetch(`${api}${path}`, { headers: session ? { Cookie: `${SESSION_COOKIE}=${encodeURIComponent(session)}` } : {}, cache: "no-store" });
|
||||
if (res.status === 401) return "signin";
|
||||
if (!res.ok) return null;
|
||||
return ((await res.json()) as Record<string, T>)[key] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export type Church = {
|
||||
timezone: string;
|
||||
locale: string;
|
||||
branding: { logoUrl: string | null; iconUrl: string | null; colours: { primary: string; accent: string | null } };
|
||||
campuses: { slug: string; name: string }[];
|
||||
serviceTimes: { day: string; time: string; label: string | null }[];
|
||||
contact: {
|
||||
email: string | null;
|
||||
@@ -33,6 +34,8 @@ export type AppInfo = {
|
||||
style: { fontPairing: string; corners: string };
|
||||
modules: AppModule[];
|
||||
timezone: string;
|
||||
/** The App's own address, for canonicals, JSON-LD and the sitemap. */
|
||||
url: string;
|
||||
};
|
||||
|
||||
const FALLBACK: AppInfo = {
|
||||
@@ -42,6 +45,7 @@ const FALLBACK: AppInfo = {
|
||||
style: { fontPairing: "warm", corners: "soft" },
|
||||
modules: ["house-of-prayer", "prayer-requests", "announcements", "devotionals", "events"],
|
||||
timezone: "Africa/Johannesburg",
|
||||
url: process.env.APP_URL || "http://localhost:3400",
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Cuts text at a word to `max` characters, with an ellipsis when it was cut (as @crosscode/seo's). */
|
||||
export function truncate(text: string, max: number): string {
|
||||
const clean = text.replace(/\s+/g, " ").trim();
|
||||
if (clean.length <= max) return clean;
|
||||
const cut = clean.slice(0, max - 1);
|
||||
const space = cut.lastIndexOf(" ");
|
||||
return `${(space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,.;:–-]+$/, "")}…`;
|
||||
}
|
||||
Reference in New Issue
Block a user