peppa/apps/web/app/(app)/p/[key]/page.tsx
Асель c03b679a1d PEP-38: all pages on the console components, globals.css removed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:21:44 +05:00

291 lines
14 KiB
TypeScript
Raw Permalink 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 { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, Target } from "lucide-react";
import { columnOf, currentReleases, describeRepo, listReleases, bugsinkWebhookBase, type Release } from "@peppa/runner";
import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
import { Hidden, SessionCard } from "@/components/cards";
import { Disclosure, Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
import { IncidentsSection } from "@/components/Incidents";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input, Textarea } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
deploying: { label: "выкатывается", tone: "info" },
healthy: { label: "работает", tone: "ok" },
rolled_back: { label: "откат", tone: "warn" },
failed: { label: "не поднялся", tone: "danger" },
removed: { label: "удалён", tone: "muted" },
};
function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) {
return (
<div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2">
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">{name}</span>
{r ? (
<span className="flex min-w-0 flex-wrap items-center gap-x-2 text-sm">
<span className="font-mono">{r.sha.slice(0, 7)}</span>
{r.host && (
<a href={`https://${r.host}`} className="truncate text-primary">
{r.host}
</a>
)}
</span>
) : (
<span className="text-sm text-muted-foreground">нет</span>
)}
</div>
);
}
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string }> }) {
const user = await requireUser();
const { key } = await params;
const { error, created } = await searchParams;
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
const [{ goals, tasks }, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([
board(p.id),
projectSessions(p.id),
listMembers(db, p),
describeRepo(db, p),
getIncidentSettings(db, p.id),
listErrorSources(db, p.id),
listIncidents(db, p.id),
listReleases(db, p.id, 15),
currentReleases(db, p.id),
]);
const collaborators = new Set((repo.collaborators ?? []).map((l) => l.toLowerCase()));
// Members who are not repo collaborators (only known when Gitea listed them; owners of the namespace see it anyway).
const noRepoAccess = (login: string) =>
repo.collaborators !== null && login.toLowerCase() !== p.giteaOwner.toLowerCase() && !collaborators.has(login.toLowerCase());
const missingAccess = team.members.some((m) => noRepoAccess(m.login));
const isOwner = p.ownerId === user.id;
const back = `/p/${p.key}`;
const groups = [...goals.map((g) => ({ goal: g })), { goal: null }];
const goalTitle = new Map(goals.map((g) => [g.id, g.title]));
const cards: Card[] = tasks.map((t) => ({
key: `${p.key}-${t.number}`,
title: t.title,
status: t.status,
column: columnOf(t.status),
goal: t.goalId ? (goalTitle.get(t.goalId) ?? null) : null,
}));
const aside = (
<div className="flex flex-col gap-6">
<PanelSection title="Репозиторий">
<dl className="m-0 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-3 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">Где</dt>
<dd className="m-0 truncate">
<a href={repo.url} className="text-primary">{repo.fullName}</a>
</dd>
<dt className="text-muted-foreground">Пространство</dt>
<dd className="m-0">
{p.giteaOwner}
{repo.ownerKind && ` — ${repo.ownerKind === "org" ? "организация" : "личное"}`}
</dd>
<dt className="text-muted-foreground">Видимость</dt>
<dd className="m-0">{repoVisibilityLabel(repo.private)}</dd>
<dt className="text-muted-foreground">Кто видит</dt>
<dd className="m-0">{repoAudience(repo)}</dd>
<dt className="text-muted-foreground">Рабочая копия</dt>
<dd className="m-0 font-mono text-xs break-all">{p.workspacePath}</dd>
</dl>
<Button asChild size="sm" className="self-start">
<a href={repo.url}>
Открыть в Gitea <ExternalLink />
</a>
</Button>
</PanelSection>
<PanelSection title="Участники" count={team.members.length + 1}>
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
<li className="flex flex-col rounded-md px-2 py-1.5">
<span className="font-medium">{team.owner?.login ?? "—"}</span>
<span className="text-xs text-muted-foreground">владелец · агенты работают на его подписке Claude</span>
</li>
{team.members.map((m) => (
<li key={m.id} className="flex items-center gap-2 rounded-md px-2 py-1.5">
<span className="flex min-w-0 flex-1 flex-col">
<span>{m.login}</span>
<span className="text-xs text-muted-foreground">участник{noRepoAccess(m.login) && " · нет доступа к репозиторию"}</span>
</span>
{(isOwner || m.id === user.id) && (
<form action={removeProjectMember}>
<Hidden fields={{ projectId: p.id, login: m.login, back }} />
<Button size="xs" variant="destructive">{m.id === user.id ? "Выйти из проекта" : "Убрать"}</Button>
</form>
)}
</li>
))}
{team.invites.map((login) => (
<li key={login} className="flex items-center gap-2 rounded-md px-2 py-1.5">
<span className="flex min-w-0 flex-1 flex-col">
<span>{login}</span>
<span className="text-xs text-muted-foreground">приглашён · появится после первого входа в Пеппу</span>
</span>
{isOwner && (
<form action={removeProjectMember}>
<Hidden fields={{ projectId: p.id, login, back }} />
<Button size="xs" variant="destructive">Отозвать</Button>
</form>
)}
</li>
))}
</ul>
{isOwner && (
<form action={addProjectMember} className="flex gap-2">
<Hidden fields={{ projectId: p.id, back }} />
<Input name="login" required placeholder="Логин в Gitea" aria-label="Логин участника в Gitea" className="h-8" />
<Button size="sm">Добавить участника</Button>
</form>
)}
{isOwner && missingAccess && (
<form action={grantRepoAccessToMembers}>
<Hidden fields={{ projectId: p.id, back }} />
<Button size="sm">Выдать доступ участникам</Button>
</form>
)}
{isOwner && <p className="m-0 text-xs text-muted-foreground">Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.</p>}
</PanelSection>
</div>
);
return (
<Workspace aside={aside}>
<AutoRefresh />
<Flash error={error} />
{created && !error && (
<Notice>
Репозиторий создан: <a href={repo.url} className="text-primary">{repo.fullName}</a> ({repoVisibilityLabel(repo.private)}).
<Button asChild size="xs">
<a href={repo.url}>Открыть в Gitea</a>
</Button>
</Notice>
)}
<PageHeader
crumbs={<a href="/projects" className="text-muted-foreground hover:text-foreground">Проекты</a>}
title={
<>
<span className="rounded-md bg-muted px-2 font-mono text-primary">{p.key}</span> {p.name}
</>
}
>
<a href={repo.url} className="text-primary">{repo.fullName}</a> · {repoVisibilityLabel(repo.private)}
</PageHeader>
<Board cards={cards} back={back} />
<div className="mt-3 grid gap-2 md:grid-cols-2">
{groups.map(({ goal }) => (
<Disclosure
key={goal?.id ?? "none"}
summary={
<span className="flex min-w-0 items-center gap-1.5">
<Plus className="size-3.5 text-primary" />
Задача
<span className="truncate text-muted-foreground">{goal ? `· ◎ ${goal.title}` : "без цели"}</span>
</span>
}
>
<form action={addTask} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, back, goalId: goal?.id }} />
<Input name="title" required placeholder="Что сделать" aria-label="Название задачи" />
<Textarea name="description" rows={3} placeholder="Описание: контекст, критерии готовности" aria-label="Описание задачи" />
<Button variant="default" size="sm" className="self-start">Создать задачу</Button>
</form>
</Disclosure>
))}
<Disclosure
summary={
<span className="flex items-center gap-1.5">
<Target className="size-3.5 text-primary" />
Цель
</span>
}
>
<form action={addGoal} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, back }} />
<Input name="title" required placeholder="Верхнеуровневая цель" aria-label="Название цели" />
<Textarea name="description" rows={3} placeholder="Зачем и какой результат" aria-label="Описание цели" />
<Button variant="default" size="sm" className="self-start">Создать цель</Button>
</form>
</Disclosure>
</div>
<Section title="Релизы">
<div className="flex flex-col gap-2 sm:flex-row">
<EnvLine name="staging" r={current.staging} />
<EnvLine name="прод" r={current.prod} />
</div>
{current.staging && current.staging.sha !== current.prod?.sha && (
<form action={deployProdAction}>
<Hidden fields={{ projectKey: p.key, back }} />
<Button variant="default" size="sm">
<Rocket />
Выкатить в прод {current.staging.sha.slice(0, 7)}
</Button>
</form>
)}
{releases.length === 0 ? (
<Empty>
Деплоев ещё не было. Настройка — <span className="font-mono">deploy</span> в .peppa/project.json (см. «Помощь → CI/CD»).
</Empty>
) : (
<div className="overflow-x-auto rounded-lg border">
<table className="w-full border-collapse text-sm">
<tbody>
{releases.map((r) => (
<tr key={r.id} className="border-b last:border-0">
<td className="px-3 py-2 whitespace-nowrap">
{r.env}
{r.prNumber ? ` #${r.prNumber}` : ""}
</td>
<td className="px-3 py-2 font-mono">{r.sha.slice(0, 7)}</td>
<td className="px-3 py-2">
<Badge variant={RELEASE_STATUS[r.status].tone}>{RELEASE_STATUS[r.status].label}</Badge>
{r.reason && <span className="ml-1.5 text-muted-foreground">{r.reason}</span>}
</td>
<td className="px-3 py-2">
{r.tasks.map((t) => (
<Key key={t} href={`/t/${t}`} className="mr-1.5">{t}</Key>
))}
</td>
<td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
{r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Section>
<IncidentsSection
projectId={p.id}
projectKey={p.key}
back={back}
isOwner={isOwner}
settings={incidentSettings}
sources={sources}
incidents={incidents}
taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))}
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
/>
<Section title="Сессии">
{sessions.length === 0 ? <Empty>Сессий ещё не было.</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)}
</Section>
</Workspace>
);
}