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

This commit is contained in:
romanskijdev 2026-11-18 14:22:49 +03:00
parent 498ed51022
commit ae43fdae60
3 changed files with 139 additions and 0 deletions

View File

@ -19,6 +19,7 @@ export interface ReportRow {
last_message?: string | null // SMS / чат last_message?: string | null // SMS / чат
manager: string manager: string
manager_id?: number | null manager_id?: number | null
notes_count?: number // число заметок, для индикатора в таблице
status: string // «Отвечен», «Пропущен, перезвон не совершен», … status: string // «Отвечен», «Пропущен, перезвон не совершен», …
} }
@ -37,13 +38,28 @@ export interface ChatSummary {
messages_count: number messages_count: number
} }
export interface Note {
id: number
text: string
author: string
created_at: string
can_delete: boolean // права решает сервер: автор или суперадмин
}
export interface ChatMessage { id: string; direction: 'in' | 'out'; text: string; at: string; author?: string } export interface ChatMessage { id: string; direction: 'in' | 'out'; text: string; at: string; author?: string }
export const telephonyApi = { export const telephonyApi = {
list: (params: ReportParams) => list: (params: ReportParams) =>
api.get<{ data: ReportRow[]; total_count: number }>('/telephony/report', { params }).then((r) => r.data), api.get<{ data: ReportRow[]; total_count: number }>('/telephony/report', { params }).then((r) => r.data),
// Заметки общие: видны всем, у кого есть доступ к разделу. id — id строки отчёта
notes: (id: string) =>
api.get<{ data: Note[] }>(`/telephony/report/${id}/notes`).then((r) => r.data.data),
addNote: (id: string, text: string) => api.post(`/telephony/report/${id}/notes`, { text }),
deleteNote: (id: string, noteId: number) => api.delete(`/telephony/report/${id}/notes/${noteId}`),
// Диалоги менеджера в одном канале
chats: (p: { channel: Channel; manager_id: string | number; search?: string; limit?: number }) => 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), api.get<{ data: ChatSummary[]; total_count: number }>('/telephony/chats', { params: p }).then((r) => r.data),
// Переписка постранично: before — id самого раннего из уже загруженных сообщений
thread: (chatId: string, p: { before?: string; limit?: number }) => 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), api.get<{ data: ChatMessage[]; has_more: boolean }>(`/telephony/chats/${chatId}/messages`, { params: p }).then((r) => r.data),
download: (params: ReportParams) => download: (params: ReportParams) =>

View File

@ -29,6 +29,7 @@ import type { ManagerSession } from '@/types/api'
// Эти три компонента нужно вынести из старой MessengersPage в отдельные файлы без изменений // Эти три компонента нужно вынести из старой MessengersPage в отдельные файлы без изменений
import AddManagerModal from './components/AddManagerModal' import AddManagerModal from './components/AddManagerModal'
import DeleteManagerModal from './components/DeleteManagersModal' import DeleteManagerModal from './components/DeleteManagersModal'
import { NoteButton, NotesPanel } from './components/Notes'
import { ChatsDrawer, MessageThread } from './components/ChatsDrawer' import { ChatsDrawer, MessageThread } from './components/ChatsDrawer'
import { AddWhatsappModal, EditManagerModal } from './components/ManagerModals' import { AddWhatsappModal, EditManagerModal } from './components/ManagerModals'
import classes from '@/components/UserDrawer.module.css' import classes from '@/components/UserDrawer.module.css'
@ -99,6 +100,12 @@ function ConversationDrawer({ row, onClose }: { row: ReportRow | null; onClose:
<Drawer.CloseButton /> <Drawer.CloseButton />
</Drawer.Header> </Drawer.Header>
<Drawer.Body className={classes.body}> <Drawer.Body className={classes.body}>
{row && (
<Stack className={classes.section} gap="xs" pb={0}>
<Text size="sm" fw={600}>Заметки</Text>
<NotesPanel id={row.id} />
</Stack>
)}
<MessageThread chatId={row?.id ?? null} /> <MessageThread chatId={row?.id ?? null} />
</Drawer.Body> </Drawer.Body>
</Drawer.Content> </Drawer.Content>
@ -211,6 +218,7 @@ function ReportView({ onTotal }: { onTotal: (n: number | undefined) => void }) {
width: 230, width: 230,
cell: (r) => <Badge variant="light" color={statusColor(r.status)}>{r.status}</Badge>, cell: (r) => <Badge variant="light" color={statusColor(r.status)}>{r.status}</Badge>,
}, },
{ key: 'notes', header: '', width: 56, cell: (r) => <NoteButton id={r.id} count={r.notes_count ?? 0} /> },
{ {
key: 'action', key: 'action',
header: '', header: '',

View File

@ -0,0 +1,115 @@
import { useState } from 'react'
import { ActionIcon, Button, Group, Indicator, Popover, Skeleton, Stack, Text, Textarea } from '@mantine/core'
import { notifications } from '@mantine/notifications'
import { IconNote, IconTrash } from '@tabler/icons-react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAuth } from '@/hooks/useAuth'
import { telephonyApi } from '@/lib/telephony'
import { formatMsk } from '@/utils/date'
/** Общие заметки к звонку, SMS или диалогу: видны всем, у кого есть доступ к разделу. */
export function NotesPanel({ id }: { id: string }) {
const queryClient = useQueryClient()
const { user } = useAuth()
const canWrite = user?.is_observer !== true
const [text, setText] = useState('')
const { data: notes, isLoading } = useQuery({
queryKey: ['telephony-notes', id],
queryFn: () => telephonyApi.notes(id),
})
// Обновляем и список заметок, и счётчик в таблице отчёта
const refresh = () => {
queryClient.invalidateQueries({ queryKey: ['telephony-notes', id] })
queryClient.invalidateQueries({ queryKey: ['telephony-report'] })
}
const onError = () => notifications.show({ title: 'Ошибка', message: 'Не удалось сохранить заметку', color: 'red' })
const add = useMutation({
mutationFn: () => telephonyApi.addNote(id, text.trim()),
onSuccess: () => { setText(''); refresh() },
onError,
})
const remove = useMutation({
mutationFn: (noteId: number) => telephonyApi.deleteNote(id, noteId),
onSuccess: refresh,
onError,
})
const submit = () => { if (text.trim() && !add.isPending) add.mutate() }
return (
<Stack gap="sm">
{isLoading ? (
<Skeleton h={40} />
) : !notes?.length ? (
<Text size="sm" c="dimmed">Заметок пока нет</Text>
) : (
notes.map((n) => (
<Stack key={n.id} gap={2}>
<Group justify="space-between" wrap="nowrap">
<Group gap={8} wrap="nowrap">
<Text size="sm" fw={500}>{n.author}</Text>
<Text size="xs" c="dimmed">{formatMsk(n.created_at)}</Text>
</Group>
{n.can_delete && (
<ActionIcon
size="sm"
color="red"
aria-label="Удалить заметку"
loading={remove.isPending && remove.variables === n.id}
onClick={() => remove.mutate(n.id)}
>
<IconTrash size={14} />
</ActionIcon>
)}
</Group>
<Text size="sm" style={{ whiteSpace: 'pre-wrap' }}>{n.text}</Text>
</Stack>
))
)}
{canWrite && (
<Stack gap="xs">
<Textarea
placeholder="Добавить заметку"
autosize
minRows={2}
maxRows={6}
value={text}
onChange={(e) => setText(e.currentTarget.value)}
onKeyDown={(e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') submit() }}
/>
<Group justify="flex-end">
<Button size="xs" onClick={submit} loading={add.isPending} disabled={!text.trim()}>Добавить</Button>
</Group>
</Stack>
)}
</Stack>
)
}
/** Кнопка в строке отчёта: счётчик заметок и поповер с ними, не открывая саму строку. */
export function NoteButton({ id, count }: { id: string; count: number }) {
const [opened, setOpened] = useState(false)
return (
<Popover opened={opened} onChange={setOpened} position="bottom-end" shadow="md" width={340} withArrow>
<Popover.Target>
<Indicator label={count} size={14} disabled={count === 0} offset={4}>
<ActionIcon
variant={count > 0 ? 'light' : 'subtle'}
color={count > 0 ? undefined : 'gray'}
aria-label="Заметки"
onClick={(e) => { e.stopPropagation(); setOpened((o) => !o) }}
>
<IconNote size={16} />
</ActionIcon>
</Indicator>
</Popover.Target>
<Popover.Dropdown onClick={(e) => e.stopPropagation()}>
{opened && <NotesPanel id={id} />}
</Popover.Dropdown>
</Popover>
)
}