SPB Git

Repository Public

RulesTab.tsx 7.1 KB 114 lines tsx

1"use client";2import { useQueryClient } from "@tanstack/react-query";3import { useState } from "react";4import { apiDelete, apiPatch } from "@/api/client";5import { ApiError } from "@/api/errors";6import { invalidatePaths, useApiList, useApiQuery } from "@/api/query";7import { metricLabel } from "@/features/shared/metrics";8import { useI18n } from "@/i18n";9import { useSession } from "@/shell/session";10import { Button, ConfirmDialog, DataStamp, DataTable, EmptyState, ErrorState, IconButton, LoadMore, SkeletonRows, StateDot, Tag, useErrorMessage, useToast, type Column } from "@/ui";11import type { Rule } from "./logic";12import { RuleEditor } from "./RuleEditor";13import { MutationError, ScopeText, SeverityBadge } from "./shared";1415export function RulesTab({ editId, onEdit }: { editId: string | null; onEdit: (id: string | null) => void }) {16  const { t, fmt } = useI18n();17  const session = useSession();18  const qc = useQueryClient();19  const toast = useToast();20  const explain = useErrorMessage();21  const list = useApiList("/alert-rules", { query: { limit: 200 } });22  const manage = session.can("alerts.manage");23  const [creating, setCreating] = useState(false);24  const [deleting, setDeleting] = useState<Rule | null>(null);25  const [busy, setBusy] = useState<string | null>(null);26  const [error, setError] = useState<ApiError | null>(null);27  const inList = editId ? list.items.find((r) => r.id === editId) : undefined;28  // deep link to a rule that is not on the loaded page29  const single = useApiQuery("/alert-rules/{id}", { path: { id: editId ?? "" } }, { enabled: !!editId && list.ready && !inList });30  const editing = inList ?? single.data ?? null;3132  const toggle = async (rule: Rule) => {33    setBusy(rule.id);34    try {35      await apiPatch("/alert-rules/{id}", { path: { id: rule.id }, body: { enabled: !rule.enabled } });36      toast({ tone: "ok", title: rule.enabled ? t("alerts.rule.disabledToast", { name: rule.name }) : t("alerts.rule.enabledToast", { name: rule.name }) });37      await invalidatePaths(qc, "/alert-rules");38    } catch (e) {39      toast({ tone: "critical", ...explain(e) });40    } finally {41      setBusy(null);42    }43  };44  const remove = async () => {45    if (!deleting) return;46    setBusy(deleting.id);47    setError(null);48    try {49      await apiDelete("/alert-rules/{id}", { path: { id: deleting.id } });50      toast({ tone: "ok", title: t("alerts.rule.deleted") });51      setDeleting(null);52      await invalidatePaths(qc, "/alert-rules", "/alerts");53    } catch (e) {54      if (e instanceof ApiError) setError(e);55    } finally {56      setBusy(null);57    }58  };5960  const condition = (r: Rule) => {61    if (r.kind === "threshold") {62      return <span><span>{r.metric ? metricLabel(t, r.metric) : t("common.unknown")}</span>{r.label_match ? <span className="mono"> [{r.label_match}]</span> : null} <span className="mono">{r.op ? t(`alerts.rule.opSymbol.${r.op}`) : ""} {r.threshold !== undefined ? fmt.number(r.threshold, 3) : ""}</span></span>;63    }64    return <span className="muted">{t(`alerts.rule.conditionOf.${r.kind}`)}</span>;65  };66  const columns: Column<Rule>[] = [67    { id: "name", header: t("common.name"), cell: (r) => <span className="row-wrap gap-2"><button type="button" className="al-linkbtn" onClick={() => onEdit(r.id)} data-testid={`rule-row-${r.id}`}>{r.name}</button>{r.builtin ? <Tag>{t("alerts.rule.builtin")}</Tag> : null}</span>, sortValue: (r) => r.name },68    { id: "kind", header: t("alerts.rule.kindLabel"), cell: (r) => t(`alerts.rule.kind.${r.kind}`), sortValue: (r) => r.kind, hide: "sm" },69    { id: "condition", header: t("alerts.rule.condition"), cell: condition, hide: "sm" },70    { id: "severity", header: t("alerts.col.severity"), cell: (r) => <SeverityBadge severity={r.severity} />, sortValue: (r) => (r.severity === "critical" ? 0 : r.severity === "warning" ? 1 : 2), shrink: true },71    { id: "scope", header: t("alerts.scope.label"), cell: (r) => <ScopeText scope={r.scope} />, hide: "md" },72    { id: "for", header: t("alerts.rule.forClear"), cell: (r) => <span className="num nowrap">{fmt.duration(r.for_seconds)} / {fmt.duration(r.clear_seconds)}</span>, sortValue: (r) => r.for_seconds, hide: "md" },73    { id: "notify", header: t("alerts.rule.notify"), cell: (r) => (r.notify ? t("common.yes") : t("common.no")), hide: "md" },74    {75      id: "enabled", header: t("alerts.rule.enabled"), sortValue: (r) => (r.enabled ? 0 : 1), shrink: true,76      cell: (r) => manage77        ? <label className="mcc-switch"><input type="checkbox" role="switch" checked={r.enabled} disabled={busy === r.id} onChange={() => void toggle(r)} aria-label={t("alerts.rule.enabledFor", { name: r.name })} data-testid={`rule-enabled-${r.id}`} /><span className="state" aria-hidden="true">{r.enabled ? t("common.on") : t("common.off")}</span></label>78        : <StateDot tone={r.enabled ? "ok" : "offline"} label={r.enabled ? t("common.on") : t("common.off")} />,79    },80    {81      id: "actions", header: t("common.actions"), srOnlyHeader: true, shrink: true,82      cell: (r) => (83        <span className="row gap-2">84          <IconButton icon={manage ? "edit" : "eye"} label={manage ? t("alerts.rule.editNamed", { name: r.name }) : t("alerts.rule.viewNamed", { name: r.name })} onClick={() => onEdit(r.id)} />85          {manage && !r.builtin ? <IconButton icon="trash" label={t("alerts.rule.deleteNamed", { name: r.name })} onClick={() => { setError(null); setDeleting(r); }} data-testid={`rule-delete-${r.id}`} /> : null}86        </span>87      ),88    },89  ];90  const create = manage ? <Button variant="primary" icon="plus" onClick={() => setCreating(true)} data-testid="rule-new">{t("alerts.rule.new")}</Button> : null;91  return (92    <div className="stack" data-testid="rules-tab">93      <div className="toolbar">94        <p className="muted grow">{t("alerts.rule.intro")}</p>95        <DataStamp at={list.ready ? list.updatedAt : undefined} />96        {create}97      </div>98      {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} /> : !list.ready ? <SkeletonRows /> : list.items.length === 0 ? (99        <EmptyState icon="alerts" title={t("alerts.rule.emptyTitle")} actions={create}>{t("alerts.rule.emptyBody")}</EmptyState>100      ) : (101        <>102          <DataTable caption={t("alerts.tab.rules")} columns={columns} rows={list.items} rowKey={(r) => r.id} initialSort={{ id: "name", dir: "asc" }} />103          <LoadMore hasMore={list.hasMore} loading={list.loadingMore} onMore={list.loadMore} />104        </>105      )}106      {editId && single.isError && !editing ? <ErrorState error={single.error} compact /> : null}107      {creating ? <RuleEditor rule={null} onClose={() => setCreating(false)} /> : null}108      {editing ? <RuleEditor key={editing.id} rule={editing} onClose={() => onEdit(null)} /> : null}109      <ConfirmDialog open={deleting !== null} onClose={() => setDeleting(null)} onConfirm={() => void remove()} busy={busy !== null && busy === deleting?.id} danger title={t("alerts.rule.deleteTitle")}110        body={deleting ? t("alerts.rule.deleteBody", { name: deleting.name }) : undefined} confirmLabel={t("common.delete")} error={error ? <MutationError error={error} /> : undefined} />111    </div>112  );113}114
Files main
Menu

Theme