// 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"; import { historyLastActivity } from "./history.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); // PEP-163: a deleted project waits in the trash — not part of the platform's progress. const allProjects = (await db.select().from(projects)).filter((p) => !p.deletedAt); 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])); // PEP-221: a quiet project's events may be only in the archive by now. const archived = historyLastActivity(); for (const [by, from] of [[activeBy, archived.projects], [userActiveBy, archived.users]] as const) for (const [k, at] of from) if (!by.get(k) || by.get(k)! < at) by.set(k, at); 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 }; }