peppa/apps/web/app/(app)/settings/page.tsx
Асель 80a3bb79ad PEP-97: the name users see is «Peppa FACTORY» everywhere
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:34:03 +05:00

297 lines
16 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 { 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 { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { unlinkGoogleAction, disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
import { PushNotifications } from "@/components/PushNotifications";
import { TimezoneField } from "@/components/TimezoneField";
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; egov?: string; google?: string; notify?: string; bot?: string }> }) {
const user = await requireUser();
const { error, egov, google, notify, bot } = await searchParams;
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 ownBotSteps = <OwnBotSteps botUsername={user.telegramBotUsername} back="/settings" />;
return (
<Workspace>
<div className="max-w-2xl">
<Flash error={error} />
<PageHeader title="Настройки" />
<Section title="Учётная запись">
<Card>
<p className="m-0 text-sm">
Логин <span className="font-mono">{user.login}</span>
{user.name ? <> · {user.name}</> : null}. Вход в Пеппу — через eGov QR или Google
{user.egovIin ? (
<>
, ИИН <span className="font-mono">{maskIin(user.egovIin)}</span>.
</>
) : (
<>. <b>ИИН ещё не привязан</b>{user.googleSub ? "." : " — привяжите его ниже или Google, иначе после выхода вы не сможете войти."}</>
)}
</p>
{local && (
<p className="m-0 text-sm text-muted-foreground">
Аккаунта Gitea нет: код проектов — через Пеппу (агенты, PR, проверки), новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.
</p>
)}
</Card>
{superadmin && (
<Row
title="Суперадмин"
actions={
<>
<Button asChild size="sm">
<a href="/users">Пользователи</a>
</Button>
<Button asChild size="sm">
<a href="/subscriptions">Подписки</a>
</Button>
<Button asChild size="sm">
<a href="/secrets">Секреты</a>
</Button>
<Button asChild size="sm">
<a href="/hosts">Хосты</a>
</Button>
<Button asChild size="sm">
<a href="/journal">Журнал</a>
</Button>
<Button asChild size="sm">
<a href="/platform">Платформа</a>
</Button>
</>
}
>
Пользователи: кто зарегистрировался через eGov, отключить и включить. Подписки агентов и пулы для ротации. Журнал: кто что сделал.
</Row>
)}
</Section>
<Section title="Агенты">
<p className="m-0 text-sm text-muted-foreground">
Подписки Claude Code, Codex и OpenCode, на которых работают агенты, ведёт суперадмин в разделе «Подписки»; проект запускает раннеры на своём пуле подписок.
</p>
</Section>
{!user.egovIin && (
<Section title="eGov" id="egov">
{egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
<Card>
<p className="m-0 text-sm">Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Пеппу — только через eGov.</p>
<div className="max-w-xs">
<EgovSign purpose="link" label="Привязать eGov" />
</div>
</Card>
</Section>
)}
{user.egovIin && egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
{(googleEnabled() || user.googleSub) && (
<Section title="Google" id="google">
{google === "linked" && <Notice>Google привязан — теперь можно входить через него</Notice>}
{user.googleSub ? (
<Row
title="Google привязан"
actions={
<form action={unlinkGoogleAction}>
<Hidden fields={{ back: "/settings#google" }} />
<Button size="sm" variant="destructive">Отвязать</Button>
</form>
}
>
{user.googleEmail}. Войти через Google можно в ту же учётку.
</Row>
) : (
<Card>
<p className="m-0 text-sm">Привяжите Google-аккаунт — и в эту учётку можно будет входить и через него.</p>
<div className="max-w-xs">
<GoogleSignIn purpose="link" label="Привязать Google" />
</div>
</Card>
)}
</Section>
)}
<Section title="Telegram" id="telegram">
{bot === "connected" && <Notice>Бот @{user.telegramBotUsername} подключён — остался последний шаг: откройте его и нажмите Start.</Notice>}
{user.telegramChatId ? (
<Row
title={`Telegram привязан${user.telegramUsername ? ` (@${user.telegramUsername})` : ""}`}
actions={
<form action={unpairTelegramAction}>
<Hidden fields={back} />
<Button size="sm" variant="destructive">Отвязать</Button>
</form>
}
>
Вопросы агентов и «готово к ревью» приходят вам {user.telegramBotUsername ? <>от вашего бота <span className="font-mono">@{user.telegramBotUsername}</span></> : "от общего бота Пеппы"}. Новую задачу можно просто написать боту.
</Row>
) : (
ownBotSteps
)}
{/* PEP-100: every user has their own bot — someone still on the shared one is asked to switch. */}
{user.telegramChatId && !hasBot && (
<>
<Notice>Сейчас сообщения приходят от общего бота Пеппы. Подключите своего бота — так у каждого пользователя свой канал с фабрикой.</Notice>
{ownBotSteps}
</>
)}
{user.telegramChatId && hasBot && (
<form action={disconnectOwnBotAction}>
<Hidden fields={back} />
<Button size="xs" variant="ghost" className="text-muted-foreground">Отключить бота @{user.telegramBotUsername}</Button>
</form>
)}
</Section>
<Section title="Уведомления" id="notifications">
{notify === "saved" && <Notice>Настройки уведомлений сохранены</Notice>}
<Card>
<div className="flex flex-col gap-1">
<div className="font-medium">Браузер</div>
<p className="m-0 text-sm text-muted-foreground">
Push приходят и при закрытой вкладке; клик открывает стори или проект. Подписано браузеров: {pushSubs.length}. Пеппу можно установить как приложение (Chrome → «Установить»).
</p>
</div>
<PushNotifications vapidKey={vapid} known={pushSubs.map((s) => s.endpoint)} />
</Card>
<form action={saveNotifyPrefsAction} className="flex flex-col gap-4" aria-label="Настройки уведомлений">
<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">Событие</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">Браузер</th>
</tr>
</thead>
<tbody>
{NOTIFY_EVENTS.filter((e) => e !== "monitoring" || superadmin).map((e) => (
<tr key={e} className="border-b last:border-0">
<td className="px-4 py-2">{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={`${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={`${NOTIFY_EVENT_NAMES[e]} — браузер`} 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" : ""} />
</>
)}
</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" />
Тихие часы
</label>
<div className="flex flex-wrap items-end gap-3">
<Label className="w-32">
С
<Input type="time" name="quietFrom" defaultValue={prefs.quiet?.from ?? "23:00"} />
</Label>
<Label className="w-32">
До
<Input type="time" name="quietTo" defaultValue={prefs.quiet?.to ?? "08:00"} />
</Label>
</div>
<p className="m-0 text-sm text-muted-foreground">В тихие часы Telegram приходит без звука, push в браузер не показываются. Дайджест приходит в своё время.</p>
<div className="flex flex-wrap items-end gap-3">
<Label className="w-32">
Дайджест в
<Input type="time" name="digestTime" defaultValue={prefs.digestTime} />
</Label>
<TimezoneField value={prefs.timezone} />
</div>
<p className="m-0 text-sm text-muted-foreground">
Сводка за сутки по вашим проектам: сделано, в работе, на ревью, ждёт вас, зависло, лимиты. Пустая не приходит. В боте — команда /digest.
</p>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="sound" defaultChecked={prefs.sound} className="size-4 accent-primary" />
Звук: сигнал в открытой вкладке при новом вопросе и звук у push
</label>
</Card>
{myProjects.length > 0 && (
<Card>
<div className="text-sm font-medium">Проекты</div>
<p className="m-0 text-sm text-muted-foreground">Из снятых проектов уведомления не приходят (вопросы остаются в вебе).</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">Сохранить уведомления</Button>
</form>
</Section>
<Section title="MCP для ChatGPT и других клиентов">
<p className="m-0 text-sm">Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 font-mono text-sm">{origin}/mcp</code>
<p className="m-0 text-sm text-muted-foreground">
Как подключить и что спрашивать — в <a href="/help" className="text-primary">Помощи</a>.
</p>
</Section>
<Section title="Подключённые приложения">
{apps.length === 0 ? (
<Empty>Нет подключённых приложений.</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">Отозвать</Button>
</form>
}
>
с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}
</Row>
))
)}
</Section>
</div>
</Workspace>
);
}