peppa/apps/web/components/Accounting.tsx

463 lines
23 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.

// Accounting blocks (PEP-5/43/47/48): the usage strip on top, story budget, project metrics, journal.
import Link from "next/link";
import type { ReactNode } from "react";
import { Gauge, Hourglass, Play } from "lucide-react";
import {
accountPeak,
actorLabel,
ACTOR_CHANNEL_NAMES,
ACTOR_KIND_NAMES,
BUDGET_KINDS,
BUDGET_LABELS,
describeUsage,
fmtCost,
fmtHours,
fmtPct,
fmtTokens,
formatBudgetValue,
PROVIDER_NAMES,
usageTotals,
type AccountUsage,
type AgentsLine,
type Budget,
type JournalEntry,
type MetricsBucket,
type ProjectMetrics,
type SessionUsage,
type TaskBudgetView,
type WindowView,
} from "@peppa/core";
import { Hidden } from "@/components/cards";
import { SubscriptionRequestButton } from "@/components/SubscriptionRequest";
import { eventLine } from "@/components/RunnerConsole";
import { LocalTime } from "@/components/LocalTime";
import { ago, Empty } from "@/components/common";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n";
import { intlLocale, type Locale, type Translator } from "@peppa/shared/i18n";
const tone = (pct: number) => (pct >= 90 ? "bg-destructive" : pct >= 70 ? "bg-warn" : "bg-primary");
function Meter({ pct, className }: { pct: number; className?: string }) {
return (
<span className={cn("relative inline-block h-1.5 w-16 overflow-hidden rounded-full bg-muted align-middle", className)} aria-hidden>
<span className={cn("absolute inset-y-0 left-0 rounded-full", tone(pct))} style={{ width: `${Math.max(2, Math.min(100, pct))}%` }} />
</span>
);
}
function WindowCell({ label, w, t }: { label: string; w: WindowView | null; t: Translator }) {
if (!w) return null;
return (
<span className="flex items-center gap-1.5 whitespace-nowrap">
<span className="text-muted-foreground">{label}</span>
{w.reset ? (
<span className="text-muted-foreground">{t("сброшено")}</span>
) : (
<>
<Meter pct={w.pct!} />
<span className="font-mono tabular-nums">{Math.round(w.pct!)}%</span>
{w.resetsAt && (
<span className="text-muted-foreground">
{t("сброс")} <LocalTime iso={w.resetsAt.toISOString()} />
</span>
)}
</>
)}
</span>
);
}
function accountTitle(a: AccountUsage, t: Translator): string {
const w = (l: string, v: WindowView | null) => (!v ? t("{label}: нет данных", { label: l }) : v.reset ? t("{label}: сброшено", { label: l }) : `${l}: ${Math.round(v.pct!)}%`);
const limited = a.limitedUntil ? ", " + t("в лимите") : "";
const updated = a.at ? ", " + t("обновлено {at}", { at: a.at.toLocaleString(intlLocale(t.locale)) }) : "";
return t.text(a.name) + " — " + w(t("5 ч"), a.fiveHour) + ", " + w(t("7 д"), a.sevenDay) + limited + updated;
}
/** PEP-5: thin bar above every page — the most loaded limit window of the user's accounts. */
export async function UsageStrip({ accounts, admin }: { accounts: AccountUsage[]; admin: boolean }) {
const t = await getT();
const withData = accounts.filter((a) => a.fiveHour || a.sevenDay || a.limitedUntil);
const top = withData[0];
const limited = accounts.filter((a) => a.limitedUntil);
return (
<div
role="status"
aria-label={t("Лимиты подписок")}
title={accounts.map((a) => accountTitle(a, t)).join("\n") || undefined}
className="flex min-h-8 flex-wrap items-center gap-x-4 gap-y-1 border-b bg-sidebar/40 px-4 py-1 text-xs md:px-8"
>
<span className="flex items-center gap-1.5 text-muted-foreground">
<Gauge className="size-3.5" />
{t("Лимиты")}
</span>
{!top ? (
<span className="text-muted-foreground">{t("нет данных о лимитах")}</span>
) : (
<>
{withData.length > 1 && <span className="font-medium">{t.text(top.name)}</span>}
<WindowCell label={t("5 ч")} w={top.fiveHour} t={t} />
<WindowCell label={t("7 д")} w={top.sevenDay} t={t} />
{top.stale && top.at && <span className="text-warn">{t("устарело ({ago})", { ago: ago(top.at, t) })}</span>}
</>
)}
{limited.map((a) => (
<span key={a.key} className="whitespace-nowrap text-destructive">
{t.text(a.name)}: {t("лимит до")} <LocalTime iso={a.limitedUntil!.toISOString()} />
</span>
))}
{withData.length > 1 && (
<span className="text-muted-foreground">
+{withData.length - 1} {admin ? <Link href="/subscriptions" className="text-muted-foreground underline-offset-2 hover:text-foreground">{t("подписки")}</Link> : t("аккаунт")}
</span>
)}
</div>
);
}
/** PEP-121: the same bar for a product manager — one line, no shares, windows or account names. */
export async function AgentsStrip({ line, offers = [] }: { line: AgentsLine; /** PEP-186: projects where the user may ask the superadmin for a subscription. */ offers?: Array<{ projectId: number; key: string; name: string; offer: "can" | "sent" }> }) {
const t = await getT();
return (
<div role="status" data-agents-line={line.state} className="flex min-h-8 items-center gap-1.5 border-b bg-sidebar/40 px-4 py-1 text-xs text-muted-foreground md:px-8">
{line.state === "working" ? (
<>
<Play className="size-3.5" />
{t("Агенты работают")}
</>
) : (
<>
<Hourglass className="size-3.5" />
<span>
{t("Агенты продолжат в")} <LocalTime iso={line.until.toISOString()} />
</span>
{offers.map((o) => (
<span key={o.projectId} className="ml-2">
<SubscriptionRequestButton projectId={o.projectId} offer={o.offer} back={`/p/${o.key}`} name={offers.length > 1 ? o.name : undefined} size="xs" />
</span>
))}
</>
)}
</div>
);
}
export const usagePeakSort = (a: AccountUsage[]) => [...a].sort((x, y) => accountPeak(y) - accountPeak(x));
/** PEP-5: one line under a runner card. */
export async function SessionUsageLine({ usage, provider }: { usage: SessionUsage | null; provider: string }) {
const tr = await getT();
const t = usageTotals(usage);
if (!t.hasData) return <p className="m-0 text-xs text-muted-foreground">{tr("Расход: нет данных")}{provider !== "claude" ? " (" + tr("{provider} не сообщает", { provider }) + ")" : ""}</p>;
return (
<p className="m-0 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground">
<span>{tr("Расход: {usage}", { usage: tr.text(describeUsage(usage)) })}</span>
{t.context && (
<span className="flex items-center gap-1.5">
{tr("контекст")} <Meter pct={t.context.pct} className="w-12" /> {tr.text(fmtTokens(t.context.used))} / {tr.text(fmtTokens(t.context.size))}
</span>
)}
</p>
);
}
// ── PEP-43: budget ────────────────────────────────────────────────────────────────
const spentOf = (v: TaskBudgetView, k: (typeof BUDGET_KINDS)[number]) => (k === "costUsd" ? (v.spend.costUsd ?? 0) : v.spend[k]);
const spentText = (v: TaskBudgetView, k: (typeof BUDGET_KINDS)[number], t: Translator) => (k === "costUsd" ? fmtCost(v.spend.usage) : t.text(formatBudgetValue(k, v.spend[k])));
export async function BudgetFields({ budget, placeholder }: { budget: Budget; placeholder?: Budget }) {
const t = await getT();
const field = (k: (typeof BUDGET_KINDS)[number], label: string, step = "1") => (
<label className="flex flex-col gap-1 text-xs text-muted-foreground">
{label}
<Input
type="number"
name={k}
min={0}
step={step}
defaultValue={budget[k] ?? ""}
placeholder={placeholder?.[k] != null ? String(placeholder[k]) : "∞"}
aria-label={label}
className="h-8 w-full"
/>
</label>
);
return (
<div className="grid grid-cols-2 gap-2">
{field("minutes", t("Минуты раннеров"))}
{field("tokens", t("Токены"))}
{field("restarts", t("Перезапуски"))}
{field("costUsd", t("Стоимость, $"), "0.01")}
</div>
);
}
export async function BudgetPanel({ view, taskId, projectBudget, back, action, paused }: { view: TaskBudgetView; taskId: number; projectBudget: Budget; back: string; action: (f: FormData) => Promise<void>; paused: boolean }) {
const t = await getT();
return (
<div className="flex flex-col gap-2.5">
{paused && <p className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-2.5 py-1.5 text-xs text-destructive">{t("Бюджет исчерпан — агент на паузе до вашего решения (вопрос во «Входящих» или новый бюджет ниже).")}</p>}
<ul className="m-0 flex list-none flex-col gap-1.5 p-0 text-sm">
{BUDGET_KINDS.map((k) => {
const limit = view.budget[k];
const pct = limit ? (spentOf(view, k) / limit) * 100 : null;
return (
<li key={k} className="flex items-center gap-2">
<span className="w-24 shrink-0 text-xs text-muted-foreground">{t.text(BUDGET_LABELS[k])}</span>
<span className="font-mono text-xs tabular-nums">{spentText(view, k, t)}</span>
<span className="text-xs text-muted-foreground">{t("из {value}", { value: t.text(formatBudgetValue(k, limit)) })}</span>
{pct != null && <Meter pct={pct} className="ml-auto w-14" />}
</li>
);
})}
</ul>
<p className="m-0 text-xs text-muted-foreground">
{view.source === "task" ? t("Свой бюджет стори.") : view.source === "project" ? t("Бюджет проекта по умолчанию.") : t("Без бюджета.")} {t("Сессий {n}", { n: view.spend.sessions })}
{view.spend.costEstimated && " · ≈ — " + t("оценка по прайсу API")}.
</p>
<details className="text-sm">
<summary className="cursor-pointer text-xs text-muted-foreground">{t("Изменить бюджет стори")}</summary>
<form action={action} className="mt-2 flex flex-col gap-2">
<Hidden fields={{ taskId, back }} />
<BudgetFields budget={view.source === "task" ? view.budget : {}} placeholder={projectBudget} />
<div className="flex flex-wrap gap-2">
<Button size="sm" name="mode" value="set">{t("Сохранить")}</Button>
<Button size="sm" variant="outline" name="mode" value="unlimited">{t("Без лимита")}</Button>
{view.source === "task" && (
<Button size="sm" variant="ghost" name="mode" value="inherit">{t("Как в проекте")}</Button>
)}
</div>
</form>
</details>
</div>
);
}
export async function ProjectBudgetPanel({ projectId, budget, back, action }: { projectId: number; budget: Budget; back: string; action: (f: FormData) => Promise<void> }) {
const t = await getT();
return (
<form action={action} className="flex flex-col gap-2">
<Hidden fields={{ projectId, back }} />
<BudgetFields budget={budget} />
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
<p className="m-0 text-xs text-muted-foreground">
{t("Бюджет по умолчанию для каждой стори; пусто — без предела. Превышение ставит стори на паузу (ход прерывается, разговор сохраняется) и присылает вопрос: продлить, снять лимит или остановить.")}
</p>
</form>
);
}
// ── PEP-47: metrics ───────────────────────────────────────────────────────────────
function Stat({ label, value, hint }: { label: string; value: ReactNode; hint?: string }) {
return (
<div className="flex flex-col gap-0.5 rounded-lg border bg-card px-3 py-2.5" title={hint}>
<span className="text-xs text-muted-foreground">{label}</span>
<span className="font-mono text-lg font-semibold tabular-nums">{value}</span>
</div>
);
}
const day = (d: Date, locale: Locale) => d.toLocaleDateString(intlLocale(locale), { day: "2-digit", month: "2-digit" });
function Bar({ value, max }: { value: number; max: number }) {
return (
<span className="relative inline-block h-1.5 w-full min-w-10 overflow-hidden rounded-full bg-muted align-middle" aria-hidden>
<span className="absolute inset-y-0 left-0 rounded-full bg-primary/70" style={{ width: `${max > 0 ? Math.max(value > 0 ? 3 : 0, (value / max) * 100) : 0}%` }} />
</span>
);
}
export async function MetricsTab({ m, projectKey }: { m: ProjectMetrics; projectKey: string }) {
const t = await getT();
const hours = (h: number | null) => t.text(fmtHours(h));
const tokens = (n: number) => t.text(fmtTokens(n));
const s = m.summary;
const maxDone = Math.max(...m.weekly.map((w) => w.done), 0);
const maxHours = Math.max(...m.weekly.map((w) => w.runnerHours), 0);
const cols: Array<[string, (b: MetricsBucket) => ReactNode]> = [
[t("Цикл"), (b) => hours(b.cycleHoursMedian)],
[t("1-й проход"), (b) => fmtPct(b.firstPassRate)],
[t("Возвраты"), (b) => fmtPct(b.reviewReturnRate)],
[t("Вопр./стори"), (b) => (b.questionsPerStory == null ? "—" : b.questionsPerStory.toFixed(1))],
[t("Ждали PM"), (b) => hours(b.pmWaitHours)],
[t("Лимиты"), (b) => b.limitHits],
[t("Токены"), (b) => tokens(b.spend.tokens)],
[t("Стоимость"), (b) => fmtCost(b.spend.usage)],
];
return (
<div className="flex flex-col gap-8">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="text-muted-foreground">{t("Период:")}</span>
{[4, 8, 12].map((w) => (
<Link key={w} href={`/p/${projectKey}?tab=metrics&weeks=${w}`} aria-current={m.weeks === w ? "page" : undefined} className={cn("rounded-md border px-2 py-0.5 text-xs", m.weeks === w ? "border-primary text-foreground" : "text-muted-foreground")}>
{t("{n} нед.", { n: w })}
</Link>
))}
</div>
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-5">
<Stat label={t("Готово стори")} value={s.done} />
<Stat label={t("Время цикла (медиана)")} value={hours(s.cycleHoursMedian)} hint={t("От «В работу» до «Готово»")} />
<Stat label={t("Приняты с первого раза")} value={fmtPct(s.firstPassRate)} hint={t("Без возврата из ревью и без замечаний ревьюера")} />
<Stat label={t("Возвраты с ревью")} value={fmtPct(s.reviewReturnRate)} />
<Stat label={t("Вопросов PM на стори")} value={s.questionsPerStory == null ? "—" : s.questionsPerStory.toFixed(1)} hint={t("Вопросы, разрешения и одобрения; уведомления не считаются")} />
<Stat label={t("Часы раннеров")} value={hours(s.runnerHours)} />
<Stat label={t("Агенты ждали PM")} value={hours(s.pmWaitHours)} hint={t("Сумма времени от вопроса агента до ответа человека")} />
<Stat label={t("Упоры в лимит")} value={s.limitHits} />
<Stat label={t("Токены")} value={tokens(s.spend.tokens)} />
<Stat label={t("Стоимость")} value={fmtCost(s.spend.usage)} hint={t("≈ — оценка по прайсу API, если агент не сообщил стоимость")} />
</div>
<section className="flex flex-col gap-2">
<h2 className="m-0 text-[15px] font-semibold">{t("По неделям")}</h2>
<div className="overflow-x-auto rounded-lg border">
<table className="w-full min-w-[760px] border-collapse text-sm">
<thead className="bg-muted/40 text-xs text-muted-foreground">
<tr>
<th className="px-3 py-2 text-left font-medium">{t("Неделя")}</th>
<th className="px-3 py-2 text-left font-medium">{t("Готово")}</th>
<th className="px-3 py-2 text-left font-medium">{t("Раннеры")}</th>
{cols.map(([h]) => (
<th key={h} className="px-3 py-2 text-right font-medium whitespace-nowrap">{h}</th>
))}
</tr>
</thead>
<tbody>
{[...m.weekly].reverse().map((w) => (
<tr key={w.from.toISOString()} className="border-t">
<td className="px-3 py-1.5 font-mono text-xs whitespace-nowrap">{day(w.from, t.locale)}</td>
<td className="px-3 py-1.5">
<span className="flex items-center gap-2"><span className="w-5 font-mono tabular-nums">{w.done}</span><Bar value={w.done} max={maxDone} /></span>
</td>
<td className="px-3 py-1.5">
<span className="flex items-center gap-2"><span className="w-16 shrink-0 font-mono text-xs whitespace-nowrap tabular-nums">{hours(w.runnerHours)}</span><Bar value={w.runnerHours} max={maxHours} /></span>
</td>
{cols.map(([h, f]) => (
<td key={h} className="px-3 py-1.5 text-right font-mono text-xs tabular-nums whitespace-nowrap">{f(w)}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</section>
<div className="grid gap-8 lg:grid-cols-2">
<section className="flex flex-col gap-2">
<h2 className="m-0 text-[15px] font-semibold">{t("По агентам")}</h2>
{m.byProvider.length === 0 ? (
<Empty>{t("Сессий за период не было.")}</Empty>
) : (
<SimpleTable
head={[t("Агент"), t("Сессий"), t("Стори"), t("Часы"), t("Токены"), t("Стоимость")]}
rows={m.byProvider.map((p) => [PROVIDER_NAMES[p.provider as keyof typeof PROVIDER_NAMES] ?? p.provider, p.sessions, p.stories, hours(p.hours), tokens(p.spend.tokens), fmtCost(p.spend.usage)])}
/>
)}
</section>
<section className="flex flex-col gap-2">
<h2 className="m-0 text-[15px] font-semibold">{t("По эпикам (всё время)")}</h2>
{m.byEpic.length === 0 ? (
<Empty>{t("Стори нет.")}</Empty>
) : (
<SimpleTable
head={[t("Эпик"), t("Стори"), t("Готово"), t("Время"), t("Токены"), t("Стоимость")]}
rows={m.byEpic.map((e) => [
e.goalId ? <Link key="t" href={`/p/${projectKey}?epic=${e.goalId}`}>{e.title}</Link> : e.title,
e.stories,
e.done,
hours(e.spend.minutes / 60),
tokens(e.spend.tokens),
fmtCost(e.spend.usage),
])}
/>
)}
</section>
</div>
</div>
);
}
function SimpleTable({ head, rows }: { head: string[]; rows: ReactNode[][] }) {
return (
<div className="overflow-x-auto rounded-lg border">
<table className="w-full border-collapse text-sm">
<thead className="bg-muted/40 text-xs text-muted-foreground">
<tr>
{head.map((h, i) => (
<th key={h} className={cn("px-3 py-2 font-medium", i === 0 ? "text-left" : "text-right")}>{h}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((r, i) => (
<tr key={i} className="border-t">
{r.map((c, j) => (
<td key={j} className={cn("px-3 py-1.5", j === 0 ? "text-left" : "text-right font-mono text-xs tabular-nums")}>{c}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
}
// ── PEP-48: journal ───────────────────────────────────────────────────────────────
const KIND_TONE = { user: "info", agent: "ok", system: "muted" } as const;
export async function JournalList({ entries, showProject = true }: { entries: JournalEntry[]; showProject?: boolean }) {
const t = await getT();
if (!entries.length) return <Empty>{t("Действий нет.")}</Empty>;
return (
<ol className="m-0 flex list-none flex-col divide-y rounded-lg border p-0">
{entries.map((e) => {
const who = t.text(actorLabel(e));
const line = eventLine(e, t);
return (
<li key={e.id} className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1 px-3 py-2 text-sm">
<span className="w-14 shrink-0 font-mono text-xs text-muted-foreground">{ago(e.createdAt, t)}</span>
{e.actorKind ? <Badge variant={KIND_TONE[e.actorKind]}>{who}</Badge> : <Badge variant="muted">{t("автор не записан")}</Badge>}
<span className="font-mono text-xs text-primary">{e.type}</span>
{showProject && !e.taskKey && <Link href={`/p/${e.projectKey}`} className="font-mono text-xs">{e.projectKey}</Link>}
{e.taskKey && <Link href={`/t/${e.taskKey}`} className="font-mono text-xs">{e.taskKey}</Link>}
{line && <span className="min-w-0 flex-[1_1_16rem] text-xs text-muted-foreground [overflow-wrap:anywhere]">{line.length > 300 ? `${line.slice(0, 300)}…` : line}</span>}
</li>
);
})}
</ol>
);
}
export async function JournalFilters({ action, projects, value }: { action: string; projects?: Array<{ key: string; name: string }>; value: { project?: string; actor?: string; channel?: string; tab?: string } }) {
const t = await getT();
return (
<form action={action} method="get" className="flex flex-wrap items-center gap-2 text-sm">
{value.tab && <input type="hidden" name="tab" value={value.tab} />}
{projects && (
<select name="project" defaultValue={value.project ?? ""} aria-label={t("Проект")} className="h-8 rounded-md border bg-background px-2 text-sm">
<option value="">{t("Все проекты")}</option>
{projects.map((p) => (
<option key={p.key} value={p.key}>{p.key} — {p.name}</option>
))}
</select>
)}
<select name="actor" defaultValue={value.actor ?? ""} aria-label={t("Кто")} className="h-8 rounded-md border bg-background px-2 text-sm">
<option value="">{t("Все авторы")}</option>
{Object.entries(ACTOR_KIND_NAMES).map(([k, v]) => (
<option key={k} value={k}>{t.text(v)}</option>
))}
</select>
<select name="channel" defaultValue={value.channel ?? ""} aria-label={t("Канал")} className="h-8 rounded-md border bg-background px-2 text-sm">
<option value="">{t("Все каналы")}</option>
{Object.entries(ACTOR_CHANNEL_NAMES).map(([k, v]) => (
<option key={k} value={k}>{t.text(v)}</option>
))}
</select>
<Button size="sm" variant="outline">{t("Показать")}</Button>
</form>
);
}