"use server"; import { createGoal, createTask, getQuestion, getSession, giteaForUser, PeppaError, projectForUser, resolveTask, revokeApp, setClaudeToken, createPairingCode, getSetting, unpairTelegram, getIncident, getProject as getProjectByKey, updateIncidentSettings, type IncidentPolicy, } from "@peppa/core"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, grantRepoAccess, moveTask, provisionProject, shareProject, startClaudeSetup, 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): Promise { 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 addGoal(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("Нужно название цели"); await createGoal(db, p.id, str(f, "title"), str(f, "description") || undefined); }); } 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 goalId = str(f, "goalId") ? Number(str(f, "goalId")) : undefined; const ref = await createTask(db, { projectId: p.id, goalId, title: str(f, "title"), description: str(f, "description") || undefined }); return `/t/${ref.key}`; }); } 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); await startSession(db, ref.key, { provider: (str(f, "provider") || "claude") as Provider, 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 owner = str(f, "owner") || user.login; const p = await provisionProject(db, { gitea: await giteaForUser(db, user), owner, ownerIsUser: owner === user.login, slug: str(f, "slug").toLowerCase(), key: str(f, "key"), name: str(f, "name"), existing: str(f, "mode") === "existing", visibility: str(f, "visibility") === "public" ? "public" : "private", 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 connectClaude(f: FormData) { const user = await requireUser(); await attempt(f, async () => { await startClaudeSetup(db, user.id); }); } export async function submitClaudeCode(f: FormData) { const user = await requireUser(); await attempt(f, async () => { await finishClaudeSetup(db, user.id, str(f, "code")); return "/settings?claude=connected"; }); } export async function cancelClaude(f: FormData) { const user = await requireUser(); await attempt(f, async () => { await cancelClaudeSetup(db, user.id); }); } export async function disconnectClaude(f: FormData) { const user = await requireUser(); await attempt(f, async () => { await setClaudeToken(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 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); }); } // ── 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, }); }); } 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 }); }); }