peppa/apps/web/app/(app)/subscriptions/actions.ts
Асель 2ef05fac12 PEP-107: failover across providers, pool view, last-subscription warning, superadmin loans
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:40:06 +05:00

140 lines
5.3 KiB
TypeScript

"use server";
// «Подписки» (PEP-67): every action is superadmin-only (others get "not found").
import { createPool, deletePool, getProject, lendSubscription, PeppaError, returnLoanNow, requireSuperadmin, setProjectPool, updatePool, updateSubscription, type SubscriptionProvider } from "@peppa/core";
import { addSubscription, 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";
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 msg = e instanceof PeppaError ? e.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("Неизвестный провайдер");
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}`;
});
}
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"));
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("Нужно название подписки");
await updateSubscription(db, Number(str(f, "id")), { name: str(f, "name") });
});
}
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`;
});
}