import { pausedProjectIds, listSessions, needsPerson, questionType, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef, discussionUnread } from "@peppa/core"; import { events, projects, questions, sessions, tasks } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { m } from "@peppa/shared/i18n"; import { and, asc, count, desc, eq, inArray, isNull, ne } from "drizzle-orm"; import { db } from "./db"; export type InboxItem = Awaited>[number]; /** * PEP-149: «Ждут вашего ответа» — open messages of type `question` across the user's projects, * oldest first. Stories waiting for «Принять» (`done`) have their own block; progress, blockers * and factory messages never land here. */ export async function inbox(userId: number) { return (await openMessages(userId)).filter((q) => questionType(q, q.taskStatus) === "question"); } /** PEP-149: finished stories waiting for «Принять» — open messages of type `done`. */ export async function acceptInbox(userId: number) { return (await openMessages(userId)).filter((q) => questionType(q, q.taskStatus) === "done" && q.taskStatus === "review"); } /** Every open message of the user's projects (any type), oldest first. */ async function openMessages(userId: number) { // PEP-174: a project on pause asks nothing — its messages wait until «Продолжить». const paused = await pausedProjectIds(db); const ids = (await userProjectIds(db, userId)).filter((id) => !paused.has(id)); if (!ids.length) return []; const rows = await db .select({ q: questions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, taskStatus: tasks.status, tmux: sessions.tmuxName }) .from(questions) .innerJoin(projects, eq(questions.projectId, projects.id)) .leftJoin(tasks, eq(questions.taskId, tasks.id)) .leftJoin(sessions, eq(questions.sessionId, sessions.id)) .where(and(inArray(projects.id, ids), isNull(questions.answeredAt))) .orderBy(asc(questions.id)); return rows.map((r) => ({ ...r.q, taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null, taskTitle: r.taskTitle, taskStatus: r.taskStatus, tmux: r.tmux })); } export async function activeSessions(userId: number) { const ids = new Set(await userProjectIds(db, userId)); if (!ids.size) return []; return (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId)); } export async function projectForUserByKey(userId: number, key: string): Promise { const [p] = await db.select().from(projects).where(eq(projects.key, key.toUpperCase())); if (!p) throw new PeppaError(m("Не найдено")); return projectForUser(db, userId, p.id); } export async function board(projectId: number) { // PEP-34: board order (position), archived stories hidden. const ts = await db.select().from(tasks).where(and(eq(tasks.projectId, projectId), isNull(tasks.archivedAt))).orderBy(asc(tasks.position), asc(tasks.number)); return { tasks: ts }; } export async function projectSessions(projectId: number) { return (await listSessions(db)).filter((s) => s.projectId === projectId).slice(0, 20); } export async function taskForUser(userId: number, key: string): Promise { const ref = await resolveTask(db, key); await projectForUser(db, userId, ref.project.id); return ref; } export async function taskActivity(taskId: number) { const qs = await db.select().from(questions).where(eq(questions.taskId, taskId)).orderBy(desc(questions.id)); const ss = await listSessions(db, { taskId }); // Steps of agents (PEP-33) have their own live feed. const evs = await db.select().from(events).where(and(eq(events.taskId, taskId), ne(events.type, STEP_EVENT))).orderBy(desc(events.id)).limit(100); return { questions: qs, sessions: ss, events: evs }; } export const isActiveSession = (status: string) => !["done", "failed"].includes(status); /** OpenSpec artifacts of a change from the working copy (active or archived). */ /** Counters of the side navigation (PEP-38): open PM questions and runners waiting for the PM. */ export async function navCounts(userId: number): Promise<{ questions: number; waitingRunners: number; chats: number }> { const ids = await userProjectIds(db, userId); if (!ids.length) return { questions: 0, waitingRunners: 0, chats: 0 }; // PEP-149: only what waits for the person — questions and finished stories to accept. const q = { n: (await openMessages(userId)).filter((x) => needsPerson(x, x.taskStatus)).length }; const [r] = await db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), eq(sessions.status, "waiting_input"))); // PEP-106: messages of other people in the projects' discussions the user has not read. const chats = [...(await discussionUnread(db, userId)).values()].reduce((a, b) => a + b, 0); return { questions: q.n, waitingRunners: r?.n ?? 0, chats }; } /** Latest events of one runner, newest first (runner details panel, PEP-38). */ export async function sessionEvents(sessionId: number, limit = 12) { return db.select().from(events).where(and(eq(events.sessionId, sessionId), ne(events.type, STEP_EVENT))).orderBy(desc(events.id)).limit(limit); }