= {
- global: 'Глобальное',
- category: 'Категория',
- topic: 'Тема',
-}
------END src/features/hierarchies/utils.ts-----
-
-File: src/features/notifications/hooks/useNotifications.ts
-Lines: 55
------BEGIN src/features/notifications/hooks/useNotifications.ts-----
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import {
- notificationsApi,
- type NotificationsListParams,
- type CreateNotificationRequest,
-} from '@/api/notifications'
-import { notifications as mantineNotifications } from '@mantine/notifications'
-
-export const NOTIFICATIONS_QUERY_KEY = 'notifications'
-
-export function useNotifications(params: NotificationsListParams = {}) {
- return useQuery({
- queryKey: [NOTIFICATIONS_QUERY_KEY, params],
- queryFn: async () => {
- const response = await notificationsApi.getList(params)
- return response.data
- },
- })
-}
-
-export function useNotification(id: number | null) {
- return useQuery({
- queryKey: ['notification', id],
- queryFn: async () => {
- if (!id) return null
- const response = await notificationsApi.getById(id)
- return response.data
- },
- enabled: !!id,
- })
-}
-
-export function useCreateNotification() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (data: CreateNotificationRequest) => notificationsApi.create(data),
- onSuccess: (response) => {
- queryClient.invalidateQueries({ queryKey: [NOTIFICATIONS_QUERY_KEY] })
- const n = response.data
- const hasFailed = (n.failed_count ?? 0) > 0
- mantineNotifications.show({
- title: hasFailed ? 'Отправлено с ошибками' : 'Отправлено',
- message: `Доставлено: ${n.sent_count ?? 0} из ${n.total_count ?? 0}`,
- color: hasFailed ? 'yellow' : 'green',
- })
- },
- onError: (error: any) => {
- mantineNotifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось отправить уведомление',
- color: 'red',
- })
- },
- })
-}
------END src/features/notifications/hooks/useNotifications.ts-----
-
-File: src/features/notifications/utils/telegramHtml.ts
-Lines: 30
------BEGIN src/features/notifications/utils/telegramHtml.ts-----
-// Приводит HTML из Tiptap-редактора к набору тегов, которые понимает Telegram ParseMode=HTML.
-// Разрешённые теги: b, i, u, s, a, code, pre, tg-spoiler
-const ALLOWED_TAGS = new Set(['b', 'i', 'u', 's', 'a', 'code', 'pre', 'tg-spoiler'])
-
-export function convertHtmlToTelegram(html: string): string {
- let result = html
-
- // Абзацы и переносы строк -> двойной/одинарный \n
- result = result.replace(/<\/p>\s*/gi, '\n\n')
- result = result.replace(/<\/?p>/gi, '')
- result = result.replace(/
/gi, '\n')
-
- // Синонимы тегов из Tiptap -> Telegram-теги
- result = result
- .replace(//gi, '').replace(/<\/strong>/gi, '')
- .replace(//gi, '').replace(/<\/em>/gi, '')
- .replace(//gi, '').replace(/<\/strike>/gi, '')
-
- // Ссылки: сохраняем только href, убираем target/rel/class и т.п.
- result = result.replace(/]*href="([^"]*)"[^>]*>/gi, '')
-
- // Убираем все теги, не входящие в белый список Telegram
- result = result.replace(/<(\/?)([a-zA-Z0-9-]+)([^>]*)>/g, (match, closing, rawTag) => {
- const tag = rawTag.toLowerCase()
- if (!ALLOWED_TAGS.has(tag)) return ''
- if (tag === 'a' && !closing) return match // href уже нормализован выше
- return closing ? `${tag}>` : `<${tag}>`
- })
-
- return result.trim()
-}
------END src/features/notifications/utils/telegramHtml.ts-----
-
-File: src/features/permissions/constants.ts
-Lines: 28
------BEGIN src/features/permissions/constants.ts-----
-export const PERMISSION_ACTIONS = [
- { value: 'create', label: 'Создание', description: 'Создание заявок по теме', color: 'blue' },
- { value: 'read', label: 'Просмотр', description: 'Просмотр заявок', color: 'gray' },
- { value: 'update', label: 'Редактирование', description: 'Редактирование заявок', color: 'cyan' },
- { value: 'delete', label: 'Удаление', description: 'Удаление заявок', color: 'red' },
- { value: 'approve', label: 'Согласование', description: 'Согласование заявок', color: 'green' },
- { value: 'revoke', label: 'Отзыв', description: 'Отзыв заявок', color: 'orange' },
- { value: 'observe', label: 'Наблюдение', description: 'Наблюдение за заявками', color: 'violet' },
-] as const
-
-export const ACTION_COLORS: Record = {
- create: 'blue',
- read: 'gray',
- update: 'cyan',
- delete: 'red',
- approve: 'green',
- revoke: 'orange',
- observe: 'violet',
-}
-
-export const ACTION_LABELS: Record = {
- create: 'Создание',
- read: 'Просмотр',
- update: 'Редактирование',
- delete: 'Удаление',
- approve: 'Согласование',
- revoke: 'Отзыв',
- observe: 'Наблюдение',
-}
------END src/features/permissions/constants.ts-----
-
-File: src/features/permissions/hooks/usePermissions.ts
-Lines: 100
------BEGIN src/features/permissions/hooks/usePermissions.ts-----
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import {
- permissionsApi,
- type PermissionsListParams,
- type CreatePermissionRequest,
- type UpdatePermissionRequest
-} from '@/api/permissions'
-import { notifications } from '@mantine/notifications'
-
-export const PERMISSIONS_QUERY_KEY = 'permissions'
-
-export function usePermissions(params: PermissionsListParams = {}) {
- return useQuery({
- queryKey: [PERMISSIONS_QUERY_KEY, params],
- queryFn: async () => {
- const response = await permissionsApi.getList(params)
- return response.data
- },
- })
-}
-
-export function usePermission(id: number | null) {
- return useQuery({
- queryKey: ['permission', id],
- queryFn: async () => {
- if (!id) return null
- const response = await permissionsApi.getById(id)
- return response.data
- },
- enabled: !!id,
- })
-}
-
-export function useCreatePermission() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (data: CreatePermissionRequest) => permissionsApi.create(data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [PERMISSIONS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Право создано',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось создать право',
- color: 'red',
- })
- },
- })
-}
-
-export function useUpdatePermission() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (data: UpdatePermissionRequest) => permissionsApi.update(data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [PERMISSIONS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Право обновлено',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось обновить право',
- color: 'red',
- })
- },
- })
-}
-
-export function useDeletePermission() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (id: number) => permissionsApi.delete(id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [PERMISSIONS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Право удалено',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось удалить право',
- color: 'red',
- })
- },
- })
-}
------END src/features/permissions/hooks/usePermissions.ts-----
-
-File: src/features/roles/hooks/useAllRoles.ts
-Lines: 14
------BEGIN src/features/roles/hooks/useAllRoles.ts-----
-import { useQuery } from '@tanstack/react-query'
-import { rolesApi } from '@/api/roles.ts'
-import type { Role } from '@/types/api'
-
-export const ALL_ROLES_QUERY_KEY = 'roles-all'
-
-export function useAllRoles() {
- return useQuery({
- queryKey: [ALL_ROLES_QUERY_KEY],
- queryFn: async (): Promise => {
- const response = await rolesApi.getList({ limit: 1000 })
- return response.data.data || []
- },
- })
-}
------END src/features/roles/hooks/useAllRoles.ts-----
-
-File: src/features/roles/hooks/useRoles.ts
-Lines: 102
------BEGIN src/features/roles/hooks/useRoles.ts-----
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import {
- rolesApi,
- type RolesListParams,
- type CreateRoleRequest,
- type UpdateRoleRequest
-} from '@/api/roles'
-import { notifications } from '@mantine/notifications'
-
-export const ROLES_QUERY_KEY = 'roles'
-
-export function useRoles(params: RolesListParams = {}) {
- return useQuery({
- queryKey: [ROLES_QUERY_KEY, params],
- queryFn: async () => {
- const response = await rolesApi.getList(params)
- return response.data
- },
- })
-}
-
-export function useRole(id: number | null) {
- return useQuery({
- queryKey: ['role', id],
- queryFn: async () => {
- if (!id) return null
- const response = await rolesApi.getById(id)
- return response.data
- },
- enabled: !!id,
- })
-}
-
-export function useCreateRole() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (data: CreateRoleRequest) => rolesApi.create(data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [ROLES_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Роль создана',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось создать роль',
- color: 'red',
- })
- },
- })
-}
-
-export function useUpdateRole() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (data: UpdateRoleRequest) => rolesApi.update(data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [ROLES_QUERY_KEY] })
- queryClient.invalidateQueries({ queryKey: ['users'] }) // Обновляем пользователей, т.к. у них есть роли
- notifications.show({
- title: 'Успешно',
- message: 'Роль обновлена',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось обновить роль',
- color: 'red',
- })
- },
- })
-}
-
-export function useDeleteRole() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (id: number) => rolesApi.delete(id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [ROLES_QUERY_KEY] })
- queryClient.invalidateQueries({ queryKey: ['users'] })
- notifications.show({
- title: 'Успешно',
- message: 'Роль удалена',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось удалить роль',
- color: 'red',
- })
- },
- })
-}
------END src/features/roles/hooks/useRoles.ts-----
-
-File: src/features/topicExecutors/hooks/useTopicExecutors.ts
-Lines: 88
------BEGIN src/features/topicExecutors/hooks/useTopicExecutors.ts-----
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import {
- topicExecutorsApi,
- type TopicExecutorsListParams,
- type CreateTopicExecutorRequest,
- type UpdateTopicExecutorRequest
-} from '@/api/topicExecutors'
-import { notifications } from '@mantine/notifications'
-
-export const TOPIC_EXECUTORS_QUERY_KEY = 'topic-executors'
-
-export function useTopicExecutors(params: TopicExecutorsListParams = {}) {
- return useQuery({
- queryKey: [TOPIC_EXECUTORS_QUERY_KEY, params],
- queryFn: async () => {
- const response = await topicExecutorsApi.getList({ limit: 1000, ...params })
- return response.data
- },
- })
-}
-
-export function useCreateTopicExecutor() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (data: CreateTopicExecutorRequest) => topicExecutorsApi.create(data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [TOPIC_EXECUTORS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Исполнитель добавлен',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось добавить исполнителя',
- color: 'red',
- })
- },
- })
-}
-
-export function useUpdateTopicExecutor() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (data: UpdateTopicExecutorRequest) => topicExecutorsApi.update(data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [TOPIC_EXECUTORS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Исполнитель обновлен',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось обновить исполнителя',
- color: 'red',
- })
- },
- })
-}
-
-export function useDeleteTopicExecutor() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (id: number) => topicExecutorsApi.delete(id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [TOPIC_EXECUTORS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Исполнитель удален',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось удалить исполнителя',
- color: 'red',
- })
- },
- })
-}
------END src/features/topicExecutors/hooks/useTopicExecutors.ts-----
-
-File: src/features/topicExecutors/utils.ts
-Lines: 58
------BEGIN src/features/topicExecutors/utils.ts-----
-import type { ApprovalTopicExecutor } from '@/types/api'
-
-// Группа исполнителей по теме
-export interface TopicExecutorsGroup {
- topicId: number
- topicName: string
- topicCode: string
- categoryName?: string
- executors: ApprovalTopicExecutor[] // Отсортированы по step_order
-}
-
-// Константы для целевых систем
-export const TARGET_SYSTEMS = [
- { value: 'all', label: 'Все системы', color: 'blue' },
- { value: 'okb', label: 'ОКБ', color: 'green' },
- { value: '1c', label: '1С', color: 'orange' },
-] as const
-
-export const TARGET_SYSTEM_LABELS: Record = {
- all: 'Все системы',
- okb: 'ОКБ',
- '1c': '1С',
-}
-
-export const TARGET_SYSTEM_COLORS: Record = {
- all: 'blue',
- okb: 'green',
- '1c': 'orange',
-}
-
-// Группируем исполнителей по темам
-export function groupExecutorsByTopic(
- executors: ApprovalTopicExecutor[]
-): TopicExecutorsGroup[] {
- const groups = new Map()
-
- for (const executor of executors) {
- if (!executor.topic_id) continue
-
- if (!groups.has(executor.topic_id)) {
- groups.set(executor.topic_id, {
- topicId: executor.topic_id,
- topicName: executor.topic?.name || `Тема #${executor.topic_id}`,
- topicCode: executor.topic?.code || '',
- categoryName: executor.topic?.category?.name,
- executors: [],
- })
- }
-
- groups.get(executor.topic_id)!.executors.push(executor)
- }
-
- // Сортируем исполнителей по step_order внутри каждой группы
- for (const group of groups.values()) {
- group.executors.sort((a, b) => (a.step_order || 0) - (b.step_order || 0))
- }
-
- return Array.from(groups.values())
-}
------END src/features/topicExecutors/utils.ts-----
-
-File: src/features/topics/constants.ts
-Lines: 37
------BEGIN src/features/topics/constants.ts-----
-export const DURATION_TYPES = [
- { value: 'single_day', label: 'Один день' },
- { value: 'multi_day', label: 'Несколько дней' },
- { value: 'date_range', label: 'Диапазон дат' },
-]
-
-export const TIME_TYPES = [
- { value: 'partial', label: 'Частично (с указанием времени)' },
- { value: 'full_day', label: 'Весь день' },
-]
-
-export const PAYMENT_TYPES = [
- { value: 'own_expense', label: 'За свой счёт' },
- { value: 'vacation_account', label: 'В счёт отпуска' },
- { value: 'official', label: 'Официально (больничный)' },
-]
-
-export const APPROVAL_MODES = [
- { value: 'sequential', label: 'Последовательное' },
- { value: 'parallel', label: 'Параллельное' },
-]
-
-export const DURATION_LABELS: Record = {
- single_day: 'Один день',
- multi_day: 'Несколько дней',
- date_range: 'Диапазон',
-}
-
-export const TIME_LABELS: Record = {
- partial: 'Частично',
- full_day: 'Весь день',
-}
-
-export const PAYMENT_LABELS: Record = {
- own_expense: 'За свой счёт',
- vacation_account: 'В счёт отпуска',
- official: 'Официально',
-}
------END src/features/topics/constants.ts-----
-
-File: src/features/topics/hooks/useTopics.ts
-Lines: 100
------BEGIN src/features/topics/hooks/useTopics.ts-----
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import {
- topicsApi,
- type TopicsListParams,
- type CreateTopicRequest,
- type UpdateTopicRequest
-} from '@/api/topics'
-import { notifications } from '@mantine/notifications'
-
-export const TOPICS_QUERY_KEY = 'topics'
-
-export function useTopics(params: TopicsListParams = {}) {
- return useQuery({
- queryKey: [TOPICS_QUERY_KEY, params],
- queryFn: async () => {
- const response = await topicsApi.getList(params)
- return response.data
- },
- })
-}
-
-export function useTopic(id: number | null) {
- return useQuery({
- queryKey: ['topic', id],
- queryFn: async () => {
- if (!id) return null
- const response = await topicsApi.getById(id)
- return response.data
- },
- enabled: !!id,
- })
-}
-
-export function useCreateTopic() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (data: CreateTopicRequest) => topicsApi.create(data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [TOPICS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Тема создана',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось создать тему',
- color: 'red',
- })
- },
- })
-}
-
-export function useUpdateTopic() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (data: UpdateTopicRequest) => topicsApi.update(data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [TOPICS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Тема обновлена',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось обновить тему',
- color: 'red',
- })
- },
- })
-}
-
-export function useDeleteTopic() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (id: number) => topicsApi.delete(id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [TOPICS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Тема удалена',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось удалить тему',
- color: 'red',
- })
- },
- })
-}
------END src/features/topics/hooks/useTopics.ts-----
-
-File: src/features/users/hooks/useDepartments.ts
-Lines: 13
------BEGIN src/features/users/hooks/useDepartments.ts-----
-import { useQuery } from '@tanstack/react-query'
-import { departmentsApi } from '@/api/departments.ts'
-
-export const DEPARTMENTS_QUERY_KEY = 'departments'
-
-export function useDepartments() {
- return useQuery({
- queryKey: [DEPARTMENTS_QUERY_KEY],
- queryFn: async () => {
- const response = await departmentsApi.getList()
- return response.data.data || []
- },
- })
-}
------END src/features/users/hooks/useDepartments.ts-----
-
-File: src/features/users/hooks/useRoles.ts
-Lines: 13
------BEGIN src/features/users/hooks/useRoles.ts-----
-import { useQuery } from '@tanstack/react-query'
-import { rolesApi } from '@/api/roles.ts'
-
-export const ROLES_QUERY_KEY = 'roles'
-
-export function useRoles(params: import('@/api/roles').RolesListParams = {}) {
- return useQuery({
- queryKey: [ROLES_QUERY_KEY, params],
- queryFn: async () => {
- const response = await rolesApi.getList(params)
- return response.data.data || []
- },
- })
-}
------END src/features/users/hooks/useRoles.ts-----
-
-File: src/features/users/hooks/useUserRoles.ts
-Lines: 39
------BEGIN src/features/users/hooks/useUserRoles.ts-----
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import { userRolesApi } from '@/api/userRoles.ts'
-import { notifications } from '@mantine/notifications'
-import { USERS_QUERY_KEY } from './useUsers.ts'
-
-export function useUserRoles(userId: number | null) {
- return useQuery({
- queryKey: ['user-roles', userId],
- queryFn: async () => {
- if (!userId) return []
- const response = await userRolesApi.getByUserId(userId)
- return response.data.data || []
- },
- enabled: !!userId,
- })
-}
-
-export function useBulkAssignRoles() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: userRolesApi.bulkAssign,
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [USERS_QUERY_KEY] })
- queryClient.invalidateQueries({ queryKey: ['user-roles'] })
- notifications.show({
- title: 'Успешно',
- message: 'Роли обновлены',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось обновить роли',
- color: 'red',
- })
- },
- })
-}
------END src/features/users/hooks/useUserRoles.ts-----
-
-File: src/features/users/hooks/useUsers.ts
-Lines: 73
------BEGIN src/features/users/hooks/useUsers.ts-----
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import { usersApi, type UsersListParams, type UpdateUserRequest } from '@/api/users.ts'
-import { notifications } from '@mantine/notifications'
-
-export const USERS_QUERY_KEY = 'users'
-
-export function useUsers(params: UsersListParams = {}) {
- return useQuery({
- queryKey: [USERS_QUERY_KEY, params],
- queryFn: async () => {
- const response = await usersApi.getList(params)
- return response.data
- },
- })
-}
-
-export function useUser(id: number | null) {
- return useQuery({
- queryKey: ['user', id],
- queryFn: async () => {
- if (!id) return null
- const response = await usersApi.getById(id)
- return response.data
- },
- enabled: !!id,
- })
-}
-
-export function useUpdateUser() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (data: UpdateUserRequest) => usersApi.update(data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [USERS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Пользователь обновлен',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось обновить пользователя',
- color: 'red',
- })
- },
- })
-}
-
-// ✅ Новый хук для удаления пользователя
-export function useDeleteUser() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (id: number) => usersApi.delete(id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: [USERS_QUERY_KEY] })
- notifications.show({
- title: 'Успешно',
- message: 'Пользователь удален',
- color: 'green',
- })
- },
- onError: (error: any) => {
- notifications.show({
- title: 'Ошибка',
- message: error.response?.data?.error_description || 'Не удалось удалить пользователя',
- color: 'red',
- })
- },
- })
-}
------END src/features/users/hooks/useUsers.ts-----
-
-File: src/hooks/useAuth.ts
-Lines: 57
------BEGIN src/hooks/useAuth.ts-----
-import { useState, useEffect } from 'react'
-import { useNavigate } from 'react-router-dom'
-import { authApi } from '@/api/auth'
-import type { Admin } from '@/types/api'
-
-export function useAuth() {
- const [user, setUser] = useState(null)
- const [loading, setLoading] = useState(true)
- const navigate = useNavigate()
-
- useEffect(() => {
- const token = localStorage.getItem('token')
- if (token) {
- loadUser()
- } else {
- setLoading(false)
- }
- }, [])
-
- const loadUser = async () => {
- try {
- const response = await authApi.getProfile()
- setUser(response.data)
- } catch (error) {
- console.error('Failed to load user:', error)
- localStorage.removeItem('token')
- } finally {
- setLoading(false)
- }
- }
-
- const login = async (login: string, password: string) => {
- const response = await authApi.login({ login, password })
- localStorage.setItem('token', response.data.token)
-
- // ✅ НЕ создаём новый device_id здесь!
- // Он уже создан в client.ts и сохранён в localStorage
- // localStorage.setItem('device_id', crypto.randomUUID()) // ← УДАЛЕНО
-
- await loadUser()
- navigate('/')
- }
-
- const logout = async () => {
- try {
- await authApi.logout()
- } catch (error) {
- console.error('Logout error:', error)
- } finally {
- localStorage.removeItem('token')
- localStorage.removeItem('user')
- setUser(null)
- navigate('/login')
- }
- }
-
- return { user, loading, login, logout, isAuthenticated: !!user }
-}
------END src/hooks/useAuth.ts-----
-
-File: src/index.css
-Lines: 111
------BEGIN src/index.css-----
-:root {
- --text: #6b6375;
- --text-h: #08060d;
- --bg: #fff;
- --border: #e5e4e7;
- --code-bg: #f4f3ec;
- --accent: #aa3bff;
- --accent-bg: rgba(170, 59, 255, 0.1);
- --accent-border: rgba(170, 59, 255, 0.5);
- --social-bg: rgba(244, 243, 236, 0.5);
- --shadow:
- rgba(0, 0, 0, 0.1) 0 10px 15px -3px, rgba(0, 0, 0, 0.05) 0 4px 6px -2px;
-
- --sans: system-ui, 'Segoe UI', Roboto, sans-serif;
- --heading: system-ui, 'Segoe UI', Roboto, sans-serif;
- --mono: ui-monospace, Consolas, monospace;
-
- font: 18px/145% var(--sans);
- letter-spacing: 0.18px;
- color-scheme: light dark;
- color: var(--text);
- background: var(--bg);
- font-synthesis: none;
- text-rendering: optimizeLegibility;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
-
- @media (max-width: 1024px) {
- font-size: 16px;
- }
-}
-
-@media (prefers-color-scheme: dark) {
- :root {
- --text: #9ca3af;
- --text-h: #f3f4f6;
- --bg: #16171d;
- --border: #2e303a;
- --code-bg: #1f2028;
- --accent: #c084fc;
- --accent-bg: rgba(192, 132, 252, 0.15);
- --accent-border: rgba(192, 132, 252, 0.5);
- --social-bg: rgba(47, 48, 58, 0.5);
- --shadow:
- rgba(0, 0, 0, 0.4) 0 10px 15px -3px, rgba(0, 0, 0, 0.25) 0 4px 6px -2px;
- }
-
- #social .button-icon {
- filter: invert(1) brightness(2);
- }
-}
-
-#root {
- width: 1126px;
- max-width: 100%;
- margin: 0 auto;
- text-align: center;
- border-inline: 1px solid var(--border);
- min-height: 100svh;
- display: flex;
- flex-direction: column;
- box-sizing: border-box;
-}
-
-body {
- margin: 0;
-}
-
-h1,
-h2 {
- font-family: var(--heading);
- font-weight: 500;
- color: var(--text-h);
-}
-
-h1 {
- font-size: 56px;
- letter-spacing: -1.68px;
- margin: 32px 0;
- @media (max-width: 1024px) {
- font-size: 36px;
- margin: 20px 0;
- }
-}
-h2 {
- font-size: 24px;
- line-height: 118%;
- letter-spacing: -0.24px;
- margin: 0 0 8px;
- @media (max-width: 1024px) {
- font-size: 20px;
- }
-}
-p {
- margin: 0;
-}
-
-code,
-.counter {
- font-family: var(--mono);
- display: inline-flex;
- border-radius: 4px;
- color: var(--text-h);
-}
-
-code {
- font-size: 15px;
- line-height: 135%;
- padding: 4px 8px;
- background: var(--code-bg);
-}
-
------END src/index.css-----
-
-File: src/main.tsx
-Lines: 38
------BEGIN src/main.tsx-----
-import React from 'react'
-import ReactDOM from 'react-dom/client'
-import { MantineProvider } from '@mantine/core'
-import { Notifications } from '@mantine/notifications'
-import { ModalsProvider } from '@mantine/modals'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { BrowserRouter } from 'react-router-dom'
-import App from './App'
-import { theme } from './theme'
-import '@mantine/core/styles.css'
-import '@mantine/notifications/styles.css'
-import '@mantine/dates/styles.css'
-import ErrorBoundary from './components/DiagnosticErrorBoundary'
-
-const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- refetchOnWindowFocus: false,
- retry: 1,
- },
- },
-})
-
-ReactDOM.createRoot(document.getElementById('root')!).render(
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-)
------END src/main.tsx-----
-
-File: src/pages/Dashboard.tsx
-Lines: 601
------BEGIN src/pages/Dashboard.tsx-----
-import { useEffect, useState } from 'react'
-import {
- SimpleGrid,
- Paper,
- Text,
- Group,
- Stack,
- Loader,
- Center,
- Badge,
- Progress,
- Alert,
- Box,
- ThemeIcon,
- UnstyledButton,
-} from '@mantine/core'
-import {
- IconUsers,
- IconFileCheck,
- IconBuilding,
- IconCategory,
- IconAlertTriangle,
- IconAlertOctagon,
- IconClock,
- IconAlertCircle,
- IconCircleCheck,
- IconChecklist,
- IconCalendarOff,
- IconChevronRight,
- IconUserExclamation,
-} 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 dayjs from 'dayjs'
-import 'dayjs/locale/ru'
-import TopicGapsModal from "@/components/TopicGapsModal.tsx";
-
-dayjs.locale('ru')
-
-const STATUS_COLORS: Record = {
- draft: '#868e96',
- pending: '#228be6',
- approved: '#40c057',
- rejected: '#fa5252',
- revoked: '#fd7e14',
- revision: '#7950f2',
-}
-
-const STATUS_LABELS: Record = {
- draft: 'Черновики',
- pending: 'На согласовании',
- approved: 'Согласованы',
- rejected: 'Отклонены',
- revoked: 'Отозваны',
- revision: 'На доработке',
-}
-
-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}`)
- }
-
- 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}
- />
-
-
-
-
- {/* Графики по заявкам */}
-
- {/* 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' ? 'Создано' : 'Согласовано'
- ]}
- />
-
-
-
-
-
- {/* 🆕 Задачи — те же два графика, что у заявок выше */}
-
-
-
-
-
-
-
- Задачи по статусам
-
- {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' ? 'Создано' : 'Выполнено'
- ]}
- />
-
-
-
-
-
- {/* Разбивка по категориям + узкие места */}
-
- {/* Разбивка по категориям */}
-
-
-
-
-
- Заявки по категориям
-
-
- {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
-}
-
-function StatCard({ title, value, subtitle, icon: Icon, color, trend }: StatCardProps) {
- return (
-
-
-
-
- {title}
-
-
- {value}
-
- {subtitle && (
-
- {subtitle}
-
- )}
-
-
-
-
-
-
- {trend && (
-
- {trend}
-
- )}
-
- )
-}
------END src/pages/Dashboard.tsx-----
-
-File: src/pages/DepartmentsPage.tsx
-Lines: 230
------BEGIN src/pages/DepartmentsPage.tsx-----
-import { useState } from 'react'
-import {
- Paper,
- Table,
- Badge,
- Group,
- ActionIcon,
- Button,
- Text,
- TextInput,
- Pagination,
- Loader,
- Center,
- Tooltip,
- Box,
- Stack,
- Switch,
-} from '@mantine/core'
-import { IconPencil, IconTrash, IconPlus, IconSearch } from '@tabler/icons-react'
-import { modals } from '@mantine/modals'
-import { useDepartments, useDeleteDepartment } from '@/features/departments/hooks/useDepartments'
-import DepartmentEditModal from "@/features/departments/components/DepartmentEditModal.tsx";
-
-const LIMIT = 20
-
-export default function DepartmentsPage() {
- const [page, setPage] = useState(1)
- const [search, setSearch] = useState('')
- const [activeFilter, setActiveFilter] = useState(null)
- const [editDepartmentId, setEditDepartmentId] = useState(null)
- const [createModalOpened, setCreateModalOpened] = useState(false)
-
- const { data, isLoading, isFetching } = useDepartments({
- offset: (page - 1) * LIMIT,
- limit: LIMIT,
- ...(search && { name: search }),
- ...(activeFilter !== null && { is_active: activeFilter }),
- })
-
- const deleteDepartment = useDeleteDepartment()
-
- const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
-
- const handleDelete = (id: number) => {
- modals.openConfirmModal({
- title: 'Подтвердите удаление',
- children: (
-
- Вы уверены, что хотите удалить этот отдел? Это действие нельзя отменить.
-
- ),
- labels: { confirm: 'Удалить', cancel: 'Отмена' },
- confirmProps: { color: 'red' },
- onConfirm: () => deleteDepartment.mutate(id),
- })
- }
-
- return (
-
-
- Отделы
-
-
- Всего: {data?.total_count || 0}
-
- }
- onClick={() => setCreateModalOpened(true)}
- >
- Создать отдел
-
-
-
-
- {/* Фильтры */}
-
-
- }
- value={search}
- onChange={(e) => {
- setSearch(e.currentTarget.value)
- setPage(1)
- }}
- style={{ flex: 1 }}
- />
-
- {
- setActiveFilter(e.currentTarget.checked ? true : null)
- setPage(1)
- }}
- />
-
-
-
- {/* Таблица */}
-
- {isLoading ? (
-
-
-
- ) : (
- <>
-
-
-
- ID
- Название
- Код
- Описание
- Статус
- Действия
-
-
-
- {data?.data?.length === 0 ? (
-
-
-
- Отделы не найдены
-
-
-
- ) : (
- (data?.data || []).map((department) => (
-
- {department.id}
-
- {department.name}
-
-
-
- {department.code}
-
-
-
-
- {department.description || '—'}
-
-
-
-
- {department.is_active ? 'Активен' : 'Неактивен'}
-
-
-
-
-
- setEditDepartmentId(department.id!)}
- >
-
-
-
-
- handleDelete(department.id!)}
- >
-
-
-
-
-
-
- ))
- )}
-
-
-
- {/* Пагинация */}
- {totalPages > 1 && (
-
-
-
- Страница {page} из {totalPages}
-
-
-
-
- )}
- >
- )}
-
-
- {/* Индикатор обновления */}
- {isFetching && !isLoading && (
-
-
-
- )}
-
- {/* Модальное окно редактирования */}
- setEditDepartmentId(null)}
- />
-
- {/* Модальное окно создания */}
- setCreateModalOpened(false)}
- />
-
- )
-}
------END src/pages/DepartmentsPage.tsx-----
-
-File: src/pages/Login.tsx
-Lines: 85
------BEGIN src/pages/Login.tsx-----
-import { useState } from 'react'
-import {
- Container,
- Paper,
- Title,
- Text,
- TextInput,
- PasswordInput,
- Button,
- Group,
-} from '@mantine/core'
-import { useForm } from '@mantine/form'
-import { notifications } from '@mantine/notifications'
-import { useAuth } from '@/hooks/useAuth'
-
-export default function Login() {
- const { login } = useAuth()
- const [loading, setLoading] = useState(false)
-
- const form = useForm({
- initialValues: {
- login: '',
- password: '',
- },
- validate: {
- login: (value: string | any[]) => (value.length < 3 ? 'Логин должен содержать минимум 3 символа' : null),
- password: (value: string | any[]) => (value.length < 4 ? 'Пароль должен содержать минимум 4 символа' : null),
- },
- })
-
- const handleSubmit = async (values: typeof form.values) => {
- setLoading(true)
- try {
- await login(values.login, values.password)
- notifications.show({
- title: 'Успешный вход',
- message: `Добро пожаловать, ${values.login}!`,
- color: 'green',
- })
- } catch (error: any) {
- notifications.show({
- title: 'Ошибка входа',
- message: error.response?.data?.error_description || 'Неверный логин или пароль',
- color: 'red',
- })
- } finally {
- setLoading(false)
- }
- }
-
- return (
-
-
- Корпоративная панель администратора
-
-
- Введите свои данные для входа в систему
-
-
-
-
-
-
- )
-}
------END src/pages/Login.tsx-----
-
-File: src/pages/adminLogs/AdminLogsPage.tsx
-Lines: 331
------BEGIN src/pages/adminLogs/AdminLogsPage.tsx-----
-import { useState } from 'react'
-import {
- Paper,
- Table,
- Group,
- ActionIcon,
- Text,
- TextInput,
- Select,
- Pagination,
- Loader,
- Center,
- Tooltip,
- Box,
- Stack,
- Badge,
-} from '@mantine/core'
-import { DatePickerInput } from '@mantine/dates'
-import { IconTrash, IconSearch, IconX, IconEye } from '@tabler/icons-react'
-import { modals } from '@mantine/modals'
-import { useAuth } from '@/hooks/useAuth'
-import { useAdminLogs, useDeleteAdminLog } from '@/features/adminLogs/hooks/useAdminLogs'
-import type { AdminActionLog } from '@/api/adminLogs'
-import AdminLogDetailModal from './components/AdminLogDetailModal'
-import dayjs from 'dayjs'
-import 'dayjs/locale/ru'
-
-dayjs.locale('ru')
-
-const LIMIT = 50
-
-const ACTION_COLORS: Record = {
- create: 'green',
- update: 'blue',
- delete: 'red',
-}
-const ACTION_LABELS: Record = {
- create: 'Создание',
- update: 'Изменение',
- delete: 'Удаление',
-}
-
-const ENTITY_TYPE_OPTIONS = [
- { value: 'user', label: 'Пользователь' },
- { value: 'admin', label: 'Администратор' },
- { value: 'department', label: 'Отдел' },
- { value: 'role', label: 'Роль' },
- { value: 'permission', label: 'Право' },
- { value: 'category', label: 'Категория' },
- { value: 'topic', label: 'Тема' },
- { value: 'topic_executor', label: 'Исполнитель темы' },
- { value: 'hierarchy', label: 'Иерархия' },
- { value: 'flow_node', label: 'Узел дерева' },
- { value: 'flow_tree', label: 'Дерево категории' },
- { value: 'user_role', label: 'Роль пользователя' },
- { value: 'user_roles', label: 'Роли пользователя (массово)' },
- { value: 'approval_task', label: 'Задача' },
- { value: 'notification', label: 'Рассылка' },
-]
-
-export default function AdminLogPage() {
- const { user: currentUser } = useAuth()
- const isRoot = currentUser?.is_root === true
-
- const [page, setPage] = useState(1)
- const [adminLogin, setAdminLogin] = useState('')
- const [action, setAction] = useState(null)
- const [entityType, setEntityType] = useState(null)
- const [entityId, setEntityId] = useState('')
- const [search, setSearch] = useState('')
- const [dateFrom, setDateFrom] = useState(null)
- const [dateTo, setDateTo] = useState(null)
- const [selectedLog, setSelectedLog] = useState(null)
-
- const { data, isLoading, isFetching } = useAdminLogs({
- offset: (page - 1) * LIMIT,
- limit: LIMIT,
- ...(adminLogin && { admin_login: adminLogin }),
- ...(action && { action }),
- ...(entityType && { entity_type: entityType }),
- ...(entityId && { entity_id: Number(entityId) }),
- ...(search && { search }),
- ...(dateFrom && { date_from: dayjs(dateFrom).format('YYYY-MM-DD') }),
- ...(dateTo && { date_to: dayjs(dateTo).format('YYYY-MM-DD') }),
- })
-
- const deleteLog = useDeleteAdminLog()
-
- const logs = data?.data || []
- const totalCount = data?.total_count || 0
- const totalPages = totalCount ? Math.ceil(totalCount / LIMIT) : 1
-
- const hasActiveFilters = adminLogin || action || entityType || entityId || search || dateFrom || dateTo
-
- const handleResetFilters = () => {
- setAdminLogin('')
- setAction(null)
- setEntityType(null)
- setEntityId('')
- setSearch('')
- setDateFrom(null)
- setDateTo(null)
- setPage(1)
- }
-
- const handleDelete = (entry: AdminActionLog) => {
- modals.openConfirmModal({
- title: 'Удалить запись журнала?',
- children: (
-
- Это действие доступно только root-администратору и необратимо.
- Обычно записи журнала не удаляют — используйте только если запись
- ошибочна или содержит чувствительные данные, которые нужно убрать.
-
- ),
- labels: { confirm: 'Удалить', cancel: 'Отмена' },
- confirmProps: { color: 'red' },
- onConfirm: () => deleteLog.mutate(entry.id),
- })
- }
-
- return (
-
-
- Журнал действий администраторов
- Всего: {totalCount}
-
-
-
-
-
- }
- value={adminLogin}
- onChange={(e) => {
- setAdminLogin(e.currentTarget.value)
- setPage(1)
- }}
- />
-
-
-
-
- }
- value={search}
- onChange={(e) => {
- setSearch(e.currentTarget.value)
- setPage(1)
- }}
- rightSection={
- search && (
- setSearch('')}>
-
-
- )
- }
- />
- {
- setDateFrom(val as Date | null)
- setPage(1)
- }}
- clearable
- maxDate={dateTo || undefined}
- />
- {
- setDateTo(val as Date | null)
- setPage(1)
- }}
- clearable
- minDate={dateFrom || undefined}
- />
-
- {hasActiveFilters && (
-
-
-
- )}
-
-
-
-
-
-
- {isLoading ? (
-
-
-
- ) : (
- <>
-
-
-
- Когда
- Администратор
- Действие
- Сущность
- Описание
- —
-
-
-
- {logs.length === 0 ? (
-
-
-
- Записей не найдено
-
-
-
- ) : (
- logs.map((entry) => (
- setSelectedLog(entry)}>
-
-
- {dayjs(entry.created_at).format('DD.MM.YYYY HH:mm')}
-
-
-
- {entry.admin_login}
-
-
-
- {ACTION_LABELS[entry.action] || entry.action}
-
-
-
-
- {entry.entity_type}{entry.entity_id ? ` #${entry.entity_id}` : ''}
-
-
-
- {entry.description}
-
- e.stopPropagation()}>
-
-
- setSelectedLog(entry)}>
-
-
-
- {isRoot && (
-
- handleDelete(entry)}>
-
-
-
- )}
-
-
-
- ))
- )}
-
-
-
- {totalPages > 1 && (
-
-
- Страница {page} из {totalPages}
-
-
-
- )}
- >
- )}
-
-
- {isFetching && !isLoading && (
-
-
-
- )}
-
- setSelectedLog(null)}
- />
-
- )
-}
------END src/pages/adminLogs/AdminLogsPage.tsx-----
-
-File: src/pages/adminLogs/components/AdminLogDetailModal.tsx
-Lines: 104
------BEGIN src/pages/adminLogs/components/AdminLogDetailModal.tsx-----
-import { useMemo } from 'react'
-import { Modal, Stack, Text, Table, Badge, Group, Code, Center } from '@mantine/core'
-import type { AdminActionLog } from '@/api/adminLogs'
-
-interface FieldChange {
- field: string
- old: unknown
- new: unknown
-}
-
-interface AdminLogDetailModalProps {
- log: AdminActionLog | null
- opened: boolean
- onClose: () => void
-}
-
-function formatValue(v: unknown): string {
- if (v === null || v === undefined || v === '') return '—'
- if (typeof v === 'boolean') return v ? 'да' : 'нет'
- if (Array.isArray(v)) return v.length ? v.join(', ') : '—'
- return String(v)
-}
-
-export default function AdminLogDetailModal({ log, opened, onClose }: AdminLogDetailModalProps) {
- const parsed = useMemo(() => {
- if (!log?.metadata) return null
- try {
- return JSON.parse(log.metadata) as {
- changes?: FieldChange[]
- snapshot?: Record
- [key: string]: unknown
- }
- } catch {
- return null
- }
- }, [log])
-
- return (
-
- {!log ? null : (
-
-
- {log.admin_login}
- {log.entity_type}
-
- {log.description}
-
- {parsed?.changes && parsed.changes.length > 0 && (
-
-
-
- Поле
- Было
- Стало
-
-
-
- {parsed.changes.map((c, i) => (
-
-
- {c.field}
-
-
- {formatValue(c.old)}
-
-
- {formatValue(c.new)}
-
-
- ))}
-
-
- )}
-
- {parsed?.snapshot && (
-
-
- {Object.entries(parsed.snapshot).map(([key, value]) => (
-
-
- {key}
-
-
- {formatValue(value)}
-
-
- ))}
-
-
- )}
-
- {!parsed?.changes && !parsed?.snapshot && parsed && (
- {JSON.stringify(parsed, null, 2)}
- )}
-
- {!log.metadata && (
-
- Дополнительных данных нет
-
- )}
-
- )}
-
- )
-}
------END src/pages/adminLogs/components/AdminLogDetailModal.tsx-----
-
-File: src/pages/admins/AdminsPage.tsx
-Lines: 398
------BEGIN src/pages/admins/AdminsPage.tsx-----
-import { useState } from 'react'
-import {
- Paper,
- Table,
- Badge,
- Group,
- ActionIcon,
- Button,
- Text,
- TextInput,
- Pagination,
- Loader,
- Center,
- Tooltip,
- Box,
- Stack,
- Switch,
-} from '@mantine/core'
-import {
- IconTrash,
- IconPlus,
- IconSearch,
- IconLock,
- IconLockOpen,
- IconPencil,
- IconShield,
- IconUser,
-} from '@tabler/icons-react'
-import { modals } from '@mantine/modals'
-import { notifications } from '@mantine/notifications'
-import {
- useAdmins,
- useDeleteAdmin,
- useUpdateAdmin
-} from '@/features/admins/hooks/useAdmins'
-import { useAuth } from '@/hooks/useAuth'
-import CreateAdminModal from './components/CreateAdminModal'
-import EditAdminModal from './components/EditAdminModal'
-import type { Admin } from '@/types/api'
-import dayjs from 'dayjs'
-import 'dayjs/locale/ru'
-
-dayjs.locale('ru')
-
-const LIMIT = 20
-
-export default function AdminsPage() {
- const [page, setPage] = useState(1)
- const [search, setSearch] = useState('')
- const [blockedFilter, setBlockedFilter] = useState(null)
- const [createModalOpened, setCreateModalOpened] = useState(false)
- const [editAdmin, setEditAdmin] = useState(null)
-
- const { user: currentUser } = useAuth()
-
- const { data, isLoading, isFetching } = useAdmins({
- offset: (page - 1) * LIMIT,
- limit: LIMIT,
- ...(search && { login: search }),
- ...(blockedFilter !== null && { is_blocked: blockedFilter }),
- })
-
- const deleteAdmin = useDeleteAdmin()
- const updateAdmin = useUpdateAdmin()
-
- const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
-
- // 🆕 Проверка, является ли текущий пользователь root
- const isRoot = currentUser?.is_root === true
-
- const handleDelete = (id: number, login: string, isAdminRoot: boolean) => {
- // Нельзя удалить себя
- if (currentUser?.id === id) {
- notifications.show({
- title: 'Ошибка',
- message: 'Вы не можете удалить свой собственный аккаунт',
- color: 'red',
- })
- return
- }
-
- // Нельзя удалить root-админа (если текущий не root)
- if (isAdminRoot && !isRoot) {
- notifications.show({
- title: 'Ошибка',
- message: 'Только root-администратор может удалять других root-администраторов',
- color: 'red',
- })
- return
- }
-
- modals.openConfirmModal({
- title: 'Подтвердите удаление',
- children: (
-
- Вы уверены, что хотите удалить администратора {login}?
- Это действие нельзя отменить.
-
- ),
- labels: { confirm: 'Удалить', cancel: 'Отмена' },
- confirmProps: { color: 'red' },
- onConfirm: () => deleteAdmin.mutate(id),
- })
- }
-
- const handleToggleBlock = (id: number, login: string, isBlocked: boolean, isAdminRoot: boolean) => {
- // Нельзя заблокировать себя
- if (currentUser?.id === id) {
- notifications.show({
- title: 'Ошибка',
- message: 'Вы не можете заблокировать свой собственный аккаунт',
- color: 'red',
- })
- return
- }
-
- // Нельзя заблокировать root-админа (если текущий не root)
- if (isAdminRoot && !isRoot) {
- notifications.show({
- title: 'Ошибка',
- message: 'Только root-администратор может блокировать других root-администраторов',
- color: 'red',
- })
- return
- }
-
- const action = isBlocked ? 'разблокировать' : 'заблокировать'
-
- modals.openConfirmModal({
- title: 'Подтвердите действие',
- children: (
-
- Вы уверены, что хотите {action} администратора {login}?
-
- ),
- labels: { confirm: action.charAt(0).toUpperCase() + action.slice(1), cancel: 'Отмена' },
- confirmProps: { color: isBlocked ? 'green' : 'red' },
- onConfirm: () => updateAdmin.mutate({ id, is_blocked: !isBlocked }),
- })
- }
-
- return (
-
- {/* Заголовок */}
-
- Администраторы
-
-
- Всего: {data?.total_count || 0}
-
- {isRoot && (
- }
- onClick={() => setCreateModalOpened(true)}
- >
- Создать администратора
-
- )}
-
-
-
- {/* Предупреждение для не-root пользователей */}
- {!isRoot && (
-
-
- ⚠️ Создание новых администраторов доступно только для root-администратора.
-
-
- )}
-
- {/* Фильтры */}
-
-
- }
- value={search}
- onChange={(e) => {
- setSearch(e.currentTarget.value)
- setPage(1)
- }}
- style={{ flex: 1 }}
- />
-
- {
- setBlockedFilter(e.currentTarget.checked ? true : null)
- setPage(1)
- }}
- />
-
-
-
- {/* Таблица */}
-
- {isLoading ? (
-
-
-
- ) : (
- <>
-
-
-
- ID
- Логин
- Имя
- Роль
- Telegram
- Создан
- Последний вход
- Последний IP
- Статус
- Действия
-
-
-
- {data?.data?.length === 0 ? (
-
-
-
- Администраторы не найдены
-
-
-
- ) : (
- (data?.data || []).map((admin) => {
- const isCurrentUser = currentUser?.id === admin.id
- const isAdminRoot = admin.is_root === true
- return (
-
- {admin.id}
-
-
- {admin.login}
- {isCurrentUser && (
-
- Вы
-
- )}
- {isAdminRoot && (
- }
- >
- ROOT
-
- )}
-
-
-
- {admin.name || '—'}
-
-
-
- {isAdminRoot && (
- }>
- ROOT
-
- )}
- {admin.is_observer && (
- }>
- Наблюдатель
-
- )}
- {!isAdminRoot && !admin.is_observer && (
-
- Админ
-
- )}
-
-
-
- {admin.telegram_user ? (
- {admin.telegram_user.full_name || admin.telegram_user.username || '—'}
- ) : admin.telegram_id ? (
- ID: {admin.telegram_id}
- ) : (
- —
- )}
-
-
-
- {admin.created_at
- ? dayjs(admin.created_at).format('DD.MM.YYYY')
- : '—'}
-
-
-
-
- {admin.last_login
- ? dayjs(admin.last_login).format('DD.MM.YYYY HH:mm')
- : '—'}
-
-
-
-
- {admin.last_ip_login || '—'}
-
-
-
-
- {admin.is_blocked ? 'Заблокирован' : 'Активен'}
-
-
-
-
-
- setEditAdmin(admin)}
- >
-
-
-
-
- handleToggleBlock(
- admin.id!,
- admin.login,
- admin.is_blocked || false,
- isAdminRoot
- )}
- disabled={isCurrentUser || (isAdminRoot && !isRoot)}
- >
- {admin.is_blocked ? : }
-
-
-
- handleDelete(admin.id!, admin.login, isAdminRoot)}
- disabled={isCurrentUser || (isAdminRoot && !isRoot)}
- >
-
-
-
-
-
-
- )
- })
- )}
-
-
-
- {/* Пагинация */}
- {totalPages > 1 && (
-
-
-
- Страница {page} из {totalPages}
-
-
-
-
- )}
- >
- )}
-
-
- {/* Индикатор обновления */}
- {isFetching && !isLoading && (
-
-
-
- )}
-
- {/* Модальные окна */}
- setCreateModalOpened(false)}
- />
-
- setEditAdmin(null)}
- />
-
- )
-}
------END src/pages/admins/AdminsPage.tsx-----
-
-File: src/pages/admins/components/CreateAdminModal.tsx
-Lines: 258
------BEGIN src/pages/admins/components/CreateAdminModal.tsx-----
-import { useState, useEffect } from 'react'
-import {
- Modal,
- Stack,
- TextInput,
- Button,
- Text,
- Alert,
- CopyButton,
- ActionIcon,
- Tooltip,
- Group,
- Paper,
- Code,
- Switch,
- Select,
-} from '@mantine/core'
-import { useForm } from '@mantine/form'
-import { IconCheck, IconCopy, IconKey, IconAlertCircle, IconShield, IconUser } from '@tabler/icons-react'
-import { useCreateAdmin } from '@/features/admins/hooks/useAdmins'
-import { useUsers } from '@/features/users/hooks/useUsers'
-import type { Admin } from '@/types/api'
-
-interface CreateAdminModalProps {
- opened: boolean
- onClose: () => void
-}
-
-export default function CreateAdminModal({ opened, onClose }: CreateAdminModalProps) {
- const [createdAdmin, setCreatedAdmin] = useState(null)
- const createAdmin = useCreateAdmin()
- const { data: usersData } = useUsers({ limit: 1000 })
-
- const form = useForm({
- initialValues: {
- login: '',
- name: '',
- is_root: false,
- is_observer: false,
- telegram_id: null as number | null,
- },
- validate: {
- login: (value) => {
- if (value.length < 3) return 'Логин должен содержать минимум 3 символа'
- if (!/^[a-zA-Z0-9_]+$/.test(value)) return 'Логин может содержать только буквы, цифры и подчеркивания'
- return null
- },
- telegram_id: (value, values) => {
- if (values.is_observer && !value) {
- return 'Для наблюдателя обязательно выберите Telegram-аккаунт'
- }
- return null
- },
- },
- })
-
- // Сброс telegram_id при снятии галочки наблюдателя
- useEffect(() => {
- if (!form.values.is_observer) {
- form.setFieldValue('telegram_id', null)
- }
- }, [form.values.is_observer])
-
- // Опции пользователей Telegram (только те, у кого есть telegram_id)
- const userOptions = usersData?.data
- ?.filter((u) => u.telegram_id && u.telegram_id > 0)
- .map((u) => ({
- value: String(u.telegram_id),
- label: u.full_name || u.username || `ID: ${u.telegram_id}`,
- })) || []
-
- const handleSubmit = async (values: typeof form.values) => {
- try {
- const admin = await createAdmin.mutateAsync({
- login: values.login,
- name: values.name || undefined,
- is_root: values.is_root,
- is_observer: values.is_observer,
- telegram_id: values.is_observer ? values.telegram_id! : undefined,
- })
- setCreatedAdmin(admin)
- form.reset()
- } catch (error) {
- // Ошибка уже обработана в хуке
- }
- }
-
- const handleClose = () => {
- setCreatedAdmin(null)
- form.reset()
- onClose()
- }
-
- return (
-
- {createdAdmin ? (
-
- }
- title="Администратор создан"
- color="green"
- variant="light"
- >
-
- Администратор {createdAdmin.login} успешно создан.
- {createdAdmin.is_root && (
-
- Выданы root-права 👑
-
- )}
- {createdAdmin.is_observer && (
-
- Роль: Наблюдатель 👁
-
- )}
-
-
-
-
-
-
-
- Временный пароль
-
-
-
- Сохраните этот пароль! После закрытия окна он больше не будет доступен.
-
-
-
-
- {createdAdmin.password || '—'}
-
-
- {({ copied, copy }) => (
-
-
- {copied ? : }
-
-
- )}
-
-
-
-
-
-
-
- ) : (
-
- )}
-
- )
-}
------END src/pages/admins/components/CreateAdminModal.tsx-----
-
-File: src/pages/admins/components/EditAdminModal.tsx
-Lines: 202
------BEGIN src/pages/admins/components/EditAdminModal.tsx-----
-import { useEffect } from 'react'
-import {
- Modal,
- Stack,
- TextInput,
- Button,
- Text,
- Group,
- Badge,
- Switch,
- Paper,
- Alert,
- Select,
-} from '@mantine/core'
-import { useForm } from '@mantine/form'
-import { IconShield, IconAlertCircle, IconUser } from '@tabler/icons-react'
-import { useUpdateAdmin } from '@/features/admins/hooks/useAdmins'
-import { useAuth } from '@/hooks/useAuth'
-import { useUsers } from '@/features/users/hooks/useUsers'
-import type { Admin } from '@/types/api'
-
-interface EditAdminModalProps {
- admin: Admin | null
- opened: boolean
- onClose: () => void
-}
-
-export default function EditAdminModal({ admin, opened, onClose }: EditAdminModalProps) {
- const updateAdmin = useUpdateAdmin()
- const { user: currentUser } = useAuth()
- const { data: usersData } = useUsers({ limit: 1000 })
-
- const form = useForm({
- initialValues: {
- name: '',
- is_root: false,
- is_observer: false,
- telegram_id: null as number | null,
- },
- validate: {
- telegram_id: (value, values) => {
- if (values.is_observer && !value) {
- return 'Для наблюдателя обязательно выберите Telegram-аккаунт'
- }
- return null
- },
- },
- })
-
- useEffect(() => {
- if (admin) {
- form.setValues({
- name: admin.name || '',
- is_root: admin.is_root ?? false,
- is_observer: admin.is_observer ?? false,
- telegram_id: admin.telegram_id || null,
- })
- }
- }, [admin])
-
- useEffect(() => {
- if (!form.values.is_observer) {
- form.setFieldValue('telegram_id', null)
- }
- }, [form.values.is_observer])
-
- const isCurrentUser = currentUser?.id === admin?.id
-
- const userOptions = usersData?.data
- ?.filter((u) => u.telegram_id && u.telegram_id > 0)
- .map((u) => ({
- value: String(u.telegram_id),
- label: u.full_name || u.username || `ID: ${u.telegram_id}`,
- })) || []
-
- const handleSubmit = async (values: typeof form.values) => {
- if (!admin?.id) return
- await updateAdmin.mutateAsync({
- id: admin.id,
- name: values.name || undefined,
- is_root: values.is_root,
- is_observer: values.is_observer,
- telegram_id: values.is_observer ? values.telegram_id! : null,
- })
- onClose()
- }
-
- return (
-
- Редактирование администратора
- {admin && {admin.login}}
- {admin?.is_root && (
- }>
- ROOT
-
- )}
- {admin?.is_observer && (
- }>
- Наблюдатель
-
- )}
-
- }
- size="md"
- >
-
-
- )
-}
------END src/pages/admins/components/EditAdminModal.tsx-----
-
-File: src/pages/approvalTasks/ApprovalTasksPage.tsx
-Lines: 284
------BEGIN src/pages/approvalTasks/ApprovalTasksPage.tsx-----
-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 { 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 dayjs from 'dayjs'
-import 'dayjs/locale/ru'
-
-dayjs.locale('ru')
-
-const LIMIT = 20
-
-export default function ApprovalTasksPage() {
- // 🆕 Начальный статус берём из 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 { data, isLoading, isFetching } = useApprovalTasks({
- offset: (page - 1) * LIMIT,
- limit: LIMIT,
- ...(statusFilter && { status: statusFilter }),
- ...(executorFilter && { executor_id: Number(executorFilter) }),
- ...(requireFileFilter !== null && { require_file: requireFileFilter }),
- })
-
- const { data: users } = useUsers({ limit: 1000 })
- const deleteTask = useDeleteApprovalTask()
-
- const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
-
- 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),
- })
- }
-
- return (
-
-
- Задачи по заявкам
-
- Всего: {data?.total_count || 0}
-
-
-
- {/* Фильтры */}
-
-
- ({ value: s.value, label: s.label }))}
- value={statusFilter}
- onChange={(v) => {
- setStatusFilter(v)
- setPage(1)
- }}
- clearable
- style={{ minWidth: 180 }}
- />
-
- {
- setExecutorFilter(v)
- setPage(1)
- }}
- clearable
- searchable
- style={{ minWidth: 200 }}
- />
-
- {
- setRequireFileFilter(e.currentTarget.checked ? true : null)
- setPage(1)
- }}
- />
-
-
-
- {/* Таблица */}
-
- {isLoading ? (
-
-
-
- ) : (
- <>
-
-
-
- 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
- ? dayjs(task.created_at).format('DD.MM.YYYY HH:mm')
- : '—'}
-
-
-
-
- {task.completed_at
- ? dayjs(task.completed_at).format('DD.MM.YYYY HH:mm')
- : '—'}
-
-
-
-
-
- setSelectedTaskId(task.id!)}
- >
-
-
-
-
- handleDelete(task.id!)}
- >
-
-
-
-
-
-
- ))
- )}
-
-
-
- {totalPages > 1 && (
-
-
-
- Страница {page} из {totalPages}
-
-
-
-
- )}
- >
- )}
-
-
- {isFetching && !isLoading && (
-
-
-
- )}
-
- setSelectedTaskId(null)}
- />
-
- )
-}
------END src/pages/approvalTasks/ApprovalTasksPage.tsx-----
-
-File: src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx
-Lines: 396
------BEGIN src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx-----
-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'
-
-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 (
-
-
-