peppa/apps/web/app/(app)/team/actions.ts
2026-11-15 14:47:50 +05:00

47 lines
1.7 KiB
TypeScript

"use server";
import { createAgent, isSuperadmin, PeppaError, updateAgent } from "@peppa/core";
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";
/** PEP-75: the team is platform-wide, so only a superadmin changes it. */
async function run(fn: () => Promise<string | void>): Promise<never> {
let target = "/team";
try {
const user = asWebActor(await requireUser());
if (!(await isSuperadmin(db, user))) throw new PeppaError(m("Команду меняет только суперадмин"));
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 });
target = `/team?error=${encodeURIComponent(msg.slice(0, 300))}`;
}
revalidatePath("/", "layout");
redirect(target);
}
export async function addAgentAction(f: FormData) {
await run(async () => {
const a = await createAgent(db, { name: String(f.get("name") ?? "") });
return `/team?saved=${a.id}#agent-${a.id}`;
});
}
export async function saveAgentAction(f: FormData) {
await run(async () => {
const id = Number(f.get("id"));
await updateAgent(db, id, { name: String(f.get("name") ?? ""), character: String(f.get("character") ?? "") });
return `/team?saved=${id}#agent-${id}`;
});
}
export async function toggleAgentAction(f: FormData) {
await run(async () => {
await updateAgent(db, Number(f.get("id")), { disabled: f.get("disabled") === "1" });
});
}