436 lines
18 KiB
TypeScript
436 lines
18 KiB
TypeScript
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 <span className="badge bg-secondary-lt text-secondary">{status.label}</span>;
|
|
if (status.key === "failing") return <span className="badge bg-red-lt text-red">{status.label}</span>;
|
|
if (status.key === "working") return <span className="badge bg-green-lt text-green">{status.label}</span>;
|
|
return (
|
|
<span className="badge bg-secondary-lt text-secondary" title="Nothing has called it since the app started. Use Test to check it now.">
|
|
{status.label}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
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<string, string>, 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") => (
|
|
<ViewTabs
|
|
label="Integrations view"
|
|
tabs={[
|
|
{ to: "/integrations", label: "Integrations", active: view === "list" },
|
|
{ to: "/integrations?view=calls", label: "Call log", active: view === "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 (
|
|
<>
|
|
<div className="d-flex align-items-center mb-2">
|
|
<h2 className="page-title mb-0">Integrations</h2>
|
|
</div>
|
|
{integrationTabs("calls")}
|
|
<DiagLogView />
|
|
</>
|
|
);
|
|
}
|
|
return <IntegrationsList user={user} tabs={isAdmin ? integrationTabs("list") : null} />;
|
|
}
|
|
|
|
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<IntegrationSummary[] | null>(null);
|
|
const [adding, setAdding] = useState(false);
|
|
const [editingIntegration, setEditingIntegration] = useState<IntegrationSummary | null>(null);
|
|
const [inspecting, setInspecting] = useState<IntegrationSummary | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [integrationColors, setIntegrationColors] = useState<Record<string, string>>({});
|
|
const [testingId, setTestingId] = useState<number | null>(null);
|
|
const [testResults, setTestResults] = useState<Record<number, { ok: boolean; latencyMs?: number; error?: string }>>({});
|
|
|
|
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<IntegrationRow>(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<string, { id: string; label: string; items: IntegrationSummary[] }>();
|
|
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 && (
|
|
<Link to={page} className="btn btn-sm btn-primary">
|
|
Open
|
|
</Link>
|
|
)}
|
|
{isOperator && i.enabled && <ReadNowButton integrationId={i.id} name={i.name} onDone={loadIntegrations} />}
|
|
{isAdmin && (
|
|
<>
|
|
<button className="btn btn-sm" onClick={() => testIntegration(i)} disabled={testingId === i.id}>
|
|
{testingId === i.id ? "Testing…" : "Test"}
|
|
</button>
|
|
{i.enabled && INSPECTABLE.includes(i.type) && (
|
|
<button className="btn btn-sm" onClick={() => setInspecting(i)} title="Read it once now and see what each request got back — to check that what is shown is what is there">
|
|
Inspect
|
|
</button>
|
|
)}
|
|
<button className="btn btn-sm" onClick={() => setEditingIntegration(i)}>
|
|
Edit
|
|
</button>
|
|
<button className="btn btn-sm" onClick={() => toggleEnabled(i)}>
|
|
{i.enabled ? "Disable" : "Enable"}
|
|
</button>
|
|
<button className="btn btn-sm btn-outline-danger" onClick={() => removeIntegration(i)}>
|
|
Delete
|
|
</button>
|
|
</>
|
|
)}
|
|
</>
|
|
);
|
|
}
|
|
|
|
/** 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 (
|
|
<span className={`badge ms-2 ${result.ok ? "bg-green-lt text-green" : "bg-red-lt text-red"}`}>
|
|
Test {result.ok ? `passed${result.latencyMs !== undefined ? ` (${result.latencyMs}ms)` : ""}` : "failed"}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<div className="d-flex align-items-center mb-3">
|
|
<div>
|
|
<h2 className="page-title mb-0">Integrations</h2>
|
|
<div className="text-secondary small mt-1">
|
|
Each connected system gets its own page — open it from here or from the sidebar, in the group shown. Add and manage credentials here.
|
|
</div>
|
|
</div>
|
|
{isAdmin && !adding && !editingIntegration && (
|
|
<button className="btn btn-primary ms-auto" onClick={() => setAdding(true)}>
|
|
Add integration
|
|
</button>
|
|
)}
|
|
</div>
|
|
{tabs}
|
|
<ErrorNotice error={error} />
|
|
{inspecting && <IntegrationInspector integration={inspecting} onClose={() => setInspecting(null)} />}
|
|
|
|
{editingIntegration ? (
|
|
<IntegrationEditForm
|
|
integration={editingIntegration}
|
|
onSaved={() => {
|
|
setEditingIntegration(null);
|
|
loadIntegrations();
|
|
}}
|
|
onCancel={() => setEditingIntegration(null)}
|
|
/>
|
|
) : (
|
|
adding && (
|
|
<IntegrationForm
|
|
onCreated={() => {
|
|
setAdding(false);
|
|
loadIntegrations();
|
|
}}
|
|
onCancel={() => setAdding(false)}
|
|
/>
|
|
)
|
|
)}
|
|
|
|
<div className="card mb-3">
|
|
<TableToolbar
|
|
search={tableSearch.query}
|
|
onSearch={tableSearch.setQuery}
|
|
placeholder="Search integrations…"
|
|
filters={
|
|
<select
|
|
className="form-select form-select-sm w-auto"
|
|
aria-label="Show integrations that are"
|
|
value={statusFilter}
|
|
onChange={(e) =>
|
|
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 },
|
|
)
|
|
}
|
|
>
|
|
<option value="">Any status</option>
|
|
<option value="failing">Failing</option>
|
|
<option value="working">Working</option>
|
|
<option value="disabled">Disabled</option>
|
|
</select>
|
|
}
|
|
actions={
|
|
<div className="btn-group btn-group-sm" role="group" aria-label="How to show the integrations">
|
|
<button type="button" className={`btn ${layout === "cards" ? "active" : ""}`} aria-pressed={layout === "cards"} onClick={() => chooseLayout("cards")}>
|
|
Cards
|
|
</button>
|
|
<button type="button" className={`btn ${layout === "table" ? "active" : ""}`} aria-pressed={layout === "table"} onClick={() => chooseLayout("table")}>
|
|
Table
|
|
</button>
|
|
</div>
|
|
}
|
|
shown={sortedIntegrations?.length}
|
|
total={integrations?.length}
|
|
onExport={exportCsv}
|
|
exportDisabled={!integrations || integrations.length === 0}
|
|
/>
|
|
</div>
|
|
|
|
{layout === "table" && sortedRows && sortedRows.length > 0 && (
|
|
<div className="card mb-3">
|
|
<div className="table-responsive">
|
|
<table className="table table-vcenter card-table">
|
|
<thead>
|
|
<tr>
|
|
<SortableTh<IntegrationRow> label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<SortableTh<IntegrationRow> label="Kind" sortKeyName="kind" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<SortableTh<IntegrationRow> label="Group" sortKeyName="group" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<SortableTh<IntegrationRow> label="Address" sortKeyName="host" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<SortableTh<IntegrationRow> label="Status" sortKeyName="statusRank" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<th scope="col">Last 30 days</th>
|
|
<th scope="col">Actions</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{sortedRows.map(({ integration: i }) => (
|
|
<tr key={i.id}>
|
|
<td className="fw-bold text-nowrap">{i.name}</td>
|
|
<td>
|
|
<span className="badge" style={typeBadgeStyle(integrationColors, i.type)}>
|
|
{TYPE_LABELS[i.type]}
|
|
</span>
|
|
</td>
|
|
<td className="text-secondary">{groupOfType(i.type).label}</td>
|
|
<td className="text-secondary">{hostOf(i.baseUrl) || "no web address"}</td>
|
|
<td>
|
|
<HealthBadge i={i} />
|
|
{testBadge(i)}
|
|
{testResults[i.id] && !testResults[i.id].ok && testingId !== i.id && <div className="text-red small mt-1">{testResults[i.id].error}</div>}
|
|
</td>
|
|
<td>{i.enabled ? <UptimeRibbon kind="integrations" id={i.id} name={i.name} /> : <span className="text-secondary">—</span>}</td>
|
|
<td>
|
|
<div className="btn-list">{actionsOf(i)}</div>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<div className="row row-cards">
|
|
{layout === "cards" && groupedIntegrations.map((group) => (
|
|
<Fragment key={group.id}>
|
|
<div className="col-12">
|
|
<h4 className="mb-0 mt-2">
|
|
{group.label} <span className="text-secondary fw-normal small">{group.items.length}</span>
|
|
</h4>
|
|
</div>
|
|
{group.items.map((i) => {
|
|
const result = testResults[i.id];
|
|
return (
|
|
<div className="col-md-6 col-xl-4" key={i.id}>
|
|
<div className="card h-100">
|
|
<div className="card-body d-flex flex-column">
|
|
<div className="d-flex align-items-start gap-2 mb-2">
|
|
<div className="flex-fill" style={{ minWidth: 0 }}>
|
|
<div className="fw-bold text-truncate">{i.name}</div>
|
|
<div className="text-secondary small text-truncate">{hostOf(i.baseUrl) || "no web address"}</div>
|
|
</div>
|
|
<span className="badge flex-shrink-0" style={typeBadgeStyle(integrationColors, i.type)}>
|
|
{TYPE_LABELS[i.type]}
|
|
</span>
|
|
</div>
|
|
<div className="mb-3">
|
|
<HealthBadge i={i} />
|
|
{testBadge(i)}
|
|
</div>
|
|
{i.enabled && (
|
|
<div className="mb-3">
|
|
<UptimeRibbon kind="integrations" id={i.id} name={i.name} />
|
|
</div>
|
|
)}
|
|
<div className="mb-3">
|
|
<RunbookEntry targetType="integration" targetId={i.id} targetName={i.name} canEdit={isOperator} offerAdd />
|
|
</div>
|
|
{result && !result.ok && testingId !== i.id && <div className="text-red small mb-3">{result.error}</div>}
|
|
<div className="btn-list mt-auto">{actionsOf(i)}</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</Fragment>
|
|
))}
|
|
{sortedIntegrations?.length === 0 && (
|
|
<div className="col-12">
|
|
<div className="card">
|
|
<div className="card-body text-secondary text-center">
|
|
{tableSearch.active || statusFilter ? "Nothing matches that." : "No integrations configured yet."}
|
|
{isAdmin && !tableSearch.active && !statusFilter && (
|
|
<>
|
|
{" "}
|
|
<button className="btn btn-link p-0 align-baseline" onClick={() => setAdding(true)}>
|
|
Add one
|
|
</button>
|
|
.
|
|
</>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</>
|
|
);
|
|
}
|