466 lines
19 KiB
TypeScript
466 lines
19 KiB
TypeScript
"use server";
|
||
|
||
import {
|
||
setAutonomy,
|
||
type AutonomyLevel,
|
||
type AutonomySettings,
|
||
linkEgovIin,
|
||
createEpic,
|
||
createTask,
|
||
updateEpic,
|
||
getQuestion,
|
||
getSession,
|
||
PeppaError,
|
||
projectForUser,
|
||
resolveTask,
|
||
revokeApp,
|
||
createPairingCode,
|
||
getSetting,
|
||
unpairTelegram,
|
||
getIncident,
|
||
getProject as getProjectByKey,
|
||
updateIncidentSettings,
|
||
setReviewSettings,
|
||
type IncidentPolicy,
|
||
changeOwnPassword,
|
||
createLocalUser,
|
||
getUser,
|
||
isLocalUser,
|
||
isSuperadmin,
|
||
setUserDisabled,
|
||
setUserPassword,
|
||
NOTIFY_EVENTS,
|
||
defaultPrefs,
|
||
deletePushSubscription,
|
||
getNotifyPrefs,
|
||
isValidTimezone,
|
||
savePushSubscription,
|
||
sendWebPush,
|
||
setNotifyPrefs,
|
||
userPushSubscriptions,
|
||
} from "@peppa/core";
|
||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||
import { loadEnv } from "@peppa/shared";
|
||
import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner";
|
||
import { revalidatePath } from "next/cache";
|
||
import { redirect } from "next/navigation";
|
||
import { requireUser } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
|
||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||
const back = (f: FormData) => str(f, "back") || "/";
|
||
|
||
/** Runs an action; errors come back to the page as ?error=… (redirect must stay outside try). */
|
||
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
||
let target = back(f);
|
||
try {
|
||
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);
|
||
}
|
||
|
||
async function ownedSession(userId: number, sessionId: number) {
|
||
const s = await getSession(db, sessionId);
|
||
await projectForUser(db, userId, s.projectId);
|
||
return s;
|
||
}
|
||
|
||
export async function answerQuestion(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const q = await getQuestion(db, Number(str(f, "questionId")));
|
||
await projectForUser(db, user.id, q.projectId);
|
||
const answer = str(f, "choice") || str(f, "answer");
|
||
if (!answer) throw new PeppaError("Пустой ответ");
|
||
if (q.answeredAt) throw new PeppaError(`Уже отвечено${q.answeredVia === "system" ? "" : ` (${q.answeredVia})`}: ${q.answer}`);
|
||
if (answer === "__accept") {
|
||
await acceptTask(db, q.id, "web");
|
||
return;
|
||
}
|
||
await answerAndDeliver(db, q.id, answer, "web");
|
||
});
|
||
}
|
||
|
||
export async function addTask(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
if (!str(f, "title")) throw new PeppaError("Нужно название стори");
|
||
const epic = Number(str(f, "epicId")) || undefined;
|
||
const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic });
|
||
return `/t/${ref.key}`;
|
||
});
|
||
}
|
||
|
||
/** Epics (PEP-66): labels that group stories; stored in the goals table. */
|
||
export async function addEpic(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
|
||
await createEpic(db, p.id, str(f, "title"), str(f, "description") || undefined);
|
||
});
|
||
}
|
||
|
||
export async function editEpic(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
const id = Number(str(f, "epicId"));
|
||
if (str(f, "archive")) {
|
||
await updateEpic(db, p.id, id, { status: "archived" });
|
||
return;
|
||
}
|
||
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
|
||
await updateEpic(db, p.id, id, { title: str(f, "title"), description: str(f, "description") || null });
|
||
});
|
||
}
|
||
|
||
export async function startTaskSession(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||
await projectForUser(db, user.id, ref.project.id);
|
||
// PEP-67: a superadmin may pick a pool or tick subscriptions; otherwise the project's pool.
|
||
const choice = (await isSuperadmin(db, user)) ? str(f, "choice") : "";
|
||
const subscriptionIds = choice === "pick" ? f.getAll("subscription").map(Number).filter((n) => n > 0) : undefined;
|
||
if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError("Отметьте хотя бы одну подписку");
|
||
const poolId = choice.startsWith("pool:") ? Number(choice.slice(5)) : undefined;
|
||
const provider = str(f, "provider") as Provider | "";
|
||
await startSession(db, ref.key, { provider: provider || undefined, subscriptionIds, poolId, prompt: str(f, "prompt") || undefined });
|
||
});
|
||
}
|
||
|
||
export async function stopTaskSession(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||
await stopSession(db, s.id);
|
||
});
|
||
}
|
||
|
||
export async function resumeTaskSession(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||
await resumeSession(db, s.id);
|
||
});
|
||
}
|
||
|
||
export async function messageSession(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||
if (!str(f, "text")) throw new PeppaError("Пустое сообщение");
|
||
await sendToSession(db, s.id, str(f, "text"));
|
||
});
|
||
}
|
||
|
||
export async function createProjectAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await provisionProject(db, {
|
||
...(await projectNamespace(db, user, str(f, "owner"))), // PEP-68: local user → peppa-bot
|
||
slug: str(f, "slug").toLowerCase(),
|
||
key: str(f, "key"),
|
||
name: str(f, "name"),
|
||
existing: str(f, "mode") === "existing",
|
||
visibility: str(f, "visibility") === "private" ? "private" : "public",
|
||
ownerId: user.id,
|
||
});
|
||
return `/p/${p.key}?created=1`;
|
||
});
|
||
}
|
||
|
||
export async function deployProdAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, (await getProjectByKey(db, str(f, "projectKey"))).id);
|
||
await deployProd(db, p, user.login);
|
||
});
|
||
}
|
||
|
||
export async function moveTaskCard(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||
await projectForUser(db, user.id, ref.project.id);
|
||
const to = str(f, "to") as BoardColumn;
|
||
if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError("Неизвестная колонка");
|
||
await moveTask(db, ref, to);
|
||
});
|
||
}
|
||
|
||
export async function revokeConnectedApp(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
await revokeApp(db, user.id, str(f, "clientId"));
|
||
});
|
||
}
|
||
|
||
export async function unlinkEgov(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
await linkEgovIin(db, user.id, null);
|
||
});
|
||
}
|
||
|
||
export async function addProjectMember(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
const r = await shareProject(db, user, p, str(f, "login"));
|
||
if (!r.repoAccess) throw new PeppaError(`${r.login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную`);
|
||
});
|
||
}
|
||
|
||
export async function grantRepoAccessToMembers(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
const r = await grantRepoAccess(db, user, p);
|
||
if (r.failed.length) throw new PeppaError(`Не удалось выдать доступ к репозиторию: ${r.failed.join(", ")} — нет прав администратора в Gitea, добавьте соавторов вручную`);
|
||
});
|
||
}
|
||
|
||
export async function setProjectVisibilityAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
await setProjectVisibility(db, p, str(f, "visibility") === "private" ? "private" : "public", { actor: user });
|
||
});
|
||
}
|
||
|
||
/** PEP-23: project autonomy — a preset level, or the individual settings (owner or member). */
|
||
export async function setAutonomyAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
const level = str(f, "level");
|
||
if (level) {
|
||
await setAutonomy(db, p.id, { level: level as AutonomyLevel });
|
||
return;
|
||
}
|
||
const hour = (k: string) => (str(f, k) === "" ? null : Number(str(f, k)));
|
||
const quiet = f.get("quiet") === "on";
|
||
await setAutonomy(db, p.id, {
|
||
pick: str(f, "pick") as AutonomySettings["pick"],
|
||
wipLimit: Number(str(f, "wipLimit")),
|
||
proposal: str(f, "proposal") as AutonomySettings["proposal"],
|
||
merge: str(f, "merge") as AutonomySettings["merge"],
|
||
close: str(f, "close") as AutonomySettings["close"],
|
||
closeAfterHours: Number(str(f, "closeAfterHours")),
|
||
idlePush: f.get("idlePush") === "on",
|
||
idlePushHours: Number(str(f, "idlePushHours")),
|
||
quietFrom: quiet ? hour("quietFrom") : null,
|
||
quietTo: quiet ? hour("quietTo") : null,
|
||
});
|
||
});
|
||
}
|
||
|
||
export async function removeProjectMember(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
const login = str(f, "login");
|
||
await unshareProject(db, user, p, login);
|
||
// Left the project myself: its page is gone for me.
|
||
if (login.toLowerCase() === user.login.toLowerCase()) return "/";
|
||
});
|
||
}
|
||
|
||
export async function pairTelegram(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||
const bot = await getSetting<{ username: string }>(db, "telegram.bot");
|
||
if (!token || !bot) throw new PeppaError("Telegram-бот Пеппы не запущен");
|
||
return `https://t.me/${bot.username}?start=${await createPairingCode(db, token, user.id)}`;
|
||
});
|
||
}
|
||
|
||
export async function unpairTelegramAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
await unpairTelegram(db, user.id);
|
||
});
|
||
}
|
||
|
||
// ── notifications (PEP-35, PEP-55) ──────────────────────────────────────────────
|
||
|
||
/** «Настройки → Уведомления»: events × channels, quiet hours, timezone, digest, sound, projects. */
|
||
export async function saveNotifyPrefsAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const cur = await getNotifyPrefs(db, user.id);
|
||
const d = defaultPrefs();
|
||
const events = { ...d.events };
|
||
for (const e of NOTIFY_EVENTS) events[e] = { telegram: f.get(`${e}.telegram`) === "on", push: f.get(`${e}.push`) === "on" };
|
||
const tz = str(f, "timezone") || cur.timezone;
|
||
if (!isValidTimezone(tz)) throw new PeppaError(`Неизвестная таймзона: ${tz}`);
|
||
const shown = f.getAll("projectShown").map(Number);
|
||
const enabled = new Set(f.getAll("project").map(Number));
|
||
// Projects not on the form (no access any more) keep their old state.
|
||
const muted = [...cur.mutedProjects.filter((id) => !shown.includes(id)), ...shown.filter((id) => !enabled.has(id))];
|
||
try {
|
||
await setNotifyPrefs(db, user.id, {
|
||
events,
|
||
quiet: f.get("quietOn") === "on" ? { from: str(f, "quietFrom"), to: str(f, "quietTo") } : null,
|
||
timezone: tz,
|
||
digestTime: str(f, "digestTime") || cur.digestTime,
|
||
sound: f.get("sound") === "on",
|
||
mutedProjects: muted,
|
||
});
|
||
} catch (e) {
|
||
throw new PeppaError((e as Error).message);
|
||
}
|
||
return "/settings?notify=saved#notifications";
|
||
});
|
||
}
|
||
|
||
/** The browser subscribed to Web Push (called from the client with PushSubscription.toJSON()). */
|
||
export async function savePushSubscriptionAction(sub: { endpoint: string; keys: { p256dh: string; auth: string } }, userAgent: string | null) {
|
||
const user = await requireUser();
|
||
await savePushSubscription(db, user.id, { ...sub, userAgent });
|
||
revalidatePath("/settings");
|
||
return { ok: true };
|
||
}
|
||
|
||
export async function deletePushSubscriptionAction(endpoint: string) {
|
||
const user = await requireUser();
|
||
await deletePushSubscription(db, user.id, endpoint);
|
||
revalidatePath("/settings");
|
||
return { ok: true };
|
||
}
|
||
|
||
/** Test notification to this browser, sent right away (doesn't depend on the bot). */
|
||
export async function testPushAction(endpoint: string): Promise<{ ok: boolean; error?: string }> {
|
||
const user = await requireUser();
|
||
const sub = (await userPushSubscriptions(db, user.id)).find((s) => s.endpoint === endpoint);
|
||
if (!sub) return { ok: false, error: "Этот браузер не подписан" };
|
||
const prefs = await getNotifyPrefs(db, user.id);
|
||
const r = await sendWebPush(db, sub, { title: "Пеппа", body: "Уведомления в этом браузере работают ✅", url: "/settings#notifications", tag: "test", sound: prefs.sound });
|
||
if (r.ok) return { ok: true };
|
||
if (r.gone) await deletePushSubscription(db, user.id, endpoint);
|
||
return { ok: false, error: r.error };
|
||
}
|
||
|
||
// ── errors from running products (PEP-58) ───────────────────────────────────────
|
||
|
||
async function incidentInProject(userId: number, f: FormData) {
|
||
const p = await projectForUser(db, userId, Number(str(f, "projectId")));
|
||
const i = await getIncident(db, Number(str(f, "incidentId")));
|
||
if (i.projectId !== p.id) throw new PeppaError("Не найдено");
|
||
return i;
|
||
}
|
||
|
||
export async function connectErrorTrackingAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
if (p.ownerId !== user.id) throw new PeppaError("Подключает владелец проекта");
|
||
await connectErrorTracking(db, p, bugsinkFromEnv(), bugsinkWebhookBase());
|
||
});
|
||
}
|
||
|
||
export async function saveIncidentSettings(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
await updateIncidentSettings(db, p.id, {
|
||
policy: str(f, "policy") as IncidentPolicy,
|
||
triagePrompt: str(f, "triagePrompt") || null,
|
||
environments: str(f, "environments").split(","),
|
||
dailyLimit: Number(str(f, "dailyLimit") || 5),
|
||
ignorePattern: str(f, "ignorePattern") || null,
|
||
});
|
||
});
|
||
}
|
||
|
||
// ── reviewer agent (PEP-26) ──────────────────────────────────────────────────────
|
||
|
||
export async function saveReviewSettingsAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
await setReviewSettings(db, p.id, {
|
||
enabled: f.get("enabled") === "on",
|
||
maxIterations: Number(str(f, "maxIterations") || 2),
|
||
rules: str(f, "rules") || null,
|
||
});
|
||
});
|
||
}
|
||
|
||
export async function decideIncidentAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const i = await incidentInProject(user.id, f);
|
||
const action = str(f, "action");
|
||
if (action !== "backlog" && action !== "start" && action !== "ignore") throw new PeppaError("Неизвестное решение");
|
||
await decideIncident(db, i.id, action, user.login);
|
||
});
|
||
}
|
||
|
||
export async function resolveIncidentAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
const i = await incidentInProject(user.id, f);
|
||
await resolveIncident(db, i.id, { who: user.login, release: str(f, "release") || null });
|
||
});
|
||
}
|
||
|
||
// ── local users (PEP-68) ────────────────────────────────────────────────────────────
|
||
|
||
/** Superadmin-only actions: everybody else gets "not found", nothing changes. */
|
||
async function requireSuperadmin() {
|
||
const user = await requireUser();
|
||
if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено");
|
||
return user;
|
||
}
|
||
|
||
export async function createLocalUserAction(f: FormData) {
|
||
await attempt(f, async () => {
|
||
await requireSuperadmin();
|
||
const u = await createLocalUser(db, { login: str(f, "login"), name: str(f, "name"), password: String(f.get("password") ?? "") });
|
||
return `/users?created=${encodeURIComponent(u.login)}`;
|
||
});
|
||
}
|
||
|
||
export async function resetUserPasswordAction(f: FormData) {
|
||
await attempt(f, async () => {
|
||
await requireSuperadmin();
|
||
const u = await getUser(db, Number(str(f, "userId")));
|
||
if (!u || !isLocalUser(u)) throw new PeppaError("Пароль задаётся только локальным пользователям");
|
||
await setUserPassword(db, u.id, String(f.get("password") ?? ""));
|
||
return `/users?reset=${encodeURIComponent(u.login)}`;
|
||
});
|
||
}
|
||
|
||
export async function setUserDisabledAction(f: FormData) {
|
||
await attempt(f, async () => {
|
||
const admin = await requireSuperadmin();
|
||
const u = await getUser(db, Number(str(f, "userId")));
|
||
if (!u) throw new PeppaError("Не найдено");
|
||
if (u.id === admin.id) throw new PeppaError("Нельзя отключить самого себя");
|
||
await setUserDisabled(db, u.id, str(f, "disabled") === "1");
|
||
});
|
||
}
|
||
|
||
export async function changePasswordAction(f: FormData) {
|
||
const user = await requireUser();
|
||
await attempt(f, async () => {
|
||
if (!isLocalUser(user)) throw new PeppaError("Вы входите через Gitea — пароль меняется там");
|
||
const next = String(f.get("newPassword") ?? "");
|
||
if (next !== String(f.get("confirm") ?? "")) throw new PeppaError("Новый пароль и повтор не совпадают");
|
||
await changeOwnPassword(db, user, String(f.get("current") ?? ""), next);
|
||
return "/settings?password=changed";
|
||
});
|
||
}
|