// 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 ( ); } function WindowCell({ label, w, t }: { label: string; w: WindowView | null; t: Translator }) { if (!w) return null; return ( {label} {w.reset ? ( {t("сброшено")} ) : ( <> {Math.round(w.pct!)}% {w.resetsAt && ( {t("сброс")} )} )} ); } 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 (
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" > {t("Лимиты")} {!top ? ( {t("нет данных о лимитах")} ) : ( <> {withData.length > 1 && {t.text(top.name)}} {top.stale && top.at && {t("устарело ({ago})", { ago: ago(top.at, t) })}} )} {limited.map((a) => ( {t.text(a.name)}: {t("лимит до")} ))} {withData.length > 1 && ( +{withData.length - 1} {admin ? {t("подписки")} : t("аккаунт")} )}
); } /** 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 (
{line.state === "working" ? ( <> {t("Агенты работают")} ) : ( <> {t("Агенты продолжат в")} {offers.map((o) => ( 1 ? o.name : undefined} size="xs" /> ))} )}
); } 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

{tr("Расход: нет данных")}{provider !== "claude" ? " (" + tr("{provider} не сообщает", { provider }) + ")" : ""}

; return (

{tr("Расход: {usage}", { usage: tr.text(describeUsage(usage)) })} {t.context && ( {tr("контекст")} {tr.text(fmtTokens(t.context.used))} / {tr.text(fmtTokens(t.context.size))} )}

); } // ── 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") => ( ); return (
{field("minutes", t("Минуты раннеров"))} {field("tokens", t("Токены"))} {field("restarts", t("Перезапуски"))} {field("costUsd", t("Стоимость, $"), "0.01")}
); } export async function BudgetPanel({ view, taskId, projectBudget, back, action, paused }: { view: TaskBudgetView; taskId: number; projectBudget: Budget; back: string; action: (f: FormData) => Promise; paused: boolean }) { const t = await getT(); return (
{paused &&

{t("Бюджет исчерпан — агент на паузе до вашего решения (вопрос во «Входящих» или новый бюджет ниже).")}

}
    {BUDGET_KINDS.map((k) => { const limit = view.budget[k]; const pct = limit ? (spentOf(view, k) / limit) * 100 : null; return (
  • {t.text(BUDGET_LABELS[k])} {spentText(view, k, t)} {t("из {value}", { value: t.text(formatBudgetValue(k, limit)) })} {pct != null && }
  • ); })}

{view.source === "task" ? t("Свой бюджет стори.") : view.source === "project" ? t("Бюджет проекта по умолчанию.") : t("Без бюджета.")} {t("Сессий {n}", { n: view.spend.sessions })} {view.spend.costEstimated && " · ≈ — " + t("оценка по прайсу API")}.

{t("Изменить бюджет стори")}
{view.source === "task" && ( )}
); } export async function ProjectBudgetPanel({ projectId, budget, back, action }: { projectId: number; budget: Budget; back: string; action: (f: FormData) => Promise }) { const t = await getT(); return (

{t("Бюджет по умолчанию для каждой стори; пусто — без предела. Превышение ставит стори на паузу (ход прерывается, разговор сохраняется) и присылает вопрос: продлить, снять лимит или остановить.")}

); } // ── PEP-47: metrics ─────────────────────────────────────────────────────────────── function Stat({ label, value, hint }: { label: string; value: ReactNode; hint?: string }) { return (
{label} {value}
); } 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 ( 0 ? Math.max(value > 0 ? 3 : 0, (value / max) * 100) : 0}%` }} /> ); } 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 (
{t("Период:")} {[4, 8, 12].map((w) => ( {t("{n} нед.", { n: w })} ))}

{t("По неделям")}

{cols.map(([h]) => ( ))} {[...m.weekly].reverse().map((w) => ( {cols.map(([h, f]) => ( ))} ))}
{t("Неделя")} {t("Готово")} {t("Раннеры")}{h}
{day(w.from, t.locale)} {w.done} {hours(w.runnerHours)} {f(w)}

{t("По агентам")}

{m.byProvider.length === 0 ? ( {t("Сессий за период не было.")} ) : ( [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)])} /> )}

{t("По эпикам (всё время)")}

{m.byEpic.length === 0 ? ( {t("Стори нет.")} ) : ( [ e.goalId ? {e.title} : e.title, e.stories, e.done, hours(e.spend.minutes / 60), tokens(e.spend.tokens), fmtCost(e.spend.usage), ])} /> )}
); } function SimpleTable({ head, rows }: { head: string[]; rows: ReactNode[][] }) { return (
{head.map((h, i) => ( ))} {rows.map((r, i) => ( {r.map((c, j) => ( ))} ))}
{h}
{c}
); } // ── 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 {t("Действий нет.")}; return (
    {entries.map((e) => { const who = t.text(actorLabel(e)); const line = eventLine(e, t); return (
  1. {ago(e.createdAt, t)} {e.actorKind ? {who} : {t("автор не записан")}} {e.type} {showProject && !e.taskKey && {e.projectKey}} {e.taskKey && {e.taskKey}} {line && {line.length > 300 ? `${line.slice(0, 300)}…` : line}}
  2. ); })}
); } 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 (
{value.tab && } {projects && ( )}
); }