diff --git a/src/pages/telephony/components/ReportPopover.tsx b/src/components/ui/ReportPopover.tsx similarity index 100% rename from src/pages/telephony/components/ReportPopover.tsx rename to src/components/ui/ReportPopover.tsx diff --git a/src/lib/telephony.ts b/src/lib/telephony.ts index 54dfac6..de0eb92 100644 --- a/src/lib/telephony.ts +++ b/src/lib/telephony.ts @@ -1,5 +1,5 @@ // ВАЖНО: пути и поля — предположение. Подставьте реальные эндпоинты бэкенда. -import { api } from '@/api/client' // ваш axios-инстанс +import api from '@/api/client' export type ReportType = 'call' | 'sms' | 'chat' export type Channel = 'telegram' | 'whatsapp' | 'max' diff --git a/src/pages/telephony/TelephonyPage.tsx b/src/pages/telephony/TelephonyPage.tsx index c4682f4..4c31ade 100644 --- a/src/pages/telephony/TelephonyPage.tsx +++ b/src/pages/telephony/TelephonyPage.tsx @@ -19,7 +19,7 @@ import { PageHeader } from '@/components/ui/PageHeader' import { FilterBar } from '@/components/ui/FilterBar' import { DataTable, type Column } from '@/components/ui/DataTable' import { ReportPopover, type DateRange } from '@/components/ui/ReportPopover' -import { telephonyApi, type Channel, type ChatMessage, type ReportParams, type ReportRow } from '@/api/telephony' +import { telephonyApi, type Channel, type ChatMessage, type ReportParams, type ReportRow } from '@/lib/telephony' import { formatMsk } from '@/utils/date' import { useDeleteTelegramManager, useTelegramManagers } from '@/features/telegramManagers/useTelegramManagers' import { useDeleteWhatsAppManager, useWhatsAppManagers } from '@/features/whatsappManagers/useWhatsappManagers' @@ -153,7 +153,7 @@ function ReportView({ onTotal }: { onTotal: (n: number | undefined) => void }) { const { data: tg } = useTelegramManagers() const { data: wa } = useWhatsAppManagers() const managerOptions = useMemo( - () => [...new Set([...(tg ?? []), ...(wa ?? [])].map((m) => m.name))].sort(), + () => [...new Set(([...(tg ?? []), ...(wa ?? [])] as ManagerSession[]).map((m) => m.name))].sort(), [tg, wa], ) @@ -312,8 +312,8 @@ function ManagersView({ onOnline }: { onOnline: (s: string | undefined) => void const rows = useMemo( () => [ - ...(tg ?? []).map((m) => ({ ...m, channel: 'telegram' as const })), - ...(wa ?? []).map((m) => ({ ...m, channel: 'whatsapp' as const })), + ...(tg ?? []).map((m: ManagerSession) => ({ ...m, channel: 'telegram' as const })), + ...(wa ?? []).map((m: ManagerSession) => ({ ...m, channel: 'whatsapp' as const })), ], [tg, wa], ) diff --git a/src/pages/telephony/components/AddManagerModal.tsx b/src/pages/telephony/components/AddManagerModal.tsx new file mode 100644 index 0000000..c3a4089 --- /dev/null +++ b/src/pages/telephony/components/AddManagerModal.tsx @@ -0,0 +1,209 @@ +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, IconQrcode, IconMessageCircle } from '@tabler/icons-react' +import { useQueryClient } from '@tanstack/react-query' +import {telegramManagersApi} from "@/api/telegramManagers.ts"; + +interface AddManagerModalProps { + opened: boolean + onClose: () => void +} + +export default function AddManagerModal({ opened, onClose }: AddManagerModalProps) { + 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({ + initialValues: { + phone: '', + name: '', + code: '', + password: '', + }, + }) + + // ── ЛОГИКА АВТОРИЗАЦИИ ПО НОМЕРУ ────────────────────────────── + const handleSendCode = async (values: typeof form.values) => { + setLoadingPhone(true) + try { + await telegramManagersApi.sendCode(values.phone, values.name) + notifications.show({ title: 'Код отправлен', message: 'Проверьте Telegram-аккаунт', color: 'green' }) + setStepPhone('code') + } catch (error: any) { + notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Не удалось отправить код', color: 'red' }) + } finally { + setLoadingPhone(false) + } + } + + const handleVerifyCode = async (values: typeof form.values) => { + setLoadingPhone(true) + try { + await telegramManagersApi.verifyCode(values.phone, values.code, values.password || undefined) + 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' }) + } finally { + 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 = () => { + setStepPhone('phone') + form.reset() + onClose() + } + + return ( + + + + }>По QR-коду + }>По номеру и коду + + + {/* ВКЛАДКА: QR КОД */} + + + + Откройте Telegram на телефоне менеджера → Настройки → Устройства → Подключить устройство, и отсканируйте этот код. + + +
+ {loadingQr ? ( + + ) : qrData ? ( + + ) : ( + + )} +
+ + {qrData && ( + // Визуальный индикатор ожидания сканирования + )} +
+
+ + {/* ВКЛАДКА: НОМЕР ТЕЛЕФОНА */} + + {stepPhone === 'phone' ? ( +
+ + + + + + + + +
+ ) : ( +
+ + } color="blue" variant="light"> + Код отправлен в официальное приложение Telegram на номер {form.values.phone} + + + + + + + + +
+ )} +
+
+
+ ) +} \ No newline at end of file diff --git a/src/pages/telephony/components/DeleteManagersModal.tsx b/src/pages/telephony/components/DeleteManagersModal.tsx new file mode 100644 index 0000000..5fd6aee --- /dev/null +++ b/src/pages/telephony/components/DeleteManagersModal.tsx @@ -0,0 +1,42 @@ +import {Button, Checkbox, Group, Modal, Stack, Text} from '@mantine/core' +import {useEffect, useState} from 'react' +import {ManagerSession} from "@/types/api.ts"; + +export default function DeleteManagerModal({ opened, onClose, manager, onConfirm, title }: { + opened: boolean, + onClose: () => void, + manager: ManagerSession | null, + onConfirm: (wipeData: boolean) => Promise, + title: string +}) { + const [wipeData, setWipeData] = useState(false) + const [loading, setLoading] = useState(false) + + useEffect(() => { if (opened) setWipeData(false) }, [opened]) + + const handleConfirm = async () => { + setLoading(true) + await onConfirm(wipeData) + setLoading(false) + onClose() + } + + return ( + + + Вы уверены, что хотите отключить сессию менеджера {manager?.name}? + setWipeData(event.currentTarget.checked)} + /> + + + + + + + ) +} \ No newline at end of file