peppa/apps/web/lib/queries.ts
Асель 2b0f2fd984 PEP-1: web platform with Gitea login, projects, goals, tasks, sessions
- web: Gitea OAuth2 login, signed session cookie, everything behind login;
  inbox with answers, project board (goals → tasks), task page with
  OpenSpec artifacts, questions and session controls; new project form;
  auto-refresh, light/dark, mobile
- users + projects.owner_id; tokens AES-256-GCM encrypted; owner-only access
- provisionProject (runner): new or existing Gitea repo, peppa-bot
  collaborator, template + openspec init, push, rollback; used by web and
  peppa project create (replaces scripts/bootstrap-project.sh)
- peppa web login-link, peppa project owner; Gitea OAuth app script
- bins/template resolved via PEPPA_ROOT (works inside the Next build)
- testkit: mock-gitea + 10 tests (42 e2e total, all green)
- OpenSpec: pep-1-web-platform archived into specs web-auth,
  project-provisioning, web-workspace

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:55:02 +05:00

78 lines
3.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { listSessions, PeppaError, projectForUser, resolveTask, type Project, type TaskRef } from "@peppa/core";
import { events, goals, projects, questions, sessions, tasks } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, asc, desc, eq, isNull } from "drizzle-orm";
import { db } from "./db";
export type InboxItem = Awaited<ReturnType<typeof inbox>>[number];
/** Open PM questions across the user's projects, oldest first. */
export async function inbox(userId: number) {
const rows = await db
.select({ q: questions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, 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(eq(projects.ownerId, userId), 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, tmux: r.tmux }));
}
export async function activeSessions(userId: number) {
const mine = await db.select({ id: projects.id }).from(projects).where(eq(projects.ownerId, userId));
if (!mine.length) return [];
const ids = new Set(mine.map((p) => p.id));
return (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
}
export async function projectForUserByKey(userId: number, key: string): Promise<Project> {
const [p] = await db.select().from(projects).where(eq(projects.key, key.toUpperCase()));
if (!p) throw new PeppaError("Не найдено");
return projectForUser(db, userId, p.id);
}
export async function board(projectId: number) {
const gs = await db.select().from(goals).where(eq(goals.projectId, projectId)).orderBy(asc(goals.id));
const ts = await db.select().from(tasks).where(eq(tasks.projectId, projectId)).orderBy(asc(tasks.number));
return { goals: gs, 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<TaskRef> {
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 });
const evs = await db.select().from(events).where(eq(events.taskId, taskId)).orderBy(desc(events.id)).limit(40);
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). */
export function openspecArtifacts(p: Project, change: string | null): Array<{ name: string; text: string }> | null {
if (!change) return null;
const changes = join(p.workspacePath, "openspec", "changes");
let dir = join(changes, change);
if (!existsSync(dir)) {
const archive = join(changes, "archive");
const hit = existsSync(archive) ? readdirSync(archive).find((d) => d.endsWith(`-${change}`) || d === change) : undefined;
if (!hit) return null;
dir = join(archive, hit);
}
return ["proposal.md", "design.md", "tasks.md"]
.filter((f) => existsSync(join(dir, f)))
.map((f) => ({ name: f, text: readFileSync(join(dir, f), "utf8") }));
}