PEP-34/42: web — board drag order, collapsed Done, epic progress, archive, dependencies, plan page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-14 05:54:05 +05:00
parent 4fdd3afd92
commit 3b86c00768
8 changed files with 478 additions and 72 deletions

View File

@ -0,0 +1,122 @@
"use server";
// Board order and archive (PEP-34), story dependencies and the epic planner (PEP-42).
// Thin wrappers over core/runner with the owner/member check, like actions.ts.
import { getEpic, PeppaError, projectForUser, resolveTask, setDependencies, type TaskRef } from "@peppa/core";
import { applyPlan, archiveTask, discardPlanDraft, parseDepsInput, planEpic, reorderBoardTask, type PlanDep, type PlannedStory } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
let target = str(f, "back") || "/";
try {
target = (await fn()) || target;
} catch (e) {
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
const [path, query] = target.split("?");
const params = new URLSearchParams(query);
params.set("error", msg.slice(0, 300));
target = `${path}?${params}`;
}
revalidatePath("/", "layout");
redirect(target);
}
async function ownedTask(userId: number, key: string): Promise<TaskRef> {
const ref = await resolveTask(db, key);
await projectForUser(db, userId, ref.project.id);
return ref;
}
/** Drag within a column (before/after another card) or the card menu (top/bottom). */
export async function reorderTaskCard(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const ref = await ownedTask(user.id, str(f, "taskKey"));
const to = str(f, "to");
if (to === "top" || to === "bottom") await reorderBoardTask(db, ref, { to });
else if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, str(f, "other")) });
else throw new PeppaError("Неизвестное место");
});
}
/** Called from the board without a page reload (drag and drop); errors are returned. */
export async function reorderTaskInline(taskKey: string, to: "top" | "bottom" | "before" | "after", other?: string): Promise<string | null> {
const user = await requireUser();
try {
const ref = await ownedTask(user.id, taskKey);
if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, other ?? "") });
else await reorderBoardTask(db, ref, { to });
revalidatePath("/", "layout");
return null;
} catch (e) {
return e instanceof PeppaError ? e.message : (e as Error).message;
}
}
export async function archiveTaskAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const ref = await ownedTask(user.id, str(f, "taskKey"));
await archiveTask(db, ref, str(f, "archived") !== "0");
});
}
export async function setDependenciesAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const ref = await ownedTask(user.id, str(f, "taskKey"));
const keys = str(f, "blockedBy").split(/[\s,;]+/).filter(Boolean);
// "remove" drops one key from the current list; otherwise the field adds to it.
const current = (f.getAll("current") as string[]).map(String);
const remove = str(f, "remove");
await setDependencies(db, ref, remove ? current.filter((k) => k !== remove) : [...current, ...keys]);
});
}
export async function planEpicAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
const r = await planEpic(db, p, epic.id, { wishes: str(f, "wishes") || null, by: user.login });
if (!r.ok) throw new PeppaError(`Планировщик: ${r.error}`);
});
}
export async function applyPlanAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const epicId = Number(str(f, "epicId"));
const n = Number(str(f, "count"));
// Plan numbers in the form refer to the full draft; renumber them for the kept stories.
const kept: number[] = [];
for (let i = 1; i <= n; i++) if (f.get(`keep_${i}`)) kept.push(i);
if (!kept.length) throw new PeppaError("Не выбрано ни одной стори");
const renum = new Map(kept.map((orig, i) => [orig, i + 1]));
const stories: PlannedStory[] = kept.map((i) => {
const deps = parseDepsInput(str(f, `deps_${i}`)).map((d): PlanDep => {
if (typeof d !== "number") return d;
if (!renum.has(d)) throw new PeppaError(`Стори ${i} зависит от №${d}, которую вы сняли — уберите зависимость или оставьте стори`);
return renum.get(d)!;
});
return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps };
});
await applyPlan(db, p, epicId, stories);
return `/p/${p.key}?epic=${epicId}`;
});
}
export async function discardPlanAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
await discardPlanDraft(db, epic.id);
});
}

View File

@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
import { taskProgress, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@ -19,7 +19,7 @@ import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction } from "../../actions";
import { CodeTab, EpicsPanel, PullsTab, SpecsTab } from "./tabs";
import { CodeTab, EpicsPanel, ProgressBar, PullsTab, SpecsTab } from "./tabs";
import { setProjectPoolAction } from "../../subscriptions/actions";
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
@ -67,7 +67,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board";
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer] = await Promise.all([
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps] = await Promise.all([
board(p.id),
listEpics(db, p.id),
projectSessions(p.id),
@ -79,6 +79,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
listReleases(db, p.id, 15),
currentReleases(db, p.id),
getReviewSettings(db, p.id),
epicProgress(db, p.id),
blockersMap(db, p.id),
]);
// Peppa itself has no staging: its prod candidate is the newest green main (PEP-18).
const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null);
@ -108,6 +110,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null,
// PEP-33: tasks.md progress of stories in work.
progress: pr && { done: pr.done, total: pr.total, current: pr.current },
blocked: t.status === "backlog" ? blockedLabel(deps.get(t.id)) : null,
};
});
// Gitea and the working copy are read only for the open tab.
@ -159,7 +162,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
</PanelSection>
<PanelSection title="Эпики" count={epics.length}>
<EpicsPanel projectId={p.id} epics={epics} back={back} />
<EpicsPanel projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
</PanelSection>
<PanelSection title="Ревьюер">
@ -347,12 +350,23 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
key={e.id}
href={boardHref(e.id || undefined)}
aria-current={active ? "page" : undefined}
className={cn("rounded-full border px-2.5 py-0.5 text-xs hover:no-underline", active ? "border-primary bg-primary/12 text-primary" : "text-muted-foreground hover:text-foreground")}
className={cn("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs hover:no-underline", active ? "border-primary bg-primary/12 text-primary" : "text-muted-foreground hover:text-foreground")}
>
{e.title}
{e.id > 0 && (
<span className="ml-1.5 inline-flex items-center gap-1 font-mono text-[10px] tabular-nums" title={`Готово ${progressLabel(progress.get(e.id))}`}>
<ProgressBar done={progress.get(e.id)?.done ?? 0} total={progress.get(e.id)?.total ?? 0} className="w-8" />
{progressLabel(progress.get(e.id))}
</span>
)}
</a>
);
})}
{epicFilter && (
<a href={`/p/${p.key}/plan/${epicFilter.id}`} className="ml-auto text-xs text-primary">
Спланировать стори эпика →
</a>
)}
</nav>
)}
<Board cards={cards} back={back} />

View File

@ -0,0 +1,102 @@
// PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves.
import Link from "next/link";
import { notFound } from "next/navigation";
import { Sparkles } from "lucide-react";
import { getEpic, listTasks } from "@peppa/core";
import { getPlanDraft } from "@peppa/runner";
import { Hidden } from "@/components/cards";
import { Empty, Flash, PageHeader, Section } from "@/components/common";
import { PendingButton } from "@/components/PendingButton";
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 { projectForUserByKey } from "@/lib/queries";
import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions";
export default async function PlanEpicPage({ params, searchParams }: { params: Promise<{ key: string; epic: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { key, epic: epicParam } = await params;
const { error } = await searchParams;
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
const epic = await getEpic(db, p.id, Number(epicParam)).catch(() => null);
if (!epic) notFound();
const [draft, existing] = await Promise.all([getPlanDraft(db, epic.id), listTasks(db, { projectId: p.id, goalId: epic.id })]);
const back = `/p/${p.key}/plan/${epic.id}`;
return (
<Workspace aside={null}>
<Flash error={error} />
<PageHeader
crumbs={
<>
<Link href={`/p/${p.key}`} className="text-muted-foreground hover:text-foreground">{p.name}</Link>
<span className="text-muted-foreground">/</span>
<Link href={`/p/${p.key}?epic=${epic.id}`} className="text-muted-foreground hover:text-foreground">эпик «{epic.title}»</Link>
</>
}
title={<>Спланировать эпик «{epic.title}»</>}
>
Планировщик (короткая сессия Claude на подписке пула проекта) предложит стори с критериями готовности и зависимостями. Ничего не создаётся, пока вы не утвердите план.
</PageHeader>
<Section title="Эпик">
<div className="rounded-lg border bg-card p-3 text-sm whitespace-pre-wrap">{epic.description || <span className="text-muted-foreground">Без описания — опишите эпик в «⋯ Настройки проекта → Эпики», так план будет точнее.</span>}</div>
{existing.length > 0 && (
<p className="m-0 text-sm text-muted-foreground">
Уже есть стори: {existing.map((t) => t.key).join(", ")} — планировщик их не повторит и может от них зависеть.
</p>
)}
<form action={planEpicAction} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, epicId: epic.id, back }} />
<Textarea name="wishes" rows={2} defaultValue={draft?.wishes ?? ""} placeholder="Пожелания планировщику (необязательно): например, «сначала API, потом экран», «без новых зависимостей»" aria-label="Пожелания планировщику" />
<PendingButton pendingText="Планировщик думает (до 3 минут)…" className="self-start">
<Sparkles />
{draft ? "Спланировать заново" : "Спланировать"}
</PendingButton>
</form>
</Section>
<Section title={draft ? `Черновик плана — ${draft.stories.length} стори` : "Черновик плана"}>
{!draft ? (
<Empty>Черновика нет. Нажмите «Спланировать».</Empty>
) : (
<>
<form action={applyPlanAction} className="flex flex-col gap-3">
<Hidden fields={{ projectId: p.id, epicId: epic.id, back, count: draft.stories.length }} />
{draft.stories.map((s, i) => {
const n = i + 1;
return (
<fieldset key={n} className="m-0 flex flex-col gap-2 rounded-lg border bg-card p-3">
<legend className="sr-only">Стори {n}</legend>
<div className="flex items-center gap-2">
<input type="checkbox" name={`keep_${n}`} defaultChecked aria-label={`Создать стори ${n}`} className="size-4 accent-primary" />
<span className="font-mono text-xs text-muted-foreground">№{n}</span>
<Input name={`title_${n}`} required minLength={3} defaultValue={s.title} aria-label={`Название стори ${n}`} className="h-8 flex-1" />
</div>
<Textarea name={`description_${n}`} rows={5} defaultValue={s.description} aria-label={`Описание стори ${n}`} />
<label className="flex items-center gap-2 text-sm">
<span className="text-muted-foreground whitespace-nowrap">Ждёт</span>
<Input name={`deps_${n}`} defaultValue={s.dependsOn.join(", ")} placeholder={`номера плана или ключи: 1, ${p.key}-3`} aria-label={`Зависимости стори ${n}`} className="h-8" />
</label>
</fieldset>
);
})}
<p className="m-0 text-xs text-muted-foreground">Снимите галочку, чтобы не создавать стори. Стори встанут в конец бэклога в этом порядке; зависимые диспетчер не возьмёт, пока предшественники не в ревью или готово.</p>
<Button variant="default" className="self-start">Создать стори</Button>
</form>
<form action={discardPlanAction}>
<Hidden fields={{ projectId: p.id, epicId: epic.id, back }} />
<Button size="sm" variant="ghost">Удалить черновик</Button>
</form>
<p className="m-0 text-xs text-muted-foreground">
Черновик от {new Date(draft.createdAt).toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}, {draft.createdBy}.
</p>
</>
)}
</Section>
</Workspace>
);
}

View File

@ -160,7 +160,17 @@ export function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; error:
}
/** «⋯ Настройки проекта» → Эпики: labels that group stories (stored as goals). */
export function EpicsPanel({ projectId, epics, back }: { projectId: number; epics: Epic[]; back: string }) {
/** PEP-34: done/total of an epic as a thin bar. */
export function ProgressBar({ done, total, className }: { done: number; total: number; className?: string }) {
const pct = total ? Math.round((done / total) * 100) : 0;
return (
<span role="progressbar" aria-valuemin={0} aria-valuemax={total} aria-valuenow={done} aria-label={`Готово ${done} из ${total}`} className={`inline-block h-1 overflow-hidden rounded-full bg-muted ${className ?? "w-12"}`}>
<span className="block h-full rounded-full bg-ok" style={{ width: `${pct}%` }} />
</span>
);
}
export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { projectId: number; projectKey: string; epics: Epic[]; progress: Map<number, { done: number; total: number }>; back: string }) {
return (
<div className="flex flex-col gap-2 text-sm">
{epics.length === 0 && <p className="m-0 text-muted-foreground">Эпиков нет. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори.</p>}
@ -169,6 +179,8 @@ export function EpicsPanel({ projectId, epics, back }: { projectId: number; epic
<summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 select-none [&::-webkit-details-marker]:hidden">
<span className="text-muted-foreground transition-transform group-open:rotate-90">›</span>
<span className="min-w-0 flex-1 truncate">{e.title}</span>
<ProgressBar done={progress.get(e.id)?.done ?? 0} total={progress.get(e.id)?.total ?? 0} />
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">{progress.get(e.id)?.done ?? 0}/{progress.get(e.id)?.total ?? 0}</span>
<span className="font-mono text-[11px] text-muted-foreground">#{e.id}</span>
</summary>
<div className="flex flex-col gap-2 border-t px-3 py-2.5">
@ -178,12 +190,17 @@ export function EpicsPanel({ projectId, epics, back }: { projectId: number; epic
<Textarea name="description" rows={3} defaultValue={e.description ?? ""} placeholder="Описание для агента: зачем этот эпик" aria-label="Описание эпика" />
<Button size="xs" className="self-start">Сохранить</Button>
</form>
<form action={editEpic}>
<Hidden fields={{ projectId, epicId: e.id, back, archive: "1" }} />
<Button size="xs" variant="ghost">
<Archive />В архив
<div className="flex flex-wrap gap-2">
<Button asChild size="xs" variant="outline">
<a href={`/p/${projectKey}/plan/${e.id}`}>Спланировать стори</a>
</Button>
</form>
<form action={editEpic}>
<Hidden fields={{ projectId, epicId: e.id, back, archive: "1" }} />
<Button size="xs" variant="ghost">
<Archive />В архив
</Button>
</form>
</div>
</div>
</details>
))}

View File

@ -2,8 +2,10 @@
// OpenSpec artifacts and the course of work (?tab=). Live updates — PEP-37, agent steps — PEP-33.
import Link from "next/link";
import { notFound } from "next/navigation";
import { CircleCheck, CircleX, GitPullRequest, Hourglass, Pencil, Play } from "lucide-react";
import { Archive, ArchiveRestore, CircleCheck, CircleX, GitPullRequest, Hourglass, Lock, Pencil, Play, X } from "lucide-react";
import {
blockersOf,
dependentsOf,
FINISHED_SESSION_STATUSES,
getEpic,
isSuperadmin,
@ -39,6 +41,8 @@ import { taskActivity, taskForUser } from "@/lib/queries";
import { cn } from "@/lib/utils";
import { editStoryAction, startTaskSession } from "../../actions";
import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs";
import { archiveTaskAction, setDependenciesAction } from "../../board-actions";
import { Badge } from "@/components/ui/badge";
const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> };
@ -67,6 +71,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
const tabHref = (id: StoryTab) => `/t/${ref.key}?tab=${id}`;
const back = tabHref(tab);
const preview = await reviewPreview(db, ref);
const [blockers, dependents] = await Promise.all([blockersOf(db, ref), dependentsOf(db, ref)]);
// PEP-67: superadmins choose the subscriptions a runner may take; others run on the project's pool.
const superadmin = await isSuperadmin(db, user);
const pool = await projectPool(db, project.id);
@ -90,6 +95,47 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
const aside = (
<div className="flex flex-col gap-6">
<ReviewPreview preview={preview} />
<PanelSection title="Зависимости">
{blockers.length === 0 && dependents.length === 0 && <p className="m-0 text-sm text-muted-foreground">Стори ни от чего не зависит.</p>}
{blockers.length > 0 && (
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{blockers.map((b) => (
<li key={b.id} className="flex items-center gap-2">
{b.open ? <Lock className="size-3.5 text-warn" /> : <CircleCheck className="size-3.5 text-ok" />}
<Link href={`/t/${b.key}`} className="min-w-0 flex-1 truncate">
<span className="font-mono text-xs text-primary">{b.key}</span> {b.title}
</Link>
<StatusBadge status={b.status} />
<form action={setDependenciesAction}>
<Hidden fields={{ taskKey: ref.key, back, remove: b.key }} />
{blockers.map((x) => <input key={x.id} type="hidden" name="current" value={x.key} />)}
<button type="submit" title={`Убрать зависимость от ${b.key}`} aria-label={`Убрать зависимость от ${b.key}`} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
<X className="size-3.5" />
</button>
</form>
</li>
))}
</ul>
)}
{blockers.some((b) => b.open) && <p className="m-0 text-xs text-muted-foreground">Диспетчер не возьмёт стори, пока предшественники не в ревью или готово.</p>}
<form action={setDependenciesAction} className="flex gap-2">
<Hidden fields={{ taskKey: ref.key, back }} />
{blockers.map((x) => <input key={x.id} type="hidden" name="current" value={x.key} />)}
<Input name="blockedBy" required placeholder={`Ждёт стори: ${project.key}-3`} aria-label="Добавить зависимость" className="h-8" />
<Button size="sm" variant="outline">Добавить</Button>
</form>
{dependents.length > 0 && (
<p className="m-0 text-sm">
<span className="text-muted-foreground">Её ждут: </span>
{dependents.map((d, i) => (
<span key={d.id}>
{i > 0 && ", "}
<Link href={`/t/${d.key}`} className="font-mono text-xs">{d.key}</Link>
</span>
))}
</p>
)}
</PanelSection>
<PanelSection title="Проверки">
<Link href={tabHref("tests")} className="flex flex-wrap items-center gap-2 text-sm text-foreground hover:no-underline">
{CI_ICON[ci.state as keyof typeof CI_ICON]}
@ -142,6 +188,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
title={
<>
<span className="font-mono text-primary">{ref.key}</span> {task.title} <StatusBadge status={task.status} />
{task.archivedAt && <Badge variant="muted" className="ml-1.5 align-middle">в архиве</Badge>}
</>
}
actions={
@ -160,6 +207,12 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
</a>
</Button>
)}
<form action={archiveTaskAction}>
<Hidden fields={{ taskKey: ref.key, back, archived: task.archivedAt ? "0" : "1" }} />
<Button size="sm" variant="ghost" title={task.archivedAt ? "Вернуть стори на доску (в конец)" : "Убрать с доски; агент остановится, история останется"}>
{task.archivedAt ? <><ArchiveRestore />Вернуть</> : <><Archive />В архив</>}
</Button>
</form>
</>
}
>

View File

@ -1,8 +1,11 @@
"use client";
import Link from "next/link";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";
import { ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Lock } from "lucide-react";
import { moveTaskCard } from "@/app/(app)/actions";
import { reorderTaskInline } from "@/app/(app)/board-actions";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
@ -17,6 +20,8 @@ export interface Card {
epic?: string | null;
/** tasks.md progress of a story in work (PEP-33). */
progress?: CardProgress | null;
/** PEP-42: "ждёт PEP-3" while a predecessor isn't in review/done. */
blocked?: string | null;
}
export interface CardProgress {
done: number;
@ -42,6 +47,8 @@ export function ProgressLine({ p, className }: { p: CardProgress; className?: st
);
}
const DONE_COLLAPSED = "peppa.board.doneCollapsed";
const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [
{ id: "backlog", title: "Бэклог", hint: "", dot: "bg-muted-foreground" },
{ id: "in_progress", title: "В работе", hint: "сюда — запустить агента", dot: "bg-info" },
@ -59,10 +66,30 @@ const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
review: { to: "done", label: "Принять ✓" },
};
/** Story board: drag a card (or use its button) to move it; the server starts/stops agents. */
/**
* Story board: drag a card to another column (or use its button) to move it — the server
* starts/stops agents; drag it onto a card of its own column to change the order (= priority
* for the dispatcher, PEP-34). «Готово» can be collapsed (remembered in the browser).
*/
export function Board({ cards, back }: { cards: Card[]; back: string }) {
const router = useRouter();
const [pending, start] = useTransition();
const [over, setOver] = useState<Column | null>(null);
const [error, setError] = useState<string | null>(null);
const [doneCollapsed, setDoneCollapsed] = useState(false);
useEffect(() => {
try {
setDoneCollapsed(localStorage.getItem(DONE_COLLAPSED) === "1");
} catch {}
}, []);
const toggleDone = () => {
setDoneCollapsed((v) => {
try {
localStorage.setItem(DONE_COLLAPSED, v ? "0" : "1");
} catch {}
return !v;
});
};
const move = (key: string, to: Column) => {
const f = new FormData();
f.set("taskKey", key);
@ -70,65 +97,121 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
f.set("back", back);
start(() => moveTaskCard(f));
};
const reorder = (key: string, to: "top" | "bottom" | "before" | "after", other?: string) =>
start(async () => {
setError(await reorderTaskInline(key, to, other));
router.refresh();
});
return (
<div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4", pending && "pointer-events-none opacity-60")}>
{COLUMNS.map((c) => {
const list = cards.filter((x) => x.column === c.id);
return (
<section
key={c.id}
aria-label={c.title}
className={cn("flex min-h-32 flex-col gap-2 rounded-lg border bg-muted/40 p-2", over === c.id && "border-dashed border-primary bg-primary/5")}
onDragOver={(e) => {
e.preventDefault();
setOver(c.id);
}}
onDragLeave={() => setOver(null)}
onDrop={(e) => {
e.preventDefault();
setOver(null);
const key = e.dataTransfer.getData("text/plain");
const card = cards.find((x) => x.key === key);
if (card && card.column !== c.id) move(key, c.id);
}}
>
<h3 className="m-0 flex items-center gap-2 px-1.5 pt-1 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
<span className={cn("size-1.5 rounded-full", c.dot)} />
{c.title}
<span className="ml-auto tabular-nums">{list.length}</span>
</h3>
{c.hint && <p className="m-0 px-1.5 text-[11px] text-muted-foreground">{c.hint}</p>}
{list.map((card) => (
<article
key={card.key}
draggable
onDragStart={(e) => e.dataTransfer.setData("text/plain", card.key)}
className="flex cursor-grab flex-col gap-2 rounded-md border bg-card p-2.5 text-sm shadow-xs transition-colors hover:border-primary/40 active:cursor-grabbing"
>
<Link href={`/t/${card.key}`} className="text-foreground hover:no-underline">
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
</Link>
{card.progress && <ProgressLine p={card.progress} />}
{(STATUS[card.status] || NEXT[c.id] || card.epic) && (
<div className="flex flex-wrap items-center gap-1.5">
{card.epic && (
<Badge variant="outline" className="max-w-full min-w-0" title={`Эпик: ${card.epic}`}>
<span className="truncate">{card.epic}</span>
</Badge>
)}
{STATUS[card.status] && <Badge variant={STATUS[card.status]!.tone}>{STATUS[card.status]!.label}</Badge>}
{NEXT[c.id] && (
<Button size="xs" className="ml-auto" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}>
{NEXT[c.id]!.label}
</Button>
)}
</div>
<div className="flex flex-col gap-2">
{error && (
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-1.5 text-sm text-destructive">
{error}
</p>
)}
<div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4", pending && "pointer-events-none opacity-60")}>
{COLUMNS.map((c) => {
const list = cards.filter((x) => x.column === c.id);
const collapsed = c.id === "done" && doneCollapsed;
return (
<section
key={c.id}
aria-label={c.title}
className={cn("flex min-h-32 flex-col gap-2 rounded-lg border bg-muted/40 p-2", over === c.id && "border-dashed border-primary bg-primary/5", collapsed && "min-h-0")}
onDragOver={(e) => {
e.preventDefault();
setOver(c.id);
}}
onDragLeave={() => setOver(null)}
onDrop={(e) => {
e.preventDefault();
setOver(null);
const key = e.dataTransfer.getData("text/plain");
const card = cards.find((x) => x.key === key);
if (!card) return;
if (card.column !== c.id) move(key, c.id);
else if (list.at(-1)?.key !== key) reorder(key, "bottom"); // empty space of its own column: to the end
}}
>
<h3 className="m-0 flex items-center gap-2 px-1.5 pt-1 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
<span className={cn("size-1.5 rounded-full", c.dot)} />
{c.title}
<span className="ml-auto tabular-nums">{list.length}</span>
{c.id === "done" && (
<button type="button" onClick={toggleDone} aria-expanded={!collapsed} aria-label={collapsed ? "Развернуть «Готово»" : "Свернуть «Готово»"} className="-mr-1 rounded p-0.5 hover:bg-muted hover:text-foreground">
{collapsed ? <ChevronRight className="size-3.5" /> : <ChevronDown className="size-3.5" />}
</button>
)}
</article>
))}
</section>
);
})}
</h3>
{!collapsed && c.hint && <p className="m-0 px-1.5 text-[11px] text-muted-foreground">{c.hint}</p>}
{!collapsed &&
list.map((card, i) => (
<article
key={card.key}
draggable
data-task-key={card.key}
onDragStart={(e) => e.dataTransfer.setData("text/plain", card.key)}
onDrop={(e) => {
const key = e.dataTransfer.getData("text/plain");
const dragged = cards.find((x) => x.key === key);
if (!dragged || dragged.column !== c.id) return; // another column: the section moves it
e.preventDefault();
e.stopPropagation();
setOver(null);
if (key === card.key) return;
const r = e.currentTarget.getBoundingClientRect();
reorder(key, e.clientY < r.top + r.height / 2 ? "before" : "after", card.key);
}}
className="group flex cursor-grab flex-col gap-2 rounded-md border bg-card p-2.5 text-sm shadow-xs transition-colors hover:border-primary/40 active:cursor-grabbing"
>
<div className="flex items-start gap-1">
<Link href={`/t/${card.key}`} className="min-w-0 flex-1 text-foreground hover:no-underline">
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
</Link>
{list.length > 1 && (
<span className="flex shrink-0 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 max-sm:opacity-100">
{i > 0 && (
<button type="button" title="Наверх" aria-label={`${card.key} наверх`} disabled={pending} onClick={() => reorder(card.key, "top")} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
<ChevronsUp className="size-3.5" />
</button>
)}
{i < list.length - 1 && (
<button type="button" title="Вниз" aria-label={`${card.key} вниз`} disabled={pending} onClick={() => reorder(card.key, "bottom")} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
<ChevronsDown className="size-3.5" />
</button>
)}
</span>
)}
</div>
{card.progress && <ProgressLine p={card.progress} />}
{(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && (
<div className="flex flex-wrap items-center gap-1.5">
{card.blocked && (
<Badge variant="warn" title="Диспетчер не возьмёт стори, пока предшественники не в ревью или готово">
<Lock className="size-3" />
{card.blocked}
</Badge>
)}
{card.epic && (
<Badge variant="outline" className="max-w-full min-w-0" title={`Эпик: ${card.epic}`}>
<span className="truncate">{card.epic}</span>
</Badge>
)}
{STATUS[card.status] && <Badge variant={STATUS[card.status]!.tone}>{STATUS[card.status]!.label}</Badge>}
{NEXT[c.id] && (
<Button size="xs" className="ml-auto" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}>
{NEXT[c.id]!.label}
</Button>
)}
</div>
)}
</article>
))}
</section>
);
})}
</div>
<p className="m-0 text-xs text-muted-foreground">Порядок в колонке — приоритет: перетащите карточку выше или ниже; диспетчер берёт стори из бэклога сверху.</p>
</div>
);
}

View File

@ -0,0 +1,14 @@
"use client";
import { useFormStatus } from "react-dom";
import { Button } from "@/components/ui/button";
/** Submit button that shows a waiting text while its form's server action runs. */
export function PendingButton({ children, pendingText, className }: { children: React.ReactNode; pendingText: string; className?: string }) {
const { pending } = useFormStatus();
return (
<Button variant="default" disabled={pending} aria-busy={pending} className={className}>
{pending ? pendingText : children}
</Button>
);
}

View File

@ -34,7 +34,8 @@ export async function projectForUserByKey(userId: number, key: string): Promise<
}
export async function board(projectId: number) {
const ts = await db.select().from(tasks).where(eq(tasks.projectId, projectId)).orderBy(asc(tasks.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 };
}