peppa/packages/core/src/product-link.ts

109 lines
6.6 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.

// PEP-145: the product of a project always opens by a link. Here: the «Показывать всем»
// setting (auto / by the button), the state of the system story «Продукт должен открываться
// по ссылке» that Peppa files itself, and its text. The watchdog side is runner/product-link.ts.
import { m as tr } from "@peppa/shared/i18n";
import { tasks, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
/** "auto": a healthy version to check whose stories are all accepted goes to everyone by itself. */
export type PublishMode = "auto" | "button";
export const PUBLISH_MODES: readonly PublishMode[] = ["auto", "button"];
/** What a newly created project starts with (existing ones keep «по кнопке» until the owner chooses). */
export const NEW_PROJECT_PUBLISH: PublishMode = "auto";
export const PUBLISH_MODE_RU: Record<PublishMode, string> = {
auto: tr("Сам"),
button: tr("По кнопке"),
};
export const PUBLISH_MODE_HINT: Record<PublishMode, string> = {
auto: tr("Когда все задачи новой версии приняты, Peppa FACTORY сама показывает её всем пользователям."),
button: tr("Новую версию сначала видите только вы; всем она открывается по кнопке «Показать всем»."),
};
/** Options of the one-time offer to an existing project. */
export const PUBLISH_AUTO_OPTION = tr("Показывать сразу");
export const PUBLISH_BUTTON_OPTION = tr("Оставить по кнопке");
const modeKey = (projectId: number) => `product.publish:${projectId}`;
/** The chosen mode; null — nobody chose yet (behaves as "button"). */
export async function getPublishChoice(db: Db, projectId: number): Promise<PublishMode | null> {
const v = await getSetting<string>(db, modeKey(projectId));
return v === "auto" || v === "button" ? v : null;
}
export async function getPublishMode(db: Db, projectId: number): Promise<PublishMode> {
return (await getPublishChoice(db, projectId)) ?? "button";
}
export async function setPublishMode(db: Db, projectId: number, mode: PublishMode): Promise<PublishMode> {
if (!PUBLISH_MODES.includes(mode)) throw new PeppaError(tr("Показывать всем: выберите «Сам» или «По кнопке»."));
await setSetting(db, modeKey(projectId), mode);
return mode;
}
/** The system story Peppa filed last for a project and when. */
export interface ProductLinkState {
taskId: number;
at: number;
}
const linkKey = (projectId: number) => `product.link:${projectId}`;
export const getProductLinkState = (db: Db, projectId: number) => getSetting<ProductLinkState>(db, linkKey(projectId));
export async function setProductLinkState(db: Db, projectId: number, state: ProductLinkState | null): Promise<void> {
if (state) await setSetting(db, linkKey(projectId), state);
else await deleteSetting(db, linkKey(projectId));
}
/** The open system story of a project (not accepted, not archived), if any. */
export async function openProductLinkTask(db: Db, projectId: number): Promise<{ id: number; number: number; status: string } | null> {
const state = await getProductLinkState(db, projectId);
if (!state) return null;
const [t] = await db.select({ id: tasks.id, number: tasks.number, status: tasks.status, archivedAt: tasks.archivedAt, projectId: tasks.projectId }).from(tasks).where(eq(tasks.id, state.taskId));
if (!t || t.projectId !== projectId || t.archivedAt || t.status === "done") return null;
return { id: t.id, number: t.number, status: t.status };
}
// glossary-user: название и описание задачи читает владелец проекта
export const PRODUCT_LINK_TITLE = "Продукт должен открываться по ссылке";
export interface ProductLinkProblem {
/** Accepted stories of the project. */
doneStories: number;
/** The last finished update of the version to check, when it did not come up. */
failed?: { status: string; sha: string; reason: string | null; logTail: string | null; runUrl: string | null } | null;
}
/** The story text: what happened in plain words, then what the agent has to do. */
export function productLinkDescription(p: ProductLinkProblem): string {
const what = p.failed
? // glossary-user: описание задачи читает владелец проекта
`Последнее обновление версии для проверки не запустилось${p.failed.status === "rolled_back" ? " — возвращена прежняя версия" : ""}, поэтому новые изменения нельзя открыть и посмотреть.`
: // glossary-user: описание задачи читает владелец проекта
`В проекте принято задач: ${p.doneStories}, но продукт не открывается по ссылке — посмотреть результат негде.`;
const lines = [
"## Зачем",
what,
"",
"## Что сделать",
"Продукт открывается по ссылке версии для проверки и показывает результат принятых задач. Вопросов владельцу не задавать: это техническая задача, её заводит сама Peppa FACTORY.",
"",
"## Условия готовности",
"- Обновление версии для проверки проходит, ссылка открывается.",
"- На странице виден продукт; у продукта без сайта — страница продукта: что это, как пользоваться, как проверить.",
"",
"## Для агента",
"- Правила: разделы «Завершение» и «CD: деплой». Нужны `Dockerfile`, `deploy/compose.yml`, `deploy` в `.peppa/project.json`; приложение слушает `$PORT` и отвечает 200 на `GET /healthz`.",
"- Проверь локально: `docker build .`, запуск образа с `PORT=3000`, `curl /healthz`.",
];
if (p.failed) {
lines.push(`- Коммит: ${p.failed.sha.slice(0, 12)}; причина: ${p.failed.reason ?? "неизвестна"}${p.failed.runUrl ? `; запуск: ${p.failed.runUrl}` : ""}.`);
if (p.failed.logTail) lines.push("", "### Журнал сбоя", "```", p.failed.logTail.split("\n").slice(-60).join("\n").slice(-4000), "```");
}
return lines.join("\n");
}