diff --git a/src/components/ui/ConfirmModal.tsx b/src/components/ui/ConfirmModal.tsx new file mode 100644 index 0000000..2412bac --- /dev/null +++ b/src/components/ui/ConfirmModal.tsx @@ -0,0 +1,29 @@ +import { Button, Group, Modal, Text } from '@mantine/core' +import type { ReactNode } from 'react' + +interface Props { + opened: boolean + onClose: () => void + onConfirm: () => void + title: string + message: ReactNode + confirmLabel?: string + danger?: boolean + loading?: boolean +} + +export function ConfirmModal({ + opened, onClose, onConfirm, title, message, confirmLabel = 'Подтвердить', danger, loading, + }: Props) { + return ( + + {message} + + + + + + ) +} \ No newline at end of file diff --git a/src/components/ui/DataTable.tsx b/src/components/ui/DataTable.tsx new file mode 100644 index 0000000..21baee9 --- /dev/null +++ b/src/components/ui/DataTable.tsx @@ -0,0 +1,90 @@ +import { Group, Pagination, Paper, Skeleton, Table, Text } from '@mantine/core' +import type { ReactNode } from 'react' +import { EmptyState } from './EmptyState' + +export interface Column { + key: string + header: ReactNode + cell: (row: T) => ReactNode + width?: number | string + align?: 'left' | 'right' | 'center' +} + +interface Props { + columns: Column[] + rows: T[] + getRowId: (row: T) => string | number + loading?: boolean // первая загрузка: показываем скелетоны + refreshing?: boolean // перезапрос: приглушаем строки + onRowClick?: (row: T) => void + empty?: { title: string; description?: string } + pagination?: { page: number; pageSize: number; total: number; onChange: (page: number) => void } + minWidth?: number +} + +export function DataTable({ + columns, rows, getRowId, loading, refreshing, onRowClick, + empty = { title: 'Ничего не найдено' }, pagination, minWidth = 800, + }: Props) { + const pages = pagination ? Math.max(1, Math.ceil(pagination.total / pagination.pageSize)) : 1 + const from = pagination ? (pagination.page - 1) * pagination.pageSize + 1 : 0 + const to = pagination ? Math.min(pagination.page * pagination.pageSize, pagination.total) : 0 + + return ( + + + + + + {columns.map((c) => ( + + {c.header} + + ))} + + + + + {loading + ? Array.from({ length: 8 }).map((_, r) => ( + + {columns.map((c, i) => ( + + + + ))} + + )) + : rows.map((row) => ( + onRowClick(row) : undefined} + style={{ cursor: onRowClick ? 'pointer' : undefined }} + > + {columns.map((c) => ( + {c.cell(row)} + ))} + + ))} + +
+
+ + {!loading && rows.length === 0 && ( + + )} + + {pagination && pagination.total > pagination.pageSize && ( + + {from}–{to} из {pagination.total} + + + )} +
+ ) +} \ No newline at end of file diff --git a/src/components/ui/FilterBar.tsx b/src/components/ui/FilterBar.tsx new file mode 100644 index 0000000..33d44fb --- /dev/null +++ b/src/components/ui/FilterBar.tsx @@ -0,0 +1,28 @@ +import { Button, Group } from '@mantine/core' +import { IconX } from '@tabler/icons-react' +import type { ReactNode } from 'react' + +interface Props { + children: ReactNode + activeCount?: number + onReset?: () => void +} + +export function FilterBar({ children, activeCount = 0, onReset }: Props) { + return ( + + {children} + {activeCount > 0 && onReset && ( + + )} + + ) +} \ No newline at end of file diff --git a/src/components/ui/MultiFilter.tsx b/src/components/ui/MultiFilter.tsx new file mode 100644 index 0000000..f96ab8e --- /dev/null +++ b/src/components/ui/MultiFilter.tsx @@ -0,0 +1,64 @@ +import { useMemo, useState } from 'react' +import { Badge, Button, Checkbox, Popover, ScrollArea, Stack, Text, TextInput } from '@mantine/core' +import { IconChevronDown, IconSearch } from '@tabler/icons-react' + +interface Props { + label: string + options: { value: string; label: string }[] + value: string[] + onChange: (value: string[]) => void + width?: number +} + +export function MultiFilter({ label, options, value, onChange, width = 260 }: Props) { + const [query, setQuery] = useState('') + + const filtered = useMemo(() => { + const q = query.trim().toLowerCase() + return q ? options.filter((o) => o.label.toLowerCase().includes(q)) : options + }, [options, query]) + + return ( + + + + + + + } + value={query} + onChange={(e) => setQuery(e.currentTarget.value)} + mb="xs" + /> + + + + {filtered.map((o) => ( + + ))} + + + {filtered.length === 0 && ( + Ничего не найдено + )} + + {value.length > 0 && ( + + )} + + + ) +} \ No newline at end of file diff --git a/src/components/ui/PageHeader.tsx b/src/components/ui/PageHeader.tsx index 725e4d8..4d6fe33 100644 --- a/src/components/ui/PageHeader.tsx +++ b/src/components/ui/PageHeader.tsx @@ -9,7 +9,7 @@ interface Props { export function PageHeader({ title, description, actions }: Props) { return ( - + {title} {description && {description}} diff --git a/src/components/ui/Panel.tsx b/src/components/ui/Panel.tsx new file mode 100644 index 0000000..f2f0923 --- /dev/null +++ b/src/components/ui/Panel.tsx @@ -0,0 +1,20 @@ +import { Group, Paper, Text } from '@mantine/core' +import type { ReactNode } from 'react' + +interface Props { + title: ReactNode + extra?: ReactNode + children: ReactNode +} + +export function Panel({ title, extra, children }: Props) { + return ( + + + {title} + {extra} + + {children} + + ) +} \ No newline at end of file diff --git a/src/components/ui/StatCard.tsx b/src/components/ui/StatCard.tsx new file mode 100644 index 0000000..d36cc42 --- /dev/null +++ b/src/components/ui/StatCard.tsx @@ -0,0 +1,59 @@ +import { Group, Paper, Text, ThemeIcon } from '@mantine/core' +import type { Icon } from '@tabler/icons-react' +import type { ReactNode } from 'react' +import { Link } from 'react-router-dom' +import classes from './ui.module.css' + +function Sparkline({ data, color }: { data: number[]; color: string }) { + if (data.length < 2) return null + const w = 72, h = 28 + const max = Math.max(...data, 1) + const points = data + .map((v, i) => `${(i / (data.length - 1)) * w},${h - 2 - (v / max) * (h - 4)}`) + .join(' ') + return ( + + + + ) +} + +interface Props { + label: string + value: ReactNode + hint?: ReactNode + icon: Icon + color?: string + to?: string + spark?: number[] +} + +export function StatCard({ label, value, hint, icon: IconCmp, color = 'gray', to, spark }: Props) { + const body = ( + <> + + {label} + + + + + + {value} + {spark && } + + {hint && {hint}} + + ) + + if (to) { + return {body} + } + return {body} +} \ No newline at end of file diff --git a/src/components/ui/StatusBadge.tsx b/src/components/ui/StatusBadge.tsx new file mode 100644 index 0000000..6230249 --- /dev/null +++ b/src/components/ui/StatusBadge.tsx @@ -0,0 +1,19 @@ +import { Badge } from '@mantine/core' +import { APPROVAL_STATUS, TASK_STATUS, USER_STATUS } from './statuses' + +const MAPS = { approval: APPROVAL_STATUS, task: TASK_STATUS, user: USER_STATUS } + +export function StatusBadge({ kind, status }: { kind: keyof typeof MAPS; status: string }) { + const meta = MAPS[kind][status] + return ( + + {meta?.label ?? status} + + ) +} + +export function userStatusOf(u: { is_blocked?: boolean; is_fired?: boolean }) { + if (u.is_fired) return 'fired' + if (u.is_blocked) return 'blocked' + return 'active' +} \ No newline at end of file diff --git a/src/components/ui/StatusBreakdown.tsx b/src/components/ui/StatusBreakdown.tsx new file mode 100644 index 0000000..28cdd5d --- /dev/null +++ b/src/components/ui/StatusBreakdown.tsx @@ -0,0 +1,58 @@ +import { Box, Group, Progress, Stack, Text, UnstyledButton } from '@mantine/core' +import { Link } from 'react-router-dom' +import { EmptyState } from './EmptyState' +import type { StatusMeta } from './statuses' +import classes from './ui.module.css' + +interface Props { + items: { status: string; count: number }[] + meta: Record + linkTo: (status: string) => string +} + +export function StatusBreakdown({ items, meta, linkTo }: Props) { + const counts = new Map(items.map((i) => [i.status, i.count])) + const rows = Object.entries(meta).map(([status, m]) => ({ + status, + ...m, + count: counts.get(status) ?? 0, + })) + const total = rows.reduce((s, r) => s + r.count, 0) + + if (total === 0) return + + return ( + + + {rows + .filter((r) => r.count > 0) + .map((r) => ( + + ))} + + + + {rows.map((r) => ( + + + + + {r.plural} + + + {r.count} + + {Math.round((r.count / total) * 100)}% + + + + + ))} + + + ) +} \ No newline at end of file diff --git a/src/components/ui/TrendChart.tsx b/src/components/ui/TrendChart.tsx new file mode 100644 index 0000000..ae9874f --- /dev/null +++ b/src/components/ui/TrendChart.tsx @@ -0,0 +1,74 @@ +import { Box, Group, Text } from '@mantine/core' +import dayjs from 'dayjs' +import { CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts' + +export interface TrendSeries { + key: string + label: string + color: string +} + +interface Props { + data: Record[] + series: TrendSeries[] + xKey?: string + height?: number +} + +const tick = { fill: 'var(--mantine-color-dimmed)', fontSize: 12 } +const colorOf = (c: string) => `var(--mantine-color-${c}-filled)` + +export function TrendChart({ data, series, xKey = 'date', height = 220 }: Props) { + const labels = Object.fromEntries(series.map((s) => [s.key, s.label])) + + return ( + <> + + {series.map((s) => ( + + + {s.label} + + ))} + + + + + + dayjs(d).format('DD.MM')} + tick={tick} + tickLine={false} + axisLine={false} + /> + + dayjs(d).format('D MMMM')} + formatter={(v: any, name: any) => [v, labels[name] ?? name]} + contentStyle={{ + background: 'var(--mantine-color-body)', + border: '1px solid var(--mantine-color-default-border)', + borderRadius: 8, + boxShadow: 'none', + fontSize: 12, + }} + labelStyle={{ color: 'var(--mantine-color-dimmed)', marginBottom: 4 }} + /> + {series.map((s) => ( + + ))} + + + + ) +} \ No newline at end of file diff --git a/src/components/ui/statuses.ts b/src/components/ui/statuses.ts new file mode 100644 index 0000000..a68b6c0 --- /dev/null +++ b/src/components/ui/statuses.ts @@ -0,0 +1,27 @@ +export interface StatusMeta { + label: string // для бейджа конкретной записи + plural: string // для сводок и счётчиков + color: string // цвет Mantine +} + +export const APPROVAL_STATUS: Record = { + pending: { label: 'На согласовании', plural: 'На согласовании', color: 'blue' }, + revision: { label: 'На доработке', plural: 'На доработке', color: 'violet' }, + approved: { label: 'Согласована', plural: 'Согласованы', color: 'green' }, + rejected: { label: 'Отклонена', plural: 'Отклонены', color: 'red' }, + revoked: { label: 'Отозвана', plural: 'Отозваны', color: 'orange' }, + draft: { label: 'Черновик', plural: 'Черновики', color: 'gray' }, +} + +export const TASK_STATUS: Record = { + pending: { label: 'В работе', plural: 'В работе', color: 'blue' }, + waiting: { label: 'В очереди', plural: 'В очереди', color: 'gray' }, + completed: { label: 'Выполнена', plural: 'Выполнены', color: 'green' }, + cancelled: { label: 'Отменена', plural: 'Отменены', color: 'red' }, +} + +export const USER_STATUS: Record = { + active: { label: 'Активен', plural: 'Активные', color: 'green' }, + blocked: { label: 'Заблокирован', plural: 'Заблокированные', color: 'red' }, + fired: { label: 'Уволен', plural: 'Уволенные', color: 'gray' }, +} \ No newline at end of file diff --git a/src/components/ui/ui.module.css b/src/components/ui/ui.module.css new file mode 100644 index 0000000..eab0d3a --- /dev/null +++ b/src/components/ui/ui.module.css @@ -0,0 +1,18 @@ +.interactive, +.row { + display: block; + color: inherit; + text-decoration: none; + transition: background-color 120ms ease; +} + +.interactive:hover, +.row:hover { + background-color: var(--mantine-color-default-hover); +} + +.row { + width: 100%; + padding: 8px; + border-radius: var(--mantine-radius-sm); +} \ No newline at end of file diff --git a/src/lib/plural.ts b/src/lib/plural.ts new file mode 100644 index 0000000..b9d58d6 --- /dev/null +++ b/src/lib/plural.ts @@ -0,0 +1,7 @@ +export function plural(n: number, forms: [string, string, string]) { + const m10 = n % 10 + const m100 = n % 100 + if (m10 === 1 && m100 !== 11) return forms[0] + if (m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14)) return forms[1] + return forms[2] +} \ No newline at end of file diff --git a/src/pages/Dashboard.tsx b/src/pages/Dashboard.tsx index 4a7efbd..84d043a 100644 --- a/src/pages/Dashboard.tsx +++ b/src/pages/Dashboard.tsx @@ -1,602 +1,346 @@ -import { useEffect, useState } from 'react' +import { useState } from 'react' import { - SimpleGrid, - Paper, - Text, - Group, - Stack, - Loader, - Center, - Badge, - Progress, - Alert, - Box, - ThemeIcon, - UnstyledButton, + ActionIcon, Alert, Avatar, Badge, Box, Button, Group, Progress, ScrollArea, + SimpleGrid, Skeleton, Stack, Text, ThemeIcon, Tooltip, UnstyledButton, } from '@mantine/core' import { - IconUsers, - IconFileCheck, - IconBuilding, - IconCategory, - IconAlertTriangle, - IconAlertOctagon, - IconClock, - IconAlertCircle, - IconCircleCheck, - IconChecklist, - IconCalendarOff, - IconChevronRight, - IconUserExclamation, + IconAlertCircle, IconAlertTriangle, IconArrowBackUp, IconCategory, IconChecklist, + IconChevronRight, IconFileCheck, IconRefresh, IconTrendingUp, IconUserExclamation, + type Icon, } from '@tabler/icons-react' -import { - PieChart, - Pie, - Cell, - ResponsiveContainer, - LineChart, - Line, - XAxis, - YAxis, - CartesianGrid, - Tooltip, - Legend, -} from 'recharts' -import { useNavigate } from 'react-router-dom' -import { dashboardApi } from '@/api/dashboard' -import type { DashboardStats } from '@/api/dashboard' +import { useQuery } from '@tanstack/react-query' +import { Link } from 'react-router-dom' import dayjs from 'dayjs' import 'dayjs/locale/ru' -import TopicGapsModal from "@/components/TopicGapsModal.tsx"; +import { dashboardApi } from '@/api/dashboard' +import type { DashboardStats } from '@/api/dashboard' +import { useAuth } from '@/hooks/useAuth' +import TopicGapsModal from '@/components/TopicGapsModal.tsx' +import { PageHeader } from '@/components/ui/PageHeader' +import { Panel } from '@/components/ui/Panel' +import { StatCard } from '@/components/ui/StatCard' +import { StatusBreakdown } from '@/components/ui/StatusBreakdown' +import { TrendChart } from '@/components/ui/TrendChart' +import { APPROVAL_STATUS, TASK_STATUS } from '@/components/ui/statuses' +import { plural } from '@/lib/plural' +import classes from '@/components/ui/ui.module.css' dayjs.locale('ru') -const STATUS_COLORS: Record = { - draft: '#868e96', - pending: '#228be6', - approved: '#40c057', - rejected: '#fa5252', - revoked: '#fd7e14', - revision: '#7950f2', +interface AttentionItem { + id: string + color: string + icon: Icon + title: string + description: string + to?: string + onClick?: () => void } -const STATUS_LABELS: Record = { - draft: 'Черновики', - pending: 'На согласовании', - approved: 'Согласованы', - rejected: 'Отклонены', - revoked: 'Отозваны', - revision: 'На доработке', +function AttentionRow({ item }: { item: AttentionItem }) { + const content = ( + + + + + + {item.title} + {item.description} + + + + ) + + if (item.to) { + return {content} + } + return {content} } -const TASK_STATUS_COLORS: Record = { - pending: '#228be6', - waiting: '#868e96', - completed: '#40c057', - cancelled: '#fa5252', -} - -const TASK_STATUS_LABELS: Record = { - pending: 'В работе', - waiting: 'В очереди', - completed: 'Выполнены', - cancelled: 'Отменены', -} - -export default function Dashboard() { - const navigate = useNavigate() - const [stats, setStats] = useState(null) - const [loading, setLoading] = useState(true) - const [error, setError] = useState(null) - const [topicGapsOpened, setTopicGapsOpened] = useState(false) - - useEffect(() => { - const loadData = async () => { - try { - const response = await dashboardApi.getStats() - setStats(response.data) - } catch (err: any) { - setError(err.response?.data?.error_description || 'Ошибка загрузки') - } finally { - setLoading(false) - } - } - loadData() - }, []) - - if (loading) { - return ( -
- -
- ) - } - - if (error || !stats) { - return ( - } color="red" title="Ошибка"> - {error || 'Не удалось загрузить данные'} - - ) - } - - // Фильтруем нулевые значения для pie chart - const chartData = stats.statusData.filter(s => s.count > 0) - const totalApprovals = chartData.reduce((sum, s) => sum + s.count, 0) - - const taskChartData = stats.taskStatusData.filter(s => s.count > 0) - const totalTasks = taskChartData.reduce((sum, s) => sum + s.count, 0) - - // 🆕 Клик по алерту "просрочены" — ведёт на заявки со status=pending - // и date_to = сегодня минус oldPendingDays (те же самые заявки, что - // посчитаны в oldPendingCount на бэкенде — общее определение "просрочки"). - const goToOldPending = () => { - const cutoff = dayjs().subtract(stats.oldPendingDays, 'day').format('YYYY-MM-DD') - navigate(`/approvals?status=pending&date_to=${cutoff}`) - } - - const goToRevision = () => { - navigate('/approvals?status=revision') - } - - const goToTasksByStatus = (status: string) => { - navigate(`/approval-tasks?status=${status}`) - } - +function DashboardSkeleton() { return ( - {/* Заголовок */} - -
- Dashboard - Обзор системы согласований -
- - {dayjs().format('DD MMMM YYYY')} - -
- - {/* 🆕 Alert теперь кликабельный — ведёт на отфильтрованный список заявок */} - {stats.oldPendingCount > 0 && ( - - } - color="orange" - variant="light" - title={`⚠️ ${stats.oldPendingCount} заявок требуют внимания`} - style={{ cursor: 'pointer' }} - > - - - Есть заявки, которые находятся на согласовании более {stats.oldPendingDays} дней. - - - Посмотреть список - - - - - - )} - - - {/* 🆕 Проблемы конфигурации инициаторов */} - {stats.topicGaps.length > 0 && ( - setTopicGapsOpened(true)} style={{ width: '100%' }}> - - - - - - -
- - {stats.topicGaps.length} {stats.topicGaps.length === 1 ? 'тема без' : 'тем без'} назначенного порядка согласования - - - Есть право создать заявку, но некому её согласовать — сотрудник наткнётся на ошибку в боте. - -
-
- - Показать список - - -
-
-
- )} - - {stats.usersWithoutHierarchy.length > 0 && ( - } - color="red" - variant="light" - title={`${stats.usersWithoutHierarchy.length} сотрудник(ов) без настроенной иерархии`} - > - - У перечисленных ниже есть право создавать заявки, но для их отдела не - настроено вообще ни одного правила согласования:{' '} - - {stats.usersWithoutHierarchy.map(u => u.full_name || `ID ${u.user_id}`).join(', ')} - - - - )} - - - setTopicGapsOpened(false)} - gaps={stats.topicGaps} - /> - - {/* 🆕 Alert теперь кликабельный — ведёт на заявки на доработке */} - {stats.approvals.revision > 0 && ( - - - - - - - -
- Требуют внимания: {stats.approvals.revision} заявок на доработке - - Эти заявки были возвращены согласующими на доработку и требуют действий от инициаторов. - -
-
- -
-
-
- )} - - {/* 🆕 Кто отсутствует сегодня */} - - - - - - - Отсутствуют сегодня{stats.absentToday.length > 0 ? ` (${stats.absentToday.length})` : ''} - - - - {stats.absentToday.length === 0 ? ( - Сегодня все на месте - ) : ( - - {stats.absentToday.map((person, i) => ( - - {person.name} - — {person.description} - - ))} - - )} - - - {/* KPI карточки */} - - 0 ? `${stats.users.blocked} заблокировано` : undefined} - /> - 0 ? `${stats.approvals.pending} в работе` : undefined} - /> - - + + + {[0, 1, 2, 3].map((i) => )} - - {/* Графики по заявкам */} - - {/* Pie chart */} - - - Распределение заявок по статусам - {totalApprovals} всего - - - {chartData.length === 0 ? ( -
- Нет данных -
- ) : ( - - - STATUS_LABELS[entry.payload?.status] || entry.payload?.status} - onClick={(entry: any) => navigate(`/approvals?status=${entry.status}`)} - style={{ cursor: 'pointer' }} - > - {chartData.map((entry, index) => ( - - ))} - - [ - value, - STATUS_LABELS[name] || name - ]} - /> - - - )} -
- - {/* Line chart */} - - - Динамика за 7 дней - Заявки - - - - - - dayjs(d).format('DD.MM')} - /> - - dayjs(d).format('DD.MM.YYYY')} - formatter={(value: any, name: any) => [ - value, - name === 'created' ? 'Создано' : 'Согласовано' - ]} - /> - - value === 'created' ? 'Создано' : 'Согласовано' - } - /> - - - - - -
- - {/* 🆕 Задачи — те же два графика, что у заявок выше */} - - - - - - - - Задачи по статусам - - {totalTasks} всего - - - {taskChartData.length === 0 ? ( -
- Нет данных -
- ) : ( - - - TASK_STATUS_LABELS[entry.payload?.status] || entry.payload?.status} - onClick={(entry: any) => goToTasksByStatus(entry.status)} - style={{ cursor: 'pointer' }} - > - {taskChartData.map((entry, index) => ( - - ))} - - [ - value, - TASK_STATUS_LABELS[name] || name - ]} - /> - - - )} -
- - - - Динамика задач за 7 дней - Задачи - - - - - - dayjs(d).format('DD.MM')} - /> - - dayjs(d).format('DD.MM.YYYY')} - formatter={(value: any, name: any) => [ - value, - name === 'created' ? 'Создано' : 'Выполнено' - ]} - /> - - value === 'created' ? 'Создано' : 'Выполнено' - } - /> - - - - - -
- - {/* Разбивка по категориям + узкие места */} - - {/* Разбивка по категориям */} - - - - - - Заявки по категориям - - - {stats.categoryBreakdown.length === 0 ? ( -
- Нет данных -
- ) : ( - - {stats.categoryBreakdown.map((cat) => { - const maxCount = Math.max(...stats.categoryBreakdown.map(c => c.total_count)) - const percent = maxCount > 0 ? (cat.total_count / maxCount) * 100 : 0 - - return ( - - - {cat.name} - - {cat.total_count} - {cat.pending_count > 0 && ( - - {cat.pending_count} в работе - - )} - - - - - ) - })} - - )} -
+ + +
) } -// Компонент карточки статистики -interface StatCardProps { - title: string - value: number | string - subtitle?: string - icon: any - color: string - trend?: string -} +const countOf = (items: { status: string; count: number }[], status: string) => + items.find((i) => i.status === status)?.count ?? 0 -function StatCard({ title, value, subtitle, icon: Icon, color, trend }: StatCardProps) { - return ( - - - - - {title} - - - {value} - - {subtitle && ( - - {subtitle} - - )} +export default function Dashboard() { + const { user } = useAuth() + const isObserver = user?.is_observer === true + const [gapsOpened, setGapsOpened] = useState(false) + + const { data: stats, isLoading, isFetching, error, refetch } = useQuery({ + queryKey: ['dashboard-stats'], + queryFn: async () => (await dashboardApi.getStats()).data as DashboardStats, + refetchInterval: 60_000, + }) + + if (isLoading) return + + if (error || !stats) { + const message = (error as any)?.response?.data?.error_description || 'Не удалось загрузить данные' + return ( + } color="red" title="Ошибка"> + + {message} + - - - - + + ) + } - {trend && ( - - {trend} - + // --- производные метрики --- + const tasksInWork = countOf(stats.taskStatusData, 'pending') + const tasksQueued = countOf(stats.taskStatusData, 'waiting') + const createdSeries = stats.dailyData.map((d) => d.created) + const created7 = createdSeries.reduce((s, v) => s + v, 0) + const approved7 = stats.dailyData.reduce((s, d) => s + d.approved, 0) + const cutoff = dayjs().subtract(stats.oldPendingDays, 'day').format('YYYY-MM-DD') + + // --- «Требует внимания» --- + const attention: AttentionItem[] = [] + + if (stats.oldPendingCount > 0) { + const n = stats.oldPendingCount + const d = stats.oldPendingDays + attention.push({ + id: 'old', + color: 'orange', + icon: IconAlertTriangle, + title: `${n} ${plural(n, ['заявка', 'заявки', 'заявок'])} на согласовании дольше ${d} ${plural(d, ['дня', 'дней', 'дней'])}`, + description: 'Стоит напомнить согласующим', + to: `/approvals?status=pending&date_to=${cutoff}`, + }) + } + + if (stats.approvals.revision > 0) { + const n = stats.approvals.revision + attention.push({ + id: 'revision', + color: 'violet', + icon: IconArrowBackUp, + title: `${n} ${plural(n, ['заявка', 'заявки', 'заявок'])} на доработке`, + description: 'Возвращены согласующими, ждут действий инициатора', + to: '/approvals?status=revision', + }) + } + + if (!isObserver && stats.topicGaps.length > 0) { + const n = stats.topicGaps.length + attention.push({ + id: 'gaps', + color: 'orange', + icon: IconCategory, + title: `${n} ${plural(n, ['тема', 'темы', 'тем'])} без порядка согласования`, + description: 'Сотрудник сможет создать заявку, но согласовать её будет некому', + onClick: () => setGapsOpened(true), + }) + } + + if (!isObserver && stats.usersWithoutHierarchy.length > 0) { + const list = stats.usersWithoutHierarchy + const names = list.slice(0, 3).map((u) => u.full_name || `ID ${u.user_id}`).join(', ') + const rest = list.length - 3 + attention.push({ + id: 'hierarchy', + color: 'red', + icon: IconUserExclamation, + title: `${list.length} ${plural(list.length, ['сотрудник', 'сотрудника', 'сотрудников'])} без иерархии согласования`, + description: rest > 0 ? `${names} и ещё ${rest}` : names, + to: '/hierarchies', + }) + } + + const maxCategory = Math.max(1, ...stats.categoryBreakdown.map((c) => c.total_count)) + + const catalog = [ + { label: 'Пользователи', value: stats.users.total, to: '/users', + hint: stats.users.blocked > 0 ? `${stats.users.blocked} заблокировано` : `${stats.users.active} активных` }, + { label: 'Темы', value: stats.topics.total, to: '/topics', hint: `${stats.topics.active} активных` }, + { label: 'Категории', value: stats.categories, to: '/categories' }, + { label: 'Отделы', value: stats.departments, to: '/departments' }, + { label: 'Роли', value: stats.roles, to: '/roles' }, + { label: 'Исполнители', value: stats.executors, to: '/executors' }, + ] + + return ( + + + refetch()} aria-label="Обновить"> + + + + } + /> + + {attention.length > 0 && ( + {attention.length}}> + + {attention.map((item) => )} + + )} - + + + 0 ? `${stats.oldPendingCount} просрочено` : 'Просрочек нет'} + icon={IconFileCheck} + color={stats.oldPendingCount > 0 ? 'orange' : 'brand'} + to="/approvals?status=pending" + /> + + + + + + + Всего {stats.approvals.total}} + > + `/approvals?status=${s}`} + /> + + + + + + + + + + `/approval-tasks?status=${s}`} + /> + + + + + + + + + + {stats.categoryBreakdown.length === 0 ? ( + Нет данных + ) : ( + + {stats.categoryBreakdown.map((cat) => ( + + + {cat.name} + + {cat.pending_count > 0 && ( + {cat.pending_count} в работе + )} + {cat.total_count} + + + + + ))} + + )} + + + 0 && {stats.absentToday.length}} + > + {stats.absentToday.length === 0 ? ( + Сегодня все на месте + ) : ( + + + {stats.absentToday.map((p, i) => ( + + + + {p.name} + {p.description} + + + ))} + + + )} + + + + {!isObserver && ( + + + {catalog.map((c) => ( + + {c.label} + {c.value} + {c.hint && {c.hint}} + + ))} + + + )} + + setGapsOpened(false)} + gaps={stats.topicGaps} + /> +
) } \ No newline at end of file diff --git a/src/pages/users/UsersPage.tsx b/src/pages/users/UsersPage.tsx index d49fa76..2810d16 100644 --- a/src/pages/users/UsersPage.tsx +++ b/src/pages/users/UsersPage.tsx @@ -1,38 +1,51 @@ -import { useState, useMemo } from 'react' +import { useMemo, useState } from 'react' import { - Paper, - Table, - Badge, - Group, - ActionIcon, - Text, - TextInput, - Select, - MultiSelect, - Pagination, - Loader, - Center, - Tooltip, - Box, - Stack, - Modal, - Button, + ActionIcon, Avatar, Badge, Box, Group, Menu, SegmentedControl, Select, Stack, Text, + TextInput, Tooltip, } from '@mantine/core' -import { IconPencil, IconSearch, IconTrash } from '@tabler/icons-react' +import { useDebouncedValue } from '@mantine/hooks' +import { IconDots, IconPencil, IconSearch, IconTrash } from '@tabler/icons-react' import { useUsers, useDeleteUser } from '@/features/users/hooks/useUsers' import { useDepartments } from '@/features/users/hooks/useDepartments' import { useRoles } from '@/features/users/hooks/useRoles' -import UserEditModal from "@/components/UserEditModal.tsx" +import UserEditModal from '@/components/UserEditModal.tsx' import { useAuth } from '@/hooks/useAuth' +import { PageHeader } from '@/components/ui/PageHeader' +import { FilterBar } from '@/components/ui/FilterBar' +import { MultiFilter } from '@/components/ui/MultiFilter' +import { DataTable, type Column } from '@/components/ui/DataTable' +import { ConfirmModal } from '@/components/ui/ConfirmModal' +import { StatusBadge, userStatusOf } from '@/components/ui/StatusBadge' const LIMIT = 20 +const MAX_ROLES = 2 + +type StatusFilter = 'all' | 'active' | 'blocked' | 'fired' + +function RoleBadges({ roles }: { roles?: { id?: number; role?: { name?: string } }[] }) { + if (!Array.isArray(roles) || roles.length === 0) return — + const rest = roles.slice(MAX_ROLES) + return ( + + {roles.slice(0, MAX_ROLES).map((ur, i) => ( + {ur.role?.name ?? 'Роль'} + ))} + {rest.length > 0 && ( + r.role?.name).join(', ')} multiline w={220}> + +{rest.length} + + )} + + ) +} export default function UsersPage() { const [page, setPage] = useState(1) const [search, setSearch] = useState('') - const [selectedRoleIds, setSelectedRoleIds] = useState([]) // ✅ Массив ID ролей - const [departmentFilter, setDepartmentFilter] = useState(null) - const [statusFilter, setStatusFilter] = useState(null) + const [debouncedSearch] = useDebouncedValue(search.trim(), 300) + const [roleIds, setRoleIds] = useState([]) + const [department, setDepartment] = useState(null) + const [status, setStatus] = useState('all') const [editUserId, setEditUserId] = useState(null) const [deleteUserId, setDeleteUserId] = useState(null) @@ -42,37 +55,40 @@ export default function UsersPage() { const { data, isLoading, isFetching } = useUsers({ offset: (page - 1) * LIMIT, limit: LIMIT, - ...(departmentFilter && { department_id: Number(departmentFilter) }), - ...(statusFilter === 'blocked' && { is_blocked: true }), - ...(statusFilter === 'fired' && { is_fired: true }), - ...(statusFilter === 'active' && { is_blocked: false, is_fired: false }), - ...(search && { full_name: search }), - ...(selectedRoleIds.length > 0 && { role_ids: selectedRoleIds }), // ✅ Передаём массив + ...(department && { department_id: Number(department) }), + ...(status === 'blocked' && { is_blocked: true }), + ...(status === 'fired' && { is_fired: true }), + ...(status === 'active' && { is_blocked: false, is_fired: false }), + ...(debouncedSearch && { full_name: debouncedSearch }), + ...(roleIds.length > 0 && { role_ids: roleIds.map(Number) }), }) const { data: departments } = useDepartments() - const { data: allRoles } = useRoles({ limit: 1000 }) // ✅ Получаем все роли + const { data: allRoles } = useRoles({ limit: 1000 }) const deleteUser = useDeleteUser() - const departmentOptions = useMemo(() => { - if (!departments || !Array.isArray(departments)) return [] - return departments.map((d) => ({ - value: String(d.id), - label: d.name || '', - })) - }, [departments]) - - const roleOptions = useMemo(() => { - if (!allRoles || !Array.isArray(allRoles)) return [] - return allRoles.map((r) => ({ - value: String(r.id), - label: r.name || '', - })) - }, [allRoles]) + const departmentOptions = useMemo( + () => (Array.isArray(departments) ? departments.map((d) => ({ value: String(d.id), label: d.name || '' })) : []), + [departments], + ) + const roleOptions = useMemo( + () => (Array.isArray(allRoles) ? allRoles.map((r) => ({ value: String(r.id), label: r.name || '' })) : []), + [allRoles], + ) const users = Array.isArray(data?.data) ? data.data : [] - const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1 - const hasSelected = selectedRoleIds.length > 0; + const total = data?.total_count ?? 0 + + const activeFilters = + (search ? 1 : 0) + (roleIds.length ? 1 : 0) + (department ? 1 : 0) + (status !== 'all' ? 1 : 0) + + const resetFilters = () => { + setSearch('') + setRoleIds([]) + setDepartment(null) + setStatus('all') + setPage(1) + } const handleDelete = async () => { if (!deleteUserId) return @@ -80,215 +96,140 @@ export default function UsersPage() { setDeleteUserId(null) } - return ( - - - Пользователи - - Всего: {data?.total_count || 0} - - - - - - } - value={search} - onChange={(e) => { - setSearch(e.currentTarget.value) - setPage(1) - }} - style={{ flex: 1 }} - /> - - - { - setSelectedRoleIds(v.map(Number)) - setPage(1) - }} - searchable - clearable - maxDropdownHeight={400} - limit={15} - styles={{ - input: { - minHeight: 36, - }, - pill: { - display: 'none', - }, - pillsList: { - display: 'none', - }, - }} - /> + const columns: Column<(typeof users)[number]>[] = [ + { + key: 'id', + header: 'ID', + width: 70, + cell: (u) => {u.id}, + }, + { + key: 'user', + header: 'Пользователь', + cell: (u) => ( + + + + {u.full_name} + {u.username ? `@${u.username}` : '—'} - - { - setStatusFilter(v) - setPage(1) - }} - clearable - style={{ minWidth: 180 }} - /> - - - - {isLoading ? ( -
- -
- ) : ( - <> - - - - ID - Telegram ID - Имя - Username - Отдел - Роли - Статус - Действия - - - - {users.length === 0 ? ( - - -
- Пользователи не найдены -
-
-
- ) : ( - users.map((user) => ( - - {user.id} - - {user.telegram_id} - - - {user.full_name} - - - @{user.username || '—'} - - - {user.department?.name || —} - - - - {Array.isArray(user.user_roles) ? ( - <> - {user.user_roles.slice(0, 3).map((ur) => ( - - {ur.role?.name || 'Роль'} - - ))} - {user.user_roles.length > 3 && ( - - +{user.user_roles.length - 3} - - )} - - ) : ( - — - )} - - - - - - - - - setEditUserId(user.id!)} - > - - - - {isRootAdmin && ( - - setDeleteUserId(user.id!)} - > - - - - )} - - - - )) - )} -
-
- - {totalPages > 1 && ( - - - - Страница {page} из {totalPages} - - - - + ), + }, + { + key: 'telegram', + header: 'Telegram ID', + cell: (u) => {u.telegram_id}, + }, + { + key: 'department', + header: 'Отдел', + cell: (u) => {u.department?.name || —}, + }, + { + key: 'roles', + header: 'Роли', + cell: (u) => , + }, + { + key: 'status', + header: 'Статус', + cell: (u) => , + }, + { + key: 'actions', + header: '', + width: 56, + align: 'right', + cell: (u) => ( + + + e.stopPropagation()}> + + + + e.stopPropagation()}> + } onClick={() => setEditUserId(u.id!)}> + Редактировать + + {isRootAdmin && ( + <> + + } onClick={() => setDeleteUserId(u.id!)}> + Удалить + + )} - - )} - + + + ), + }, + ] - {isFetching && !isLoading && ( - - - - )} + return ( + + + + + } + value={search} + onChange={(e) => { + setSearch(e.currentTarget.value) + setPage(1) + }} + w={260} + /> + { + setRoleIds(v) + setPage(1) + }} + /> +