- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin; the choice is kept in the database (job_overrides), wins over the .env and applies at once. Accounts gets an Admin -> Background jobs page and per-job env flags, as Events. - Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same plain text (src/lib/emails.ts). - Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName. - crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads, and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats). - Agent 1.3.0: runs env-read and env-set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
626 lines
40 KiB
TypeScript
626 lines
40 KiB
TypeScript
"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<ShellUser | null>(null);
|
|
const [allowed, setAllowed] = useState<boolean | null>(null);
|
|
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
|
|
|
|
useExternalEffect(() => {
|
|
let alive = true;
|
|
Promise.all([call<ShellUser>("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 <ShellLoading />;
|
|
if (!allowed) {
|
|
return (
|
|
<AppShell me={me} active={s.path}>
|
|
<div className="max-w-xl"><Card><Notice tone="error">Only Accounts admins can open this page.</Notice><Link href="/account" className="text-brand underline">Your account</Link></Card></div>
|
|
</AppShell>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<AppShell me={me} active={s.path}>
|
|
<PageTitle sub={s.sub}>{s.title}</PageTitle>
|
|
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
|
|
{section === "people" && <People flash={flash} />}
|
|
<div className="max-w-3xl">
|
|
{section === "deletions" && <Deletions flash={flash} />}
|
|
{section === "church" && <Church flash={flash} />}
|
|
{section === "linked" && <Linked flash={flash} />}
|
|
{section === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "session_days"]} />}
|
|
{section === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
|
|
{section === "notice" && <NoticeTab flash={flash} />}
|
|
{section === "backups" && <Backups flash={flash} />}
|
|
{section === "jobs" && <Jobs flash={flash} />}
|
|
{section === "licence" && <Licence flash={flash} />}
|
|
{section === "audit" && <Audit />}
|
|
</div>
|
|
</AppShell>
|
|
);
|
|
}
|
|
|
|
// ─── 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<PersonDetail | null>(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<PersonDetail>("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 (
|
|
<div className="grid gap-6 md:grid-cols-2">
|
|
<Card>
|
|
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-4 flex gap-2">
|
|
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="flex-1 rounded-lg border px-3 py-2" />
|
|
<Button type="submit" variant="secondary">Search</Button>
|
|
</form>
|
|
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} people</p>
|
|
<ul className="divide-y">
|
|
{list?.items.map((p) => (
|
|
<li key={p.id}>
|
|
<button type="button" onClick={() => show(p.id)} className="w-full py-2 text-left hover:bg-gray-50">
|
|
<span className="block font-medium">{p.name}{p.role === "admin" && <span className="ml-2 rounded bg-brand/10 px-1.5 text-xs text-brand">admin</span>}{p.status !== "active" && <span className="ml-2 text-xs text-amber-700">{p.status}</span>}</span>
|
|
<span className="block text-sm text-gray-500">{p.email}</span>
|
|
</button>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</Card>
|
|
{open && (
|
|
<Card>
|
|
<Heading sub={open.email}>{open.name}</Heading>
|
|
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
|
|
<dt className="text-gray-500">Phone</dt><dd>{open.phone ?? "—"}</dd>
|
|
<dt className="text-gray-500">Email confirmed</dt><dd>{open.emailVerified ? "yes" : "no"}</dd>
|
|
<dt className="text-gray-500">Two-step sign-in</dt><dd>{open.twoFactor ?? "off"}{open.twoFactor ? ` (${open.recoveryCodesLeft} codes left)` : ""}</dd>
|
|
<dt className="text-gray-500">Account since</dt><dd>{when(open.createdAt)}</dd>
|
|
<dt className="text-gray-500">Locked until</dt><dd>{when(open.lockedUntil)}</dd>
|
|
</dl>
|
|
<div className="mb-4 flex flex-wrap gap-2">
|
|
{open.twoFactor && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/reset-two-factor`, {}, "Two-step sign-in reset. They'll set it up again when they next sign in, if they need it.")}>Reset two-step sign-in</Button>}
|
|
{open.lockedUntil && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/unlock`, {}, "Unlocked.")}>Unlock</Button>}
|
|
<Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/role`, { role: open.role === "admin" ? "member" : "admin" }, "Role changed.")}>{open.role === "admin" ? "Remove admin" : "Make Accounts admin"}</Button>
|
|
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated.")}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
|
|
</div>
|
|
<p className="mb-1 text-xs text-gray-500">Roles in each product (an Events supervisor, for example) are set in that product, not here.</p>
|
|
<p className="mb-2 mt-4 text-sm font-medium">Recent sign-ins</p>
|
|
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((s, i) => <li key={i}>{s.type} · {when(s.at)} {s.ip && <span className="text-gray-400">· {s.ip}</span>}</li>)}</ul>
|
|
</Card>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ─── Deletions ───────────────────────────────────────────────────────────────
|
|
|
|
type Deletion = { id: string; status: string; requestedAt: string; products: Record<string, { status: string; product?: string; reason?: string; retryAfter?: string }>; person: { name: string; email: string } };
|
|
|
|
function Deletions({ flash }: { flash: Flash }) {
|
|
const [items, setItems] = useState<Deletion[]>([]);
|
|
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 (
|
|
<Card>
|
|
<Heading sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
|
|
{!items.length && <p className="text-sm text-gray-500">None waiting.</p>}
|
|
<ul className="divide-y">
|
|
{items.map((d) => (
|
|
<li key={d.id} className="py-3">
|
|
<p className="font-medium">{d.person.name} <span className="text-sm font-normal text-gray-500">{d.person.email} · asked {when(d.requestedAt)}</span></p>
|
|
{d.status === "waiting_approval" ? (
|
|
<div className="mt-2 flex gap-2">
|
|
<Button variant="danger" onClick={async () => { const r = await call("POST", `/admin/deletions/${d.id}/approve`); if (r.ok) { flash("success", "Approved: each site is deleting what it holds."); void load(); } else flash("error", r.error.message); }}>Approve</Button>
|
|
<Button variant="secondary" onClick={async () => { const r = await call("POST", `/admin/deletions/${d.id}/cancel`); if (r.ok) { flash("success", "Cancelled; the account works again."); void load(); } else flash("error", r.error.message); }}>Cancel</Button>
|
|
</div>
|
|
) : (
|
|
<ul className="mt-2 text-sm text-gray-700">
|
|
{Object.entries(d.products).map(([id, s]) => <li key={id}>{s.product ?? id}: {s.status === "deferred" ? `waiting — ${s.reason} (asking again ${when(s.retryAfter)})` : s.status}</li>)}
|
|
</ul>
|
|
)}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
// ─── 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<ChurchData | null>(null);
|
|
const [fields, setFields] = useState<Record<string, string>>({});
|
|
useExternalEffect(() => {
|
|
let alive = true;
|
|
call<ChurchData>("GET", "/admin/church").then((r) => { if (alive && r.ok) setC(r.data); });
|
|
return () => { alive = false; };
|
|
}, []);
|
|
if (!c) return <p className="text-gray-600">Loading…</p>;
|
|
const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null);
|
|
return (
|
|
<Card>
|
|
<Heading sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
|
|
<form onSubmit={async (e) => {
|
|
e.preventDefault();
|
|
const f = new FormData(e.currentTarget);
|
|
const r = await call<ChurchData>("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); }
|
|
}}>
|
|
<Field label="Name" name="name" defaultValue={c.name} required error={fields.name} />
|
|
<Field label="Short name" name="shortName" defaultValue={c.shortName ?? ""} maxLength={30} hint="For small spaces, like the authenticator app's label." error={fields.shortName} />
|
|
<Field label="Logo address (https://…)" name="logoUrl" type="url" defaultValue={c.branding.logoUrl ?? ""} error={fields["branding.logoUrl"]} />
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<Field label="Main colour" name="primary" type="color" defaultValue={c.branding.colours.primary} />
|
|
<Field label="Accent colour" name="accent" type="color" defaultValue={c.branding.colours.accent ?? "#f2a900"} />
|
|
</div>
|
|
<Field label="Office email" name="email" type="email" defaultValue={c.contact.email ?? ""} error={fields["contact.email"]} />
|
|
<Field label="Office phone" name="phone" defaultValue={c.contact.phone ?? ""} hint="With the country code, e.g. +27161234567." error={fields["contact.phone"]} />
|
|
<Field label="WhatsApp" name="whatsapp" defaultValue={c.contact.whatsapp ?? ""} error={fields["contact.whatsapp"]} />
|
|
<Button type="submit">Save</Button>
|
|
</form>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
// ─── 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 <p className="text-gray-600">Loading…</p>;
|
|
return (
|
|
<Card>
|
|
<Heading sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
|
|
{!data.hubConnected && <Notice tone="warning">Accounts isn't connected to the Hub yet (Licence).</Notice>}
|
|
{!data.items.length && <p className="text-sm text-gray-500">The church has no other Cross Code products yet.</p>}
|
|
<ul className="divide-y">
|
|
{data.items.map((l) => (
|
|
<li key={l.installId} className="flex flex-wrap items-center justify-between gap-2 py-3">
|
|
<span><span className="font-medium">{l.name}</span> <span className="text-sm text-gray-500">{l.url.replace(/^https?:\/\//, "")}</span><br />
|
|
<span className="text-sm text-gray-600">{l.signsInHere ? `Connected ${when(l.connectedAt)}` : "Not connected"}{!l.listed && " · no longer listed by the Hub"}</span></span>
|
|
{l.signsInHere
|
|
? <Button variant="secondary" onClick={async () => { if (!window.confirm(`Disconnect ${l.name}? People won't be able to sign in to it until it's connected again.`)) return; const r = await call("POST", `/admin/linked-products/${l.installId}/disconnect`); if (r.ok) { flash("success", "Disconnected."); void load(); } else flash("error", r.error.message); }}>Disconnect</Button>
|
|
: <Button disabled={!l.listed} onClick={async () => { const r = await call("POST", `/admin/linked-products/${l.installId}/connect`); if (r.ok) { flash("success", `Connected: ${l.name} signs people in here now.`); void load(); } else flash("error", r.error.message); }}>Connect</Button>}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
// ─── Settings ────────────────────────────────────────────────────────────────
|
|
|
|
const SETTING_LABELS: Record<string, [string, "bool" | "text" | "secret" | "number"]> = {
|
|
signup_enabled: ["Members can create their own account", "bool"],
|
|
two_factor_required_for_admins: ["Admins must use two-step 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<Record<string, string | boolean | null> | null>(null);
|
|
useExternalEffect(() => {
|
|
let alive = true;
|
|
call<Record<string, string | boolean | null>>("GET", "/admin/settings").then((r) => { if (alive && r.ok) setValues(r.data); });
|
|
return () => { alive = false; };
|
|
}, []);
|
|
if (!values) return <p className="text-gray-600">Loading…</p>;
|
|
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true };
|
|
return (
|
|
<Card>
|
|
<form onSubmit={async (e) => {
|
|
e.preventDefault();
|
|
const f = new FormData(e.currentTarget);
|
|
const body: Record<string, string> = {};
|
|
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 <Checkbox key={k} name={k} label={label} defaultChecked={v === null ? defaults[k] ?? false : v === "true"} />;
|
|
if (kind === "secret") return <Field key={k} name={k} label={label} type="password" autoComplete="off" placeholder={v ? "Saved — leave empty to keep it" : ""} />;
|
|
return <Field key={k} name={k} label={label} type={kind === "number" ? "number" : "text"} defaultValue={typeof v === "string" ? v : ""} />;
|
|
})}
|
|
<div className="flex gap-2">
|
|
<Button type="submit">Save</Button>
|
|
{keys.includes("smtp_host") && <Button type="button" variant="secondary" onClick={async () => { const r = await call("POST", "/admin/settings/test-email"); flash(r.ok ? "success" : "error", r.ok ? "A test email is on its way to you." : r.error.message); }}>Send a test email</Button>}
|
|
{keys.includes("wawp_instance_id") && <Button type="button" variant="secondary" onClick={async () => { const r = await call("POST", "/admin/settings/test-whatsapp"); flash(r.ok ? "success" : "error", r.ok ? "A test WhatsApp message is on its way to your phone." : r.error.message); }}>Send a test WhatsApp</Button>}
|
|
</div>
|
|
</form>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
// ─── 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 <p className="text-gray-600">Loading…</p>;
|
|
const { current, builtIn } = data;
|
|
const isBuiltIn = current.version === 1;
|
|
return (
|
|
<div className="space-y-6">
|
|
<Card>
|
|
<Heading sub={`Version ${current.version}${isBuiltIn ? " (the built-in notice, filled in from the church profile)" : ""}. Publishing a new version asks everyone to read it the next time they sign in.`}>Edit and publish</Heading>
|
|
{builtIn && !isBuiltIn && (
|
|
<p className="mb-4 text-sm text-gray-600">
|
|
The built-in notice was rewritten in Accounts 1.3.0 to say more fully what Accounts does.{" "}
|
|
<Button type="button" variant="link" className="text-sm" onClick={() => setDraft({ title: builtIn.title, body: builtIn.body })}>Start from the built-in notice</Button>
|
|
</p>
|
|
)}
|
|
<form onSubmit={async (e) => {
|
|
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);
|
|
}}>
|
|
<Field label="Title" name="title" value={draft.title} onChange={(e) => setDraft({ ...draft, title: e.target.value })} required />
|
|
<label htmlFor="notice-body" className="mb-1 block text-sm font-medium">Text</label>
|
|
<textarea id="notice-body" name="body" value={draft.body} onChange={(e) => setDraft({ ...draft, body: e.target.value })} rows={18} className="mb-1 w-full rounded-lg border p-3 font-mono text-xs" required />
|
|
<p className="mb-4 text-xs text-gray-500">A line starting with "## " is a heading, and one starting with "• " is a bullet.</p>
|
|
<Button type="submit">Publish a new version</Button>
|
|
</form>
|
|
</Card>
|
|
<Card>
|
|
<Heading sub="As people will see it.">Preview</Heading>
|
|
<h3 className="mb-3 text-base font-semibold text-gray-900">{draft.title}</h3>
|
|
<div className="max-h-[32rem] overflow-y-auto rounded-lg border bg-gray-50 p-4"><NoticeText body={draft.body} compact /></div>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function Licence({ flash }: { flash: Flash }) {
|
|
const [s, setS] = useState<{ connected: boolean; state: string; customer: string | null; endsAt: string | null; lastHeartbeatAt: string | null; lastError: string | null } | null>(null);
|
|
const load = useCallback(async () => {
|
|
const r = await call<NonNullable<typeof s>>("GET", "/admin/licence");
|
|
if (r.ok) setS(r.data);
|
|
}, []);
|
|
useExternalEffect(() => { void load(); }, [load]);
|
|
if (!s) return <p className="text-gray-600">Loading…</p>;
|
|
return (
|
|
<Card>
|
|
<Heading sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
|
|
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
|
|
<dt className="text-gray-500">Connected to the Hub</dt><dd>{s.connected ? "yes" : "no"}</dd>
|
|
<dt className="text-gray-500">Licence</dt><dd>{s.state}</dd>
|
|
<dt className="text-gray-500">Customer</dt><dd>{s.customer ?? "—"}</dd>
|
|
<dt className="text-gray-500">Last heartbeat</dt><dd>{when(s.lastHeartbeatAt)}</dd>
|
|
</dl>
|
|
{s.lastError && <Notice tone="warning">{s.lastError}</Notice>}
|
|
{!s.connected && (
|
|
<form onSubmit={async (e) => {
|
|
e.preventDefault();
|
|
const r = await call("POST", "/admin/licence", { licenceKey: new FormData(e.currentTarget).get("licenceKey") });
|
|
if (r.ok) { flash("success", "Connected to the Hub."); void load(); } else flash("error", r.error.message);
|
|
}}>
|
|
<Field label="Licence key" name="licenceKey" placeholder="CCA-XXXX-XXXX-XXXX-XXXX" required />
|
|
<Button type="submit">Connect</Button>
|
|
</form>
|
|
)}
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
function Audit() {
|
|
const [items, setItems] = useState<{ id: string; action: string; actorRole: string; targetType: string; targetId: string | null; createdAt: string }[]>([]);
|
|
useExternalEffect(() => {
|
|
let alive = true;
|
|
call<{ items: typeof items }>("GET", "/admin/audit").then((r) => { if (alive && r.ok) setItems(r.data.items); });
|
|
return () => { alive = false; };
|
|
}, []);
|
|
return (
|
|
<Card>
|
|
<Heading>Audit log</Heading>
|
|
<ul className="divide-y text-sm">
|
|
{items.map((a) => <li key={a.id} className="flex justify-between gap-3 py-2"><span>{a.action.replace(/_/g, " ")} <span className="text-gray-500">({a.actorRole}{a.targetId ? ` · ${a.targetType}` : ""})</span></span><span className="shrink-0 text-gray-500">{when(a.createdAt)}</span></li>)}
|
|
{!items.length && <li className="py-2 text-gray-500">Nothing yet.</li>}
|
|
</ul>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
// ─── Backups (1.3.0) ─────────────────────────────────────────────────────────
|
|
|
|
type BackupList = { items: { filename: string; size: number; createdAt: string }[]; nightly: boolean; retain: number; lastError: string | null };
|
|
|
|
const size = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / (1024 * 1024)).toFixed(1)} MB`);
|
|
|
|
function Backups({ flash }: { flash: Flash }) {
|
|
const [data, setData] = useState<BackupList | null>(null);
|
|
const [running, setRunning] = useState(false);
|
|
const [saving, setSaving] = useState(false);
|
|
const load = useCallback(async () => {
|
|
const r = await call<BackupList>("GET", "/admin/backups");
|
|
if (r.ok) setData(r.data);
|
|
}, []);
|
|
useExternalEffect(() => { void load(); }, [load]);
|
|
if (!data) return <p className="text-gray-600">Loading…</p>;
|
|
return (
|
|
<div className="space-y-6">
|
|
<Card>
|
|
<Heading icon={<DatabaseBackup className="h-4 w-4" />} sub="Every night at 02:00, and before every update of Accounts. Kept on this server only, never sent anywhere.">Database backups</Heading>
|
|
{data.lastError && <Notice tone="warning">The last backup didn't work: {data.lastError}</Notice>}
|
|
<Button busy={running} onClick={async () => {
|
|
setRunning(true);
|
|
const r = await call<{ filename: string }>("POST", "/admin/backups/run");
|
|
setRunning(false);
|
|
if (r.ok) { flash("success", `Backup made: ${r.data.filename}`); } else flash("error", r.error.message);
|
|
void load();
|
|
}}>Back up now</Button>
|
|
|
|
<form className="mt-5 flex flex-wrap items-end gap-x-4 gap-y-2 border-t pt-4" onSubmit={async (e) => {
|
|
e.preventDefault();
|
|
const f = new FormData(e.currentTarget);
|
|
setSaving(true);
|
|
const r = await call<{ deleted: number }>("PUT", "/admin/backups/settings", { retain: Number(f.get("retain")), nightly: f.get("nightly") === "on" });
|
|
setSaving(false);
|
|
if (r.ok) { flash("success", r.data.deleted ? `Saved. ${r.data.deleted} older backups were deleted.` : "Saved."); void load(); } else flash("error", r.error.message);
|
|
}}>
|
|
<div className="w-full"><Checkbox name="nightly" label="Back up every night" defaultChecked={data.nightly} hint="Backups before each update are made either way." /></div>
|
|
<Field label="Keep the newest" name="retain" type="number" min={1} max={365} defaultValue={String(data.retain)} className="mb-0 w-32" />
|
|
<span className="pb-3 text-sm text-gray-500">backups, and delete older ones</span>
|
|
<Button type="submit" variant="secondary" busy={saving} className="mb-1 ml-auto">Save</Button>
|
|
</form>
|
|
</Card>
|
|
|
|
<Card>
|
|
<Heading sub="A backup holds everyone's details: keep a downloaded copy somewhere safe, and delete it when you're done.">Backups on this server</Heading>
|
|
<div className="overflow-x-auto rounded-lg border">
|
|
<table className="min-w-full text-sm">
|
|
<thead><tr className="border-b bg-gray-50 text-left text-gray-600"><th className="p-2.5 font-medium">Made</th><th className="p-2.5 font-medium">Size</th><th className="p-2.5 font-medium"><span className="sr-only">Download</span></th></tr></thead>
|
|
<tbody>
|
|
{data.items.map((b) => (
|
|
<tr key={b.filename} className="border-t">
|
|
<td className="p-2.5">{when(b.createdAt)}</td>
|
|
<td className="p-2.5 text-gray-500">{size(b.size)}</td>
|
|
<td className="p-2.5 text-right">
|
|
<a href={`/api/v2/admin/backups/${encodeURIComponent(b.filename)}/download`} download className="inline-flex items-center gap-1.5 text-brand hover:underline">
|
|
<Download className="h-3.5 w-3.5" aria-hidden /> Download
|
|
</a>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
{!data.items.length && <tr><td colSpan={3} className="p-3 text-gray-500">No backups yet.</td></tr>}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ─── Background jobs (1.4.0, as Cross Events) ────────────────────────────────
|
|
|
|
type JobRun = { state: string; createdOn?: string | null; startedOn: string | null; completedOn: string | null; output: unknown };
|
|
type JobInfo = {
|
|
name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[];
|
|
envEnabled: boolean; envCron: string; defaultCron: string; override: { enabled: boolean | null; cron: string | null };
|
|
};
|
|
type JobList = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] };
|
|
|
|
const RUN_STATE: Record<string, string> = {
|
|
completed: "bg-green-50 text-green-800", failed: "bg-red-50 text-red-700", active: "bg-blue-50 text-blue-700",
|
|
created: "bg-gray-100 text-gray-600", retry: "bg-amber-50 text-amber-800", cancelled: "bg-gray-100 text-gray-500",
|
|
};
|
|
const SCHEDULES = [
|
|
{ label: "Every minute", cron: "* * * * *" }, { label: "Every 5 minutes", cron: "*/5 * * * *" }, { label: "Every 15 minutes", cron: "*/15 * * * *" },
|
|
{ label: "Every hour", cron: "0 * * * *" }, { label: "Daily at 02:00", cron: "0 2 * * *" }, { label: "Daily at 07:00", cron: "0 7 * * *" },
|
|
];
|
|
|
|
function describeCron(cron: string): string {
|
|
if (cron === "* * * * *") return "Every minute";
|
|
const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron);
|
|
if (m) return `Every ${m[1]} minutes`;
|
|
const h = /^(\d+) \* \* \* \*$/.exec(cron);
|
|
if (h) return `Every hour at :${h[1]!.padStart(2, "0")}`;
|
|
const d = /^(\d+) (\d+) \* \* \*$/.exec(cron);
|
|
if (d) return `Daily at ${d[2]!.padStart(2, "0")}:${d[1]!.padStart(2, "0")}`;
|
|
return cron;
|
|
}
|
|
|
|
function runText(r: JobRun): string {
|
|
if (r.output === null || r.output === undefined) return "";
|
|
if (r.state === "failed" && typeof r.output === "object" && r.output && "message" in r.output) return String((r.output as { message: unknown }).message);
|
|
try { return JSON.stringify(r.output); } catch { return ""; }
|
|
}
|
|
|
|
/** An on/off switch (role="switch", so screen readers hear on and off). */
|
|
function Toggle({ on, label, disabled, onChange }: { on: boolean; label: string; disabled?: boolean; onChange: (on: boolean) => void }) {
|
|
return (
|
|
<button type="button" role="switch" aria-checked={on} aria-label={label} disabled={disabled} onClick={() => onChange(!on)}
|
|
className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed disabled:opacity-50 ${on ? "bg-brand" : "bg-gray-300"}`}>
|
|
<span className={`inline-block h-5 w-5 rounded-full bg-white shadow transition-transform ${on ? "translate-x-5" : "translate-x-0.5"}`} />
|
|
</button>
|
|
);
|
|
}
|
|
|
|
function Jobs({ flash }: { flash: Flash }) {
|
|
const [data, setData] = useState<JobList | null>(null);
|
|
const [busy, setBusy] = useState<string | null>(null);
|
|
const [open, setOpen] = useState<string | null>(null);
|
|
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
|
|
const [loadError, setLoadError] = useState<string | null>(null);
|
|
// Not tied to `flash` (a new function each render): the list loads once, then on Refresh.
|
|
const load = useCallback(async () => {
|
|
const r = await call<JobList>("GET", "/admin/jobs");
|
|
if (r.ok) { setData(r.data); setLoadError(null); } else setLoadError(r.error.message);
|
|
}, []);
|
|
useExternalEffect(() => { void load(); }, [load]);
|
|
|
|
const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => {
|
|
setBusy(job.name);
|
|
const r = await call("PUT", `/admin/jobs/${encodeURIComponent(job.name)}`, change);
|
|
setBusy(null);
|
|
if (r.ok) { flash("success", done); setEditing(null); void load(); } else flash("error", r.error.message);
|
|
};
|
|
const runNow = async (job: JobInfo) => {
|
|
setBusy(job.name);
|
|
const r = await call<{ queued: boolean }>("POST", `/admin/jobs/${encodeURIComponent(job.name)}/run`);
|
|
setBusy(null);
|
|
if (r.ok) {
|
|
flash("success", r.data.queued ? `"${job.label}" queued: it starts within a few seconds.` : `"${job.label}" ran.`);
|
|
setTimeout(() => void load(), r.data.queued ? 4000 : 0);
|
|
} else flash("error", r.error.message);
|
|
};
|
|
|
|
if (!data) return loadError ? <Notice tone="error">{loadError}</Notice> : <p className="text-gray-600">Loading…</p>;
|
|
const off = data.mode === "off";
|
|
return (
|
|
<Card>
|
|
<div className="mb-3 flex items-start justify-between gap-3">
|
|
<Heading icon={<Timer className="h-4 w-4" />} sub={`Times are ${data.timezone}. Each job runs once per schedule, however many server processes there are.`}>Jobs</Heading>
|
|
<Button variant="secondary" onClick={() => void load()}><RefreshCw className="mr-1.5 inline h-3.5 w-3.5" aria-hidden />Refresh</Button>
|
|
</div>
|
|
{off && <Notice tone="warning">All background jobs are switched off in the server's .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change that from the Hub.</Notice>}
|
|
{data.mode === "timers" && <Notice tone="warning">The job queue couldn't start, so jobs run on simple timers in this process (history only since the last restart).</Notice>}
|
|
<ul className="divide-y rounded-lg border">
|
|
{data.jobs.map((job) => {
|
|
const last = job.recent[0];
|
|
const mine = busy === job.name;
|
|
const isEditing = editing?.name === job.name;
|
|
return (
|
|
<li key={job.name} className="p-3">
|
|
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
|
|
<Toggle on={job.enabled} disabled={mine || off} label={`${job.label}: ${job.enabled ? "on" : "off"}`}
|
|
onChange={(on) => void save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} />
|
|
<div className="mr-auto min-w-0">
|
|
<div className={`text-sm font-medium ${job.enabled ? "text-gray-900" : "text-gray-500"}`}>{job.label}</div>
|
|
<div className="text-xs text-gray-500">
|
|
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"}
|
|
{job.override.enabled !== null
|
|
? <> · {job.enabled ? "switched on" : "switched off"} here · <button type="button" disabled={mine} className="underline hover:text-gray-700" onClick={() => void save(job, { enabled: null }, `"${job.label}" follows the .env again.`)}>use the .env ({job.envEnabled ? "on" : "off"})</button></>
|
|
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
|
|
</div>
|
|
</div>
|
|
{last && (
|
|
<button type="button" onClick={() => setOpen(open === job.name ? null : job.name)} title="Recent runs" className={`rounded px-2 py-0.5 text-xs ${RUN_STATE[last.state] ?? "bg-gray-100 text-gray-600"}`}>
|
|
{last.state} · {when(last.completedOn || last.startedOn || last.createdOn)}
|
|
</button>
|
|
)}
|
|
<Button variant="secondary" disabled={mine || isEditing} onClick={() => setEditing({ name: job.name, cron: job.cron })}>Schedule</Button>
|
|
<Button variant="secondary" disabled={!!busy || off} onClick={() => void runNow(job)}><Play className="mr-1 inline h-3.5 w-3.5" aria-hidden />Run now</Button>
|
|
</div>
|
|
{isEditing && editing && (
|
|
<form className="mt-3 space-y-2 rounded-lg border bg-gray-50 p-3" onSubmit={(e) => { e.preventDefault(); void save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
|
|
<div className="flex flex-wrap gap-1.5">
|
|
{SCHEDULES.map((p) => (
|
|
<button key={p.cron} type="button" onClick={() => setEditing({ name: job.name, cron: p.cron })}
|
|
className={`rounded border px-2 py-1 text-xs ${editing.cron === p.cron ? "border-brand bg-white font-medium" : "bg-white hover:bg-gray-100"}`}>{p.label}</button>
|
|
))}
|
|
</div>
|
|
<div className="flex flex-wrap items-end gap-3">
|
|
<Field label="Cron (minute hour day month weekday)" name="cron" value={editing.cron} maxLength={100} className="mb-0 w-64 font-mono"
|
|
onChange={(e) => setEditing({ name: job.name, cron: e.target.value })} hint={describeCron(editing.cron.trim())} />
|
|
<div className="ml-auto flex gap-2 pb-6">
|
|
<Button type="button" variant="secondary" onClick={() => setEditing(null)}>Cancel</Button>
|
|
<Button type="submit" busy={mine} disabled={!editing.cron.trim()}>Save schedule</Button>
|
|
</div>
|
|
</div>
|
|
<p className="text-xs text-gray-500">
|
|
The server's own schedule is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (from the .env; normally ${describeCron(job.defaultCron)})` : ""}.{" "}
|
|
{job.override.cron !== null && <button type="button" disabled={mine} className="underline hover:text-gray-700" onClick={() => void save(job, { cron: null }, `"${job.label}" is back on its own schedule.`)}>Use that again</button>}
|
|
</p>
|
|
</form>
|
|
)}
|
|
{open === job.name && job.recent.length > 0 && (
|
|
<div className="mt-2 overflow-x-auto">
|
|
<table className="w-full text-xs">
|
|
<thead className="text-gray-500"><tr><th className="py-1 text-left font-medium">Started</th><th className="text-left font-medium">Finished</th><th className="text-left font-medium">State</th><th className="text-left font-medium">Result</th></tr></thead>
|
|
<tbody>
|
|
{job.recent.map((r, i) => (
|
|
<tr key={i} className="border-t">
|
|
<td className="whitespace-nowrap py-1 pr-2">{when(r.startedOn)}</td>
|
|
<td className="whitespace-nowrap pr-2">{when(r.completedOn)}</td>
|
|
<td className="pr-2"><span className={`rounded px-1.5 py-0.5 ${RUN_STATE[r.state] ?? ""}`}>{r.state}</span></td>
|
|
<td className="break-all font-mono text-[11px] text-gray-600">{runText(r)}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
</li>
|
|
);
|
|
})}
|
|
</ul>
|
|
<p className="mt-3 text-xs text-gray-500">Without a choice here, the server's .env applies: a job's own flag (e.g. BACKUP_ENABLED=false) and JOB_SCHEDULE_<NAME>. The nightly backup also follows Backups → "Back up every night".</p>
|
|
</Card>
|
|
);
|
|
}
|