PEP-167: the superadmin's dashboard — totals, every user, every project and what needs attention

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-16 15:31:58 +05:00
parent 71a8636ab2
commit ecb667c677
7 changed files with 478 additions and 1 deletions

View File

@ -0,0 +1,189 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Gauge } from "lucide-react";
import { isSuperadmin, platformDashboard, type DashboardCounts } from "@peppa/core";
import { ago, Empty, PageHeader, Section } from "@/components/common";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { m } from "@peppa/shared/i18n";
export async function generateMetadata() {
const t = await getT();
return { title: t("Дашборд — Peppa FACTORY") };
}
const SIGN_IN: Record<string, string> = { egov: "eGov", google: "Google", gitea: "Gitea", local: m("пароль") };
/** «сделано / всего» with a thin bar. */
function Done({ c }: { c: DashboardCounts }) {
const pct = c.total ? Math.round((c.done / c.total) * 100) : 0;
return (
<span className="flex min-w-24 items-center gap-2">
<span className="h-1.5 w-14 overflow-hidden rounded-full bg-muted">
<span className="block h-full rounded-full bg-ok" style={{ width: `${pct}%` }} />
</span>
<span className="tabular-nums">
{c.done}/{c.total}
</span>
</span>
);
}
function Stat({ label, value, hint }: { label: string; value: number | string; hint?: string }) {
return (
<Card className="gap-0.5 px-4 py-3">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-2xl font-semibold tabular-nums">{value}</span>
{hint && <span className="text-xs text-muted-foreground">{hint}</span>}
</Card>
);
}
const th = "px-2 py-1.5 text-left text-xs font-medium whitespace-nowrap text-muted-foreground";
const td = "px-2 py-1.5 align-top whitespace-nowrap";
/** PEP-167: the superadmin's view of every user and project of the platform. */
export default async function Dashboard() {
const user = await requireUser();
if (!(await isSuperadmin(db, user))) notFound();
const t = await getT();
const d = await platformDashboard(db);
const x = d.totals;
return (
<Workspace>
<LiveRefresh scope="home" />
<PageHeader title={<><Gauge className="mr-1 inline size-5 text-primary" />{t("Дашборд платформы")}</>}>
{t("Как идут дела у всех пользователей и во всех проектах. Видит только суперадмин.")}
</PageHeader>
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6" data-dashboard-totals>
<Stat label={t("Пользователи")} value={x.users} hint={t("новых за неделю: {n} · активны за сутки: {m}", { n: x.newUsers7d, m: x.activeUsers24h })} />
<Stat label={t("Проекты")} value={x.projects} />
<Stat label={t("Задачи готово")} value={`${x.done}/${x.total}`} hint={t("в работе {a} · ждут «Принять» {b} · бэклог {c}", { a: x.inProgress, b: x.review, c: x.backlog })} />
<Stat label={t("Принято")} value={x.acceptedLast24h} hint={t("за сутки · за неделю: {n}", { n: x.acceptedLast7d })} />
<Stat label={t("Агенты работают")} value={x.agentsNow} />
<Stat label={t("Ждут ответа людей")} value={x.openQuestions} />
</div>
<Section title={t("Требует внимания")} count={d.attention.length} id="attention">
{d.attention.length === 0 ? (
<Empty>{t("Всё в порядке: ничего не зависло.")}</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-1.5 p-0">
{d.attention.map((a, i) => (
<li key={i} className="flex flex-wrap items-baseline gap-2 rounded-md border bg-card px-3 py-2 text-sm" data-attention={a.kind}>
<Badge variant={a.kind === "subscription" || a.kind === "question" ? "warn" : "muted"}>{a.who}</Badge>
<Link href={a.href} className="text-foreground hover:text-primary">{t.text(a.text)}</Link>
</li>
))}
</ul>
)}
</Section>
<Section title={t("Пользователи")} count={d.users.length} id="users">
<div className="overflow-x-auto rounded-lg border bg-card">
<table className="w-full border-collapse text-sm" data-dashboard-users>
<thead className="border-b">
<tr>
<th className={th}>{t("Пользователь")}</th>
<th className={th}>{t("Вход")}</th>
<th className={th}>{t("Проекты")}</th>
<th className={th}>{t("Готово")}</th>
<th className={th}>{t("В работе")}</th>
<th className={th}>{t("Ждут «Принять»")}</th>
<th className={th}>{t("Агенты")}</th>
<th className={th}>{t("Вопросы")}</th>
<th className={th}>{t("Принято за неделю")}</th>
<th className={th}>{t("Активность")}</th>
</tr>
</thead>
<tbody>
{d.users.map((u) => (
<tr key={u.id} className="border-b last:border-0">
<td className={td}>
<span className="font-medium">{u.name || u.login}</span>
{u.name && <span className="ml-1 text-xs text-muted-foreground">{u.login}</span>}
<div className="text-xs text-muted-foreground">{t("с {date}", { date: u.createdAt.toLocaleDateString("ru-RU") })}</div>
</td>
<td className={td}>
{t.text(SIGN_IN[u.signIn] ?? u.signIn)}
{u.telegram && <Badge variant="muted" className="ml-1">Telegram</Badge>}
</td>
<td className={td}>
{u.projects.length ? (
<span className="flex flex-wrap gap-1">
{u.projects.map((k) => (
<Link key={k} href={`/p/${k}`} className="font-mono text-xs text-primary">{k}</Link>
))}
</span>
) : (
<span className="text-muted-foreground">{t("нет")}</span>
)}
</td>
<td className={td}><Done c={u} /></td>
<td className={`${td} tabular-nums`}>{u.inProgress}</td>
<td className={`${td} tabular-nums`}>{u.review}</td>
<td className={`${td} tabular-nums`}>{u.agentsNow}</td>
<td className={`${td} tabular-nums`}>{u.openQuestions}</td>
<td className={`${td} tabular-nums`}>{u.acceptedLast7d}</td>
<td className={`${td} text-muted-foreground`}>{ago(u.lastActiveAt, t)}</td>
</tr>
))}
</tbody>
</table>
</div>
</Section>
<Section title={t("Проекты")} count={d.projects.length} id="projects">
<div className="overflow-x-auto rounded-lg border bg-card">
<table className="w-full border-collapse text-sm" data-dashboard-projects>
<thead className="border-b">
<tr>
<th className={th}>{t("Проект")}</th>
<th className={th}>{t("Владелец")}</th>
<th className={th}>{t("Готово")}</th>
<th className={th}>{t("Бэклог")}</th>
<th className={th}>{t("В работе")}</th>
<th className={th}>{t("Ждут «Принять»")}</th>
<th className={th}>{t("Агенты")}</th>
<th className={th}>{t("Вопросы")}</th>
<th className={th}>{t("Продукт")}</th>
<th className={th}>{t("Активность")}</th>
</tr>
</thead>
<tbody>
{d.projects.map((p) => (
<tr key={p.id} className="border-b last:border-0">
<td className={td}>
<Link href={`/p/${p.key}`} className="font-mono text-primary">{p.key}</Link> <span>{p.name}</span>
{p.warning && <div className="max-w-xs text-xs whitespace-normal text-warn">{t("Агенты не запустятся")}</div>}
</td>
<td className={`${td} text-muted-foreground`}>{p.ownerLogin ?? "—"}</td>
<td className={td}><Done c={p} /></td>
<td className={`${td} tabular-nums`}>{p.backlog}</td>
<td className={`${td} tabular-nums`}>{p.inProgress}</td>
<td className={`${td} tabular-nums`}>{p.review}</td>
<td className={`${td} tabular-nums`}>{p.agentsNow}</td>
<td className={`${td} tabular-nums`}>{p.openQuestions}</td>
<td className={td}>
{p.productUrl ? (
<a href={p.productUrl} target="_blank" rel="noreferrer" className="text-primary">{t("открыть")}</a>
) : (
<span className="text-muted-foreground">—</span>
)}
</td>
<td className={`${td} text-muted-foreground`}>{ago(p.lastActiveAt, t)}</td>
</tr>
))}
</tbody>
</table>
</div>
</Section>
</Workspace>
);
}

View File

@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Bot, Contact, FolderKanban, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon } from "lucide-react";
import { Bot, Contact, FolderKanban, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon, Gauge } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { LanguageSwitcher } from "@/components/I18n";
@ -33,6 +33,7 @@ const ITEMS: Item[] = [
{ href: "/team", label: m("Команда"), icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true },
{ href: "/welcome", label: m("О Peppa FACTORY"), icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true },
{ href: "/help", label: m("Помощь"), icon: LifeBuoy, match: (p) => p.startsWith("/help") },
{ href: "/dashboard", label: m("Дашборд"), icon: Gauge, match: (p) => p.startsWith("/dashboard"), admin: true },
{ href: "/subscriptions", label: m("Подписки"), icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true },
{ href: "/secrets", label: m("Секреты"), icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
{ href: "/hosts", label: m("Хосты"), icon: Server, match: (p) => p.startsWith("/hosts"), admin: true },

View File

@ -26,6 +26,7 @@ export * from "./egov.ts";
export * from "./google.ts";
export * from "./team.ts";
export * from "./progress.ts";
export * from "./platform-dashboard.ts";
export * from "./intake.ts";
export * from "./analyst-chat.ts";
export * from "./ui-mode.ts";

View File

@ -0,0 +1,186 @@
// PEP-167: the superadmin's dashboard — how every user and every project of the platform is
// doing: totals, a row per user, a row per project, and what needs the superadmin's attention.
import { events, projectMembers, projects, questions, sessions, tasks, users, type Db } from "@peppa/db";
import { m as tr } from "@peppa/shared/i18n";
import { and, isNull, max, sql } from "drizzle-orm";
import { projectAgentWarning } from "./onboarding.ts";
import { productUrls } from "./product.ts";
const HOUR = 3600_000;
/** Agent sessions that are doing a task right now (not waiting, not finished). */
const LIVE_SESSIONS = ["starting", "running"];
export interface DashboardCounts {
backlog: number;
inProgress: number;
review: number;
done: number;
total: number;
}
export interface DashboardProject extends DashboardCounts {
id: number;
key: string;
name: string;
ownerLogin: string | null;
agentsNow: number;
openQuestions: number;
/** Oldest unanswered question to the owner (ms), for «ждёт ответа N ч». */
oldestQuestionAt: number | null;
acceptedLast7d: number;
lastAcceptedAt: Date | null;
lastActiveAt: Date | null;
productUrl: string | null;
/** «Агенты не запустятся…» — no working subscription. */
warning: string | null;
}
export interface DashboardUser extends DashboardCounts {
id: number;
login: string;
name: string | null;
createdAt: Date;
signIn: "egov" | "google" | "gitea" | "local";
telegram: boolean;
projects: string[];
agentsNow: number;
openQuestions: number;
acceptedLast7d: number;
lastActiveAt: Date | null;
}
export interface DashboardAttention {
kind: "subscription" | "question" | "review" | "no_project" | "idle";
who: string;
text: string;
href: string;
}
export interface PlatformDashboard {
totals: DashboardCounts & {
users: number;
newUsers7d: number;
activeUsers24h: number;
projects: number;
agentsNow: number;
openQuestions: number;
acceptedLast24h: number;
acceptedLast7d: number;
};
users: DashboardUser[];
projects: DashboardProject[];
attention: DashboardAttention[];
}
const zero = (): DashboardCounts => ({ backlog: 0, inProgress: 0, review: 0, done: 0, total: 0 });
const column = (status: string): keyof Omit<DashboardCounts, "total"> =>
status === "backlog" ? "backlog" : status === "review" ? "review" : status === "done" ? "done" : "inProgress";
const later = (a: Date | null, b: Date | null) => (!a ? b : !b ? a : a > b ? a : b);
const hours = (ms: number) => Math.max(1, Math.round(ms / HOUR));
export async function platformDashboard(db: Db, now = new Date()): Promise<PlatformDashboard> {
const t = now.getTime();
const allUsers = (await db.select().from(users)).filter((u) => !u.disabledAt);
const allProjects = await db.select().from(projects);
const members = await db.select().from(projectMembers);
const allTasks = await db.select({ projectId: tasks.projectId, number: tasks.number, status: tasks.status, updatedAt: tasks.updatedAt }).from(tasks).where(isNull(tasks.archivedAt));
const live = await db
.select({ projectId: sessions.projectId, n: sql<number>`count(*)` })
.from(sessions)
.where(sql`${sessions.status} in (${sql.join(LIVE_SESSIONS.map((s) => sql`${s}`), sql`, `)}) and ${sessions.taskId} is not null`)
.groupBy(sessions.projectId);
// Questions the owner must answer: product questions and «готово — примите» (PEP-149), not progress notes.
const open = await db
.select({ projectId: questions.projectId, n: sql<number>`count(*)`, oldest: sql<number>`min(${questions.createdAt})` })
.from(questions)
.where(and(isNull(questions.answeredAt), sql`coalesce(${questions.msgType}, case when ${questions.kind} = 'attention' then 'progress' else 'question' end) in ('question', 'done')`))
.groupBy(questions.projectId);
const activity = await db.select({ projectId: events.projectId, at: max(events.createdAt) }).from(events).groupBy(events.projectId);
const userActivity = await db.select({ userId: events.actorUserId, at: max(events.createdAt) }).from(events).where(sql`${events.actorUserId} is not null`).groupBy(events.actorUserId);
const products = await productUrls(db, allProjects.map((p) => p.id));
const liveBy = new Map(live.map((r) => [r.projectId, Number(r.n)]));
const openBy = new Map(open.map((r) => [r.projectId, { n: Number(r.n), oldest: r.oldest == null ? null : Number(r.oldest) }]));
const activeBy = new Map(activity.map((r) => [r.projectId, r.at ? new Date(r.at) : null]));
const userActiveBy = new Map(userActivity.map((r) => [r.userId!, r.at ? new Date(r.at) : null]));
const loginOf = new Map(allUsers.map((u) => [u.id, u.login]));
const projectRows: DashboardProject[] = [];
for (const p of allProjects) {
const own = allTasks.filter((x) => x.projectId === p.id);
const row: DashboardProject = {
...zero(),
id: p.id,
key: p.key,
name: p.name,
ownerLogin: p.ownerId != null ? (loginOf.get(p.ownerId) ?? null) : null,
agentsNow: liveBy.get(p.id) ?? 0,
openQuestions: openBy.get(p.id)?.n ?? 0,
oldestQuestionAt: openBy.get(p.id)?.oldest ?? null,
acceptedLast7d: 0,
lastAcceptedAt: null,
lastActiveAt: activeBy.get(p.id) ?? null,
productUrl: products.get(p.id)?.url ?? null,
warning: await projectAgentWarning(db, p.id, now).catch(() => null),
};
for (const x of own) {
row[column(x.status)]++;
row.total++;
if (x.status === "done") {
row.lastAcceptedAt = later(row.lastAcceptedAt, x.updatedAt);
if (x.updatedAt && t - x.updatedAt.getTime() < 7 * 24 * HOUR) row.acceptedLast7d++;
}
}
projectRows.push(row);
}
// Busiest first: agents at work, then what waits for people, then the newest activity.
projectRows.sort((a, b) => b.agentsNow - a.agentsNow || b.openQuestions - a.openQuestions || (b.lastActiveAt?.getTime() ?? 0) - (a.lastActiveAt?.getTime() ?? 0));
const userRows: DashboardUser[] = allUsers.map((u) => {
const ids = new Set([...allProjects.filter((p) => p.ownerId === u.id).map((p) => p.id), ...members.filter((m) => m.userId === u.id).map((m) => m.projectId)]);
const mine = projectRows.filter((p) => ids.has(p.id));
const row: DashboardUser = {
...zero(),
id: u.id,
login: u.login,
name: u.name,
createdAt: u.createdAt,
signIn: u.egovIin ? "egov" : u.googleSub ? "google" : u.giteaId > 0 ? "gitea" : "local",
telegram: u.telegramChatId != null,
projects: mine.map((p) => p.key),
agentsNow: 0,
openQuestions: 0,
acceptedLast7d: 0,
lastActiveAt: userActiveBy.get(u.id) ?? null,
};
for (const p of mine) {
for (const k of ["backlog", "inProgress", "review", "done", "total", "agentsNow", "openQuestions", "acceptedLast7d"] as const) row[k] += p[k];
}
return row;
});
userRows.sort((a, b) => (b.lastActiveAt?.getTime() ?? b.createdAt.getTime()) - (a.lastActiveAt?.getTime() ?? a.createdAt.getTime()));
const attention: DashboardAttention[] = [];
for (const p of projectRows) {
const who = p.ownerLogin ?? p.key;
const href = `/p/${p.key}`;
if (p.warning) attention.push({ kind: "subscription", who, text: tr("{key}: агенты не запустятся — {warning}", { key: p.key, warning: p.warning }), href });
if (p.oldestQuestionAt && t - p.oldestQuestionAt > 2 * HOUR) attention.push({ kind: "question", who, text: tr("{key}: вопрос ждёт ответа {n} ч", { key: p.key, n: hours(t - p.oldestQuestionAt) }), href });
const waitingReview = allTasks.filter((x) => x.projectId === p.id && x.status === "review" && x.updatedAt && t - x.updatedAt.getTime() > 24 * HOUR).length;
if (waitingReview) attention.push({ kind: "review", who, text: tr("{key}: «Принять» ждёт дольше суток — задач: {n}", { key: p.key, n: waitingReview }), href });
const stuck = p.backlog + p.inProgress > 0 && p.agentsNow === 0 && !p.warning && (!p.lastActiveAt || t - p.lastActiveAt.getTime() > 6 * HOUR);
if (stuck) attention.push({ kind: "idle", who, text: tr("{key}: есть задачи, но агенты не работают больше 6 ч", { key: p.key }), href });
}
for (const u of userRows) {
if (!u.projects.length && t - u.createdAt.getTime() > HOUR) attention.push({ kind: "no_project", who: u.login, text: tr("{login}: зарегистрировался, проекта нет", { login: u.login }), href: "/users" });
}
const totals = { ...zero(), users: allUsers.length, newUsers7d: 0, activeUsers24h: 0, projects: allProjects.length, agentsNow: 0, openQuestions: 0, acceptedLast24h: 0, acceptedLast7d: 0 };
for (const p of projectRows) {
for (const k of ["backlog", "inProgress", "review", "done", "total", "agentsNow", "openQuestions", "acceptedLast7d"] as const) totals[k] += p[k];
}
totals.acceptedLast24h = allTasks.filter((x) => x.status === "done" && x.updatedAt && t - x.updatedAt.getTime() < 24 * HOUR).length;
totals.newUsers7d = allUsers.filter((u) => t - u.createdAt.getTime() < 7 * 24 * HOUR).length;
totals.activeUsers24h = userRows.filter((u) => u.lastActiveAt && t - u.lastActiveAt.getTime() < 24 * HOUR).length;
return { totals, users: userRows, projects: projectRows, attention };
}

View File

@ -261,4 +261,31 @@ export const admin: Dict = {
"Главная, стори, раннер": "Home, story, runner",
"Список сочетаний": "List of shortcuts",
"Закрыть палитру или окно": "Close the palette or dialog",
"{key}: «Принять» ждёт дольше суток — задач: {n}": "{key}: “Accept” has waited over a day — tasks: {n}",
"{key}: агенты не запустятся — {warning}": "{key}: agents will not start — {warning}",
"{key}: вопрос ждёт ответа {n} ч": "{key}: a question has waited {n} h for an answer",
"{key}: есть задачи, но агенты не работают больше 6 ч": "{key}: there are tasks, but agents have not worked for over 6 h",
"{login}: зарегистрировался, проекта нет": "{login}: signed up, no project yet",
"Агенты не запустятся": "Agents will not start",
"Владелец": "Owner",
"Вопросы": "Questions",
"Всё в порядке: ничего не зависло.": "All good: nothing is stuck.",
"Вход": "Sign-in",
"Дашборд": "Dashboard",
"Дашборд платформы": "Platform dashboard",
"Дашборд — Peppa FACTORY": "Dashboard — Peppa FACTORY",
"Ждут ответа людей": "Waiting for people",
"Задачи готово": "Tasks done",
"Как идут дела у всех пользователей и во всех проектах. Видит только суперадмин.": "How every user and every project is doing. Only the superadmin sees this.",
"Пользователь": "User",
"Принято": "Accepted",
"Принято за неделю": "Accepted this week",
"Продукт": "Product",
"Требует внимания": "Needs attention",
"в работе {a} · ждут «Принять» {b} · бэклог {c}": "in progress {a} · waiting for “Accept” {b} · backlog {c}",
"за сутки · за неделю: {n}": "in a day · this week: {n}",
"новых за неделю: {n} · активны за сутки: {m}": "new this week: {n} · active today: {m}",
"открыть": "open",
"с {date}": "since {date}",
"пароль": "password",
};

View File

@ -228,4 +228,31 @@ export const admin: Dict = {
"Главная, стори, раннер": "Басты бет, стори, раннер",
"Список сочетаний": "Пернелер тіркесімдерінің тізімі",
"Закрыть палитру или окно": "Палитраны немесе терезені жабу",
"{key}: «Принять» ждёт дольше суток — задач: {n}": "{key}: «Қабылдау» бір тәуліктен астам күтіп тұр — тапсырмалар: {n}",
"{key}: агенты не запустятся — {warning}": "{key}: агенттер іске қосылмайды — {warning}",
"{key}: вопрос ждёт ответа {n} ч": "{key}: сұрақ {n} сағ жауап күтіп тұр",
"{key}: есть задачи, но агенты не работают больше 6 ч": "{key}: тапсырмалар бар, бірақ агенттер 6 сағаттан астам жұмыс істемей тұр",
"{login}: зарегистрировался, проекта нет": "{login}: тіркелді, жобасы жоқ",
"Агенты не запустятся": "Агенттер іске қосылмайды",
"Владелец": "Иесі",
"Вопросы": "Сұрақтар",
"Всё в порядке: ничего не зависло.": "Бәрі жақсы: ештеңе тұрып қалған жоқ.",
"Вход": "Кіру",
"Дашборд": "Дашборд",
"Дашборд платформы": "Платформа дашборды",
"Дашборд — Peppa FACTORY": "Дашборд — Peppa FACTORY",
"Ждут ответа людей": "Адамдардың жауабын күтуде",
"Задачи готово": "Дайын тапсырмалар",
"Как идут дела у всех пользователей и во всех проектах. Видит только суперадмин.": "Барлық пайдаланушылар мен жобалардың жағдайы. Мұны тек суперәкімші көреді.",
"Пользователь": "Пайдаланушы",
"Принято": "Қабылданды",
"Принято за неделю": "Аптада қабылданды",
"Продукт": "Өнім",
"Требует внимания": "Назар аударуды қажет етеді",
"в работе {a} · ждут «Принять» {b} · бэклог {c}": "жұмыста {a} · «Қабылдау» күтуде {b} · бэклог {c}",
"за сутки · за неделю: {n}": "тәулікте · аптада: {n}",
"новых за неделю: {n} · активны за сутки: {m}": "аптада жаңа: {n} · тәулікте белсенді: {m}",
"открыть": "ашу",
"с {date}": "{date} бастап",
"пароль": "құпиясөз",
};

View File

@ -0,0 +1,46 @@
// PEP-167: the superadmin's dashboard — totals, a row per user and per project, what needs attention.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { tasks } from "@peppa/db";
import { eq } from "drizzle-orm";
import { core, db, teardown } from "./helpers.ts";
process.env.PEPPA_SECRET ??= "mock-secret-for-tests";
after(teardown);
let ownerId = 0;
let loneId = 0;
before(async () => {
const owner = await core.upsertUserFromGitea(db, { id: 167, login: "mock-dash-owner" }, { access_token: "x" });
const lone = await core.upsertUserFromGitea(db, { id: 168, login: "mock-dash-lone" }, { access_token: "x" });
ownerId = owner.id;
loneId = lone.id;
const p = await core.createProject(db, { slug: "mock-dash", key: "MDASH", name: "Dash", ownerId: owner.id, giteaOwner: "mock", workspacePath: "/tmp/mock-dash" });
const a = await core.createTask(db, { projectId: p.id, title: "Готовая" });
const b = await core.createTask(db, { projectId: p.id, title: "На приёмке" });
await core.createTask(db, { projectId: p.id, title: "В бэклоге" });
await db.update(tasks).set({ status: "done" }).where(eq(tasks.id, a.task.id));
// «Принять» waits for two days.
await db.update(tasks).set({ status: "review", updatedAt: new Date(Date.now() - 48 * 3600_000) }).where(eq(tasks.id, b.task.id));
});
describe("PEP-167: дашборд суперадмина", () => {
test("итоги, строка пользователя и проекта", async () => {
const d = await core.platformDashboard(db);
const p = d.projects.find((x) => x.key === "MDASH")!;
assert.deepEqual({ done: p.done, review: p.review, backlog: p.backlog, total: p.total, owner: p.ownerLogin }, { done: 1, review: 1, backlog: 1, total: 3, owner: "mock-dash-owner" });
const u = d.users.find((x) => x.id === ownerId)!;
assert.deepEqual(u.projects, ["MDASH"]);
assert.equal(u.done, 1);
assert.ok(d.totals.total >= 3 && d.totals.users >= 2);
});
test("«Требует внимания»: «Принять» ждёт дольше суток; пользователь без проекта — через час", async () => {
const d = await core.platformDashboard(db);
assert.ok(d.attention.some((a) => a.kind === "review" && a.text.includes("MDASH")));
assert.ok(!d.attention.some((a) => a.kind === "no_project" && a.who === "mock-dash-lone"), "just signed up — not yet");
const later = await core.platformDashboard(db, new Date(Date.now() + 2 * 3600_000));
assert.ok(later.attention.some((a) => a.kind === "no_project" && a.who === "mock-dash-lone"));
void loneId;
});
});