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,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>
);
}