From ecb667c677834fe63c545f8a830cc6965d1f5fd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 15:31:58 +0500 Subject: [PATCH] =?UTF-8?q?PEP-167:=20the=20superadmin's=20dashboard=20?= =?UTF-8?q?=E2=80=94=20totals,=20every=20user,=20every=20project=20and=20w?= =?UTF-8?q?hat=20needs=20attention?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/dashboard/page.tsx | 189 ++++++++++++++++++ apps/web/components/Sidebar.tsx | 3 +- packages/core/src/index.ts | 1 + packages/core/src/platform-dashboard.ts | 186 +++++++++++++++++ packages/shared/src/i18n/en/admin.ts | 27 +++ packages/shared/src/i18n/kk/admin.ts | 27 +++ .../testkit/test/platform-dashboard.test.ts | 46 +++++ 7 files changed, 478 insertions(+), 1 deletion(-) create mode 100644 apps/web/app/(app)/dashboard/page.tsx create mode 100644 packages/core/src/platform-dashboard.ts create mode 100644 packages/testkit/test/platform-dashboard.test.ts diff --git a/apps/web/app/(app)/dashboard/page.tsx b/apps/web/app/(app)/dashboard/page.tsx new file mode 100644 index 00000000..727be144 --- /dev/null +++ b/apps/web/app/(app)/dashboard/page.tsx @@ -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 = { 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 ( + + + + + + {c.done}/{c.total} + + + ); +} + +function Stat({ label, value, hint }: { label: string; value: number | string; hint?: string }) { + return ( + + {label} + {value} + {hint && {hint}} + + ); +} + +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 ( + + + {t("Дашборд платформы")}}> + {t("Как идут дела у всех пользователей и во всех проектах. Видит только суперадмин.")} + + +
+ + + + + + +
+ +
+ {d.attention.length === 0 ? ( + {t("Всё в порядке: ничего не зависло.")} + ) : ( +
    + {d.attention.map((a, i) => ( +
  • + {a.who} + {t.text(a.text)} +
  • + ))} +
+ )} +
+ +
+
+ + + + + + + + + + + + + + + + + {d.users.map((u) => ( + + + + + + + + + + + + + ))} + +
{t("Пользователь")}{t("Вход")}{t("Проекты")}{t("Готово")}{t("В работе")}{t("Ждут «Принять»")}{t("Агенты")}{t("Вопросы")}{t("Принято за неделю")}{t("Активность")}
+ {u.name || u.login} + {u.name && {u.login}} +
{t("с {date}", { date: u.createdAt.toLocaleDateString("ru-RU") })}
+
+ {t.text(SIGN_IN[u.signIn] ?? u.signIn)} + {u.telegram && Telegram} + + {u.projects.length ? ( + + {u.projects.map((k) => ( + {k} + ))} + + ) : ( + {t("нет")} + )} + {u.inProgress}{u.review}{u.agentsNow}{u.openQuestions}{u.acceptedLast7d}{ago(u.lastActiveAt, t)}
+
+
+ +
+
+ + + + + + + + + + + + + + + + + {d.projects.map((p) => ( + + + + + + + + + + + + + ))} + +
{t("Проект")}{t("Владелец")}{t("Готово")}{t("Бэклог")}{t("В работе")}{t("Ждут «Принять»")}{t("Агенты")}{t("Вопросы")}{t("Продукт")}{t("Активность")}
+ {p.key} {p.name} + {p.warning &&
{t("Агенты не запустятся")}
} +
{p.ownerLogin ?? "—"}{p.backlog}{p.inProgress}{p.review}{p.agentsNow}{p.openQuestions} + {p.productUrl ? ( + {t("открыть")} + ) : ( + — + )} + {ago(p.lastActiveAt, t)}
+
+
+
+ ); +} diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index 0137c70c..d835c4e4 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -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 }, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4f1bec34..4367e0d1 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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"; diff --git a/packages/core/src/platform-dashboard.ts b/packages/core/src/platform-dashboard.ts new file mode 100644 index 00000000..1d640649 --- /dev/null +++ b/packages/core/src/platform-dashboard.ts @@ -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 => + 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 { + 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`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`count(*)`, oldest: sql`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 }; +} diff --git a/packages/shared/src/i18n/en/admin.ts b/packages/shared/src/i18n/en/admin.ts index 1f0daa27..946d91d1 100644 --- a/packages/shared/src/i18n/en/admin.ts +++ b/packages/shared/src/i18n/en/admin.ts @@ -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", }; diff --git a/packages/shared/src/i18n/kk/admin.ts b/packages/shared/src/i18n/kk/admin.ts index 67d38da2..061f730d 100644 --- a/packages/shared/src/i18n/kk/admin.ts +++ b/packages/shared/src/i18n/kk/admin.ts @@ -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} бастап", + "пароль": "құпиясөз", }; diff --git a/packages/testkit/test/platform-dashboard.test.ts b/packages/testkit/test/platform-dashboard.test.ts new file mode 100644 index 00000000..afc91c5c --- /dev/null +++ b/packages/testkit/test/platform-dashboard.test.ts @@ -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; + }); +});