peppa/packages/core/src/onboarding.ts
Асель 80a3bb79ad PEP-97: the name users see is «Peppa FACTORY» everywhere
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:34:03 +05:00

175 lines
9.2 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-31: first-run checklist on the home page and the "agents won't start" project warning.
import { projects, sessions, subscriptions, tasks, users, type Db } from "@peppa/db";
import { and, count, eq, inArray, isNotNull } from "drizzle-orm";
import { mayUseMachineLogin } from "./access.ts";
import { isSuperadmin } from "./monitor.ts";
import { getSetting, setSetting } from "./settings.ts";
import { isUsable, poolSubscriptions } from "./subscriptions.ts";
import { userProjectIds, type User } from "./users.ts";
export type OnboardingStepId = "subscription" | "telegram" | "project" | "story" | "started" | "accepted";
export interface OnboardingStep {
id: OnboardingStepId;
title: string;
hint: string;
/** Button label of the step while it is the current one (PEP-83). */
action: string;
href: string;
done: boolean;
optional: boolean;
}
export interface Onboarding {
steps: OnboardingStep[];
/** Required steps done / total. */
done: number;
total: number;
/** All required steps done. */
complete: boolean;
dismissed: boolean;
/** Shown on the home page. */
visible: boolean;
}
const dismissedKey = (userId: number) => `onboarding.dismissed:${userId}`;
export async function dismissOnboarding(db: Db, userId: number): Promise<void> {
await setSetting(db, dismissedKey(userId), { at: new Date().toISOString() });
}
const welcomeKey = (userId: number) => `welcome.shown:${userId}`;
const WELCOME_EVERYONE = "welcome.everyone_after";
/**
* PEP-92: the welcome page opens by itself once — for a user with no projects who has not seen
* it yet. PEP-95: after «выкинуть всех» (`showWelcomeToEveryone`) it opens once for everyone.
*/
export async function claimWelcome(db: Db, userId: number, now = new Date()): Promise<boolean> {
const shown = await getSetting<{ at: string }>(db, welcomeKey(userId));
const everyone = await getSetting<number>(db, WELCOME_EVERYONE);
const owedToAll = typeof everyone === "number" && (!shown || Date.parse(shown.at) < everyone);
if (shown && !owedToAll) return false;
await setSetting(db, welcomeKey(userId), { at: now.toISOString() });
return owedToAll || (await userProjectIds(db, userId)).length === 0;
}
/** PEP-95: everyone sees the welcome page once more, at their next visit of Home. */
export async function showWelcomeToEveryone(db: Db, now = new Date()): Promise<void> {
await setSetting(db, WELCOME_EVERYONE, now.getTime());
}
export async function onboardingChecklist(db: Db, user: Pick<User, "id" | "login">): Promise<Onboarding> {
const [me] = await db.select({ chat: users.telegramChatId, iin: users.egovIin }).from(users).where(eq(users.id, user.id));
const admin = await isSuperadmin(db, user);
const ids = await userProjectIds(db, user.id);
const n = async (q: Promise<Array<{ n: number }>>) => (await q)[0]?.n ?? 0;
const storyCount = ids.length ? await n(db.select({ n: count() }).from(tasks).where(inArray(tasks.projectId, ids))) : 0;
const started = ids.length ? await n(db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), isNotNull(sessions.taskId)))) : 0;
const firstKey = ids.length ? (await db.select({ key: projects.key }).from(projects).where(inArray(projects.id, ids)).limit(1))[0]?.key : undefined;
const accepted = ids.length ? await n(db.select({ n: count() }).from(tasks).where(and(inArray(tasks.projectId, ids), eq(tasks.status, "done")))) : 0;
const projectHref = firstKey ? `/p/${firstKey}` : "/projects/new";
// PEP-83: written for a product manager, not a programmer — what to do and why, in order.
const telegram: OnboardingStep = {
id: "telegram",
title: "Подключите своего Telegram-бота",
hint: "Через него фабрика позовёт вас, когда агенту нужен ответ или когда работа готова. Бота создают в самом Telegram у @BotFather: команда /newbot, имя, адрес на …bot — и вставить токен сюда. Пошагово — ниже.",
action: "Подключить Telegram",
href: "/settings#telegram",
done: me?.chat != null,
optional: false,
};
const project: OnboardingStep = {
id: "project",
title: "Создайте проект",
hint: "Проект — один продукт: сайт, бот, сервис. Нужны только название и короткий код, например SHOP.",
action: "Создать проект",
href: "/projects/new",
done: ids.length > 0,
optional: false,
};
let subscription: OnboardingStep;
if (admin) {
const subs = await db.select({ status: subscriptions.status, limitedUntil: subscriptions.limitedUntil }).from(subscriptions);
subscription = {
id: "subscription",
title: "Подключите подписку агента",
hint: "Claude, Codex или OpenCode — на ней работают агенты; добавьте её в пул проекта.",
action: "Открыть подписки",
href: "/subscriptions",
done: subs.some((s) => s.status === "active" || s.status === "limited"),
optional: false,
};
} else {
let ready = false;
for (const id of ids) if (!(await projectAgentWarning(db, id))) ready = true;
subscription = {
id: "subscription",
title: "Подключите свою подписку Claude или ChatGPT",
hint: "На ней агенты пишут код. Подойдёт обычная платная подписка; подключение — одна минута, кнопка на странице проекта.",
action: "Подключить подписку",
href: projectHref,
done: ready,
optional: false,
};
}
const rest: OnboardingStep[] = [
{
id: "story",
title: "Опишите первую задачу",
hint: "Кнопка «+ Стори» в проекте. Напишите обычными словами, что должно получиться, — как объяснили бы человеку.",
action: "Написать задачу",
href: projectHref,
done: storyCount > 0,
optional: false,
},
{
id: "started",
title: "Агент берёт задачу в работу",
hint: "В новом проекте это происходит само за минуту; на карточке появятся имя агента и прогресс. Ничего перетаскивать не нужно.",
action: "Открыть доску",
href: projectHref,
done: started > 0,
optional: false,
},
{
id: "accepted",
title: "Посмотрите результат и нажмите «Принять»",
hint: "Когда агент закончит, придёт сообщение, а карточка перейдёт в «Ревью». Что-то не так — напишите комментарий, агент переделает.",
action: "Открыть доску",
href: projectHref,
done: accepted > 0,
optional: false,
},
];
const steps: OnboardingStep[] = admin ? [subscription, telegram, project, ...rest] : [telegram, project, subscription, ...rest];
const required = steps.filter((s) => !s.optional);
const done = required.filter((s) => s.done).length;
const complete = done === required.length;
const dismissed = !!(await getSetting(db, dismissedKey(user.id)));
return { steps, done, total: required.length, complete, dismissed, visible: !complete && !dismissed };
}
const STATUS_RU: Record<string, string> = { pending: "не подключена", limited: "в лимите", auth_error: "ошибка входа", active: "активна" };
/**
* Why agents of the project won't start, or null: the project's pool has no working
* subscription. Without a pool the runner uses this machine's login (not checked here).
*/
export async function projectAgentWarning(db: Db, projectId: number, now = new Date()): Promise<string | null> {
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId));
if (p?.poolId == null) {
// PEP-71/76: a self-registered owner has no machine login — a subscription must be chosen.
const [o] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId));
return (await mayUseMachineLogin(db, o?.ownerId ?? null)) ? null : "подписка не подключена — владелец подключает свою (Claude или ChatGPT) в «⋯ Настройки проекта → Подписки»";
}
const subs = await poolSubscriptions(db, p.poolId);
if (!subs.length) return "в пуле подписок проекта нет ни одной подписки";
if (subs.some((s) => isUsable(s, now))) return null;
const why = subs.map((s) => `«${s.name}» — ${STATUS_RU[s.status] ?? s.status}${s.status === "limited" && s.limitedUntil ? ` до ${s.limitedUntil.toLocaleString("ru-RU", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit" })}` : ""}`);
return `нет рабочей подписки в пуле проекта: ${why.join(", ")}`;
}