diff --git a/src/components/ui/FileList.tsx b/src/components/ui/FileList.tsx
new file mode 100644
index 0000000..24c9cc5
--- /dev/null
+++ b/src/components/ui/FileList.tsx
@@ -0,0 +1,60 @@
+import { ActionIcon, Box, Divider, Group, Stack, Text, ThemeIcon, Tooltip } from '@mantine/core'
+import { IconDownload, IconEye, IconFileText } from '@tabler/icons-react'
+import { formatFileSize, getMimeType, isPreviewable } from '@/lib/fileApi'
+
+export interface FileItem {
+ id?: number
+ file_name?: string
+ file_base64?: string
+}
+
+interface Props {
+ files: FileItem[]
+ onPreview: (file: { id: number; name: string; type: string }) => void
+ onDownload: (id: number, name: string) => void
+}
+
+export function FileList({ files, onPreview, onDownload }: Props) {
+ return (
+
+ {files.map((file, i) => {
+ const name = file.file_name || 'Без имени'
+ const mime = getMimeType(name)
+ const kb = file.file_base64 ? Math.round((file.file_base64.length * 3) / 4 / 1024) : 0
+ return (
+
+ {i > 0 && }
+
+
+
+
+
+
+ {name}
+ {kb > 0 && {formatFileSize(kb)}}
+
+
+
+ {isPreviewable(mime) && (
+
+ onPreview({ id: file.id!, name, type: mime })}
+ >
+
+
+
+ )}
+
+ onDownload(file.id!, name)}>
+
+
+
+
+
+
+ )
+ })}
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/approvalTasks/ApprovalTasksPage.tsx b/src/pages/approvalTasks/ApprovalTasksPage.tsx
index 020189e..590ecbd 100644
--- a/src/pages/approvalTasks/ApprovalTasksPage.tsx
+++ b/src/pages/approvalTasks/ApprovalTasksPage.tsx
@@ -1,285 +1,236 @@
-import { useState } from 'react'
-import {
- Paper,
- Table,
- Badge,
- Group,
- ActionIcon,
- Button,
- Text,
- Select,
- Pagination,
- Loader,
- Center,
- Tooltip,
- Box,
- Stack,
- Switch,
-} from '@mantine/core'
-import { IconEye, IconTrash, IconSearch } from '@tabler/icons-react'
-import { modals } from '@mantine/modals'
+import { useMemo, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
-import { useApprovalTasks, useDeleteApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
-import { useUsers } from '@/features/users/hooks/useUsers'
-import { TASK_STATUSES, STATUS_COLORS, STATUS_LABELS } from '@/features/approvalTasks/const'
-import ApprovalTaskDetailsModal from './components/ApprovalTaskDetailsModal'
+import { ActionIcon, Avatar, Group, Select, Stack, Switch, Text, Tooltip } from '@mantine/core'
+import { IconPaperclip, IconTrash } from '@tabler/icons-react'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
-import {formatMsk} from "@/utils/date.ts";
+
+import { useApprovalTasks, useDeleteApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
+import { useUsers } from '@/features/users/hooks/useUsers'
+import { formatMsk } from '@/utils/date'
+
+import { PageHeader } from '@/components/ui/PageHeader'
+import { FilterBar } from '@/components/ui/FilterBar'
+import { DataTable, type Column } from '@/components/ui/DataTable'
+import { StatusBadge } from '@/components/ui/StatusBadge'
+import { ConfirmModal } from '@/components/ui/ConfirmModal'
+import { TASK_STATUS } from '@/components/ui/statuses'
+import ApprovalTaskDetailsDrawer from './components/ApprovalTaskDetailsDrawer'
dayjs.locale('ru')
const LIMIT = 20
+type Row = NonNullable['data']>['data']>[number]
+
+interface Filters {
+ status: string | null
+ executor: string | null
+ requireFile: boolean
+}
+
+const STATUS_OPTIONS = Object.entries(TASK_STATUS).map(([value, m]) => ({ value, label: m.label }))
+const VALID_STATUSES = new Set(STATUS_OPTIONS.map((o) => o.value))
+
export default function ApprovalTasksPage() {
- // 🆕 Начальный статус берём из URL (например, с дашборда:
- // /approval-tasks?status=completed) — читаем один раз при монтировании.
+ // Начальный статус берём из URL (например, с дашборда: /approval-tasks?status=completed).
+ // Читаем один раз при монтировании.
const [searchParams] = useSearchParams()
const [page, setPage] = useState(1)
- const [statusFilter, setStatusFilter] = useState(
- () => searchParams.get('status')
- )
- const [executorFilter, setExecutorFilter] = useState(null)
- const [requireFileFilter, setRequireFileFilter] = useState(null)
- const [selectedTaskId, setSelectedTaskId] = useState(null)
+ const [filters, setFilters] = useState(() => {
+ const status = searchParams.get('status')
+ return { status: status && VALID_STATUSES.has(status) ? status : null, executor: null, requireFile: false }
+ })
+
+ // Drawer: id храним отдельно от opened, чтобы содержимое не мигало при закрытии
+ const [drawerId, setDrawerId] = useState(null)
+ const [drawerOpened, setDrawerOpened] = useState(false)
+ const [deleteId, setDeleteId] = useState(null)
+
+ const update = (patch: Partial) => {
+ setFilters((prev) => ({ ...prev, ...patch }))
+ setPage(1)
+ }
const { data, isLoading, isFetching } = useApprovalTasks({
offset: (page - 1) * LIMIT,
limit: LIMIT,
- ...(statusFilter && { status: statusFilter }),
- ...(executorFilter && { executor_id: Number(executorFilter) }),
- ...(requireFileFilter !== null && { require_file: requireFileFilter }),
+ ...(filters.status && { status: filters.status }),
+ ...(filters.executor && { executor_id: Number(filters.executor) }),
+ ...(filters.requireFile && { require_file: true }),
})
+ const total = data?.total_count ?? 0
const { data: users } = useUsers({ limit: 1000 })
const deleteTask = useDeleteApprovalTask()
- const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
+ const executorOptions = useMemo(
+ () => (users?.data ?? []).map((u) => ({ value: String(u.id), label: u.full_name || '' })),
+ [users],
+ )
- const executorOptions = users?.data?.map((u) => ({
- value: String(u.id),
- label: u.full_name || '',
- })) || []
-
- const handleDelete = (id: number) => {
- modals.openConfirmModal({
- title: 'Подтвердите удаление',
- children: (
-
- Вы уверены, что хотите удалить эту задачу? Это действие нельзя отменить.
-
- ),
- labels: { confirm: 'Удалить', cancel: 'Отмена' },
- confirmProps: { color: 'red' },
- onConfirm: () => deleteTask.mutate(id),
- })
+ const activeCount = [filters.status, filters.executor, filters.requireFile].filter(Boolean).length
+ const resetFilters = () => {
+ setFilters({ status: null, executor: null, requireFile: false })
+ setPage(1)
}
- return (
-
-
- Задачи по заявкам
-
- Всего: {data?.total_count || 0}
-
-
-
- {/* Фильтры */}
-
-
-
-
- {/* Таблица */}
-
- {isLoading ? (
-
-
-
+ ),
+ },
+ {
+ key: 'approval',
+ header: 'Заявка',
+ width: 220,
+ cell: (r) => (
+
+ {r.approval?.topic?.name || '—'}
+ #{r.approval_id} · шаг {r.step_order}
+
+ ),
+ },
+ {
+ key: 'executor',
+ header: 'Исполнитель',
+ width: 220,
+ cell: (r) =>
+ r.executor?.full_name ? (
+
+
+
+ {r.executor.full_name}
+ {r.executor.department?.name && (
+ {r.executor.department.name}
+ )}
+
+
) : (
- <>
-
-
-
- ID
- Заявка
- Исполнитель
- Текст задачи
- Шаг
- Статус
- Файл
- Создана
- Выполнена
- Действия
-
-
-
- {data?.data?.length === 0 ? (
-
-
-
- Задачи не найдены
-
-
-
- ) : (
- (data?.data || []).map((task) => (
-
-
- #{task.id}
-
-
-
-
- #{task.approval_id}
-
-
- {task.approval?.topic?.name || '—'}
-
-
-
-
-
- {task.executor?.full_name || '—'}
-
-
- {task.executor?.department?.name}
-
-
-
-
- {task.task_text || '—'}
-
-
-
-
- #{task.step_order}
-
-
-
-
- {STATUS_LABELS[task.status || ''] || task.status}
-
-
-
- {task.require_file ? (
-
- Да
-
- ) : (
- —
- )}
-
-
-
- {task.created_at
- ? formatMsk(task.created_at)
- : '—'}
-
-
-
-
- {task.completed_at
- ? formatMsk(task.created_at)
- : '—'}
-
-
-
-
-
- setSelectedTaskId(task.id!)}
- >
-
-
-
-
- handleDelete(task.id!)}
- >
-
-
-
-
-
-
- ))
- )}
-
-
+ —
+ ),
+ },
+ {
+ key: 'status',
+ header: 'Статус',
+ width: 150,
+ cell: (r) => ,
+ },
+ {
+ key: 'created',
+ header: 'Создана',
+ width: 150,
+ cell: (r) => {r.created_at ? formatMsk(r.created_at) : '—'},
+ },
+ {
+ key: 'completed',
+ header: 'Выполнена',
+ width: 150,
+ cell: (r) => {r.completed_at ? formatMsk(r.completed_at) : '—'},
+ },
+ {
+ key: 'actions',
+ header: '',
+ width: 56,
+ align: 'right',
+ cell: (r) => (
+
+ {
+ e.stopPropagation() // не открывать drawer
+ setDeleteId(r.id!)
+ }}
+ >
+
+
+
+ ),
+ },
+ ]
- {totalPages > 1 && (
-
-
-
- Страница {page} из {totalPages}
-
-
-
-
- )}
- >
- )}
-
+ return (
+
+
- {isFetching && !isLoading && (
-
-
-
- )}
+
+ update({ status })}
+ clearable
+ w={180}
+ />
+ update({ executor })}
+ searchable
+ clearable
+ w={220}
+ />
+ update({ requireFile: e.currentTarget.checked })}
+ />
+
- setSelectedTaskId(null)}
+
+ columns={columns}
+ rows={data?.data ?? []}
+ getRowId={(r) => r.id!}
+ loading={isLoading}
+ refreshing={isFetching}
+ minWidth={1000}
+ onRowClick={(r) => {
+ setDrawerId(r.id!)
+ setDrawerOpened(true)
+ }}
+ empty={{
+ title: 'Задачи не найдены',
+ description: activeCount > 0 ? 'Измените или сбросьте фильтры' : undefined,
+ }}
+ pagination={{ page, pageSize: LIMIT, total, onChange: setPage }}
+ />
+
+ setDrawerOpened(false)}
+ />
+
+ setDeleteId(null)}
+ onConfirm={() => {
+ if (deleteId !== null) deleteTask.mutate(deleteId, { onSettled: () => setDeleteId(null) })
+ }}
+ title="Удалить задачу?"
+ message={`Задача #${deleteId} будет удалена без возможности восстановления.`}
+ confirmLabel="Удалить"
+ danger
+ loading={deleteTask.isPending}
/>
)
diff --git a/src/pages/approvalTasks/components/ApprovalTaskDetailsDrawer.tsx b/src/pages/approvalTasks/components/ApprovalTaskDetailsDrawer.tsx
new file mode 100644
index 0000000..b6c86a9
--- /dev/null
+++ b/src/pages/approvalTasks/components/ApprovalTaskDetailsDrawer.tsx
@@ -0,0 +1,211 @@
+import { useEffect, useState } from 'react'
+import { Avatar, Box, Button, Drawer, Group, Select, Skeleton, Stack, Text } from '@mantine/core'
+import { notifications } from '@mantine/notifications'
+import { IconPaperclip } from '@tabler/icons-react'
+
+import { useApprovalTask, useUpdateApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
+import { TASK_STATUSES } from '@/features/approvalTasks/const'
+import { StatusBadge } from '@/components/ui/StatusBadge'
+import { InfoList, InfoRow } from '@/components/ui/InfoRow'
+import { FileList } from '@/components/ui/FileList'
+import { saveFile, taskFileUrl } from '@/lib/fileApi'
+import { formatMsk } from '@/utils/date'
+import FilePreviewModal from '@/pages/approvals/components/FilePreviewModal'
+import classes from '@/components/UserDrawer.module.css'
+
+interface Props {
+ taskId: number | null
+ opened: boolean
+ onClose: () => void
+}
+
+function Section({ title, count, children }: { title: string; count?: number; children: React.ReactNode }) {
+ return (
+
+
+ {title}
+ {count !== undefined && {count}}
+
+ {children}
+
+ )
+}
+
+export default function ApprovalTaskDetailsDrawer({ taskId, opened, onClose }: Props) {
+ const { data: task, isLoading } = useApprovalTask(taskId)
+ const updateTask = useUpdateApprovalTask()
+
+ const [status, setStatus] = useState(null)
+ const [preview, setPreview] = useState<{ id: number; name: string; type: string } | null>(null)
+
+ // Выбранный статус синхронизируем с данными задачи
+ useEffect(() => {
+ setStatus(task?.status ?? null)
+ }, [task?.id, task?.status])
+
+ useEffect(() => {
+ if (!opened) setPreview(null)
+ }, [opened])
+
+ const dirty = !!task && !!status && status !== task.status
+
+ const handleSave = async () => {
+ if (!task?.id || !status) return
+ await updateTask.mutateAsync({ id: task.id, status })
+ onClose()
+ }
+
+ const handleDownload = async (fileId: number, fileName: string) => {
+ if (!taskId) return
+ try {
+ await saveFile(taskFileUrl(taskId, fileId, true), fileName)
+ notifications.show({ title: 'Готово', message: 'Файл скачан', color: 'green' })
+ } catch (error) {
+ console.error('Download error:', error)
+ notifications.show({ title: 'Ошибка', message: 'Не удалось скачать файл', color: 'red' })
+ }
+ }
+
+ const files = task?.files ?? []
+
+ return (
+ <>
+
+
+
+
+
+
+ Задача #{taskId}
+ {task && }
+
+ {task && (
+
+ Заявка #{task.approval_id}
+ {task.approval?.topic?.name && ` · ${task.approval.topic.name}`}
+
+ )}
+
+
+
+
+
+ {isLoading ? (
+
+
+
+
+
+ ) : !task ? (
+ Задача не найдена
+ ) : (
+ <>
+
+
+ {task.task_text || '—'}
+ {task.require_file && (
+
+
+ Для выполнения нужен файл
+
+ )}
+
+
+
+
+ {task.executor?.full_name ? (
+ <>
+
+ {task.executor.full_name}
+ >
+ ) : (
+ —
+ )}
+
+ {task.executor?.department?.name && (
+
+ {task.executor.department.name}
+
+ )}
+
+ {task.step_order}
+
+
+ {task.created_at ? formatMsk(task.created_at) : '—'}
+
+ {task.updated_at && (
+
+ {formatMsk(task.updated_at)}
+
+ )}
+ {task.completed_at && (
+
+ {formatMsk(task.completed_at)}
+
+ )}
+
+
+ {files.length > 0 && (
+
+ )}
+
+ {task.approval && (
+
+
+
+ #{task.approval.id}
+
+
+ {task.approval.topic?.name || '—'}
+
+
+ {task.approval.initiator?.full_name || '—'}
+
+
+
+
+
+
+ )}
+
+
+
+ ({ value: s.value, label: s.label }))}
+ value={status}
+ onChange={setStatus}
+ allowDeselect={false}
+ w={200}
+ />
+
+
+
+
+
+ >
+ )}
+
+
+
+
+ {preview && taskId && (
+ setPreview(null)}
+ />
+ )}
+ >
+ )
+}
\ No newline at end of file
diff --git a/src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx b/src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx
deleted file mode 100644
index f009206..0000000
--- a/src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx
+++ /dev/null
@@ -1,398 +0,0 @@
-import { useState } from 'react'
-import {
- Modal,
- Stack,
- Text,
- Group,
- Badge,
- Paper,
- Loader,
- Center,
- ScrollArea,
- Select,
- Button,
- Box,
- ActionIcon,
- Tooltip,
-} from '@mantine/core'
-import { useForm } from '@mantine/form'
-import { notifications } from '@mantine/notifications'
-import {
- IconUser,
- IconBuilding,
- IconCalendar,
- IconFileText,
- IconCheck,
- IconEye,
- IconDownload,
-} from '@tabler/icons-react'
-import { useApprovalTask, useUpdateApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
-import { TASK_STATUSES, STATUS_COLORS, STATUS_LABELS } from '@/features/approvalTasks/const'
-import FilePreviewModal from '@/pages/approvals/components/FilePreviewModal'
-import dayjs from 'dayjs'
-import 'dayjs/locale/ru'
-import {formatMsk} from "@/utils/date.ts";
-
-dayjs.locale('ru')
-
-interface ApprovalTaskDetailsModalProps {
- taskId: number | null
- opened: boolean
- onClose: () => void
-}
-
-// Определение MIME типа по расширению
-const getMimeType = (fileName: string): string => {
- const ext = fileName.split('.').pop()?.toLowerCase() || ''
- const mimeTypes: Record = {
- 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'png': 'image/png',
- 'gif': 'image/gif', 'webp': 'image/webp', 'svg': 'image/svg+xml',
- 'pdf': 'application/pdf', 'txt': 'text/plain',
- 'doc': 'application/msword',
- 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- 'xls': 'application/vnd.ms-excel',
- 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- }
- return mimeTypes[ext] || 'application/octet-stream'
-}
-
-const PREVIEWABLE_TYPES = [
- 'image/jpeg', 'image/png', 'image/gif', 'image/webp',
- 'image/svg+xml', 'application/pdf', 'text/plain',
-]
-
-export default function ApprovalTaskDetailsModal({
- taskId,
- opened,
- onClose
- }: ApprovalTaskDetailsModalProps) {
- const { data: task, isLoading } = useApprovalTask(taskId)
- const updateTask = useUpdateApprovalTask()
-
- // Состояние для предпросмотра файла
- const [previewFileId, setPreviewFileId] = useState(null)
- const [previewFileName, setPreviewFileName] = useState('')
- const [previewFileType, setPreviewFileType] = useState('')
-
- const form = useForm({
- initialValues: {
- status: '',
- },
- })
-
- const handleFilePreview = (fileId: number, fileName: string) => {
- setPreviewFileId(fileId)
- setPreviewFileName(fileName)
- setPreviewFileType(getMimeType(fileName))
- }
-
- const handleFileDownload = async (fileId: number, fileName: string) => {
- try {
- const token = localStorage.getItem('token')
- const timestamp = Math.floor(Date.now() / 1000).toString()
- const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
- const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
- const message = publicKey + ':' + timestamp
- const CryptoJS = await import('crypto-js')
- const signature = CryptoJS.HmacSHA256(message, privateKey).toString(CryptoJS.enc.Hex)
- const deviceId = localStorage.getItem('device_id') || 'admin-panel'
-
- // 🆕 Используем URL для задач
- const url = `/api/approval-tasks/${taskId}/files/${fileId}/download`
-
- const response = await fetch(url, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'ApiKey': signature,
- 'X-Timestamp': timestamp,
- 'x-device-id': deviceId,
- },
- })
-
- if (!response.ok) throw new Error('Failed to download file')
-
- const blob = await response.blob()
- const blobUrl = window.URL.createObjectURL(blob)
- const link = document.createElement('a')
- link.href = blobUrl
- link.download = fileName
- document.body.appendChild(link)
- link.click()
- link.remove()
- window.URL.revokeObjectURL(blobUrl)
-
- notifications.show({
- title: 'Успешно',
- message: 'Файл скачан',
- color: 'green',
- })
- } catch (error) {
- notifications.show({
- title: 'Ошибка',
- message: 'Не удалось скачать файл',
- color: 'red',
- })
- }
- }
-
- const handleSubmit = async (values: typeof form.values) => {
- if (!task?.id) return
- await updateTask.mutateAsync({
- id: task.id,
- status: values.status,
- })
- onClose()
- }
-
- return (
- <>
-
- Задача #{taskId}
- {task && (
-
- {STATUS_LABELS[task.status || ''] || task.status}
-
- )}
-
- }
- size="xl"
- styles={{
- body: {
- height: 'calc(80vh - 120px)',
- padding: 0,
- },
- }}
- >
- {isLoading ? (
-
-
-
- ) : task ? (
-
-
-
- {/* Информация о задаче */}
-
- Информация о задаче
-
- Текст задачи:
-
- {task.task_text || '—'}
-
-
- Шаг:
- #{task.step_order}
-
-
- Требует файл:
-
- {task.require_file ? 'Да' : 'Нет'}
-
-
-
-
-
- {/* 🆕 Прикреплённые файлы */}
- {task.files && task.files.length > 0 && (
-
- Прикреплённые файлы
-
- {task.files.map((file) => {
- const mimeType = getMimeType(file.file_name || '')
- const canPreview = PREVIEWABLE_TYPES.includes(mimeType)
- const fileSizeKB = file.file_base64
- ? Math.round((file.file_base64.length * 3 / 4) / 1024)
- : 0
-
- return (
-
-
-
-
-
-
- {file.file_name || 'Без имени'}
-
- {fileSizeKB > 0 && (
-
- {fileSizeKB} KB
-
- )}
-
-
-
- {canPreview && (
-
- handleFilePreview(file.id!, file.file_name || '')}
- >
-
-
-
- )}
-
- handleFileDownload(file.id!, file.file_name || '')}
- >
-
-
-
-
-
-
- )
- })}
-
-
- )}
-
- {/* Связанная заявка */}
- {task.approval && (
-
- Связанная заявка
-
-
- ID заявки:
- #{task.approval.id}
-
-
- Тема:
- {task.approval.topic?.name || '—'}
-
-
- Инициатор:
-
-
- {task.approval.initiator?.full_name || '—'}
-
-
-
- Статус заявки:
- {task.approval.status}
-
-
-
- )}
-
- {/* Исполнитель */}
- {task.executor && (
-
- Исполнитель
-
-
- Имя:
-
-
- {task.executor.full_name}
-
-
- {task.executor.department && (
-
- Отдел:
-
-
- {task.executor.department.name}
-
-
- )}
-
-
- )}
-
- {/* Даты */}
-
- Временные метки
-
-
- Создана:
-
-
-
- {task.created_at
- ? formatMsk(task.created_at)
- : '—'}
-
-
-
-
- Обновлена:
-
- {task.updated_at
- ? formatMsk(task.created_at)
- : '—'}
-
-
- {task.completed_at && (
-
- Выполнена:
-
-
-
- {formatMsk(task.created_at)}
-
-
-
- )}
-
-
-
- {/* Форма обновления статуса */}
-
- Изменить статус
-
-
-
-
-
- ) : (
-
- Задача не найдена
-
- )}
-
-
- {previewFileId && taskId && (
- setPreviewFileId(null)}
- />
- )}
- >
- )
-}
\ No newline at end of file