peppa/apps/web/app/(app)/p/[key]/page.tsx
Асель 59c3b583de PEP-57: CD — deploy workflow, preview/staging/prod, health check and rollback, releases
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:49:24 +05:00

231 lines
11 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 { notFound } from "next/navigation";
import { AutoRefresh } from "@/components/AutoRefresh";
import { Flash, Notice, SessionCard } from "@/components/ui";
import { Board, type Card } from "@/components/Board";
import { columnOf, currentReleases, describeRepo, listReleases, type Release } from "@peppa/runner";
import { requireUser } from "@/lib/auth";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { bugsinkWebhookBase } from "@peppa/runner";
import { IncidentsSection } from "@/components/Incidents";
import { db } from "@/lib/db";
import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
const RELEASE_STATUS: Record<Release["status"], string> = {
deploying: "⏳ выкатывается",
healthy: "✅ работает",
rolled_back: "↩️ откат",
failed: "❌ не поднялся",
removed: "🗑 удалён",
};
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,
}));
return (
<>
<AutoRefresh />
<Flash error={error} />
{created && !error && (
<Notice>
Репозиторий создан: <a href={repo.url}>{repo.fullName}</a> ({repoVisibilityLabel(repo.private)}).{" "}
<a href={repo.url} className="button small">Открыть в Gitea</a>
</Notice>
)}
<h1>
<span className="mono">{p.key}</span> {p.name}
</h1>
<p className="muted">
<a href={repo.url}>{repo.fullName}</a> · {repoVisibilityLabel(repo.private)}
</p>
<Board cards={cards} back={back} />
{groups.map(({ goal }) => (
<details key={goal?.id ?? "none"} className="add">
<summary>+ Задача{goal ? ` · 🎯 ${goal.title}` : " без цели"}</summary>
<form action={addTask} className="stack">
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="back" value={back} />
{goal && <input type="hidden" name="goalId" value={goal.id} />}
<input type="text" name="title" required placeholder="Что сделать" aria-label="Название задачи" />
<textarea name="description" rows={3} placeholder="Описание: контекст, критерии готовности" aria-label="Описание задачи" />
<button className="primary">Создать задачу</button>
</form>
</details>
))}
<section>
<details>
<summary>+ Цель</summary>
<form action={addGoal} className="stack">
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="back" value={back} />
<input type="text" name="title" required placeholder="Верхнеуровневая цель" aria-label="Название цели" />
<textarea name="description" rows={3} placeholder="Зачем и какой результат" aria-label="Описание цели" />
<button className="primary">Создать цель</button>
</form>
</details>
</section>
<section>
<h2>Релизы</h2>
<p>
Staging: {current.staging ? <><span className="mono">{current.staging.sha.slice(0, 7)}</span>{current.staging.host && <> · <a href={`https://${current.staging.host}`}>{current.staging.host}</a></>}</> : <span className="muted">нет</span>}
{" · "}Прод: {current.prod ? <><span className="mono">{current.prod.sha.slice(0, 7)}</span>{current.prod.host && <> · <a href={`https://${current.prod.host}`}>{current.prod.host}</a></>}</> : <span className="muted">нет</span>}
</p>
{current.staging && current.staging.sha !== current.prod?.sha && (
<form action={deployProdAction} className="row">
<input type="hidden" name="projectKey" value={p.key} />
<input type="hidden" name="back" value={back} />
<button className="primary">🚀 Выкатить в прод {current.staging.sha.slice(0, 7)}</button>
</form>
)}
{releases.length === 0 ? (
<p className="empty">Деплоев ещё не было. Настройка — <span className="mono">deploy</span> в .peppa/project.json (см. «Помощь → CI/CD»).</p>
) : (
<table className="releases">
<tbody>
{releases.map((r) => (
<tr key={r.id}>
<td>{r.env}{r.prNumber ? ` #${r.prNumber}` : ""}</td>
<td className="mono">{r.sha.slice(0, 7)}</td>
<td>{RELEASE_STATUS[r.status]}{r.reason ? <span className="muted"> — {r.reason}</span> : null}</td>
<td>{r.tasks.join(", ")}</td>
<td className="muted">{r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}</td>
</tr>
))}
</tbody>
</table>
)}
</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>
<h2>Участники</h2>
<ul className="members">
<li>
<span><b>{team.owner?.login ?? "—"}</b> <span className="muted">владелец · агенты работают на его подписке Claude</span></span>
</li>
{team.members.map((m) => (
<li key={m.id}>
<span>
{m.login} <span className="muted">участник</span>
{noRepoAccess(m.login) && <span className="muted"> · нет доступа к репозиторию</span>}
</span>
{(isOwner || m.id === user.id) && (
<form action={removeProjectMember}>
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="login" value={m.login} />
<input type="hidden" name="back" value={back} />
<button className="small danger">{m.id === user.id ? "Выйти из проекта" : "Убрать"}</button>
</form>
)}
</li>
))}
{team.invites.map((login) => (
<li key={login}>
<span>{login} <span className="muted">приглашён · появится после первого входа в Пеппу</span></span>
{isOwner && (
<form action={removeProjectMember}>
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="login" value={login} />
<input type="hidden" name="back" value={back} />
<button className="small danger">Отозвать</button>
</form>
)}
</li>
))}
</ul>
{isOwner && (
<form action={addProjectMember} className="row">
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="back" value={back} />
<input type="text" name="login" required placeholder="Логин в Gitea" aria-label="Логин участника в Gitea" />
<button>Добавить участника</button>
</form>
)}
{isOwner && missingAccess && (
<form action={grantRepoAccessToMembers}>
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="back" value={back} />
<button>Выдать доступ участникам</button>
</form>
)}
{isOwner && (
<p className="muted">
Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.
</p>
)}
</section>
<section>
<h2>Репозиторий</h2>
<dl className="repo">
<dt>Где</dt>
<dd>
<a href={repo.url}>{repo.fullName}</a> · <a href={repo.url}>Открыть в Gitea</a>
</dd>
<dt>Пространство</dt>
<dd>
{p.giteaOwner}
{repo.ownerKind && ` — ${repo.ownerKind === "org" ? "организация" : "личное"}`}
</dd>
<dt>Видимость</dt>
<dd>{repoVisibilityLabel(repo.private)}</dd>
<dt>Кто видит</dt>
<dd>{repoAudience(repo)}</dd>
<dt>Рабочая копия</dt>
<dd className="mono">{p.workspacePath}</dd>
</dl>
</section>
<section>
<h2>Сессии</h2>
{sessions.length === 0 ? <p className="empty">Сессий ещё не было.</p> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} />)}
</section>
</>
);
}