peppa/apps/web/components/Incidents.tsx

223 lines
12 KiB
TypeScript
Raw Permalink 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.

// Project page «Баги» (PEP-58, PEP-66): incidents list (tab) and Bugsink settings (⋯ Настройки проекта).
import { Bug, CircleCheck, EyeOff, Inbox, MapPin, Play } from "lucide-react";
import { INCIDENT_STATUS_RU, incidentPolicies, POLICY_RU, type ErrorSource, type Incident, type IncidentSettings } from "@peppa/core";
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings, setDirectIncidentsAction } from "@/app/(app)/actions";
import { Hidden } from "@/components/cards";
import { ago, Disclosure, Empty, Key, Section } from "@/components/common";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input, Label, NativeSelect, Textarea } from "@/components/ui/input";
import type { Words } from "@peppa/shared/wording";
import { getT } from "@/lib/i18n";
const STATUS_TONE: Record<Incident["status"], "danger" | "warn" | "info" | "ok" | "muted"> = { new: "danger", open: "warn", pending: "warn", task: "info", ignored: "muted", resolved: "ok", regressed: "danger" };
function Code({ children }: { children: React.ReactNode }) {
return <code className="block overflow-x-auto rounded-md bg-muted px-2.5 py-1.5 font-mono text-xs">{children}</code>;
}
/** Tab «Баги»: the incidents list. Settings live in «⋯ Настройки проекта» (PEP-66). */
export async function IncidentsSection(props: {
projectId: number;
back: string;
settings: IncidentSettings | null;
incidents: Incident[];
taskKeys: Map<number, string>;
w: Words;
}) {
const { settings: s, w } = props;
const t = await getT();
if (!s) {
return (
<Section title={t("Баги")}>
<p className="m-0 text-sm text-muted-foreground">{w.engineer ? t("Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся стори по политике проекта.") : t("Когда ваш продукт заработает, его ошибки будут приходить сюда и становиться задачами для агентов.")}</p>
<Empty>{t("Отслеживание ошибок не подключено — подключает владелец в «Настройках проекта».")}</Empty>
</Section>
);
}
const active = props.incidents.filter((i) => !["ignored", "resolved"].includes(i.status));
const rest = props.incidents.filter((i) => ["ignored", "resolved"].includes(i.status));
return (
<Section title={t("Баги")} count={active.length} actions={w.engineer ? <span className="text-xs text-muted-foreground">{t("политика: {policy}", { policy: t(POLICY_RU[s.policy]) })}</span> : undefined}>
{active.length === 0 ? <Empty>{t("Открытых ошибок нет.")}</Empty> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)}
{rest.length > 0 && (
<Disclosure summary={t("Исправленные и игнорируемые ({n})", { n: rest.length })}>
<div className="flex flex-col gap-2">
{rest.map((i) => (
<IncidentCard key={i.id} i={i} {...props} />
))}
</div>
</Disclosure>
)}
</Section>
);
}
/** «⋯ Настройки проекта» → Баги: connect Bugsink, DSN, webhook, incident policy (PEP-66). */
export async function IncidentSettingsPanel(props: {
projectId: number;
back: string;
isOwner: boolean;
settings: IncidentSettings | null;
sources: ErrorSource[];
webhookUrl: string | null;
/** PEP-295: the owner let errors of the product go to work without «Делать». */
direct: boolean;
w: Words;
}) {
const { projectId, back, settings: s, w } = props;
const t = await getT();
if (!s) {
return (
<div className="flex flex-col gap-2 text-sm">
<p className="m-0 text-muted-foreground">{w.engineer ? t("Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят во вкладку «Баги» и становятся стори по политике проекта.") : t("Ошибки вашего продукта будут приходить во вкладку «Баги» и становиться задачами для агентов.")}</p>
{props.isOwner ? (
<form action={connectErrorTrackingAction}>
<Hidden fields={{ projectId, back }} />
<Button variant="default" size="sm">
<Bug />
{t("Подключить отслеживание ошибок")}
</Button>
</form>
) : (
<Empty>{t("Не подключено — подключает владелец проекта.")}</Empty>
)}
</div>
);
}
// PEP-295: whether errors go to work without «Делать» is the owner's decision — shown in both views.
const direct = (
<div className="flex flex-col gap-1.5 text-sm">
<span>
{props.direct
? t("Задачи из ошибок продукта агенты берут в работу сразу, без вашего «Делать».")
: t("Задачи из ошибок продукта ждут вашего «Делать» в «Предложено».")}
</span>
{props.isOwner && (
<form action={setDirectIncidentsAction}>
<Hidden fields={{ projectId, back, on: props.direct ? "no" : "yes" }} />
<Button size="sm" variant="outline">
{props.direct ? t("Ждать моего решения") : t("Брать в работу сразу")}
</Button>
</form>
)}
</div>
);
// PEP-123: addresses, variables and the policy of incidents are an engineer's settings.
if (w.product)
return (
<div className="flex flex-col gap-3">
<p className="m-0 text-sm text-muted-foreground">{t("Подключено: ошибки вашего продукта приходят во вкладку «Баги» и становятся задачами для агентов.")}</p>
{direct}
</div>
);
return (
<div className="flex flex-col gap-3 text-sm">
{direct}
{props.sources.map((src) => (
<div key={src.id} className="flex flex-col gap-1">
<span className="font-medium">{src.kind === "web" ? t("DSN фронта (web)") : t("DSN бэка (api)")}</span>
<Code>{src.dsn}</Code>
</div>
))}
<p className="m-0 text-muted-foreground">
{t("В коде:")} <code className="font-mono">NEXT_PUBLIC_SENTRY_DSN</code> / <code className="font-mono">SENTRY_DSN</code> {t("из окружения,")} <code className="font-mono">release</code> = {t("SHA деплоя,")}{" "}
<code className="font-mono">environment</code> = prod, <code className="font-mono">sendDefaultPii: false</code>.
</p>
{!s.webhookAuto && props.webhookUrl && (
<div className="flex flex-col gap-1">
<span><b>{t("Вебхук не настроен автоматически.")}</b> {t("В Bugsink: проект → Alerts → Custom webhook:")}</span>
<Code>{props.webhookUrl}</Code>
<span className="text-muted-foreground">{t("Пока его нет, FORGE опрашивает Bugsink раз в 2 минуты.")}</span>
</div>
)}
<form action={saveIncidentSettings} className="flex flex-col gap-2.5">
<Hidden fields={{ projectId, back }} />
<Label>
{t("Политика инцидентов")}
<NativeSelect name="policy" defaultValue={s.policy} aria-label={t("Политика инцидентов")}>
{incidentPolicies.map((p) => (
<option key={p} value={p}>
{p} — {t(POLICY_RU[p])}
</option>
))}
</NativeSelect>
</Label>
<Textarea
name="triagePrompt"
rows={3}
defaultValue={s.triagePrompt ?? ""}
aria-label={t("Как принимать решение (для триажёра)")}
placeholder={t("Как принимать решение (для политики triage): например, «падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси»")}
/>
<div className="flex gap-2">
<Input name="environments" defaultValue={s.environments.join(", ")} aria-label={t("Окружения")} placeholder={t("Окружения: prod, production")} />
<Input type="number" name="dailyLimit" min={0} defaultValue={s.dailyLimit} aria-label={t("Стори в сутки")} title={t("Стори из ошибок в сутки")} className="w-24" />
</div>
<Input name="ignorePattern" defaultValue={s.ignorePattern ?? ""} aria-label={t("Игнорировать по названию")} placeholder={t("Игнорировать по названию (регэксп), например ResizeObserver loop")} />
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
</form>
</div>
);
}
async function IncidentCard({ i, back, projectId, taskKeys, w }: { i: Incident; back: string; projectId: number; taskKeys: Map<number, string>; w: Words }) {
const t = await getT();
const taskKey = i.taskId ? taskKeys.get(i.taskId) : null;
const decide = (action: string, label: string, icon: React.ReactNode) => (
<form action={decideIncidentAction}>
<Hidden fields={{ projectId, back, incidentId: i.id, action }} />
<Button size="xs">
{icon}
{label}
</Button>
</form>
);
return (
<article className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5 text-sm">
<div className="flex items-start gap-2">
<Badge variant={STATUS_TONE[i.status]}>{t(INCIDENT_STATUS_RU[i.status])}</Badge>
<b className="min-w-0 flex-1 font-mono text-[13px] font-medium [overflow-wrap:anywhere]">{i.title}</b>
<span className="shrink-0 font-mono text-xs text-muted-foreground">{ago(i.lastSeen, t)}</span>
</div>
<div className="flex flex-wrap items-center gap-x-1.5 text-xs text-muted-foreground">
{w.engineer ? <>{i.source} · {i.environment ?? "—"} · {t("релиз {release}", { release: i.lastRelease ?? "—" })} · {t("событий {n}", { n: i.events })}</> : <>{t("случалась раз: {n}", { n: i.events })}</>}
{w.engineer && i.culprit && (
<span className="inline-flex items-center gap-1">
· <MapPin className="size-3" /> {i.culprit}
</span>
)}
{w.engineer && i.url && (
<>
· <a href={i.url} className="text-primary">Bugsink</a>
</>
)}
{taskKey && (
<>
· <Key href={`/t/${taskKey}`}>{taskKey}</Key>
</>
)}
</div>
{i.decisionReason && <div className="text-xs text-muted-foreground">{i.decidedBy === "triage" ? "🤖 " : ""}{t.text(i.decisionReason)}</div>}
<div className="flex flex-wrap gap-1.5">
{!i.taskId && i.status !== "resolved" && (
<>
{decide("backlog", t("В бэклог"), <Inbox />)}
{decide("start", t("В работу"), <Play />)}
{i.status !== "ignored" && decide("ignore", t("Игнорировать"), <EyeOff />)}
</>
)}
{i.status !== "resolved" && i.status !== "ignored" && (
<form action={resolveIncidentAction}>
<Hidden fields={{ projectId, back, incidentId: i.id }} />
<Button size="xs">
<CircleCheck />
{t("Исправлено")}
</Button>
</form>
)}
</div>
</article>
);
}