61 lines
2.4 KiB
TypeScript
61 lines
2.4 KiB
TypeScript
"use server";
|
|
// «Платформа» (PEP-60): the platform's Telegram channel and digest — superadmin only.
|
|
|
|
import { checkPlatformChannel, parseChatId, PeppaError, platformDigestTick, PLATFORM_CHANNEL_EVENTS, requireSuperadmin, setPlatformChannel } 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";
|
|
|
|
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
|
const BASE = "/platform";
|
|
|
|
async function attempt(fn: () => Promise<string | void>): Promise<never> {
|
|
const user = asWebActor(await requireUser());
|
|
let target = BASE;
|
|
try {
|
|
await requireSuperadmin(db, user);
|
|
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 = `${BASE}?error=${encodeURIComponent(msg.slice(0, 300))}`;
|
|
}
|
|
revalidatePath(BASE);
|
|
redirect(target);
|
|
}
|
|
|
|
/** Saves the Chat ID (and checks the channel right away). */
|
|
export async function saveChannelAction(f: FormData) {
|
|
await attempt(async () => {
|
|
const raw = str(f, "chatId");
|
|
const c = await setPlatformChannel(db, { chatId: raw ? parseChatId(raw) : null });
|
|
if (c.chatId != null) await checkPlatformChannel(db);
|
|
});
|
|
}
|
|
|
|
export async function checkChannelAction() {
|
|
await attempt(async () => {
|
|
await checkPlatformChannel(db);
|
|
});
|
|
}
|
|
|
|
export async function saveChannelSettingsAction(f: FormData) {
|
|
await attempt(async () => {
|
|
const events = Object.fromEntries(PLATFORM_CHANNEL_EVENTS.map((e) => [e, f.get(`event.${e}`) === "on"]));
|
|
await setPlatformChannel(db, { events, digest: { time: str(f, "time"), timezone: str(f, "timezone"), users: f.get("users") === "on" } });
|
|
});
|
|
}
|
|
|
|
/** Sends the platform digest now (over the time since the previous one). */
|
|
export async function sendDigestNowAction() {
|
|
await attempt(async () => {
|
|
const r = await platformDigestTick(db, { force: true });
|
|
if (!r) throw new PeppaError(m("Некуда отправлять: канал не подключён и дайджест пользователям выключен"));
|
|
if (!r.channel && !r.users) return `${BASE}?sent=empty`;
|
|
return `${BASE}?sent=${r.channel ? "channel" : ""}${r.users ? `,users:${r.users}` : ""}`;
|
|
});
|
|
}
|