68 lines
3.3 KiB
TypeScript
68 lines
3.3 KiB
TypeScript
"use server";
|
|
// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
|
|
|
|
import { parseAttachmentIds, chatForUser, createChatLinkCode, isSuperadmin, PeppaError, unlinkChat } from "@peppa/core";
|
|
import { postToChat, resolveChatOffer, type ChatOfferChoice } from "@peppa/runner";
|
|
import { loadEnv } from "@peppa/shared";
|
|
import { m } from "@peppa/shared/i18n";
|
|
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();
|
|
|
|
/** Runs an action; errors come back as ?error=… (redirect stays outside try). */
|
|
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
|
let target = str(f, "back") || "/chats";
|
|
try {
|
|
target = (await fn()) || target;
|
|
} catch (e) {
|
|
const msg = e instanceof PeppaError ? e.message : m("Ошибка: {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("/chats", "layout");
|
|
redirect(target);
|
|
}
|
|
|
|
export async function postChatAction(f: FormData) {
|
|
const user = asWebActor(await requireUser());
|
|
await attempt(f, async () => {
|
|
const thread = str(f, "thread");
|
|
await postToChat(db, user, { chatId: Number(str(f, "chatId")), threadKey: thread || null, text: String(f.get("text") ?? ""), via: "web", attachmentIds: parseAttachmentIds(f.getAll("attachment")) });
|
|
});
|
|
}
|
|
|
|
/** PEP-153: a button under a chat message — «Завести как задачу», «Ответить», «Создать», «Отмена». */
|
|
export async function chatOfferAction(f: FormData) {
|
|
const user = asWebActor(await requireUser());
|
|
await attempt(f, async () => {
|
|
const choice = str(f, "choice");
|
|
if (!["task", "answer", "create", "cancel", "stories"].includes(choice)) throw new PeppaError(m("Эта кнопка уже не работает. Напишите сообщение ещё раз."));
|
|
await resolveChatOffer(db, user, Number(str(f, "messageId")), choice as ChatOfferChoice);
|
|
});
|
|
}
|
|
|
|
/** A one-time code (10 min) for `/link <код>` in a group, or the startgroup link of the user's bot that sends it. */
|
|
export async function linkChatAction(f: FormData) {
|
|
const user = asWebActor(await requireUser());
|
|
await attempt(f, async () => {
|
|
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
|
if (!token) throw new PeppaError(m("Telegram пока не настроен. Напишите в поддержку Peppa FACTORY."));
|
|
const chat = await chatForUser(db, user, Number(str(f, "chatId")));
|
|
// PEP-109: the group is linked through the user's own bot; the platform's bot is the
|
|
// superadmin's (PEP-106) and serves only a superadmin who has no bot of their own.
|
|
const code = await createChatLinkCode(db, token, user, chat.id, { sharedBot: await isSuperadmin(db, user) });
|
|
const back = str(f, "back") || "/chats";
|
|
return `${back}${back.includes("?") ? "&" : "?"}link=${encodeURIComponent(code)}`;
|
|
});
|
|
}
|
|
|
|
export async function unlinkChatAction(f: FormData) {
|
|
const user = asWebActor(await requireUser());
|
|
await attempt(f, () => unlinkChat(db, user, Number(str(f, "chatId"))));
|
|
}
|