Merge pull request 'PEP-111: «Ваш продукт» — где результат и что дальше' (#101) from task/pep-111 into main
This commit is contained in:
commit
83ad46cefc
@ -1,8 +1,9 @@
|
||||
import { Fragment } from "react";
|
||||
import { ProductCard } from "@/components/ProductCard";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
|
||||
import { discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Board, type Card } from "@/components/Board";
|
||||
@ -145,6 +146,9 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
const [code, pulls] = await Promise.all([tab === "code" ? repoOverview(db, p) : null, tab === "pulls" ? openPulls(db, p) : null]);
|
||||
const specs = tab === "specs" ? listSpecs(p) : [];
|
||||
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
|
||||
const product = await projectProduct(db, p.id);
|
||||
// The chat belongs to the project's people; a superadmin looking at someone else's project has none.
|
||||
const canChat = (await userProjectIds(db, user.id)).includes(p.id);
|
||||
const discussionNew = (await discussionUnread(db, user.id)).get((await ensureProjectChat(db, p.id)).id) ?? 0;
|
||||
const memory = tab === "specs" ? readMemory(p.workspacePath) : "";
|
||||
// PEP-47 metrics, PEP-48 journal, PEP-43 default budget.
|
||||
@ -461,6 +465,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
</p>
|
||||
)}
|
||||
|
||||
{tab === "board" && <ProductCard product={product} projectKey={p.key} chat={canChat} />}
|
||||
<nav aria-label="Разделы проекта" className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b">
|
||||
{TABS.map((t) => (
|
||||
<Fragment key={t.id}>
|
||||
@ -476,7 +481,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
{!!tabCount[t.id] && <span className="rounded-full bg-muted px-1.5 font-mono text-[11px] tabular-nums">{tabCount[t.id]}</span>}
|
||||
</a>
|
||||
{/* PEP-106: the people's chat of the project lives in «Чаты»; the link sits right after the board. */}
|
||||
{t.id === "board" && (
|
||||
{t.id === "board" && canChat && (
|
||||
<a href={`/chats/${p.key}`} className="-mb-px flex items-center gap-1.5 border-b-2 border-transparent px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline">
|
||||
Чат с аналитиком
|
||||
{discussionNew > 0 && <span className="rounded-full bg-info px-1.5 font-mono text-[11px] text-background tabular-nums">{discussionNew}</span>}
|
||||
|
||||
76
apps/web/components/ProductCard.tsx
Normal file
76
apps/web/components/ProductCard.tsx
Normal file
@ -0,0 +1,76 @@
|
||||
import Link from "next/link";
|
||||
import { ExternalLink, Rocket } from "lucide-react";
|
||||
import type { ProjectProduct } from "@peppa/core";
|
||||
import { ago } from "@/components/common";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
const host = (url: string) => url.replace(/^https?:\/\//, "");
|
||||
|
||||
/**
|
||||
* PEP-111: «Ваш продукт» on the project page — where the result is and what to do next, for a
|
||||
* product manager who asks «где это работает?». Nothing is shown before the first accepted story.
|
||||
*/
|
||||
export function ProductCard({ product, projectKey, chat = true }: { product: ProjectProduct; projectKey: string; chat?: boolean }) {
|
||||
const { live, check, doneStories } = product;
|
||||
if (!live && !check && doneStories === 0) return null;
|
||||
const next = chat && (
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
Что дальше: опишите следующую задачу <Link href={`/chats/${projectKey}`}>аналитику в чате</Link> — он поможет сформулировать стори, агенты сделают.
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
<section aria-label="Ваш продукт" className="mb-5 flex flex-col gap-3 rounded-xl border border-ok/40 bg-ok/5 p-4">
|
||||
{live ? (
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="text-[15px] font-semibold">Ваш продукт работает</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Открыт для всех по адресу <span className="font-mono text-foreground">{host(live.url)}</span> · обновлён {ago(live.at)}
|
||||
{live.stories.length > 0 && <> · вошли стори {live.stories.slice(0, 6).join(", ")}</>}
|
||||
</span>
|
||||
</div>
|
||||
<Button asChild variant="default">
|
||||
<a href={live.url} target="_blank" rel="noreferrer">
|
||||
<ExternalLink /> Открыть продукт
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
) : check ? (
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="text-[15px] font-semibold">Версия для проверки готова</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Пока её видите только вы: <span className="font-mono text-foreground">{host(check.url)}</span> · обновлена {ago(check.at)}. Посмотрите — и покажите всем кнопкой «Выкатить» в{" "}
|
||||
<Link href={`/p/${projectKey}?tab=releases`}>Релизах</Link>.
|
||||
</span>
|
||||
</div>
|
||||
<Button asChild variant="default">
|
||||
<a href={check.url} target="_blank" rel="noreferrer">
|
||||
<ExternalLink /> Посмотреть
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-[15px] font-semibold">Готово стори: {doneStories}</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Этот проект пока не выкатывается как сайт. Что получилось — на странице каждой готовой стори, вкладка «Результат», и во вкладке «Код». Хотите открыть продукт по ссылке — попросите аналитика
|
||||
в чате: «сделай, чтобы продукт открывался по ссылке».
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{live && check && (
|
||||
<p className="m-0 flex flex-wrap items-center gap-2 text-sm">
|
||||
<Rocket className="size-4 text-primary" />
|
||||
Есть новая версия для проверки:{" "}
|
||||
<a href={check.url} target="_blank" rel="noreferrer">
|
||||
{host(check.url)}
|
||||
</a>
|
||||
{check.stories.length > 0 && <span className="text-muted-foreground">({check.stories.slice(0, 6).join(", ")})</span>} — показать её всем можно в{" "}
|
||||
<Link href={`/p/${projectKey}?tab=releases`}>Релизах</Link>.
|
||||
</p>
|
||||
)}
|
||||
{next}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@ -45,6 +45,11 @@ function ProjectRow({ p }: { p: ProjectProgress }) {
|
||||
<Key href={`/p/${p.key}`}>{p.key}</Key>
|
||||
<Link href={`/p/${p.key}`} className="min-w-0 truncate font-medium text-foreground hover:no-underline">{p.name}</Link>
|
||||
{p.ownerLogin && <span className="rounded-full border px-2 text-[11px] text-muted-foreground">{p.ownerLogin}</span>}
|
||||
{p.product && (
|
||||
<a href={p.product.url} target="_blank" rel="noreferrer" className="rounded-full border border-ok/50 bg-ok/10 px-2 text-[11px] font-medium text-foreground hover:no-underline" title={p.product.live ? "Рабочая версия, открыта для всех" : "Версия для проверки"}>
|
||||
{p.product.live ? "Открыть продукт ↗" : "Версия для проверки ↗"}
|
||||
</a>
|
||||
)}
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{p.total ? (
|
||||
<>
|
||||
|
||||
19
openspec/changes/pep-111-your-product/proposal.md
Normal file
19
openspec/changes/pep-111-your-product/proposal.md
Normal file
@ -0,0 +1,19 @@
|
||||
# Proposal: PEP-111 — «Ваш продукт»: где результат и что дальше
|
||||
|
||||
## Why
|
||||
Владелец проекта: стори приняты, продукт выкачен и открыт по адресу, но она об этом не знает и
|
||||
спрашивает в чате «где это работает? где увидеть результат?». В ленте вместо ответа —
|
||||
«preview bc476e6: убран».
|
||||
|
||||
## What Changes
|
||||
- `core/product.ts`: `projectProduct` (рабочая версия — prod; версия для проверки — staging, если
|
||||
новее; число принятых стори), `productUrls` (для Главной).
|
||||
- Веб: карточка `ProductCard` над доской проекта («Ваш продукт работает» + адрес + «Открыть
|
||||
продукт» / «Версия для проверки готова» / «проект не выкатывается как сайт — где смотреть»),
|
||||
ссылка «Открыть продукт ↗» у проекта на Главной.
|
||||
- Сообщения PM: staging — «новая версия готова к проверке… Показать её всем?»; prod — «ваш
|
||||
продукт обновлён и открыт для всех… Что дальше»; «бэклог пуст» — со ссылкой на продукт и
|
||||
подсказкой написать аналитику. Без хэшей коммитов.
|
||||
- Чат: релизы словами («Версия для проверки: работает», «Рабочая версия продукта: работает»),
|
||||
черновые стенды стори в ленту не попадают (кроме сбоя).
|
||||
- Ссылка «Чат с аналитиком» на странице проекта — только участникам проекта.
|
||||
@ -0,0 +1,16 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Результат проекта на виду
|
||||
Веб SHALL показывать владельцу, где работает его продукт, и что делать дальше.
|
||||
|
||||
#### Scenario: Продукт выкачен
|
||||
- **WHEN** у проекта есть здоровая рабочая версия
|
||||
- **THEN** над доской видно «Ваш продукт работает», адрес и кнопка «Открыть продукт»
|
||||
|
||||
#### Scenario: Только версия для проверки
|
||||
- **WHEN** есть здоровая версия для проверки новее рабочей
|
||||
- **THEN** карточка предлагает посмотреть её и показать всем
|
||||
|
||||
#### Scenario: Проект не выкатывается
|
||||
- **WHEN** принятые стори есть, а версий нет
|
||||
- **THEN** карточка говорит, где смотреть результат
|
||||
3
openspec/changes/pep-111-your-product/tasks.md
Normal file
3
openspec/changes/pep-111-your-product/tasks.md
Normal file
@ -0,0 +1,3 @@
|
||||
- [x] 1.1 core/product.ts, сообщения релизов и «бэклог пуст»
|
||||
- [x] 1.2 веб: ProductCard, ссылка на Главной
|
||||
- [x] 1.3 тест product.test.ts; проверка в браузере на копии базы
|
||||
@ -332,7 +332,9 @@ const EVENT_TEXT: Record<string, (p: P) => { text: string; important?: boolean;
|
||||
};
|
||||
|
||||
const RELEASE_ICON: Record<string, string> = { deploying: "⏳", healthy: "🚀", rolled_back: "↩️", failed: "❌", removed: "🧹" };
|
||||
const RELEASE_RU: Record<string, string> = { deploying: "выкатывается", healthy: "здоров", rolled_back: "откатан", failed: "не выкатился", removed: "убран" };
|
||||
const RELEASE_RU: Record<string, string> = { deploying: "выкатывается", healthy: "работает", rolled_back: "не прошла проверку — возвращена прежняя", failed: "не выкатилась", removed: "убрана" };
|
||||
// PEP-111: what a release is, in words for a product manager.
|
||||
const ENV_RU: Record<string, string> = { preview: "Черновой стенд стори", staging: "Версия для проверки", prod: "Рабочая версия продукта" };
|
||||
const INCIDENT_RU: Record<string, string> = { new: "новая", open: "открыта", pending: "ждёт решения", task: "заведена стори", ignored: "игнорируем", resolved: "исправлена", regressed: "вернулась" };
|
||||
|
||||
/** First id of rows newer than a day (a fresh install doesn't import the whole history). */
|
||||
@ -430,13 +432,15 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
|
||||
const savedObjects = await getSetting<number>(db, CURSOR_OBJECTS);
|
||||
const since = new Date((savedObjects ?? now.getTime() - DAY) - 60_000);
|
||||
for (const r of await db.select().from(releases).where(gt(releases.updatedAt, since)).orderBy(asc(releases.id))) {
|
||||
const tasksIn = r.tasks.length ? ` · ${r.tasks.slice(0, 8).join(", ")}` : "";
|
||||
// A story's draft stand coming and going is plumbing: only its failure is worth a message.
|
||||
if (r.env === "preview" && r.status !== "failed" && r.status !== "rolled_back") continue;
|
||||
const tasksIn = r.tasks.length ? ` · стори: ${r.tasks.slice(0, 8).join(", ")}` : "";
|
||||
await add({
|
||||
chatId: await chatId(r.projectId),
|
||||
threadKey: `release:${r.id}`,
|
||||
kind: "event",
|
||||
important: r.env !== "preview" || r.status === "failed" || r.status === "rolled_back",
|
||||
text: `${RELEASE_ICON[r.status] ?? "•"} ${r.env} ${r.sha.slice(0, 7)}: ${RELEASE_RU[r.status] ?? r.status}${tasksIn}${r.reason ? `\n${cut(r.reason, 300)}` : ""}`,
|
||||
text: `${RELEASE_ICON[r.status] ?? "•"} ${ENV_RU[r.env] ?? r.env}: ${RELEASE_RU[r.status] ?? r.status}${tasksIn}${r.reason ? `\n${cut(r.reason, 300)}` : ""}`,
|
||||
url: r.host ? `https://${r.host}` : r.runUrl,
|
||||
dedupeKey: `release:${r.id}:${r.status}`,
|
||||
});
|
||||
|
||||
@ -26,6 +26,7 @@ export * from "./team.ts";
|
||||
export * from "./progress.ts";
|
||||
export * from "./intake.ts";
|
||||
export * from "./analyst-chat.ts";
|
||||
export * from "./product.ts";
|
||||
export * from "./local-users.ts";
|
||||
export * from "./specs.ts";
|
||||
export * from "./subscriptions.ts";
|
||||
|
||||
51
packages/core/src/product.ts
Normal file
51
packages/core/src/product.ts
Normal file
@ -0,0 +1,51 @@
|
||||
// PEP-111: «Ваш продукт» — where the result of the project lives, in words for a product
|
||||
// manager: the working version everyone sees (prod), the version to check (staging), or the
|
||||
// fact that the project is not deployed as a site at all.
|
||||
import { releases, tasks, type Db } from "@peppa/db";
|
||||
import { and, desc, eq, inArray, isNull } from "drizzle-orm";
|
||||
|
||||
export interface ProductVersion {
|
||||
url: string;
|
||||
at: Date;
|
||||
/** Story keys that went into it. */
|
||||
stories: string[];
|
||||
}
|
||||
|
||||
export interface ProjectProduct {
|
||||
/** The working product, open to everyone. */
|
||||
live: ProductVersion | null;
|
||||
/** The version to check before showing it to everyone — only when newer than `live`. */
|
||||
check: ProductVersion | null;
|
||||
/** Stories accepted so far (a product without a site still has results). */
|
||||
doneStories: number;
|
||||
}
|
||||
|
||||
export async function projectProduct(db: Db, projectId: number): Promise<ProjectProduct> {
|
||||
const latest = async (env: "prod" | "staging") =>
|
||||
(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))[0];
|
||||
const [prod, staging] = [await latest("prod"), await latest("staging")];
|
||||
const version = (r: NonNullable<typeof prod>): ProductVersion | null => (r.host ? { url: `https://${r.host}`, at: r.updatedAt ?? r.createdAt, stories: r.tasks } : null);
|
||||
const done = await db.select({ id: tasks.id }).from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.status, "done"), isNull(tasks.archivedAt)));
|
||||
return {
|
||||
live: prod ? version(prod) : null,
|
||||
check: staging && (!prod || (staging.id > prod.id && staging.sha !== prod.sha)) ? version(staging) : null,
|
||||
doneStories: done.length,
|
||||
};
|
||||
}
|
||||
|
||||
/** Product links of several projects at once (the Home page): projectId → URL of the best version. */
|
||||
export async function productUrls(db: Db, projectIds: number[]): Promise<Map<number, { url: string; live: boolean }>> {
|
||||
const out = new Map<number, { url: string; live: boolean }>();
|
||||
if (!projectIds.length) return out;
|
||||
const rows = await db
|
||||
.select({ projectId: releases.projectId, env: releases.env, host: releases.host })
|
||||
.from(releases)
|
||||
.where(and(inArray(releases.projectId, projectIds), inArray(releases.env, ["prod", "staging"]), eq(releases.status, "healthy")))
|
||||
.orderBy(desc(releases.id));
|
||||
for (const r of rows) {
|
||||
if (!r.host) continue;
|
||||
const cur = out.get(r.projectId);
|
||||
if (!cur || (!cur.live && r.env === "prod")) out.set(r.projectId, { url: `https://${r.host}`, live: r.env === "prod" });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
// PEP-77: progress of every project on the Home page — stories per board column and what is
|
||||
// in work right now (agent, tasks.md progress).
|
||||
import { productUrls } from "./product.ts";
|
||||
import { projects, tasks, users, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
|
||||
@ -31,6 +32,8 @@ export interface ProjectProgress {
|
||||
working: StoryInWork[];
|
||||
/** Stories waiting for the PM's «Принять». */
|
||||
reviewKeys: string[];
|
||||
/** PEP-111: where the product runs (prod, else the version to check), if it is deployed. */
|
||||
product: { url: string; live: boolean } | null;
|
||||
}
|
||||
|
||||
export interface ProgressOverview {
|
||||
@ -47,6 +50,7 @@ export async function progressOverview(db: Db, userId: number): Promise<Progress
|
||||
const mineIds = await userProjectIds(db, userId);
|
||||
const otherRows = await listOtherProjects(db, userId);
|
||||
const ids = [...mineIds, ...otherRows.map((p) => p.id)];
|
||||
const products = await productUrls(db, ids);
|
||||
const empty: ProgressOverview = { mine: [], others: [], totals: { backlog: 0, inProgress: 0, review: 0, done: 0, total: 0 } };
|
||||
if (!ids.length) return empty;
|
||||
const ps = await db.select({ p: projects, ownerLogin: users.login }).from(projects).leftJoin(users, eq(users.id, projects.ownerId)).where(inArray(projects.id, ids)).orderBy(asc(projects.key));
|
||||
@ -54,7 +58,7 @@ export async function progressOverview(db: Db, userId: number): Promise<Progress
|
||||
const mine = new Set(mineIds);
|
||||
const out = empty;
|
||||
for (const { p, ownerLogin } of ps) {
|
||||
const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? "без владельца"), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [] };
|
||||
const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? "без владельца"), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [], product: products.get(p.id) ?? null };
|
||||
const own = ts.filter((t) => t.projectId === p.id);
|
||||
const agentsOf = own.some((t) => column(t.status) === "inProgress") ? await taskAgentNames(db, p.id) : new Map<number, string>();
|
||||
for (const t of own) {
|
||||
|
||||
@ -33,6 +33,7 @@ import {
|
||||
type TaskRef,
|
||||
projectAgentWarning,
|
||||
intakePendingTasks,
|
||||
productUrls,
|
||||
} from "@peppa/core";
|
||||
import { goals, incidents, questions, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
@ -272,7 +273,17 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
|
||||
}
|
||||
if (!backlog.length && working.length === 0 && a.idlePush && !state.emptyNotified) {
|
||||
await setIdle(db, project.id, { ...state, emptyNotified: true });
|
||||
await askPmProject(db, project, { kind: "attention", text: `📭 ${project.name}: бэклог пуст — агентам нечего делать. Добавьте стори, и Пеппа возьмёт их сама.` });
|
||||
// PEP-111: everything asked for is done — say where the result is and what to do next.
|
||||
const product = (await productUrls(db, [project.id])).get(project.id);
|
||||
const web = process.env.PEPPA_WEB_URL ?? "";
|
||||
await askPmProject(db, project, {
|
||||
kind: "attention",
|
||||
text: [
|
||||
`📭 ${project.name}: все стори сделаны, бэклог пуст — агентам нечего делать.`,
|
||||
...(product ? [`${product.live ? "Ваш продукт" : "Версия для проверки"}: ${product.url}`] : []),
|
||||
`Что дальше: опишите следующую задачу аналитику в чате проекта (${web}/chats/${project.key}) или добавьте стори на доске — агенты возьмут её сами.`,
|
||||
].join("\n"),
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@ -122,10 +122,14 @@ async function notifyRelease(db: Db, project: Project, rel: Release) {
|
||||
await askPmProject(db, project, {
|
||||
kind: "question",
|
||||
options: [PROD_OPTION],
|
||||
text: `✅ ${project.name}: staging обновлён — ${short(rel.sha)}${tasks}${rel.host ? `\nhttps://${rel.host}` : ""}\nВыкатить этот релиз в прод?`,
|
||||
// PEP-111: said for a product manager — what it is, where to look, what the button does.
|
||||
text: `✅ ${project.name}: новая версия готова к проверке${tasks}${rel.host ? `\nПосмотреть: https://${rel.host}` : ""}\nЭто версия только для вас. Показать её всем пользователям?`,
|
||||
});
|
||||
} else if (rel.status === "healthy" && rel.env === "prod") {
|
||||
await askPmProject(db, project, { kind: "attention", text: `🚀 ${project.name} в проде: ${short(rel.sha)}${tasks}${rel.host ? `\nhttps://${rel.host}` : ""}` });
|
||||
await askPmProject(db, project, {
|
||||
kind: "attention",
|
||||
text: `🚀 ${project.name}: ваш продукт обновлён и открыт для всех${rel.host ? `\nОткрыть: https://${rel.host}` : ""}${tasks}\nЧто дальше: опишите следующую задачу аналитику в чате проекта — ${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -103,6 +103,7 @@ describe("dispatcher", () => {
|
||||
await autonomy();
|
||||
assert.equal((await taskOf(second.key)).status, "done");
|
||||
const empty = (await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст"));
|
||||
assert.match(empty[0]?.text ?? "", /Что дальше: опишите следующую задачу аналитику в чате проекта/, "PEP-111: what to do next");
|
||||
assert.equal(empty.length, 1);
|
||||
await autonomy();
|
||||
assert.equal((await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст")).length, 1, "told once");
|
||||
|
||||
@ -162,7 +162,7 @@ describe("Релиз с бэкапом и автооткатом", () => {
|
||||
assert.equal(done.id, rel.id, "the button's release row is the one completed");
|
||||
assert.equal(done.status, "healthy");
|
||||
assert.deepEqual(done.tasks, [`${pep.key}-5`]);
|
||||
assert.ok((await messages()).some((t) => t.includes(`в проде: ${rel.sha.slice(0, 7)}`)), "the PM is told");
|
||||
assert.ok((await messages()).some((t) => t.includes("ваш продукт обновлён и открыт для всех")), "the PM is told");
|
||||
// The worktree is the commit; .env is the shared one.
|
||||
assert.equal(readlinkSync(join(RELEASES, "releases", rel.sha, ".env")), join(RELEASES, "shared/.env"));
|
||||
assert.ok(existsSync(join(RELEASES, "releases", rel.sha, "apps/web/.next/BUILD_ID")));
|
||||
|
||||
69
packages/testkit/test/product.test.ts
Normal file
69
packages/testkit/test/product.test.ts
Normal file
@ -0,0 +1,69 @@
|
||||
// PEP-111: «Ваш продукт» — where the project's result lives and how releases are said to a PM.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { releases } from "@peppa/db";
|
||||
import { core, db, teardown } from "./helpers.ts";
|
||||
|
||||
after(teardown);
|
||||
let n = 0;
|
||||
const proj = async () => {
|
||||
n++;
|
||||
return core.createProject(db, { slug: `mock-prod-${n}`, key: `MPR${String.fromCharCode(64 + n)}`, name: `Продукт ${n}`, giteaOwner: "x", workspacePath: `/tmp/mock-prod-${n}` });
|
||||
};
|
||||
const rel = (projectId: number, env: "preview" | "staging" | "prod", sha: string, status: "healthy" | "removed" | "failed" = "healthy", tasks: string[] = []) =>
|
||||
db.insert(releases).values({ projectId, env, sha, status, host: `${env}.mock.test`, tasks }).returning().then((r) => r[0]!);
|
||||
|
||||
describe("PEP-111: the project's product", () => {
|
||||
test("nothing deployed: no versions, only the count of accepted stories", async () => {
|
||||
const p = await proj();
|
||||
const t = await core.createTask(db, { projectId: p.id, title: "Первая" });
|
||||
assert.deepEqual(await core.projectProduct(db, p.id), { live: null, check: null, doneStories: 0 });
|
||||
await core.updateTask(db, t, { status: "done" });
|
||||
assert.equal((await core.projectProduct(db, p.id)).doneStories, 1);
|
||||
assert.equal((await core.productUrls(db, [p.id])).size, 0);
|
||||
});
|
||||
|
||||
test("staging only → the version to check; prod → the working product; a newer staging is offered again", async () => {
|
||||
const p = await proj();
|
||||
await rel(p.id, "preview", "aaa1111", "removed");
|
||||
await rel(p.id, "staging", "bbb2222", "healthy", ["X-1"]);
|
||||
let v = await core.projectProduct(db, p.id);
|
||||
assert.equal(v.live, null);
|
||||
assert.equal(v.check?.url, "https://staging.mock.test");
|
||||
assert.deepEqual((await core.productUrls(db, [p.id])).get(p.id), { url: "https://staging.mock.test", live: false });
|
||||
|
||||
await rel(p.id, "prod", "bbb2222", "healthy", ["X-1"]);
|
||||
v = await core.projectProduct(db, p.id);
|
||||
assert.equal(v.live?.url, "https://prod.mock.test");
|
||||
assert.deepEqual(v.live?.stories, ["X-1"]);
|
||||
assert.equal(v.check, null, "the same commit is already live");
|
||||
assert.deepEqual((await core.productUrls(db, [p.id])).get(p.id), { url: "https://prod.mock.test", live: true });
|
||||
|
||||
await rel(p.id, "staging", "ccc3333", "healthy", ["X-2"]);
|
||||
v = await core.projectProduct(db, p.id);
|
||||
assert.equal(v.live?.url, "https://prod.mock.test");
|
||||
assert.deepEqual(v.check?.stories, ["X-2"], "a newer version waits to be shown to everyone");
|
||||
});
|
||||
|
||||
test("the chat says releases in plain words and keeps the draft stands out", async () => {
|
||||
const p = await proj();
|
||||
await rel(p.id, "preview", "ddd4444", "healthy");
|
||||
await rel(p.id, "preview", "ddd4445", "removed");
|
||||
await rel(p.id, "preview", "ddd4446", "failed");
|
||||
await rel(p.id, "staging", "eee5555", "healthy", ["Y-1"]);
|
||||
await rel(p.id, "prod", "eee5555", "healthy", ["Y-1"]);
|
||||
await core.syncChats(db);
|
||||
const chat = await core.ensureProjectChat(db, p.id);
|
||||
const texts = (await core.chatMessagesView(db, chat.id, {})).map((m) => m.text);
|
||||
assert.deepEqual(texts, ["❌ Черновой стенд стори: не выкатилась", "🚀 Версия для проверки: работает · стори: Y-1", "🚀 Рабочая версия продукта: работает · стори: Y-1"]);
|
||||
assert.ok(texts.every((t) => !/[0-9a-f]{7}/.test(t)), "no commit hashes for a product manager");
|
||||
});
|
||||
|
||||
test("the Home page carries the product link of each project", async () => {
|
||||
const owner = await core.registerEgovUser(db, { iin: "880808400011", name: "ПРОДАКТ ТЕСТОВЫЙ" });
|
||||
const p = await core.createProject(db, { slug: "mock-prod-home", key: "MPRH", name: "Домой", giteaOwner: "x", workspacePath: "/tmp/mock-prod-home", ownerId: owner.id });
|
||||
await rel(p.id, "prod", "fff6666");
|
||||
const o = await core.progressOverview(db, owner.id);
|
||||
assert.deepEqual(o.mine.find((x) => x.key === "MPRH")?.product, { url: "https://prod.mock.test", live: true });
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user