From 97b77a3ea512f2656e06119314a98f2e0d176e7b Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Tue, 27 Oct 2026 17:00:15 +0300 Subject: [PATCH] Added QR auth method --- src/api/telegramManagers.ts | 6 + .../components/AddManagerModal.tsx | 219 +++++++++++++----- 2 files changed, 164 insertions(+), 61 deletions(-) diff --git a/src/api/telegramManagers.ts b/src/api/telegramManagers.ts index beb6402..3e9a5f3 100644 --- a/src/api/telegramManagers.ts +++ b/src/api/telegramManagers.ts @@ -21,4 +21,10 @@ export const telegramManagersApi = { delete: (managerId: number) => managerApiClient.delete(`/managers/${managerId}`), + + startQr: () => + managerApiClient.post('/managers/auth/qr/start'), + + checkQrStatus: (token: string) => + managerApiClient.get(`/managers/auth/qr/status?token=${token}`), } \ No newline at end of file diff --git a/src/pages/telegramManagers/components/AddManagerModal.tsx b/src/pages/telegramManagers/components/AddManagerModal.tsx index 6d07f2b..c3a4089 100644 --- a/src/pages/telegramManagers/components/AddManagerModal.tsx +++ b/src/pages/telegramManagers/components/AddManagerModal.tsx @@ -1,8 +1,8 @@ -import { useState } from 'react' -import { Modal, Stack, TextInput, Button, Text, Alert, Group } from '@mantine/core' +import { useState, useEffect, useRef } from 'react' +import { Modal, Stack, TextInput, Button, Text, Alert, Group, Tabs, Image, Center, Loader } from '@mantine/core' import { useForm } from '@mantine/form' import { notifications } from '@mantine/notifications' -import { IconDeviceMobile, IconLock } from '@tabler/icons-react' +import { IconDeviceMobile, IconQrcode, IconMessageCircle } from '@tabler/icons-react' import { useQueryClient } from '@tanstack/react-query' import {telegramManagersApi} from "@/api/telegramManagers.ts"; @@ -12,8 +12,17 @@ interface AddManagerModalProps { } export default function AddManagerModal({ opened, onClose }: AddManagerModalProps) { - const [step, setStep] = useState<'phone' | 'code'>('phone') - const [loading, setLoading] = useState(false) + const [activeTab, setActiveTab] = useState('qr') + + // Состояния для авторизации по номеру + const [stepPhone, setStepPhone] = useState<'phone' | 'code'>('phone') + const [loadingPhone, setLoadingPhone] = useState(false) + + // Состояния для авторизации по QR + const [qrData, setQrData] = useState<{ token: string, img: string } | null>(null) + const [loadingQr, setLoadingQr] = useState(false) + const pollingIntervalRef = useRef(null) + const queryClient = useQueryClient() const form = useForm({ @@ -25,88 +34,176 @@ export default function AddManagerModal({ opened, onClose }: AddManagerModalProp }, }) + // ── ЛОГИКА АВТОРИЗАЦИИ ПО НОМЕРУ ────────────────────────────── const handleSendCode = async (values: typeof form.values) => { - setLoading(true) + setLoadingPhone(true) try { await telegramManagersApi.sendCode(values.phone, values.name) - notifications.show({ title: 'Код отправлен', message: 'Проверьте Telegram-аккаунт менеджера', color: 'green' }) - setStep('code') + notifications.show({ title: 'Код отправлен', message: 'Проверьте Telegram-аккаунт', color: 'green' }) + setStepPhone('code') } catch (error: any) { notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Не удалось отправить код', color: 'red' }) } finally { - setLoading(false) + setLoadingPhone(false) } } const handleVerifyCode = async (values: typeof form.values) => { - setLoading(true) + setLoadingPhone(true) try { await telegramManagersApi.verifyCode(values.phone, values.code, values.password || undefined) - notifications.show({ title: 'Успешно', message: 'Менеджер успешно авторизован и добавлен', color: 'green' }) + notifications.show({ title: 'Успешно', message: 'Менеджер подключен', color: 'green' }) queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] }) handleClose() } catch (error: any) { - notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Неверный код или ошибка входа', color: 'red' }) + notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Неверный код', color: 'red' }) } finally { - setLoading(false) + setLoadingPhone(false) } } + // ── ЛОГИКА АВТОРИЗАЦИИ ПО QR ────────────────────────────────── + const fetchQr = async () => { + setLoadingQr(true) + stopPolling() + try { + const res = await telegramManagersApi.startQr() + setQrData({ token: res.data.token, img: res.data.qr_base64 }) + startPolling(res.data.token) + } catch (error: any) { + notifications.show({ title: 'Ошибка', message: 'Не удалось сгенерировать QR-код', color: 'red' }) + } finally { + setLoadingQr(false) + } + } + + const startPolling = (token: string) => { + pollingIntervalRef.current = window.setInterval(async () => { + try { + const res = await telegramManagersApi.checkQrStatus(token) + if (res.data.status === 'success') { + stopPolling() + notifications.show({ title: 'Успешно', message: `Менеджер ${res.data.name} подключен!`, color: 'green' }) + queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] }) + handleClose() + } else if (res.data.status === 'failed') { + stopPolling() + notifications.show({ title: 'Ошибка', message: res.data.error || 'Ошибка сканирования', color: 'red' }) + setQrData(null) // Сбрасываем QR, чтобы пользователь мог запросить новый + } + } catch (err) { + stopPolling() + } + }, 3000) // Проверяем статус каждые 3 секунды + } + + const stopPolling = () => { + if (pollingIntervalRef.current) { + clearInterval(pollingIntervalRef.current) + pollingIntervalRef.current = null + } + } + + // Обработка открытия/закрытия модалки + useEffect(() => { + if (opened && activeTab === 'qr' && !qrData) { + fetchQr() + } + if (!opened) { + stopPolling() + setQrData(null) + } + return stopPolling + }, [opened, activeTab]) + const handleClose = () => { - setStep('phone') + setStepPhone('phone') form.reset() onClose() } return ( - - {step === 'phone' ? ( -
- - - - - - - + + + + }>По QR-коду + }>По номеру и коду + + + {/* ВКЛАДКА: QR КОД */} + + + + Откройте Telegram на телефоне менеджера → Настройки → Устройства → Подключить устройство, и отсканируйте этот код. + + +
+ {loadingQr ? ( + + ) : qrData ? ( + + ) : ( + + )} +
+ + {qrData && ( + // Визуальный индикатор ожидания сканирования + )}
- - ) : ( -
- - } color="blue" variant="light"> - Код подтверждения отправлен в официальное приложение Telegram на номер {form.values.phone} - - - - - - - - -
- )} +
+ + {/* ВКЛАДКА: НОМЕР ТЕЛЕФОНА */} + + {stepPhone === 'phone' ? ( +
+ + + + + + + + +
+ ) : ( +
+ + } color="blue" variant="light"> + Код отправлен в официальное приложение Telegram на номер {form.values.phone} + + + + + + + + +
+ )} +
+
) } \ No newline at end of file