Updated telephony page
Deploy Frontend / build-and-deploy (push) Successful in 29s
Details
Deploy Frontend / build-and-deploy (push) Successful in 29s
Details
This commit is contained in:
parent
4d24ff36b4
commit
498ed51022
|
|
@ -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),
|
||||
}
|
||||
|
|
@ -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:
|
|||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
<Drawer.Body className={classes.body}>
|
||||
<Stack className={classes.section} gap="sm">
|
||||
{isLoading ? (
|
||||
<><Skeleton h={44} /><Skeleton h={44} /><Skeleton h={44} /></>
|
||||
) : !data?.length ? (
|
||||
<Text size="sm" c="dimmed">Сообщений нет</Text>
|
||||
) : (
|
||||
data.map((m: ChatMessage) => (
|
||||
<Box
|
||||
key={m.id}
|
||||
maw="85%"
|
||||
px="sm"
|
||||
py={6}
|
||||
style={{
|
||||
alignSelf: m.direction === 'out' ? 'flex-end' : 'flex-start',
|
||||
borderRadius: 'var(--mantine-radius-md)',
|
||||
background: m.direction === 'out'
|
||||
? 'var(--mantine-primary-color-light)'
|
||||
: 'var(--mantine-color-default-hover)',
|
||||
}}
|
||||
>
|
||||
<Text size="sm" style={{ whiteSpace: 'pre-wrap' }}>{m.text}</Text>
|
||||
<Text size="xs" c="dimmed" ta="right">{formatMsk(m.at)}</Text>
|
||||
</Box>
|
||||
))
|
||||
)}
|
||||
</Stack>
|
||||
<MessageThread chatId={row?.id ?? null} />
|
||||
</Drawer.Body>
|
||||
</Drawer.Content>
|
||||
</Drawer.Root>
|
||||
|
|
@ -309,6 +280,7 @@ function ManagersView({ onOnline }: { onOnline: (s: string | undefined) => void
|
|||
const [adding, setAdding] = useState<Dialog>(null)
|
||||
const [editing, setEditing] = useState<Row | null>(null)
|
||||
const [deleting, setDeleting] = useState<Row | null>(null)
|
||||
const [chatsOf, setChatsOf] = useState<Row | null>(null)
|
||||
|
||||
const rows = useMemo<Row[]>(
|
||||
() => [
|
||||
|
|
@ -390,6 +362,7 @@ function ManagersView({ onOnline }: { onOnline: (s: string | undefined) => void
|
|||
</ActionIcon>
|
||||
</Menu.Target>
|
||||
<Menu.Dropdown onClick={(e) => e.stopPropagation()}>
|
||||
<Menu.Item leftSection={<IconMessage2 size={14} />} onClick={() => setChatsOf(r)}>Переписки</Menu.Item>
|
||||
<Menu.Item leftSection={<IconEdit size={14} />} onClick={() => setEditing(r)}>Изменить имя</Menu.Item>
|
||||
<Menu.Divider />
|
||||
<Menu.Item leftSection={<IconTrash size={14} />} 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' }}
|
||||
/>
|
||||
|
||||
<ChatsDrawer manager={chatsOf} onClose={() => setChatsOf(null)} />
|
||||
<AddManagerModal opened={adding === 'telegram'} onClose={() => setAdding(null)} />
|
||||
<AddWhatsappModal opened={adding === 'whatsapp'} onClose={() => setAdding(null)} />
|
||||
<EditManagerModal opened={!!editing} onClose={() => setEditing(null)} manager={editing} onSave={saveName} />
|
||||
|
|
|
|||
|
|
@ -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<Channel, string> = { telegram: 'Telegram', whatsapp: 'WhatsApp', max: 'Max' }
|
||||
|
||||
const chatTitle = (c: Pick<ChatSummary, 'contact_name' | 'phone'>) =>
|
||||
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<HTMLDivElement>(null)
|
||||
const initial = data?.pages.length === 1
|
||||
useEffect(() => {
|
||||
if (initial) bottom.current?.scrollIntoView()
|
||||
}, [initial, chatId, messages.length])
|
||||
|
||||
return (
|
||||
<Stack className={classes.section} gap="sm">
|
||||
{isLoading ? (
|
||||
<><Skeleton h={44} /><Skeleton h={44} /><Skeleton h={44} /></>
|
||||
) : messages.length === 0 ? (
|
||||
<Text size="sm" c="dimmed">Сообщений нет</Text>
|
||||
) : (
|
||||
<>
|
||||
{hasNextPage && (
|
||||
<Center>
|
||||
<Button size="compact-sm" variant="default" loading={isFetchingNextPage} onClick={() => fetchNextPage()}>
|
||||
Показать ранее
|
||||
</Button>
|
||||
</Center>
|
||||
)}
|
||||
{messages.map((m) => (
|
||||
<Box
|
||||
key={m.id}
|
||||
maw="85%"
|
||||
px="sm"
|
||||
py={6}
|
||||
style={{
|
||||
alignSelf: m.direction === 'out' ? 'flex-end' : 'flex-start',
|
||||
borderRadius: 'var(--mantine-radius-md)',
|
||||
background:
|
||||
m.direction === 'out' ? 'var(--mantine-primary-color-light)' : 'var(--mantine-color-default-hover)',
|
||||
}}
|
||||
>
|
||||
<Text size="sm" style={{ whiteSpace: 'pre-wrap' }}>{m.text}</Text>
|
||||
<Text size="xs" c="dimmed" ta="right">{formatMsk(m.at)}</Text>
|
||||
</Box>
|
||||
))}
|
||||
<div ref={bottom} />
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
type Props = { manager: (ManagerSession & { channel: Channel }) | null; onClose: () => void }
|
||||
|
||||
/** Все диалоги менеджера в его канале: список с поиском, по клику — полная переписка. */
|
||||
export function ChatsDrawer({ manager, onClose }: Props) {
|
||||
const [chat, setChat] = useState<ChatSummary | null>(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 (
|
||||
<Drawer.Root opened={!!manager} onClose={onClose} position="right" size="min(560px, 100vw)">
|
||||
<Drawer.Overlay backgroundOpacity={0.25} />
|
||||
<Drawer.Content>
|
||||
<Drawer.Header>
|
||||
<Group gap="xs" wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
{chat && (
|
||||
<ActionIcon aria-label="К списку диалогов" onClick={() => setChat(null)}>
|
||||
<IconArrowLeft size={16} />
|
||||
</ActionIcon>
|
||||
)}
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text fw={600} truncate>{chat ? chatTitle(chat) : 'Переписки'}</Text>
|
||||
<Text size="xs" c="dimmed" truncate>
|
||||
{manager && `${manager.name} · ${CHANNEL_LABEL[manager.channel]}`}
|
||||
</Text>
|
||||
</Box>
|
||||
</Group>
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body className={classes.body}>
|
||||
{chat ? (
|
||||
<MessageThread chatId={chat.id} />
|
||||
) : (
|
||||
<Stack className={classes.section} gap="sm">
|
||||
<TextInput
|
||||
placeholder="Имя или номер"
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.currentTarget.value)}
|
||||
/>
|
||||
{isLoading ? (
|
||||
<><Skeleton h={48} /><Skeleton h={48} /><Skeleton h={48} /></>
|
||||
) : chats.length === 0 ? (
|
||||
<Text size="sm" c="dimmed">{search ? 'Ничего не найдено' : 'Диалогов нет'}</Text>
|
||||
) : (
|
||||
<Stack gap={0}>
|
||||
{chats.map((c) => (
|
||||
<UnstyledButton
|
||||
key={c.id}
|
||||
onClick={() => setChat(c)}
|
||||
py={8}
|
||||
px="xs"
|
||||
style={{ borderBottom: '1px solid var(--mantine-color-default-border)' }}
|
||||
>
|
||||
<Group justify="space-between" wrap="nowrap" align="flex-start">
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text size="sm" fw={500} truncate>{chatTitle(c)}</Text>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>{c.last_message || '—'}</Text>
|
||||
</Box>
|
||||
<Stack gap={0} align="flex-end" style={{ flexShrink: 0 }}>
|
||||
<Text size="xs" c="dimmed">{c.last_at ? formatMsk(c.last_at) : ''}</Text>
|
||||
<Text size="xs" c="dimmed">{c.messages_count}</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
</Drawer.Body>
|
||||
</Drawer.Content>
|
||||
</Drawer.Root>
|
||||
)
|
||||
}
|
||||
Loading…
Reference in New Issue