From 498ed510223806e783d60ee8cf1addf992ee084e Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Wed, 18 Nov 2026 14:19:22 +0300 Subject: [PATCH] Updated telephony page --- src/lib/telephony.ts | 15 +- src/pages/telephony/TelephonyPage.tsx | 43 +---- .../telephony/components/ChatsDrawer.tsx | 162 ++++++++++++++++++ 3 files changed, 184 insertions(+), 36 deletions(-) create mode 100644 src/pages/telephony/components/ChatsDrawer.tsx diff --git a/src/lib/telephony.ts b/src/lib/telephony.ts index de0eb92..7af630e 100644 --- a/src/lib/telephony.ts +++ b/src/lib/telephony.ts @@ -28,13 +28,24 @@ export interface ReportParams { status?: string; content?: string; date_from?: string; date_to?: string } +export interface ChatSummary { + id: string + contact_name?: string | null + phone: string + last_message?: string | null + last_at?: string | null + messages_count: number +} + 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), + chats: (p: { channel: Channel; manager_id: string | number; search?: string; limit?: number }) => + api.get<{ data: ChatSummary[]; total_count: number }>('/telephony/chats', { params: p }).then((r) => r.data), + thread: (chatId: string, p: { before?: string; limit?: number }) => + api.get<{ data: ChatMessage[]; has_more: boolean }>(`/telephony/chats/${chatId}/messages`, { params: p }).then((r) => r.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/telephony/TelephonyPage.tsx b/src/pages/telephony/TelephonyPage.tsx index 4c31ade..07a6296 100644 --- a/src/pages/telephony/TelephonyPage.tsx +++ b/src/pages/telephony/TelephonyPage.tsx @@ -1,13 +1,13 @@ import { useEffect, useMemo, useState } from 'react' import { - ActionIcon, Avatar, Badge, Box, Button, Drawer, Group, Menu, Popover, Select, Skeleton, Stack, Tabs, Text, + ActionIcon, Avatar, Badge, Box, Button, Drawer, Group, Menu, Popover, Select, 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, + IconBrandTelegram, IconBrandWhatsapp, IconCalendar, IconDots, IconEdit, IconMessage, IconMessage2, IconMessageCircle, IconPhone, IconPhoneIncoming, IconPhoneOutgoing, IconPlayerPlay, IconPlus, IconSearch, IconTrash, type Icon, } from '@tabler/icons-react' @@ -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 '@/lib/telephony' +import { telephonyApi, type Channel, 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' @@ -29,6 +29,7 @@ import type { ManagerSession } from '@/types/api' // Эти три компонента нужно вынести из старой MessengersPage в отдельные файлы без изменений import AddManagerModal from './components/AddManagerModal' import DeleteManagerModal from './components/DeleteManagersModal' +import { ChatsDrawer, MessageThread } from './components/ChatsDrawer' import { AddWhatsappModal, EditManagerModal } from './components/ManagerModals' import classes from '@/components/UserDrawer.module.css' @@ -81,11 +82,6 @@ function PlayButton({ url }: { url: string }) { } 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 ( @@ -103,32 +99,7 @@ function ConversationDrawer({ row, onClose }: { row: ReportRow | null; onClose: - - {isLoading ? ( - <> - ) : !data?.length ? ( - Сообщений нет - ) : ( - data.map((m: ChatMessage) => ( - - {m.text} - {formatMsk(m.at)} - - )) - )} - + @@ -309,6 +280,7 @@ function ManagersView({ onOnline }: { onOnline: (s: string | undefined) => void const [adding, setAdding] = useState(null) const [editing, setEditing] = useState(null) const [deleting, setDeleting] = useState(null) + const [chatsOf, setChatsOf] = useState(null) const rows = useMemo( () => [ @@ -390,6 +362,7 @@ function ManagersView({ onOnline }: { onOnline: (s: string | undefined) => void e.stopPropagation()}> + } onClick={() => setChatsOf(r)}>Переписки } onClick={() => setEditing(r)}>Изменить имя } color="red" onClick={() => setDeleting(r)}> @@ -422,9 +395,11 @@ function ManagersView({ onOnline }: { onOnline: (s: string | undefined) => void getRowId={(r) => `${r.channel}-${r.manager_id}`} loading={loading} refreshing={(f1 || f2) && !loading} + onRowClick={setChatsOf} empty={{ title: 'Нет подключённых менеджеров', description: 'Подключите Telegram или WhatsApp' }} /> + setChatsOf(null)} /> setAdding(null)} /> setAdding(null)} /> setEditing(null)} manager={editing} onSave={saveName} /> diff --git a/src/pages/telephony/components/ChatsDrawer.tsx b/src/pages/telephony/components/ChatsDrawer.tsx new file mode 100644 index 0000000..8332368 --- /dev/null +++ b/src/pages/telephony/components/ChatsDrawer.tsx @@ -0,0 +1,162 @@ +import { useEffect, useRef, useState } from 'react' +import { ActionIcon, Box, Button, Center, Drawer, Group, Skeleton, Stack, Text, TextInput, UnstyledButton } from '@mantine/core' +import { useDebouncedValue } from '@mantine/hooks' +import { IconArrowLeft, IconSearch } from '@tabler/icons-react' +import { useInfiniteQuery, useQuery } from '@tanstack/react-query' +import { telephonyApi, type Channel, type ChatSummary } from '@/lib/telephony' +import { formatMsk } from '@/utils/date' +import type { ManagerSession } from '@/types/api' +import classes from '@/components/UserDrawer.module.css' + +const CHANNEL_LABEL: Record = { telegram: 'Telegram', whatsapp: 'WhatsApp', max: 'Max' } + +const chatTitle = (c: Pick) => + c.contact_name && c.contact_name !== 'Неизвестно' ? c.contact_name : `+${c.phone}` + +export function MessageThread({ chatId }: { chatId: string | null }) { + const { data, isLoading, hasNextPage, fetchNextPage, isFetchingNextPage } = useInfiniteQuery({ + queryKey: ['telephony-thread', chatId], + enabled: !!chatId, + initialPageParam: undefined as string | undefined, + queryFn: ({ pageParam }) => telephonyApi.thread(chatId!, { before: pageParam, limit: 50 }), + getNextPageParam: (last) => (last.has_more ? last.data[0]?.id : undefined), + }) + + // pages[0] — самая свежая порция, внутри порции сообщения идут от старых к новым + const messages = [...(data?.pages ?? [])].reverse().flatMap((p) => p.data) + + // При первой загрузке прокручиваем к последнему сообщению, при подгрузке старых — не трогаем + const bottom = useRef(null) + const initial = data?.pages.length === 1 + useEffect(() => { + if (initial) bottom.current?.scrollIntoView() + }, [initial, chatId, messages.length]) + + return ( + + {isLoading ? ( + <> + ) : messages.length === 0 ? ( + Сообщений нет + ) : ( + <> + {hasNextPage && ( +
+ +
+ )} + {messages.map((m) => ( + + {m.text} + {formatMsk(m.at)} + + ))} +
+ + )} + + ) +} + +type Props = { manager: (ManagerSession & { channel: Channel }) | null; onClose: () => void } + +/** Все диалоги менеджера в его канале: список с поиском, по клику — полная переписка. */ +export function ChatsDrawer({ manager, onClose }: Props) { + const [chat, setChat] = useState(null) + const [input, setInput] = useState('') + const [debounced] = useDebouncedValue(input.trim(), 400) + const search = debounced.length >= 2 ? debounced : '' + + // Сбрасываем выбранный диалог и поиск при смене менеджера или закрытии + useEffect(() => { + setChat(null) + setInput('') + }, [manager?.manager_id, manager?.channel]) + + const { data, isLoading } = useQuery({ + queryKey: ['telephony-chats', manager?.channel, manager?.manager_id, search], + enabled: !!manager, + queryFn: () => telephonyApi.chats({ channel: manager!.channel, manager_id: manager!.manager_id, search, limit: 100 }), + }) + const chats = data?.data ?? [] + + return ( + + + + + + {chat && ( + setChat(null)}> + + + )} + + {chat ? chatTitle(chat) : 'Переписки'} + + {manager && `${manager.name} · ${CHANNEL_LABEL[manager.channel]}`} + + + + + + + + {chat ? ( + + ) : ( + + } + value={input} + onChange={(e) => setInput(e.currentTarget.value)} + /> + {isLoading ? ( + <> + ) : chats.length === 0 ? ( + {search ? 'Ничего не найдено' : 'Диалогов нет'} + ) : ( + + {chats.map((c) => ( + setChat(c)} + py={8} + px="xs" + style={{ borderBottom: '1px solid var(--mantine-color-default-border)' }} + > + + + {chatTitle(c)} + {c.last_message || '—'} + + + {c.last_at ? formatMsk(c.last_at) : ''} + {c.messages_count} + + + + ))} + + )} + + )} + + + + ) +} \ No newline at end of file