"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; }; 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 = { 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 (

Signing secret — copy it now, it won't be shown again

{secret}

Each request has an X-CrossEvents-Signature: t=…,v1=… header: v1 is the HMAC-SHA256 (hex) of <t>.<body> with this secret. Check it, and that t is recent, before trusting a request.

); } function Deliveries({ endpointId, token }: { endpointId: string; token: string }) { const [rows, setRows] = useState(null); const [open, setOpen] = useState(null); const [busy, setBusy] = useState(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).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

Loading…

; if (!rows.length && !status) return

Nothing sent yet.

; return (
{!rows.length &&

None with this status.

}
    {rows.map(d => (
  • {when(d.createdAt)} {d.type} {d.status} {d.attempts} tr{d.attempts === 1 ? "y" : "ies"}{d.lastStatusCode ? ` · ${d.lastStatusCode}` : ""}{d.status === "retrying" ? ` · next ${when(d.nextAttemptAt)}` : ""} {d.lastError && {d.lastError}} {d.status !== "sending" && ( )}
    {open === d.id &&
    {JSON.stringify(d.payload, null, 2)}
    }
  • ))}
{more && (
)}
); } // 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(null); const [draft, setDraft] = useState(null); const [secret, setSecret] = useState<{ endpointId: string; value: string } | null>(null); const [openLog, setOpenLog] = useState(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)); } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Couldn't load webhooks" }); } }, [token]); useExternalEffect(() => { if (active) load(); }, [active, load]); const run = async (fn: () => Promise) => { 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); 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 ?

{msg.text}

:

Loading…

; const label = (type: string) => data.eventTypes.find(t => t.type === type)?.label || type; return (

Webhooks

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).

{!draft && }

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.

{msg &&
{msg.text}
} {secret && setSecret(null)} />} {draft && (
setDraft({ ...draft, name: e.target.value })} placeholder="e.g. ChurchSuite sync" />
setDraft({ ...draft, url: e.target.value })} placeholder="https://…" />
Send when
{data.eventTypes.map(t => ( ))}
)} {data.endpoints.length === 0 && !draft ? (

No webhooks yet.

) : (
    {data.endpoints.map(e => (
  • {e.name} {!e.isActive && Off}
    {e.url}
    {e.events.map(t => {label(t)})}
    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(", ")}}
    {openLog === e.id && token && }
  • ))}
)}
); }