peppa/apps/web/components/Errors.tsx

202 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-218: production errors read from Bugsink on the server — summary, filters, rows and the
// error card blocks. «Инженер» and the superadmin (`tech`) also see code places, releases,
// stacks and tags; «Продакт» — the title, how often, when and the bug task.
import Link from "next/link";
import { Bug, TrendingUp } from "lucide-react";
import type { ErrorDetail, ErrorFilter, ErrorRow, ErrorScope, ErrorsOverview, ErrorState } from "@peppa/core";
import { m, type Translator } from "@peppa/shared/i18n";
import { Hidden } from "@/components/cards";
import { ago, Empty, Key, Notice } from "@/components/common";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input, NativeSelect } from "@/components/ui/input";
import { errorAction } from "@/app/(app)/errors/actions";
const STATE_LABEL: Record<ErrorState, string> = { unresolved: m("не решена"), resolved: m("решена"), muted: m("приглушена") };
const STATE_TONE: Record<ErrorState, "danger" | "ok" | "muted"> = { unresolved: "danger", resolved: "ok", muted: "muted" };
const hhmm = (d: Date, t: Translator) => d.toLocaleTimeString(t.locale === "en" ? "en-GB" : "ru-RU", { hour: "2-digit", minute: "2-digit" });
/** Bugsink failed: say so; the data below (if any) is from the cache. */
export function ErrorsDown({ down, at, tech, t }: { down: boolean; at: Date | null; tech: boolean; t: Translator }) {
if (!down) return null;
return (
<Notice>
{tech
? at
? // glossary-ignore: «Инженер» and the superadmin only.
t("Bugsink не отвечает — показаны данные на {time}.", { time: hhmm(at, t) })
: // glossary-ignore: «Инженер» and the superadmin only.
t("Bugsink не отвечает, данных пока нет. Загляните через минуту.")
: at
? t("Учёт ошибок не отвечает — показаны данные на {time}.", { time: hhmm(at, t) })
: t("Учёт ошибок не отвечает. Загляните через минуту.")}
</Notice>
);
}
export function ErrorStateBadge({ state, t }: { state: ErrorState; t: Translator }) {
return <Badge variant={STATE_TONE[state]}>{t(STATE_LABEL[state])}</Badge>;
}
/** Superadmin summary: one line per Bugsink project. */
export function ErrorsSummary({ ov, t, hrefFor }: { ov: ErrorsOverview; t: Translator; hrefFor: (bugsinkId: number) => string }) {
if (!ov.projects.length) return <Empty>{t("Проектов учёта ошибок нет.")}</Empty>;
return (
<div className="overflow-x-auto rounded-md border">
<table className="w-full text-sm">
<thead className="text-left text-xs text-muted-foreground">
<tr>
<th className="px-3 py-2 font-medium">{t("Проект")}</th>
<th className="px-3 py-2 text-right font-medium">{t("Нерешённых")}</th>
<th className="px-3 py-2 text-right font-medium">{t("Новых за сутки")}</th>
<th className="px-3 py-2 text-right font-medium" title={t("Событий за последний час и в среднем за час прошлых суток")}>{t("За час")}</th>
</tr>
</thead>
<tbody>
{ov.projects.map((p) => (
<tr key={p.bugsinkId} className="border-t">
<td className="px-3 py-2">
<Link href={hrefFor(p.bugsinkId)} className="font-medium hover:underline">{p.name}</Link>
{p.projectKey ? <Key href={`/p/${p.projectKey}?tab=bugs`} className="ml-2">{p.projectKey}</Key> : <span className="ml-2 text-xs text-muted-foreground">{t("не подключён")}</span>}
</td>
<td className={`px-3 py-2 text-right tabular-nums ${p.unresolved ? "font-semibold" : "text-muted-foreground"}`}>{p.unresolved}{p.more ? "+" : ""}</td>
<td className={`px-3 py-2 text-right tabular-nums ${p.newDay ? "text-destructive" : "text-muted-foreground"}`}>{p.newDay}</td>
<td className="px-3 py-2 text-right whitespace-nowrap tabular-nums">
{p.growing ? <Badge variant="danger" className="mr-1.5"><TrendingUp className="size-3" />{t("растёт")}</Badge> : null}
{p.lastHour} <span className="text-xs text-muted-foreground">/ {p.dayAvg}</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
/** Errors as cards; the title opens the error card. */
export function ErrorRows({ rows, tech, from, t, showProject = true }: { rows: ErrorRow[]; tech: boolean; from: string; t: Translator; showProject?: boolean }) {
if (!rows.length) return <Empty>{t("Ошибок нет.")}</Empty>;
return (
<div className="flex flex-col gap-2">
{rows.map((r) => (
<Card key={r.id} className="gap-1 py-2.5">
<div className="flex min-w-0 items-start gap-2">
<Bug className={`mt-0.5 size-4 shrink-0 ${r.state === "unresolved" ? "text-destructive" : "text-muted-foreground"}`} />
<Link href={`/errors/${encodeURIComponent(r.id)}?from=${encodeURIComponent(from)}`} className="line-clamp-2 min-w-0 flex-1 font-medium break-all hover:underline" title={r.title}>{r.title}</Link>
{r.state !== "unresolved" ? <ErrorStateBadge state={r.state} t={t} /> : null}
</div>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 pl-6 text-xs text-muted-foreground">
{tech && r.culprit ? <span className="max-w-full truncate font-mono">{r.culprit}</span> : null}
{showProject ? <span>{r.bugsinkName}</span> : null}
<span className="tabular-nums">{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
<span title={r.firstSeen.toLocaleString()}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
<span title={r.lastSeen.toLocaleString()}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
{/* glossary-ignore: the release is shown to «Инженер» and the superadmin only */}
{tech && r.release ? <span className="font-mono" title={r.release}>{t("релиз {sha}", { sha: r.release.slice(0, 8) })}</span> : null}
{r.taskKey ? <Key href={`/t/${r.taskKey}`}>{r.taskKey}</Key> : null}
</div>
</Card>
))}
</div>
);
}
/** Filters (GET form): project, state, environment, release, text, order. */
export function ErrorFilters({ action, scope, f, keep, t, showProject = true }: { action: string; scope: ErrorScope; f: ErrorFilter; keep: Record<string, string>; t: Translator; showProject?: boolean }) {
return (
<form action={action} method="get" className="mb-3 flex flex-wrap items-end gap-2 text-sm">
{Object.entries(keep).map(([k, v]) => (
<input key={k} type="hidden" name={k} value={v} />
))}
{showProject && scope.projects.length > 1 ? (
<NativeSelect name="bp" defaultValue={f.bugsink != null ? String(f.bugsink) : ""} aria-label={t("Проект")} className="w-auto">
<option value="">{t("Все проекты")}</option>
{scope.projects.map((p) => (
<option key={p.bugsinkId} value={p.bugsinkId}>{p.name}</option>
))}
</NativeSelect>
) : null}
<NativeSelect name="state" defaultValue={f.state ?? "unresolved"} aria-label={t("Состояние")} className="w-auto">
<option value="unresolved">{t("Нерешённые")}</option>
<option value="resolved">{t("Решённые")}</option>
<option value="muted">{t("Приглушённые")}</option>
<option value="all">{t("Все")}</option>
</NativeSelect>
<NativeSelect name="sort" defaultValue={f.sort ?? "last_seen"} aria-label={t("Порядок")} className="w-auto">
<option value="last_seen">{t("Сначала свежие")}</option>
<option value="digested_event_count">{t("Сначала частые")}</option>
</NativeSelect>
{scope.tech ? (
<>
<Input name="env" defaultValue={f.environment ?? ""} placeholder={t("Окружение")} className="w-32" />
{/* glossary-ignore: «Инженер» and the superadmin only */}
<Input name="rel" defaultValue={f.release ?? ""} placeholder={t("Релиз")} className="w-32" />
</>
) : null}
<Input name="q" defaultValue={f.q ?? ""} placeholder={t("Поиск по тексту")} className="w-48" />
<Button size="sm" variant="secondary">{t("Показать")}</Button>
</form>
);
}
/** The filter from the page's query string. */
export function errorFilterFrom(sp: Record<string, string | undefined>): ErrorFilter {
const state = sp.state === "resolved" || sp.state === "muted" || sp.state === "all" ? sp.state : "unresolved";
return {
bugsink: sp.bp && /^\d+$/.test(sp.bp) ? Number(sp.bp) : undefined,
state,
environment: sp.env?.trim() || undefined,
release: sp.rel?.trim() || undefined,
q: sp.q?.trim() || undefined,
sort: sp.sort === "digested_event_count" ? "digested_event_count" : "last_seen",
cursor: sp.cursor || undefined,
};
}
/** «Решено», «Приглушить»/«Вернуть», «Завести задачу» on the error card. */
export function ErrorActions({ d, back, t }: { d: ErrorDetail; back: string; t: Translator }) {
const btn = (action: string, label: string, variant: "default" | "secondary" | "ghost" = "secondary") => (
<form action={errorAction}>
<Hidden fields={{ id: d.row.id, action, back }} />
<Button size="sm" variant={variant}>{label}</Button>
</form>
);
return (
<div className="flex flex-wrap items-center gap-2">
{d.row.taskKey ? null : d.projectId != null ? btn("task", t("Завести задачу"), "default") : null}
{d.row.state === "resolved" ? btn("reopen", t("Открыть снова")) : btn("resolve", t("Решено"))}
{d.row.state === "muted" ? btn("unmute", t("Вернуть")) : d.row.state === "unresolved" ? btn("mute", t("Приглушить"), "ghost") : null}
</div>
);
}
/** Stack frames, innermost first; code around the line where the SDK sent it. */
export function ErrorStack({ d, t }: { d: ErrorDetail; t: Translator }) {
if (!d.frames.length) return <Empty>{t("Кадров нет.")}</Empty>;
return (
<div className="flex flex-col gap-1.5">
{d.frames.map((f, n) => (
<div key={n} className={`rounded-md border px-2.5 py-1.5 ${f.inApp ? "" : "opacity-60"}`}>
<div className="font-mono text-xs break-all">
<span className="font-semibold">{f.fn ?? "?"}</span> <span className="text-muted-foreground">{f.file}{f.line != null ? `:${f.line}` : ""}</span>
</div>
{f.context.length ? (
<pre className="m-0 mt-1 overflow-x-auto rounded bg-muted px-2 py-1 font-mono text-xs leading-5">
{f.context.map(([no, text, hit], k) => (
<div key={k} className={hit ? "bg-destructive/15 font-semibold" : ""}>
<span className="mr-3 inline-block w-10 text-right text-muted-foreground select-none">{no ?? ""}</span>
{text}
</div>
))}
</pre>
) : n === 0 ? (
<div className="text-xs text-muted-foreground">{t("Кода вокруг строки нет: его не прислали.")}</div>
) : null}
</div>
))}
</div>
);
}