- The 192 places the rules flagged are fixed and the rules are errors again (npx eslint src: nothing). lib/hooks.ts: useStateSync (state that follows other state, set while rendering), useExternalEffect (API loads and browser reads), useNow; lib/navigation.ts hardNavigate for full reloads after sign-out or identity switches; other pages use the router. Resets moved into the handlers that cause them. - The banner shows and hides at its times on open pages. - HANDOVER, roadmap, README, FEATURES, SETTINGS, CHANGELOG updated; 2.0.0 section drafted in WHATS-NEW. e2e 102/102 (PayFast sandbox skipped); production build passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
287 lines
18 KiB
TypeScript
287 lines
18 KiB
TypeScript
"use client";
|
|
|
|
import React, { useCallback, useState } from "react";
|
|
import { Webhook, Send, RefreshCw, KeyRound, Trash2, Pencil, Copy, ChevronDown, ChevronRight, RotateCcw } from "lucide-react";
|
|
import { useAuth } from "@/hooks/useAuth";
|
|
import { errorMessage } from "@/lib/utils";
|
|
import { WebhookGuide } from "./WebhookGuide";
|
|
import { apiV2Data } from "@/lib/apiV2";
|
|
import { useExternalEffect } from "@/lib/hooks";
|
|
|
|
type EventType = { type: string; label: string; description: string; example?: unknown };
|
|
type Endpoint = {
|
|
id: string; name: string; url: string; events: string[]; isActive: boolean;
|
|
lastSuccessAt: string | null; lastFailureAt: string | null; createdAt: string;
|
|
lastWeek?: Record<string, number>;
|
|
};
|
|
type Delivery = {
|
|
id: string; eventId: string; type: string; status: string; attempts: number; nextAttemptAt: string;
|
|
lastStatusCode: number | null; lastError: string | null; deliveredAt: string | null; createdAt: string; payload: unknown;
|
|
};
|
|
type ListResponse = { eventTypes: EventType[]; keepDays: number; endpoints: Endpoint[] };
|
|
type Draft = { id?: string; name: string; url: string; events: string[] };
|
|
|
|
const when = (d: string | null) => (d ? new Date(d).toLocaleString("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "—");
|
|
// Deliveries shown at a time in the log ("Load older" fetches the next lot).
|
|
const PAGE = 50;
|
|
|
|
const STATUS: Record<string, string> = {
|
|
succeeded: "bg-green-50 text-green-800", failed: "bg-red-50 text-red-700", retrying: "bg-amber-50 text-amber-800",
|
|
pending: "bg-gray-100 text-gray-600", sending: "bg-blue-50 text-blue-700",
|
|
};
|
|
|
|
/** Shown once after adding an endpoint or making a new secret. */
|
|
function SecretBox({ secret, onClose }: { secret: string; onClose: () => void }) {
|
|
const [copied, setCopied] = useState(false);
|
|
return (
|
|
<div className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm space-y-2" data-testid="webhook-secret">
|
|
<p className="font-medium text-amber-900">Signing secret — copy it now, it won't be shown again</p>
|
|
<div className="flex items-center gap-2">
|
|
<code className="flex-1 break-all rounded bg-white border px-2 py-1 text-xs">{secret}</code>
|
|
<button type="button" className="inline-flex items-center gap-1 px-2 py-1 rounded border bg-white text-xs hover:bg-gray-50"
|
|
onClick={() => { navigator.clipboard?.writeText(secret).then(() => setCopied(true)).catch(() => {}); }}>
|
|
<Copy className="w-3.5 h-3.5" /> {copied ? "Copied" : "Copy"}
|
|
</button>
|
|
</div>
|
|
<p className="text-xs text-amber-900">
|
|
Each request has an <code>X-CrossEvents-Signature: t=…,v1=…</code> header: v1 is the HMAC-SHA256 (hex) of <code><t>.<body></code> with this secret. Check it, and that t is recent, before trusting a request.
|
|
</p>
|
|
<button type="button" className="text-xs underline text-amber-900" onClick={onClose}>I've saved it</button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function Deliveries({ endpointId, token }: { endpointId: string; token: string }) {
|
|
const [rows, setRows] = useState<Delivery[] | null>(null);
|
|
const [open, setOpen] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState<string | null>(null);
|
|
const [status, setStatus] = useState("");
|
|
const [more, setMore] = useState(false);
|
|
const fetchPage = useCallback((before?: string) => {
|
|
const qs = new URLSearchParams({ limit: String(PAGE) });
|
|
if (status) qs.set("status", status);
|
|
if (before) qs.set("before", before);
|
|
return (apiV2Data("get", "/outbound-webhooks/{id}/deliveries", { params: { id: endpointId }, query: Object.fromEntries(qs), authToken: token }) as Promise<Delivery[]>).catch(() => [] as Delivery[]);
|
|
}, [endpointId, token, status]);
|
|
const load = useCallback(async () => {
|
|
const page = await fetchPage();
|
|
setRows(page);
|
|
setMore(page.length === PAGE);
|
|
}, [fetchPage]);
|
|
useExternalEffect(() => { load(); }, [load]);
|
|
const loadOlder = async () => {
|
|
if (!rows?.length) return;
|
|
const page = await fetchPage(rows[rows.length - 1].createdAt);
|
|
setRows([...rows, ...page]);
|
|
setMore(page.length === PAGE);
|
|
};
|
|
const resend = async (id: string) => {
|
|
setBusy(id);
|
|
await apiV2Data("post", "/outbound-webhook-deliveries/{id}/resend", { params: { id: id }, authToken: token, body: {} }).catch(() => {});
|
|
setBusy(null);
|
|
load();
|
|
};
|
|
if (!rows) return <p className="text-xs text-gray-500">Loading…</p>;
|
|
if (!rows.length && !status) return <p className="text-xs text-gray-500">Nothing sent yet.</p>;
|
|
return (
|
|
<div className="space-y-1" data-testid="webhook-deliveries">
|
|
<div className="flex items-center justify-between gap-2">
|
|
<select aria-label="Show deliveries" className="border rounded px-2 py-1 text-xs" value={status} onChange={e => setStatus(e.target.value)}>
|
|
<option value="">All deliveries</option>
|
|
<option value="failed">Failed</option>
|
|
<option value="retrying">Retrying</option>
|
|
<option value="succeeded">Succeeded</option>
|
|
</select>
|
|
<button type="button" onClick={load} className="inline-flex items-center gap-1 text-xs text-gray-600 hover:text-gray-900"><RefreshCw className="w-3 h-3" aria-hidden="true" /> Refresh</button>
|
|
</div>
|
|
{!rows.length && <p className="text-xs text-gray-500">None with this status.</p>}
|
|
<ul className="divide-y border rounded-lg bg-white">
|
|
{rows.map(d => (
|
|
<li key={d.id} className="text-xs" data-testid="webhook-delivery">
|
|
<div className="flex flex-wrap items-center gap-2 px-3 py-2">
|
|
<button type="button" onClick={() => setOpen(open === d.id ? null : d.id)} className="text-gray-500" aria-label="Show what was sent">
|
|
{open === d.id ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
|
|
</button>
|
|
<span className="text-gray-500 w-28">{when(d.createdAt)}</span>
|
|
<code className="font-medium">{d.type}</code>
|
|
<span className={`px-1.5 py-0.5 rounded ${STATUS[d.status] || "bg-gray-100"}`}>{d.status}</span>
|
|
<span className="text-gray-500">
|
|
{d.attempts} tr{d.attempts === 1 ? "y" : "ies"}{d.lastStatusCode ? ` · ${d.lastStatusCode}` : ""}{d.status === "retrying" ? ` · next ${when(d.nextAttemptAt)}` : ""}
|
|
</span>
|
|
{d.lastError && <span className="text-red-700 truncate max-w-[16rem]" title={d.lastError}>{d.lastError}</span>}
|
|
{d.status !== "sending" && (
|
|
<button type="button" disabled={busy === d.id} onClick={() => resend(d.id)} className="ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded border bg-white hover:bg-gray-50 disabled:opacity-50">
|
|
<RotateCcw className="w-3 h-3" /> Resend
|
|
</button>
|
|
)}
|
|
</div>
|
|
{open === d.id && <pre className="mx-3 mb-2 max-h-64 overflow-auto rounded bg-gray-50 p-2 text-[11px]">{JSON.stringify(d.payload, null, 2)}</pre>}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
{more && (
|
|
<div className="flex justify-center">
|
|
<button type="button" onClick={loadOlder} className="text-xs px-3 py-1 rounded border bg-white hover:bg-gray-50">Load older</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// Settings → Webhooks: send what happens here (registrations, payments, check-ins…) to other systems.
|
|
export function WebhooksTab({ active }: { active: boolean }) {
|
|
const { token } = useAuth();
|
|
const [data, setData] = useState<ListResponse | null>(null);
|
|
const [draft, setDraft] = useState<Draft | null>(null);
|
|
const [secret, setSecret] = useState<{ endpointId: string; value: string } | null>(null);
|
|
const [openLog, setOpenLog] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
|
|
|
|
const load = useCallback(async () => {
|
|
if (!token) return;
|
|
try { setData(await (apiV2Data("get", "/outbound-webhooks", { authToken: token }) as Promise<ListResponse>)); } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Couldn't load webhooks" }); }
|
|
}, [token]);
|
|
useExternalEffect(() => { if (active) load(); }, [active, load]);
|
|
|
|
const run = async (fn: () => Promise<void>) => {
|
|
setBusy(true); setMsg(null);
|
|
try { await fn(); } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Something went wrong" }); } finally { setBusy(false); }
|
|
};
|
|
|
|
const save = () => run(async () => {
|
|
if (!draft) return;
|
|
const body = { name: draft.name, url: draft.url, events: draft.events };
|
|
if (draft.id) {
|
|
await apiV2Data("patch", "/outbound-webhooks/{id}", { params: { id: draft.id }, authToken: token, body });
|
|
setMsg({ type: "ok", text: "Webhook saved." });
|
|
} else {
|
|
const made = await (apiV2Data("post", "/outbound-webhooks", { authToken: token, body }) as Promise<Endpoint & { secret: string }>);
|
|
setSecret({ endpointId: made.id, value: made.secret });
|
|
setMsg({ type: "ok", text: `"${made.name}" added, and listed in the operator register (Admin → Privacy).` });
|
|
}
|
|
setDraft(null);
|
|
await load();
|
|
});
|
|
|
|
const toggle = (e: Endpoint) => run(async () => {
|
|
await apiV2Data("patch", "/outbound-webhooks/{id}", { params: { id: e.id }, authToken: token, body: { isActive: !e.isActive } });
|
|
await load();
|
|
});
|
|
const test = (e: Endpoint) => run(async () => {
|
|
const r = await (apiV2Data("post", "/outbound-webhooks/{id}/test", { params: { id: e.id }, authToken: token, body: {} }) as Promise<{ status: string; statusCode: number | null; error: string | null }>);
|
|
setMsg(r.status === "succeeded"
|
|
? { type: "ok", text: `Test delivered (answered ${r.statusCode}).` }
|
|
: { type: "err", text: `Test not delivered: ${r.error || "no answer"}. It will be retried; see the delivery log.` });
|
|
if (openLog === e.id) setOpenLog(null);
|
|
await load();
|
|
});
|
|
const rotate = (e: Endpoint) => run(async () => {
|
|
if (!confirm(`Make a new secret for "${e.name}"? The old one stops working at once, so update the receiving side straight away.`)) return;
|
|
const r = await (apiV2Data("post", "/outbound-webhooks/{id}/rotate-secret", { params: { id: e.id }, authToken: token, body: {} }) as Promise<{ secret: string }>);
|
|
setSecret({ endpointId: e.id, value: r.secret });
|
|
});
|
|
const remove = (e: Endpoint) => run(async () => {
|
|
if (!confirm(`Delete "${e.name}" and its delivery log?`)) return;
|
|
await apiV2Data("delete", "/outbound-webhooks/{id}", { params: { id: e.id }, authToken: token });
|
|
setMsg({ type: "ok", text: "Webhook deleted. Its operator register entry is marked inactive." });
|
|
await load();
|
|
});
|
|
|
|
const toggleEvent = (type: string) => setDraft(d => d && ({ ...d, events: d.events.includes(type) ? d.events.filter(t => t !== type) : [...d.events, type] }));
|
|
|
|
if (!data) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
|
|
const label = (type: string) => data.eventTypes.find(t => t.type === type)?.label || type;
|
|
|
|
return (
|
|
<div className="space-y-5">
|
|
<div className="flex items-start justify-between gap-3 flex-wrap">
|
|
<div>
|
|
<h2 className="text-lg font-semibold text-gray-900 flex items-center gap-2"><Webhook className="w-5 h-5" /> Webhooks</h2>
|
|
<p className="text-sm text-gray-500 max-w-2xl">
|
|
Send what happens here — registrations, payments, check-ins, new accounts — to another system as it happens (e.g. ChurchSuite or Planning Center through Zapier or Make).
|
|
</p>
|
|
</div>
|
|
{!draft && <button type="button" onClick={() => { setMsg(null); setDraft({ name: "", url: "", events: [] }); }} className="px-4 py-2 text-sm rounded-lg bg-brand-600 text-white hover:bg-brand-700 font-medium">+ Add webhook</button>}
|
|
</div>
|
|
|
|
<p className="text-xs text-gray-600 bg-gray-50 border rounded-lg p-3">
|
|
Webhooks send personal information (names, email addresses, phone numbers) to the service you choose, so each one is added to your operator register. Make sure you have an agreement with that service. What was sent is kept {data.keepDays} days for the delivery log. Children's details from kids check-in are never sent.
|
|
</p>
|
|
|
|
<WebhookGuide eventTypes={data.eventTypes} keepDays={data.keepDays} defaultOpen={data.endpoints.length === 0} />
|
|
|
|
{msg && <div className={`p-3 border rounded text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`} role="status">{msg.text}</div>}
|
|
{secret && <SecretBox secret={secret.value} onClose={() => setSecret(null)} />}
|
|
|
|
{draft && (
|
|
<div className="border rounded-xl p-4 space-y-3 bg-white" data-testid="webhook-form">
|
|
<div className="grid sm:grid-cols-2 gap-3">
|
|
<div>
|
|
<label className="block text-xs text-gray-600 mb-1" htmlFor="webhook-name">Name</label>
|
|
<input id="webhook-name" className="w-full border rounded px-3 py-2 text-sm" value={draft.name} onChange={e => setDraft({ ...draft, name: e.target.value })} placeholder="e.g. ChurchSuite sync" />
|
|
</div>
|
|
<div>
|
|
<label className="block text-xs text-gray-600 mb-1" htmlFor="webhook-url">Address (https)</label>
|
|
<input id="webhook-url" className="w-full border rounded px-3 py-2 text-sm" value={draft.url} onChange={e => setDraft({ ...draft, url: e.target.value })} placeholder="https://…" />
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<div className="text-xs text-gray-600 mb-1">Send when</div>
|
|
<div className="grid sm:grid-cols-2 gap-2">
|
|
{data.eventTypes.map(t => (
|
|
<label key={t.type} className="flex items-start gap-2 text-sm border rounded-lg p-2 cursor-pointer hover:bg-gray-50">
|
|
<input type="checkbox" className="mt-1" checked={draft.events.includes(t.type)} onChange={() => toggleEvent(t.type)} />
|
|
<span><span className="font-medium">{t.label}</span> <code className="text-[10px] text-gray-500">{t.type}</code><span className="block text-xs text-gray-500">{t.description}</span></span>
|
|
</label>
|
|
))}
|
|
</div>
|
|
</div>
|
|
<div className="flex gap-2">
|
|
<button type="button" disabled={busy || !draft.name.trim() || !draft.url.trim() || !draft.events.length} onClick={save} className="px-4 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50 font-medium">
|
|
{busy ? "Saving…" : draft.id ? "Save webhook" : "Add webhook"}
|
|
</button>
|
|
<button type="button" onClick={() => setDraft(null)} className="px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50">Cancel</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{data.endpoints.length === 0 && !draft ? (
|
|
<p className="text-sm text-gray-500 border rounded-xl p-4">No webhooks yet.</p>
|
|
) : (
|
|
<ul className="space-y-3">
|
|
{data.endpoints.map(e => (
|
|
<li key={e.id} className="border rounded-xl p-4 bg-white space-y-2" data-testid="webhook-endpoint">
|
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
|
<div className="min-w-0">
|
|
<div className="font-medium text-gray-900 flex items-center gap-2">
|
|
{e.name}
|
|
{!e.isActive && <span className="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">Off</span>}
|
|
</div>
|
|
<div className="text-xs text-gray-500 break-all">{e.url}</div>
|
|
<div className="mt-1 flex flex-wrap gap-1">{e.events.map(t => <span key={t} className="text-[10px] px-1.5 py-0.5 rounded bg-brand-50 text-brand-700">{label(t)}</span>)}</div>
|
|
<div className="mt-1 text-xs text-gray-500">
|
|
Last delivered {when(e.lastSuccessAt)}{e.lastFailureAt && <> · last failure {when(e.lastFailureAt)}</>}
|
|
{e.lastWeek && Object.keys(e.lastWeek).length > 0 && <> · this week: {Object.entries(e.lastWeek).map(([s, n]) => `${n} ${s}`).join(", ")}</>}
|
|
</div>
|
|
</div>
|
|
<div className="flex flex-wrap gap-2">
|
|
<button type="button" disabled={busy} onClick={() => test(e)} className="inline-flex items-center gap-1 text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-50 disabled:opacity-50"><Send className="w-3.5 h-3.5" /> Send test</button>
|
|
<button type="button" onClick={() => { setMsg(null); setDraft({ id: e.id, name: e.name, url: e.url, events: e.events }); }} className="inline-flex items-center gap-1 text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-50"><Pencil className="w-3.5 h-3.5" /> Edit</button>
|
|
<button type="button" disabled={busy} onClick={() => toggle(e)} className="text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-50 disabled:opacity-50">{e.isActive ? "Switch off" : "Switch on"}</button>
|
|
<button type="button" disabled={busy} onClick={() => rotate(e)} className="inline-flex items-center gap-1 text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-50 disabled:opacity-50"><KeyRound className="w-3.5 h-3.5" /> New secret</button>
|
|
<button type="button" disabled={busy} onClick={() => remove(e)} className="inline-flex items-center gap-1 text-xs px-2.5 py-1.5 rounded bg-red-50 text-red-700 border border-red-200 disabled:opacity-50"><Trash2 className="w-3.5 h-3.5" /> Delete</button>
|
|
</div>
|
|
</div>
|
|
<button type="button" onClick={() => setOpenLog(openLog === e.id ? null : e.id)} className="inline-flex items-center gap-1 text-xs text-brand-700 hover:underline">
|
|
{openLog === e.id ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />} Delivery log
|
|
</button>
|
|
{openLog === e.id && token && <Deliveries endpointId={e.id} token={token} />}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|