peppa/apps/web/app/(app)/subscriptions/actions.ts
peppa-bot 0097cb07f7 PEP-182: не больше 9 агентов на подписку — ёмкость, очередь задач, «Делается · В очереди»
Ёмкость подписки (core/capacity.ts, по умолчанию 9, суперадмин меняет на набор 1–20);
pickSubscription, ротация и ручной перевод агентов уважают ёмкость; без места задача
ждёт в очереди и запускается сама по порядку доски (capacityQueueTick); команда растёт
только в пределах ёмкости; экраны «Подписки», Главная, доска, страница задачи; ru/kk/en;
тест subscription-capacity.test.ts; OpenSpec change archived.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:55:40 +05:00

175 lines
6.9 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.

"use server";
// «Подписки» (PEP-67): every action is superadmin-only (others get "not found").
import { createPool, setPoolCapacity, deletePool, getProject, lendSubscription, PeppaError, returnLoanNow, requireSuperadmin, setProjectPool, updatePool, updateSubscription, type SubscriptionProvider, setSubscriptionAccount } from "@peppa/core";
import { addPoolSubscription, addSubscription, switchAgents, cancelLogin, checkSubscription, finishClaudeLogin, removeSubscription, startClaudeLogin, startCodexLogin } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { m } from "@peppa/shared/i18n";
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
const ids = (f: FormData, k: string) => f.getAll(k).map(Number).filter((n) => Number.isInteger(n) && n > 0);
const BASE = "/subscriptions";
/** Runs a superadmin action; errors come back as ?error=… (redirect stays outside try). */
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
const user = asWebActor(await requireUser());
let target = str(f, "back") || BASE;
try {
await requireSuperadmin(db, user);
target = (await fn()) || target;
} catch (e) {
const t = await getT();
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { 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);
}
export async function addSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const provider = str(f, "provider") as SubscriptionProvider;
if (!["claude", "codex", "opencode"].includes(provider)) throw new PeppaError(m("Неизвестный провайдер"));
const s = await addSubscription(db, {
provider,
name: str(f, "name"),
method: str(f, "method"),
secret: str(f, "secret") || undefined,
keyProvider: str(f, "keyProvider") || undefined,
createdBy: user.id,
});
return s.status === "pending" ? `${BASE}?login=${s.id}#s-${s.id}` : `${BASE}?added=${s.id}#s-${s.id}`;
});
}
/** PEP-164: one more Claude / ChatGPT straight into a pool, sign-in starts at once. */
export async function addPoolSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const provider = str(f, "provider") === "codex" ? "codex" : "claude";
const s = await addPoolSubscription(db, { poolId: Number(str(f, "poolId")), provider, createdBy: user.id });
return `${BASE}?login=${s.id}#s-${s.id}`;
});
}
/** PEP-176: the superadmin moves the agents off a subscription by hand. */
export async function switchAgentsAction(f: FormData) {
await attempt(f, async () => {
const fromId = Number(str(f, "fromId"));
const to = str(f, "toId");
const r = await switchAgents(db, { fromId, toId: to ? Number(to) : null });
return `${BASE}?switched=${r.moved}&left=${r.skipped}#s-${fromId}`;
});
}
export async function reconnectSubscription(f: FormData) {
await attempt(f, async () => {
const id = Number(str(f, "id"));
if (str(f, "provider") === "codex") await startCodexLogin(db, id);
else await startClaudeLogin(db, id);
return `${BASE}?login=${id}#s-${id}`;
});
}
export async function submitLoginCode(f: FormData) {
await attempt(f, async () => {
const id = Number(str(f, "id"));
await finishClaudeLogin(db, id, str(f, "code"), str(f, "account"));
return `${BASE}?added=${id}#s-${id}`;
});
}
export async function cancelLoginAction(f: FormData) {
await attempt(f, async () => {
await cancelLogin(db, Number(str(f, "id")));
});
}
export async function checkSubscriptionAction(f: FormData) {
await attempt(f, async () => {
const id = Number(str(f, "id"));
await checkSubscription(db, id);
return `${BASE}#s-${id}`;
});
}
export async function renameSubscription(f: FormData) {
await attempt(f, async () => {
if (!str(f, "name")) throw new PeppaError(m("Нужно название подписки"));
await updateSubscription(db, Number(str(f, "id")), { name: str(f, "name") });
// PEP-178: which account it is — the e-mail the person signed in with.
if (f.has("account")) await setSubscriptionAccount(db, Number(str(f, "id")), str(f, "account"));
});
}
export async function deleteSubscriptionAction(f: FormData) {
await attempt(f, async () => {
await removeSubscription(db, Number(str(f, "id")));
});
}
export async function createPoolAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await createPool(db, { name: str(f, "name"), subscriptionIds: ids(f, "subscription"), createdBy: user.id });
return `${BASE}#pools`;
});
}
export async function updatePoolAction(f: FormData) {
await attempt(f, async () => {
await updatePool(db, Number(str(f, "id")), { name: str(f, "name") || undefined, subscriptionIds: ids(f, "subscription") });
return `${BASE}#pools`;
});
}
export async function deletePoolAction(f: FormData) {
await attempt(f, async () => {
await deletePool(db, Number(str(f, "id")));
return `${BASE}#pools`;
});
}
/** «⋯ Настройки проекта» → пул по умолчанию (only a superadmin changes it). */
export async function setProjectPoolAction(f: FormData) {
await attempt(f, async () => {
const p = await getProject(db, str(f, "projectKey"));
await setProjectPool(db, p.id, str(f, "poolId") ? Number(str(f, "poolId")) : null);
});
}
// ── PEP-107: lending a spare subscription to someone's pool ─────────────────────────
export async function lendSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await lendSubscription(db, user, { subscriptionId: Number(str(f, "subscriptionId")), poolId: Number(str(f, "poolId")), hours: Number(str(f, "hours")) });
return `${BASE}#overview`;
});
}
export async function returnLoanAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await returnLoanNow(db, user, Number(str(f, "poolId")), Number(str(f, "subscriptionId")));
return `${BASE}#overview`;
});
}
/** PEP-182: «Агентов на подписку» of a set (1–20), works from the next start on. */
export async function setPoolCapacityAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const id = Number(str(f, "poolId"));
await setPoolCapacity(db, user, id, Number(str(f, "capacity")));
return `${BASE}#pool-${id}`;
});
}