peppa/apps/web/app/(app)/settings/page.tsx
2026-11-17 12:46:19 +05:00

343 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { CONNECT_HELP, googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
import { Hidden } from "@/components/cards";
import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
import { GoogleSignIn } from "@/components/GoogleSignIn";
import { EgovSign } from "@/components/EgovSign";
import { OwnBotSteps } from "@/components/OwnBotSteps";
import { voiceStoriesEnabled } from "@peppa/shared";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser, uiMode, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { unlinkGoogleAction, disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, setUiModeAction, unpairTelegramAction } from "../actions";
import { PushNotifications } from "@/components/PushNotifications";
import { TimezoneField } from "@/components/TimezoneField";
import { LanguageSwitcher } from "@/components/I18n";
import { getLocale, getT } from "@/lib/i18n";
import { CopyText } from "@/components/CopyText";
import { intlLocale } from "@peppa/shared/i18n";
const back = { back: "/settings" };
/** A connected thing: title + details on the left, actions on the right. */
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
return (
<Card className="flex-row flex-wrap items-center gap-3">
<div className="min-w-0 flex-[1_1_16rem]">
<div className="font-medium">{title}</div>
{children && <div className="text-sm text-muted-foreground">{children}</div>}
</div>
{actions && <div className="flex gap-2">{actions}</div>}
</Card>
);
}
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; mode?: string; egov?: string; google?: string; notify?: string; bot?: string }> }) {
const user = await requireUser();
const { error, egov, google, notify, bot, mode: modeSaved } = await searchParams;
const mode = await uiMode();
const w = await words();
const hasBot = !!user.telegramBotUsername;
const local = isLocalUser(user);
const superadmin = await isSuperadmin(db, user);
const apps = await connectedApps(db, user.id);
const origin = await publicOrigin();
const prefs = await getNotifyPrefs(db, user.id);
const myProjects = await listUserProjects(db, user.id);
const pushSubs = await userPushSubscriptions(db, user.id);
const vapid = await vapidPublicKey(db);
const t = await getT();
const connect = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
const ownBotSteps = <OwnBotSteps botUsername={user.telegramBotUsername} back="/settings" />;
return (
<Workspace>
<div className="max-w-2xl">
<Flash error={error} />
<PageHeader title={t("Настройки")} />
<Section title={t("Язык интерфейса")} id="language">
<Card className="flex-row flex-wrap items-center gap-3">
<LanguageSwitcher />
</Card>
</Section>
<Section title={t("Вид Peppa FACTORY")} id="mode">
{modeSaved === "saved" && <Notice>{t("Сохранено. Сейчас у вас вид «{mode}».", { mode: mode === "engineer" ? t("Инженер") : t("Продакт") })}</Notice>}
<form action={setUiModeAction} className="flex flex-col gap-2">
<label className="flex cursor-pointer items-start gap-2.5 rounded-lg border bg-card px-4 py-3 text-sm has-checked:border-primary/60 has-checked:bg-primary/5">
<input type="radio" name="mode" value="product" defaultChecked={mode === "product"} className="mt-1 accent-primary" />
<span className="flex flex-col gap-0.5">
<span className="font-medium">{t("Продакт")}</span>
<span className="text-muted-foreground">{t("Только главное: что делается, что нужно от вас и где результат. Для тех, кто придумывает продукт, а не пишет код.")}</span>
</span>
</label>
<label className="flex cursor-pointer items-start gap-2.5 rounded-lg border bg-card px-4 py-3 text-sm has-checked:border-primary/60 has-checked:bg-primary/5">
<input type="radio" name="mode" value="engineer" defaultChecked={mode === "engineer"} className="mt-1 accent-primary" />
<span className="flex flex-col gap-0.5">
<span className="font-medium">{t("Инженер")}</span>
<span className="text-muted-foreground">{t("Всё, что делают агенты: код, проверки, каждый шаг агента, расход. Для тех, кто хочет заглянуть под капот.")}</span>
</span>
</label>
<Button variant="default" size="sm" className="self-start">{t("Сохранить")}</Button>
</form>
</Section>
<Section title={t("Учётная запись")}>
<Card>
<p className="m-0 text-sm">
{t("Логин")} <span className="font-mono">{user.login}</span>
{user.name ? <> · {user.name}</> : null}.{" "}{t("Вход в Peppa FACTORY — через eGov QR или Google")}
{user.egovIin ? (
<>
, {t("ИИН")} <span className="font-mono">{maskIin(user.egovIin)}</span>.
</>
) : (
<>. <b>{t("ИИН ещё не привязан")}</b>{user.googleSub ? "." : <>{" — "}{t("привяжите его ниже или Google, иначе после выхода вы не сможете войти.")}</>}</>
)}
</p>
{local && w.engineer && (
<p className="m-0 text-sm text-muted-foreground">
{t("Аккаунта Gitea нет: код проектов — через Peppa FACTORY (агенты, PR, проверки), новые проекты создаются в пространстве")} <span className="font-mono">peppa-bot</span>.
</p>
)}
</Card>
{superadmin && (
<Row
title={t("Суперадмин")}
actions={
<>
<Button asChild size="sm">
<a href="/users">{t("Пользователи")}</a>
</Button>
<Button asChild size="sm">
<a href="/feedback">{t("Обращения")}</a>
</Button>
<Button asChild size="sm">
<a href="/subscriptions">{t("Подписки")}</a>
</Button>
<Button asChild size="sm">
<a href="/secrets">{t("Секреты")}</a>
</Button>
<Button asChild size="sm">
<a href="/hosts">{t("Хосты")}</a>
</Button>
<Button asChild size="sm">
<a href="/journal">{t("Журнал")}</a>
</Button>
<Button asChild size="sm">
<a href="/platform">{t("Платформа")}</a>
</Button>
</>
}
>
{t("Пользователи: кто зарегистрировался через eGov, отключить и включить. Подписки агентов и пулы для ротации. Журнал: кто что сделал.")}
</Row>
)}
</Section>
{w.engineer && (
<Section title={t("Агенты")}>
<p className="m-0 text-sm text-muted-foreground">
{t("Подписки Claude Code, Codex и OpenCode, на которых работают агенты, ведёт суперадмин в разделе «Подписки»; проект запускает раннеры на своём пуле подписок.")}
</p>
</Section>
)}
{!user.egovIin && (
<Section title="eGov" id="egov">
{egov === "linked" && <Notice>{t("eGov привязан — теперь можно входить по QR")}</Notice>}
<Card>
<p className="m-0 text-sm">{t("Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Peppa FACTORY — только через eGov.")}</p>
<div className="max-w-xs">
<EgovSign purpose="link" label={t("Привязать eGov")} />
</div>
</Card>
</Section>
)}
{user.egovIin && egov === "linked" && <Notice>{t("eGov привязан — теперь можно входить по QR")}</Notice>}
{(googleEnabled() || user.googleSub) && (
<Section title="Google" id="google">
{google === "linked" && <Notice>{t("Google привязан — теперь можно входить через него")}</Notice>}
{user.googleSub ? (
<Row
title={t("Google привязан")}
actions={
<form action={unlinkGoogleAction}>
<Hidden fields={{ back: "/settings#google" }} />
<Button size="sm" variant="destructive">{t("Отвязать")}</Button>
</form>
}
>
{user.googleEmail}. {t("Войти через Google можно в ту же учётку.")}
</Row>
) : (
<Card>
<p className="m-0 text-sm">{t("Привяжите Google-аккаунт — и в эту учётку можно будет входить и через него.")}</p>
<div className="max-w-xs">
<GoogleSignIn purpose="link" label={t("Привязать Google")} />
</div>
</Card>
)}
</Section>
)}
<Section title="Telegram" id="telegram">
{bot === "connected" && <Notice>{t("Бот @{bot} подключён — остался последний шаг: откройте его и нажмите Start.", { bot: user.telegramBotUsername })}</Notice>}
{user.telegramChatId ? (
<Row
title={t("Telegram привязан") + (user.telegramUsername ? ` (@${user.telegramUsername})` : "")}
actions={
<form action={unpairTelegramAction}>
<Hidden fields={back} />
<Button size="sm" variant="destructive">{t("Отвязать")}</Button>
</form>
}
>
{t("Вопросы агентов и «готово к ревью» приходят вам")} {user.telegramBotUsername ? <>{t("от вашего бота")} <span className="font-mono">@{user.telegramBotUsername}</span></> : t("от общего бота Peppa FACTORY")}. {voiceStoriesEnabled() ? t("Новую задачу можно просто написать или наговорить голосом боту.") : t("Новую задачу можно просто написать боту.")}
</Row>
) : (
ownBotSteps
)}
{/* PEP-100: every user has their own bot — someone still on the shared one is asked to switch. */}
{user.telegramChatId && !hasBot && (
<>
<Notice>{t("Сейчас сообщения приходят от общего бота Peppa FACTORY. Подключите своего бота — так у вас будет свой канал для задач и ответов.")}</Notice>
{ownBotSteps}
</>
)}
{user.telegramChatId && hasBot && (
<form action={disconnectOwnBotAction}>
<Hidden fields={back} />
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Отключить бота @{bot}", { bot: user.telegramBotUsername })}</Button>
</form>
)}
</Section>
<Section title={t("Уведомления")} id="notifications">
{notify === "saved" && <Notice>{t("Настройки уведомлений сохранены")}</Notice>}
<Card>
<div className="flex flex-col gap-1">
<div className="font-medium">{t("Браузер")}</div>
<p className="m-0 text-sm text-muted-foreground">
{t("Push приходят и при закрытой вкладке; клик открывает {task} или проект. Подписано браузеров: {n}. Peppa FACTORY можно установить как приложение (Chrome → «Установить»).", { task: w.task("acc"), n: pushSubs.length })}
</p>
</div>
<PushNotifications vapidKey={vapid} known={pushSubs.map((s) => s.endpoint)} />
</Card>
<form action={saveNotifyPrefsAction} className="flex flex-col gap-4" aria-label={t("Настройки уведомлений")}>
<Hidden fields={back} />
<Card className="gap-0 p-0">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-left text-muted-foreground">
<th className="px-4 py-2 font-normal">{t("Событие")}</th>
<th className="w-24 px-2 py-2 text-center font-normal">Telegram</th>
<th className="w-24 px-2 py-2 text-center font-normal">{t("Браузер")}</th>
</tr>
</thead>
<tbody>
{NOTIFY_EVENTS.filter((e) => (e !== "monitoring" && e !== "users" && e !== "feedback") || superadmin).map((e) => (
<tr key={e} className="border-b last:border-0">
<td className="px-4 py-2">{t.text(NOTIFY_EVENT_NAMES[e])}</td>
<td className="px-2 py-2 text-center">
<input type="checkbox" name={`${e}.telegram`} defaultChecked={prefs.events[e].telegram} aria-label={`${t.text(NOTIFY_EVENT_NAMES[e])} — Telegram`} className="size-4 accent-primary" />
</td>
<td className="px-2 py-2 text-center">
<input type="checkbox" name={`${e}.push`} defaultChecked={prefs.events[e].push} aria-label={t.text(NOTIFY_EVENT_NAMES[e]) + " — " + t("браузер")} className="size-4 accent-primary" />
</td>
</tr>
))}
</tbody>
</table>
{!superadmin && (
<>
<input type="hidden" name="monitoring.telegram" value={prefs.events.monitoring.telegram ? "on" : ""} />
<input type="hidden" name="monitoring.push" value={prefs.events.monitoring.push ? "on" : ""} />
<input type="hidden" name="users.telegram" value={prefs.events.users.telegram ? "on" : ""} />
<input type="hidden" name="users.push" value={prefs.events.users.push ? "on" : ""} />
{/* PEP-143: the author's own «исправили» comes by this event; the row is the superadmin's. */}
<input type="hidden" name="feedback.telegram" value={prefs.events.feedback.telegram ? "on" : ""} />
<input type="hidden" name="feedback.push" value={prefs.events.feedback.push ? "on" : ""} />
</>
)}
</Card>
<Card>
<label className="flex items-center gap-2 text-sm font-medium">
<input type="checkbox" name="quietOn" defaultChecked={!!prefs.quiet} className="size-4 accent-primary" />
{t("Тихие часы")}
</label>
<div className="flex flex-wrap items-end gap-3">
<Label className="w-32">
{t("С")}
<Input type="time" name="quietFrom" defaultValue={prefs.quiet?.from ?? "23:00"} />
</Label>
<Label className="w-32">
{t("До")}
<Input type="time" name="quietTo" defaultValue={prefs.quiet?.to ?? "08:00"} />
</Label>
</div>
<p className="m-0 text-sm text-muted-foreground">{t("В тихие часы Telegram приходит без звука, push в браузер не показываются. Дайджест приходит в своё время.")}</p>
<div className="flex flex-wrap items-end gap-3">
<Label className="w-32">
{t("Дайджест в")}
<Input type="time" name="digestTime" defaultValue={prefs.digestTime} />
</Label>
<TimezoneField value={prefs.timezone} />
</div>
<p className="m-0 text-sm text-muted-foreground">
{t("Сводка за сутки по вашим проектам: сделано, в работе, на ревью, ждёт вас, зависло, лимиты. Пустая не приходит. В боте — команда /digest.")}
</p>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="sound" defaultChecked={prefs.sound} className="size-4 accent-primary" />
{t("Звук: сигнал в открытой вкладке при новом вопросе и звук у push")}
</label>
</Card>
{myProjects.length > 0 && (
<Card>
<div className="text-sm font-medium">{t("Проекты")}</div>
<p className="m-0 text-sm text-muted-foreground">{t("Из снятых проектов уведомления не приходят (вопросы остаются в вебе).")}</p>
<div className="flex flex-wrap gap-x-5 gap-y-2">
{myProjects.map((p) => (
<label key={p.id} className="flex items-center gap-2 text-sm">
<input type="hidden" name="projectShown" value={p.id} />
<input type="checkbox" name="project" value={p.id} defaultChecked={!prefs.mutedProjects.includes(p.id)} className="size-4 accent-primary" />
{p.name} <span className="font-mono text-xs text-muted-foreground">{p.key}</span>
</label>
))}
</div>
</Card>
)}
<Button variant="default" className="self-start">{t("Сохранить уведомления")}</Button>
</form>
</Section>
<Section title={w.engineer ? t("MCP для ChatGPT и других клиентов") : t("Peppa FACTORY в вашем Claude или ChatGPT")}>
<p className="m-0 text-sm">{w.engineer ? t("Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Peppa FACTORY.") : t("Подключите Peppa FACTORY к своему чату — и ставьте задачи и отвечайте агентам прямо из него. Понадобится этот адрес; доступ вы подтвердите на экране Peppa FACTORY.")}</p>
<CopyText value={`${origin}/mcp`} label={connect.copy} done={connect.copied} />
<p className="m-0 text-sm">
<a href="/help/connect" className="font-medium text-primary">{connect.linkLabel} →</a>
{" · "}
<a href="/mcp-guide" className="font-medium text-primary">{t("Инструкция для ИИ")} →</a>
</p>
</Section>
<Section title={t("Подключённые приложения")} id="apps">
{apps.length === 0 ? (
<Empty>{t("Нет подключённых приложений.")}</Empty>
) : (
apps.map((a) => (
<Row
key={a.clientId}
title={a.name}
actions={
<form action={revokeConnectedApp}>
<Hidden fields={{ clientId: a.clientId, ...back }} />
<Button size="sm" variant="destructive">{t("Отозвать")}</Button>
</form>
}
>
{t("с {date} · последний запрос {ago}", { date: a.since.toLocaleDateString(intlLocale(t.locale)), ago: ago(a.lastUsedAt, t) })}
</Row>
))
)}
</Section>
</div>
</Workspace>
);
}