164 lines
7.2 KiB
TypeScript
164 lines
7.2 KiB
TypeScript
// PEP-209: acceptance on one screen — every story of a project waiting for «Принять», grouped by
|
|
// the product page it changes, each with one plain sentence of what changed and the screenshots
|
|
// «было» (the working version, staging — else what everyone sees) and «стало» (the story's own
|
|
// version to check). No screenshot — a link to open the story's version to check.
|
|
import { releases, settings, tasks, type Db, keyPrefix } from "@peppa/db";
|
|
import { formatTaskKey } from "@peppa/shared";
|
|
import { m as tr } from "@peppa/shared/i18n";
|
|
import { and, desc, eq, inArray, isNull, like } from "drizzle-orm";
|
|
import { getPendingAccept } from "./accept-pending.ts";
|
|
import { getTaskResult } from "./message-details.ts";
|
|
import { reviewPreview } from "./preview.ts";
|
|
import { getSetting, setSetting } from "./settings.ts";
|
|
import type { Project } from "./projects.ts";
|
|
import type { TaskRef } from "./tasks.ts";
|
|
|
|
export interface AcceptShot {
|
|
/** The product page, e.g. "/" or "/settings". */
|
|
path: string;
|
|
/** `/api/releases/<id>/shots/<n>`; null — no screenshot of this side. */
|
|
before: string | null;
|
|
after: string | null;
|
|
}
|
|
|
|
export interface AcceptItem {
|
|
taskId: number;
|
|
key: string;
|
|
title: string;
|
|
/** What changed, in one sentence: the agent's result, else the story's title. */
|
|
summary: string;
|
|
/** The page the story changes ("" — not known: no screenshots). */
|
|
page: string;
|
|
shots: AcceptShot[];
|
|
/** The story's own version to check (its preview), if it runs. */
|
|
previewUrl: string | null;
|
|
/** «Принять» was pressed already, Peppa carries it to the merge (PEP-127). */
|
|
pending: boolean;
|
|
/** Why the last «Принять всё» could not accept it (kept 30 min). */
|
|
failed: string | null;
|
|
}
|
|
|
|
export interface AcceptGroup {
|
|
page: string;
|
|
items: AcceptItem[];
|
|
}
|
|
|
|
export interface AcceptScreen {
|
|
groups: AcceptGroup[];
|
|
total: number;
|
|
/** The version to check of the whole product (staging), and the working one everyone sees. */
|
|
checkUrl: string | null;
|
|
liveUrl: string | null;
|
|
}
|
|
|
|
const shotUrl = (releaseId: number, n: number) => `/api/releases/${releaseId}/shots/${n}`;
|
|
|
|
/** The first sentence of a text, at most `max` characters. */
|
|
export function oneSentence(text: string, max = 220): string {
|
|
const flat = text.replace(/\s+/g, " ").trim();
|
|
const first = flat.match(/^.+?[.!?](?=\s|$)/)?.[0] ?? flat;
|
|
return first.length > max ? `${first.slice(0, max - 1).trimEnd()}…` : first;
|
|
}
|
|
|
|
async function latestHealthy(db: Db, projectId: number, env: "staging" | "prod") {
|
|
const [r] = await db
|
|
.select()
|
|
.from(releases)
|
|
.where(and(eq(releases.projectId, projectId), eq(releases.env, env), eq(releases.status, "healthy")))
|
|
.orderBy(desc(releases.id))
|
|
.limit(1);
|
|
return r ?? null;
|
|
}
|
|
|
|
/** Stories in review of the project, as the acceptance page shows them. */
|
|
export async function acceptScreen(db: Db, project: Project): Promise<AcceptScreen> {
|
|
const rows = await db
|
|
.select()
|
|
.from(tasks)
|
|
.where(and(eq(tasks.projectId, project.id), eq(tasks.status, "review"), isNull(tasks.archivedAt)))
|
|
.orderBy(tasks.position, tasks.number);
|
|
const staging = await latestHealthy(db, project.id, "staging");
|
|
const prod = await latestHealthy(db, project.id, "prod");
|
|
// «было»: the working version's screenshots by page (staging, else prod).
|
|
const before = new Map<string, string>();
|
|
for (const rel of [prod, staging]) for (const [n, s] of (rel?.screenshots ?? []).entries()) before.set(s.path, shotUrl(rel!.id, n));
|
|
const items: AcceptItem[] = [];
|
|
for (const task of rows) {
|
|
const ref: TaskRef = { project, task, key: formatTaskKey(project.key, task.number) };
|
|
const p = await reviewPreview(db, ref).catch(() => null);
|
|
const shots: AcceptShot[] = (p?.screenshots ?? []).map((s) => ({ path: s.path, before: before.get(s.path) ?? null, after: p?.releaseId != null ? shotUrl(p.releaseId, s.n) : null }));
|
|
const result = await getTaskResult(db, task.id);
|
|
items.push({
|
|
taskId: task.id,
|
|
key: ref.key,
|
|
title: task.title,
|
|
summary: oneSentence(result?.summary || task.title),
|
|
page: shots[0]?.path ?? "",
|
|
shots,
|
|
previewUrl: p?.previewUrl ?? null,
|
|
pending: !!(await getPendingAccept(db, task.id)),
|
|
failed: await acceptFailure(db, task.id),
|
|
});
|
|
}
|
|
// Pages in the order their first story comes; stories without a known page last.
|
|
const groups: AcceptGroup[] = [];
|
|
for (const it of items) {
|
|
const g = groups.find((x) => x.page === it.page);
|
|
if (g) g.items.push(it);
|
|
else groups.push({ page: it.page, items: [it] });
|
|
}
|
|
groups.sort((a, b) => (a.page === "" ? 1 : 0) - (b.page === "" ? 1 : 0));
|
|
return {
|
|
groups,
|
|
total: items.length,
|
|
checkUrl: staging?.host ? `https://${staging.host}` : null,
|
|
liveUrl: prod?.host ? `https://${prod.host}` : staging?.host ? `https://${staging.host}` : null,
|
|
};
|
|
}
|
|
|
|
/** Stories in review per project (the «Принять работу · N» buttons). Archived ones don't count. */
|
|
export async function reviewCounts(db: Db, projectIds: number[]): Promise<Map<number, number>> {
|
|
const out = new Map<number, number>();
|
|
if (!projectIds.length) return out;
|
|
for (const t of await db.select({ projectId: tasks.projectId }).from(tasks).where(and(inArray(tasks.projectId, projectIds), eq(tasks.status, "review"), isNull(tasks.archivedAt)))) {
|
|
out.set(t.projectId, (out.get(t.projectId) ?? 0) + 1);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// ── «Принять всё»: why a story stayed ────────────────────────────────────────────
|
|
|
|
const FAIL_PREFIX = "accept.fail:";
|
|
const FAIL_TTL_MS = 30 * 60_000;
|
|
|
|
export async function setAcceptFailure(db: Db, taskId: number, reason: string): Promise<void> {
|
|
await setSetting(db, `${FAIL_PREFIX}${taskId}`, { reason, at: Date.now() });
|
|
}
|
|
|
|
export async function acceptFailure(db: Db, taskId: number): Promise<string | null> {
|
|
const f = await getSetting<{ reason: string; at: number }>(db, `${FAIL_PREFIX}${taskId}`);
|
|
return f && Date.now() - f.at < FAIL_TTL_MS ? f.reason : null;
|
|
}
|
|
|
|
/** Old failure notes of stories no longer in review go. */
|
|
export async function pruneAcceptFailures(db: Db): Promise<void> {
|
|
for (const row of await db.select().from(settings).where(keyPrefix(settings.key, `${FAIL_PREFIX}`))) {
|
|
if (Date.now() - (row.value as { at: number }).at >= FAIL_TTL_MS) await db.delete(settings).where(eq(settings.key, row.key));
|
|
}
|
|
}
|
|
|
|
export interface AcceptAllResult {
|
|
accepted: string[];
|
|
/** Accepted, Peppa still carries it to the merge (conflict, checks running). */
|
|
pending: string[];
|
|
failed: Array<{ key: string; reason: string }>;
|
|
}
|
|
|
|
/** «Принято 6, на доработке 1. Рабочая версия обновится через несколько минут». */
|
|
export function acceptAllSummary(r: { accepted: number; pending: number; failed: number }): string {
|
|
const parts = [tr("Принято {n}", { n: r.accepted + r.pending })];
|
|
if (r.failed) parts.push(tr("на доработке {n}", { n: r.failed }));
|
|
const head = parts.join(", ");
|
|
return r.accepted + r.pending ? `${head}. ${tr("Рабочая версия обновится через несколько минут")}` : head;
|
|
}
|