"use client"; import Link from "next/link"; import React, { useCallback, useState } from "react"; import { DatabaseBackup, Download, Play, RefreshCw, Timer } from "lucide-react"; import { Button, Checkbox, Field, Notice } from "@crosscode/ui"; import { AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell"; import { NoticeText } from "@/components/NoticeText"; import { Card, Heading } from "@/components/Panel"; import { call, selfSignIn } from "@/lib/api"; import { useExternalEffect } from "@/lib/hooks"; import { ADMIN_SECTIONS, type AdminSection } from "@/lib/sections"; const when = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—"); type Flash = (tone: "success" | "error", text: string) => void; /** * Accounts' admin (docs/ACCOUNTS-1.0-PLAN.md §8). Admins only, signed in with their second step. * 1.3.0: one section per address, down the side (as Cross Events' settings), and Backups. */ export function Admin({ section = "people" }: { section?: AdminSection }) { const s = ADMIN_SECTIONS[section] ?? ADMIN_SECTIONS.people; const [me, setMe] = useState(null); const [allowed, setAllowed] = useState(null); const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null); useExternalEffect(() => { let alive = true; Promise.all([call("GET", "/me"), call("GET", "/admin/licence")]).then(([who, r]) => { if (!alive) return; if (who.status === 401 || r.status === 401) return window.location.assign(selfSignIn(s.path)); if (!r.ok && r.error.code === "MFA_REQUIRED") return window.location.assign(selfSignIn(s.path, "&acr=mfa")); if (who.ok) setMe(who.data); setAllowed(r.ok); }); return () => { alive = false; }; }, [s.path]); const flash: Flash = (tone, text) => setMsg({ tone, text }); if (allowed === null || !me) return ; if (!allowed) { return (
Only Accounts admins can open this page.Your account
); } return ( {s.title} {msg && {msg.text}} {section === "people" && }
{section === "deletions" && } {section === "church" && } {section === "linked" && } {section === "signin" && } {section === "messages" && } {section === "notice" && } {section === "backups" && } {section === "jobs" && } {section === "licence" && } {section === "audit" && }
); } // ─── People ────────────────────────────────────────────────────────────────── type Person = { id: string; name: string; email: string; role: string; status: string; twoFactor: string | null; lastSignInAt: string | null }; type PersonDetail = Person & { phone: string | null; emailVerified: boolean; recoveryCodesLeft: number; createdAt: string; lockedUntil: string | null; signIns: { type: string; at: string; ip: string | null }[] }; function People({ flash }: { flash: Flash }) { const [q, setQ] = useState(""); const [list, setList] = useState<{ items: Person[]; total: number } | null>(null); const [open, setOpen] = useState(null); const search = useCallback(async (query: string) => { const r = await call<{ items: Person[]; total: number }>("GET", `/admin/people?q=${encodeURIComponent(query)}`); if (r.ok) setList(r.data); }, []); useExternalEffect(() => { void search(""); }, [search]); const show = async (id: string) => { const r = await call("GET", `/admin/people/${id}`); if (r.ok) setOpen(r.data); }; const act = async (path: string, body: unknown, ok: string) => { const r = await call(path.endsWith("/role") || path.endsWith("/status") ? "PUT" : "POST", path, body); if (r.ok) { flash("success", ok); if (open) void show(open.id); void search(q); } else flash("error", r.error.message); }; return (
{ e.preventDefault(); void search(q); }} className="mb-4 flex gap-2"> setQ(e.target.value)} placeholder="Name or email" className="flex-1 rounded-lg border px-3 py-2" />

{list?.total ?? 0} people

    {list?.items.map((p) => (
  • ))}
{open && ( {open.name}
Phone
{open.phone ?? "—"}
Email confirmed
{open.emailVerified ? "yes" : "no"}
Two-step sign-in
{open.twoFactor ?? "off"}{open.twoFactor ? ` (${open.recoveryCodesLeft} codes left)` : ""}
Account since
{when(open.createdAt)}
Locked until
{when(open.lockedUntil)}
{open.twoFactor && } {open.lockedUntil && }

Roles in each product (an Events supervisor, for example) are set in that product, not here.

Recent sign-ins

    {open.signIns.map((s, i) =>
  • {s.type} · {when(s.at)} {s.ip && · {s.ip}}
  • )}
)}
); } // ─── Deletions ─────────────────────────────────────────────────────────────── type Deletion = { id: string; status: string; requestedAt: string; products: Record; person: { name: string; email: string } }; function Deletions({ flash }: { flash: Flash }) { const [items, setItems] = useState([]); const load = useCallback(async () => { const r = await call<{ items: Deletion[] }>("GET", "/admin/deletions"); if (r.ok) setItems(r.data.items); }, []); useExternalEffect(() => { void load(); }, [load]); return ( Deletion requests {!items.length &&

None waiting.

}
    {items.map((d) => (
  • {d.person.name} {d.person.email} · asked {when(d.requestedAt)}

    {d.status === "waiting_approval" ? (
    ) : (
      {Object.entries(d.products).map(([id, s]) =>
    • {s.product ?? id}: {s.status === "deferred" ? `waiting — ${s.reason} (asking again ${when(s.retryAfter)})` : s.status}
    • )}
    )}
  • ))}
); } // ─── Church profile ────────────────────────────────────────────────────────── type ChurchData = { name: string; shortName: string | null; branding: { logoUrl: string | null; colours: { primary: string; accent: string | null } }; contact: { email: string | null; phone: string | null; whatsapp: string | null } }; function Church({ flash }: { flash: Flash }) { const [c, setC] = useState(null); const [fields, setFields] = useState>({}); useExternalEffect(() => { let alive = true; call("GET", "/admin/church").then((r) => { if (alive && r.ok) setC(r.data); }); return () => { alive = false; }; }, []); if (!c) return

Loading…

; const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null); return ( Church profile
{ e.preventDefault(); const f = new FormData(e.currentTarget); const r = await call("PUT", "/admin/church", { name: f.get("name"), shortName: nul(f.get("shortName")), branding: { ...c.branding, logoUrl: nul(f.get("logoUrl")), colours: { primary: f.get("primary"), accent: nul(f.get("accent")) } }, contact: { ...c.contact, email: nul(f.get("email")), phone: nul(f.get("phone")), whatsapp: nul(f.get("whatsapp")) }, }); if (r.ok) { setC(r.data); setFields({}); flash("success", "Saved. The church's products are told about the change."); } else { setFields(r.error.fields ?? {}); flash("error", r.error.message); } }}>
); } // ─── Linked products ───────────────────────────────────────────────────────── type LinkedItem = { installId: string; product: string; name: string; url: string; listed: boolean; connectedAt: string | null; signsInHere: boolean }; function Linked({ flash }: { flash: Flash }) { const [data, setData] = useState<{ hubConnected: boolean; items: LinkedItem[] } | null>(null); const load = useCallback(async () => { const r = await call<{ hubConnected: boolean; items: LinkedItem[] }>("GET", "/admin/linked-products"); if (r.ok) setData(r.data); }, []); useExternalEffect(() => { void load(); }, [load]); if (!data) return

Loading…

; return ( Linked products {!data.hubConnected && Accounts isn't connected to the Hub yet (Licence).} {!data.items.length &&

The church has no other Cross Code products yet.

}
    {data.items.map((l) => (
  • {l.name} {l.url.replace(/^https?:\/\//, "")}
    {l.signsInHere ? `Connected ${when(l.connectedAt)}` : "Not connected"}{!l.listed && " · no longer listed by the Hub"}
    {l.signsInHere ? : }
  • ))}
); } // ─── Settings ──────────────────────────────────────────────────────────────── const SETTING_LABELS: Record = { signup_enabled: ["Members can create their own account", "bool"], two_factor_required_for_admins: ["Admins must use two-step sign-in", "bool"], signin_notices: ["Tell people by email (and WhatsApp) each time they sign in", "bool"], session_days: ['Days "Keep me signed in" lasts', "number"], smtp_host: ["SMTP server", "text"], smtp_port: ["SMTP port", "number"], smtp_user: ["SMTP user name", "text"], smtp_pass: ["SMTP password", "secret"], smtp_from: ["Send from (email address)", "text"], smtp_secure: ["Use TLS from the start (port 465)", "bool"], wawp_access_token: ["WAWP access token", "secret"], wawp_instance_id: ["WAWP instance id", "text"], }; function Settings({ flash, keys }: { flash: Flash; keys: string[] }) { const [values, setValues] = useState | null>(null); useExternalEffect(() => { let alive = true; call>("GET", "/admin/settings").then((r) => { if (alive && r.ok) setValues(r.data); }); return () => { alive = false; }; }, []); if (!values) return

Loading…

; const defaults: Record = { signup_enabled: true, two_factor_required_for_admins: true, signin_notices: true }; return (
{ e.preventDefault(); const f = new FormData(e.currentTarget); const body: Record = {}; for (const k of keys) { const kind = SETTING_LABELS[k]![1]; if (kind === "bool") body[k] = f.get(k) === "on" ? "true" : "false"; else body[k] = String(f.get(k) ?? ""); } const r = await call("PUT", "/admin/settings", body); if (r.ok) flash("success", "Saved."); else flash("error", r.error.message); }}> {keys.map((k) => { const [label, kind] = SETTING_LABELS[k]!; const v = values[k]; if (kind === "bool") return ; if (kind === "secret") return ; return ; })}
{keys.includes("smtp_host") && } {keys.includes("wawp_instance_id") && }
); } // ─── Privacy notice, licence, audit ─────────────────────────────────────────── type NoticeVersion = { version: number; title: string; body: string }; function NoticeTab({ flash }: { flash: Flash }) { const [data, setData] = useState<{ current: NoticeVersion; builtIn: NoticeVersion | null } | null>(null); const [draft, setDraft] = useState<{ title: string; body: string } | null>(null); const load = useCallback(async () => { const r = await call<{ current: NoticeVersion; builtIn?: NoticeVersion }>("GET", "/admin/notices"); if (r.ok) { setData({ current: r.data.current, builtIn: r.data.builtIn ?? null }); setDraft({ title: r.data.current.title, body: r.data.current.body }); } }, []); useExternalEffect(() => { void load(); }, [load]); if (!data || !draft) return

Loading…

; const { current, builtIn } = data; const isBuiltIn = current.version === 1; return (
Edit and publish {builtIn && !isBuiltIn && (

The built-in notice was rewritten in Accounts 1.3.0 to say more fully what Accounts does.{" "}

)}
{ e.preventDefault(); if (!window.confirm("Publish this as a new version? Everyone will be asked to read it when they next sign in.")) return; const r = await call("POST", "/admin/notices", draft); if (r.ok) { flash("success", "Published."); void load(); } else flash("error", r.error.message); }}> setDraft({ ...draft, title: e.target.value })} required />