diff --git a/result.txt b/result.txt index e68b809..ad67e63 100644 --- a/result.txt +++ b/result.txt @@ -184,7 +184,7 @@ │ │ ├── settings │ │ │ ├── SettingsPage.tsx │ │ ├── telegramManagers -│ │ │ ├── TelegramManagersPage.tsx +│ │ │ ├── TelephonyPage.tsx │ │ │ ├── components │ │ │ │ ├── AddManagerModal.tsx │ │ │ │ ├── DeleteManagersModal.tsx diff --git a/src/App.tsx b/src/App.tsx index bcccc15..c35d37a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -22,7 +22,7 @@ import FlowTreeGuidePage from './pages/flowNodes/FlowTreeGuidePage' import NotificationsPage from "@/pages/notifications/NotificationsPage.tsx" import AdminLogsPage from './pages/adminLogs/AdminLogsPage' import MonthlyOrdersSettingsPage from "@/pages/monthlyOrders/MonthlyOrdersSettingsPage.tsx"; -import TelegramManagersPage from "@/pages/telegramManagers/TelegramManagersPage.tsx"; +import TelephonyPage from "@/pages/telephony/TelephonyPage.tsx"; const Placeholder = ({ title }: { title: string }) => (
@@ -74,7 +74,7 @@ function App() { } /> } /> } /> - } /> + } /> ) diff --git a/src/lib/telephony.ts b/src/lib/telephony.ts new file mode 100644 index 0000000..54dfac6 --- /dev/null +++ b/src/lib/telephony.ts @@ -0,0 +1,40 @@ +// ВАЖНО: пути и поля — предположение. Подставьте реальные эндпоинты бэкенда. +import { api } from '@/api/client' // ваш axios-инстанс + +export type ReportType = 'call' | 'sms' | 'chat' +export type Channel = 'telegram' | 'whatsapp' | 'max' + +export interface ReportRow { + id: string + type: ReportType + channel?: Channel | null // только для type = 'chat' + started_at: string // ISO; дата и время из таблицы одним полем + direction: 'in' | 'out' + phone: string + contact_name?: string | null + company?: string | null + value: number // звонок — секунды, SMS/чат — число сообщений + answered: boolean + recording_url?: string | null // звонок + last_message?: string | null // SMS / чат + manager: string + manager_id?: number | null + status: string // «Отвечен», «Пропущен, перезвон не совершен», … +} + +export interface ReportParams { + offset?: number; limit?: number + type?: ReportType; manager?: string; direction?: 'in' | 'out' + status?: string; content?: string; date_from?: string; date_to?: string +} + +export interface ChatMessage { id: string; direction: 'in' | 'out'; text: string; at: string; author?: string } + +export const telephonyApi = { + list: (params: ReportParams) => + api.get<{ data: ReportRow[]; total_count: number }>('/telephony/report', { params }).then((r) => r.data), + messages: (id: string) => + api.get<{ data: ChatMessage[] }>(`/telephony/report/${id}/messages`).then((r) => r.data.data), + download: (params: ReportParams) => + api.get('/telephony/report/xlsx', { params, responseType: 'blob' }).then((r) => r.data as BlobPart), +} \ No newline at end of file diff --git a/src/pages/telegramManagers/TelegramManagersPage.tsx b/src/pages/telegramManagers/TelegramManagersPage.tsx deleted file mode 100644 index 9fa1d99..0000000 --- a/src/pages/telegramManagers/TelegramManagersPage.tsx +++ /dev/null @@ -1,411 +0,0 @@ -import { useState, useEffect, useRef } from 'react' -import { - Paper, - Table, - Badge, - Group, - ActionIcon, - Button, - Text, - Loader, - Center, - Tooltip, - Stack, - Box, - Tabs, - Alert, - Modal, - Image, - TextInput, - Checkbox -} from '@mantine/core' -import { - IconTrash, - IconPlus, - IconCircleCheck, - IconCircleX, - IconBrandTelegram, - IconBrandWhatsapp, - IconMessageCircle, - IconInfoCircle, - IconEdit, - IconMessage2 -} from '@tabler/icons-react' -import { notifications } from '@mantine/notifications' -import { useQueryClient } from '@tanstack/react-query' -import dayjs from 'dayjs' -import 'dayjs/locale/ru' -import { formatMsk } from '@/utils/date.ts' - -// Импорты Telegram -import AddManagerModal from './components/AddManagerModal' -import DeleteManagerModal from "./components/DeleteManagersModal" -import { useDeleteTelegramManager, useTelegramManagers } from "@/features/telegramManagers/useTelegramManagers" -import { telegramManagersApi } from '@/api/telegramManagers' - -// Импорты WhatsApp -import { useDeleteWhatsAppManager, useWhatsAppManagers } from '@/features/whatsappManagers/useWhatsappManagers' -import { whatsappManagersApi } from "@/api/whatsappManagers.ts" -import {ManagerSession} from "@/types/api.ts"; - -dayjs.locale('ru') - -// ── ПЕРЕИСПОЛЬЗУЕМЫЕ КОМПОНЕНТЫ ───────────────────────────────────────────── - -interface ManagersTableProps { - managers: ManagerSession[] | undefined; - isLoading: boolean; - onDelete: (manager: ManagerSession) => void; - onEdit: (manager: ManagerSession) => void; - onViewChats: (manager: ManagerSession) => void; - emptyText?: string; -} - -function ManagersTable({ managers, isLoading, onDelete, onEdit, onViewChats, emptyText = "Менеджеры не найдены" }: ManagersTableProps) { - if (isLoading) return
; - - return ( - - - - ID - Имя - Телефон - Статус сессии - Последнее входящее - Последнее исходящее - Действия - - - - {!managers || managers.length === 0 ? ( - - -
{emptyText}
-
-
- ) : ( - managers.map((mgr) => ( - - - {mgr.manager_id} - - {mgr.name} - +{mgr.phone} - - : } - > - {mgr.is_online ? 'Онлайн' : 'Оффлайн'} - - - - {mgr.last_incoming_message_at ? formatMsk(mgr.last_incoming_message_at) : '—'} - - - {mgr.last_outgoing_message_at ? formatMsk(mgr.last_outgoing_message_at) : '—'} - - - - - onViewChats(mgr)}> - - - - - onEdit(mgr)}> - - - - - onDelete(mgr)}> - - - - - - - )) - )} -
-
- ); -} - -function EditManagerModal({ opened, onClose, manager, onSave }: { opened: boolean, onClose: () => void, manager: ManagerSession | null, onSave: (name: string) => Promise }) { - const [name, setName] = useState('') - const [loading, setLoading] = useState(false) - - useEffect(() => { - if (manager) setName(manager.name) - }, [manager]) - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault() - setLoading(true) - await onSave(name) - setLoading(false) - onClose() - } - - return ( - -
- - setName(e.currentTarget.value)} required /> - - - - - - -
-
- ) -} -// ── ВКЛАДКА TELEGRAM ──────────────────────────────────────────────────────── - -function TelegramTab() { - const [createModalOpened, setCreateModalOpened] = useState(false) - const [editingManager, setEditingManager] = useState(null) - const [deletingManager, setDeletingManager] = useState(null) - - const { data: managers, isLoading, isFetching } = useTelegramManagers() - const deleteManager = useDeleteTelegramManager() - const queryClient = useQueryClient() - - const confirmDelete = async (wipeData: boolean) => { - if (deletingManager) { - await deleteManager.mutateAsync({ managerId: Number(deletingManager.manager_id), wipeData }) - } - } - - const handleSaveName = async (newName: string) => { - if (!editingManager) return - try { - await telegramManagersApi.updateName(Number(editingManager.manager_id), newName) - notifications.show({ title: 'Успешно', message: 'Имя обновлено', color: 'green' }) - queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] }) - } catch (e) { - notifications.show({ title: 'Ошибка', message: 'Не удалось обновить имя', color: 'red' }) - } - } - - const handleViewChats = (mgr: ManagerSession) => { - notifications.show({ title: 'Чаты', message: `Открытие переписки для ${mgr.name}...`, color: 'blue' }) - } - - return ( - - - Управление активными сессиями пользовательских Telegram аккаунтов - - - - - - - - {isFetching && !isLoading && } - - setCreateModalOpened(false)} /> - - setEditingManager(null)} - manager={editingManager} - onSave={handleSaveName} - /> - - setDeletingManager(null)} - manager={deletingManager} - onConfirm={confirmDelete} - title="Отключение Telegram" - /> - - ) -} - -function AddWhatsappModal({ opened, onClose }: { opened: boolean, onClose: () => void }) { - const [qrData, setQrData] = useState<{ token: string, img: string } | null>(null) - const pollingIntervalRef = useRef(null) - const queryClient = useQueryClient() - - const stopPolling = () => { - if (pollingIntervalRef.current) { - clearInterval(pollingIntervalRef.current) - pollingIntervalRef.current = null - } - } - - const fetchQr = async () => { - stopPolling() - try { - const res = await whatsappManagersApi.startQr() - setQrData({ token: res.data.token, img: '' }) - startPolling(res.data.token) - } catch (error) { - notifications.show({ title: 'Ошибка', message: 'Не удалось загрузить QR-код', color: 'red' }) - } - } - - const startPolling = (token: string) => { - pollingIntervalRef.current = window.setInterval(async () => { - try { - const res = await whatsappManagersApi.checkQrStatus(token) - if (res.data.status === 'pending' && res.data.qr) { - setQrData(prev => prev ? { ...prev, img: res.data.qr } : null) - } - else if (res.data.status === 'success') { - stopPolling() - notifications.show({ title: 'Успешно', message: 'WhatsApp подключен!', color: 'green' }) - queryClient.invalidateQueries({ queryKey: ['whatsapp-managers-status'] }) - onClose() - } - else if (res.data.status === 'failed') { - stopPolling() - notifications.show({ title: 'Ошибка', message: 'Ошибка сканирования', color: 'red' }) - setQrData(null) - } - } catch (err) {} - }, 2000) - } - - useEffect(() => { - if (opened && !qrData) fetchQr() - - if (!opened) { - stopPolling() - setQrData(null) - } - - return stopPolling - }, [opened]) - - return ( - { stopPolling(); onClose(); }} title="Сканируйте QR-код в WhatsApp" size="sm"> - - Настройки → Связанные устройства → Привязка устройства -
- {qrData?.img ? : } -
- {qrData && } -
-
- ) -} - -function WhatsappTab() { - const [createModalOpened, setCreateModalOpened] = useState(false) - const [editingManager, setEditingManager] = useState(null) - const [deletingManager, setDeletingManager] = useState(null) - - const { data: managers, isLoading, isFetching } = useWhatsAppManagers() - const deleteManager = useDeleteWhatsAppManager() - const queryClient = useQueryClient() - - const confirmDelete = async (wipeData: boolean) => { - if (deletingManager) { - await deleteManager.mutateAsync({ phone: deletingManager.phone, wipeData }) - } - } - - const handleSaveName = async (newName: string) => { - if (!editingManager) return - try { - await whatsappManagersApi.updateName(editingManager.phone, newName) - notifications.show({ title: 'Успешно', message: 'Имя обновлено', color: 'green' }) - queryClient.invalidateQueries({ queryKey: ['whatsapp-managers-status'] }) - } catch (e) { - notifications.show({ title: 'Ошибка', message: 'Не удалось обновить имя', color: 'red' }) - } - } - - const handleViewChats = (mgr: ManagerSession) => { - notifications.show({ title: 'Чаты', message: `Открытие переписки WhatsApp для ${mgr.name}...`, color: 'green' }) - } - - return ( - - - Управление активными сессиями пользовательских аккаунтов WhatsApp - - - - - - - - {isFetching && !isLoading && } - - setCreateModalOpened(false)} /> - - setEditingManager(null)} - manager={editingManager} - onSave={handleSaveName} - /> - - setDeletingManager(null)} - manager={deletingManager} - onConfirm={confirmDelete} - title="Отключение WhatsApp" - /> - - ) -} - -// ── ГЛАВНАЯ СТРАНИЦА ──────────────────────────────────────────────────────── - -export default function MessengersPage() { - const [activeTab, setActiveTab] = useState('telegram') - - return ( - -
- Интеграции мессенджеров - Подключение и мониторинг каналов связи менеджеров -
- - - - }>Telegram - }>WhatsApp - }>Max - - - - - - - - - } color="blue" variant="light"> - Интеграция с сервисом Max находится в стадии планирования. - - - - -
- ) -} \ No newline at end of file diff --git a/src/pages/telegramManagers/components/AddManagerModal.tsx b/src/pages/telegramManagers/components/AddManagerModal.tsx deleted file mode 100644 index c3a4089..0000000 --- a/src/pages/telegramManagers/components/AddManagerModal.tsx +++ /dev/null @@ -1,209 +0,0 @@ -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/telegramManagers/components/DeleteManagersModal.tsx b/src/pages/telegramManagers/components/DeleteManagersModal.tsx deleted file mode 100644 index 5fd6aee..0000000 --- a/src/pages/telegramManagers/components/DeleteManagersModal.tsx +++ /dev/null @@ -1,42 +0,0 @@ -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 diff --git a/src/pages/telephony/TelephonyPage.tsx b/src/pages/telephony/TelephonyPage.tsx new file mode 100644 index 0000000..c4682f4 --- /dev/null +++ b/src/pages/telephony/TelephonyPage.tsx @@ -0,0 +1,481 @@ +import { useEffect, useMemo, useState } from 'react' +import { + ActionIcon, Avatar, Badge, Box, Button, Drawer, Group, Menu, Popover, Select, Skeleton, Stack, Tabs, Text, + TextInput, ThemeIcon, +} from '@mantine/core' +import { DatePickerInput } from '@mantine/dates' +import { useDebouncedValue } from '@mantine/hooks' +import { notifications } from '@mantine/notifications' +import { + IconBrandTelegram, IconBrandWhatsapp, IconCalendar, IconDots, IconEdit, IconMessage, IconMessageCircle, + IconPhone, IconPhoneIncoming, IconPhoneOutgoing, IconPlayerPlay, IconPlus, IconSearch, IconTrash, + type Icon, +} from '@tabler/icons-react' +import { useQuery, useQueryClient } from '@tanstack/react-query' +import dayjs from 'dayjs' +import 'dayjs/locale/ru' + +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 { formatMsk } from '@/utils/date' +import { useDeleteTelegramManager, useTelegramManagers } from '@/features/telegramManagers/useTelegramManagers' +import { useDeleteWhatsAppManager, useWhatsAppManagers } from '@/features/whatsappManagers/useWhatsappManagers' +import { telegramManagersApi } from '@/api/telegramManagers' +import { whatsappManagersApi } from '@/api/whatsappManagers' +import type { ManagerSession } from '@/types/api' +// Эти три компонента нужно вынести из старой MessengersPage в отдельные файлы без изменений +import AddManagerModal from './components/AddManagerModal' +import DeleteManagerModal from './components/DeleteManagersModal' +import { AddWhatsappModal, EditManagerModal } from './components/ManagerModals' +import classes from '@/components/UserDrawer.module.css' + +dayjs.locale('ru') + +const LIMIT = 20 +const fmtDate = (d: Date) => dayjs(d).format('YYYY-MM-DD') + +const CHANNELS: Record = { + telegram: { label: 'Telegram', icon: IconBrandTelegram }, + whatsapp: { label: 'WhatsApp', icon: IconBrandWhatsapp }, + max: { label: 'Max', icon: IconMessageCircle }, +} + +const TYPE_OPTIONS = [ + { value: 'call', label: 'Звонки' }, + { value: 'sms', label: 'SMS' }, + { value: 'chat', label: 'Диалоги' }, +] +const DIRECTION_OPTIONS = [ + { value: 'in', label: 'Входящие' }, + { value: 'out', label: 'Исходящие' }, +] +// Статусы из выгрузки; сюда же добавятся статусы SMS и диалогов +const STATUS_OPTIONS = ['Отвечен', 'Пропущен, перезвон не совершен', 'Пропущен, перезвон совершен'] + +// Можно перенести в components/ui/statuses.ts как kind="call" +const statusColor = (s: string) => + s === 'Отвечен' ? 'green' : s.includes('не совершен') ? 'red' : s.includes('совершен') ? 'yellow' : 'gray' + +const fmtDuration = (sec: number) => `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}` + +/* ——— Отчёт ——— */ + +function PlayButton({ url }: { url: string }) { + const [opened, setOpened] = useState(false) + return ( + + + { e.stopPropagation(); setOpened((o) => !o) }}> + + + + e.stopPropagation()}> + {/* key заставляет плеер пересоздаться и остановиться при закрытии */} + + + ) +} + +function ConversationDrawer({ row, onClose }: { row: ReportRow | null; onClose: () => void }) { + const { data, isLoading } = useQuery({ + queryKey: ['telephony-messages', row?.id], + queryFn: () => telephonyApi.messages(row!.id), + enabled: !!row, + }) + const title = row?.contact_name && row.contact_name !== 'Неизвестно' ? row.contact_name : `+${row?.phone}` + + return ( + + + + + + {title} + + {row?.type === 'sms' ? 'SMS' : row?.channel ? CHANNELS[row.channel].label : 'Диалог'} + {row && ` · ${row.manager}`} + + + + + + + {isLoading ? ( + <> + ) : !data?.length ? ( + Сообщений нет + ) : ( + data.map((m: ChatMessage) => ( + + {m.text} + {formatMsk(m.at)} + + )) + )} + + + + + ) +} + +function ReportView({ onTotal }: { onTotal: (n: number | undefined) => void }) { + const [page, setPage] = useState(1) + const [searchInput, setSearchInput] = useState('') + const [debounced] = useDebouncedValue(searchInput.trim(), 400) + const search = debounced.length >= 2 ? debounced : '' + const [type, setType] = useState(null) + const [direction, setDirection] = useState(null) + const [status, setStatus] = useState(null) + const [manager, setManager] = useState(null) + const [range, setRange] = useState([dayjs().startOf('month').toDate(), null]) + const [open, setOpen] = useState(null) + + useEffect(() => setPage(1), [search, type, direction, status, manager, range]) + + // Менеджеры для фильтра берём из подключённых сессий + const { data: tg } = useTelegramManagers() + const { data: wa } = useWhatsAppManagers() + const managerOptions = useMemo( + () => [...new Set([...(tg ?? []), ...(wa ?? [])].map((m) => m.name))].sort(), + [tg, wa], + ) + + const filters = useMemo(() => { + const p: ReportParams = {} + if (search) p.content = search + if (type) p.type = type as ReportParams['type'] + if (direction) p.direction = direction as ReportParams['direction'] + if (status) p.status = status + if (manager) p.manager = manager + if (range[0]) p.date_from = fmtDate(range[0]) + if (range[1]) p.date_to = fmtDate(range[1]) + return p + }, [search, type, direction, status, manager, range]) + + const { data, isLoading, isFetching } = useQuery({ + queryKey: ['telephony-report', filters, page], + queryFn: () => telephonyApi.list({ ...filters, offset: (page - 1) * LIMIT, limit: LIMIT }), + placeholderData: (prev) => prev, + }) + const total = data?.total_count ?? 0 + useEffect(() => onTotal(isLoading ? undefined : total), [isLoading, total, onTotal]) + + const activeCount = [search, type, direction, status, manager, range[0] || range[1]].filter(Boolean).length + const reset = () => { + setSearchInput(''); setType(null); setDirection(null); setStatus(null); setManager(null); setRange([null, null]) + } + + const columns: Column[] = [ + { + key: 'when', + header: 'Дата', + width: 150, + cell: (r) => ( + + + {r.type === 'call' + ? (r.direction === 'in' ? : ) + : r.type === 'sms' ? + : r.channel ? (() => { const I = CHANNELS[r.channel].icon; return })() : } + + {formatMsk(r.started_at)} + + ), + }, + { + key: 'contact', + header: 'Контакт', + cell: (r) => { + const known = r.contact_name && r.contact_name !== 'Неизвестно' + return ( + + {known ? r.contact_name : `+${r.phone}`} + + {[known ? `+${r.phone}` : null, r.company && !r.company.startsWith('Не найдена') ? r.company : null] + .filter(Boolean).join(' · ') || '—'} + + + ) + }, + }, + { + key: 'summary', + header: 'Длительность / сообщение', + cell: (r) => + r.type === 'call' ? ( + {r.answered ? fmtDuration(r.value) : '—'} + ) : ( + + {r.last_message || '—'} + Сообщений: {r.value} + + ), + }, + { key: 'manager', header: 'Менеджер', width: 170, cell: (r) => ( + + + {r.manager} + + ) }, + { + key: 'status', + header: 'Статус', + width: 230, + cell: (r) => {r.status}, + }, + { + key: 'action', + header: '', + width: 56, + cell: (r) => (r.type === 'call' && r.recording_url ? : null), + }, + ] + + return ( + + + } + value={searchInput} + onChange={(e) => setSearchInput(e.currentTarget.value)} + w={240} + /> + + + } + value={range} + onChange={(v) => setRange(v as DateRange)} + clearable + w={250} + /> + + + + columns={columns} + rows={data?.data ?? []} + getRowId={(r) => r.id} + loading={isLoading} + refreshing={isFetching} + // Звонки открывать не нужно — запись играет в строке; SMS и диалоги читаются в drawer + onRowClick={(r) => r.type !== 'call' && setOpen(r)} + empty={{ + title: 'Ничего не найдено', + description: activeCount > 0 ? 'Измените или сбросьте фильтры' : undefined, + }} + pagination={{ page, pageSize: LIMIT, total, onChange: setPage }} + /> + + setOpen(null)} /> + + ) +} + +/* ——— Менеджеры ——— */ + +type Row = ManagerSession & { channel: Channel } +type Dialog = 'telegram' | 'whatsapp' | null + +function ManagersView({ onOnline }: { onOnline: (s: string | undefined) => void }) { + const queryClient = useQueryClient() + const { data: tg, isLoading: l1, isFetching: f1 } = useTelegramManagers() + const { data: wa, isLoading: l2, isFetching: f2 } = useWhatsAppManagers() + const delTg = useDeleteTelegramManager() + const delWa = useDeleteWhatsAppManager() + + const [adding, setAdding] = useState(null) + const [editing, setEditing] = useState(null) + const [deleting, setDeleting] = useState(null) + + const rows = useMemo( + () => [ + ...(tg ?? []).map((m) => ({ ...m, channel: 'telegram' as const })), + ...(wa ?? []).map((m) => ({ ...m, channel: 'whatsapp' as const })), + ], + [tg, wa], + ) + const loading = l1 || l2 + useEffect(() => { + onOnline(loading ? undefined : `Онлайн ${rows.filter((r) => r.is_online).length} из ${rows.length}`) + }, [loading, rows, onOnline]) + + const confirmDelete = async (wipeData: boolean) => { + if (!deleting) return + if (deleting.channel === 'telegram') await delTg.mutateAsync({ managerId: Number(deleting.manager_id), wipeData }) + else await delWa.mutateAsync({ phone: deleting.phone, wipeData }) + } + + const saveName = async (name: string) => { + if (!editing) return + try { + if (editing.channel === 'telegram') await telegramManagersApi.updateName(Number(editing.manager_id), name) + else await whatsappManagersApi.updateName(editing.phone, name) + notifications.show({ title: 'Готово', message: 'Имя обновлено', color: 'green' }) + queryClient.invalidateQueries({ queryKey: [`${editing.channel}-managers-status`] }) + } catch { + notifications.show({ title: 'Ошибка', message: 'Не удалось обновить имя', color: 'red' }) + } + } + + const last = (v?: string | null) => {v ? formatMsk(v) : '—'} + + const columns: Column[] = [ + { + key: 'name', + header: 'Менеджер', + cell: (r) => ( + + + + {r.name} + +{r.phone} + + + ), + }, + { + key: 'channel', + header: 'Канал', + width: 140, + cell: (r) => { + const C = CHANNELS[r.channel] + return ( + + + {C.label} + + ) + }, + }, + { + key: 'online', + header: 'Сессия', + width: 120, + cell: (r) => {r.is_online ? 'Онлайн' : 'Оффлайн'}, + }, + { key: 'in', header: 'Последнее входящее', width: 180, cell: (r) => last(r.last_incoming_message_at) }, + { key: 'out', header: 'Последнее исходящее', width: 180, cell: (r) => last(r.last_outgoing_message_at) }, + { + key: 'menu', + header: '', + width: 56, + cell: (r) => ( + + + e.stopPropagation()}> + + + + e.stopPropagation()}> + } onClick={() => setEditing(r)}>Изменить имя + + } color="red" onClick={() => setDeleting(r)}> + Отключить сессию + + + + ), + }, + ] + + return ( + + + Подключённые аккаунты менеджеров. Max пока не поддерживается. + + + + + + } onClick={() => setAdding('telegram')}>Telegram + } onClick={() => setAdding('whatsapp')}>WhatsApp + + + + + + columns={columns} + rows={rows} + getRowId={(r) => `${r.channel}-${r.manager_id}`} + loading={loading} + refreshing={(f1 || f2) && !loading} + empty={{ title: 'Нет подключённых менеджеров', description: 'Подключите Telegram или WhatsApp' }} + /> + + setAdding(null)} /> + setAdding(null)} /> + setEditing(null)} manager={editing} onSave={saveName} /> + setDeleting(null)} + manager={deleting} + onConfirm={confirmDelete} + title={deleting ? `Отключение ${CHANNELS[deleting.channel].label}` : ''} + /> + + ) +} + +/* ——— Страница ——— */ + +export default function TelephonyPage() { + const [tab, setTab] = useState('report') + const [total, setTotal] = useState() + const [online, setOnline] = useState() + + return ( + + + telephonyApi.download({ + ...(from && { date_from: fmtDate(from) }), + ...(to && { date_to: fmtDate(to) }), + }) + } + /> + ) : undefined + } + /> + + + + }>Отчёт + }>Менеджеры + + + + + + ) +} \ No newline at end of file diff --git a/src/pages/telephony/components/ManagerModals.tsx b/src/pages/telephony/components/ManagerModals.tsx new file mode 100644 index 0000000..8896968 --- /dev/null +++ b/src/pages/telephony/components/ManagerModals.tsx @@ -0,0 +1,95 @@ +// Вынесено из старой MessengersPage без изменений логики. +import { useEffect, useRef, useState } from 'react' +import { Button, Center, Group, Image, Loader, Modal, Stack, Text, TextInput } from '@mantine/core' +import { notifications } from '@mantine/notifications' +import { useQueryClient } from '@tanstack/react-query' +import { whatsappManagersApi } from '@/api/whatsappManagers' +import type { ManagerSession } from '@/types/api' + +export function EditManagerModal({ opened, onClose, manager, onSave }: { + opened: boolean + onClose: () => void + manager: ManagerSession | null + onSave: (name: string) => Promise +}) { + const [name, setName] = useState('') + const [loading, setLoading] = useState(false) + + useEffect(() => { if (manager) setName(manager.name) }, [manager]) + + const submit = async (e: React.FormEvent) => { + e.preventDefault() + setLoading(true) + await onSave(name) + setLoading(false) + onClose() + } + + return ( + +
+ + setName(e.currentTarget.value)} required /> + + + + + + +
+
+ ) +} + +export function AddWhatsappModal({ opened, onClose }: { opened: boolean; onClose: () => void }) { + const [img, setImg] = useState('') + const timer = useRef(null) + const queryClient = useQueryClient() + + const stop = () => { + if (timer.current) clearInterval(timer.current) + timer.current = null + } + + const poll = (token: string) => { + timer.current = window.setInterval(async () => { + try { + const { data } = await whatsappManagersApi.checkQrStatus(token) + if (data.status === 'pending' && data.qr) setImg(data.qr) + else if (data.status === 'success') { + stop() + notifications.show({ title: 'Готово', message: 'WhatsApp подключён', color: 'green' }) + queryClient.invalidateQueries({ queryKey: ['whatsapp-managers-status'] }) + onClose() + } else if (data.status === 'failed') { + stop() + notifications.show({ title: 'Ошибка', message: 'Не удалось отсканировать код', color: 'red' }) + setImg('') + } + } catch { /* следующий тик повторит запрос */ } + }, 2000) + } + + useEffect(() => { + if (opened) { + whatsappManagersApi.startQr() + .then((res) => poll(res.data.token)) + .catch(() => notifications.show({ title: 'Ошибка', message: 'Не удалось загрузить QR-код', color: 'red' })) + } else { + stop() + setImg('') + } + return stop + }, [opened]) + + return ( + + + Настройки → Связанные устройства → Привязка устройства +
+ {img ? : } +
+
+
+ ) +} \ No newline at end of file diff --git a/src/pages/telephony/components/ReportPopover.tsx b/src/pages/telephony/components/ReportPopover.tsx new file mode 100644 index 0000000..67f7b74 --- /dev/null +++ b/src/pages/telephony/components/ReportPopover.tsx @@ -0,0 +1,88 @@ +// Общая кнопка «Отчёт»: выбор периода и выгрузка в Excel. +// Тот же паттерн, что в ApprovalsPage, — ReportButton там можно заменить на этот компонент. +import { useState } from 'react' +import { Button, Group, Popover, Stack, Text } from '@mantine/core' +import { DatePicker } from '@mantine/dates' +import { notifications } from '@mantine/notifications' +import { IconDownload } from '@tabler/icons-react' +import dayjs from 'dayjs' + +export type DateRange = [Date | null, Date | null] + +const PRESETS: { label: string; range: () => DateRange }[] = [ + { label: 'Сегодня', range: () => [dayjs().startOf('day').toDate(), dayjs().endOf('day').toDate()] }, + { label: 'Этот месяц', range: () => [dayjs().startOf('month').toDate(), dayjs().endOf('month').toDate()] }, + { + label: 'Прошлый месяц', + range: () => [ + dayjs().subtract(1, 'month').startOf('month').toDate(), + dayjs().subtract(1, 'month').endOf('month').toDate(), + ], + }, + { label: 'Всё время', range: () => [null, null] }, +] + +interface Props { + title: string + fileName: string // без расширения + hint?: string + onDownload: (range: DateRange) => Promise +} + +export function ReportPopover({ title, fileName, hint, onDownload }: Props) { + const [opened, setOpened] = useState(false) + const [range, setRange] = useState([null, null]) + const [loading, setLoading] = useState(false) + + const download = async () => { + setLoading(true) + try { + const blob = new Blob([await onDownload(range)], { + type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }) + const url = window.URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = `${fileName}_${dayjs().format('DD.MM.YYYY_HH-mm')}.xlsx` + document.body.appendChild(a) + a.click() + a.remove() + window.URL.revokeObjectURL(url) + notifications.show({ title: 'Готово', message: 'Отчёт скачан', color: 'green' }) + setOpened(false) + } catch { + notifications.show({ title: 'Ошибка', message: 'Не удалось сформировать отчёт', color: 'red' }) + } finally { + setLoading(false) + } + } + + return ( + + + + + + + + {title} + {hint && {hint}} + + + {PRESETS.map((p) => ( + + ))} + + setRange(v as DateRange)} /> + + + + + ) +} \ No newline at end of file