app: the admin's side menu and pages: members, settings, jobs, logs, share (APP-1.0-PLAN §10)

Every admin page in one frame, as the Website's and Events' admins (decision
9): a bar across the top, a white side menu in groups (only what the roles
and modules allow), a drawer on a phone. The dashboard has the setup
checklist, the stat cards, what's waiting, this week on the prayer wall and
recent changes. New: Members and roles, Settings (modules, the licence and
active members, each module's settings), Background jobs, Audit and access
logs, and Share the App with a printable A4 poster and its QR code (drawn on
the server with qrcode). Role names in lib/roles.ts for client components.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 14:42:31 +02:00
co-authored by Claude Opus 5.5
parent f4cf5587be
commit 13eaaffb95
23 changed files with 881 additions and 90 deletions
@@ -1,5 +1,4 @@
import type { Metadata } from "next";
import Link from "next/link";
import { AdminAnnouncements } from "@/components/admin/AdminAnnouncements";
import { requireAdmin } from "@/lib/admin";
@@ -9,12 +8,11 @@ export const metadata: Metadata = { title: "Announcements · Admin", robots: { i
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 className="space-y-6">
<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>
<h1 className="text-2xl font-semibold">Announcements</h1>
</div>
<AdminAnnouncements timezone={app.timezone} campuses={(app.church?.campuses ?? []).map((c) => ({ slug: c.slug, name: c.name }))} />
</main>
</div>
);
}
@@ -0,0 +1,16 @@
import type { Metadata } from "next";
import { AdminLogs } from "@/components/admin/AdminLogs";
import { requireAdmin } from "@/lib/admin";
export const metadata: Metadata = { title: "Audit and access logs · Admin", robots: { index: false, follow: false } };
/** The audit log and the access log (APP-1.0-PLAN §10): Owner and Church admin. */
export default async function AuditPage() {
const { app } = await requireAdmin([]);
return (
<div className="space-y-6">
<h1 className="text-2xl font-semibold">Audit and access logs</h1>
<AdminLogs timezone={app.timezone} />
</div>
);
}
@@ -1,5 +1,4 @@
import type { Metadata } from "next";
import Link from "next/link";
import { AdminDevotionals } from "@/components/admin/AdminDevotionals";
import { churchToday, requireAdmin } from "@/lib/admin";
@@ -9,12 +8,11 @@ export const metadata: Metadata = { title: "Devotionals · Admin", robots: { ind
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 className="space-y-6">
<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>
<h1 className="text-2xl font-semibold">Devotionals</h1>
</div>
<AdminDevotionals today={churchToday(app.timezone)} />
</main>
</div>
);
}
@@ -1,5 +1,4 @@
import type { Metadata } from "next";
import Link from "next/link";
import { AdminEvents } from "@/components/admin/AdminEvents";
import { churchToday, requireAdmin } from "@/lib/admin";
@@ -9,12 +8,11 @@ export const metadata: Metadata = { title: "Events · Admin", robots: { index: f
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 className="space-y-6">
<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>
<h1 className="text-2xl font-semibold">Events</h1>
</div>
<AdminEvents today={churchToday(app.timezone)} />
</main>
</div>
);
}
@@ -0,0 +1,16 @@
import type { Metadata } from "next";
import { AdminJobs } from "@/components/admin/AdminJobs";
import { requireAdmin } from "@/lib/admin";
export const metadata: Metadata = { title: "Background jobs · Admin", robots: { index: false, follow: false } };
/** Settings → Background jobs (APP-1.0-PLAN §10): Owner and Church admin. */
export default async function JobsPage() {
await requireAdmin([]);
return (
<div className="space-y-6">
<h1 className="text-2xl font-semibold">Background jobs</h1>
<AdminJobs />
</div>
);
}
@@ -0,0 +1,21 @@
import type { Metadata } from "next";
import { AdminShell } from "@/components/admin/AdminShell";
import { loadApp, loadMe } from "@/lib/load";
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
export const dynamic = "force-dynamic";
/**
* Every admin page (APP-1.0-PLAN §10): the side menu for someone whose sign-in may use a role (one
* above Member, with 2FA). Anyone else sees the page on its own: the dashboard explains how to get
* in, and every other page sends them there.
*/
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const [me, app] = await Promise.all([loadMe(), loadApp()]);
if (!me || !me.activeRoles.length) return <main className="mx-auto max-w-4xl space-y-6 px-4 py-10">{children}</main>;
return (
<AdminShell name={me.member.name} church={app.shortName} roles={me.activeRoles} modules={app.modules}>
{children}
</AdminShell>
);
}
@@ -0,0 +1,16 @@
import type { Metadata } from "next";
import { AdminMembers } from "@/components/admin/AdminMembers";
import { requireAdmin } from "@/lib/admin";
export const metadata: Metadata = { title: "Members and roles · Admin", robots: { index: false, follow: false } };
/** Members and roles (APP-1.0-PLAN §10): Owner and Church admin. */
export default async function MembersPage() {
const { me, app } = await requireAdmin([]);
return (
<div className="space-y-6">
<h1 className="text-2xl font-semibold">Members and roles</h1>
<AdminMembers meId={me.member.id} isOwner={me.member.roles.includes("owner")} timezone={app.timezone} />
</div>
);
}
@@ -1,5 +1,4 @@
import type { Metadata } from "next";
import Link from "next/link";
import { AdminMessaging } from "@/components/admin/AdminMessaging";
import { requireAdmin } from "@/lib/admin";
@@ -9,12 +8,11 @@ export const metadata: Metadata = { title: "Email and WhatsApp · Admin", robots
export default async function AdminMessagingPage() {
const { app } = await requireAdmin([]);
return (
<main className="mx-auto max-w-5xl space-y-6 px-4 py-10">
<div className="space-y-6">
<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">Email and WhatsApp</h1>
<h1 className="text-2xl font-semibold">Email and WhatsApp</h1>
</div>
<AdminMessaging timezone={app.timezone} />
</main>
</div>
);
}
+114 -50
View File
@@ -1,15 +1,23 @@
import type { Metadata } from "next";
import { cookies } from "next/headers";
import Link from "next/link";
import { CheckCircle2, Circle } from "lucide-react";
import { api, loadMe, ROLE_NAMES, SESSION_COOKIE, signInHref } from "@/lib/load";
import { dayName, hhmm } from "@/lib/prayer";
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
/** GET /api/v1/admin/overview (backend/src/admin/routes.ts). */
type Overview = {
activeMembers90d: { count: number; band: string };
modules: string[];
hub: { connected: boolean; state: string; lastHeartbeatAt: string | null };
accounts: { url: string; connectedAt: string } | null;
timezone: string;
checklist: { items: { key: string; label: string; done: boolean; href: string | null }[]; done: boolean } | null;
week: { slotMinutes: number; days: { date: string; covered: number; total: number; gaps: number[] }[] } | null;
waiting: { requests: number | null; escalated: number | null; testimonies: number | null };
recent: { at: string; who: string; action: string; detail: string | null }[];
};
const MODULE_NAMES: Record<string, string> = {
@@ -32,46 +40,50 @@ async function loadOverview(): Promise<Overview | null> {
return null;
}
function Page({ children }: { children: React.ReactNode }) {
return <main className="mx-auto max-w-4xl space-y-6 px-4 py-10">{children}</main>;
/** "02:00, 03:00 and 4 more" for a day's open slots. */
function gapList(gaps: number[]) {
if (!gaps.length) return "every slot covered";
const shown = gaps.slice(0, 3).map(hhmm).join(", ");
return gaps.length > 3 ? `open: ${shown} and ${gaps.length - 3} more` : `open: ${shown}`;
}
/**
* The admin's dashboard (APP-1.0-PLAN §10; the Website's and Events' layout, decision 9). For now
* the foundation: who's using the App, the modules on, and the links to the Hub and Accounts. The
* side menu, setup checklist and each module's pages come with the modules.
* The admin's dashboard (APP-1.0-PLAN §10; the Website's and Events' layout, decision 9): who's
* using the App, the setup checklist (Owner, Church admin), this week's coverage and gaps and what
* waits for the prayer team, and the latest changes. Someone who can't use the admin yet is told why.
*/
export default async function Admin() {
const me = await loadMe();
if (!me) {
return (
<Page>
<>
<h1 className="text-2xl font-semibold">The App&apos;s admin</h1>
<a href={signInHref("/admin", true)} className="cca-btn">Sign in</a>
</Page>
</>
);
}
if (!me.member.roles.length) {
return (
<Page>
<>
<h1 className="text-2xl font-semibold">No access to the admin</h1>
<p className="text-gray-600">Your account doesn&apos;t have a role in the App. Ask the App&apos;s Owner or a Church admin if you need one.</p>
<Link href="/" className="cca-btn-quiet">Back to the App</Link>
</Page>
</>
);
}
if (!me.mfa) {
return (
<Page>
<>
<h1 className="text-2xl font-semibold">Two-step sign-in needed</h1>
<p className="text-gray-600">Every role in the App needs a sign-in with your second step. Turn on two-step sign-in in your church account if it isn&apos;t yet, then sign in again.</p>
<a href={signInHref("/admin", true)} className="cca-btn">Sign in with two-step</a>
</Page>
</>
);
}
const o = await loadOverview();
const when = (iso: string) => new Intl.DateTimeFormat("en-ZA", { timeZone: o?.timezone ?? "Africa/Johannesburg", dateStyle: "medium", timeStyle: "short" }).format(new Date(iso));
return (
<Page>
<>
<div>
<h1 className="text-2xl font-semibold">Dashboard</h1>
<p className="text-sm text-gray-600">{me.member.name} · {me.member.roles.map((r) => ROLE_NAMES[r]).join(", ")}</p>
@@ -79,44 +91,96 @@ export default async function Admin() {
{!o ? (
<p className="text-gray-600">The dashboard can&apos;t be loaded right now. Please try again in a minute.</p>
) : (
<div className="grid gap-4 sm:grid-cols-3">
<section className="cca-card">
<h2 className="text-sm text-gray-600">Active members (90 days)</h2>
<p className="mt-1 text-3xl font-semibold">{o.activeMembers90d.count}</p>
<p className="text-sm text-gray-600">Band {o.activeMembers90d.band}</p>
</section>
<section className="cca-card">
<h2 className="text-sm text-gray-600">Modules on</h2>
<ul className="mt-1 text-sm">{o.modules.map((m) => <li key={m}>{MODULE_NAMES[m] ?? m}</li>)}</ul>
</section>
<section className="cca-card">
<h2 className="text-sm text-gray-600">Connections</h2>
<p className="mt-1 text-sm">Cross Code Hub: {o.hub.connected ? `connected (${o.hub.state})` : "not connected"}</p>
<p className="text-sm">Accounts: {o.accounts ? "linked" : "not linked yet"}</p>
</section>
</div>
<>
{o.checklist && !o.checklist.done && (
<section className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm" aria-labelledby="setup">
<h2 id="setup" className="text-lg font-semibold">Get the App ready</h2>
<p className="text-sm text-gray-600">Before you tell the church about it.</p>
<ul className="mt-3 space-y-1">
{o.checklist.items.map((i) => {
const Icon = i.done ? CheckCircle2 : Circle;
const label = <><Icon className={`h-5 w-5 shrink-0 ${i.done ? "text-green-700" : "text-gray-400"}`} aria-hidden /><span className={i.done ? "text-gray-500 line-through" : ""}>{i.label}</span><span className="sr-only">{i.done ? " (done)" : " (to do)"}</span></>;
return (
<li key={i.key}>
{i.href ? (
i.href.startsWith("/") ? <Link href={i.href} className="flex min-h-10 items-center gap-3 rounded-md px-2 hover:bg-gray-50">{label}</Link>
: <a href={i.href} className="flex min-h-10 items-center gap-3 rounded-md px-2 hover:bg-gray-50">{label}</a>
) : <span className="flex min-h-10 items-center gap-3 px-2">{label}</span>}
</li>
);
})}
</ul>
</section>
)}
<div className="grid gap-4 sm:grid-cols-3">
<section className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm">
<h2 className="text-sm text-gray-600">Active members (90 days)</h2>
<p className="mt-1 text-3xl font-semibold">{o.activeMembers90d.count}</p>
<p className="text-sm text-gray-600">Band {o.activeMembers90d.band}</p>
</section>
<section className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm">
<h2 className="text-sm text-gray-600">Modules on</h2>
<ul className="mt-1 text-sm">{o.modules.map((m) => <li key={m}>{MODULE_NAMES[m] ?? m}</li>)}</ul>
</section>
<section className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm">
<h2 className="text-sm text-gray-600">Connections</h2>
<p className="mt-1 text-sm">Cross Code Hub: {o.hub.connected ? `connected (${o.hub.state})` : "not connected"}</p>
<p className="text-sm">Accounts: {o.accounts ? "linked" : "not linked yet"}</p>
</section>
</div>
{(o.waiting.requests !== null || o.waiting.testimonies !== null || o.waiting.escalated !== null) && (
<div className="grid gap-4 sm:grid-cols-3">
{o.waiting.requests !== null && (
<Link href="/admin/requests" className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm hover:border-gray-300">
<h2 className="text-sm text-gray-600">Requests waiting for approval</h2>
<p className={`mt-1 text-3xl font-semibold ${o.waiting.requests ? "text-amber-700" : ""}`}>{o.waiting.requests}</p>
</Link>
)}
{o.waiting.testimonies !== null && (
<Link href="/admin/prayer" className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm hover:border-gray-300">
<h2 className="text-sm text-gray-600">Testimonies waiting</h2>
<p className={`mt-1 text-3xl font-semibold ${o.waiting.testimonies ? "text-amber-700" : ""}`}>{o.waiting.testimonies}</p>
</Link>
)}
{o.waiting.escalated !== null && (
<Link href="/admin/requests?view=escalated" className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm hover:border-gray-300">
<h2 className="text-sm text-gray-600">Escalated requests open</h2>
<p className={`mt-1 text-3xl font-semibold ${o.waiting.escalated ? "text-red-700" : ""}`}>{o.waiting.escalated}</p>
</Link>
)}
</div>
)}
{o.week && (
<section className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm" aria-labelledby="week">
<div className="flex items-end justify-between"><h2 id="week" className="text-lg font-semibold">This week on the prayer wall</h2><Link href="/admin/prayer" className="text-sm font-semibold underline-offset-4 hover:underline">Open</Link></div>
<ul className="mt-3 divide-y divide-gray-100">
{o.week.days.map((d) => (
<li key={d.date} className="flex flex-wrap items-center gap-x-4 gap-y-1 py-2 text-sm">
<span className="w-36 font-medium">{dayName(d.date, { weekday: "short", day: "numeric", month: "short" })}</span>
<span className="flex min-w-40 flex-1 items-center gap-2">
<span className="h-2 flex-1 overflow-hidden rounded-full bg-gray-100" aria-hidden><span className="block h-full rounded-full bg-brand" style={{ width: `${d.total ? Math.round((d.covered / d.total) * 100) : 0}%` }} /></span>
<span className="whitespace-nowrap">{d.covered} of {d.total}</span>
</span>
<span className="w-full text-gray-600 sm:w-auto">{gapList(d.gaps)}</span>
</li>
))}
</ul>
</section>
)}
{o.recent.length > 0 && (
<section className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm" aria-labelledby="recent">
<div className="flex items-end justify-between"><h2 id="recent" className="text-lg font-semibold">Recent changes</h2><Link href="/admin/audit" className="text-sm font-semibold underline-offset-4 hover:underline">Audit log</Link></div>
<ul className="mt-3 space-y-2 text-sm">
{o.recent.map((e, i) => <li key={i}><span className="font-medium">{e.who}</span> {e.action.charAt(0).toLowerCase() + e.action.slice(1)}{e.detail ? `: ${e.detail}` : ""} <span className="text-gray-500">· {when(e.at)}</span></li>)}
</ul>
</section>
)}
</>
)}
{o?.modules.includes("house-of-prayer") && me.activeRoles.some((r) => ["owner", "church_admin", "prayer_coordinator"].includes(r)) && (
<Link href="/admin/prayer" className="cca-card flex items-center justify-between font-semibold">
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>
</Link>
)}
{me.activeRoles.some((r) => r === "owner" || r === "church_admin") && (
<Link href="/admin/messaging" className="cca-card flex items-center justify-between font-semibold">
Email and WhatsApp: what the App sends with, Send a test, messages not sent<span aria-hidden>›</span>
</Link>
)}
<Link href="/" className="cca-btn-quiet">Back to the App</Link>
</Page>
</>
);
}
@@ -20,20 +20,19 @@ export default async function AdminPrayerPage() {
if (!me || !me.mfa || !me.member.roles.some((r) => CAN.includes(r))) redirect("/admin");
if (!app.modules.includes("house-of-prayer")) {
return (
<main className="mx-auto max-w-5xl space-y-4 px-4 py-10">
<div className="space-y-4">
<h1 className="text-2xl font-semibold">House of Prayer</h1>
<p className="text-gray-600">The House of Prayer is switched off. An Owner or Church admin can switch it on in Settings → Modules.</p>
<Link href="/admin" className="cca-btn-quiet">Back to the dashboard</Link>
</main>
</div>
);
}
return (
<main className="mx-auto max-w-5xl space-y-6 px-4 py-10">
<div className="space-y-6">
<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">House of Prayer</h1>
<h1 className="text-2xl font-semibold">House of Prayer</h1>
</div>
<AdminPrayer today={localToday(app.timezone)} />
</main>
</div>
);
}
@@ -1,5 +1,4 @@
import type { Metadata } from "next";
import Link from "next/link";
import { redirect } from "next/navigation";
import { AdminRequests } from "@/components/requests/AdminRequests";
import { loadApp, loadMe } from "@/lib/load";
@@ -14,16 +13,15 @@ export default async function AdminRequestsPage({ searchParams }: { searchParams
if (!me || !me.mfa || !me.member.roles.some((r) => [...COORDINATORS, "pastoral_care"].includes(r))) redirect("/admin");
const coordinator = me.member.roles.some((r) => COORDINATORS.includes(r));
return (
<main className="mx-auto max-w-5xl space-y-6 px-4 py-10">
<div className="space-y-6">
<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">Prayer requests</h1>
<h1 className="text-2xl font-semibold">Prayer requests</h1>
</div>
{app.modules.includes("prayer-requests") ? (
<AdminRequests coordinator={coordinator} initialView={(["queue", "open", "escalated", "closed", "settings"].includes(q.view ?? "") ? q.view : "queue") as "queue"} />
) : (
<p className="text-gray-600">Prayer requests are switched off. An Owner or Church admin can switch them on in Settings → Modules.</p>
)}
</main>
</div>
);
}
@@ -0,0 +1,28 @@
import type { Metadata } from "next";
import { AdminSettings } from "@/components/admin/AdminSettings";
import { requireAdmin } from "@/lib/admin";
import { backendGet } from "@/lib/prayerServer";
export const metadata: Metadata = { title: "Settings · Admin", robots: { index: false, follow: false } };
type Overview = {
activeMembers90d: { count: number; band: string };
modules: string[];
hub: { connected: boolean; state: string; endsAt: string | null; daysLeft: number | null };
};
/** Settings (APP-1.0-PLAN §10): modules, the licence, and each module's settings. Owner and Church admin. */
export default async function SettingsPage() {
const { me, app } = await requireAdmin([]);
const o = await backendGet<Overview>("/api/v1/admin/overview");
return (
<div className="space-y-6">
<h1 className="text-2xl font-semibold">Settings</h1>
{o ? (
<AdminSettings initialModules={o.modules} activeMembers={o.activeMembers90d} licence={o.hub} accountsUrl={app.church?.links.accounts ?? null} isOwner={me.member.roles.includes("owner")} timezone={app.timezone} />
) : (
<p className="text-gray-600">The settings can&apos;t be loaded right now. Please try again in a minute.</p>
)}
</div>
);
}
@@ -0,0 +1,50 @@
import type { Metadata } from "next";
import QRCode from "qrcode";
import { ShareActions } from "@/components/admin/ShareActions";
import { requireAdmin } from "@/lib/admin";
import { backendGet } from "@/lib/prayerServer";
export const metadata: Metadata = { title: "Share the App · Admin", robots: { index: false, follow: false } };
/**
* Share the App (APP-1.0-PLAN §10, the setup checklist): its link, and a poster with a QR code to
* print for the church's notice board and screens. The QR code is drawn here, on the server, as
* SVG: nothing is sent anywhere to make it.
*/
export default async function SharePage() {
const { app } = await requireAdmin([]);
const share = await backendGet<{ url: string; name: string | null; sharedAt: string | null }>("/api/v1/admin/share");
const url = share?.url ?? app.url;
const link = `${url.replace(/\/+$/, "")}/?source=poster`;
const qr = await QRCode.toString(link, { type: "svg", margin: 1, errorCorrectionLevel: "M", color: { dark: "#111827", light: "#ffffff" } });
const name = share?.name ?? app.church?.name ?? app.shortName;
return (
<div className="space-y-6">
<div className="print:hidden">
<h1 className="text-2xl font-semibold">Share the App</h1>
<p className="text-sm text-gray-600">Tell the church once the prayer wall is set up: on Sunday, in the newsletter, on the screens. The poster prints on one A4 page.</p>
</div>
<section className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm print:hidden">
<h2 className="text-lg font-semibold">The App&apos;s link</h2>
<p className="my-3 break-all font-mono text-sm">{url}</p>
<ShareActions url={url} sharedAt={share?.sharedAt ?? null} />
</section>
<section aria-label="The poster" className="mx-auto max-w-[180mm] rounded-lg border border-gray-200 bg-white p-10 text-center shadow-sm print:max-w-none print:border-0 print:p-0 print:shadow-none">
{app.church?.branding.logoUrl
? <img src={app.church.branding.logoUrl} alt={name} className="mx-auto mb-6 max-h-24 max-w-[60%] object-contain" />
: <p className="mb-6 font-heading text-3xl font-bold text-brand-text">{name}</p>}
<h2 className="font-heading text-4xl font-bold text-gray-900">Our church in your pocket</h2>
<p className="mx-auto mt-3 max-w-md text-lg text-gray-700">Pray with us around the clock, ask for prayer, and get the news, today&apos;s devotional and what&apos;s on.</p>
<div className="mx-auto my-8 w-64 [&_svg]:h-auto [&_svg]:w-full" role="img" aria-label={`A QR code for ${link}`} dangerouslySetInnerHTML={{ __html: qr }} />
<p className="text-lg font-semibold">Scan with your phone&apos;s camera, or go to</p>
<p className="break-all font-mono text-xl text-brand-text">{url.replace(/^https?:\/\//, "")}</p>
<ol className="mx-auto mt-8 max-w-md space-y-1 text-left text-gray-700">
<li><strong>1.</strong> Open the link.</li>
<li><strong>2.</strong> Android: tap <em>Install</em> or <em>Add to home screen</em>. iPhone: tap Share, then <em>Add to Home Screen</em>.</li>
<li><strong>3.</strong> Sign in with your church account to book your hour of prayer.</li>
</ol>
</section>
</div>
);
}
@@ -0,0 +1,89 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { adminCall, input, Notice, Panel, type Msg } from "./kit";
type Run = { state: string; startedOn: string | null; completedOn: string | null; output: unknown };
type Job = {
name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; envEnabled: boolean; envCron: string; defaultCron: string;
override: { enabled: boolean | null; cron: string | null }; nextRun: string | null; recent: Run[];
};
type Status = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: Job[] };
const MODE = { queue: "Running on the job queue", timers: "Running on timers in the App (the job queue isn't available)", off: "Switched off on the server (JOBS_ENABLED=false)" } as const;
/**
* Settings → Background jobs (APP-1.0-PLAN §10, as Accounts, Events and the Website): each job's
* switch and schedule, the last runs, and Run now. A choice here wins over the server's .env and
* takes effect straight away; "Use the server's" goes back to it.
*/
export function AdminJobs() {
const [s, setS] = useState<Status | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [crons, setCrons] = useState<Record<string, string>>({});
const [busy, setBusy] = useState<string | null>(null);
const load = useCallback(() => {
adminCall<Status>("GET", "/jobs").then((r) => {
if (!r.ok) return setMsg({ kind: "error", text: r.error });
setS(r.data);
setCrons(Object.fromEntries(r.data.jobs.map((j) => [j.name, j.cron])));
});
}, []);
useEffect(load, [load]);
const when = (iso: string | null) => (iso && s ? new Intl.DateTimeFormat("en-ZA", { timeZone: s.timezone, dateStyle: "short", timeStyle: "short" }).format(new Date(iso)) : "–");
async function change(name: string, body: { enabled?: boolean | null; cron?: string | null }, done: string) {
setBusy(name);
const r = await adminCall("PUT", `/jobs/${name}`, body);
setBusy(null);
setMsg(r.ok ? { kind: "ok", text: done } : { kind: "error", text: r.error });
if (r.ok) load();
}
async function run(name: string) {
setBusy(name);
const r = await adminCall<{ queued: boolean; output?: unknown }>("POST", `/jobs/${name}/run`, {});
setBusy(null);
setMsg(r.ok ? { kind: "ok", text: r.data.queued ? "Queued: it runs in a moment." : `Done: ${JSON.stringify(r.data.output ?? null)}` } : { kind: "error", text: r.error });
if (r.ok) load();
}
if (!s) return <Notice msg={msg} />;
return (
<div className="space-y-6">
<Notice msg={msg} />
<p className="text-sm text-gray-600">{MODE[s.mode]}. Times are in {s.timezone}. A schedule is a cron expression with five fields (minute hour day month weekday).</p>
{s.jobs.map((j) => {
const last = j.recent[0];
return (
<Panel key={j.name} title={j.label} aside={<span className={`rounded-full px-2 py-0.5 text-xs font-semibold ${j.enabled ? "bg-green-50 text-green-800" : "bg-gray-100 text-gray-600"}`}>{j.enabled ? "On" : "Off"}</span>}>
<div className="grid gap-4 text-sm sm:grid-cols-3">
<div>
<p className="text-gray-600">Next run</p><p className="font-medium">{when(j.nextRun)}</p>
<p className="mt-2 text-gray-600">Last run</p>
<p className={last?.state === "failed" ? "font-medium text-red-700" : "font-medium"}>{last ? `${when(last.completedOn ?? last.startedOn)} · ${last.state}` : "–"}</p>
</div>
<div>
<label className="block font-medium" htmlFor={`cron-${j.name}`}>Schedule</label>
<input id={`cron-${j.name}`} className={`${input} font-mono`} value={crons[j.name] ?? ""} onChange={(e) => setCrons({ ...crons, [j.name]: e.target.value })} />
<p className="mt-1 text-xs text-gray-500">{j.override.cron ? "Set here" : `The server's (${j.envCron})`}</p>
<div className="mt-2 flex flex-wrap gap-2">
<button type="button" className="cca-btn-quiet" disabled={busy === j.name || crons[j.name] === j.cron} onClick={() => change(j.name, { cron: crons[j.name] }, "Schedule saved.")}>Save</button>
{j.override.cron && <button type="button" className="cca-btn-quiet" disabled={busy === j.name} onClick={() => change(j.name, { cron: null }, "Back to the server's schedule.")}>Use the server&apos;s</button>}
</div>
</div>
<div className="flex flex-col items-start gap-2">
<button type="button" className="cca-btn" disabled={busy === j.name} onClick={() => run(j.name)}>{busy === j.name ? "Working…" : "Run now"}</button>
<button type="button" className="cca-btn-quiet" disabled={busy === j.name} onClick={() => change(j.name, { enabled: !j.enabled }, j.enabled ? "Switched off." : "Switched on.")}>{j.enabled ? "Switch off" : "Switch on"}</button>
{j.override.enabled !== null && <button type="button" className="text-xs underline" disabled={busy === j.name} onClick={() => change(j.name, { enabled: null }, "Back to the server's setting.")}>Use the server&apos;s setting ({j.envEnabled ? "on" : "off"})</button>}
</div>
</div>
{last?.state === "failed" && last.output != null && <p className="mt-3 rounded-md bg-red-50 p-3 text-sm text-red-800">{String((last.output as { message?: string })?.message ?? JSON.stringify(last.output))}</p>}
</Panel>
);
})}
</div>
);
}
@@ -0,0 +1,60 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { adminCall, Notice, Panel, type Msg } from "./kit";
type Entry = { at: string; who: string; action: string; detail: string | null; ip: string | null };
/**
* The audit log (who changed what) and the access log (who saw names on the prayer wall and in
* prayer requests), APP-1.0-PLAN §10: newest first, 100 at a time.
*/
export function AdminLogs({ timezone }: { timezone: string }) {
const [tab, setTab] = useState<"audit" | "access">("audit");
const [entries, setEntries] = useState<Entry[]>([]);
const [more, setMore] = useState(false);
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback((before?: string) => {
adminCall<{ entries: Entry[] }>("GET", `/${tab}${before ? `?before=${encodeURIComponent(before)}` : ""}`).then((r) => {
if (!r.ok) return setMsg({ kind: "error", text: r.error });
setEntries((old) => (before ? [...old, ...r.data.entries] : r.data.entries));
setMore(r.data.entries.length === 100);
});
}, [tab]);
useEffect(() => load(), [load]);
const when = (iso: string) => new Intl.DateTimeFormat("en-ZA", { timeZone: timezone, dateStyle: "medium", timeStyle: "short" }).format(new Date(iso));
return (
<div className="space-y-4">
<div role="tablist" aria-label="Logs" className="flex gap-2">
{(["audit", "access"] as const).map((t) => (
<button key={t} type="button" role="tab" aria-selected={tab === t} onClick={() => { setTab(t); setEntries([]); }}
className={`rounded-full px-4 py-1.5 text-sm font-semibold ${tab === t ? "bg-brand text-brand-on" : "border border-gray-300 bg-white"}`}>{t === "audit" ? "Audit log" : "Access log"}</button>
))}
</div>
<Notice msg={msg} />
<Panel title={tab === "audit" ? "Who changed what" : "Who saw names"}>
<p className="mb-3 text-sm text-gray-600">{tab === "audit" ? "Every change in the admin, and sign-ins." : "Every time someone saw who prays when, testimonies with names or prayer requests with their senders. Names are never shown without this record."}</p>
{entries.length === 0 ? <p className="text-sm text-gray-600">Nothing yet.</p> : (
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead><tr className="text-gray-600"><th className="py-1 pr-3 font-medium">When</th><th className="py-1 pr-3 font-medium">Who</th><th className="py-1 pr-3 font-medium">What</th><th className="py-1 font-medium">From</th></tr></thead>
<tbody>
{entries.map((e, i) => (
<tr key={i} className="border-t border-gray-100 align-top">
<td className="whitespace-nowrap py-1.5 pr-3">{when(e.at)}</td>
<td className="py-1.5 pr-3">{e.who}</td>
<td className="py-1.5 pr-3">{e.action}{e.detail ? <span className="text-gray-500"> · {e.detail}</span> : null}</td>
<td className="py-1.5 text-gray-500">{e.ip ?? ""}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{more && <button type="button" className="cca-btn-quiet mt-4" onClick={() => load(entries.at(-1)?.at)}>Older</button>}
</Panel>
</div>
);
}
@@ -0,0 +1,156 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { ROLE_NAMES, type Role } from "@/lib/roles";
import { adminCall, Field, input, Notice, Panel, type Msg } from "./kit";
type Member = { id: string; name: string; email: string; roles: Role[]; hasPhone: boolean; whatsappStopped: boolean; lastActiveAt: string | null; lastSignInAt: string | null; since: string };
type List = { total: number; page: number; pageSize: number; roleCounts: Record<Role, number>; members: Member[] };
const ROLES = Object.keys(ROLE_NAMES) as Role[];
const ROLE_HINTS: Record<Role, string> = {
owner: "Everything, including roles and the licence",
church_admin: "Everything but the licence and Owners",
content_admin: "Announcements and events",
devotional_writer: "Devotionals, the CSV import, where they come from",
prayer_coordinator: "The prayer wall with names, campaigns, testimonies, prayer requests",
pastoral_care: "Escalated prayer requests and safeguarding",
};
function RolePicker({ value, onChange, mayOwner, idPrefix }: { value: Role[]; onChange: (r: Role[]) => void; mayOwner: boolean; idPrefix: string }) {
return (
<fieldset className="space-y-1">
<legend className="text-sm font-medium">Roles</legend>
{ROLES.filter((r) => mayOwner || r !== "owner").map((r) => (
<label key={r} htmlFor={`${idPrefix}-${r}`} className="flex items-start gap-2 text-sm">
<input id={`${idPrefix}-${r}`} type="checkbox" className="mt-1" checked={value.includes(r)} onChange={(e) => onChange(e.target.checked ? [...value, r] : value.filter((x) => x !== r))} />
<span><span className="font-medium">{ROLE_NAMES[r]}</span> <span className="text-gray-500">· {ROLE_HINTS[r]}</span></span>
</label>
))}
</fieldset>
);
}
/**
* Members and roles (APP-1.0-PLAN §10): everyone who uses the App signed in, searched by name or
* email; roles given and taken here (every one needs a 2FA sign-in), or someone added by email
* with a role (Accounts makes them an account if they have none). Only an Owner makes an Owner.
*/
export function AdminMembers({ meId, isOwner, timezone }: { meId: string; isOwner: boolean; timezone: string }) {
const [q, setQ] = useState("");
const [role, setRole] = useState("");
const [page, setPage] = useState(1);
const [list, setList] = useState<List | null>(null);
const [editing, setEditing] = useState<{ id: string; roles: Role[] } | null>(null);
const [adding, setAdding] = useState<{ name: string; email: string; roles: Role[] } | null>(null);
const [errors, setErrors] = useState<Record<string, string>>({});
const [msg, setMsg] = useState<Msg>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(() => {
const qs = new URLSearchParams({ page: String(page), ...(q.trim() ? { q: q.trim() } : {}), ...(role ? { role } : {}) });
adminCall<List>("GET", `/members?${qs}`).then((r) => (r.ok ? setList(r.data) : setMsg({ kind: "error", text: r.error })));
}, [page, q, role]);
useEffect(() => {
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
const day = (iso: string | null) => (iso ? new Intl.DateTimeFormat("en-ZA", { timeZone: timezone, dateStyle: "medium" }).format(new Date(iso)) : "never");
async function saveRoles() {
if (!editing) return;
setBusy(true);
const r = await adminCall<{ roles: Role[] }>("PUT", `/members/${editing.id}/roles`, { roles: editing.roles });
setBusy(false);
if (!r.ok) return setMsg({ kind: "error", text: r.error });
setEditing(null);
setMsg({ kind: "ok", text: "Roles saved. A new role works from their next sign-in with their second step." });
load();
}
async function add(e: React.FormEvent) {
e.preventDefault();
if (!adding) return;
setBusy(true);
setErrors({});
const r = await adminCall<{ newAccount: boolean; emailSent: boolean | null; alreadyMember: boolean }>("POST", "/members", adding);
setBusy(false);
if (!r.ok) {
setErrors(r.fields ?? {});
return setMsg({ kind: "error", text: r.error });
}
setAdding(null);
setMsg({ kind: "ok", text: r.data.newAccount ? `Added. ${r.data.emailSent ? "Accounts emailed them to choose a password." : "They need an account at Accounts: their email couldn't be sent."} They need two-step sign-in for the admin.` : "Added. They sign in with their church account, with their second step." });
load();
}
const counts = list?.roleCounts;
return (
<div className="space-y-6">
<Notice msg={msg} />
<Panel title="Members" aside={!adding && <button type="button" className="cca-btn" onClick={() => setAdding({ name: "", email: "", roles: ["prayer_coordinator"] })}>Add someone with a role</button>}>
{adding && (
<form onSubmit={add} className="mb-6 space-y-3 rounded-md border border-gray-200 bg-gray-50 p-4">
<p className="text-sm text-gray-600">For someone who hasn&apos;t used the App yet. Everyone who signs in is a Member already; give them a role from the list below.</p>
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Name" error={errors.name}><input className={input} value={adding.name} onChange={(e) => setAdding({ ...adding, name: e.target.value })} required maxLength={200} /></Field>
<Field label="Email" error={errors.email}><input type="email" className={input} value={adding.email} onChange={(e) => setAdding({ ...adding, email: e.target.value })} required maxLength={254} /></Field>
</div>
<RolePicker value={adding.roles} onChange={(roles) => setAdding({ ...adding, roles })} mayOwner={isOwner} idPrefix="add" />
{errors.roles && <p className="text-xs text-red-700">{errors.roles}</p>}
<div className="flex gap-2"><button type="submit" className="cca-btn" disabled={busy}>Add</button><button type="button" className="cca-btn-quiet" onClick={() => setAdding(null)}>Cancel</button></div>
</form>
)}
<div className="mb-4 flex flex-wrap gap-3">
<label className="flex-1 text-sm font-medium">Search<input className={input} value={q} onChange={(e) => { setQ(e.target.value); setPage(1); }} placeholder="Name or email" /></label>
<label className="text-sm font-medium">Role
<select className={input} value={role} onChange={(e) => { setRole(e.target.value); setPage(1); }}>
<option value="">Everyone</option>
<option value="any">Anyone with a role</option>
{ROLES.map((r) => <option key={r} value={r}>{ROLE_NAMES[r]}{counts ? ` (${counts[r]})` : ""}</option>)}
</select>
</label>
</div>
{!list ? <p className="text-sm text-gray-600">Loading…</p> : (
<>
<p className="mb-2 text-sm text-gray-600">{list.total} {list.total === 1 ? "member" : "members"}</p>
<ul className="divide-y divide-gray-100">
{list.members.map((m) => (
<li key={m.id} className="py-3">
<div className="flex flex-wrap items-start justify-between gap-2">
<div className="min-w-0">
<p className="font-medium">{m.name}{m.id === meId && <span className="text-gray-500"> (you)</span>}</p>
<p className="truncate text-sm text-gray-600">{m.email}</p>
<p className="text-xs text-gray-500">Last used the App {day(m.lastActiveAt)}{m.whatsappStopped ? " · replied STOP to WhatsApp" : ""}</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{m.roles.length ? m.roles.map((r) => <span key={r} className="rounded-full bg-brand-tint px-2 py-0.5 text-xs font-medium text-brand-text">{ROLE_NAMES[r]}</span>) : <span className="text-xs text-gray-500">Member</span>}
{m.id !== meId && (isOwner || !m.roles.includes("owner")) && editing?.id !== m.id && (
<button type="button" className="text-sm font-semibold underline-offset-4 hover:underline" onClick={() => setEditing({ id: m.id, roles: m.roles })}>Roles</button>
)}
</div>
</div>
{editing?.id === m.id && (
<div className="mt-3 space-y-3 rounded-md border border-gray-200 bg-gray-50 p-4">
<RolePicker value={editing.roles} onChange={(roles) => setEditing({ ...editing, roles })} mayOwner={isOwner} idPrefix={m.id} />
<div className="flex gap-2"><button type="button" className="cca-btn" disabled={busy} onClick={saveRoles}>Save roles</button><button type="button" className="cca-btn-quiet" onClick={() => setEditing(null)}>Cancel</button></div>
</div>
)}
</li>
))}
</ul>
{list.total > list.pageSize && (
<div className="mt-4 flex items-center justify-between text-sm">
<button type="button" className="cca-btn-quiet" disabled={page <= 1} onClick={() => setPage(page - 1)}>Previous</button>
<span>Page {page} of {Math.ceil(list.total / list.pageSize)}</span>
<button type="button" className="cca-btn-quiet" disabled={page * list.pageSize >= list.total} onClick={() => setPage(page + 1)}>Next</button>
</div>
)}
</>
)}
</Panel>
</div>
);
}
@@ -0,0 +1,88 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { adminCall, Notice, Panel, type Msg } from "./kit";
const MODULES: { key: string; name: string; hint: string }[] = [
{ key: "house-of-prayer", name: "House of Prayer", hint: "The 24/7 prayer wall, campaigns and testimonies" },
{ key: "prayer-requests", name: "Prayer requests", hint: "Asking the prayer team (or members) to pray" },
{ key: "announcements", name: "Announcements", hint: "News, pinned notices, sent by email or WhatsApp if you choose" },
{ key: "devotionals", name: "Devotionals", hint: "Cross Code's or your own, each morning" },
{ key: "events", name: "Events", hint: "Your own simple events and Cross Events' through the feed" },
];
type Licence = { connected: boolean; state: string; endsAt: string | null; daysLeft: number | null };
/**
* Settings (APP-1.0-PLAN §10): the modules on and off, the licence and active members, and where
* each module's own settings are. The church's shared facts are changed in Accounts (P16).
*/
export function AdminSettings({ initialModules, activeMembers, licence, accountsUrl, isOwner, timezone }: {
initialModules: string[]; activeMembers: { count: number; band: string }; licence: Licence; accountsUrl: string | null; isOwner: boolean; timezone: string;
}) {
const [modules, setModules] = useState(initialModules);
const [msg, setMsg] = useState<Msg>(null);
const [busy, setBusy] = useState(false);
async function toggle(key: string, on: boolean) {
setBusy(true);
const r = await adminCall<{ modules: string[] }>("PUT", "/modules", { [key]: on });
setBusy(false);
if (!r.ok) return setMsg({ kind: "error", text: r.error });
setModules(r.data.modules);
setMsg({ kind: "ok", text: `${MODULES.find((m) => m.key === key)?.name} ${on ? "switched on" : "switched off"}. Members see the change within a minute.` });
}
const links: [string, string, string][] = [
["/admin/prayer", "The prayer wall's rules", "Slot length, target per slot, how far ahead, the cancel window, who to contact"],
["/admin/requests?view=settings", "Prayer requests and safeguarding", "Closing after how many days, anonymous requests, emergency numbers"],
["/admin/devotionals", "Devotionals", "From Cross Code or your own"],
["/admin/events", "Linked products", "Publish your events, and show Cross Events' and the Website's"],
["/admin/messaging", "Email and WhatsApp", "What the App sends with, Send a test"],
["/admin/backups", "Backups", "Nightly backups of the App's database and images"],
["/admin/jobs", "Background jobs", "Reminders, sends, the feed, the heartbeat"],
];
return (
<div className="space-y-6">
<Notice msg={msg} />
<Panel title="Modules">
<p className="mb-3 text-sm text-gray-600">Switch off what your church doesn&apos;t use: Home and the tab bar only show what&apos;s on. Nothing is deleted.</p>
<ul className="divide-y divide-gray-100">
{MODULES.map((m) => {
const on = modules.includes(m.key);
return (
<li key={m.key} className="flex items-center justify-between gap-3 py-3">
<span><span className="block font-medium">{m.name}</span><span className="text-sm text-gray-600">{m.hint}</span></span>
<button type="button" role="switch" aria-checked={on} aria-label={m.name} disabled={busy} onClick={() => toggle(m.key, !on)}
className={`relative h-6 w-11 shrink-0 rounded-full transition-colors ${on ? "bg-brand" : "bg-gray-300"}`}>
<span className={`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-all ${on ? "left-[22px]" : "left-0.5"}`} />
</button>
</li>
);
})}
</ul>
</Panel>
<Panel title="Licence">
<dl className="grid gap-4 text-sm sm:grid-cols-3">
<div><dt className="text-gray-600">Active members (90 days)</dt><dd className="text-2xl font-semibold">{activeMembers.count}</dd><dd className="text-gray-600">Band {activeMembers.band}</dd></div>
<div><dt className="text-gray-600">Cross Code Hub</dt><dd className="font-medium">{licence.connected ? `Connected (${licence.state})` : "Not connected"}</dd></div>
<div><dt className="text-gray-600">Licence ends</dt><dd className="font-medium">{licence.endsAt ? new Intl.DateTimeFormat("en-ZA", { timeZone: timezone, dateStyle: "medium" }).format(new Date(licence.endsAt)) : "–"}{licence.daysLeft !== null ? ` (${licence.daysLeft} days)` : ""}</dd></div>
</dl>
<p className="mt-3 text-sm text-gray-600">An active member is someone who used the App signed in in the last 90 days; visitors never count. The App&apos;s tier is checked against the band once a year, at renewal.{isOwner ? " Questions about the licence: Cross Code." : ""}</p>
</Panel>
<Panel title="More settings">
<ul className="divide-y divide-gray-100">
{links.map(([href, name, hint]) => (
<li key={href}><Link href={href} className="flex items-center justify-between gap-3 py-3 hover:text-brand-text"><span><span className="block font-medium">{name}</span><span className="text-sm text-gray-600">{hint}</span></span><span aria-hidden>›</span></Link></li>
))}
{accountsUrl && (
<li><a href={`${accountsUrl.replace(/\/+$/, "")}/admin/church`} className="flex items-center justify-between gap-3 py-3 hover:text-brand-text"><span><span className="block font-medium">The church&apos;s details (in Accounts)</span><span className="text-sm text-gray-600">Name, logo, icon, colours, timezone, contact, service times: shared by all the church&apos;s sites</span></span><span aria-hidden>›</span></a></li>
)}
</ul>
</Panel>
</div>
);
}
@@ -0,0 +1,151 @@
"use client";
/**
* The admin's frame (APP-1.0-PLAN §10, decision 9: the Website's and Events' admin): a bar across
* the top (the church, who's signed in, back to the App, Sign out), the sections down a white side
* menu in groups on a grey page, and a drawer for the menu on a phone. Only the sections the
* person's roles and the modules that are on allow are listed.
*/
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";
import {
Activity, BookOpen, CalendarDays, Clock, HandHeart, HardDrive, LayoutDashboard, LogOut, Mail, Megaphone, Menu, MessageCircleHeart, QrCode, Settings, Smartphone, Users, X,
type LucideIcon,
} from "lucide-react";
import type { AppModule } from "@/lib/load";
import type { Role } from "@/lib/roles";
type Item = { href: string; label: string; icon: LucideIcon; roles: Role[]; module?: AppModule };
/** `roles`: who besides an Owner and Church admin; empty: those two only. */
const GROUPS: { title: string | null; items: Item[] }[] = [
{ title: null, items: [{ href: "/admin", label: "Dashboard", icon: LayoutDashboard, roles: ["content_admin", "devotional_writer", "prayer_coordinator", "pastoral_care"] }] },
{
title: "Prayer",
items: [
{ href: "/admin/prayer", label: "House of Prayer", icon: HandHeart, roles: ["prayer_coordinator"], module: "house-of-prayer" },
{ href: "/admin/requests", label: "Prayer requests", icon: MessageCircleHeart, roles: ["prayer_coordinator", "pastoral_care"], module: "prayer-requests" },
],
},
{
title: "Content",
items: [
{ href: "/admin/announcements", label: "Announcements", icon: Megaphone, roles: ["content_admin"], module: "announcements" },
{ href: "/admin/devotionals", label: "Devotionals", icon: BookOpen, roles: ["devotional_writer"], module: "devotionals" },
{ href: "/admin/events", label: "Events", icon: CalendarDays, roles: ["content_admin"], module: "events" },
],
},
{
title: "People",
items: [
{ href: "/admin/members", label: "Members and roles", icon: Users, roles: [] },
{ href: "/admin/share", label: "Share the App", icon: QrCode, roles: [] },
],
},
{
title: "Settings",
items: [
{ href: "/admin/settings", label: "Settings", icon: Settings, roles: [] },
{ href: "/admin/messaging", label: "Email and WhatsApp", icon: Mail, roles: [] },
{ href: "/admin/backups", label: "Backups", icon: HardDrive, roles: [] },
{ href: "/admin/jobs", label: "Background jobs", icon: Clock, roles: [] },
{ href: "/admin/audit", label: "Audit and access logs", icon: Activity, roles: [] },
],
},
];
const FULL: Role[] = ["owner", "church_admin"];
const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
const initials = (name: string) => name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]!.toUpperCase()).join("") || "?";
function SideNav({ roles, modules, path, onNavigate }: { roles: Role[]; modules: AppModule[]; path: string; onNavigate?: () => void }) {
const full = roles.some((r) => FULL.includes(r));
return (
<nav aria-label="Admin" className="space-y-5">
{GROUPS.map((g, gi) => {
const items = g.items.filter((n) => (full || n.roles.some((r) => roles.includes(r))) && (!n.module || modules.includes(n.module)));
if (!items.length) return null;
return (
<div key={g.title ?? gi}>
{g.title && <p className="mb-1.5 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">{g.title}</p>}
<ul className="space-y-0.5">
{items.map((n) => {
const Icon = n.icon;
const current = n.href === "/admin" ? path === "/admin" : path === n.href || path.startsWith(`${n.href}/`);
return (
<li key={n.href}>
<Link href={n.href} onClick={onNavigate} aria-current={current ? "page" : undefined}
className={cx("flex min-h-10 items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors", current ? "bg-brand-tint font-medium text-brand-text" : "text-gray-600 hover:bg-gray-50 hover:text-gray-900")}>
<Icon className="h-4 w-4 shrink-0" aria-hidden />
<span className="flex-1">{n.label}</span>
</Link>
</li>
);
})}
</ul>
</div>
);
})}
</nav>
);
}
const ROLE_SHORT: Record<Role, string> = {
owner: "Owner", church_admin: "Church admin", content_admin: "Content admin", devotional_writer: "Devotional writer", prayer_coordinator: "Prayer coordinator", pastoral_care: "Pastoral care",
};
export function AdminShell({ name, church, roles, modules, children }: { name: string; church: string; roles: Role[]; modules: AppModule[]; children: React.ReactNode }) {
const path = usePathname();
const [open, setOpen] = useState(false);
const roleLine = roles.map((r) => ROLE_SHORT[r]).join(", ");
return (
<div className="min-h-screen bg-gray-50 print:bg-white font-sans text-gray-900">
<a href="#admin-main" className="sr-only focus:not-sr-only focus:absolute focus:left-4 focus:top-4 focus:z-50 focus:rounded focus:bg-white focus:px-3 focus:py-2">Skip to content</a>
<header className="sticky top-0 z-30 print:hidden border-b border-gray-200 bg-white/95 backdrop-blur">
<div className="flex items-center justify-between gap-3 px-4 py-2.5">
<div className="flex min-w-0 items-center gap-2">
<button type="button" onClick={() => setOpen(true)} aria-label="Open the menu" aria-expanded={open} className="rounded-lg p-2 hover:bg-gray-100 md:hidden"><Menu className="h-5 w-5" /></button>
<Link href="/admin" className="flex min-w-0 items-center gap-2 font-semibold">
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand text-brand-on" aria-hidden><Smartphone className="h-4 w-4" /></span>
<span className="truncate">{church} App admin</span>
</Link>
</div>
<div className="flex items-center gap-2 text-sm sm:gap-3">
<Link href="/" className="hidden rounded-lg border border-gray-300 px-3 py-1.5 font-semibold hover:bg-gray-50 sm:inline-block">Open the App</Link>
<span className="hidden items-center gap-2 lg:flex">
<span className="flex h-8 w-8 items-center justify-center rounded-full bg-brand-tint text-xs font-semibold text-brand-text" aria-hidden>{initials(name)}</span>
<span className="leading-tight"><span className="block font-medium">{name}</span><span className="block text-xs text-gray-500">{roleLine}</span></span>
</span>
<form method="post" action="/api/auth/signout">
<button type="submit" className="inline-flex items-center gap-1.5 rounded-lg px-2 py-1.5 text-gray-600 hover:bg-gray-100 hover:text-gray-900"><LogOut className="h-4 w-4" aria-hidden /><span className="hidden sm:inline">Sign out</span><span className="sr-only sm:hidden">Sign out</span></button>
</form>
</div>
</div>
</header>
{open && (
<div className="fixed inset-0 z-40 md:hidden" role="dialog" aria-modal="true" aria-label="Menu">
<button type="button" className="absolute inset-0 bg-black/30" aria-label="Close the menu" onClick={() => setOpen(false)} />
<div className="absolute inset-y-0 left-0 w-72 max-w-[85vw] overflow-y-auto bg-white p-4 shadow-xl">
<div className="mb-4 flex items-center justify-between">
<span className="text-sm"><span className="block font-semibold">{name}</span><span className="text-xs text-gray-500">{roleLine}</span></span>
<button type="button" onClick={() => setOpen(false)} aria-label="Close the menu" className="rounded-lg p-2 hover:bg-gray-100"><X className="h-5 w-5" /></button>
</div>
<SideNav roles={roles} modules={modules} path={path} onNavigate={() => setOpen(false)} />
<Link href="/" className="mt-6 block rounded-lg border border-gray-300 px-3 py-2 text-center text-sm font-semibold">Open the App</Link>
</div>
</div>
)}
<div className="flex">
<aside className="hidden w-60 print:!hidden shrink-0 border-r border-gray-200 bg-white md:block">
<div className="sticky top-[53px] max-h-[calc(100vh-53px)] overflow-y-auto p-4"><SideNav roles={roles} modules={modules} path={path} /></div>
</aside>
<main id="admin-main" className="min-w-0 flex-1 p-4 sm:p-6 print:p-0">
<div className="mx-auto w-full max-w-5xl space-y-6">{children}</div>
</main>
</div>
</div>
);
}
@@ -0,0 +1,39 @@
"use client";
import { useState } from "react";
import { adminCall } from "./kit";
/** Copy the link, print the poster, and tick "Share the App" off the setup checklist. */
export function ShareActions({ url, sharedAt }: { url: string; sharedAt: string | null }) {
const [copied, setCopied] = useState(false);
const [shared, setShared] = useState(!!sharedAt);
const [error, setError] = useState<string | null>(null);
async function copy() {
try {
await navigator.clipboard.writeText(url);
setCopied(true);
setTimeout(() => setCopied(false), 2500);
} catch {
setError("Your browser didn't let the App copy it: select the link and copy it yourself.");
}
}
async function markShared() {
const r = await adminCall<{ sharedAt: string }>("POST", "/share", {});
if (r.ok) setShared(true);
else setError(r.error);
}
return (
<div className="space-y-2 print:hidden">
<div className="flex flex-wrap gap-2">
<button type="button" className="cca-btn" onClick={copy}>{copied ? "Copied" : "Copy the link"}</button>
<button type="button" className="cca-btn-quiet" onClick={() => window.print()}>Print the poster</button>
{!shared && <button type="button" className="cca-btn-quiet" onClick={markShared}>I&apos;ve shared it</button>}
</div>
{shared && <p role="status" className="text-sm text-green-800">Ticked off the setup checklist.</p>}
{error && <p role="alert" className="text-sm text-red-800">{error}</p>}
</div>
);
}
+2 -9
View File
@@ -63,16 +63,9 @@ export const loadApp = cache(async (): Promise<AppInfo> => {
return FALLBACK;
});
export const ROLE_NAMES = {
owner: "Owner",
church_admin: "Church admin",
content_admin: "Content admin",
devotional_writer: "Devotional writer",
prayer_coordinator: "Prayer coordinator",
pastoral_care: "Pastoral care",
} as const;
import type { Role } from "./roles";
export type Role = keyof typeof ROLE_NAMES;
export { ROLE_NAMES, type Role } from "./roles";
/** The signed-in member (the backend's /api/auth/me). */
export type Me = {
+11
View File
@@ -0,0 +1,11 @@
/** The App's roles above Member (APP-1.0-PLAN §10), for server and client components alike. */
export const ROLE_NAMES = {
owner: "Owner",
church_admin: "Church admin",
content_admin: "Content admin",
devotional_writer: "Devotional writer",
prayer_coordinator: "Prayer coordinator",
pastoral_care: "Pastoral care",
} as const;
export type Role = keyof typeof ROLE_NAMES;