Updated telephony page
Deploy Frontend / build-and-deploy (push) Successful in 32s Details

This commit is contained in:
romanskijdev 2026-11-18 14:13:08 +03:00
parent 5d5e5e2ebb
commit 4d24ff36b4
5 changed files with 256 additions and 5 deletions

View File

@ -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'

View File

@ -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<Row[]>(
() => [
...(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],
)

View File

@ -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<string | null>('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<number | null>(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 (
<Modal opened={opened} onClose={handleClose} title="Подключение менеджера Telegram" size="md">
<Tabs value={activeTab} onChange={setActiveTab}>
<Tabs.List mb="md">
<Tabs.Tab value="qr" leftSection={<IconQrcode size={16} />}>По QR-коду</Tabs.Tab>
<Tabs.Tab value="phone" leftSection={<IconMessageCircle size={16} />}>По номеру и коду</Tabs.Tab>
</Tabs.List>
{/* ВКЛАДКА: QR КОД */}
<Tabs.Panel value="qr">
<Stack gap="md" align="center">
<Text size="sm" c="dimmed" ta="center">
Откройте Telegram на телефоне менеджера → Настройки → Устройства → Подключить устройство, и отсканируйте этот код.
</Text>
<Center style={{ width: 250, height: 250, border: '1px solid #eee', borderRadius: 8 }}>
{loadingQr ? (
<Loader />
) : qrData ? (
<Image src={qrData.img} w={230} h={230} fit="contain" />
) : (
<Button variant="light" onClick={fetchQr}>Сгенерировать новый QR</Button>
)}
</Center>
{qrData && (
<Loader type="dots" size="sm" /> // Визуальный индикатор ожидания сканирования
)}
</Stack>
</Tabs.Panel>
{/* ВКЛАДКА: НОМЕР ТЕЛЕФОНА */}
<Tabs.Panel value="phone">
{stepPhone === 'phone' ? (
<form onSubmit={form.onSubmit(handleSendCode)}>
<Stack gap="md">
<TextInput
label="Имя менеджера"
placeholder="Иван Иванов"
required
{...form.getInputProps('name')}
/>
<TextInput
label="Номер телефона"
placeholder="+79991234567"
required
description="В международном формате с плюсом"
{...form.getInputProps('phone')}
/>
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={handleClose}>Отмена</Button>
<Button type="submit" loading={loadingPhone}>Далее (Запросить код)</Button>
</Group>
</Stack>
</form>
) : (
<form onSubmit={form.onSubmit(handleVerifyCode)}>
<Stack gap="md">
<Alert icon={<IconDeviceMobile size={16} />} color="blue" variant="light">
Код отправлен в официальное приложение Telegram на номер {form.values.phone}
</Alert>
<TextInput
label="Код из Telegram"
placeholder="12345"
required
{...form.getInputProps('code')}
/>
<TextInput
label="Облачный пароль 2FA (если установлен)"
placeholder="Пароль двухэтапной аутентификации"
type="password"
{...form.getInputProps('password')}
/>
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={() => setStepPhone('phone')}>Назад</Button>
<Button type="submit" loading={loadingPhone} color="green">Подтвердить и войти</Button>
</Group>
</Stack>
</form>
)}
</Tabs.Panel>
</Tabs>
</Modal>
)
}

View File

@ -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<void>,
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 (
<Modal opened={opened} onClose={onClose} title={title} size="sm">
<Stack gap="md">
<Text size="sm">Вы уверены, что хотите отключить сессию менеджера <b>{manager?.name}</b>?</Text>
<Checkbox
label="Полностью удалить историю переписки"
description="Если не отмечать, сессия отключится, но чаты останутся в архиве БД"
color="red"
checked={wipeData}
onChange={(event) => setWipeData(event.currentTarget.checked)}
/>
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose} disabled={loading}>Отмена</Button>
<Button color="red" onClick={handleConfirm} loading={loading}>Отключить</Button>
</Group>
</Stack>
</Modal>
)
}