SPB Git

Repository Public

IncidentDetail.tsx 15.8 KB 260 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Command Center (MCC)8 * File             : apps/web/src/features/alerts/IncidentDetail.tsx9 * Module           : features10 * Repository       : https://git.spboucher.ai/maclustr-command-center11 * Project Website  : https://clustr.spboucher.ai12 * Created          : 2026-11-1813 * Last Modified    : 2026-11-1814 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142"use client";43import Link from "next/link";44import { useQueryClient } from "@tanstack/react-query";45import { useMemo, useState } from "react";46import { apiPatch, apiPost, type Schemas } from "@/api/client";47import { ApiError } from "@/api/errors";48import { invalidatePaths, useApiList, useApiQuery } from "@/api/query";49import { NodeLink } from "@/features/shared/nodes";50import { useI18n } from "@/i18n";51import { Page, RequirePermission } from "@/shell/AppShell";52import { useEvent } from "@/shell/realtime";53import { useSession } from "@/shell/session";54import { Button, Combobox, DataStamp, DataTable, Dialog, EmptyState, ErrorState, IconButton, KeyValue, LinkButton, Linkified, QueryBoundary, Segmented, SelectField, SkeletonRows, TextAreaField, TextField, useErrorMessage, useToast, type Column } from "@/ui";55import type { Severity } from "./logic";56import { AlertStateDot, CommentBox, IncidentStateDot, MutationError, SeverityBadge, Timeline } from "./shared";5758type Alert = Schemas["Alert"];59type Incident = Schemas["Incident"];60type State = Schemas["IncidentState"];6162export function IncidentDetail({ id }: { id: string }) {63  const { t } = useI18n();64  const qc = useQueryClient();65  const q = useApiQuery("/incidents/{id}", { path: { id } });66  useEvent("incident.changed", (e) => {67    if (e.incident_id === id) void invalidatePaths(qc, "/incidents");68  });69  return (70    <RequirePermission permission="alerts.read">71      <Page title={q.data ? q.data.incident.title : t("alerts.incident.detailTitle")} sub={<LinkButton href="/alerts?tab=incidents" variant="ghost" size="sm" icon="chevron-left">{t("alerts.incident.back")}</LinkButton>}>72        <div className="stack-lg" data-testid="screen-incident-detail">73          <QueryBoundary query={q}>{(d) => <Body detail={d} updatedAt={q.dataUpdatedAt} />}</QueryBoundary>74        </div>75      </Page>76    </RequirePermission>77  );78}7980function Body({ detail, updatedAt }: { detail: Schemas["IncidentDetail"]; updatedAt: number }) {81  const { t, fmt } = useI18n();82  const session = useSession();83  const qc = useQueryClient();84  const toast = useToast();85  const explain = useErrorMessage();86  const inc = detail.incident;87  const manage = session.can("alerts.manage");88  const [busy, setBusy] = useState(false);89  const [dialog, setDialog] = useState<"edit" | "add" | "owner" | null>(null);9091  const patch = async (body: Schemas["UpdateIncidentRequest"], done: string): Promise<boolean> => {92    setBusy(true);93    try {94      await apiPatch("/incidents/{id}", { path: { id: inc.id }, body });95      toast({ tone: "ok", title: done });96      await invalidatePaths(qc, "/incidents", "/alerts", "/cluster/overview");97      return true;98    } catch (e) {99      toast({ tone: "critical", ...explain(e) });100      return false;101    } finally {102      setBusy(false);103    }104  };105106  const columns: Column<Alert>[] = [107    { id: "severity", header: t("alerts.col.severity"), cell: (a) => <SeverityBadge severity={a.severity} />, shrink: true },108    { id: "state", header: t("common.state"), cell: (a) => <AlertStateDot alert={a} />, sortValue: (a) => a.state, shrink: true },109    { id: "rule", header: t("alerts.col.rule"), cell: (a) => <Link href={`/alerts/${a.id}`} className="rowlink">{a.rule_name}</Link>, sortValue: (a) => a.rule_name },110    { id: "node", header: t("common.node"), cell: (a) => (a.node_id ? <NodeLink id={a.node_id} alias={a.node_alias} /> : <span className="faint">{t("alerts.noNode")}</span>), sortValue: (a) => a.node_alias },111    { id: "summary", header: t("alerts.col.summary"), cell: (a) => <span className="al-summary">{a.summary}</span>, hide: "sm" },112    { id: "since", header: t("alerts.col.since"), cell: (a) => <span className="num nowrap">{fmt.relative(a.fired_at ?? a.started_at)}</span>, sortValue: (a) => Date.parse(a.fired_at ?? a.started_at), hide: "sm" },113    ...(manage ? [{ id: "actions", header: t("common.actions"), srOnlyHeader: true, shrink: true, cell: (a: Alert) => <IconButton icon="close" label={t("alerts.incident.unlinkNamed", { name: `${a.rule_name} ${a.node_alias ?? ""}` })} disabled={busy} onClick={() => void patch({ remove_alert_ids: [a.id] }, t("alerts.incident.unlinked"))} data-testid={`incident-unlink-${a.id}`} /> } satisfies Column<Alert>] : []),114  ];115116  return (117    <>118      <div className="row-between al-head">119        <div className="row-wrap" role="status" aria-live="polite" data-testid="incident-state" data-state={inc.state}>120          <SeverityBadge severity={inc.severity} />121          <IncidentStateDot state={inc.state} />122        </div>123        <div className="row-wrap">124          <DataStamp at={updatedAt} />125          {manage ? <Button icon="edit" onClick={() => setDialog("edit")} data-testid="incident-edit">{t("common.edit")}</Button> : null}126        </div>127      </div>128129      {manage ? (130        <div className="toolbar">131          <fieldset className="mcc-fieldset" disabled={busy}>132            <legend>{t("alerts.incident.setState")}</legend>133            <span data-testid="incident-state-control">134              <Segmented<State> label={t("alerts.incident.setState")} value={inc.state} onChange={(state) => { if (state !== inc.state) void patch({ state }, t("alerts.incident.stateChanged", { state: t(`states.incident.${state}`) })); }}135                options={(["open", "mitigated", "resolved"] as const).map((s) => ({ value: s, label: t(`states.incident.${s}`) }))} />136            </span>137          </fieldset>138          <SelectField<Severity> label={t("alerts.col.severity")} value={inc.severity} disabled={busy} onChange={(severity) => void patch({ severity }, t("alerts.incident.updated"))}139            options={(["critical", "warning", "info"] as const).map((s) => ({ value: s, label: t(`states.severity.${s}`) }))} />140        </div>141      ) : null}142143      <div className="cols-2">144        <section className="section" aria-label={t("alerts.incident.facts")}>145          <h2>{t("alerts.incident.facts")}</h2>146          <KeyValue147            items={[148              { label: t("alerts.incident.owner"), value: (149                <span className="row-wrap">150                  {inc.owner_display_name ?? <span className="faint">{t("alerts.incident.noOwner")}</span>}151                  {manage && session.me && inc.owner_id !== session.me.user.id ? <Button size="sm" disabled={busy} onClick={() => void patch({ owner_id: session.me?.user.id ?? "" }, t("alerts.incident.ownerChanged"))} data-testid="incident-take">{t("alerts.incident.take")}</Button> : null}152                  {manage && session.can("users.manage") ? <Button size="sm" variant="ghost" disabled={busy} onClick={() => setDialog("owner")}>{t("alerts.incident.assign")}</Button> : null}153                </span>154              ) },155              { label: t("alerts.incident.opened"), value: <time dateTime={inc.opened_at} className="num" title={fmt.relative(inc.opened_at)}>{fmt.dateTime(inc.opened_at, { seconds: true })}</time> },156              { label: t("alerts.incident.resolved"), value: inc.resolved_at ? <time dateTime={inc.resolved_at} className="num">{fmt.dateTime(inc.resolved_at, { seconds: true })}</time> : <span className="faint">{t("alerts.incident.notResolved")}</span> },157              ...(inc.resolved_at ? [{ label: t("alerts.incident.duration"), value: <span className="num">{fmt.duration((Date.parse(inc.resolved_at) - Date.parse(inc.opened_at)) / 1000)}</span> }] : []),158              { label: t("alerts.incident.summary"), value: inc.summary ? <Linkified text={inc.summary} /> : <span className="faint">{t("alerts.incident.noSummary")}</span> },159            ]}160          />161        </section>162        <section className="section" aria-label={t("alerts.timeline.title")}>163          <h2>{t("alerts.timeline.title")}</h2>164          <Timeline events={detail.timeline} />165          <CommentBox disabledReason={session.can("alerts.ack") ? undefined : t("alerts.comment.needAck")}166            onSubmit={async (body) => { await apiPost("/incidents/{id}/comments", { path: { id: inc.id }, body: { body } }); await invalidatePaths(qc, "/incidents"); }} />167        </section>168      </div>169170      <section className="section" aria-label={t("alerts.incident.linked")}>171        <div className="section-head">172          <h2>{t("alerts.incident.linked")} <span className="mcc-count">{detail.alerts.length}</span></h2>173          {manage ? <Button icon="plus" onClick={() => setDialog("add")} data-testid="incident-add-alerts">{t("alerts.incident.addAlerts")}</Button> : null}174        </div>175        {detail.alerts.length === 0 ? <EmptyState compact icon="alerts" title={t("alerts.incident.noAlerts")}>{t("alerts.incident.noAlertsBody")}</EmptyState> : <DataTable caption={t("alerts.incident.linked")} columns={columns} rows={detail.alerts} rowKey={(a) => a.id} />}176      </section>177178      {dialog === "edit" ? <EditDialog incident={inc} onClose={() => setDialog(null)} /> : null}179      {dialog === "add" ? <AddAlertsDialog incident={inc} linked={detail.alerts} onClose={() => setDialog(null)} onAdd={(ids) => patch({ add_alert_ids: ids }, t("alerts.incident.linkedToast"))} /> : null}180      {dialog === "owner" ? <OwnerDialog incident={inc} onClose={() => setDialog(null)} onPick={(owner_id) => patch({ owner_id }, t("alerts.incident.ownerChanged"))} /> : null}181    </>182  );183}184185function EditDialog({ incident, onClose }: { incident: Incident; onClose: () => void }) {186  const { t } = useI18n();187  const qc = useQueryClient();188  const toast = useToast();189  const [title, setTitle] = useState(incident.title);190  const [summary, setSummary] = useState(incident.summary);191  const [busy, setBusy] = useState(false);192  const [error, setError] = useState<ApiError | null>(null);193  const save = async () => {194    if (title.trim() === "") return;195    setBusy(true);196    setError(null);197    try {198      await apiPatch("/incidents/{id}", { path: { id: incident.id }, body: { title: title.trim(), summary } });199      toast({ tone: "ok", title: t("alerts.incident.updated") });200      await invalidatePaths(qc, "/incidents");201      onClose();202    } catch (e) {203      setBusy(false);204      setError(e instanceof ApiError ? e : new ApiError({ status: 0, code: "network", message: "network" }));205    }206  };207  return (208    <Dialog open onClose={onClose} size="wide" dismissable={!busy} title={t("alerts.incident.editTitle")}209      footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} disabled={title.trim() === ""} onClick={() => void save()} data-testid="incident-edit-save">{t("common.save")}</Button></>}>210      <form className="mcc-form" onSubmit={(e) => { e.preventDefault(); void save(); }}>211        <TextField label={t("alerts.incident.title")} value={title} onChange={setTitle} required maxLength={160} disabled={busy} />212        <TextAreaField label={t("alerts.incident.summary")} value={summary} onChange={setSummary} maxLength={8000} rows={8} disabled={busy} />213      </form>214      {error ? <MutationError error={error} /> : null}215    </Dialog>216  );217}218219function AddAlertsDialog({ incident, linked, onClose, onAdd }: { incident: Incident; linked: readonly Alert[]; onClose: () => void; onAdd: (ids: string[]) => Promise<boolean> }) {220  const { t, tn, fmt } = useI18n();221  const list = useApiList("/alerts", { query: { open: true, limit: 100 } });222  const [selected, setSelected] = useState<Set<string>>(new Set());223  const [busy, setBusy] = useState(false);224  const candidates = useMemo(() => {225    const have = new Set(linked.map((a) => a.id));226    return list.items.filter((a) => !have.has(a.id) && !a.incident_id);227  }, [list.items, linked]);228  const columns: Column<Alert>[] = [229    { id: "severity", header: t("alerts.col.severity"), cell: (a) => <SeverityBadge severity={a.severity} />, shrink: true },230    { id: "rule", header: t("alerts.col.rule"), cell: (a) => a.rule_name, sortValue: (a) => a.rule_name },231    { id: "node", header: t("common.node"), cell: (a) => <span className="mono">{a.node_alias ?? ""}</span>, sortValue: (a) => a.node_alias },232    { id: "since", header: t("alerts.col.since"), cell: (a) => <span className="num nowrap">{fmt.relative(a.fired_at ?? a.started_at)}</span>, hide: "sm" },233  ];234  return (235    <Dialog open onClose={onClose} size="wide" dismissable={!busy} title={t("alerts.incident.addAlerts")} description={t("alerts.incident.addAlertsBody", { title: incident.title })}236      footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} disabled={selected.size === 0} data-testid="incident-add-confirm"237        onClick={() => { setBusy(true); void onAdd([...selected]).then((ok) => { setBusy(false); if (ok) onClose(); }); }}>{tn("alerts.incident.addCount", selected.size)}</Button></>}>238      {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} compact /> : !list.ready ? <SkeletonRows rows={4} /> : candidates.length === 0 ? <EmptyState compact icon="ok" title={t("alerts.incident.noCandidates")} /> : (239        <DataTable caption={t("alerts.incident.candidates")} columns={columns} rows={candidates} rowKey={(a) => a.id} selected={selected} onSelectedChange={setSelected} selectLabel={(a) => t("alerts.bulk.selectOne", { name: `${a.rule_name} ${a.node_alias ?? ""}` })} compact />240      )}241    </Dialog>242  );243}244245function OwnerDialog({ incident, onClose, onPick }: { incident: Incident; onClose: () => void; onPick: (id: string) => Promise<boolean> }) {246  const { t } = useI18n();247  const users = useApiList("/users", { query: { limit: 200 } });248  const [owner, setOwner] = useState<string | null>(incident.owner_id ?? null);249  const [busy, setBusy] = useState(false);250  return (251    <Dialog open onClose={onClose} dismissable={!busy} title={t("alerts.incident.assign")}252      footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} disabled={!owner || owner === incident.owner_id}253        onClick={() => { if (!owner) return; setBusy(true); void onPick(owner).then((ok) => { setBusy(false); if (ok) onClose(); }); }}>{t("common.save")}</Button></>}>254      {users.error && !users.ready ? <ErrorState error={users.error} compact /> : (255        <Combobox label={t("alerts.incident.owner")} value={owner} onChange={setOwner} options={users.items.filter((u) => !u.disabled).map((u) => ({ value: u.id, label: u.display_name, hint: `@${u.handle}` }))} />256      )}257    </Dialog>258  );259}260
Files main
Menu

Theme