global update and global fix

This commit is contained in:
lendry
2026-06-25 23:48:57 +03:00
parent 3880c68d59
commit b0ea87e898
121 changed files with 13759 additions and 663 deletions

View File

@@ -0,0 +1,234 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Ban, Bot, CheckCircle2, Loader2, MessageSquare, Search, Users } from 'lucide-react';
import { AdminShell } from '@/components/id/admin-shell';
import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import {
AdminBotMetrics,
ManagedBot,
fetchAdminBotMetrics,
fetchAdminBots,
setAdminBotActive
} from '@/lib/api';
import { getAdminLandingPath } from '@/lib/admin-access';
export default function AdminBotsPage() {
const router = useRouter();
const { token, user: currentUser } = useAuth();
const { showToast } = useToast();
const [bots, setBots] = useState<ManagedBot[]>([]);
const [total, setTotal] = useState(0);
const [metrics, setMetrics] = useState<AdminBotMetrics | null>(null);
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(true);
const [actionBotId, setActionBotId] = useState<string | null>(null);
const loadBots = useCallback(async () => {
if (!token) return;
setLoading(true);
try {
const [botsResponse, metricsResponse] = await Promise.all([
fetchAdminBots({ search, page, limit: 20 }, token),
fetchAdminBotMetrics(token)
]);
setBots(botsResponse.bots ?? []);
setTotal(botsResponse.total ?? 0);
setMetrics(metricsResponse);
} catch (error) {
showToast(error instanceof Error ? error.message : 'Не удалось загрузить ботов');
} finally {
setLoading(false);
}
}, [page, search, showToast, token]);
useEffect(() => {
if (!currentUser) return;
if (!currentUser.canManageBots && !currentUser.isSuperAdmin) {
router.replace(getAdminLandingPath(currentUser));
}
}, [currentUser, router]);
useEffect(() => {
if (!currentUser?.canManageBots && !currentUser?.isSuperAdmin) return;
void loadBots();
}, [currentUser?.canManageBots, currentUser?.isSuperAdmin, loadBots]);
async function handleToggleActive(bot: ManagedBot) {
if (!token) return;
setActionBotId(bot.id);
try {
await setAdminBotActive(bot.id, !bot.isActive, token);
showToast(bot.isActive ? 'Бот заблокирован' : 'Бот разблокирован');
await loadBots();
} catch (error) {
showToast(error instanceof Error ? error.message : 'Не удалось изменить статус бота');
} finally {
setActionBotId(null);
}
}
const totalPages = Math.max(1, Math.ceil(total / 20));
return (
<AdminShell active="/admin/bots">
<h2 className="mb-4 text-2xl font-medium tracking-tight">Telegram-боты</h2>
<div className="mb-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<MetricCard label="Всего ботов" value={metrics?.totalBots ?? 0} icon={Bot} />
<MetricCard label="Активных" value={metrics?.activeBots ?? 0} icon={CheckCircle2} accent="text-emerald-600" />
<MetricCard label="Заблокированных" value={metrics?.blockedBots ?? 0} icon={Ban} accent="text-rose-600" />
<MetricCard label="Сообщений" value={metrics?.totalMessages ?? 0} icon={MessageSquare} />
</div>
<div className="mb-4 flex flex-wrap items-center gap-3">
<div className="relative min-w-[240px] flex-1">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#667085]" />
<Input
className="rounded-xl pl-9"
placeholder="Поиск по названию или @username"
value={search}
onChange={(event) => {
setSearch(event.target.value);
setPage(1);
}}
/>
</div>
<p className="text-sm text-[#667085]">Найдено: {total}</p>
</div>
<div className="overflow-hidden rounded-2xl border border-[#eceef4] bg-white">
<Table>
<TableHeader>
<TableRow>
<TableHead>Бот</TableHead>
<TableHead>Владелец</TableHead>
<TableHead>Статус</TableHead>
<TableHead className="text-right">Действия</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={4} className="py-10 text-center text-[#667085]">
<Loader2 className="mx-auto h-5 w-5 animate-spin" />
</TableCell>
</TableRow>
) : bots.length ? (
bots.map((bot) => (
<TableRow key={bot.id}>
<TableCell>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#eef4ff] text-[#3390ec]">
<Bot className="h-5 w-5" />
</div>
<div>
<p className="font-medium">{bot.name}</p>
<p className="text-sm text-[#667085]">@{bot.username}</p>
{bot.isSystemBot ? <p className="text-xs text-[#3390ec]">Системный</p> : null}
</div>
</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<Users className="h-4 w-4 text-[#667085]" />
<div>
<p className="text-sm font-medium">{bot.owner?.displayName ?? '—'}</p>
{bot.owner?.username ? <p className="text-xs text-[#667085]">@{bot.owner.username}</p> : null}
</div>
</div>
</TableCell>
<TableCell>
<span
className={
bot.isActive
? 'inline-flex rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-medium text-emerald-700'
: 'inline-flex rounded-full bg-rose-50 px-2.5 py-1 text-xs font-medium text-rose-700'
}
>
{bot.isActive ? 'Активен' : 'Заблокирован'}
</span>
</TableCell>
<TableCell className="text-right">
{!bot.isSystemBot ? (
<Button
variant="outline"
size="sm"
className="rounded-xl"
disabled={actionBotId === bot.id}
onClick={() => void handleToggleActive(bot)}
>
{actionBotId === bot.id ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : bot.isActive ? (
'Заблокировать'
) : (
'Разблокировать'
)}
</Button>
) : (
<span className="text-xs text-[#667085]"></span>
)}
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={4} className="py-10 text-center text-[#667085]">
Боты не найдены
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
{totalPages > 1 ? (
<div className="mt-4 flex items-center justify-center gap-2">
<Button variant="outline" size="sm" className="rounded-xl" disabled={page <= 1} onClick={() => setPage((value) => value - 1)}>
Назад
</Button>
<span className="text-sm text-[#667085]">
{page} / {totalPages}
</span>
<Button
variant="outline"
size="sm"
className="rounded-xl"
disabled={page >= totalPages}
onClick={() => setPage((value) => value + 1)}
>
Вперёд
</Button>
</div>
) : null}
</AdminShell>
);
}
function MetricCard({
label,
value,
icon: Icon,
accent
}: {
label: string;
value: number;
icon: typeof Bot;
accent?: string;
}) {
return (
<div className="rounded-2xl border border-[#eceef4] bg-white p-4">
<div className="mb-2 flex items-center gap-2 text-sm text-[#667085]">
<Icon className={`h-4 w-4 ${accent ?? ''}`} />
{label}
</div>
<p className="text-2xl font-semibold">{value.toLocaleString('ru-RU')}</p>
</div>
);
}

View File

@@ -82,6 +82,16 @@ export default function LoginPage() {
const router = useRouter();
const finishLoginRedirect = useCallback(() => {
const redirectAfterLogin =
typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('redirect') : null;
if (redirectAfterLogin && redirectAfterLogin.startsWith('/')) {
router.push(redirectAfterLogin);
return;
}
router.push('/');
}, [router]);
const { identifyLogin, sendLoginOtp, verifyLoginOtp, loginWithPassword, loginWithLdap, beginTotpLogin, verifyTotpLogin, completePin, applyLoginAuth } = useAuth();
const { showToast } = useToast();
@@ -174,7 +184,7 @@ export default function LoginPage() {
} else {
router.push('/');
finishLoginRedirect();
}
@@ -596,7 +606,7 @@ export default function LoginPage() {
await completePin(pendingSessionId, pin);
router.push('/');
finishLoginRedirect();
} catch (error) {

View File

@@ -0,0 +1,150 @@
'use client';
import { Suspense, useCallback, useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Loader2, ShieldCheck } from 'lucide-react';
import { BrandLogo } from '@/components/id/brand-logo';
import { useAuth } from '@/components/id/auth-provider';
import { Button } from '@/components/ui/button';
function OAuthAuthorizeContent() {
const searchParams = useSearchParams();
const router = useRouter();
const { user, token, isPinLocked, isLoading } = useAuth();
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const oauthQuery = useMemo(() => {
const params = new URLSearchParams();
searchParams.forEach((value, key) => params.set(key, value));
return params;
}, [searchParams]);
const clientId = searchParams.get('client_id') ?? searchParams.get('clientId');
const redirectUri = searchParams.get('redirect_uri') ?? searchParams.get('redirectUri');
const scope = searchParams.get('scope') ?? 'openid profile';
useEffect(() => {
if (isLoading) return;
if (!clientId || !redirectUri) return;
if (user && token && !isPinLocked) return;
const returnUrl = `/auth/oauth/authorize?${oauthQuery.toString()}`;
router.replace(`/auth/login?redirect=${encodeURIComponent(returnUrl)}`);
}, [clientId, isLoading, isPinLocked, oauthQuery, redirectUri, router, token, user]);
const approve = useCallback(async () => {
if (!token || !user) return;
setSubmitting(true);
setError(null);
try {
const apiBase = (process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3000').replace(/\/$/, '');
const url = new URL(`${apiBase}/oauth/authorize`);
oauthQuery.forEach((value, key) => url.searchParams.set(key, value));
url.searchParams.set('userId', user.id);
const response = await fetch(url.toString(), {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json'
}
});
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as { message?: string | string[] } | null;
const message = Array.isArray(payload?.message) ? payload.message.join(', ') : payload?.message;
throw new Error(message || 'Не удалось подтвердить доступ');
}
const data = (await response.json()) as { redirectUrl?: string };
if (!data.redirectUrl) {
throw new Error('Сервер не вернул redirect URL');
}
window.location.href = data.redirectUrl;
} catch (err) {
setError(err instanceof Error ? err.message : 'Ошибка OAuth авторизации');
} finally {
setSubmitting(false);
}
}, [oauthQuery, token, user]);
if (isLoading) {
return (
<div className="flex min-h-[60vh] items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-[#667085]" />
</div>
);
}
if (!clientId || !redirectUri) {
return (
<div className="mx-auto max-w-md px-4 py-16 text-center">
<h1 className="text-xl font-semibold">Некорректный OAuth запрос</h1>
<p className="mt-3 text-sm text-[#667085]">Отсутствуют обязательные параметры client_id и redirect_uri.</p>
<Link href="/" className="mt-6 inline-block text-[#3390ec] hover:underline">
На главную
</Link>
</div>
);
}
if (!user || !token || isPinLocked) {
return (
<div className="flex min-h-[60vh] items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-[#667085]" />
</div>
);
}
return (
<div className="mx-auto flex min-h-[70vh] max-w-lg flex-col justify-center px-4 py-12">
<div className="mb-8 flex justify-center">
<BrandLogo />
</div>
<div className="rounded-[24px] border border-[#eceef4] bg-white p-6 shadow-sm">
<div className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-[#eef4ff] text-[#3390ec]">
<ShieldCheck className="h-6 w-6" />
</div>
<h1 className="text-2xl font-semibold">Разрешить доступ?</h1>
<p className="mt-2 text-sm leading-relaxed text-[#667085]">
Приложение <span className="font-medium text-[#1f2430]">{clientId}</span> запрашивает доступ к вашему аккаунту Lendry ID.
</p>
<div className="mt-4 space-y-2 rounded-2xl bg-[#f4f5f8] p-4 text-sm">
<p>
<span className="text-[#667085]">Пользователь:</span> {user.displayName}
</p>
<p>
<span className="text-[#667085]">Scopes:</span> {scope}
</p>
<p className="break-all">
<span className="text-[#667085]">Redirect URI:</span> {redirectUri}
</p>
</div>
{error ? <p className="mt-4 text-sm text-red-600">{error}</p> : null}
<div className="mt-6 flex flex-col gap-3 sm:flex-row">
<Button className="flex-1 rounded-xl" disabled={submitting} onClick={() => void approve()}>
{submitting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
Разрешить
</Button>
<Button variant="outline" className="flex-1 rounded-xl" disabled={submitting} onClick={() => router.push('/')}>
Отмена
</Button>
</div>
</div>
</div>
);
}
export default function OAuthAuthorizePage() {
return (
<Suspense
fallback={
<div className="flex min-h-[60vh] items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-[#667085]" />
</div>
}
>
<OAuthAuthorizeContent />
</Suspense>
);
}

View File

@@ -5,17 +5,22 @@ import { FamilyGroupView } from '@/components/family/family-group-view';
import { useFamilyOverlay } from '@/components/family/family-overlay-provider';
import { IdShell } from '@/components/id/shell';
export default function FamilyGroupPage({ params }: { params: Promise<{ groupId: string }> }) {
const { groupId } = use(params);
function FamilyGroupPageContent({ groupId }: { groupId: string }) {
const { setSelectedGroupId } = useFamilyOverlay();
useEffect(() => {
setSelectedGroupId(groupId);
}, [groupId, setSelectedGroupId]);
return <FamilyGroupView groupId={groupId} />;
}
export default function FamilyGroupPage({ params }: { params: Promise<{ groupId: string }> }) {
const { groupId } = use(params);
return (
<IdShell active="/family" wide>
<FamilyGroupView groupId={groupId} />
<FamilyGroupPageContent groupId={groupId} />
</IdShell>
);
}

View File

@@ -46,6 +46,20 @@ input {
background: var(--muted);
}
@keyframes chat-message-blink {
0%, 100% {
background-color: transparent;
}
25%, 75% {
background-color: rgb(51 144 236 / 18%);
}
}
.blink-highlight {
animation: chat-message-blink 0.55s ease-in-out 2;
border-radius: 18px;
}
.id-shadow {
box-shadow: 0 24px 70px rgb(22 26 43 / 12%);
}

View File

@@ -0,0 +1,181 @@
'use client';
import { useMemo, useState } from 'react';
import { Check, Copy, Loader2, Bot } from 'lucide-react';
import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { createManagedBot, getApiErrorMessage } from '@/lib/api';
import { cn } from '@/lib/utils';
type Step = 'name' | 'username' | 'done';
export function BotCreateMiniAppContent() {
const { token, user, isPinLocked } = useAuth();
const { showToast } = useToast();
const [step, setStep] = useState<Step>('name');
const [name, setName] = useState('');
const [username, setUsername] = useState('');
const [creating, setCreating] = useState(false);
const [createdBot, setCreatedBot] = useState<{ username: string; token: string; botId: string } | null>(null);
const canUse = Boolean(token && user && !isPinLocked);
const usernamePreview = useMemo(() => `${username.replace(/_bot$/i, '').trim()}_bot`, [username]);
async function handleCreate() {
if (!canUse) return;
const trimmedName = name.trim();
const trimmedUsername = username.replace(/_bot$/i, '').trim();
if (!trimmedName) {
showToast('Укажите название бота');
setStep('name');
return;
}
if (trimmedUsername.length < 5) {
showToast('Username должен содержать минимум 5 символов');
return;
}
setCreating(true);
try {
const response = await createManagedBot({ name: trimmedName, username: trimmedUsername }, token);
setCreatedBot({
username: response.bot?.username ?? usernamePreview,
token: response.token ?? '',
botId: response.bot?.id ?? ''
});
setStep('done');
showToast('Бот успешно создан');
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось создать бота') ?? 'Ошибка');
} finally {
setCreating(false);
}
}
async function copyToken() {
if (!createdBot?.token) return;
await navigator.clipboard.writeText(createdBot.token);
showToast('Токен скопирован');
}
if (!canUse) {
return (
<div className="flex min-h-screen items-center justify-center p-6 text-center text-sm text-[#667085]">
Войдите в Lendry ID, чтобы создать бота
</div>
);
}
return (
<div className="min-h-screen bg-[#17212b] p-4 text-white">
<div className="mx-auto max-w-md space-y-5 rounded-[24px] bg-[#242f3d] p-5 shadow-xl">
<div className="flex items-center gap-3">
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-[#3390ec]/20 text-[#3390ec]">
<Bot className="h-6 w-6" />
</div>
<div>
<h1 className="text-lg font-semibold">Создание бота</h1>
<p className="text-sm text-[#8b93a7]">Как в BotFather Telegram</p>
</div>
</div>
<div className="flex items-center gap-2 text-xs text-[#8b93a7]">
{(['name', 'username', 'done'] as Step[]).map((item, index) => (
<div key={item} className="flex items-center gap-2">
<span
className={cn(
'flex h-6 w-6 items-center justify-center rounded-full',
step === item || (step === 'done' && item !== 'done') || (item === 'name' && step !== 'name')
? 'bg-[#3390ec] text-white'
: 'bg-[#17212b] text-[#8b93a7]'
)}
>
{step === 'done' && item !== 'done' ? <Check className="h-3.5 w-3.5" /> : index + 1}
</span>
{index < 2 ? <span className="h-px w-8 bg-[#2a3544]" /> : null}
</div>
))}
</div>
{step === 'name' ? (
<div className="space-y-4">
<p className="text-sm leading-relaxed text-[#c5cad3]">
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
</p>
<p className="text-sm text-[#8b93a7]">Хорошо, новый бот. Как мы его назовём? Выберите название.</p>
<Input
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="Например: Сервис уведомлений"
className="rounded-xl border-[#2a3544] bg-[#17212b] text-white placeholder:text-[#667085]"
autoFocus
/>
<Button className="w-full rounded-xl" disabled={!name.trim()} onClick={() => setStep('username')}>
Далее
</Button>
</div>
) : null}
{step === 'username' ? (
<div className="space-y-4">
<p className="text-sm leading-relaxed text-[#c5cad3]">
Good. Now let&apos;s choose a username for your bot. It must end in `bot`.
</p>
<p className="text-sm text-[#8b93a7]">Username должен заканчиваться на `_bot` (суффикс добавится автоматически).</p>
<div className="flex items-center gap-2">
<span className="text-[#8b93a7]">@</span>
<Input
value={username}
onChange={(event) => setUsername(event.target.value.replace(/[^a-zA-Z0-9_]/g, ''))}
placeholder="notify_service"
className="rounded-xl border-[#2a3544] bg-[#17212b] text-white placeholder:text-[#667085]"
autoFocus
/>
</div>
<p className="text-xs text-[#8b93a7]">Будет: @{usernamePreview || 'your_bot'}</p>
<div className="flex gap-2">
<Button variant="secondary" className="flex-1 rounded-xl bg-[#17212b] text-white hover:bg-[#1c2733]" onClick={() => setStep('name')}>
Назад
</Button>
<Button className="flex-1 rounded-xl" disabled={creating || username.replace(/_bot$/i, '').trim().length < 5} onClick={() => void handleCreate()}>
{creating ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
Создать бота
</Button>
</div>
</div>
) : null}
{step === 'done' && createdBot ? (
<div className="space-y-4">
<div className="rounded-2xl bg-[#17212b] p-4">
<p className="text-sm text-[#8b93a7]">Done! Congratulations on your new bot.</p>
<p className="mt-2 text-base font-semibold">@{createdBot.username}</p>
<p className="mt-3 text-sm text-red-300">Сохраните токен он больше не будет показан:</p>
<div className="mt-2 flex items-center gap-2">
<Input value={createdBot.token} readOnly className="rounded-xl border-[#2a3544] bg-[#242f3d] font-mono text-xs text-white" />
<Button type="button" variant="secondary" className="rounded-xl bg-[#3390ec] text-white hover:bg-[#2b7fd4]" onClick={() => void copyToken()}>
<Copy className="h-4 w-4" />
</Button>
</div>
</div>
<Button
className="w-full rounded-xl"
variant="secondary"
onClick={() => {
setStep('name');
setName('');
setUsername('');
setCreatedBot(null);
}}
>
Создать ещё одного бота
</Button>
</div>
) : null}
</div>
</div>
);
}

View File

@@ -0,0 +1,16 @@
'use client';
import { Suspense } from 'react';
import { BotCreateMiniAppContent } from './content';
export default function BotCreateMiniAppPage() {
return (
<Suspense
fallback={
<div className="flex min-h-screen items-center justify-center p-6 text-sm text-[#667085]">Загрузка...</div>
}
>
<BotCreateMiniAppContent />
</Suspense>
);
}

View File

@@ -0,0 +1,371 @@
'use client';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { Copy, ImageIcon, LayoutGrid, Loader2, RefreshCw, TextQuote, UserCircle2 } from 'lucide-react';
import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
fetchBot,
getApiErrorMessage,
revokeManagedBotToken,
updateManagedBot,
updateManagedBotProfile
} from '@/lib/api';
import { parseComposerMenuButtonJson } from '@/lib/bot-menu-button';
function FieldTextarea({
label,
hint,
value,
onChange,
maxLength,
rows = 3
}: {
label: string;
hint?: string;
value: string;
onChange: (value: string) => void;
maxLength?: number;
rows?: number;
}) {
return (
<div className="space-y-2">
<label className="text-sm font-medium">{label}</label>
{hint ? <p className="text-xs text-[#667085]">{hint}</p> : null}
<textarea
value={value}
onChange={(event) => onChange(event.target.value)}
maxLength={maxLength}
rows={rows}
className="w-full resize-y rounded-xl border border-[#dce3ec] bg-white px-3 py-2 text-sm outline-none transition focus:border-[#3390ec] focus:ring-2 focus:ring-[#3390ec]/15"
/>
{maxLength ? <p className="text-right text-xs text-[#a8adbc]">{value.length}/{maxLength}</p> : null}
</div>
);
}
function SectionCard({
icon: Icon,
title,
description,
children
}: {
icon: React.ComponentType<{ className?: string }>;
title: string;
description: string;
children: React.ReactNode;
}) {
return (
<section className="space-y-4 rounded-[20px] border border-[#eceef4] bg-[#fafbfc] p-4">
<div className="flex items-start gap-3">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-[#3390ec]/10 text-[#3390ec]">
<Icon className="h-5 w-5" />
</div>
<div>
<h2 className="font-semibold">{title}</h2>
<p className="text-sm text-[#667085]">{description}</p>
</div>
</div>
{children}
</section>
);
}
export function BotManageMiniAppContent() {
const searchParams = useSearchParams();
const botId = searchParams.get('botId') ?? '';
const { token, user, isPinLocked } = useAuth();
const { showToast } = useToast();
const [loading, setLoading] = useState(true);
const [savingBasic, setSavingBasic] = useState(false);
const [savingProfile, setSavingProfile] = useState(false);
const [revoking, setRevoking] = useState(false);
const [name, setName] = useState('');
const [username, setUsername] = useState('');
const [description, setDescription] = useState('');
const [aboutText, setAboutText] = useState('');
const [botPicUrl, setBotPicUrl] = useState('');
const [menuButtonUrl, setMenuButtonUrl] = useState('');
const [menuButtonText, setMenuButtonText] = useState('App');
const [tokenPrefix, setTokenPrefix] = useState('');
const [newToken, setNewToken] = useState<string | null>(null);
const canUse = Boolean(token && user && !isPinLocked && botId);
const loadBot = useCallback(async () => {
if (!canUse) return;
setLoading(true);
try {
const bot = await fetchBot(botId, token);
setName(bot.name);
setUsername(bot.username);
setDescription(bot.description ?? '');
setAboutText(bot.aboutText ?? '');
setBotPicUrl(bot.botPicUrl ?? '');
setTokenPrefix(bot.tokenPrefix ?? '');
const menuButton = parseComposerMenuButtonJson(bot.menuButtonJson);
if (menuButton) {
setMenuButtonUrl(menuButton.web_app.url);
setMenuButtonText(menuButton.text);
} else {
setMenuButtonUrl('');
setMenuButtonText('App');
}
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось загрузить бота') ?? 'Ошибка');
} finally {
setLoading(false);
}
}, [botId, canUse, showToast, token]);
useEffect(() => {
void loadBot();
}, [loadBot]);
const usernameWithoutSuffix = useMemo(() => username.replace(/_bot$/i, ''), [username]);
async function handleSaveBasic() {
if (!canUse) return;
setSavingBasic(true);
try {
const bot = await updateManagedBot(
botId,
{
name: name.trim(),
username: usernameWithoutSuffix.trim()
},
token
);
setName(bot.name);
setUsername(bot.username);
showToast('Основные настройки сохранены');
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось сохранить настройки') ?? 'Ошибка');
} finally {
setSavingBasic(false);
}
}
async function handleSaveProfile() {
if (!canUse) return;
setSavingProfile(true);
try {
const bot = await updateManagedBotProfile(
botId,
{
description: description.trim(),
aboutText: aboutText.trim(),
botPicUrl: botPicUrl.trim(),
menuButtonUrl: menuButtonUrl.trim(),
menuButtonText: menuButtonText.trim() || 'App'
},
token
);
setDescription(bot.description ?? '');
setAboutText(bot.aboutText ?? '');
setBotPicUrl(bot.botPicUrl ?? '');
const menuButton = parseComposerMenuButtonJson(bot.menuButtonJson);
if (menuButton) {
setMenuButtonUrl(menuButton.web_app.url);
setMenuButtonText(menuButton.text);
}
showToast('Профиль бота обновлён');
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось обновить профиль') ?? 'Ошибка');
} finally {
setSavingProfile(false);
}
}
async function handleRevokeToken() {
if (!canUse) return;
setRevoking(true);
try {
const response = await revokeManagedBotToken(botId, token);
setNewToken(response.token ?? null);
setTokenPrefix(response.bot?.tokenPrefix ?? tokenPrefix);
showToast('Токен перевыпущен');
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось перевыпустить токен') ?? 'Ошибка');
} finally {
setRevoking(false);
}
}
async function copyToken() {
if (!newToken) return;
await navigator.clipboard.writeText(newToken);
showToast('Токен скопирован');
}
if (!botId) {
return <div className="flex min-h-screen items-center justify-center p-6 text-sm text-[#667085]">Не указан botId</div>;
}
if (!canUse) {
return (
<div className="flex min-h-screen items-center justify-center p-6 text-center text-sm text-[#667085]">
Войдите в Lendry ID, чтобы управлять ботом
</div>
);
}
return (
<div className="min-h-screen bg-[#f4f5f8] p-4 pb-8">
<div className="mx-auto max-w-lg space-y-4">
<div className="rounded-[24px] bg-white p-5 shadow-sm">
<h1 className="text-lg font-semibold">Настройки бота</h1>
<p className="text-sm text-[#667085]">Интерактивное управление профилем аналог команд BotFather</p>
</div>
{loading ? (
<div className="flex items-center justify-center gap-2 rounded-[24px] bg-white p-8 text-sm text-[#667085] shadow-sm">
<Loader2 className="h-4 w-4 animate-spin" />
Загрузка...
</div>
) : (
<>
<div className="space-y-4 rounded-[24px] bg-white p-5 shadow-sm">
<SectionCard icon={UserCircle2} title="Основное" description="Название и username бота (/newbot)">
<div className="space-y-2">
<label className="text-sm font-medium">Название</label>
<Input value={name} onChange={(event) => setName(event.target.value)} className="rounded-xl" />
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Username</label>
<div className="flex items-center gap-2">
<span className="text-sm text-[#667085]">@</span>
<Input
value={usernameWithoutSuffix}
onChange={(event) => setUsername(`${event.target.value.replace(/_bot$/i, '')}_bot`)}
className="rounded-xl"
/>
</div>
</div>
<Button className="w-full rounded-xl" disabled={savingBasic} onClick={() => void handleSaveBasic()}>
{savingBasic ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
Сохранить основное
</Button>
</SectionCard>
</div>
<div className="space-y-4 rounded-[24px] bg-white p-5 shadow-sm">
<SectionCard
icon={TextQuote}
title="Профиль"
description="Описание и краткий текст — /setdescription и /setabouttext"
>
<FieldTextarea
label="Описание (/setdescription)"
hint="Показывается пользователю перед началом диалога"
value={description}
onChange={setDescription}
maxLength={512}
rows={4}
/>
<FieldTextarea
label="О боте (/setabouttext)"
hint="Краткое описание на странице профиля бота"
value={aboutText}
onChange={setAboutText}
maxLength={120}
rows={2}
/>
</SectionCard>
<SectionCard icon={ImageIcon} title="Аватар" description="URL изображения — /setuserpic">
<div className="space-y-3">
<Input
value={botPicUrl}
onChange={(event) => setBotPicUrl(event.target.value)}
placeholder="https://cdn.example.com/avatar.png"
className="rounded-xl"
/>
{botPicUrl.trim() ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={botPicUrl.trim()}
alt="Аватар бота"
className="h-16 w-16 rounded-full border border-[#dce3ec] object-cover"
onError={(event) => {
event.currentTarget.style.display = 'none';
}}
/>
) : null}
</div>
</SectionCard>
<SectionCard
icon={LayoutGrid}
title="Кнопка меню"
description="Глобальная Web App-кнопка слева от поля ввода — /setmenubutton"
>
<div className="space-y-2">
<label className="text-sm font-medium">URL Mini App</label>
<Input
value={menuButtonUrl}
onChange={(event) => setMenuButtonUrl(event.target.value)}
placeholder="https://app.example.com/webapp"
className="rounded-xl"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Текст кнопки</label>
<Input
value={menuButtonText}
onChange={(event) => setMenuButtonText(event.target.value)}
placeholder="App"
className="rounded-xl"
/>
</div>
<p className="text-xs text-[#667085]">Оставьте URL пустым, чтобы сбросить кнопку меню.</p>
</SectionCard>
<Button className="w-full rounded-xl" disabled={savingProfile} onClick={() => void handleSaveProfile()}>
{savingProfile ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
Сохранить профиль
</Button>
</div>
<div className="space-y-4 rounded-[24px] bg-white p-5 shadow-sm">
<h2 className="font-semibold">Токен Bot API</h2>
<div className="rounded-2xl bg-[#f4f5f8] px-3 py-3 text-sm text-[#667085]">
Текущий префикс: <span className="font-mono text-[#1f2430]">{tokenPrefix || '—'}</span>
</div>
{newToken ? (
<div className="space-y-2 rounded-2xl border border-[#dce3ec] p-3">
<p className="text-sm font-medium text-red-600">Сохраните новый токен он больше не будет показан</p>
<div className="flex items-center gap-2">
<Input value={newToken} readOnly className="rounded-xl font-mono text-xs" />
<Button type="button" variant="secondary" className="rounded-xl" onClick={() => void copyToken()}>
<Copy className="h-4 w-4" />
</Button>
</div>
</div>
) : null}
<Button variant="secondary" className="w-full rounded-xl" disabled={revoking} onClick={() => void handleRevokeToken()}>
{revoking ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <RefreshCw className="mr-2 h-4 w-4" />}
Перевыпустить токен
</Button>
</div>
<div className="rounded-[20px] border border-dashed border-[#dce3ec] bg-white/70 p-4 text-xs leading-relaxed text-[#667085]">
<p className="mb-2 font-medium text-[#1f2430]">Эквивалент команд BotFather</p>
<ul className="space-y-1">
<li>/setdescription поле «Описание»</li>
<li>/setabouttext поле «О боте»</li>
<li>/setuserpic URL аватара</li>
<li>/setmenubutton URL и текст кнопки меню</li>
</ul>
</div>
</>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,20 @@
import { Suspense } from 'react';
import { Loader2 } from 'lucide-react';
import { BotManageMiniAppContent } from './content';
function BotManageFallback() {
return (
<div className="flex min-h-screen items-center justify-center p-6 text-sm text-[#667085]">
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Загрузка Mini App...
</div>
);
}
export default function BotManageMiniAppPage() {
return (
<Suspense fallback={<BotManageFallback />}>
<BotManageMiniAppContent />
</Suspense>
);
}