peppa/apps/web/lib/queries.ts
Асель 56b6224587 PEP-12: share projects with other users
- project_members / project_invites; owner adds people by Gitea login,
  invitations are applied at first login; members get the owner's access
  except member management; a member can leave
- access everywhere via projectForUser / userProjectIds (owner or member):
  web inbox, sessions, project pages, MCP
- shareProject / unshareProject: login checked in Gitea, repo collaborator
  (write) added by the owner's client or peppa-bot; missing admin rights
  don't block membership (repoAccess flag)
- web: Members block on the project page, 'shared' badge; MCP:
  list_members, add_member, remove_member; Help updated
- tests: 5 sharing journeys on mock-gitea (64 e2e total, green); test DB
  now also clears users and OAuth clients between files
- OpenSpec: pep-12 archived (project-sharing, web-auth)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-12 22:35:56 +05:00

79 lines
3.7 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, userProjectIds, 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, inArray, 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 ids = await userProjectIds(db, userId);
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<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") }));
}