import { Fragment, useEffect, useState, type CSSProperties, type ReactNode } from "react"; import { Link, useSearchParams } from "react-router-dom"; import { api, type CurrentUser, type IntegrationSummary, type IntegrationType } from "../api/client"; import IntegrationForm from "../components/IntegrationForm"; import ViewTabs from "../components/ViewTabs"; import DiagLogView from "../views/DiagLogView"; import IntegrationEditForm from "../components/IntegrationEditForm"; import TableToolbar from "../components/TableToolbar"; import { useTableSearch } from "../hooks/useTableSearch"; import { downloadCsv } from "../utils/csv"; import { confirmDialog } from "../utils/dialogs"; import { ErrorNotice } from "../components/Notice"; import { toast } from "../utils/toast"; import UptimeRibbon from "../components/UptimeRibbon"; import RunbookEntry from "../components/RunbookEntry"; import IntegrationInspector from "../components/IntegrationInspector"; import ReadNowButton from "../components/ReadNowButton"; import { groupOfType, INSPECTABLE, TYPE_GROUPS, TYPE_LABELS, TYPE_PAGES } from "../utils/integrationTypes"; import { hostOf, integrationRow, integrationStatus, type IntegrationRow } from "../utils/integrationRows"; import { useSortable } from "../hooks/useSortable"; import SortableTh from "../components/SortableTh"; function HealthBadge({ i }: { i: IntegrationSummary }) { const status = integrationStatus(i); if (status.key === "disabled") return {status.label}; if (status.key === "failing") return {status.label}; if (status.key === "working") return {status.label}; return ( {status.label} ); } const LAYOUT_KEY = "integrations.layout"; /** Cards or table: the address says so when it does, else what this browser last chose, else cards. */ function layoutOf(param: string | null): "cards" | "table" { if (param === "table" || param === "cards") return param; try { return localStorage.getItem(LAYOUT_KEY) === "table" ? "table" : "cards"; } catch { return "cards"; } } function rememberLayout(layout: "cards" | "table") { try { localStorage.setItem(LAYOUT_KEY, layout); } catch { /* a private window: the choice then lives in the address alone */ } } function typeBadgeStyle(colors: Record, type: IntegrationType): CSSProperties { const color = colors[type]; if (!color) return {}; return { backgroundColor: `${color}22`, color, border: `1px solid ${color}55` }; } const integrationTabs = (view: "list" | "calls") => ( ); /** The integrations, and — for administrators — the log of every call made to them (`?view=calls`), where a connection is troubleshot. */ export default function Integrations({ user }: { user: CurrentUser }) { const [params] = useSearchParams(); const isAdmin = user.role === "admin"; if (isAdmin && params.get("view") === "calls") { return ( <>

Integrations

{integrationTabs("calls")} ); } return ; } function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) { const isAdmin = user.role === "admin"; const isOperator = user.role === "admin" || user.role === "operator"; const [searchParams, setSearchParams] = useSearchParams(); const [integrations, setIntegrations] = useState(null); const [adding, setAdding] = useState(false); const [editingIntegration, setEditingIntegration] = useState(null); const [inspecting, setInspecting] = useState(null); const [error, setError] = useState(null); const [integrationColors, setIntegrationColors] = useState>({}); const [testingId, setTestingId] = useState(null); const [testResults, setTestResults] = useState>({}); useEffect(() => { api.settings.integrationColors().then((res) => setIntegrationColors(res.integrationColors)).catch(() => {}); }, []); function loadIntegrations() { api.integrations .list() .then((res) => { setIntegrations(res.integrations); // Deep-link from global search (?editId=) — jump straight to that integration's edit form. const editId = Number(searchParams.get("editId")); const target = res.integrations.find((i) => i.id === editId); if (target && isAdmin) setEditingIntegration(target); }) .catch((err) => setError(String(err))); } useEffect(loadIntegrations, []); async function toggleEnabled(i: IntegrationSummary) { try { await api.integrations.update(i.id, { enabled: !i.enabled }); toast.success(`${i.name} ${i.enabled ? "disabled" : "enabled"}.`); loadIntegrations(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } } async function testIntegration(i: IntegrationSummary) { setTestingId(i.id); try { const result = await api.integrations.testExisting(i.id, {}); setTestResults((prev) => ({ ...prev, [i.id]: result })); } catch (err) { setTestResults((prev) => ({ ...prev, [i.id]: { ok: false, error: err instanceof Error ? err.message : String(err) } })); } finally { setTestingId(null); } } async function removeIntegration(i: IntegrationSummary) { if (!(await confirmDialog({ title: "Delete integration", message: `Delete integration "${i.name}"?`, confirmLabel: "Delete", danger: true }))) return; try { await api.integrations.remove(i.id); toast.success(`Deleted ${i.name}.`); loadIntegrations(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } } const tableSearch = useTableSearch(integrations); const statusParam = searchParams.get("status"); const statusFilter = statusParam === "failing" || statusParam === "working" || statusParam === "disabled" ? statusParam : ""; const matchesStatus = (i: IntegrationSummary) => statusFilter === "" || (statusFilter === "disabled" ? !i.enabled : statusFilter === "failing" ? i.enabled && i.health?.status === "failing" : i.enabled && i.health?.status === "ok"); const layout = layoutOf(searchParams.get("layout")); function chooseLayout(next: "cards" | "table") { rememberLayout(next); setSearchParams( (prev) => { const p = new URLSearchParams(prev); p.set("layout", next); return p; }, { replace: true }, ); } const sortedIntegrations = tableSearch.filtered ? [...tableSearch.filtered].filter(matchesStatus).sort((a, b) => a.name.localeCompare(b.name)) : null; const rows = sortedIntegrations ? sortedIntegrations.map(integrationRow) : null; const { sorted: sortedRows, sortKey, sortDir, requestSort } = useSortable(rows, "name", "asc", { url: true }); // The cards in groups, as the sidebar groups their pages (a kind nobody has placed goes under "Other"). const groupedIntegrations = (() => { const groups = new Map(); for (const g of [...TYPE_GROUPS.map(({ id, label }) => ({ id, label })), { id: "other", label: "Other" }]) groups.set(g.id, { ...g, items: [] }); for (const i of sortedIntegrations ?? []) groups.get(groupOfType(i.type).id)!.items.push(i); return [...groups.values()].filter((g) => g.items.length > 0); })(); function exportCsv() { if (!sortedIntegrations) return; downloadCsv( "integrations.csv", ["Name", "Type", "Status"], sortedIntegrations.map((i) => [i.name, TYPE_LABELS[i.type], i.enabled ? "Enabled" : "Disabled"]), ); } /** The buttons of a card or a table row: the same, so the two views can do the same things. */ function actionsOf(i: IntegrationSummary) { const page = TYPE_PAGES[i.type]; return ( <> {i.enabled && ( Open )} {isOperator && i.enabled && } {isAdmin && ( <> {i.enabled && INSPECTABLE.includes(i.type) && ( )} )} ); } /** What a test of it said, beside its status. */ function testBadge(i: IntegrationSummary) { const result = testResults[i.id]; if (!result || testingId === i.id) return null; return ( Test {result.ok ? `passed${result.latencyMs !== undefined ? ` (${result.latencyMs}ms)` : ""}` : "failed"} ); } return ( <>

Integrations

Each connected system gets its own page — open it from here or from the sidebar, in the group shown. Add and manage credentials here.
{isAdmin && !adding && !editingIntegration && ( )}
{tabs} {inspecting && setInspecting(null)} />} {editingIntegration ? ( { setEditingIntegration(null); loadIntegrations(); }} onCancel={() => setEditingIntegration(null)} /> ) : ( adding && ( { setAdding(false); loadIntegrations(); }} onCancel={() => setAdding(false)} /> ) )}
setSearchParams( (prev) => { const next = new URLSearchParams(prev); if (e.target.value) next.set("status", e.target.value); else next.delete("status"); return next; }, { replace: true }, ) } > } actions={
} shown={sortedIntegrations?.length} total={integrations?.length} onExport={exportCsv} exportDisabled={!integrations || integrations.length === 0} />
{layout === "table" && sortedRows && sortedRows.length > 0 && (
label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Kind" sortKeyName="kind" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Group" sortKeyName="group" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Address" sortKeyName="host" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Status" sortKeyName="statusRank" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> {sortedRows.map(({ integration: i }) => ( ))}
Last 30 days Actions
{i.name} {TYPE_LABELS[i.type]} {groupOfType(i.type).label} {hostOf(i.baseUrl) || "no web address"} {testBadge(i)} {testResults[i.id] && !testResults[i.id].ok && testingId !== i.id &&
{testResults[i.id].error}
}
{i.enabled ? : —}
{actionsOf(i)}
)}
{layout === "cards" && groupedIntegrations.map((group) => (

{group.label} {group.items.length}

{group.items.map((i) => { const result = testResults[i.id]; return (
{i.name}
{hostOf(i.baseUrl) || "no web address"}
{TYPE_LABELS[i.type]}
{testBadge(i)}
{i.enabled && (
)}
{result && !result.ok && testingId !== i.id &&
{result.error}
}
{actionsOf(i)}
); })}
))} {sortedIntegrations?.length === 0 && (
{tableSearch.active || statusFilter ? "Nothing matches that." : "No integrations configured yet."} {isAdmin && !tableSearch.active && !statusFilter && ( <> {" "} . )}
)}
); }