From 13eaaffb9508f950bc0e973c26c6cbe47179dd12 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Tue, 1 Dec 2026 14:42:31 +0200 Subject: [PATCH] =?UTF-8?q?app:=20the=20admin's=20side=20menu=20and=20page?= =?UTF-8?q?s:=20members,=20settings,=20jobs,=20logs,=20share=20(APP-1.0-PL?= =?UTF-8?q?AN=20=C2=A710)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- apps/app/frontend/package.json | 2 + .../src/app/admin/announcements/page.tsx | 8 +- .../app/frontend/src/app/admin/audit/page.tsx | 16 ++ .../src/app/admin/devotionals/page.tsx | 8 +- .../frontend/src/app/admin/events/page.tsx | 8 +- apps/app/frontend/src/app/admin/jobs/page.tsx | 16 ++ apps/app/frontend/src/app/admin/layout.tsx | 21 +++ .../frontend/src/app/admin/members/page.tsx | 16 ++ .../frontend/src/app/admin/messaging/page.tsx | 8 +- apps/app/frontend/src/app/admin/page.tsx | 164 ++++++++++++------ .../frontend/src/app/admin/prayer/page.tsx | 11 +- .../frontend/src/app/admin/requests/page.tsx | 8 +- .../frontend/src/app/admin/settings/page.tsx | 28 +++ .../app/frontend/src/app/admin/share/page.tsx | 50 ++++++ .../src/components/admin/AdminJobs.tsx | 89 ++++++++++ .../src/components/admin/AdminLogs.tsx | 60 +++++++ .../src/components/admin/AdminMembers.tsx | 156 +++++++++++++++++ .../src/components/admin/AdminSettings.tsx | 88 ++++++++++ .../src/components/admin/AdminShell.tsx | 151 ++++++++++++++++ .../src/components/admin/ShareActions.tsx | 39 +++++ apps/app/frontend/src/lib/load.ts | 11 +- apps/app/frontend/src/lib/roles.ts | 11 ++ package-lock.json | 2 + 23 files changed, 881 insertions(+), 90 deletions(-) create mode 100644 apps/app/frontend/src/app/admin/audit/page.tsx create mode 100644 apps/app/frontend/src/app/admin/jobs/page.tsx create mode 100644 apps/app/frontend/src/app/admin/layout.tsx create mode 100644 apps/app/frontend/src/app/admin/members/page.tsx create mode 100644 apps/app/frontend/src/app/admin/settings/page.tsx create mode 100644 apps/app/frontend/src/app/admin/share/page.tsx create mode 100644 apps/app/frontend/src/components/admin/AdminJobs.tsx create mode 100644 apps/app/frontend/src/components/admin/AdminLogs.tsx create mode 100644 apps/app/frontend/src/components/admin/AdminMembers.tsx create mode 100644 apps/app/frontend/src/components/admin/AdminSettings.tsx create mode 100644 apps/app/frontend/src/components/admin/AdminShell.tsx create mode 100644 apps/app/frontend/src/components/admin/ShareActions.tsx create mode 100644 apps/app/frontend/src/lib/roles.ts diff --git a/apps/app/frontend/package.json b/apps/app/frontend/package.json index 9203775..1b97be6 100644 --- a/apps/app/frontend/package.json +++ b/apps/app/frontend/package.json @@ -16,6 +16,7 @@ "@crosscode/ui": "*", "lucide-react": "^0.536.0", "next": "^16.4.6", + "qrcode": "^1.5.4", "react": "^19.3.1", "react-dom": "^19.3.1", "react-markdown": "^10.1.0" @@ -23,6 +24,7 @@ "devDependencies": { "@eslint/eslintrc": "^3", "@types/node": "^20", + "@types/qrcode": "^1.5.5", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "autoprefixer": "^10.4.21", diff --git a/apps/app/frontend/src/app/admin/announcements/page.tsx b/apps/app/frontend/src/app/admin/announcements/page.tsx index 09590e1..30dc04e 100644 --- a/apps/app/frontend/src/app/admin/announcements/page.tsx +++ b/apps/app/frontend/src/app/admin/announcements/page.tsx @@ -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 ( -
+
- ← Dashboard -

Announcements

+

Announcements

({ slug: c.slug, name: c.name }))} /> -
+ ); } diff --git a/apps/app/frontend/src/app/admin/audit/page.tsx b/apps/app/frontend/src/app/admin/audit/page.tsx new file mode 100644 index 0000000..0604ad2 --- /dev/null +++ b/apps/app/frontend/src/app/admin/audit/page.tsx @@ -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 ( +
+

Audit and access logs

+ +
+ ); +} diff --git a/apps/app/frontend/src/app/admin/devotionals/page.tsx b/apps/app/frontend/src/app/admin/devotionals/page.tsx index fc469ba..9615d47 100644 --- a/apps/app/frontend/src/app/admin/devotionals/page.tsx +++ b/apps/app/frontend/src/app/admin/devotionals/page.tsx @@ -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 ( -
+
- ← Dashboard -

Devotionals

+

Devotionals

-
+ ); } diff --git a/apps/app/frontend/src/app/admin/events/page.tsx b/apps/app/frontend/src/app/admin/events/page.tsx index b176092..38667db 100644 --- a/apps/app/frontend/src/app/admin/events/page.tsx +++ b/apps/app/frontend/src/app/admin/events/page.tsx @@ -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 ( -
+
- ← Dashboard -

Events

+

Events

-
+ ); } diff --git a/apps/app/frontend/src/app/admin/jobs/page.tsx b/apps/app/frontend/src/app/admin/jobs/page.tsx new file mode 100644 index 0000000..cd4904a --- /dev/null +++ b/apps/app/frontend/src/app/admin/jobs/page.tsx @@ -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 ( +
+

Background jobs

+ +
+ ); +} diff --git a/apps/app/frontend/src/app/admin/layout.tsx b/apps/app/frontend/src/app/admin/layout.tsx new file mode 100644 index 0000000..86e3b09 --- /dev/null +++ b/apps/app/frontend/src/app/admin/layout.tsx @@ -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
{children}
; + return ( + + {children} + + ); +} diff --git a/apps/app/frontend/src/app/admin/members/page.tsx b/apps/app/frontend/src/app/admin/members/page.tsx new file mode 100644 index 0000000..f49adab --- /dev/null +++ b/apps/app/frontend/src/app/admin/members/page.tsx @@ -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 ( +
+

Members and roles

+ +
+ ); +} diff --git a/apps/app/frontend/src/app/admin/messaging/page.tsx b/apps/app/frontend/src/app/admin/messaging/page.tsx index 99bba5c..3af3c00 100644 --- a/apps/app/frontend/src/app/admin/messaging/page.tsx +++ b/apps/app/frontend/src/app/admin/messaging/page.tsx @@ -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 ( -
+
- ← Dashboard -

Email and WhatsApp

+

Email and WhatsApp

-
+ ); } diff --git a/apps/app/frontend/src/app/admin/page.tsx b/apps/app/frontend/src/app/admin/page.tsx index b35731c..44cd44f 100644 --- a/apps/app/frontend/src/app/admin/page.tsx +++ b/apps/app/frontend/src/app/admin/page.tsx @@ -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 = { @@ -32,46 +40,50 @@ async function loadOverview(): Promise { return null; } -function Page({ children }: { children: React.ReactNode }) { - return
{children}
; +/** "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 ( - + <>

The App's admin

Sign in -
+ ); } if (!me.member.roles.length) { return ( - + <>

No access to the admin

Your account doesn't have a role in the App. Ask the App's Owner or a Church admin if you need one.

Back to the App -
+ ); } if (!me.mfa) { return ( - + <>

Two-step sign-in needed

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't yet, then sign in again.

Sign in with two-step -
+ ); } 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 ( - + <>

Dashboard

{me.member.name} · {me.member.roles.map((r) => ROLE_NAMES[r]).join(", ")}

@@ -79,44 +91,96 @@ export default async function Admin() { {!o ? (

The dashboard can't be loaded right now. Please try again in a minute.

) : ( -
-
-

Active members (90 days)

-

{o.activeMembers90d.count}

-

Band {o.activeMembers90d.band}

-
-
-

Modules on

-
    {o.modules.map((m) =>
  • {MODULE_NAMES[m] ?? m}
  • )}
-
-
-

Connections

-

Cross Code Hub: {o.hub.connected ? `connected (${o.hub.state})` : "not connected"}

-

Accounts: {o.accounts ? "linked" : "not linked yet"}

-
-
+ <> + {o.checklist && !o.checklist.done && ( +
+

Get the App ready

+

Before you tell the church about it.

+
    + {o.checklist.items.map((i) => { + const Icon = i.done ? CheckCircle2 : Circle; + const label = <>{i.label}{i.done ? " (done)" : " (to do)"}; + return ( +
  • + {i.href ? ( + i.href.startsWith("/") ? {label} + : {label} + ) : {label}} +
  • + ); + })} +
+
+ )} + +
+
+

Active members (90 days)

+

{o.activeMembers90d.count}

+

Band {o.activeMembers90d.band}

+
+
+

Modules on

+
    {o.modules.map((m) =>
  • {MODULE_NAMES[m] ?? m}
  • )}
+
+
+

Connections

+

Cross Code Hub: {o.hub.connected ? `connected (${o.hub.state})` : "not connected"}

+

Accounts: {o.accounts ? "linked" : "not linked yet"}

+
+
+ + {(o.waiting.requests !== null || o.waiting.testimonies !== null || o.waiting.escalated !== null) && ( +
+ {o.waiting.requests !== null && ( + +

Requests waiting for approval

+

{o.waiting.requests}

+ + )} + {o.waiting.testimonies !== null && ( + +

Testimonies waiting

+

{o.waiting.testimonies}

+ + )} + {o.waiting.escalated !== null && ( + +

Escalated requests open

+

{o.waiting.escalated}

+ + )} +
+ )} + + {o.week && ( +
+

This week on the prayer wall

Open
+
    + {o.week.days.map((d) => ( +
  • + {dayName(d.date, { weekday: "short", day: "numeric", month: "short" })} + + + {d.covered} of {d.total} + + {gapList(d.gaps)} +
  • + ))} +
+
+ )} + + {o.recent.length > 0 && ( +
+

Recent changes

Audit log
+
    + {o.recent.map((e, i) =>
  • {e.who} {e.action.charAt(0).toLowerCase() + e.action.slice(1)}{e.detail ? `: ${e.detail}` : ""} · {when(e.at)}
  • )} +
+
+ )} + )} - {o?.modules.includes("house-of-prayer") && me.activeRoles.some((r) => ["owner", "church_admin", "prayer_coordinator"].includes(r)) && ( - - House of Prayer: the week, who prays when, rules, campaigns, testimonies› - - )} - {([["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)) ? ( - {label}› - ) : null, - )} - {o?.modules.includes("prayer-requests") && me.activeRoles.some((r) => ["owner", "church_admin", "prayer_coordinator", "pastoral_care"].includes(r)) && ( - - Prayer requests: approval, escalations, replies, settings› - - )} - {me.activeRoles.some((r) => r === "owner" || r === "church_admin") && ( - - Email and WhatsApp: what the App sends with, Send a test, messages not sent› - - )} - Back to the App - + ); } diff --git a/apps/app/frontend/src/app/admin/prayer/page.tsx b/apps/app/frontend/src/app/admin/prayer/page.tsx index 21a8f38..fc12be1 100644 --- a/apps/app/frontend/src/app/admin/prayer/page.tsx +++ b/apps/app/frontend/src/app/admin/prayer/page.tsx @@ -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 ( -
+

House of Prayer

The House of Prayer is switched off. An Owner or Church admin can switch it on in Settings → Modules.

Back to the dashboard -
+
); } return ( -
+
- ← Dashboard -

House of Prayer

+

House of Prayer

-
+ ); } diff --git a/apps/app/frontend/src/app/admin/requests/page.tsx b/apps/app/frontend/src/app/admin/requests/page.tsx index cc6adf0..9c5a91a 100644 --- a/apps/app/frontend/src/app/admin/requests/page.tsx +++ b/apps/app/frontend/src/app/admin/requests/page.tsx @@ -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 ( -
+
- ← Dashboard -

Prayer requests

+

Prayer requests

{app.modules.includes("prayer-requests") ? ( ) : (

Prayer requests are switched off. An Owner or Church admin can switch them on in Settings → Modules.

)} -
+ ); } diff --git a/apps/app/frontend/src/app/admin/settings/page.tsx b/apps/app/frontend/src/app/admin/settings/page.tsx new file mode 100644 index 0000000..59e053b --- /dev/null +++ b/apps/app/frontend/src/app/admin/settings/page.tsx @@ -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("/api/v1/admin/overview"); + return ( +
+

Settings

+ {o ? ( + + ) : ( +

The settings can't be loaded right now. Please try again in a minute.

+ )} +
+ ); +} diff --git a/apps/app/frontend/src/app/admin/share/page.tsx b/apps/app/frontend/src/app/admin/share/page.tsx new file mode 100644 index 0000000..ea2ddb5 --- /dev/null +++ b/apps/app/frontend/src/app/admin/share/page.tsx @@ -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 ( +
+
+

Share the App

+

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.

+
+
+

The App's link

+

{url}

+ +
+ +
+ {app.church?.branding.logoUrl + ? {name} + :

{name}

} +

Our church in your pocket

+

Pray with us around the clock, ask for prayer, and get the news, today's devotional and what's on.

+
+

Scan with your phone's camera, or go to

+

{url.replace(/^https?:\/\//, "")}

+
    +
  1. 1. Open the link.
  2. +
  3. 2. Android: tap Install or Add to home screen. iPhone: tap Share, then Add to Home Screen.
  4. +
  5. 3. Sign in with your church account to book your hour of prayer.
  6. +
+
+
+ ); +} diff --git a/apps/app/frontend/src/components/admin/AdminJobs.tsx b/apps/app/frontend/src/components/admin/AdminJobs.tsx new file mode 100644 index 0000000..4ab1830 --- /dev/null +++ b/apps/app/frontend/src/components/admin/AdminJobs.tsx @@ -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(null); + const [msg, setMsg] = useState(null); + const [crons, setCrons] = useState>({}); + const [busy, setBusy] = useState(null); + + const load = useCallback(() => { + adminCall("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 ; + return ( +
+ +

{MODE[s.mode]}. Times are in {s.timezone}. A schedule is a cron expression with five fields (minute hour day month weekday).

+ {s.jobs.map((j) => { + const last = j.recent[0]; + return ( + {j.enabled ? "On" : "Off"}}> +
+
+

Next run

{when(j.nextRun)}

+

Last run

+

{last ? `${when(last.completedOn ?? last.startedOn)} · ${last.state}` : "–"}

+
+
+ + setCrons({ ...crons, [j.name]: e.target.value })} /> +

{j.override.cron ? "Set here" : `The server's (${j.envCron})`}

+
+ + {j.override.cron && } +
+
+
+ + + {j.override.enabled !== null && } +
+
+ {last?.state === "failed" && last.output != null &&

{String((last.output as { message?: string })?.message ?? JSON.stringify(last.output))}

} +
+ ); + })} +
+ ); +} diff --git a/apps/app/frontend/src/components/admin/AdminLogs.tsx b/apps/app/frontend/src/components/admin/AdminLogs.tsx new file mode 100644 index 0000000..c29c58e --- /dev/null +++ b/apps/app/frontend/src/components/admin/AdminLogs.tsx @@ -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([]); + const [more, setMore] = useState(false); + const [msg, setMsg] = useState(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 ( +
+
+ {(["audit", "access"] as const).map((t) => ( + + ))} +
+ + +

{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."}

+ {entries.length === 0 ?

Nothing yet.

: ( +
+ + + + {entries.map((e, i) => ( + + + + + + + ))} + +
WhenWhoWhatFrom
{when(e.at)}{e.who}{e.action}{e.detail ? · {e.detail} : null}{e.ip ?? ""}
+
+ )} + {more && } +
+
+ ); +} diff --git a/apps/app/frontend/src/components/admin/AdminMembers.tsx b/apps/app/frontend/src/components/admin/AdminMembers.tsx new file mode 100644 index 0000000..d3f6445 --- /dev/null +++ b/apps/app/frontend/src/components/admin/AdminMembers.tsx @@ -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; members: Member[] }; + +const ROLES = Object.keys(ROLE_NAMES) as Role[]; + +const ROLE_HINTS: Record = { + 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 ( +
+ Roles + {ROLES.filter((r) => mayOwner || r !== "owner").map((r) => ( + + ))} +
+ ); +} + +/** + * 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(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>({}); + const [msg, setMsg] = useState(null); + const [busy, setBusy] = useState(false); + + const load = useCallback(() => { + const qs = new URLSearchParams({ page: String(page), ...(q.trim() ? { q: q.trim() } : {}), ...(role ? { role } : {}) }); + adminCall("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 ( +
+ + setAdding({ name: "", email: "", roles: ["prayer_coordinator"] })}>Add someone with a role}> + {adding && ( +
+

For someone who hasn't used the App yet. Everyone who signs in is a Member already; give them a role from the list below.

+
+ setAdding({ ...adding, name: e.target.value })} required maxLength={200} /> + setAdding({ ...adding, email: e.target.value })} required maxLength={254} /> +
+ setAdding({ ...adding, roles })} mayOwner={isOwner} idPrefix="add" /> + {errors.roles &&

{errors.roles}

} +
+ + )} +
+ + +
+ {!list ?

Loading…

: ( + <> +

{list.total} {list.total === 1 ? "member" : "members"}

+
    + {list.members.map((m) => ( +
  • +
    +
    +

    {m.name}{m.id === meId && (you)}

    +

    {m.email}

    +

    Last used the App {day(m.lastActiveAt)}{m.whatsappStopped ? " · replied STOP to WhatsApp" : ""}

    +
    +
    + {m.roles.length ? m.roles.map((r) => {ROLE_NAMES[r]}) : Member} + {m.id !== meId && (isOwner || !m.roles.includes("owner")) && editing?.id !== m.id && ( + + )} +
    +
    + {editing?.id === m.id && ( +
    + setEditing({ ...editing, roles })} mayOwner={isOwner} idPrefix={m.id} /> +
    +
    + )} +
  • + ))} +
+ {list.total > list.pageSize && ( +
+ + Page {page} of {Math.ceil(list.total / list.pageSize)} + +
+ )} + + )} +
+
+ ); +} diff --git a/apps/app/frontend/src/components/admin/AdminSettings.tsx b/apps/app/frontend/src/components/admin/AdminSettings.tsx new file mode 100644 index 0000000..3574b4d --- /dev/null +++ b/apps/app/frontend/src/components/admin/AdminSettings.tsx @@ -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(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 ( +
+ + +

Switch off what your church doesn't use: Home and the tab bar only show what's on. Nothing is deleted.

+
    + {MODULES.map((m) => { + const on = modules.includes(m.key); + return ( +
  • + {m.name}{m.hint} + +
  • + ); + })} +
+
+ + +
+
Active members (90 days)
{activeMembers.count}
Band {activeMembers.band}
+
Cross Code Hub
{licence.connected ? `Connected (${licence.state})` : "Not connected"}
+
Licence ends
{licence.endsAt ? new Intl.DateTimeFormat("en-ZA", { timeZone: timezone, dateStyle: "medium" }).format(new Date(licence.endsAt)) : "–"}{licence.daysLeft !== null ? ` (${licence.daysLeft} days)` : ""}
+
+

An active member is someone who used the App signed in in the last 90 days; visitors never count. The App's tier is checked against the band once a year, at renewal.{isOwner ? " Questions about the licence: Cross Code." : ""}

+
+ + + + +
+ ); +} diff --git a/apps/app/frontend/src/components/admin/AdminShell.tsx b/apps/app/frontend/src/components/admin/AdminShell.tsx new file mode 100644 index 0000000..bb1433d --- /dev/null +++ b/apps/app/frontend/src/components/admin/AdminShell.tsx @@ -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 ( + + ); +} + +const ROLE_SHORT: Record = { + 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 ( +
+ Skip to content +
+
+
+ + + + {church} App admin + +
+
+ Open the App + + {initials(name)} + {name}{roleLine} + +
+ +
+
+
+
+ + {open && ( +
+ +
+ setOpen(false)} /> + Open the App +
+ + )} + +
+ +
+
{children}
+
+
+ + ); +} diff --git a/apps/app/frontend/src/components/admin/ShareActions.tsx b/apps/app/frontend/src/components/admin/ShareActions.tsx new file mode 100644 index 0000000..10d18b1 --- /dev/null +++ b/apps/app/frontend/src/components/admin/ShareActions.tsx @@ -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(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 ( +
+
+ + + {!shared && } +
+ {shared &&

Ticked off the setup checklist.

} + {error &&

{error}

} +
+ ); +} diff --git a/apps/app/frontend/src/lib/load.ts b/apps/app/frontend/src/lib/load.ts index d3269fb..169f64d 100644 --- a/apps/app/frontend/src/lib/load.ts +++ b/apps/app/frontend/src/lib/load.ts @@ -63,16 +63,9 @@ export const loadApp = cache(async (): Promise => { 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 = { diff --git a/apps/app/frontend/src/lib/roles.ts b/apps/app/frontend/src/lib/roles.ts new file mode 100644 index 0000000..9608157 --- /dev/null +++ b/apps/app/frontend/src/lib/roles.ts @@ -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; diff --git a/package-lock.json b/package-lock.json index 9486306..f7225fe 100644 --- a/package-lock.json +++ b/package-lock.json @@ -177,6 +177,7 @@ "@crosscode/ui": "*", "lucide-react": "^0.536.0", "next": "^16.4.6", + "qrcode": "^1.5.4", "react": "^19.3.1", "react-dom": "^19.3.1", "react-markdown": "^10.1.0" @@ -184,6 +185,7 @@ "devDependencies": { "@eslint/eslintrc": "^3", "@types/node": "^20", + "@types/qrcode": "^1.5.5", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "autoprefixer": "^10.4.21",