= {
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' ? 'Создано' : 'Согласовано'
]}
/>
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
}
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)
}}
/>
{
setAction(v)
setPage(1)
}}
clearable
/>
{
setEntityType(v)
setPage(1)
}}
clearable
searchable
/>
{
setEntityId(e.currentTarget.value.replace(/\D/g, ''))
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 (
{file.file_name || 'Без имени'}
{fileSizeKB > 0 && (
{fileSizeKB} KB
)}
{canPreview && (
handleFilePreview(file.id!, file.file_name || '')}
>
)}
handleFileDownload(file.id!, file.file_name || '')}
>
)
})}
)}
{/* Связанная заявка */}
{task.approval && (
Связанная заявка
ID заявки:
#{task.approval.id}
Тема:
{task.approval.topic?.name || '—'}
Инициатор:
{task.approval.initiator?.full_name || '—'}
Статус заявки:
{task.approval.status}
)}
{/* Исполнитель */}
{task.executor && (
Исполнитель
Имя:
{task.executor.full_name}
{task.executor.department && (
Отдел:
{task.executor.department.name}
)}
)}
{/* Даты */}
Временные метки
Создана:
{task.created_at
? dayjs(task.created_at).format('DD.MM.YYYY HH:mm')
: '—'}
Обновлена:
{task.updated_at
? dayjs(task.updated_at).format('DD.MM.YYYY HH:mm')
: '—'}
{task.completed_at && (
Выполнена:
{dayjs(task.completed_at).format('DD.MM.YYYY HH:mm')}
)}
{/* Форма обновления статуса */}
Изменить статус
) : (
Задача не найдена
)}
{previewFileId && taskId && (
setPreviewFileId(null)}
/>
)}
>
)
}
-----END src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx-----
File: src/pages/approvals/ApprovalsPage.tsx
Lines: 614
-----BEGIN src/pages/approvals/ApprovalsPage.tsx-----
import { useEffect, useState, useMemo } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Select,
MultiSelect,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Divider,
Alert,
} from '@mantine/core'
import { DatePickerInput } from '@mantine/dates'
import {
IconEye,
IconSearch,
IconFileText,
IconFileExcel,
IconInfoCircle,
IconX,
IconFilter,
} from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import { useSearchParams } from 'react-router-dom'
import { useApprovals } from '@/features/approvals/hooks/useApprovals'
import { useTopics } from '@/features/topics/hooks/useTopics'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useUsers } from '@/features/users/hooks/useUsers'
import { approvalsApi } from '@/api/approvals'
import ApprovalDetailsModal from './components/ApprovalDetailsModal'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
import { useDebouncedValue } from '@mantine/hooks'
dayjs.locale('ru')
const LIMIT = 20
const STATUS_COLORS: Record = {
pending: 'blue',
approved: 'green',
rejected: 'red',
revoked: 'orange',
revision: 'violet',
}
const STATUS_LABELS: Record = {
pending: 'На согласовании',
approved: 'Согласована',
rejected: 'Отклонена',
revoked: 'Отозвана',
revision: 'На доработке',
}
export default function ApprovalsPage() {
// 🆕 Значения фильтров, с которыми пришли по ссылке (например, с
// дашборда: /approvals?status=pending&date_to=2026-07-20). Читаем
// только один раз при монтировании — страница не синхронизирует
// фильтры с URL постоянно, только принимает начальное состояние.
const [searchParams] = useSearchParams()
// === Состояния фильтров ===
const [page, setPage] = useState(1)
const [searchInput, setSearchInput] = useState('')
const [search, setSearch] = useState('')
const [searchError, setSearchError] = useState(null)
const [debouncedSearch] = useDebouncedValue(searchInput, 400)
const [statusFilter, setStatusFilter] = useState(
() => searchParams.get('status')
)
const [categoryFilter, setCategoryFilter] = useState([])
const [topicFilter, setTopicFilter] = useState([])
const [departmentFilter, setDepartmentFilter] = useState(null)
const [initiatorFilter, setInitiatorFilter] = useState(null)
const [dateFrom, setDateFrom] = useState(() => {
const v = searchParams.get('date_from')
return v ? dayjs(v).toDate() : null
})
const [dateTo, setDateTo] = useState(() => {
const v = searchParams.get('date_to')
return v ? dayjs(v).toDate() : null
})
// === Отчёт ===
const [reportDateFrom, setReportDateFrom] = useState(null)
const [reportDateTo, setReportDateTo] = useState(null)
const [reportLoading, setReportLoading] = useState(false)
const [selectedApprovalId, setSelectedApprovalId] = useState(null)
// === Обработка поиска ===
useEffect(() => {
if (debouncedSearch === '') {
setSearch('')
setSearchError(null)
setPage(1)
return
}
if (debouncedSearch.length < 2) {
setSearchError('Введите минимум 2 символа')
return
}
setSearchError(null)
setSearch(debouncedSearch)
setPage(1)
}, [debouncedSearch])
// === Загрузка справочников ===
const { data: categories } = useCategories({ limit: 1000 })
const { data: allTopics } = useTopics({ limit: 1000 })
const { data: departments } = useDepartments()
const { data: users } = useUsers({ limit: 1000 })
// === Темы, отфильтрованные по выбранным категориям ===
const filteredTopics = useMemo(() => {
if (!allTopics?.data) return []
if (categoryFilter.length === 0) return allTopics.data
const categoryIds = categoryFilter.map(Number)
return allTopics.data.filter((t) =>
t.category_id && categoryIds.includes(t.category_id)
)
}, [allTopics, categoryFilter])
// === Сброс невалидных тем при изменении категорий ===
useEffect(() => {
if (categoryFilter.length > 0 && topicFilter.length > 0) {
const validTopicIds = new Set(filteredTopics.map((t) => String(t.id)))
const validSelected = topicFilter.filter((id) => validTopicIds.has(id))
if (validSelected.length !== topicFilter.length) {
setTopicFilter(validSelected)
}
}
// Если категории сброшены — темы остаются как есть
}, [categoryFilter, filteredTopics, topicFilter])
// === Опции для Select/MultiSelect ===
const categoryOptions = useMemo(
() =>
categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || [],
[categories]
)
const topicOptions = useMemo(
() =>
filteredTopics.map((t) => ({
value: String(t.id),
label: `${t.category?.name || '—'} / ${t.name || ''}`,
})),
[filteredTopics]
)
const departmentOptions = useMemo(
() =>
departments?.data?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || [],
[departments]
)
const userOptions = useMemo(
() =>
users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || u.username || `ID: ${u.id}`,
})) || [],
[users]
)
// === Формирование параметров запроса ===
const requestParams = useMemo(() => {
const params: any = {
offset: (page - 1) * LIMIT,
limit: LIMIT,
}
if (search) params.content = search
if (statusFilter) params.status = statusFilter
if (departmentFilter) params.department_id = Number(departmentFilter)
if (initiatorFilter) params.initiator_id = Number(initiatorFilter)
if (categoryFilter.length > 0) {
params.category_ids = categoryFilter.map(Number)
}
if (topicFilter.length > 0) {
params.topic_ids = topicFilter.map(Number)
}
if (dateFrom) params.date_from = dayjs(dateFrom).format('YYYY-MM-DD')
if (dateTo) params.date_to = dayjs(dateTo).format('YYYY-MM-DD')
return params
}, [
page, search, statusFilter, departmentFilter,
initiatorFilter, categoryFilter, topicFilter, dateFrom, dateTo,
])
// === Запрос списка заявок ===
const { data, isLoading, isFetching } = useApprovals(requestParams)
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
// === Сброс фильтров ===
const handleResetFilters = () => {
setSearchInput('')
setSearch('')
setStatusFilter(null)
setCategoryFilter([])
setTopicFilter([])
setDepartmentFilter(null)
setInitiatorFilter(null)
setDateFrom(null)
setDateTo(null)
setPage(1)
}
const hasActiveFilters =
search ||
statusFilter ||
categoryFilter.length > 0 ||
topicFilter.length > 0 ||
departmentFilter ||
initiatorFilter ||
dateFrom ||
dateTo
// === Генерация отчёта ===
const handleGenerateReport = async () => {
setReportLoading(true)
try {
const params: any = { all_access: true }
if (reportDateFrom) params.date_from = dayjs(reportDateFrom).format('YYYY-MM-DD')
if (reportDateTo) params.date_to = dayjs(reportDateTo).format('YYYY-MM-DD')
const response = await approvalsApi.downloadReport(params)
const blob = new Blob([response.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
})
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
const now = dayjs()
link.setAttribute(
'download',
`Согласования_${now.format('DD.MM.YYYY')}_${now.format('HH-mm')}.xlsx`
)
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(url)
notifications.show({
title: 'Успешно',
message: 'Отчёт сформирован и скачан',
color: 'green',
})
} catch (error: any) {
notifications.show({
title: 'Ошибка',
message: error.response?.data?.error_description || 'Не удалось сформировать отчёт',
color: 'red',
})
} finally {
setReportLoading(false)
}
}
return (
{/* Заголовок */}
Заявки
Всего: {data?.total_count || 0}
{/* Секция отчёта */}
Формирование отчёта
}
color="green"
onClick={handleGenerateReport}
loading={reportLoading}
size="sm"
>
Скачать XLSX
} color="blue" variant="light" p="xs">
Выберите период для выгрузки отчёта. Если даты не указаны — будут выгружены все заявки.
setReportDateFrom(val as Date | null)}
clearable
style={{ flex: 1 }}
/>
setReportDateTo(val as Date | null)}
clearable
minDate={reportDateFrom || undefined}
style={{ flex: 1 }}
/>
{/* Фильтры списка */}
Фильтры
{hasActiveFilters && (
}
onClick={handleResetFilters}
>
Сбросить фильтры
)}
{/* Строка 1: Поиск + Статус + Инициатор */}
}
value={searchInput}
onChange={(e) => setSearchInput(e.currentTarget.value)}
error={searchError}
rightSection={
searchInput && (
setSearchInput('')}
>
)
}
/>
{
setStatusFilter(v)
setPage(1)
}}
clearable
/>
{
setInitiatorFilter(v)
setPage(1)
}}
clearable
searchable
/>
{/* Строка 2: Категории + Темы + Отдел */}
{
setCategoryFilter(v)
setPage(1)
}}
clearable
searchable
nothingFoundMessage="Категории не найдены"
/>
0
? 'Выберите темы'
: 'Все темы'
}
data={topicOptions}
value={topicFilter}
onChange={(v) => {
setTopicFilter(v)
setPage(1)
}}
clearable
searchable
disabled={filteredTopics.length === 0}
nothingFoundMessage="Темы не найдены"
description={
categoryFilter.length > 0
? `Показаны темы выбранных категорий (${filteredTopics.length})`
: undefined
}
/>
{
setDepartmentFilter(v)
setPage(1)
}}
clearable
/>
{/* Строка 3: Период дат */}
{
setDateFrom(val as Date | null)
setPage(1)
}}
clearable
maxDate={dateTo || undefined}
/>
{
setDateTo(val as Date | null)
setPage(1)
}}
clearable
minDate={dateFrom || undefined}
/>
{/* Таблица */}
{isLoading ? (
) : (
<>
ID
Категория / Тема
Инициатор
Отдел
Дата создания
Статус
Действия
{data?.data?.length === 0 ? (
Заявки не найдены
) : (
(data?.data || []).map((approval) => (
#{approval.id}
{approval.topic?.category?.name || '—'}
{approval.topic?.name || 'Тема не указана'}
{approval.initiator?.full_name || '—'}
{approval.department?.name || '—'}
{approval.created_at
? dayjs(approval.created_at).format('DD.MM.YYYY HH:mm')
: '—'}
{STATUS_LABELS[approval.status || ''] || approval.status}
setSelectedApprovalId(approval.id!)}
>
))
)}
{totalPages > 1 && (
Страница {page} из {totalPages}
)}
>
)}
{isFetching && !isLoading && (
)}
setSelectedApprovalId(null)}
/>
)
}
-----END src/pages/approvals/ApprovalsPage.tsx-----
File: src/pages/approvals/components/ApprovalDetailsModal.tsx
Lines: 690
-----BEGIN src/pages/approvals/components/ApprovalDetailsModal.tsx-----
import { useState } from 'react'
import {
Modal,
Stack,
Text,
Group,
Badge,
Paper,
Loader,
Center,
Timeline,
ScrollArea,
Box,
ActionIcon,
Tooltip,
Alert,
Divider,
} from '@mantine/core'
import {
IconUser,
IconBuilding,
IconCalendar,
IconFileText,
IconCheck,
IconX,
IconClock,
IconAlertCircle,
IconEye,
IconDownload,
IconMessageCircle,
IconUserPlus,
IconEyeglass,
IconRotate,
IconChecklist,
IconAlertTriangle,
} from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import {
useApproval,
useAdditionalApprovers,
useApprovalComments,
useApprovalObservers,
useRevocationRequest,
useApprovalTasks,
} from '@/features/approvals/hooks/useApprovals'
import { useCategories } from '@/features/categories/hooks/useCategories'
import FilePreviewModal from './FilePreviewModal'
import { formatMsk } from '@/utils/date'
interface ApprovalDetailsModalProps {
approvalId: number | null
opened: boolean
onClose: () => void
}
const STATUS_COLORS: Record = {
draft: 'gray',
pending: 'blue',
approved: 'green',
rejected: 'red',
revoked: 'orange',
revision: 'violet',
}
const STATUS_LABELS: Record = {
pending: 'На согласовании',
approved: 'Согласована',
rejected: 'Отклонена',
revoked: 'Отозвана',
revision: 'На доработке',
}
const STEP_STATUS_ICONS: Record = {
pending: IconClock,
approved: IconCheck,
rejected: IconX,
waiting: IconClock,
cancelled_any_of: IconAlertCircle,
}
const STEP_STATUS_COLORS: Record = {
pending: 'blue',
approved: 'green',
rejected: 'red',
waiting: 'gray',
cancelled_any_of: 'orange',
}
// Статусы "доп. согласующего" — те же значения, что в handleDecision
// (isAdditionalApprover): "pending" / "approved" / "rejected".
const ADDITIONAL_APPROVER_LABELS: Record = {
pending: 'Ожидает решения',
approved: 'Одобрил',
rejected: 'Отклонил',
}
const ADDITIONAL_APPROVER_COLORS: Record = {
pending: 'blue',
approved: 'green',
rejected: 'red',
}
// Статусы согласующего на запрос отзыва (см. HandleRevocationApproverDecision
// в telegram_service).
const REVOCATION_APPROVER_LABELS: Record = {
pending: 'Ещё не ответил',
approved: 'Согласен на отзыв',
rejected: 'Против отзыва',
}
const REVOCATION_APPROVER_COLORS: Record = {
pending: 'gray',
approved: 'green',
rejected: 'red',
}
const APPROVAL_MODE_LABELS: Record = {
sequential: 'Последовательно',
any_of: 'Любой из согласующих',
}
// Статусы задач — те же значения и подписи, что в отчёте (reportcore.go)
// и в "Стадиях согласования" бота.
const TASK_STATUS_LABELS: Record = {
pending: 'В работе',
waiting: 'Ожидает',
completed: 'Выполнена',
cancelled: 'Отменена',
cancellation: 'Требует отмены изменений',
}
const TASK_STATUS_COLORS: Record = {
pending: 'blue',
waiting: 'gray',
completed: 'green',
cancelled: 'red',
cancellation: 'orange',
}
const PREVIEWABLE_TYPES = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/svg+xml',
'application/pdf',
'text/plain',
]
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 generateSignature = async (): Promise<{ signature: string; timestamp: string; deviceId: string }> => {
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'
return { signature, timestamp, deviceId }
}
const getAuthHeaders = async () => {
const token = localStorage.getItem('token')
const { signature, timestamp, deviceId } = await generateSignature()
return {
Authorization: `Bearer ${token}`,
ApiKey: signature,
'X-Timestamp': timestamp,
'x-device-id': deviceId,
}
}
export default function ApprovalDetailsModal({
approvalId,
opened,
onClose,
}: ApprovalDetailsModalProps) {
const { data: approval, isLoading } = useApproval(approvalId)
const { data: categories } = useCategories({ limit: 1000 })
// Хуки отдают ApiResponse целиком (как useFlowNodesTree раньше) —
// разворачиваем здесь, а не в самих хуках, чтобы не плодить два разных
// соглашения об обёртке в одном проекте.
const { data: additionalApproversResponse } = useAdditionalApprovers(approvalId)
const { data: commentsResponse } = useApprovalComments(approvalId)
const { data: observersResponse } = useApprovalObservers(approvalId)
const { data: revocationRequestResponse } = useRevocationRequest(approvalId)
const { data: tasksResponse } = useApprovalTasks(approvalId)
const additionalApprovers = additionalApproversResponse?.data
const comments = commentsResponse?.data
const observers = observersResponse?.data
const revocationRequest = revocationRequestResponse?.data
const tasksData = tasksResponse?.data
const [previewFileId, setPreviewFileId] = useState(null)
const [previewFileName, setPreviewFileName] = useState('')
const [previewFileType, setPreviewFileType] = useState('')
const category = approval?.topic?.category_id && categories?.data
? categories.data.find((c) => c.id === approval.topic?.category_id)
: null
const handleFilePreview = (fileId: number, fileName: string) => {
setPreviewFileId(fileId)
setPreviewFileName(fileName)
setPreviewFileType(getMimeType(fileName))
}
const handleFileDownload = async (fileId: number, fileName: string) => {
try {
const headers = await getAuthHeaders()
const url = `/api/approvals/${approvalId}/files/${fileId}/download`
const response = await fetch(url, { method: 'GET', headers })
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) {
console.error('Download error:', error)
notifications.show({ title: 'Ошибка', message: 'Не удалось скачать файл', color: 'red' })
}
}
// Показываем превью "что будет поставлено" только пока заявка ещё не
// согласована И задачи по факту ещё не созданы — как только появились
// реальные ApprovalTask, показываем уже их (ниже), а не план.
const showPlannedTasks =
approval?.status === 'pending' &&
!!tasksData?.topic_executors?.length &&
!tasksData?.tasks?.length
return (
<>
Заявка #{approvalId}
{approval && (
{STATUS_LABELS[approval.status || ''] || approval.status}
)}
}
size="xl"
styles={{ body: { height: 'calc(80vh - 120px)', padding: 0 } }}
>
{isLoading ? (
) : approval ? (
{/* НОВОЕ: ошибка создания задач — та же логика, что в отчёте
(reportcore.go: hasTaskError). Ставим у самого верха, это
требует внимания администратора, а не просто информация. */}
{tasksData?.has_task_error && (
} color="red" variant="filled">
Ошибка при создании задачи
Для темы этой заявки настроены исполнители, заявка согласована, но ни
одной задачи по факту не создано — стоит проверить вручную.
)}
{/* НОВОЕ: активный запрос на отзыв — самое "срочное", поэтому
сверху, ещё до общей информации. Показывается, только если
такой запрос реально есть (backend отдаёт data: null иначе) */}
{revocationRequest && (
} color="orange" variant="light">
Идёт запрос на отзыв этой заявки
Инициатор запроса: {revocationRequest.requested_by_name}
{revocationRequest.reason && (
Причина: {revocationRequest.reason}
)}
{revocationRequest.approvers.map((a) => (
{a.approver_name}
{REVOCATION_APPROVER_LABELS[a.status] || a.status}
))}
)}
{/* Основная информация */}
Основная информация
Категория:
{category?.name || '—'}
Тема:
{approval.topic?.name || '—'}
{/* Режим согласования — лежит на теме */}
{approval.topic?.approval_mode && (
Режим согласования:
{APPROVAL_MODE_LABELS[approval.topic.approval_mode] ||
approval.topic.approval_mode}
)}
Инициатор:
{approval.initiator?.full_name || '—'}
Отдел:
{approval.department?.name || '—'}
Дата создания (МСК):
{formatMsk(approval.created_at)}
{/* НОВОЕ: превью "что будет поставлено" — только для pending-заявок,
пока реальных задач ещё нет. Данные берём из ApprovalTopicExecutor
(настройка темы), а не из ApprovalTask (их ещё физически не существует). */}
{showPlannedTasks && (
Какие задачи будут поставлены после согласования
{tasksData!.topic_executors
.slice()
.sort((a, b) => a.step_order - b.step_order)
.map((te) => (
{te.task_text || '—'}
{te.executor_name || 'Исполнитель не назначен'}
))}
Появится автоматически, как только заявку согласуют полностью.
)}
{/* НОВОЕ: уже реально выставленные задачи */}
{!!tasksData?.tasks?.length && (
Задачи
{tasksData.tasks.map((task, i) => (
Выставлена задача №{i + 1}
{TASK_STATUS_LABELS[task.status] || task.status}
{task.task_text || '—'}
Исполнитель: {task.executor_name || '—'}
{task.completed_at && <> · Выполнена {formatMsk(task.completed_at)}>}
))}
)}
{/* Наблюдатели — вычисляются динамически по категории/теме
(не хранимая связь), поэтому отдельным запросом */}
{observers && observers.length > 0 && (
Наблюдатели
{observers.map((o) => (
{o.full_name}
))}
)}
{/* Текст заявки */}
{approval.content && (
Текст заявки
{approval.content}
)}
{/* Метаданные */}
{approval.metadata && (
Метаданные
{(() => {
try {
return JSON.stringify(JSON.parse(approval.metadata), null, 2)
} catch {
return approval.metadata
}
})()}
)}
{/* Файлы */}
{approval.files && approval.files.length > 0 && (
Прикреплённые файлы
{approval.files.map((file) => {
const mimeType = getMimeType(file.file_name || '')
const canPreview = PREVIEWABLE_TYPES.includes(mimeType)
const fileSizeKB = file.file_base64
? Math.round((file.file_base64.length * 3) / 4 / 1024)
: 0
return (
{file.file_name || 'Без имени'}
{fileSizeKB > 0 && (
{fileSizeKB} KB
)}
{canPreview && (
handleFilePreview(file.id!, file.file_name || '')}
>
)}
handleFileDownload(file.id!, file.file_name || '')}
>
)
})}
)}
{/* Шаги согласования */}
{approval.steps && approval.steps.length > 0 && (
Шаги согласования
{approval.steps
.sort((a, b) => (a.step_order || 0) - (b.step_order || 0))
.map((step, index) => {
const StatusIcon = STEP_STATUS_ICONS[step.status || ''] || IconClock
return (
}
title={
Шаг {index + 1}: {step.approver_name_snapshot || 'Согласующий'}
{step.status}
}
>
{step.approver?.full_name || '—'}
{step.acted_at && (
<>
{' • '}
{formatMsk(step.acted_at)}
>
)}
{step.comment && (
Комментарий: {step.comment}
)}
)
})}
)}
{/* Дополнительные согласующие */}
{additionalApprovers && additionalApprovers.length > 0 && (
Дополнительные согласующие
{additionalApprovers.map((aa) => (
{aa.approver_name}
{aa.acted_at && (
{formatMsk(aa.acted_at)}
)}
{ADDITIONAL_APPROVER_LABELS[aa.status] || aa.status}
))}
)}
{/* Комментарии */}
{comments && comments.length > 0 && (
Комментарии ({comments.length})
{comments.map((c, i) => (
{c.user_name}
{c.created_at && (
{formatMsk(c.created_at)}
)}
{c.comment}
{i < comments.length - 1 && }
))}
)}
{/* Информация об отзыве */}
{approval.status === 'revoked' && approval.revoked_by && (
Информация об отзыве
Отозвана: {approval.revoked_by.full_name}
{approval.revoked_at && <> {formatMsk(approval.revoked_at)}>}
)}
{/* Информация о доработке */}
{approval.status === 'revision' && (
Информация о доработке
{approval.revision_comment && (
Комментарий: {approval.revision_comment}
)}
{approval.revision_count !== undefined && approval.revision_count > 0 && (
Количество доработок: {approval.revision_count}
)}
)}
) : (
Заявка не найдена
)}
{previewFileId && approvalId && (
setPreviewFileId(null)}
/>
)}
>
)
}
-----END src/pages/approvals/components/ApprovalDetailsModal.tsx-----
File: src/pages/approvals/components/FilePreviewModal.tsx
Lines: 266
-----BEGIN src/pages/approvals/components/FilePreviewModal.tsx-----
import { useState, useEffect } from 'react'
import { Modal, Group, Text, Loader, Center, Paper, ActionIcon, Stack, Box } from '@mantine/core'
import { IconDownload } from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
interface FilePreviewModalProps {
approvalId?: number // Теперь опционально
fileId: number
fileName: string
fileType: string
opened: boolean
onClose: () => void
taskId?: number // 🆕 Для файлов задач
}
// 🆕 Тип сущности
type EntityType = 'approval' | 'task'
const getAuthHeaders = async () => {
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'
return {
'Authorization': `Bearer ${token}`,
'ApiKey': signature,
'X-Timestamp': timestamp,
'x-device-id': deviceId,
}
}
export default function FilePreviewModal({
approvalId,
fileId,
fileName,
fileType,
opened,
onClose,
taskId, // 🆕
}: FilePreviewModalProps) {
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [fileUrl, setFileUrl] = useState(null)
// 🆕 Определяем тип сущности
const entityType: EntityType = taskId ? 'task' : 'approval'
const entityId = taskId || approvalId
// 🆕 Формируем URL в зависимости от типа сущности
const getPreviewUrl = () => {
if (entityType === 'task') {
return `/api/approval-tasks/${taskId}/files/${fileId}`
}
return `/api/approvals/${approvalId}/files/${fileId}`
}
const getDownloadUrl = () => {
if (entityType === 'task') {
return `/api/approval-tasks/${taskId}/files/${fileId}/download`
}
return `/api/approvals/${approvalId}/files/${fileId}/download`
}
const canPreview = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/svg+xml',
'application/pdf',
'text/plain',
].includes(fileType)
useEffect(() => {
if (!opened || !canPreview || !entityId) return
let objectUrl: string | null = null
const loadFile = async () => {
setLoading(true)
setError(null)
try {
const headers = await getAuthHeaders()
const url = getPreviewUrl()
const response = await fetch(url, {
method: 'GET',
headers,
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
const blob = await response.blob()
objectUrl = window.URL.createObjectURL(blob)
setFileUrl(objectUrl)
} catch (err) {
console.error('File load error:', err)
setError('Не удалось загрузить файл')
} finally {
setLoading(false)
}
}
loadFile()
return () => {
if (objectUrl) {
window.URL.revokeObjectURL(objectUrl)
}
}
}, [opened, entityId, fileId, canPreview])
const handleDownload = async () => {
try {
const headers = await getAuthHeaders()
const url = getDownloadUrl()
const response = await fetch(url, {
method: 'GET',
headers,
})
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 (err) {
console.error('Download error:', err)
notifications.show({
title: 'Ошибка',
message: 'Не удалось скачать файл',
color: 'red',
})
}
}
if (!canPreview) {
return (
Предпросмотр этого типа файла не поддерживается.
Вы можете скачать файл.
)
}
return (
{fileName}
}
size="xl"
styles={{
body: {
height: 'calc(80vh - 120px)',
padding: 0,
},
}}
>
{loading && (
Загрузка файла...
)}
{error && (
{error}
)}
{fileUrl && !error && (
<>
{fileType.startsWith('image/') ? (
) : fileType === 'application/pdf' ? (
) : fileType === 'text/plain' ? (
) : null}
>
)}
)
}
-----END src/pages/approvals/components/FilePreviewModal.tsx-----
File: src/pages/categories/CategoriesPage.tsx
Lines: 230
-----BEGIN src/pages/categories/CategoriesPage.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 { useCategories, useDeleteCategory } from '@/features/categories/hooks/useCategories'
import CategoryEditModal from './components/CategoryEditModal'
const LIMIT = 20
export default function CategoriesPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [activeFilter, setActiveFilter] = useState(null)
const [editCategoryId, setEditCategoryId] = useState(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const { data, isLoading, isFetching } = useCategories({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(search && { name: search }),
...(activeFilter !== null && { is_active: activeFilter }),
})
const deleteCategory = useDeleteCategory()
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: () => deleteCategory.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((category) => (
{category.id}
{category.name}
{category.code}
{category.description || '—'}
{category.is_active ? 'Активна' : 'Неактивна'}
setEditCategoryId(category.id!)}
>
handleDelete(category.id!)}
>
))
)}
{/* Пагинация */}
{totalPages > 1 && (
Страница {page} из {totalPages}
)}
>
)}
{/* Индикатор обновления */}
{isFetching && !isLoading && (
)}
{/* Модальное окно редактирования */}
setEditCategoryId(null)}
/>
{/* Модальное окно создания */}
setCreateModalOpened(false)}
/>
)
}
-----END src/pages/categories/CategoriesPage.tsx-----
File: src/pages/categories/components/CategoryEditModal.tsx
Lines: 151
-----BEGIN src/pages/categories/components/CategoryEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Textarea,
Switch,
Group,
Button,
Text,
Loader,
Center,
Badge,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
useCategory,
useCreateCategory,
useUpdateCategory
} from '@/features/categories/hooks/useCategories'
interface CategoryEditModalProps {
categoryId: number | null
opened: boolean
onClose: () => void
}
export default function CategoryEditModal({
categoryId,
opened,
onClose
}: CategoryEditModalProps) {
const { data: category, isLoading: categoryLoading } = useCategory(categoryId)
const createCategory = useCreateCategory()
const updateCategory = useUpdateCategory()
const isEditMode = categoryId !== null
const form = useForm({
initialValues: {
name: '',
code: '',
description: '',
is_active: true,
},
validate: {
name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
code: (value: string | any[]) => {
if (value.length < 2) return 'Код должен содержать минимум 2 символа'
if (!/^[a-z0-9_]+$/.test(value as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
return null
},
},
})
// Заполняем форму данными категории
useEffect(() => {
if (category) {
form.setValues({
name: category.name || '',
code: category.code || '',
description: category.description || '',
is_active: category.is_active ?? true,
})
} else if (!isEditMode) {
form.reset()
}
}, [category, isEditMode])
const handleSubmit = async (values: typeof form.values) => {
if (isEditMode && categoryId) {
// Режим редактирования
await updateCategory.mutateAsync({
id: categoryId,
...values,
})
} else {
// Режим создания
await createCategory.mutateAsync(values)
}
onClose()
}
const isLoading = categoryLoading
const isSubmitting = createCategory.isPending || updateCategory.isPending
return (
{isEditMode ? 'Редактирование категории' : 'Создание категории'}
{category && ID: {category.id} }
}
size="md"
>
{isLoading ? (
) : (
)}
)
}
-----END src/pages/categories/components/CategoryEditModal.tsx-----
File: src/pages/flowNodes/FlowTreeGuidePage.tsx
Lines: 766
-----BEGIN src/pages/flowNodes/FlowTreeGuidePage.tsx-----
import { useState, useEffect } from 'react'
import {
Stack,
Text,
Code,
Paper,
Group,
Box,
Title,
Table,
Divider,
ActionIcon,
Tooltip,
CopyButton,
ScrollArea,
Badge,
Alert,
UnstyledButton,
Timeline,
ThemeIcon,
} from '@mantine/core'
import {
IconArrowLeft,
IconCopy,
IconCheck,
IconBulb,
IconAlertTriangle,
} from '@tabler/icons-react'
import { useNavigate } from 'react-router-dom'
// ================================================================
// Структура документации
// ================================================================
interface DocSection {
id: string
title: string
level: number
}
const SECTIONS: DocSection[] = [
{ id: 'overview', title: 'Что это такое', level: 1 },
{ id: 'terms', title: 'Три простых понятия', level: 1 },
{ id: 'howto', title: 'Как создать дерево — по шагам', level: 1 },
{ id: 'step-1', title: ' 1. Выбрать категорию', level: 2 },
{ id: 'step-2', title: ' 2. Создать первый узел', level: 2 },
{ id: 'step-3', title: ' 3. Добавить варианты (ветки)', level: 2 },
{ id: 'step-4', title: ' 4. Завершить ветку вводом текста', level: 2 },
{ id: 'step-5', title: ' 5. Настроить сообщение согласующему', level: 2 },
{ id: 'step-6', title: ' 6. Проверить результат', level: 2 },
{ id: 'node-types', title: 'Три типа узлов', level: 1 },
{ id: 'example-1', title: 'Пример: «Отпуска»', level: 1 },
{ id: 'example-2', title: 'Пример: выбор из нескольких списков', level: 1 },
{ id: 'template-basics', title: 'Как писать сообщение согласующему', level: 1 },
{ id: 'tips', title: 'Советы и правила', level: 1 },
{ id: 'troubleshooting', title: 'Если что-то не работает', level: 1 },
]
export default function FlowTreeGuidePage() {
const navigate = useNavigate()
const [activeSection, setActiveSection] = useState('overview')
useEffect(() => {
const handleScroll = () => {
const scrollPosition = window.scrollY + 100
for (const section of [...SECTIONS].reverse()) {
const element = document.getElementById(section.id)
if (element && element.offsetTop <= scrollPosition) {
setActiveSection(section.id)
break
}
}
}
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
}, [])
const scrollTo = (id: string) => {
document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' })
setActiveSection(id)
}
return (
Руководство
navigate('/nodes')}
>
{SECTIONS.map((section) => (
scrollTo(section.id)}
px={section.level === 2 ? 20 : 12}
py={6}
style={{
borderRadius: 4,
backgroundColor:
activeSection === section.id
? 'var(--mantine-color-blue-0)'
: 'transparent',
borderLeft:
activeSection === section.id
? '2px solid var(--mantine-color-blue-6)'
: '2px solid transparent',
}}
>
{section.title}
))}
{/* ============================================================ */}
{/* Основной контент */}
{/* ============================================================ */}
{/* Заголовок */}
Как настроить дерево согласования
Это руководство для тех, кто настраивает бота — без программирования.
Здесь пошагово показано, как собрать «дерево» вопросов, которые бот задаёт
сотруднику, когда тот создаёт заявку: например, «Какой регион?» →
«Какая причина?» → «Опишите заявку».
{/* ============================================================ */}
{/* ОБЗОР */}
{/* ============================================================ */}
Когда сотрудник создаёт заявку в Telegram-боте, бот задаёт ему вопросы по
очереди и предлагает варианты ответов кнопками. Например: «Выберите
регион» → «Крым» или «Краснодар» → «Опишите заявку текстом». Эта
последовательность вопросов и есть дерево .
Вы настраиваете это дерево в разделе «Конструктор деревьев» — без единой
строчки кода. Каждый вопрос и каждая кнопка — это отдельный «узел», который
вы добавляете через простую форму.
Так настраиваются любые сценарии: отпуска, больничные, внебюджетные
расходы, возвраты и любые другие заявки. Если появится новый вид заявки —
не нужно ничего программировать, достаточно собрать новое дерево здесь.
{/* ============================================================ */}
{/* ТРИ ПОНЯТИЯ */}
{/* ============================================================ */}
Прежде чем начать, важно понимать всего три вещи:
Понятие
Что это простыми словами
Категория
Раздел заявок, который вы выбираете вверху страницы («Отпуска»,
«Внебюджетные расходы» и т.д.). Одно дерево всегда строится
внутри одной категории.
Узел
Один шаг в дереве: кнопка с вариантом ответа, поле ввода текста
или список для множественного выбора. Узлы соединяются друг с
другом — у каждого может быть несколько «детей» (следующих
шагов).
Тема заявки
То, во что в итоге превращается пройденный сотрудником путь по
дереву. Например, путь «Крым → За свой счёт» превращается в
конкретную тему заявки со своими согласующими.
Дерево — это как схема метро: от начальной станции (первого вопроса) до
конечной (поля ввода текста) должен существовать путь через любые
промежуточные станции (кнопки-варианты). Ваша задача — построить эти пути.
{/* ============================================================ */}
{/* ПОРЯДОК СОЗДАНИЯ */}
{/* ============================================================ */}
Ниже — точный порядок действий от пустой категории до готового,
работающего дерева.
Откройте страницу «Конструктор деревьев» и в выпадающем списке «Категория»
выберите нужный раздел. Если подходящей категории ещё нет — обратитесь к
администратору, чтобы её создали (это отдельная настройка, не относится к
дереву).
Если дерево для этой категории уже существует, вы увидите его сразу после
выбора. Можно смело редактировать — все изменения сохраняются
автоматически, ничего не потеряется.
Нажмите кнопку «Добавить корневой узел». Это будет самый первый вопрос,
который увидит сотрудник. Откроется окно с тремя полями:
Поле
Что писать
Тип узла
Оставьте «Кнопка» — для первого шага почти всегда нужна кнопка
Название
То, что увидит сотрудник, например «Отпуска»
Ключ
Не трогайте — заполняется автоматически из названия
Нажмите «Создать». Узел появится в дереве — с него всё и начинается.
Наведите на созданный узел — рядом появятся кнопки. Нажмите «+», чтобы
добавить к нему дочерний узел — следующий шаг вопроса. Повторяйте это для
каждого варианта ответа.
Например, если первый узел — «Тип отпуска», добавьте к нему детей:
«Отпуск», «Отгул», «Больничный». Каждый из них — отдельная кнопка, которую
увидит сотрудник после выбора первого шага.
Для узлов-кнопок в форме есть два поля: DataKey — название того, что
мы запоминаем (например «тип отпуска»), и DataValue — конкретное
значение этой кнопки (например «отпуск»). У всех кнопок-веток одного и того
же вопроса DataKey должен быть одинаковым, а DataValue — у каждой свой.
Смотрите готовый пример ниже — там всё видно на конкретных значениях.
Каждая ветка дерева обязательно должна заканчиваться узлом «Текстовый
ввод» — это последний шаг, где сотрудник пишет саму заявку своими словами.
Добавьте такой узел к каждому «листу» дерева (к узлу, у которого больше нет
вариантов выбора).
В форме выберите тип узла «Текстовый ввод» и заполните поле «Подсказка» —
это пример того, что должен написать сотрудник, чтобы ему было понятнее.
Пройдите мысленно (или на бумаге) каждый путь от первого узла до конца.
Если какой-то путь обрывается на кнопке, не доходя до текстового ввода —
сотрудник не сможет завершить заявку. Добавьте туда узел ввода.
На узле, где заявка «превращается» в конкретную тему (обычно это последний
узел-кнопка перед вводом текста), можно раскрыть блок «Шаблоны сообщения и
кода темы» и задать, как будет выглядеть уведомление у согласующего в
Telegram. Подробно про это — в разделе{' '}
«Как писать сообщение согласующему» {' '}
ниже. Если ничего не менять — сработает оформление по умолчанию.
Дерево сохраняется автоматически после каждого действия — отдельной кнопки
«Сохранить всё» нажимать не нужно. Лучший способ проверить готовое дерево —
попросить коллегу создать тестовую заявку через бота и убедиться, что все
вопросы задаются в правильном порядке, а итоговое сообщение согласующему
выглядит понятно.
{/* ============================================================ */}
{/* ТИПЫ УЗЛОВ */}
{/* ============================================================ */}
При создании или редактировании узла вы выбираете один из трёх типов:
🔘
Кнопка
Сотрудник нажимает и переходит к следующему шагу. Используется для
любого выбора из вариантов: регион, тип заявки, филиал и т.д.
Требует заполнения DataKey и DataValue.
📝
Текстовый ввод
Сотрудник печатает текст. Всегда завершает ветку дерева — после
него бот создаёт заявку. Требует заполнения «Подсказки» —
примера того, что нужно написать.
☑️
Мультивыбор
Сотрудник может отметить сразу несколько вариантов (например,
несколько систем: «ОКБ» и «1С»). Все отмеченные варианты
сохранятся вместе, через запятую.
{/* ============================================================ */}
{/* ПРИМЕР 1 */}
{/* ============================================================ */}
Разберём готовый пример целиком — от первого узла до отправки заявки.
Сценарий: сотрудник выбирает тип отсутствия, затем способ оплаты, затем
пишет причину.
Название: Тип отсутствия. Тип узла: Кнопка. Это
«заголовок» дерева — сам по себе кнопкой сотруднику не показывается,
но от него отходят первые варианты.
Добавляем к корню три узла: Отпуск, Отгул,{' '}
Больничный. У всех трёх DataKey одинаковый —{' '}
absence_type, а DataValue разный: vacation,{' '}
timeoff, sickleave.
К узлу «Отпуск» добавляем два дочерних узла: За свой счёт{' '}
и В счёт отпуска. DataKey у обоих —{' '}
payment_type, DataValue — own_expense и{' '}
vacation_account соответственно. Аналогично поступаем с
ветками «Отгул» и «Больничный».
К каждому из узлов способа оплаты добавляем узел «Текстовый ввод» с
подсказкой: Укажите даты отпуска, например: 22.02.2026 — 25.02.2026.
На узле способа оплаты (там, где заявка уже точно определена)
открываем «Шаблоны сообщения и кода темы» и вписываем текст — см.
пример ниже.
Что увидит сотрудник в боте: сначала кнопки «Отпуск / Отгул /
Больничный», затем — «За свой счёт / В счёт отпуска», затем поле для
ввода дат. Три нажатия и один текст — заявка готова.
Тип: {{.absence_type_label}}
{{.initiator_name}} просит согласовать: {{.payment_type_label}}
{{.content}}`}
/>
Всё, что в фигурных скобках — подставится автоматически: название узла,
который выбрал сотрудник, его имя и текст, который он написал. Про этот
синтаксис подробнее — в разделе ниже.
{/* ============================================================ */}
{/* ПРИМЕР 2 */}
{/* ============================================================ */}
Более сложный, но частый случай: нужно спросить у сотрудника два
независимых параметра подряд — например, филиал и тип расхода.
Обратите внимание: узел «ТМЦ» повторяется дважды — под «Филиал 1» и под
«Филиал 2». Это нормально: узлы с одинаковым названием на разных ветках
дерева — это разные, независимые узлы, у каждого свой ключ (система
добавляет к ключу префикс родителя автоматически).
Внебюджетные расходы — {{.branch_label}} ({{.expense_type_label}})
{{.initiator_name}} :
{{.content}}`}
/>
{/* ============================================================ */}
{/* ШАБЛОНЫ */}
{/* ============================================================ */}
В блоке «Шаблоны сообщения и кода темы» вы пишете обычный текст с
HTML-разметкой (<b>жирный</b>,{' '}
<i>курсив</i>) — так, как хотите видеть уведомление
у согласующего. В нужных местах вставляете «плейсхолдеры» в фигурных
скобках — они подставляются автоматически.
Что написать
Что подставится
{`{{.initiator_name}}`}
Имя сотрудника, который создал заявку
{`{{.content}}`}
Текст, который сотрудник ввёл на последнем шаге
{`{{.название_кнопки_label}}`}
Название выбранной сотрудником кнопки. Например, если DataKey
кнопки — region, пишите{' '}
{`{{.region_label}}`}, и туда подставится «Крым» или
«Краснодар» — смотря что выбрал сотрудник
Не нужно запоминать синтаксис. Откройте похожий уже настроенный узел (в
этой же или другой категории), скопируйте оттуда шаблон и замените
плейсхолдеры на DataKey ваших узлов.
Дополнительно доступны несколько простых условий — пригодятся, если
сообщение должно немного отличаться в зависимости от выбора:
Поле «Шаблон кода темы» обычно можно не трогать — если оставить пустым,
система сама соберёт код заявки из всех выборов сотрудника. Заполняйте его
только если вам явно сказали, что для этой темы нужен особый код
(например, если это уже настроенная в системе тема с заранее заданным
названием).
{/* ============================================================ */}
{/* СОВЕТЫ */}
{/* ============================================================ */}
{/* ============================================================ */}
{/* ДИАГНОСТИКА */}
{/* ============================================================ */}
Частые ситуации и что с ними делать:
Остались вопросы — обратитесь к администратору системы согласований.
)
}
// ================================================================
// Вспомогательные компоненты
// ================================================================
function DocSection({ id, title, level = 1 }: { id: string; title: string; level?: number }) {
return (
{level === 1 ? (
{title}
) : (
{title}
)}
)
}
function CodeBlock({ title, code }: { title: string; code: string }) {
return (
{title}
{({ copied, copy }) => (
{copied ? : }
)}
{code}
)
}
function Callout({ title, children, mt = 'md' }: { title: string; children: React.ReactNode; mt?: string }) {
return (
}
title={title}
mt={mt}
styles={{
title: { fontSize: 13, fontWeight: 600 },
message: { fontSize: 13 },
}}
>
{children}
)
}
function TipEntry({ title, text }: { title: string; text: string }) {
return (
{title}
{text}
)
}
function ErrorEntry({ title, description, resolution }: { title: string; description: string; resolution: string }) {
return (
{title}
{description}
Что делать:
{resolution}
)
}
-----END src/pages/flowNodes/FlowTreeGuidePage.tsx-----
File: src/pages/flowNodes/FlowTreePage.tsx
Lines: 210
-----BEGIN src/pages/flowNodes/FlowTreePage.tsx-----
import { useState, useMemo } from 'react'
import {
Paper,
Group,
Button,
Text,
Select,
Loader,
Center,
Stack,
Badge,
Alert,
Tooltip,
} from '@mantine/core'
import { IconPlus, IconInfoCircle, IconBook, IconFolderPlus, IconRefresh } from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { useCategories } from '@/features/categories/hooks/useCategories'
import {
useFlowNodesTree,
useDeleteFlowNode,
useDuplicateFlowNode,
useReloadBot,
} from '@/features/flowNodes/hooks/useFlowNodes'
import { findParent } from '@/features/flowNodes/utils/treeWalk'
import type { ApprovalFlowNode, ApprovalTopicCategory } from '@/types/api'
import { useNavigate } from 'react-router-dom'
import CategoryCreateModal from "@/pages/flowNodes/components/CategoryCreateModal.tsx";
import FlowNodeEditModal from "@/pages/flowNodes/components/FlowNodeEditModal.tsx";
import SortableFlowTree from "@/pages/flowNodes/components/SortableFlowTree.tsx";
import TreeHealthPanel from "@/pages/flowNodes/components/TreeHealthPanel.tsx";
export default function FlowTreePage() {
const [selectedCategoryId, setSelectedCategoryId] = useState(null)
const [categoryModalOpened, setCategoryModalOpened] = useState(false)
const [editModal, setEditModal] = useState<{
opened: boolean
parentNode: ApprovalFlowNode | null
editNode: ApprovalFlowNode | null
}>({ opened: false, parentNode: null, editNode: null })
const { data: categoriesData } = useCategories({ limit: 1000, is_active: true })
const categories = categoriesData?.data || []
const { data: treeData, isLoading: treeLoading } = useFlowNodesTree(selectedCategoryId)
const tree = treeData?.data || []
const deleteFlowNode = useDeleteFlowNode()
const duplicateFlowNode = useDuplicateFlowNode()
const reloadBot = useReloadBot()
const navigate = useNavigate()
const selectedCategory = useMemo(
() => categories.find((c) => c.id === selectedCategoryId) || null,
[categories, selectedCategoryId]
)
const categoryOptions = categories.map((c) => ({ value: String(c.id), label: `${c.name} (${c.code})` }))
const countNodes = (nodes: ApprovalFlowNode[]): number => {
let count = nodes.length
for (const n of nodes) if (n.children) count += countNodes(n.children)
return count
}
const totalNodes = countNodes(tree)
const handleEdit = (node: ApprovalFlowNode) => {
const parent = findParent(tree, node.id!)
setEditModal({ opened: true, parentNode: parent, editNode: node })
}
const handleAddChild = (parent: ApprovalFlowNode) => {
setEditModal({ opened: true, parentNode: parent, editNode: null })
}
const handleAddRoot = () => {
setEditModal({ opened: true, parentNode: null, editNode: null })
}
const handleDelete = (node: ApprovalFlowNode) => {
modals.openConfirmModal({
title: 'Удалить этот шаг?',
children: (
Удалить шаг {node.label} ? Все шаги, которые идут после него, тоже удалятся.
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteFlowNode.mutate(node.id!),
})
}
const handleDuplicate = (node: ApprovalFlowNode) => duplicateFlowNode.mutate(node.id!)
return (
Конструктор тем
{selectedCategory && {totalNodes} шагов }
}
onClick={() => reloadBot.mutate()}
loading={reloadBot.isPending}
>
Обновить бота
} onClick={() => navigate('/guide/flow-trees')}>
Руководство
setSelectedCategoryId(v ? Number(v) : null)}
searchable
style={{ flex: 1 }}
/>
}
onClick={() => setCategoryModalOpened(true)}
>
Новый раздел
{selectedCategoryId && (
{treeLoading && }
} onClick={handleAddRoot} disabled={tree.length > 0}>
Добавить первый вопрос
} color="blue" variant="light">
Перетаскивайте шаги за значок ⠿ слева, чтобы менять порядок и вложенность — тяните
влево/вправо во время перетаскивания, чтобы изменить уровень. Первый шаг дерева
(с пометкой «начало дерева») не перетаскивается.
{treeLoading ? (
) : tree.length === 0 ? (
В этом разделе пока нет вопросов
} onClick={handleAddRoot}>
Добавить первый вопрос
) : (
)}
)}
{selectedCategoryId && tree.length > 0 && }
{selectedCategoryId && (
setEditModal({ opened: false, parentNode: null, editNode: null })}
/>
)}
setCategoryModalOpened(false)}
onCreated={(newId) => setSelectedCategoryId(newId)}
/>
)
}
-----END src/pages/flowNodes/FlowTreePage.tsx-----
File: src/pages/flowNodes/components/CategoryCreateModal.tsx
Lines: 120
-----BEGIN src/pages/flowNodes/components/CategoryCreateModal.tsx-----
import { useEffect } from 'react'
import { Modal, Stack, TextInput, Textarea, Group, Button, Text, Alert } from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconInfoCircle } from '@tabler/icons-react'
import { useCreateCategory } from '@/features/categories/hooks/useCategories'
import type { CreateCategoryRequest } from '@/api/categories'
interface CategoryCreateModalProps {
opened: boolean
onClose: () => void
onCreated: (categoryId: number) => void
}
const translitMap: Record = {
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'yo', ж: 'zh', з: 'z', и: 'i', й: 'y',
к: 'k', л: 'l', м: 'm', н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f',
х: 'h', ц: 'ts', ч: 'ch', ш: 'sh', щ: 'sch', ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
}
function slugify(text: string): string {
return text
.toLowerCase()
.split('')
.map((ch) => translitMap[ch] ?? ch)
.join('')
.replace(/[\s-]+/g, '_')
.replace(/[^a-z0-9_]/g, '')
.replace(/_+/g, '_')
.replace(/^_+|_+$/g, '')
// Код раздела попадает в Telegram callback_data КАЖДОЙ кнопки внутри
// этой категории (формат "appr:{код_раздела}:{ключ_шага}", лимит
// Telegram — 64 байта на всю строку) — держим его коротким, иначе
// он съедает бюджет, который нужен для ключей узлов вглубь дерева.
.substring(0, 20)
}
// Создание новой категории (раздела заявок) прямо из конструктора дерева —
// требование "полной автономности": админ не должен переходить в другой
// раздел, чтобы завести новый вид заявки.
export default function CategoryCreateModal({ opened, onClose, onCreated }: CategoryCreateModalProps) {
const createCategory = useCreateCategory()
const form = useForm({
initialValues: { name: '', code: '', description: '' },
validate: {
name: (v) => (!v || v.length < 2 ? 'Введите название раздела' : null),
code: (v) => (!v || v.length < 2 ? 'Технический код должен быть заполнен' : null),
},
})
useEffect(() => {
if (opened) form.reset()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [opened])
useEffect(() => {
form.setFieldValue('code', slugify(form.values.name))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [form.values.name])
const handleSubmit = async (values: typeof form.values) => {
const payload: CreateCategoryRequest = {
name: values.name,
code: values.code,
description: values.description || undefined,
is_active: true,
}
const result = await createCategory.mutateAsync(payload)
// categoriesApi.create возвращает ApprovalTopicCategory без обёртки
// (apiClient.post), axios кладёт его в response.data.
const newId = result?.data?.id
if (newId) onCreated(newId)
onClose()
}
return (
Новый раздел заявок}>
} color="blue" variant="light">
Раздел — это то, что сотрудник увидит в главном меню бота (например, «Отпуска» или
«Возвраты»). Внутри одного раздела вы потом соберёте дерево вопросов.
Отмена
Создать раздел
)
}
-----END src/pages/flowNodes/components/CategoryCreateModal.tsx-----
File: src/pages/flowNodes/components/DataFlowExplainer.tsx
Lines: 462
-----BEGIN src/pages/flowNodes/components/DataFlowExplainer.tsx-----
import {
Paper,
Stack,
Text,
Code,
Box,
Group,
Badge,
Alert,
Divider,
Table,
ThemeIcon,
Collapse,
ActionIcon,
} from '@mantine/core'
import { useState } from 'react'
import {
IconArrowRight,
IconDatabase,
IconCode,
IconMessage,
IconAlertTriangle,
IconCheck,
IconChevronDown,
IconChevronRight, IconBulb,
} from '@tabler/icons-react'
interface DataFlowExplainerProps {
dataKey?: string
dataValue?: string
label?: string
nodeType: 'button' | 'input' | 'multiselect'
}
export default function DataFlowExplainer({
dataKey,
dataValue,
label,
nodeType,
}: DataFlowExplainerProps) {
const [showDetails, setShowDetails] = useState(false)
// Примеры из реальных тем
const examples = [
{
label: 'Крым',
dataKey: 'region',
dataValue: 'crimea',
description: 'Выбор региона',
category: 'region',
},
{
label: 'Ф1',
dataKey: 'branch',
dataValue: 'f1',
description: 'Выбор филиала',
category: 'branch',
},
{
label: 'За свой счёт',
dataKey: 'payment_type',
dataValue: 'own_expense',
description: 'Тип оплаты',
category: 'payment',
},
{
label: 'ТМЦ',
dataKey: 'expense_type',
dataValue: 'tmc',
description: 'Тип расхода',
category: 'expense',
},
{
label: 'На один день',
dataKey: 'duration_type',
dataValue: 'single_day',
description: 'Длительность',
category: 'duration',
},
]
// Определяем, есть ли конфликт с существующими ключами
const isDuplicateKey = examples.some(
(e) => e.dataKey === dataKey && e.dataValue === dataValue
)
return (
{/* Заголовок */}
Что такое DataKey и DataValue?
Краткое объяснение — нажми, чтобы узнать больше
setShowDetails(!showDetails)}
>
{showDetails ? (
) : (
)}
{/* Краткое объяснение (всегда видно) */}
DataKey и DataValue — это пара "ключ-значение", которая
сохраняется в память пользователя, когда он нажимает на этот узел.
Позже эти значения используются для:
}>
Формирования кода темы
}>
Сообщения согласующему
}>
Сохранения в заявке
{/* Интерактивный превью */}
{dataKey && dataValue && (
📊 Что произойдёт, когда пользователь нажмёт "{label || 'этот узел'}":
{/* Поток данных */}
{/* Шаг 1: Нажатие */}
1
Пользователь нажимает "{label || '...'}"
{/* Шаг 2: Сохранение */}
2
В память сохраняется:{' '}
{dataKey} = "{dataValue}"
{/* Шаг 3: Автоматический label */}
3
Автоматически добавляется:{' '}
{dataKey}_label = "{label || '...'}"
{/* Шаг 4: Использование */}
4
Эти значения можно использовать в шаблонах темы:
{`В message_template:
"{{.${dataKey}}}" → "${dataValue}"
"{{.${dataKey}_label}}" → "${label || '...'}"
В code_template:
"{{.${dataKey}}}" → "${dataValue}"`}
)}
{/* Развёрнутое объяснение */}
{/* Зачем это нужно */}
🎯 Зачем это нужно?
Представьте, что пользователь создаёт заявку "Отпуск на один день за свой счёт".
Система должна понять, какую именно тему использовать и как отформатировать
сообщение для согласующего. Для этого она собирает "память" пользователя —
map collected, куда по пути попадают все DataKey/DataValue.
{/* Реальный пример */}
📖 Реальный пример (тема "Отпуск")
Пользователь проходит путь: Отпуск → На один день → За свой счёт → Ввод текста
Шаг
Узел (Label)
DataKey
DataValue
1
Отпуск
absence_type
vacation
2
На один день
duration_type
single_day
3
За свой счёт
payment_type
own_expense
4
Ввод текста
content
(текст пользователя)
Итоговый collected:
{`{
"absence_type": "vacation",
"absence_type_label": "Отпуск", ← автоматически из Label
"duration_type": "single_day",
"duration_type_label": "На один день", ← автоматически
"payment_type": "own_expense",
"payment_type_label": "За свой счёт", ← автоматически
"content": "22.02.2026"
}`}
{/* Как это используется */}
🔧 Как это используется?
1. Формирование кода темы (code_template):
{`Шаблон: vacation_{{.duration_type}}_full_day_{{.payment_type}}
Результат: vacation_single_day_full_day_own_expense
Этот код ищет в БД конкретную тему для заявки.`}
2. Сообщение согласующему (message_template):
{`Шаблон:
📋 Тип: Отпуск
{{.initiator_name}} : прошу согласовать отпуск
{{.content}}
{{.payment_type_label}}
Результат:
📋 Тип: Отпуск
Иванов И.И. : прошу согласовать отпуск
22.02.2026
За свой счёт `}
{/* Правила */}
} color="yellow" variant="light">
⚠️ Правила, которые нужно соблюдать:
1. DataKey должен быть осмысленным. Используйте понятные имена:{' '}
region, branch, payment_type.
Не используйте x, val, data.
2. DataValue должен быть уникальным в рамках одного DataKey. {' '}
Если у вас есть два узла с region=crimea и{' '}
region=krasnodar — это правильно. Но если оба будут{' '}
region=crimea — система не сможет их различить.
3. Используйте snake_case. Только lowercase, цифры и подчёркивания:{' '}
own_expense ✅, OwnExpense ❌,{' '}
own-expense ❌.
4. Один DataKey на одном уровне дерева. Если на одном уровне
несколько кнопок — у всех должен быть одинаковый DataKey, но разные DataValue.
Например, три кнопки "Крым/Краснодар/Беларусь" — все с region,
но с разными значениями.
5. Label — это то, что видит пользователь. DataValue — техническое
значение. Они могут отличаться: Label="За свой счёт", DataValue="own_expense".
{/* Типичные ошибки */}
❌ Типичные ошибки:
Ошибка: Два узла на одном уровне с одинаковыми DataKey и DataValue
Последствие: система не сможет различить, какую ветку выбрал пользователь
Ошибка: Разные DataKey на одном уровне (например, у одной кнопки{' '}
region, у другой area)
Последствие: в collected появятся два разных ключа, что сломает шаблоны
Ошибка: DataValue с пробелами или заглавными буквами
Последствие: код темы будет некорректным, заявка не создастся
Ошибка: Пустой DataKey или DataValue у кнопки
Последствие: данные не сохранятся, шаблон не сможет их использовать
{/* Правильные примеры */}
✅ Правильные примеры из реальных тем:
Label
DataKey
DataValue
Комментарий
{examples.map((ex, i) => (
{ex.label}
{ex.dataKey}
{ex.dataValue}
{ex.description}
))}
{/* Подсказка по текущему узлу */}
{dataKey && dataValue && label && (
}
color={isDuplicateKey ? 'blue' : 'green'}
variant="light"
>
{isDuplicateKey ? (
<>
💡 Ваш узел похож на существующий пример. Убедитесь, что это именно то,
что вам нужно.
>
) : (
<>
✅ Отлично! Ваш узел "{label}" с{' '}
{dataKey}="{dataValue}" выглядит корректно.
В шаблонах можно использовать {`{{.${dataKey}}}`} и{' '}
{`{{.${dataKey}_label}}`}.
>
)}
)}
)
}
-----END src/pages/flowNodes/components/DataFlowExplainer.tsx-----
File: src/pages/flowNodes/components/FlowNodeEditModal.tsx
Lines: 833
-----BEGIN src/pages/flowNodes/components/FlowNodeEditModal.tsx-----
import { useEffect, useMemo, useState } from 'react'
import {
Modal,
Stack,
TextInput,
Textarea,
Group,
Button,
Text,
Badge,
Paper,
Select,
Code,
Alert,
Box,
Collapse,
ActionIcon,
Divider,
Loader,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
IconAlertCircle,
IconAlertTriangle,
IconInfoCircle,
IconChevronDown,
IconChevronRight,
IconWand,
IconEye,
IconCircleCheck,
IconCirclePlus,
IconPlus,
} from '@tabler/icons-react'
import { useCreateFlowNode, useUpdateFlowNode, usePreviewFlow } from '@/features/flowNodes/hooks/useFlowNodes'
import { useCreateTopic } from '@/features/topics/hooks/useTopics'
import { useCategory } from '@/features/categories/hooks/useCategories'
import type { CreateTopicRequest } from '@/api/topics'
import {
collectFromPath,
collectLeafPaths,
generateDraftMessageTemplate,
getPathToNode,
pathLabel,
findMissingKeysInCodeTemplate,
buildMissingKeySegment,
} from '@/features/flowNodes/utils/treeWalk'
import type { ApprovalFlowNode } from '@/types/api'
interface FlowNodeEditModalProps {
categoryId: number
tree: ApprovalFlowNode[]
parentNode: ApprovalFlowNode | null
editNode: ApprovalFlowNode | null
opened: boolean
onClose: () => void
}
const NODE_TYPE_OPTIONS = [
{ value: 'button', label: '🔘 Кнопка — сотрудник нажимает и переходит к следующему вопросу' },
{ value: 'input', label: '📝 Текстовый ввод — сотрудник пишет заявку своими словами (конец пути)' },
{ value: 'multiselect', label: '☑️ Можно выбрать несколько вариантов сразу' },
]
const TRANSLIT_MAP: Record = {
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'yo', ж: 'zh', з: 'z', и: 'i', й: 'y',
к: 'k', л: 'l', м: 'm', н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f',
х: 'h', ц: 'ts', ч: 'ch', ш: 'sh', щ: 'sch', ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
}
function transliterate(text: string): string {
return text.toLowerCase().split('').map((ch) => TRANSLIT_MAP[ch] ?? ch).join('')
}
function slugify(label: string): string {
if (!label?.trim()) return ''
return transliterate(label.trim())
.replace(/[\s-]+/g, '_')
.replace(/[^a-z0-9_]/g, '')
.replace(/_+/g, '_')
.replace(/^_+|_+$/g, '')
.substring(0, 50)
}
// Ключ узла попадает в Telegram callback_data ("appr:{код_раздела}:{ключ}"),
// а у него жёсткий лимит 64 байта на всю строку. Поэтому ключ короче и НЕ
// собирается из цепочки всех родителей (иначе длина растёт с каждым уровнем
// вложенности и легко перешагивает лимит на 4-5 шаге — именно так ломался
// ваш тест: "категория_кнопка1_вложенная1" вышло за 64 байта, Telegram
// отклонил сообщение целиком, а ошибка нигде не показывалась).
const KEY_MAX_LEN = 20
function shortSlug(label: string): string {
return slugify(label).substring(0, KEY_MAX_LEN)
}
// Уникальный короткий ключ в пределах категории: если базовый слаг уже
// занят (например, два узла с одинаковым названием "Вложенная 1" на разных
// ветках — это нормально и допустимо), добавляем числовой суффикс.
function uniqueShortKey(label: string, existingKeys: string[], skipKey?: string): string {
const base = shortSlug(label) || 'shag'
if (!existingKeys.includes(base) || base === skipKey) return base
let n = 2
while (existingKeys.includes(`${base}_${n}`) && `${base}_${n}` !== skipKey) {
n++
}
return `${base}_${n}`
}
function collectAllKeys(nodes: ApprovalFlowNode[]): string[] {
const keys: string[] = []
for (const node of nodes) {
if (node.key) keys.push(node.key)
if (node.children) keys.push(...collectAllKeys(node.children))
}
return keys
}
export default function FlowNodeEditModal({
categoryId,
tree,
parentNode,
editNode,
opened,
onClose,
}: FlowNodeEditModalProps) {
const createFlowNode = useCreateFlowNode()
const updateFlowNode = useUpdateFlowNode()
const createTopic = useCreateTopic()
const previewFlow = usePreviewFlow(categoryId)
const { data: category } = useCategory(categoryId)
const [showAdvanced, setShowAdvanced] = useState(false)
const [showTemplates, setShowTemplates] = useState(false)
const [previewLeafKey, setPreviewLeafKey] = useState(null)
const isEditMode = editNode !== null
// Корень дерева категории — узел без родителя. Только на нём имеют
// смысл шаблоны сообщения/кода: DynamicTopic на бэкенде читает их
// ИСКЛЮЧИТЕЛЬНО с узла с parent_id = null (см. approvalflow.NewDynamicTopic).
const isRootNode = parentNode === null
const form = useForm({
initialValues: {
key: '',
label: '',
nodeType: 'button' as 'button' | 'input' | 'multiselect',
data_key: '',
data_value: '',
input_key: 'content',
input_hint: '',
multi_select_key: '',
multi_select_value: '',
topic_code: '',
message_template: '',
code_template: '',
auto_generate_key: true,
},
validate: {
key: (v) => {
if (!v || v.length < 2) return 'Слишком короткий технический ключ'
if (!/^[a-z0-9_]+$/.test(v)) return 'Только латинские буквы, цифры и подчёркивания'
if (isRootNode && category?.code && v !== category.code) {
return 'Подождите загрузку раздела — ключ первого шага подставится сам'
}
// "appr:" + код раздела + ":" + ключ уходит в Telegram callback_data,
// у которого жёсткий лимит 64 байта. 60 вместо 64 — небольшой запас.
const categoryCodeLen = category?.code?.length || 0
const callbackLen = 'appr:'.length + categoryCodeLen + 1 + v.length
if (callbackLen > 60) {
return `Ключ слишком длинный для Telegram (осталось ${60 - 'appr:'.length - categoryCodeLen - 1} символов) — сократите название`
}
const existingKeys = collectAllKeys(tree)
if (existingKeys.includes(v) && (!editNode || editNode.key !== v)) {
return 'Такой ключ уже есть в этой категории — измените название'
}
return null
},
label: (v, values) => {
// У узла "текстовый ввод" название нигде не показывается
// сотруднику — бот выводит InputHint, а не Label. Название
// тут чисто для вашего удобства в конструкторе, необязательно.
if (values.nodeType === 'input') return null
return !v || v.length < 1 ? 'Название обязательно' : null
},
data_key: (v, values) => {
// Раньше это была декоративная проверка, которая ничего не
// блокировала (только жёлтое предупреждение) — из-за этого
// можно было сохранить кнопку без "что запомнить", и тогда
// РАЗНЫЕ кнопки на бэкенде дают ОДИНАКОВЫЙ код темы (бот не
// видит разницы между ними). Теперь это жёсткая проверка.
if (values.nodeType === 'button' && !v) {
return 'Обязательно для кнопки — иначе бот не отличит эту кнопку от других, и разные пути могут привести к одной и той же теме'
}
return null
},
data_value: (v, values) => {
if (values.nodeType === 'button' && !v) {
return 'Обязательно для кнопки — у каждой кнопки должно быть своё значение'
}
return null
},
multi_select_key: (v, values) =>
values.nodeType === 'multiselect' && !v
? 'Обязательно для мультивыбора — иначе бот не запомнит выбранные варианты'
: null,
multi_select_value: (v, values) =>
values.nodeType === 'multiselect' && !v
? 'Обязательно для мультивыбора — у каждого варианта должно быть своё значение'
: null,
input_hint: (v, values) =>
values.nodeType === 'input' && (!v || v.length < 5) ? 'Подсказка должна быть не короче 5 символов' : null,
},
})
// Ближайшие "братья" (уже существующие соседние кнопки того же родителя) —
// используем, чтобы подсказать DataKey автоматически: у всех кнопок
// одного вопроса DataKey обязан совпадать.
const siblingDataKey = useMemo(() => {
const siblings = parentNode?.children || (parentNode === null ? [] : [])
const withKey = siblings.find((s) => s.data_key)
return withKey?.data_key || ''
}, [parentNode])
const siblingMultiKey = useMemo(() => {
const siblings = parentNode?.children || []
const withKey = siblings.find((s) => s.multi_select_key)
return withKey?.multi_select_key || ''
}, [parentNode])
// Автогенерация ключа из названия — КРОМЕ корневого узла: его ключ
// ОБЯЗАН совпадать с кодом категории. Причина: когда сотрудник нажимает
// кнопку раздела в главном меню бота, бот ищет самый первый узел дерева
// по nodeKey == код категории (см. HandleCallback в telegram_service) —
// у Topic просто нет отдельного способа узнать реальный ключ корня.
// Если ключ корня не совпадёт с кодом раздела — бот не найдёт начало
// дерева и покажет "node not found" в логах, а сотрудник не увидит
// следующий шаг после нажатия кнопки раздела.
useEffect(() => {
if (isRootNode) {
if (category?.code && form.values.key !== category.code) {
form.setFieldValue('key', category.code)
}
return
}
if (form.values.auto_generate_key) {
// Для текстового ввода название необязательно — если его нет,
// используем понятный технический суффикс вместо пустого ключа.
const baseLabel = form.values.label || (form.values.nodeType === 'input' ? 'Текст' : '')
if (baseLabel) {
const existingKeys = collectAllKeys(tree)
const key = uniqueShortKey(baseLabel, existingKeys, editNode?.key)
if (key !== form.values.key) {
form.setFieldValue('key', key)
}
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [form.values.label, form.values.nodeType, form.values.auto_generate_key, isRootNode, category?.code, tree, editNode])
// Автоподстановка DataKey/DataValue при смене типа/названия
useEffect(() => {
if (form.values.nodeType === 'button') {
if (!form.values.data_key) form.setFieldValue('data_key', siblingDataKey || '')
if (!form.values.data_value) form.setFieldValue('data_value', slugify(form.values.label))
} else if (form.values.nodeType === 'multiselect') {
if (!form.values.multi_select_key) form.setFieldValue('multi_select_key', siblingMultiKey || '')
if (!form.values.multi_select_value) form.setFieldValue('multi_select_value', slugify(form.values.label))
} else if (form.values.nodeType === 'input') {
if (!form.values.input_key) form.setFieldValue('input_key', 'content')
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [form.values.nodeType, form.values.label, siblingDataKey, siblingMultiKey])
// Заполнение формы при редактировании / сброс при создании
useEffect(() => {
if (editNode) {
let nodeType: 'button' | 'input' | 'multiselect' = 'button'
if (editNode.is_input) nodeType = 'input'
else if (editNode.is_multi_select) nodeType = 'multiselect'
form.setValues({
key: editNode.key || '',
label: editNode.label || '',
nodeType,
data_key: editNode.data_key || '',
data_value: editNode.data_value || '',
input_key: editNode.input_key || 'content',
input_hint: editNode.input_hint || '',
multi_select_key: editNode.multi_select_key || '',
multi_select_value: editNode.multi_select_value || '',
topic_code: editNode.topic_code || '',
message_template: editNode.message_template || '',
code_template: editNode.code_template || '',
auto_generate_key: false,
})
setShowTemplates(!!(editNode.message_template || editNode.code_template))
setShowAdvanced(!!editNode.topic_code)
} else {
form.reset()
const baseKey = parentNode?.key || ''
form.setValues({
key: baseKey ? `${baseKey}_new` : 'new_node',
label: '',
nodeType: 'button',
data_key: '',
data_value: '',
input_key: 'content',
input_hint: '',
multi_select_key: '',
multi_select_value: '',
topic_code: '',
message_template: '',
code_template: '',
auto_generate_key: true,
})
setShowTemplates(false)
setShowAdvanced(false)
}
previewFlow.reset()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editNode, parentNode, opened])
const handleSubmit = async (values: typeof form.values) => {
const payload = {
key: values.key,
// label в БД NOT NULL — если оставили пустым (разрешено только
// для текстового ввода), подставляем нейтральное значение.
label: values.label || (values.nodeType === 'input' ? 'Текст' : values.label),
data_key: values.data_key || null,
data_value: values.data_value || null,
is_input: values.nodeType === 'input',
input_key: values.nodeType === 'input' ? values.input_key : null,
input_hint: values.nodeType === 'input' ? values.input_hint : null,
is_multi_select: values.nodeType === 'multiselect',
multi_select_key: values.nodeType === 'multiselect' ? values.multi_select_key : null,
multi_select_value: values.nodeType === 'multiselect' ? values.multi_select_value : null,
topic_code: values.topic_code || null,
message_template: isRootNode ? values.message_template || null : null,
code_template: isRootNode ? values.code_template || null : null,
}
if (isEditMode && editNode?.id) {
await updateFlowNode.mutateAsync({ id: editNode.id, ...payload })
} else {
await createFlowNode.mutateAsync({
category_id: categoryId,
parent_id: parentNode?.id || null,
...payload,
})
}
onClose()
}
const isSubmitting = createFlowNode.isPending || updateFlowNode.isPending
const nodeType = form.values.nodeType
const warnings = useMemo(() => {
const warns: string[] = []
if (nodeType === 'button' && !form.values.data_key) {
warns.push('У кнопки нет «что запомнить» — без этого бот не поймёт, что выбрал сотрudnik. Заполните поля ниже.')
}
if (nodeType === 'multiselect' && !form.values.multi_select_key) {
warns.push('Не заполнено, что запоминать при мультивыборе.')
}
return warns
}, [nodeType, form.values.data_key, form.values.multi_select_key])
// ============================================================
// Черновик пути для предпросмотра (виртуальный узел = текущие
// значения формы, ещё не сохранённые)
// ============================================================
const pathToParent = useMemo(() => {
if (!parentNode?.id) return []
return getPathToNode(tree, parentNode.id)
}, [tree, parentNode])
const virtualNode: ApprovalFlowNode = {
...(editNode || {}),
data_key: form.values.data_key || undefined,
data_value: form.values.data_value || undefined,
multi_select_key: form.values.multi_select_key || undefined,
multi_select_value: form.values.multi_select_value || undefined,
is_input: nodeType === 'input',
} as ApprovalFlowNode
const currentPathCollected = useMemo(
() => collectFromPath([...pathToParent, virtualNode]),
// eslint-disable-next-line react-hooks/exhaustive-deps
[pathToParent, form.values.data_key, form.values.data_value, form.values.multi_select_key, form.values.multi_select_value, nodeType]
)
const handleCheckThisStep = () => {
previewFlow.mutate({ collected: currentPathCollected })
}
const handleCreateTopicFromPreview = async () => {
if (!previewFlow.data?.code) return
// Намеренно НЕ передаём message_template/code_template/is_tree_root на
// самой теме: боевой код (approvalflow.DynamicTopic) читает шаблоны
// только с корневого узла дерева, а не с ApprovalTopic — см. FlowNodeEditModal
// раздел "Сообщение согласующему" (isRootNode). Заполнение этих полей
// здесь ничего бы не включило и только запутало бы админа.
const payload: CreateTopicRequest = {
category_id: categoryId,
code: previewFlow.data.code,
name: form.values.label || previewFlow.data.code,
is_active: true,
}
await createTopic.mutateAsync(payload)
previewFlow.mutate({ collected: currentPathCollected })
}
// ============================================================
// Для корневого узла: список готовых веток дерева для предпросмотра
// ============================================================
const leafOptions = useMemo(() => {
if (!isRootNode) return []
return collectLeafPaths(tree).map((path) => ({
value: path.map((n) => n.id).join('-'),
label: pathLabel(path),
collected: collectFromPath(path),
}))
}, [isRootNode, tree])
// НОВОЕ: автообнаружение "в дереве есть данные, которых нет в шаблоне
// кода" — то, что раньше приходилось замечать самому и чинить руками
// (см. случай с filiale Ф1/Ф2, которые не попадали в код темы).
const missingCodeKeys = useMemo(() => {
if (!isRootNode || !editNode) return []
return findMissingKeysInCodeTemplate(editNode, form.values.code_template)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isRootNode, editNode, form.values.code_template])
const handleAddMissingKey = (key: string) => {
form.setFieldValue('code_template', (form.values.code_template || '') + buildMissingKeySegment(key))
}
const handleAddAllMissingKeys = () => {
const addition = missingCodeKeys.map(buildMissingKeySegment).join('')
form.setFieldValue('code_template', (form.values.code_template || '') + addition)
}
const handleGenerateDraft = () => {
if (!editNode && !parentNode) return
const rootForDraft = editNode || { label: form.values.label, children: [] }
form.setFieldValue('message_template', generateDraftMessageTemplate(rootForDraft as ApprovalFlowNode))
}
const handlePreviewLeaf = (leafKey: string | null) => {
setPreviewLeafKey(leafKey)
const option = leafOptions.find((o) => o.value === leafKey)
if (option) {
previewFlow.mutate({ collected: option.collected })
}
}
return (
{isEditMode ? 'Изменить шаг' : 'Новый шаг'}
{parentNode && (
после: {parentNode.label}
)}
}
size="lg"
>
{warnings.length > 0 && (
} color="yellow" variant="light">
{warnings.map((w, i) => (
⚠️ {w}
))}
)}
1. Тип шага
form.setFieldValue('nodeType', (v as any) || 'button')}
/>
{nodeType === 'input' ? '2. Название шага (для вас, необязательно)' : '2. Что увидит сотрудник'}
{isRootNode && (
} color="blue" variant="light">
Это первый шаг дерева — по нему бот находит начало сценария, когда
сотрудник нажимает кнопку раздела в главном меню. Технический ключ этого
шага всегда равен коду раздела:{' '}
{category?.code || '…'} — менять его нельзя, это сделано
автоматически.
)}
{(nodeType === 'button' || nodeType === 'multiselect') && (
3. Что запомнить при нажатии
} color="blue" variant="light" mb="sm">
Если у этого вопроса уже есть другие варианты ответа — поле «что запомнить» уже
подставлено само (оно должно быть одинаковым у всех кнопок одного вопроса).
Меняйте только «значение» — оно у каждой кнопки своё.
«Название» этой кнопки (из блока выше) — это то, что покажется согласующему
в сообщении, если в шаблоне используется {`{{.${form.values.data_key || 'ключ'}_label}}`}.
Переименуете кнопку — текст сообщения обновится сам, без правки шаблона.
{nodeType === 'button' ? (
) : (
)}
)}
{nodeType === 'input' && (
3. Подсказка для сотрудника
)}
{/* Живой предпросмотр этого конкретного шага — только там, где уже
можно посчитать код (обычно на текстовом вводе, но доступно и раньше) */}
Проверка: что получится на этом пути
}
onClick={handleCheckThisStep}
loading={previewFlow.isPending}
>
Проверить
{previewFlow.data && (
{previewFlow.data.incomplete ? (
Пока не хватает выборов на предыдущих шагах, чтобы определить тему заявки —
это нормально, если вы ещё не дошли до конца ветки.
) : (
<>
Код темы: {previewFlow.data.code}
{previewFlow.data.topic_exists ? (
Такая тема уже настроена в системе ({previewFlow.data.topic_name})
) : (
⚠️ Темы с таким кодом пока нет — без неё бот не сможет отправить
заявку согласующим.
}
onClick={handleCreateTopicFromPreview}
loading={createTopic.isPending}
>
Создать тему
)}
Так будет выглядеть сообщение согласующему:
{previewFlow.data.message}
>
)}
)}
{/* Дополнительно: технический ключ + код проверки прав */}
setShowAdvanced(!showAdvanced)}
>
{showAdvanced ? : }
Дополнительно (обычно не нужно трогать)
Если заполнить — эту конкретную кнопку увидят только сотрудники, у
которых есть право на такую тему. Не влияет на то, в какую тему попадёт
заявка — код темы считается автоматически по всем ответам сотрудника.
}
{...form.getInputProps('topic_code')}
/>
{nodeType === 'input' && (
)}
{/* Шаблоны — ТОЛЬКО на корневом узле дерева */}
{isRootNode && (
setShowTemplates(!showTemplates)}
>
{showTemplates ? : }
Сообщение согласующему и код темы
} color="blue" variant="light">
Это ОДНО сообщение на всё дерево этого раздела, а не на одну ветку.
Чтобы текст отличался в зависимости от выбора сотрудника — используйте
условия (кнопка ниже сама расставит их за вас на основе первого вопроса
в дереве, дальше можно поправить руками).
}
onClick={handleGenerateDraft}
>
Сформировать черновик
{missingCodeKeys.length > 0 && (
} color="orange" variant="light">
В дереве есть шаги, запоминающие данные, которых нет в шаблоне
кода выше — темы для таких веток могут случайно совпасть с
другими (бот их не различит):
{missingCodeKeys.map((key) => (
}
onClick={() => handleAddMissingKey(key)}
>
{key}
))}
{missingCodeKeys.length > 1 && (
Добавить все в шаблон
)}
)}
{leafOptions.length > 0 && (
<>
({ value: o.value, label: o.label }))}
value={previewLeafKey}
onChange={handlePreviewLeaf}
searchable
/>
{previewFlow.isPending && }
{previewFlow.data && !previewFlow.data.incomplete && (
Код: {previewFlow.data.code}
{previewFlow.data.message}
)}
>
)}
)}
Отмена
{isEditMode ? 'Сохранить' : 'Создать'}
)
}
-----END src/pages/flowNodes/components/FlowNodeEditModal.tsx-----
File: src/pages/flowNodes/components/SortableFlowTree.tsx
Lines: 268
-----BEGIN src/pages/flowNodes/components/SortableFlowTree.tsx-----
import { useMemo, useState } from 'react'
import {
DndContext,
DragOverlay,
PointerSensor,
useSensor,
useSensors,
closestCenter,
type DragStartEvent,
type DragMoveEvent,
type DragOverEvent,
type DragEndEvent,
} from '@dnd-kit/core'
import { SortableContext, verticalListSortingStrategy, useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { Paper, Group, Text, ActionIcon, Tooltip, Badge, Box, Alert } from '@mantine/core'
import {
IconGripVertical,
IconPlus,
IconEdit,
IconTrash,
IconCopy,
IconChevronDown,
IconChevronRight,
IconArrowsMove,
} from '@tabler/icons-react'
import type { ApprovalFlowNode } from '@/types/api'
import { useReorderNodes } from '@/features/flowNodes/hooks/useFlowNodes'
import {buildReorderPlan, FlatFlowNode, flattenTree, getProjection} from "@/features/flowNodes/utils/flattenTree.ts";
const INDENTATION = 24
interface SortableFlowTreeProps {
tree: ApprovalFlowNode[]
onEdit: (node: ApprovalFlowNode) => void
onAddChild: (parent: ApprovalFlowNode) => void
onDelete: (node: ApprovalFlowNode) => void
onDuplicate: (node: ApprovalFlowNode) => void
}
function nodeIcon(node: ApprovalFlowNode): string {
if (node.is_input) return '📝'
if (node.is_multi_select) return '☑️'
return '🔘'
}
function nodeKindLabel(node: ApprovalFlowNode): string {
if (node.is_input) return 'Текстовый ввод — здесь сотрудник пишет заявку'
if (node.is_multi_select) return 'Можно выбрать несколько вариантов'
return 'Кнопка'
}
export default function SortableFlowTree({ tree, onEdit, onAddChild, onDelete, onDuplicate }: SortableFlowTreeProps) {
const [collapsed, setCollapsed] = useState>(new Set())
const [activeId, setActiveId] = useState(null)
const [overId, setOverId] = useState(null)
const [offsetX, setOffsetX] = useState(0)
const reorder = useReorderNodes()
const flatItems = useMemo(() => flattenTree(tree, collapsed), [tree, collapsed])
const sortableIds = useMemo(() => flatItems.map((n) => n.id!), [flatItems])
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))
const projected = useMemo(() => {
if (activeId == null || overId == null) return null
return getProjection(flatItems, activeId, overId, offsetX, INDENTATION)
}, [flatItems, activeId, overId, offsetX])
const activeNode = flatItems.find((n) => n.id === activeId) || null
const projectedParentLabel = projected
? flatItems.find((n) => n.id === projected.parentId)?.label || null
: null
const toggleCollapse = (id: number) => {
setCollapsed((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
const handleDragStart = (event: DragStartEvent) => {
setActiveId(event.active.id as number)
setOverId(event.active.id as number)
setOffsetX(0)
}
const handleDragMove = (event: DragMoveEvent) => {
setOffsetX(event.delta.x)
}
const handleDragOver = (event: DragOverEvent) => {
setOverId((event.over?.id as number) ?? null)
}
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event
const currentProjected = projected
setActiveId(null)
setOverId(null)
setOffsetX(0)
if (!over || !currentProjected) return
const activeIdNum = active.id as number
const overIdNum = over.id as number
const activeNodeBefore = flatItems.find((n) => n.id === activeIdNum)
if (!activeNodeBefore) return
const noParentChange = (activeNodeBefore.parent_id ?? null) === currentProjected.parentId
const droppedOnSelf = activeIdNum === overIdNum
if (noParentChange && droppedOnSelf) return
const ops = buildReorderPlan(tree, activeIdNum, currentProjected.parentId, overIdNum)
if (ops.length > 0) {
reorder.mutate(ops)
}
}
return (
{activeNode && (
}>
«{activeNode.label}» станет шагом внутри «{projectedParentLabel || '…'}» — потяните влево/вправо,
чтобы поменять уровень вложенности
)}
{flatItems.map((node) => (
node.id != null && toggleCollapse(node.id)}
onEdit={onEdit}
onAddChild={onAddChild}
onDelete={onDelete}
onDuplicate={onDuplicate}
/>
))}
{activeNode ? (
{nodeIcon(activeNode)}
{activeNode.label}
) : null}
)
}
interface SortableRowProps {
node: FlatFlowNode
hasChildren: boolean
collapsed: boolean
onToggleCollapse: () => void
onEdit: (node: ApprovalFlowNode) => void
onAddChild: (parent: ApprovalFlowNode) => void
onDelete: (node: ApprovalFlowNode) => void
onDuplicate: (node: ApprovalFlowNode) => void
}
function SortableRow({ node, hasChildren, collapsed, onToggleCollapse, onEdit, onAddChild, onDelete, onDuplicate }: SortableRowProps) {
const isRoot = node.depth === 0
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: node.id!,
disabled: isRoot, // корень дерева не перетаскивается — его ключ жёстко привязан к коду раздела
})
const style = {
transform: CSS.Translate.toString(transform),
transition,
marginLeft: node.depth * INDENTATION,
opacity: isDragging ? 0.4 : 1,
}
return (
{!isRoot ? (
) : (
)}
{hasChildren ? (
{collapsed ? : }
) : (
)}
{nodeIcon(node)}
{node.label}
{isRoot && (
начало дерева
)}
{nodeKindLabel(node)}
{node.data_key ? ` · запоминает: ${node.data_key} = ${node.data_value}` : ''}
onAddChild(node)}>
onEdit(node)}>
onDuplicate(node)}>
onDelete(node)}>
)
}
-----END src/pages/flowNodes/components/SortableFlowTree.tsx-----
File: src/pages/flowNodes/components/TreeHealthPanel.tsx
Lines: 151
-----BEGIN src/pages/flowNodes/components/TreeHealthPanel.tsx-----
import { useState } from 'react'
import { Paper, Group, Text, Button, Table, Badge, Loader, Alert } from '@mantine/core'
import { IconStethoscope, IconInfoCircle, IconCirclePlus } from '@tabler/icons-react'
import { flowNodesApi, type PreviewFlowResponse } from '@/api/flowNodes'
import { useCreateTopic } from '@/features/topics/hooks/useTopics'
import type { CreateTopicRequest } from '@/api/topics'
import { collectFromPath, collectLeafPaths, pathLabel } from '@/features/flowNodes/utils/treeWalk'
import type { ApprovalFlowNode } from '@/types/api'
interface TreeHealthPanelProps {
categoryId: number
tree: ApprovalFlowNode[]
}
interface HealthRow {
key: string
label: string
result: PreviewFlowResponse | null
error?: boolean
}
// Проходит по каждой готовой ветке дерева ("от начала до текстового ввода")
// и проверяет через реальный движок бэкенда, есть ли для неё настроенная
// тема. Так администратор видит проблему ДО того, как сотрудник наткнётся
// на неё в боте — а не после жалобы, что "заявка не отправляется".
export default function TreeHealthPanel({ categoryId, tree }: TreeHealthPanelProps) {
const [rows, setRows] = useState(null)
const [checking, setChecking] = useState(false)
const createTopic = useCreateTopic()
const runCheck = async () => {
setChecking(true)
const leafPaths = collectLeafPaths(tree)
const results = await Promise.all(
leafPaths.map(async (path) => {
const key = path.map((n) => n.id).join('-')
const label = pathLabel(path)
try {
const response = await flowNodesApi.preview(categoryId, {
collected: collectFromPath(path),
})
return { key, label, result: response.data } as HealthRow
} catch {
return { key, label, result: null, error: true } as HealthRow
}
})
)
setRows(results)
setChecking(false)
}
const handleCreateTopic = async (row: HealthRow) => {
if (!row.result?.code) return
const payload: CreateTopicRequest = {
category_id: categoryId,
code: row.result.code,
name: row.label,
is_active: true,
}
await createTopic.mutateAsync(payload)
runCheck()
}
const missingCount = rows?.filter((r) => r.result && !r.result.incomplete && !r.result.topic_exists).length || 0
return (
Проверка дерева
}
onClick={runCheck}
loading={checking}
>
Проверить все ветки
} color="blue" variant="light" mb="sm">
Пройдёт по каждому возможному пути в дереве и проверит, для всех ли есть настроенная тема
заявки. Если для какого-то пути темы нет — заявку по нему бот не сможет отправить.
{rows && missingCount > 0 && (
Не хватает тем для {missingCount} путей — см. таблицу ниже.
)}
{rows && missingCount === 0 && (
Все ветки дерева ведут к настроенным темам ✅
)}
{checking && }
{rows && (
Путь
Код темы
Статус
{rows.map((row) => (
{row.label}
{row.result?.code || '—'}
{row.error ? (
Ошибка проверки
) : row.result?.incomplete ? (
Путь не завершён
) : row.result?.topic_exists ? (
Есть тема
) : (
Темы нет
)}
{row.result && !row.result.incomplete && !row.result.topic_exists && (
}
onClick={() => handleCreateTopic(row)}
loading={createTopic.isPending}
>
Создать
)}
))}
)}
)
}
-----END src/pages/flowNodes/components/TreeHealthPanel.tsx-----
File: src/pages/hierarchies/HierarchiesPage.tsx
Lines: 631
-----BEGIN src/pages/hierarchies/HierarchiesPage.tsx-----
import { useState, useMemo } from 'react'
import {
Paper,
Table,
Group,
ActionIcon,
Button,
Text,
Select,
Loader,
Center,
Tooltip,
Box,
Stack,
SegmentedControl,
Badge,
Alert,
ScrollArea,
Pagination,
Checkbox,
} from '@mantine/core'
import {
IconPencil,
IconTrash,
IconPlus,
IconInfoCircle,
IconUsers,
} from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { notifications } from '@mantine/notifications'
import {
useHierarchies,
useDeleteHierarchy,
useUpdateHierarchy, HIERARCHIES_QUERY_KEY,
} from '@/features/hierarchies/hooks/useHierarchies'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
import {
groupHierarchiesIntoChains,
SCOPE_COLORS,
SCOPE_LABELS,
type ChainGroup,
} from '@/features/hierarchies/utils'
import ChainVisualization from './components/ChainVisualization'
import ChainDuplicateModal from './components/ChainDuplicateModal'
import HierarchyEditModal from './components/HierarchyEditModal'
import PersonDuplicateModal from './components/PersonDuplicateModal'
import type { UserHierarchy } from '@/types/api'
import { hierarchiesApi } from '@/api/hierarchies'
import { useQueryClient } from '@tanstack/react-query'
const LIMIT = 20
type ViewMode = 'chains' | 'table'
export default function HierarchiesPage() {
const [viewMode, setViewMode] = useState('chains')
const [page, setPage] = useState(1)
// Фильтры
const [subordinateFilter, setSubordinateFilter] = useState(null)
const [departmentFilter, setDepartmentFilter] = useState(null)
const [categoryFilter, setCategoryFilter] = useState(null)
const [topicFilter, setTopicFilter] = useState(null)
// Массовое удаление
const [selectedIds, setSelectedIds] = useState([])
const [isDeleting, setIsDeleting] = useState(false)
// Модалки
const [editHierarchy, setEditHierarchy] = useState(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const [presetGroup, setPresetGroup] = useState(null)
const [duplicateGroup, setDuplicateGroup] = useState(null)
const [duplicateModalOpened, setDuplicateModalOpened] = useState(false)
const [personDuplicateOpened, setPersonDuplicateOpened] = useState(false)
const { data: categoryTopics } = useTopics({
limit: 1000,
...(categoryFilter && { category_id: Number(categoryFilter) }),
})
const { data, isLoading, isFetching } = useHierarchies({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(subordinateFilter && { subordinate_id: Number(subordinateFilter) }),
...(departmentFilter && { department_id: Number(departmentFilter) }),
...(categoryFilter && { topic_category_id: Number(categoryFilter) }),
...(topicFilter && { topic_id: Number(topicFilter) }),
})
const { data: users } = useUsers({ limit: 1000 })
const { data: departments } = useDepartments()
const { data: categories } = useCategories({ limit: 1000 })
const { data: topics } = useTopics({ limit: 1000 })
const deleteHierarchy = useDeleteHierarchy()
const updateHierarchy = useUpdateHierarchy()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const chains = useMemo(() => {
if (!data?.data) return []
return groupHierarchiesIntoChains(data.data)
}, [data])
const enrichedChains = useMemo(() => {
return chains.map((chain) => {
let scopeObjectName = 'Все темы'
if (chain.scopeType === 'category' && chain.scopeObjectId) {
const cat = categories?.data?.find((c) => c.id === chain.scopeObjectId)
scopeObjectName = cat?.name || `Категория #${chain.scopeObjectId}`
} else if (chain.scopeType === 'topic' && chain.scopeObjectId) {
const topic = topics?.data?.find((t) => t.id === chain.scopeObjectId)
scopeObjectName = topic?.name || `Тема #${chain.scopeObjectId}`
}
return { ...chain, scopeObjectName }
})
}, [chains, categories, topics])
const userOptions =
users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const departmentOptions =
departments?.data?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || []
const categoryOptions =
categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions =
(categoryFilter ? categoryTopics?.data : topics?.data)?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const handleSelectAll = () => {
if (selectedIds.length === data?.data?.length) {
setSelectedIds([])
} else {
setSelectedIds(data?.data?.map((h) => h.id!) || [])
}
}
const handleSelectOne = (id: number) => {
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
)
}
const handleFilterChange =
(setter: (value: string | null) => void) => (value: string | null) => {
setter(value)
setPage(1)
setSelectedIds([])
}
const queryClient = useQueryClient()
const handleBulkDelete = () => {
modals.openConfirmModal({
title: 'Подтвердите массовое удаление',
children: (
Вы уверены, что хотите удалить {selectedIds.length} {' '}
записей? Это действие необратимо.
),
labels: { confirm: 'Удалить все', cancel: 'Отмена' },
confirmProps: { color: 'red', loading: isDeleting },
onConfirm: async () => {
setIsDeleting(true)
try {
// Удаляем напрямую через API, не вызывая мутацию поштучно
await Promise.all(selectedIds.map((id) => hierarchiesApi.delete(id)))
// Обновляем список один раз
queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] })
notifications.show({
title: 'Успешно',
message: `Успешно удалено записей: ${selectedIds.length}`,
color: 'green',
})
setSelectedIds([])
} catch (error) {
notifications.show({
title: 'Ошибка',
message: 'Не удалось удалить некоторые записи',
color: 'red',
})
} finally {
setIsDeleting(false)
}
},
})
}
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
Вы уверены, что хотите удалить эту связь?
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: async () => {
await deleteHierarchy.mutateAsync(id)
},
})
}
const handleEditStep = (id: number) => {
const hierarchy = data?.data?.find((h) => h.id === id)
if (hierarchy) {
setEditHierarchy(hierarchy)
}
}
const handleAddStep = (group: ChainGroup) => {
setPresetGroup(group)
setCreateModalOpened(true)
}
const handleDuplicateChain = (group: ChainGroup) => {
setDuplicateGroup(group)
setDuplicateModalOpened(true)
}
const handleCloseModal = () => {
setEditHierarchy(null)
setCreateModalOpened(false)
setPresetGroup(null)
}
const handleCloseDuplicateModal = () => {
setDuplicateGroup(null)
setDuplicateModalOpened(false)
}
const isAllSelected =
(data?.data?.length ?? 0) > 0 && selectedIds.length === (data?.data?.length ?? 0)
const isIndeterminate =
selectedIds.length > 0 && selectedIds.length < (data?.data?.length || 0)
const handleBulkUpdateSystem = async (group: ChainGroup, targetSystem: string | null) => {
try {
// Обновляем все шаги в выбранной цепочке асинхронно
await Promise.all(
group.steps.map((step) =>
updateHierarchy.mutateAsync({
id: step.id!,
subordinate_id: step.subordinate_id,
approver_id: step.approver_id,
department_id: step.department_id,
topic_category_id: step.topic_category_id,
topic_id: step.topic_id,
priority: step.priority,
target_system: targetSystem, // Применяем новую систему
})
)
)
} catch (error) {
console.error("Ошибка при массовом обновлении систем цепочки", error)
}
}
return (
{/* Заголовок */}
Иерархия согласований
Всего: {data?.total_count || 0}
{
setViewMode(v as ViewMode)
setSelectedIds([])
}}
data={[
{ value: 'chains', label: 'Цепочки' },
{ value: 'table', label: 'Таблица' },
]}
/>
}
onClick={() => setPersonDuplicateOpened(true)}
>
Дублировать по сотруднику
}
onClick={() => {
setPresetGroup(null)
setCreateModalOpened(true)
}}
>
Добавить связь
} color="blue" variant="light">
Иерархия определяет порядок согласования заявок. Каждая цепочка показывает,
через каких согласующих проходит заявка от конкретного сотрудника.
{/* Фильтры */}
{
handleFilterChange(setCategoryFilter)(v)
setTopicFilter(null)
}}
clearable
searchable
style={{ flex: 1, minWidth: 200 }}
/>
{/* Контент */}
{isLoading ? (
) : viewMode === 'chains' ? (
{enrichedChains.length === 0 ? (
Связи не найдены
) : (
enrichedChains.map((chain) => (
))
)}
) : (
<>
{selectedIds.length > 0 && (
Выбрано записей: {selectedIds.length}
setSelectedIds([])}
>
Снять выделение
}
onClick={handleBulkDelete}
loading={isDeleting}
>
Удалить выбранные
)}
ID
Подчинённый
Согласующий
Отдел
Область
Объект
Порядок
Действия
{data?.data?.length === 0 ? (
Связи не найдены
) : (
data?.data?.map((h) => {
const scopeType = h.topic_id
? 'topic'
: h.topic_category_id
? 'category'
: 'global'
let scopeObjectName = 'Все темы'
if (scopeType === 'category' && h.topic_category_id) {
const cat = categories?.data?.find(
(c) => c.id === h.topic_category_id
)
scopeObjectName = cat?.name || `#${h.topic_category_id}`
} else if (scopeType === 'topic' && h.topic_id) {
const topic = topics?.data?.find(
(t) => t.id === h.topic_id
)
scopeObjectName = topic?.name || `#${h.topic_id}`
}
return (
handleSelectOne(h.id!)}
/>
{h.id}
{h.subordinate?.full_name || '—'}
{h.approver?.full_name || '—'}
{h.department?.name || '—'}
{
SCOPE_LABELS[
scopeType as keyof typeof SCOPE_LABELS
]
}
{scopeObjectName}
#{h.priority}
setEditHierarchy(h)}
>
handleDelete(h.id!)}
>
)
})
)}
>
)}
{totalPages > 1 && (
Страница {page} из {totalPages}
{
setPage(newPage)
setSelectedIds([])
}}
total={totalPages}
withEdges
/>
)}
{isFetching && !isLoading && (
)}
{/* Модалки */}
setPersonDuplicateOpened(false)}
/>
)
}
-----END src/pages/hierarchies/HierarchiesPage.tsx-----
File: src/pages/hierarchies/components/ChainDuplicateModal.tsx
Lines: 526
-----BEGIN src/pages/hierarchies/components/ChainDuplicateModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
Select,
Group,
Button,
Text,
Paper,
Divider,
ActionIcon,
Badge,
Avatar,
Box,
Radio,
Alert,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
IconInfoCircle,
IconPlus,
IconTrash,
IconCopy,
IconChevronRight,
} from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import { useCreateHierarchy } from '@/features/hierarchies/hooks/useHierarchies'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
import { useAllSystemOptions } from '@/features/hierarchies/hooks/useSystemOptions' // 👈 ИМПОРТИРОВАЛИ ХУК
import type { ChainGroup } from '@/features/hierarchies/utils'
interface ChainDuplicateModalProps {
group: ChainGroup | null
opened: boolean
onClose: () => void
}
type ScopeType = 'global' | 'category' | 'topic'
interface StepForm {
approver_id: number | null
priority: number
target_system: string | null // 👈 ДОБАВИЛИ ПОЛЕ В ИНТЕРФЕЙС
}
export default function ChainDuplicateModal({
group,
opened,
onClose,
}: ChainDuplicateModalProps) {
const createHierarchy = useCreateHierarchy()
const { data: users } = useUsers({ limit: 1000 })
const { data: departments } = useDepartments()
const { data: categories } = useCategories({ limit: 1000 })
// Подтягиваем доступные системы
const { options: systemOptions } = useAllSystemOptions()
const { data: allTopics } = useTopics({ limit: 1000 })
const form = useForm({
initialValues: {
subordinate_id: null as number | null,
department_id: null as number | null,
scope_type: 'global' as ScopeType,
topic_category_id: null as number | null,
topic_id: null as number | null,
steps: [] as StepForm[],
},
validate: {
subordinate_id: (v) => (v === null ? 'Выберите инициатора' : null),
department_id: (v) => (v === null ? 'Выберите отдел' : null),
topic_category_id: (v, values) => {
if (
(values.scope_type === 'category' || values.scope_type === 'topic') &&
v === null
) {
return 'Выберите категорию'
}
return null
},
topic_id: (v, values) => {
if (values.scope_type === 'topic' && v === null) {
return 'Выберите тему'
}
return null
},
steps: {
approver_id: (v) => (v === null ? 'Выберите согласующего' : null),
},
},
})
const { data: categoryTopics } = useTopics({
limit: 1000,
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
})
useEffect(() => {
if (group && opened) {
let resolvedCategoryId: number | null = null
if (group.scopeType === 'category') {
resolvedCategoryId = group.scopeObjectId
} else if (group.scopeType === 'topic') {
const matchedTopic = allTopics?.data?.find((t) => t.id === group.scopeObjectId)
resolvedCategoryId = matchedTopic?.category_id || null
}
form.setValues({
subordinate_id: group.subordinateId,
department_id: group.departmentId,
scope_type: group.scopeType,
topic_category_id: resolvedCategoryId,
topic_id: group.scopeType === 'topic' ? group.scopeObjectId : null,
steps: group.steps.map((s, idx) => ({
approver_id: s.approver_id || null,
priority: idx,
target_system: s.target_system || null, // 👈 ИНИЦИАЛИЗИРУЕМ ИЗ БД
})),
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [group, opened, allTopics])
const handleScopeTypeChange = (value: ScopeType) => {
form.setFieldValue('scope_type', value)
if (value === 'global') {
form.setFieldValue('topic_category_id', null)
form.setFieldValue('topic_id', null)
} else if (value === 'category') {
form.setFieldValue('topic_id', null)
}
}
const addStep = () => {
form.insertListItem('steps', {
approver_id: null,
priority: form.values.steps.length,
target_system: null, // 👈 ИНИЦИАЛИЗИРУЕМ ДЛЯ НОВОГО ШАГА
})
}
const removeStep = (index: number) => {
form.removeListItem('steps', index)
form.values.steps.forEach((_, idx) => {
form.setFieldValue(`steps.${idx}.priority`, idx)
})
}
const userOptions =
users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const departmentOptions =
departments?.data?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || []
const categoryOptions =
categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions =
categoryTopics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const handleSubmit = async (values: typeof form.values) => {
if (values.steps.length === 0) {
notifications.show({
title: 'Ошибка',
message: 'Добавьте хотя бы один шаг согласования',
color: 'red',
})
return
}
try {
for (const step of values.steps) {
await createHierarchy.mutateAsync({
subordinate_id: values.subordinate_id!,
approver_id: step.approver_id!,
department_id: values.department_id!,
priority: step.priority,
target_system: step.target_system || null, // 👈 ОТПРАВЛЯЕМ СИСТЕМУ
topic_category_id:
values.scope_type === 'global'
? null
: values.scope_type === 'category'
? values.topic_category_id
: null,
topic_id: values.scope_type === 'topic' ? values.topic_id : null,
})
}
notifications.show({
title: 'Успешно',
message: `Цепочка дублирована (${values.steps.length} шагов)`,
color: 'green',
})
onClose()
} catch (error) {
notifications.show({
title: 'Ошибка',
message: 'Не удалось дублировать цепочку',
color: 'red',
})
}
}
const isSubmitting = createHierarchy.isPending
return (
Дублирование цепочки
}
size="lg"
centered
>
} color="blue" variant="light">
Создайте новую цепочку на основе существующей. Вы можете изменить
инициатора, отдел, область действия и согласующих.
{/* Общие параметры */}
Общие параметры
form.setFieldValue(
'subordinate_id',
v ? Number(v) : null
)
}
searchable
required
error={form.errors.subordinate_id}
/>
form.setFieldValue(
'department_id',
v ? Number(v) : null
)
}
searchable
required
error={form.errors.department_id}
/>
{/* Область действия */}
Область действия
handleScopeTypeChange(v as ScopeType)}
>
{(form.values.scope_type === 'category' ||
form.values.scope_type === 'topic') && (
{
form.setFieldValue(
'topic_category_id',
v ? Number(v) : null
)
form.setFieldValue('topic_id', null)
}}
searchable
required
error={form.errors.topic_category_id}
/>
)}
{form.values.scope_type === 'topic' && (
form.setFieldValue('topic_id', v ? Number(v) : null)
}
searchable
required
disabled={!form.values.topic_category_id}
error={form.errors.topic_id}
/>
)}
{/* Шаги согласования */}
Шаги согласования
}
onClick={addStep}
>
Добавить шаг
{form.values.steps.length === 0 ? (
Нет шагов согласования. Добавьте хотя бы один.
) : (
form.values.steps.map((step, index) => (
{index + 1}
Шаг {index + 1}
Priority: {step.priority}
form.setFieldValue(`steps.${index}.approver_id`, v ? Number(v) : null)
}
searchable
error={
Array.isArray(form.errors.steps) && form.errors.steps[index]
? (form.errors.steps[index] as any)?.approver_id
: undefined
}
/>
{/* 👈 ДОБАВЛЕННЫЙ ВЫБОР СИСТЕМЫ */}
({ value: s.value, label: `Система: ${s.label}` })),
]}
value={step.target_system || 'all'}
onChange={(v) =>
form.setFieldValue(
`steps.${index}.target_system`,
(v === 'all' || !v) ? null : v
)
}
clearable
/>
removeStep(index)}
>
))
)}
{/* Предпросмотр */}
{form.values.steps.length > 0 && (
Предпросмотр цепочки
{users?.data?.find(
(u) => u.id === form.values.subordinate_id
)?.full_name || 'Инициатор'}
{form.values.steps.map((step, index) => (
{users?.data?.find(
(u) => u.id === step.approver_id
)?.full_name || `Шаг ${index + 1}`}
{step.target_system && ` (${step.target_system})`}
))}
)}
Отмена
Дублировать цепочку
)
}
-----END src/pages/hierarchies/components/ChainDuplicateModal.tsx-----
File: src/pages/hierarchies/components/ChainVisualization.tsx
Lines: 323
-----BEGIN src/pages/hierarchies/components/ChainVisualization.tsx-----
// ChainVisualization.tsx
import {useMemo, useState} from 'react'
import {
Paper,
Group,
Stack,
Text,
Badge,
ActionIcon,
Avatar,
Box,
Divider,
Tooltip,
Select,
} from '@mantine/core'
import {
IconChevronRight,
IconPencil,
IconTrash,
IconWorld,
IconCategory,
IconFileText,
IconCopy,
IconPlus,
IconServer,
} from '@tabler/icons-react'
import type { ChainGroup } from '@/features/hierarchies/utils'
import { SCOPE_COLORS, SCOPE_LABELS } from '@/features/hierarchies/utils'
import {
useCategorySystemOptions,
ALL_SYSTEMS_VALUE,
useAllSystemOptions
} from '@/features/hierarchies/hooks/useSystemOptions'
import {useTopics} from "@/features/topics/hooks/useTopics.ts";
interface ChainVisualizationProps {
group: ChainGroup
onEditStep: (hierarchyId: number) => void
onDeleteStep: (hierarchyId: number) => void
onAddStep: (group: ChainGroup) => void
onDuplicateChain: (group: ChainGroup) => void
onBulkUpdateSystem?: (group: ChainGroup, targetSystem: string | null) => void
}
const ScopeIcon = ({ type }: { type: string }) => {
switch (type) {
case 'global':
return
case 'category':
return
case 'topic':
return
default:
return
}
}
// Внутри компонента ChainVisualization:
export default function ChainVisualization({
group,
onEditStep,
onDeleteStep,
onAddStep,
onDuplicateChain,
onBulkUpdateSystem,
}: ChainVisualizationProps) {
// Получаем все темы, чтобы уметь мапить topicId -> categoryId, если scopeType === 'topic'
const { data: allTopics } = useTopics({ limit: 1000 })
const resolvedCategoryId = useMemo(() => {
if (group.scopeType === 'category') {
return group.scopeObjectId
}
if (group.scopeType === 'topic' && group.scopeObjectId && allTopics?.data) {
const foundTopic = allTopics.data.find(t => t.id === group.scopeObjectId)
return foundTopic?.category_id || null
}
return null
}, [group.scopeType, group.scopeObjectId, allTopics?.data])
// Если цепочка глобальная (resolvedCategoryId === null), берем вообще все системы через useAllSystemOptions,
// иначе — системы конкретной категории через useCategorySystemOptions.
const categoryOptionsResult = useCategorySystemOptions(resolvedCategoryId)
const allOptionsResult = useAllSystemOptions(group.scopeType === 'global')
const systemOptions = group.scopeType === 'global' ? allOptionsResult.options : categoryOptionsResult.options
console.log(`[ChainVisualization] Группа ${group.key} (scope: ${group.scopeType}): resolvedCategoryId = ${resolvedCategoryId}, доступно систем:`, systemOptions)
// Текущая система цепочки (если у всех шагов одинаковая система, иначе 'all')
const currentChainSystem = group.steps.every(
(s) => s.target_system === group.steps[0]?.target_system
)
? group.steps[0]?.target_system || ALL_SYSTEMS_VALUE
: ALL_SYSTEMS_VALUE
// Формируем опции для Select
const selectData = [
{ value: ALL_SYSTEMS_VALUE, label: 'Система: Все' },
...systemOptions.map((opt) => ({
value: opt.value,
label: `Система: ${opt.label}`,
})),
]
return (
{/* Заголовок группы */}
{group.subordinateName.charAt(0).toUpperCase()}
{group.subordinateName}
{group.departmentName}
}
size="sm"
tt="none"
>
{SCOPE_LABELS[group.scopeType]}: {group.scopeObjectName}
{/* Выпадающий список систем отображается ТОЛЬКО если у темы/категории есть заданные systems */}
{systemOptions.length > 0 && (
}
data={selectData}
value={currentChainSystem}
onChange={(val) => {
const newSystem = val === ALL_SYSTEMS_VALUE ? "" : val
if (onBulkUpdateSystem) {
onBulkUpdateSystem(group, newSystem)
}
}}
style={{ width: 180 }}
/>
)}
onAddStep(group)}
>
onDuplicateChain(group)}
>
{/* Цепочка согласования */}
{/* Карточка инициатора */}
Инициатор
{group.subordinateName.charAt(0).toUpperCase()}
{group.subordinateName}
{/* Шаги согласования */}
{group.steps.map((step, index) => (
{index + 1}
{/* Карточка согласующего */}
onEditStep(step.id!)}
onMouseEnter={(e) => {
e.currentTarget.style.borderColor = 'var(--mantine-color-blue-5)'
}}
onMouseLeave={(e) => {
e.currentTarget.style.borderColor = 'var(--mantine-color-gray-3)'
}}
>
Шаг {index + 1}
#{step.priority}
{step.approver?.full_name?.charAt(0).toUpperCase() || '?'}
{step.approver?.full_name || '—'}
{/* Бейдж конкретной целевой системы для шага (если выбрано) */}
{step.target_system && (
Система: {step.target_system}
)}
{
e.stopPropagation()
onEditStep(step.id!)
}}
>
{
e.stopPropagation()
onDeleteStep(step.id!)
}}
>
))}
)
}
-----END src/pages/hierarchies/components/ChainVisualization.tsx-----
File: src/pages/hierarchies/components/HierarchyEditModal.tsx
Lines: 420
-----BEGIN src/pages/hierarchies/components/HierarchyEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
Select,
NumberInput,
Group,
Button,
Text,
Badge,
Paper,
Alert,
Radio,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconInfoCircle, IconAlertCircle, IconCopy } from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import {
useCreateHierarchy,
useUpdateHierarchy
} from '@/features/hierarchies/hooks/useHierarchies'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
import type { UserHierarchy } from '@/types/api'
import type { ChainGroup } from '@/features/hierarchies/utils'
import { useAllSystemOptions } from '@/features/hierarchies/hooks/useSystemOptions'
interface HierarchyEditModalProps {
hierarchy: UserHierarchy | null
presetGroup?: ChainGroup | null // Для добавления шага в существующую группу
opened: boolean
onClose: () => void
}
type ScopeType = 'global' | 'category' | 'topic'
export default function HierarchyEditModal({
hierarchy,
presetGroup,
opened,
onClose
}: HierarchyEditModalProps) {
const createHierarchy = useCreateHierarchy()
const updateHierarchy = useUpdateHierarchy()
const { data: users } = useUsers({ limit: 1000 })
const { data: departments } = useDepartments()
const { data: categories } = useCategories({ limit: 1000 })
const { options: systemOptions } = useAllSystemOptions()
const isEditMode = hierarchy !== null
const form = useForm({
initialValues: {
subordinate_id: null as number | null,
approver_id: null as number | null,
department_id: null as number | null,
scope_type: 'global' as ScopeType,
topic_category_id: null as number | null,
topic_id: null as number | null,
priority: 0,
target_system: null as string | null
},
validate: {
subordinate_id: (v) => (v === null ? 'Выберите подчинённого' : null),
approver_id: (v) => (v === null ? 'Выберите согласующего' : null),
// department_id/topic_category_id/topic_id заблокированы в режиме
// редактирования (см. disabled ниже) — если их всё же валидировать
// как обязательные, а на самой записи значение почему-то пустое,
// форма зависает намертво: поле нельзя ни заполнить (заблокировано),
// ни пропустить (обязательное).
department_id: (v) => (!isEditMode && v === null ? 'Выберите отдел' : null),
topic_category_id: (v, values) => {
if (isEditMode) return null
if ((values.scope_type === 'category' || values.scope_type === 'topic') && v === null) {
return 'Выберите категорию'
}
return null
},
topic_id: (v, values) => {
if (isEditMode) return null
if (values.scope_type === 'topic' && v === null) {
return 'Выберите тему'
}
return null
},
},
})
// Темы выбранной категории — для выпадающего списка "Тема" при создании.
const { data: categoryTopics } = useTopics({
limit: 1000,
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
})
// Полный список тем без фильтра — нужен, чтобы восстановить
// topic_category_id по topic_id (см. useEffect ниже), когда сама
// категория не сохранена явно — и на записи из БД (режим редактирования),
// и в presetGroup (добавление шага в существующую цепочку с областью
// действия "тема" — это и был баг №5).
const { data: allTopics } = useTopics({ limit: 1000 })
// Заполняем форму данными
useEffect(() => {
if (hierarchy) {
let scopeType: ScopeType = 'global'
if (hierarchy.topic_id) scopeType = 'topic'
else if (hierarchy.topic_category_id) scopeType = 'category'
let resolvedCategoryId = hierarchy.topic_category_id || null
if (scopeType === 'topic' && !resolvedCategoryId && allTopics?.data) {
const matchedTopic = allTopics.data.find((t) => t.id === hierarchy.topic_id)
resolvedCategoryId = matchedTopic?.category_id || null
}
form.setValues({
subordinate_id: hierarchy.subordinate_id || null,
approver_id: hierarchy.approver_id || null,
department_id: hierarchy.department_id || null,
scope_type: scopeType,
topic_category_id: resolvedCategoryId,
topic_id: hierarchy.topic_id || null,
target_system: hierarchy.target_system || null,
priority: hierarchy.priority ?? 0,
})
} else if (presetGroup) {
let resolvedCategoryId: number | null = null
if (presetGroup.scopeType === 'category') {
resolvedCategoryId = presetGroup.scopeObjectId
} else if (presetGroup.scopeType === 'topic') {
const matchedTopic = allTopics?.data?.find((t) => t.id === presetGroup.scopeObjectId)
resolvedCategoryId = matchedTopic?.category_id || null
}
form.setValues({
subordinate_id: presetGroup.subordinateId,
department_id: presetGroup.departmentId,
scope_type: presetGroup.scopeType,
topic_category_id: resolvedCategoryId,
topic_id: presetGroup.scopeType === 'topic' ? presetGroup.scopeObjectId : null,
priority: presetGroup.steps.length, // Следующий priority
approver_id: null,
})
} else {
form.reset()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hierarchy, presetGroup, opened, allTopics])
const handleScopeTypeChange = (value: ScopeType) => {
form.setFieldValue('scope_type', value)
if (value === 'global') {
form.setFieldValue('topic_category_id', null)
form.setFieldValue('topic_id', null)
} else if (value === 'category') {
form.setFieldValue('topic_id', null)
}
}
// Опции
const userOptions = users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const departmentOptions = departments?.data?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || []
const categoryOptions = categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions = categoryTopics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const buildPayload = (values: typeof form.values) => ({
subordinate_id: values.subordinate_id!,
approver_id: values.approver_id!,
department_id: values.department_id!,
priority: values.priority,
target_system: values.target_system || null,
topic_category_id: values.scope_type === 'global' ? null :
values.scope_type === 'category' ? values.topic_category_id : null,
topic_id: values.scope_type === 'topic' ? values.topic_id : null,
})
const handleSubmit = async (values: typeof form.values) => {
const payload = buildPayload(values)
if (isEditMode && hierarchy?.id) {
await updateHierarchy.mutateAsync({
id: hierarchy.id,
...payload,
})
} else {
await createHierarchy.mutateAsync(payload)
}
onClose()
}
// НОВОЕ (пункт 3): дублирование прямо из окна редактирования — создаёт
// новую запись с теми же значениями, что сейчас на экране, не трогая
// ту, что редактируется. Доступно только в режиме редактирования —
// дублировать ещё не сохранённую форму нечего.
const handleDuplicate = async () => {
if (!isEditMode) return
try {
await createHierarchy.mutateAsync(buildPayload(form.values))
notifications.show({
title: 'Успешно',
message: 'Связь продублирована — можно найти копию в списке и отредактировать при необходимости',
color: 'green',
})
onClose()
} catch (error) {
notifications.show({
title: 'Ошибка',
message: 'Не удалось продублировать связь',
color: 'red',
})
}
}
const isSubmitting = createHierarchy.isPending || updateHierarchy.isPending
const hasErrors = Object.keys(form.errors).length > 0
return (
{isEditMode ? 'Редактирование связи' : 'Добавление связи'}
{hierarchy && ID: {hierarchy.id} }
}
size="lg"
>
{hasErrors && (
} color="red" variant="light">
Проверьте поля, отмеченные красным, ниже.
)}
form.setFieldValue('subordinate_id', v ? Number(v) : null)}
searchable
required
disabled={!!presetGroup}
description="Пользователь, для которого настраивается согласование"
error={form.errors.subordinate_id}
/>
{/* Отдел */}
form.setFieldValue('department_id', v ? Number(v) : null)}
searchable
required={!isEditMode}
disabled={isEditMode || !!presetGroup}
error={form.errors.department_id}
/>
{/* Согласующий */}
form.setFieldValue('approver_id', v ? Number(v) : null)}
searchable
required
description="Пользователь, который будет согласовывать заявки"
error={form.errors.approver_id}
/>
{/* Область действия */}
Область действия
handleScopeTypeChange(v as ScopeType)}
>
{/* Категория */}
{(form.values.scope_type === 'category' || form.values.scope_type === 'topic') && (
{
form.setFieldValue('topic_category_id', v ? Number(v) : null)
form.setFieldValue('topic_id', null)
}}
searchable
required={!isEditMode}
disabled={isEditMode || !!presetGroup}
error={form.errors.topic_category_id}
/>
)}
{/* Тема */}
{form.values.scope_type === 'topic' && (
form.setFieldValue('topic_id', v ? Number(v) : null)}
searchable
required={!isEditMode}
disabled={!form.values.topic_category_id || isEditMode || !!presetGroup}
description={!form.values.topic_category_id && !isEditMode ? 'Сначала выберите категорию' : undefined}
error={form.errors.topic_id}
/>
)}
({ value: s.value, label: s.label })),
]}
value={form.values.target_system || 'all'}
onChange={(v) => form.setFieldValue('target_system', (v === 'all' || !v) ? "" : v)}
description="Укажите систему, если данный шаг согласующего применяется только к определенной системе"
/>
{/* Priority */}
form.setFieldValue('priority', Number(v) || 0)}
min={0}
required
/>
} color="blue" variant="light">
Шаги выполняются последовательно в порядке возрастания priority.
Заявка переходит к следующему согласующему только после одобрения предыдущим.
{isEditMode && ' Область действия и отдел при редактировании не меняются — чтобы поменять их, удалите связь и создайте новую.'}
{/* Кнопки */}
{isEditMode ? (
}
onClick={handleDuplicate}
disabled={isSubmitting}
>
Дублировать
) : (
)}
Отмена
{isEditMode ? 'Сохранить' : 'Создать'}
)
}
-----END src/pages/hierarchies/components/HierarchyEditModal.tsx-----
File: src/pages/hierarchies/components/PersonDuplicateModal.tsx
Lines: 197
-----BEGIN src/pages/hierarchies/components/PersonDuplicateModal.tsx-----
import { useState } from 'react'
import {
Modal,
Stack,
Select,
Group,
Button,
Text,
Paper,
Alert,
Badge,
Loader,
Center,
} from '@mantine/core'
import { IconInfoCircle, IconUsers } from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import { useHierarchies, useCreateHierarchy } from '@/features/hierarchies/hooks/useHierarchies'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
interface PersonDuplicateModalProps {
opened: boolean
onClose: () => void
}
// 0 — заведомо несуществующий id пользователя, чтобы не дёргать хук
// условно (нарушает Rules of Hooks) и не гадать, как бэкенд обработает
// limit:0 — просто явно просим "ничего не найдётся".
const NO_USER_SENTINEL = 0
export default function PersonDuplicateModal({ opened, onClose }: PersonDuplicateModalProps) {
const [sourceId, setSourceId] = useState(null)
const [targetId, setTargetId] = useState(null)
const [isDuplicating, setIsDuplicating] = useState(false)
const { data: users } = useUsers({ limit: 1000 })
const { data: categories } = useCategories({ limit: 1000 })
const { data: topics } = useTopics({ limit: 1000 })
const createHierarchy = useCreateHierarchy()
// Все связи исходного сотрудника — по всем областям действия сразу
// (глобальные + по категориям + по темам), без пагинации.
const { data: sourceHierarchies, isLoading: sourceLoading } = useHierarchies({
subordinate_id: sourceId ? Number(sourceId) : NO_USER_SENTINEL,
limit: 1000,
})
const sourceRows = sourceId ? sourceHierarchies?.data || [] : []
const userOptions = users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const describeScope = (h: { topic_id?: number | null; topic_category_id?: number | null }) => {
if (h.topic_id) {
const t = topics?.data?.find((t) => t.id === h.topic_id)
return `Тема: ${t?.name || `#${h.topic_id}`}`
}
if (h.topic_category_id) {
const c = categories?.data?.find((c) => c.id === h.topic_category_id)
return `Категория: ${c?.name || `#${h.topic_category_id}`}`
}
return 'Глобально'
}
const handleClose = () => {
setSourceId(null)
setTargetId(null)
onClose()
}
const handleDuplicate = async () => {
if (!sourceId || !targetId || sourceRows.length === 0) return
setIsDuplicating(true)
try {
// Последовательно, а не Promise.all — чтобы не заваливать API
// залпом при большом количестве связей у сотрудника, и чтобы
// при ошибке было понятно, на какой именно записи остановились.
for (const h of sourceRows) {
if (!h.approver_id || !h.department_id) continue
await createHierarchy.mutateAsync({
subordinate_id: Number(targetId),
approver_id: h.approver_id,
department_id: h.department_id,
priority: h.priority ?? 0,
topic_category_id: h.topic_category_id ?? null,
topic_id: h.topic_id ?? null,
})
}
notifications.show({
title: 'Успешно',
message: `Продублировано связей: ${sourceRows.length}`,
color: 'green',
})
handleClose()
} catch (error) {
notifications.show({
title: 'Ошибка',
message: 'Не удалось продублировать связи — часть могла успеть создаться, проверьте список',
color: 'red',
})
} finally {
setIsDuplicating(false)
}
}
return (
Дублировать все связи сотрудника
}
size="lg"
centered
>
} color="blue" variant="light">
Скопирует ВСЕ цепочки согласования выбранного сотрудника — глобальные, по
категориям и по темам — для нового сотрудника. Отдел, согласующие,
категории/темы и порядок шагов сохранятся как на образце.
o.value !== targetId)}
value={sourceId}
onChange={setSourceId}
searchable
required
/>
o.value !== sourceId)}
value={targetId}
onChange={setTargetId}
searchable
required
disabled={!sourceId}
/>
{sourceId && (
Будет продублировано
{sourceLoading ? (
) : sourceRows.length === 0 ? (
У этого сотрудника нет ни одной настроенной связи — дублировать нечего.
) : (
{sourceRows.map((h) => (
{h.approver?.full_name || `Согласующий #${h.approver_id}`}
{describeScope(h)}
))}
)}
)}
Отмена
{sourceRows.length > 0 ? `Продублировать (${sourceRows.length})` : 'Продублировать'}
)
}
-----END src/pages/hierarchies/components/PersonDuplicateModal.tsx-----
File: src/pages/notifications/NotificationsPage.tsx
Lines: 44
-----BEGIN src/pages/notifications/NotificationsPage.tsx-----
import { Stack, Tabs, Text, Alert } from '@mantine/core'
import { IconSend, IconHistory, IconLock } from '@tabler/icons-react'
import { useAuth } from '@/hooks/useAuth'
import SendNotificationForm from './components/SendNotificationForm'
import NotificationsHistoryTable from './components/NotificationsHistoryTable'
export default function NotificationsPage() {
const { user } = useAuth()
const isObserver = user?.is_observer === true
return (
Уведомления
{!isObserver && (
}>
Отправить
)}
}>
История
{!isObserver && (
)}
{isObserver && (
}>
В режиме наблюдателя доступен только просмотр истории уведомлений
)}
)
}
-----END src/pages/notifications/NotificationsPage.tsx-----
File: src/pages/notifications/components/NotificationDetailsModal.tsx
Lines: 74
-----BEGIN src/pages/notifications/components/NotificationDetailsModal.tsx-----
import { useNotification } from '@/features/notifications/hooks/useNotifications'
import { Modal, Stack, Text, Badge, ScrollArea, Table, Divider, Loader, Center } from '@mantine/core'
interface Props {
notificationId: number | null
opened: boolean
onClose: () => void
}
const RECIPIENT_STATUS_LABELS: Record = {
pending: { label: 'В очереди', color: 'gray' },
sent: { label: 'Доставлено', color: 'green' },
failed: { label: 'Ошибка', color: 'red' },
}
export default function NotificationDetailsModal({ notificationId, opened, onClose }: Props) {
const { data: notification, isLoading } = useNotification(notificationId)
return (
{isLoading || !notification ? (
) : (
{notification.title}
Пользователь
Статус
Ошибка
{(notification.recipients || []).map((r) => {
const statusInfo = RECIPIENT_STATUS_LABELS[r.status || ''] || {
label: r.status || '—',
color: 'gray',
}
return (
{r.user?.full_name || `ID ${r.user_id}`}
{statusInfo.label}
{r.error_message || ''}
)
})}
)}
)
}
-----END src/pages/notifications/components/NotificationDetailsModal.tsx-----
File: src/pages/notifications/components/NotificationsHistoryTable.tsx
Lines: 124
-----BEGIN src/pages/notifications/components/NotificationsHistoryTable.tsx-----
import { useState } from 'react'
import {
Paper, Table, Badge, Group, Text, Pagination, Loader, Center, Box, Stack,
} from '@mantine/core'
import NotificationDetailsModal from './NotificationDetailsModal'
import { useNotifications } from '@/features/notifications/hooks/useNotifications'
const LIMIT = 20
const STATUS_LABELS: Record = {
pending: { label: 'В очереди', color: 'gray' },
sending: { label: 'Отправляется', color: 'blue' },
completed: { label: 'Завершено', color: 'green' },
failed: { label: 'Ошибка', color: 'red' },
}
export default function NotificationsHistoryTable() {
const [page, setPage] = useState(1)
const [selectedId, setSelectedId] = useState(null)
const { data, isLoading } = useNotifications({
offset: (page - 1) * LIMIT,
limit: LIMIT,
})
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
return (
{isLoading ? (
) : (
<>
ID
Заголовок
Статус
Доставлено
Дата отправки
{data?.data?.length === 0 ? (
Уведомления не отправлялись
) : (
(data?.data || []).map((n) => {
const statusInfo = STATUS_LABELS[n.status || ''] || {
label: n.status || '—',
color: 'gray',
}
return (
setSelectedId(n.id!)}
>
{n.id}
{n.title}
{statusInfo.label}
{n.sent_count ?? 0}
{(n.failed_count ?? 0) > 0 && (
{n.failed_count} ошибок
)}
из {n.total_count ?? 0}
{n.sent_at ? new Date(n.sent_at).toLocaleString('ru-RU') : '—'}
)
})
)}
{totalPages > 1 && (
Страница {page} из {totalPages}
)}
>
)}
setSelectedId(null)}
/>
)
}
-----END src/pages/notifications/components/NotificationsHistoryTable.tsx-----
File: src/pages/notifications/components/SendNotificationForm.tsx
Lines: 445
-----BEGIN src/pages/notifications/components/SendNotificationForm.tsx-----
import { useState, useMemo } from 'react'
import {
Paper, Stack, TextInput, Button, Group, MultiSelect, Checkbox,
Text, FileButton, Image, ActionIcon, Divider, Alert, Badge, Grid,
ThemeIcon,
} from '@mantine/core'
import {
IconPhoto, IconX, IconSend, IconAlertCircle, IconUsers,
IconUser, IconMask, IconBuilding, IconTag, IconEye, IconMessage,
} from '@tabler/icons-react'
import { RichTextEditor, Link } from '@mantine/tiptap'
import { useEditor } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import Underline from '@tiptap/extension-underline'
import { useDebouncedValue } from '@mantine/hooks'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useAllRoles } from '@/features/roles/hooks/useAllRoles'
import { useCreateNotification } from '@/features/notifications/hooks/useNotifications.ts'
import { convertHtmlToTelegram } from '@/features/notifications/utils/telegramHtml.ts'
import { notifications } from '@mantine/notifications'
import { Modal } from '@mantine/core'
import '@mantine/tiptap/styles.css'
const ROLE_TYPE_OPTIONS = [
{ value: 'director', label: 'Директора', icon: '👔' },
{ value: 'approver', label: 'Согласующие', icon: '✅' },
{ value: 'observer', label: 'Наблюдатели', icon: '👀' },
{ value: 'executor', label: 'Исполнители', icon: '⚙️' },
{ value: 'controller', label: 'Контролёры', icon: '🎯' },
]
export default function SendNotificationForm() {
const [title, setTitle] = useState('')
const [userSearch, setUserSearch] = useState('')
const [debouncedUserSearch] = useDebouncedValue(userSearch, 300)
const [selectedUserIds, setSelectedUserIds] = useState([])
const [selectedRoleIds, setSelectedRoleIds] = useState([])
const [selectedRoleFlags, setSelectedRoleFlags] = useState([])
const [selectedDepartmentIds, setSelectedDepartmentIds] = useState([])
const [photoBase64, setPhotoBase64] = useState(null)
const [photoFileName, setPhotoFileName] = useState(null)
const [photoPreviewUrl, setPhotoPreviewUrl] = useState(null)
const [confirmOpen, setConfirmOpen] = useState(false)
const { data: usersData } = useUsers({
limit: 50,
...(debouncedUserSearch && { full_name: debouncedUserSearch }),
})
const { data: roles = [] } = useAllRoles()
const { data: departmentsResponse } = useDepartments({ limit: 1000 })
const departments = departmentsResponse?.data || []
const createNotification = useCreateNotification()
const editor = useEditor({
extensions: [StarterKit, Underline, Link],
content: '',
})
const userOptions = useMemo(
() => (usersData?.data || []).map((u) => ({
value: String(u.id),
label: u.full_name + (u.username ? ` (@${u.username})` : ''),
})),
[usersData],
)
const roleOptions = useMemo(
() => roles.map((r) => ({ value: String(r.id), label: r.name })),
[roles],
)
const departmentOptions = useMemo(
() => departments.map((d) => ({ value: String(d.id), label: d.name })),
[departments],
)
const MAX_ASPECT_RATIO = 20
const handlePhotoChange = (file: File | null) => {
if (!file) {
setPhotoBase64(null)
setPhotoFileName(null)
setPhotoPreviewUrl(null)
return
}
const reader = new FileReader()
reader.onload = () => {
const result = reader.result as string
const img = new window.Image()
img.onload = () => {
const ratio = Math.max(img.width, img.height) / Math.min(img.width, img.height)
const sumDimensions = img.width + img.height
if (ratio > MAX_ASPECT_RATIO || sumDimensions > 10000) {
notifications.show({
title: 'Некорректное изображение',
message: `Telegram не примет это фото: слишком вытянутые пропорции (${img.width}×${img.height}).`,
color: 'red',
})
return
}
setPhotoBase64(result.split(',')[1] || '')
setPhotoFileName(file.name)
setPhotoPreviewUrl(result)
}
img.src = result
}
reader.readAsDataURL(file)
}
const hasAnyTarget =
selectedUserIds.length > 0 ||
selectedRoleIds.length > 0 ||
selectedRoleFlags.length > 0 ||
selectedDepartmentIds.length > 0
const messageHtml = editor?.getHTML() ?? ''
const messageText = editor?.getText() ?? ''
const isMessageEmpty = editor?.isEmpty ?? true
const canSubmit = title.trim().length > 0 && !isMessageEmpty && hasAnyTarget
const totalCriteria =
(selectedUserIds.length > 0 ? 1 : 0) +
(selectedRoleIds.length > 0 ? 1 : 0) +
(selectedRoleFlags.length > 0 ? 1 : 0) +
(selectedDepartmentIds.length > 0 ? 1 : 0)
const doSubmit = () => {
setConfirmOpen(false)
createNotification.mutate(
{
title: title.trim(),
message_html: convertHtmlToTelegram(messageHtml),
photo_base64: photoBase64 || undefined,
photo_file_name: photoFileName || undefined,
targets: {
user_ids: selectedUserIds.map(Number),
role_ids: selectedRoleIds.map(Number),
role_type_flags: selectedRoleFlags,
department_ids: selectedDepartmentIds.map(Number),
},
},
{
onSuccess: () => {
setTitle('')
editor?.commands.clearContent()
setSelectedUserIds([])
setSelectedRoleIds([])
setSelectedRoleFlags([])
setSelectedDepartmentIds([])
handlePhotoChange(null)
notifications.show({
title: 'Успешно',
message: 'Уведомление отправлено',
color: 'green',
})
},
},
)
}
return (
{/* ===== HEADER ===== */}
Новая рассылка
Отправится через Telegram Bot
{totalCriteria > 0 && (
{totalCriteria} {totalCriteria === 1 ? 'критерий' : 'критериев'}
)}
setTitle(e.currentTarget.value)}
required
size="md"
/>
{/* Редактор */}
Текст сообщения
{!isMessageEmpty && (
}>
Заполнено
)}
жирный · курсив · подчёркнутый · зачёркнутый · код · ссылки — остальное Telegram не отобразит
{/* Фото */}
Фото (опционально)
{photoPreviewUrl ? (
{photoFileName}
Готово к отправке
handlePhotoChange(null)}
>
) : (
{(props) => (
}>
Прикрепить фото
)}
)}
{/* ===== ПРАВАЯ КОЛОНКА: ПОЛУЧАТЕЛИ + ПРЕВЬЮ ===== */}
{/* Получатели */}
Получатели
{hasAnyTarget && (
Настроено
)}
Конкретные пользователи
{selectedUserIds.length > 0 && (
{selectedUserIds.length}
)}
}
placeholder="Начните вводить имя..."
data={userOptions}
value={selectedUserIds}
onChange={setSelectedUserIds}
searchable
searchValue={userSearch}
onSearchChange={setUserSearch}
clearable
nothingFoundMessage="Никого не найдено"
size="xs"
/>
Роли
{selectedRoleIds.length > 0 && (
{selectedRoleIds.length}
)}
}
placeholder="Выберите роли"
data={roleOptions}
value={selectedRoleIds}
onChange={setSelectedRoleIds}
searchable
clearable
size="xs"
/>
Тип роли
{selectedRoleFlags.length > 0 && (
{selectedRoleFlags.length}
)}
{ROLE_TYPE_OPTIONS.map((opt) => (
{opt.icon}
{opt.label}
}
/>
))}
Отделы
{selectedDepartmentIds.length > 0 && (
{selectedDepartmentIds.length}
)}
}
placeholder="Выберите отделы"
data={departmentOptions}
value={selectedDepartmentIds}
onChange={setSelectedDepartmentIds}
searchable
clearable
size="xs"
/>
{!hasAnyTarget && (
} p="xs">
Выберите хотя бы один способ определения получателей
)}
{/* Кнопка отправки */}
}
onClick={() => setConfirmOpen(true)}
loading={createNotification.isPending}
disabled={!canSubmit}
>
Отправить уведомление
{/* ===== МОДАЛКА ПОДТВЕРЖДЕНИЯ ===== */}
setConfirmOpen(false)}
title="Подтверждение отправки"
centered
>
Отправить уведомление «{title.trim()}» ?
{selectedUserIds.length > 0 && (
Пользователей
{selectedUserIds.length}
)}
{selectedRoleIds.length > 0 && (
Ролей
{selectedRoleIds.length}
)}
{selectedRoleFlags.length > 0 && (
Типов ролей
{selectedRoleFlags.length}
)}
{selectedDepartmentIds.length > 0 && (
Отделов
{selectedDepartmentIds.length}
)}
setConfirmOpen(false)}>
Отмена
Отправить
)
}
-----END src/pages/notifications/components/SendNotificationForm.tsx-----
File: src/pages/permissions/PermissionsPage.tsx
Lines: 306
-----BEGIN src/pages/permissions/PermissionsPage.tsx-----
import { useState } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
Select,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Tabs,
UnstyledButton,
ThemeIcon,
} from '@mantine/core'
import {
IconPencil,
IconTrash,
IconPlus,
IconSearch,
IconShield,
IconCategory,
IconBriefcase,
IconWorld,
} from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { usePermissions, useDeletePermission } from '@/features/permissions/hooks/usePermissions'
import { useRoles } from '@/features/roles/hooks/useRoles'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { PERMISSION_ACTIONS, ACTION_COLORS, ACTION_LABELS } from '@/features/permissions/constants'
import PermissionEditModal from './components/PermissionEditModal'
const LIMIT = 50
export default function PermissionsPage() {
const [page, setPage] = useState(1)
const [roleFilter, setRoleFilter] = useState(null)
const [actionFilter, setActionFilter] = useState(null)
const [editPermissionId, setEditPermissionId] = useState(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const { data, isLoading, isFetching } = usePermissions({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(roleFilter && { role_id: Number(roleFilter) }),
...(actionFilter && { action: actionFilter }),
})
const { data: roles } = useRoles({ limit: 1000 })
const deletePermission = useDeletePermission()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const roleOptions = roles?.data?.map((r) => ({
value: String(r.id),
label: r.name || '',
})) || []
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
Вы уверены, что хотите удалить это право? Пользователи с этой ролью потеряют соответствующие возможности.
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deletePermission.mutate(id),
})
}
// Определяем "уровень" права
const getPermissionLevel = (permission: any) => {
if (permission.topic_id && permission.topic) {
return {
level: 'topic',
label: 'Тема',
value: permission.topic.name,
icon: IconBriefcase,
color: 'orange',
}
}
if (permission.topic_category_id && permission.topic_category) {
return {
level: 'category',
label: 'Категория',
value: permission.topic_category.name,
icon: IconCategory,
color: 'blue',
}
}
return {
level: 'global',
label: 'Глобальное',
value: 'Все темы',
icon: IconWorld,
color: 'violet',
}
}
return (
Права доступа
Всего: {data?.total_count || 0}
}
onClick={() => setCreateModalOpened(true)}
>
Добавить право
{/* Подсказка */}
Права определяют, какие действия могут выполнять пользователи с определённой ролью.
Право может быть глобальным (на все темы),
на категорию (на все темы категории) или на конкретную тему .
{/* Фильтры */}
{
setRoleFilter(v)
setPage(1)
}}
clearable
searchable
style={{ minWidth: 200 }}
/>
({
value: a.value,
label: a.label,
}))}
value={actionFilter}
onChange={(v) => {
setActionFilter(v)
setPage(1)
}}
clearable
style={{ minWidth: 200 }}
/>
{/* Таблица */}
{isLoading ? (
) : (
<>
ID
Роль
Действие
Область действия
Объект
Действия
{data?.data?.length === 0 ? (
Права не найдены
) : (
(data?.data || []).map((permission) => {
const level = getPermissionLevel(permission)
const LevelIcon = level.icon
return (
{permission.id}
{permission.role?.name || '—'}
{permission.role?.code}
{ACTION_LABELS[permission.action || ''] || permission.action}
{level.label}
{level.value}
setEditPermissionId(permission.id!)}
>
handleDelete(permission.id!)}
>
)
})
)}
{totalPages > 1 && (
Страница {page} из {totalPages}
)}
>
)}
{isFetching && !isLoading && (
)}
setEditPermissionId(null)}
/>
setCreateModalOpened(false)}
/>
)
}
-----END src/pages/permissions/PermissionsPage.tsx-----
File: src/pages/permissions/components/PermissionEditModal.tsx
Lines: 303
-----BEGIN src/pages/permissions/components/PermissionEditModal.tsx-----
import { useEffect, useMemo } from 'react'
import {
Modal,
Stack,
Select,
Group,
Button,
Text,
Loader,
Center,
Badge,
Paper,
Alert,
Radio,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconInfoCircle } from '@tabler/icons-react'
import {
usePermission,
useCreatePermission,
useUpdatePermission
} from '@/features/permissions/hooks/usePermissions'
import { useRoles } from '@/features/roles/hooks/useRoles'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
import { PERMISSION_ACTIONS } from '@/features/permissions/constants'
interface PermissionEditModalProps {
permissionId: number | null
opened: boolean
onClose: () => void
}
type ScopeType = 'global' | 'category' | 'topic'
export default function PermissionEditModal({
permissionId,
opened,
onClose
}: PermissionEditModalProps) {
const { data: permission, isLoading: permissionLoading } = usePermission(permissionId)
const createPermission = useCreatePermission()
const updatePermission = useUpdatePermission()
const { data: roles } = useRoles({ limit: 1000 })
const { data: categories } = useCategories({ limit: 1000 })
const isEditMode = permissionId !== null
const form = useForm({
initialValues: {
role_id: null as number | null,
action: '',
scope_type: 'global' as ScopeType,
topic_category_id: null as number | null,
topic_id: null as number | null,
},
validate: {
role_id: (value) => (value === null ? 'Выберите роль' : null),
action: (value) => (value === '' ? 'Выберите действие' : null),
topic_id: (value, values) => {
if (values.scope_type === 'topic' && value === null) {
return 'Выберите тему'
}
return null
},
topic_category_id: (value, values) => {
if (values.scope_type === 'category' && value === null) {
return 'Выберите категорию'
}
return null
},
},
})
// Загружаем темы выбранной категории
const { data: categoryTopics } = useTopics({
limit: 1000,
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
})
// Заполняем форму данными
useEffect(() => {
if (permission) {
let scopeType: ScopeType = 'global'
if (permission.topic_id) scopeType = 'topic'
else if (permission.topic_category_id) scopeType = 'category'
form.setValues({
role_id: permission.role_id || null,
action: permission.action || '',
scope_type: scopeType,
topic_category_id: permission.topic_category_id || null,
topic_id: permission.topic_id || null,
})
} else if (!isEditMode) {
form.reset()
}
}, [permission, isEditMode])
// При смене scope_type сбрасываем связанные поля
const handleScopeTypeChange = (value: ScopeType) => {
form.setFieldValue('scope_type', value)
if (value === 'global') {
form.setFieldValue('topic_category_id', null)
form.setFieldValue('topic_id', null)
} else if (value === 'category') {
form.setFieldValue('topic_id', null)
}
}
// При смене категории сбрасываем тему
const handleCategoryChange = (value: string | null) => {
form.setFieldValue('topic_category_id', value ? Number(value) : null)
form.setFieldValue('topic_id', null)
}
// Опции
const roleOptions = roles?.data?.map((r) => ({
value: String(r.id),
label: r.name || '',
})) || []
const categoryOptions = categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions = categoryTopics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const actionOptions = PERMISSION_ACTIONS.map((a) => ({
value: a.value,
label: `${a.label} — ${a.description}`,
}))
// Получаем описание области действия
const scopeDescription = useMemo(() => {
switch (form.values.scope_type) {
case 'global':
return 'Право будет действовать на все темы согласований'
case 'category':
return 'Право будет действовать на все темы выбранной категории'
case 'topic':
return 'Право будет действовать только на выбранную тему'
}
}, [form.values.scope_type])
const handleSubmit = async (values: typeof form.values) => {
const payload = {
role_id: values.role_id!,
action: values.action,
topic_category_id: values.scope_type === 'global' ? null :
values.scope_type === 'category' ? values.topic_category_id : null,
topic_id: values.scope_type === 'topic' ? values.topic_id : null,
}
if (isEditMode && permissionId) {
await updatePermission.mutateAsync({
id: permissionId,
...payload,
})
} else {
await createPermission.mutateAsync(payload)
}
onClose()
}
const isLoading = permissionLoading
const isSubmitting = createPermission.isPending || updatePermission.isPending
return (
{isEditMode ? 'Редактирование права' : 'Добавление права'}
{permission && ID: {permission.id} }
}
size="lg"
>
{isLoading ? (
) : (
{/* Роль */}
form.setFieldValue('role_id', v ? Number(v) : null)}
searchable
required
disabled={isEditMode}
description="Роль, которой назначается право"
/>
{/* Действие */}
form.setFieldValue('action', v || '')}
required
description="Какое действие будет доступно"
/>
{/* Область действия */}
Область действия
handleScopeTypeChange(v as ScopeType)}
>
} color="blue" variant="light" mt="sm">
{scopeDescription}
{/* Категория (если выбрана) */}
{(form.values.scope_type === 'category' || form.values.scope_type === 'topic') && (
)}
{/* Тема (если выбрана) */}
{form.values.scope_type === 'topic' && (
form.setFieldValue('topic_id', v ? Number(v) : null)}
searchable
required
disabled={!form.values.topic_category_id}
description={
!form.values.topic_category_id
? 'Сначала выберите категорию'
: 'Тема, на которую распространяется право'
}
/>
)}
{/* Кнопки */}
Отмена
{isEditMode ? 'Сохранить' : 'Создать'}
)}
)
}
-----END src/pages/permissions/components/PermissionEditModal.tsx-----
File: src/pages/roles/RolesPage.tsx
Lines: 318
-----BEGIN src/pages/roles/RolesPage.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 { useRoles, useDeleteRole } from '@/features/roles/hooks/useRoles'
import RoleEditModal from './components/RoleEditModal'
const LIMIT = 20
export default function RolesPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [roleTypeFilter, setRoleTypeFilter] = useState(null)
const [editRoleId, setEditRoleId] = useState(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const { data, isLoading, isFetching } = useRoles({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(search && { name: search }),
...(roleTypeFilter === 'director' && { is_director: true }),
...(roleTypeFilter === 'approver' && { is_approver: true }),
...(roleTypeFilter === 'observer' && { is_observer: true }),
...(roleTypeFilter === 'executor' && { is_executor: true }),
...(roleTypeFilter === 'controller' && { is_controller: true }), // 🆕
})
const deleteRole = useDeleteRole()
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: () => deleteRole.mutate(id),
})
}
return (
Роли
Всего: {data?.total_count || 0}
}
onClick={() => setCreateModalOpened(true)}
>
Создать роль
{/* Фильтры */}
}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
style={{ flex: 1 }}
/>
{
setRoleTypeFilter(null)
setPage(1)
}}
>
Все
{
setRoleTypeFilter(roleTypeFilter === 'director' ? null : 'director')
setPage(1)
}}
>
Директора
{
setRoleTypeFilter(roleTypeFilter === 'approver' ? null : 'approver')
setPage(1)
}}
>
Согласующие
{
setRoleTypeFilter(roleTypeFilter === 'observer' ? null : 'observer')
setPage(1)
}}
>
Наблюдатели
{
setRoleTypeFilter(roleTypeFilter === 'controller' ? null : 'controller')
setPage(1)
}}
>
Контролёры
{
setRoleTypeFilter(roleTypeFilter === 'executor' ? null : 'executor')
setPage(1)
}}
>
Исполнители
{/* Таблица */}
{isLoading ? (
) : (
<>
ID
Название
Код
Типы ролей
Описание
Статус
Действия
{data?.data?.length === 0 ? (
Роли не найдены
) : (
(data?.data || []).map((role) => (
{role.id}
{role.name}
{role.code}
{role.is_director && (
Директор
)}
{role.is_approver && (
Согласующий
)}
{role.is_observer && (
Наблюдатель
)}
{role.is_executor && (
Исполнитель
)}
{role.is_controller && (
Контролёр
)}
{!role.is_director && !role.is_approver && !role.is_observer &&
!role.is_executor && !role.is_controller && (
—
)}
{role.description || '—'}
{role.is_default ? 'По умолчанию' : 'Пользовательская'}
setEditRoleId(role.id!)}
>
handleDelete(role.id!)}
disabled={role.is_default}
>
))
)}
{/* Пагинация */}
{totalPages > 1 && (
Страница {page} из {totalPages}
)}
>
)}
{/* Индикатор обновления */}
{isFetching && !isLoading && (
)}
{/* Модальное окно редактирования */}
setEditRoleId(null)}
/>
{/* Модальное окно создания */}
setCreateModalOpened(false)}
/>
)
}
-----END src/pages/roles/RolesPage.tsx-----
File: src/pages/roles/components/RoleEditModal.tsx
Lines: 209
-----BEGIN src/pages/roles/components/RoleEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Textarea,
Switch,
Group,
Button,
Text,
Loader,
Center,
Badge,
Paper,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
useRole,
useCreateRole,
useUpdateRole
} from '@/features/roles/hooks/useRoles'
interface RoleEditModalProps {
roleId: number | null
opened: boolean
onClose: () => void
}
export default function RoleEditModal({
roleId,
opened,
onClose
}: RoleEditModalProps) {
const { data: role, isLoading: roleLoading } = useRole(roleId)
const createRole = useCreateRole()
const updateRole = useUpdateRole()
const isEditMode = roleId !== null
const form = useForm({
initialValues: {
name: '',
code: '',
description: '',
is_default: false,
is_director: false,
is_approver: false,
is_observer: false,
is_executor: false,
is_controller: false,
},
validate: {
name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
code: (value: string | any[]) => {
if (value.length < 2) return 'Код должен содержать минимум 2 символа'
if (!/^[a-z0-9_]+$/.test(value as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
return null
},
},
})
// Заполняем форму данными роли
useEffect(() => {
if (role) {
form.setValues({
name: role.name || '',
code: role.code || '',
description: role.description || '',
is_default: role.is_default ?? false,
is_director: role.is_director ?? false,
is_approver: role.is_approver ?? false,
is_observer: role.is_observer ?? false,
is_executor: role.is_executor ?? false,
is_controller: role.is_controller ?? false,
})
} else if (!isEditMode) {
form.reset()
}
}, [role, isEditMode])
const handleSubmit = async (values: typeof form.values) => {
if (isEditMode && roleId) {
// Режим редактирования
await updateRole.mutateAsync({
id: roleId,
...values,
})
} else {
// Режим создания
await createRole.mutateAsync(values)
}
onClose()
}
const isLoading = roleLoading
const isSubmitting = createRole.isPending || updateRole.isPending
return (
{isEditMode ? 'Редактирование роли' : 'Создание роли'}
{role && ID: {role.id} }
}
size="lg"
>
{isLoading ? (
) : (
Типы ролей
form.setFieldValue('is_director', e.currentTarget.checked)}
color="violet"
/>
form.setFieldValue('is_approver', e.currentTarget.checked)}
color="blue"
/>
form.setFieldValue('is_observer', e.currentTarget.checked)}
color="green"
/>
form.setFieldValue('is_executor', e.currentTarget.checked)}
color="orange"
/>
form.setFieldValue('is_controller', e.currentTarget.checked)}
color="teal"
/>
form.setFieldValue('is_default', e.currentTarget.checked)}
color="blue"
/>
Отмена
{isEditMode ? 'Сохранить' : 'Создать'}
)}
)
}
-----END src/pages/roles/components/RoleEditModal.tsx-----
File: src/pages/settings/SettingsPage.tsx
Lines: 179
-----BEGIN src/pages/settings/SettingsPage.tsx-----
import { useState } from 'react'
import {
Paper,
Stack,
Text,
PasswordInput,
Button,
Group,
Alert,
Box,
Title,
Divider,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import { modals } from '@mantine/modals'
import { IconShield, IconAlertCircle, IconKey } from '@tabler/icons-react'
import { authApi } from '@/api/auth'
import { useAuth } from '@/hooks/useAuth'
export default function SettingsPage() {
const [loading, setLoading] = useState(false)
const { user } = useAuth()
const form = useForm({
initialValues: {
current_password: '',
new_password: '',
confirm_password: '',
},
validate: {
current_password: (value) =>
value.length === 0 ? 'Введите текущий пароль' : null,
new_password: (value) => {
if (value.length === 0) return 'Введите новый пароль'
if (value.length < 6) return 'Пароль должен содержать минимум 6 символов'
return null
},
confirm_password: (value, values) =>
value !== values.new_password ? 'Пароли не совпадают' : null,
},
})
const handleSubmit = async (values: typeof form.values) => {
// Подтверждение через модальное окно
modals.openConfirmModal({
title: 'Подтвердите смену пароля',
children: (
Вы уверены, что хотите изменить пароль? После смены пароля вам нужно будет
войти заново на всех устройствах.
),
labels: { confirm: 'Изменить пароль', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: async () => {
setLoading(true)
try {
await authApi.updateProfile({ password: values.new_password })
notifications.show({
title: 'Успешно',
message: 'Пароль успешно изменен',
color: 'green',
})
form.reset()
// Разлогиниваем пользователя, чтобы он вошёл заново
setTimeout(() => {
localStorage.removeItem('token')
window.location.href = '/login'
}, 1500)
} catch (error: any) {
notifications.show({
title: 'Ошибка',
message: error.response?.data?.error_description || 'Не удалось изменить пароль',
color: 'red',
})
} finally {
setLoading(false)
}
},
})
}
return (
Настройки
Управление вашим аккаунтом
{/* Информация о профиле */}
Логин:
{user?.login || '—'}
{user?.last_login && (
Последний вход:
{new Date(user.last_login).toLocaleString('ru-RU')}
)}
{user?.last_ip_login && (
Последний IP:
{user.last_ip_login}
)}
{/* Смена пароля */}
Смена пароля
}
color="yellow"
variant="light"
mb="md"
>
После смены пароля вам нужно будет войти заново на всех устройствах.
}
>
Изменить пароль
)
}
-----END src/pages/settings/SettingsPage.tsx-----
File: src/pages/topicExecutors/TopicExecutorsPage.tsx
Lines: 397
-----BEGIN src/pages/topicExecutors/TopicExecutorsPage.tsx-----
import { useState, useMemo } from 'react'
import {
Paper,
Table,
Group,
ActionIcon,
Button,
Text,
Select,
Loader,
Center,
Tooltip,
Box,
Stack,
SegmentedControl,
Badge,
Alert,
ScrollArea,
} from '@mantine/core'
import {
IconPencil,
IconTrash,
IconPlus,
IconInfoCircle,
IconFile,
IconCheck,
IconX,
} from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import {
useTopicExecutors,
useDeleteTopicExecutor
} from '@/features/topicExecutors/hooks/useTopicExecutors'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useTopics } from '@/features/topics/hooks/useTopics'
import { useCategories } from '@/features/categories/hooks/useCategories'
import {
groupExecutorsByTopic,
TARGET_SYSTEMS,
TARGET_SYSTEM_LABELS,
TARGET_SYSTEM_COLORS,
type TopicExecutorsGroup,
} from '@/features/topicExecutors/utils'
import TopicExecutorsCard from './components/TopicExecutorsCard'
import TopicExecutorEditModal from './components/TopicExecutorEditModal'
import type { ApprovalTopicExecutor } from '@/types/api'
type ViewMode = 'cards' | 'table'
export default function TopicExecutorsPage() {
const [viewMode, setViewMode] = useState('cards')
// ✅ Фильтры - адаптированы под дизайн Hierarchies
const [topicFilter, setTopicFilter] = useState(null)
const [categoryFilter, setCategoryFilter] = useState(null)
const [userFilter, setUserFilter] = useState(null)
const [targetSystemFilter, setTargetSystemFilter] = useState(null)
const [editExecutor, setEditExecutor] = useState(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const [presetGroup, setPresetGroup] = useState(null)
// ✅ Получаем категории
const { data: categories } = useCategories({ limit: 1000 })
// ✅ Получаем темы с учетом фильтра по категории
const { data: categoryTopics } = useTopics({
limit: 1000,
...(categoryFilter && { category_id: Number(categoryFilter) }),
})
const { data, isLoading, isFetching } = useTopicExecutors({
...(topicFilter && { topic_id: Number(topicFilter) }),
...(userFilter && { user_id: Number(userFilter) }),
...(categoryFilter && { category_id: Number(categoryFilter) }),
...(targetSystemFilter && { target_system: targetSystemFilter }),
})
const { data: users } = useUsers({ limit: 1000 })
const { data: topics } = useTopics({ limit: 1000 })
const deleteExecutor = useDeleteTopicExecutor()
// Группируем по темам
const groups = useMemo(() => {
if (!data?.data) return []
return groupExecutorsByTopic(data.data)
}, [data])
// ✅ Опции для фильтров
const userOptions = users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const categoryOptions = categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions = (categoryFilter ? categoryTopics?.data : topics?.data)?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const targetSystemOptions = TARGET_SYSTEMS.map((s) => ({
value: s.value,
label: s.label,
}))
// ✅ Обработчик изменения фильтров - сбрасывает страницу и выделение
const handleFilterChange =
(setter: (value: string | null) => void) => (value: string | null) => {
setter(value)
// Если меняется категория, сбрасываем тему
if (setter === setCategoryFilter) {
setTopicFilter(null)
}
}
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
Вы уверены, что хотите удалить этого исполнителя?
Задачи по этой теме не будут назначаться данному пользователю.
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteExecutor.mutate(id),
})
}
const handleEditExecutor = (id: number) => {
const executor = data?.data?.find((e) => e.id === id)
if (executor) {
setEditExecutor(executor)
}
}
const handleAddExecutor = (group: TopicExecutorsGroup) => {
setPresetGroup(group)
setCreateModalOpened(true)
}
const handleCloseModal = () => {
setEditExecutor(null)
setCreateModalOpened(false)
setPresetGroup(null)
}
return (
{/* Заголовок - адаптирован под дизайн Hierarchies */}
Исполнители тем
Всего: {data?.data?.length || 0}
setViewMode(v as ViewMode)}
data={[
{ value: 'cards', label: 'Карточки' },
{ value: 'table', label: 'Таблица' },
]}
/>
}
onClick={() => {
setPresetGroup(null)
setCreateModalOpened(true)
}}
>
Добавить исполнителя
{/* Подсказка */}
} color="orange" variant="light">
Исполнители — это пользователи, которые выполняют задачи после согласования заявки.
Каждая тема может иметь несколько исполнителей с разными шагами.
Поле "Текст задачи" содержит инструкцию для исполнителя.
{/* ✅ Фильтры - адаптированы под дизайн Hierarchies */}
{/* Контент */}
{isLoading ? (
) : viewMode === 'cards' ? (
{groups.length === 0 ? (
Исполнители не найдены
) : (
groups.map((group) => (
))
)}
) : (
ID
Тема
Исполнитель
Шаг
Задача
Система
Файл
Статус
Действия
{data?.data?.length === 0 ? (
Исполнители не найдены
) : (
data?.data?.map((executor) => (
{executor.id}
{executor.topic?.name || '—'}
{executor.topic?.code}
{executor.user?.full_name || '—'}
{executor.user?.department?.name}
#{executor.step_order}
{executor.task_text || '—'}
{TARGET_SYSTEM_LABELS[executor.target_system || ''] || executor.target_system}
{executor.require_file ? (
) : (
—
)}
: }
>
{executor.is_active ? 'Активен' : 'Неактивен'}
setEditExecutor(executor)}
>
handleDelete(executor.id!)}
>
))
)}
)}
{isFetching && !isLoading && (
)}
{/* Модальные окна */}
)
}
-----END src/pages/topicExecutors/TopicExecutorsPage.tsx-----
File: src/pages/topicExecutors/components/TopicExecutorEditModal.tsx
Lines: 233
-----BEGIN src/pages/topicExecutors/components/TopicExecutorEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
Select,
NumberInput,
Textarea,
Switch,
Group,
Button,
Text,
Loader,
Center,
Badge,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
useCreateTopicExecutor,
useUpdateTopicExecutor
} from '@/features/topicExecutors/hooks/useTopicExecutors'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useTopics } from '@/features/topics/hooks/useTopics'
import { TARGET_SYSTEMS } from '@/features/topicExecutors/utils'
import type { ApprovalTopicExecutor } from '@/types/api'
import type { TopicExecutorsGroup } from '@/features/topicExecutors/utils'
interface TopicExecutorEditModalProps {
executor: ApprovalTopicExecutor | null
presetGroup?: TopicExecutorsGroup | null
opened: boolean
onClose: () => void
}
export default function TopicExecutorEditModal({
executor,
presetGroup,
opened,
onClose
}: TopicExecutorEditModalProps) {
const createExecutor = useCreateTopicExecutor()
const updateExecutor = useUpdateTopicExecutor()
const { data: users } = useUsers({ limit: 1000 })
const { data: topics } = useTopics({ limit: 1000 })
const isEditMode = executor !== null
const form = useForm({
initialValues: {
topic_id: null as number | null,
user_id: null as number | null,
step_order: 0,
require_file: false,
task_text: '',
is_active: true,
target_system: 'all',
},
validate: {
topic_id: (v) => (v === null ? 'Выберите тему' : null),
user_id: (v) => (v === null ? 'Выберите исполнителя' : null),
},
})
// Заполняем форму данными
useEffect(() => {
if (executor) {
form.setValues({
topic_id: executor.topic_id || null,
user_id: executor.user_id || null,
step_order: executor.step_order ?? 0,
require_file: executor.require_file ?? false,
task_text: executor.task_text || '',
is_active: executor.is_active ?? true,
target_system: executor.target_system || 'all',
})
} else if (presetGroup) {
// Предзаполняем из группы
form.setValues({
topic_id: presetGroup.topicId,
user_id: null,
step_order: presetGroup.executors.length,
require_file: false,
task_text: '',
is_active: true,
target_system: 'all',
})
} else {
form.reset()
}
}, [executor, presetGroup, opened])
// Опции
const userOptions = users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
description: u.department?.name,
})) || []
const topicOptions = topics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
description: t.category?.name,
})) || []
const targetSystemOptions = TARGET_SYSTEMS.map((s) => ({
value: s.value,
label: s.label,
}))
const handleSubmit = async (values: typeof form.values) => {
const payload = {
topic_id: values.topic_id!,
user_id: values.user_id!,
step_order: values.step_order,
require_file: values.require_file,
task_text: values.task_text || null,
is_active: values.is_active,
target_system: values.target_system,
}
if (isEditMode && executor?.id) {
await updateExecutor.mutateAsync({
id: executor.id,
...payload,
})
} else {
await createExecutor.mutateAsync(payload)
}
onClose()
}
const isSubmitting = createExecutor.isPending || updateExecutor.isPending
return (
{isEditMode ? 'Редактирование исполнителя' : 'Добавление исполнителя'}
{executor && ID: {executor.id} }
}
size="lg"
>
{/* Тема */}
form.setFieldValue('topic_id', v ? Number(v) : null)}
searchable
required
disabled={isEditMode || !!presetGroup}
description="Тема, для которой назначается исполнитель"
/>
{/* Исполнитель */}
form.setFieldValue('user_id', v ? Number(v) : null)}
searchable
required
description="Пользователь, который будет выполнять задачу"
/>
{/* Порядок шага */}
form.setFieldValue('step_order', Number(v) || 0)}
min={0}
required
/>
{/* Целевая система */}
form.setFieldValue('target_system', v || 'all')}
description="Система, в которой будет выполняться задача"
/>
{/* Текст задачи */}
form.setFieldValue('task_text', e.currentTarget.value)}
minRows={3}
description="Инструкция для исполнителя"
/>
{/* Требует файл */}
form.setFieldValue('require_file', e.currentTarget.checked)}
/>
{/* Активен */}
form.setFieldValue('is_active', e.currentTarget.checked)}
/>
{/* Кнопки */}
Отмена
{isEditMode ? 'Сохранить' : 'Добавить'}
)
}
-----END src/pages/topicExecutors/components/TopicExecutorEditModal.tsx-----
File: src/pages/topicExecutors/components/TopicExecutorsCard.tsx
Lines: 218
-----BEGIN src/pages/topicExecutors/components/TopicExecutorsCard.tsx-----
import {
Paper,
Group,
Stack,
Text,
Badge,
ActionIcon,
Avatar,
Box,
Tooltip,
Switch,
} from '@mantine/core'
import {
IconPencil,
IconTrash,
IconUserPlus,
IconBriefcase,
IconCategory,
IconFile,
IconCheck,
IconX,
} from '@tabler/icons-react'
import type { TopicExecutorsGroup } from '@/features/topicExecutors/utils'
import { TARGET_SYSTEM_LABELS, TARGET_SYSTEM_COLORS } from '@/features/topicExecutors/utils'
interface TopicExecutorsCardProps {
group: TopicExecutorsGroup
onEditExecutor: (executorId: number) => void
onDeleteExecutor: (executorId: number) => void
onAddExecutor: (group: TopicExecutorsGroup) => void
}
export default function TopicExecutorsCard({
group,
onEditExecutor,
onDeleteExecutor,
onAddExecutor,
}: TopicExecutorsCardProps) {
return (
{/* Заголовок темы */}
{group.topicName}
{group.topicCode}
{group.categoryName && (
}
mt={4}
>
{group.categoryName}
)}
onAddExecutor(group)}
>
{/* Список исполнителей */}
{group.executors.length === 0 ? (
Исполнители не назначены
) : (
{group.executors.map((executor, index) => (
onEditExecutor(executor.id!)}
className="hover-shadow"
>
{/* Верхняя строка: исполнитель и метаданные */}
Шаг #{executor.step_order ?? index}
{executor.user?.full_name?.charAt(0) || '?'}
{executor.user?.full_name || '—'}
{executor.user?.department?.name && (
{executor.user.department.name}
)}
{/* Целевая система */}
{executor.target_system && (
{TARGET_SYSTEM_LABELS[executor.target_system] || executor.target_system}
)}
{/* Требует файл */}
{executor.require_file && (
}
>
Файл
)}
{/* Активен/неактивен */}
: }
>
{executor.is_active ? 'Активен' : 'Неактивен'}
{/* Кнопки действий */}
{
e.stopPropagation()
onEditExecutor(executor.id!)
}}
>
{
e.stopPropagation()
onDeleteExecutor(executor.id!)
}}
>
{/* Текст задачи */}
{executor.task_text && (
Задача:
{executor.task_text}
)}
))}
)}
)
}
-----END src/pages/topicExecutors/components/TopicExecutorsCard.tsx-----
File: src/pages/topics/TopicsPage.tsx
Lines: 268
-----BEGIN src/pages/topics/TopicsPage.tsx-----
import { useState } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Select,
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 { useTopics, useDeleteTopic } from '@/features/topics/hooks/useTopics'
import { useCategories } from '@/features/categories/hooks/useCategories'
import TopicEditModal from './components/TopicEditModal'
const LIMIT = 20
export default function TopicsPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [categoryFilter, setCategoryFilter] = useState(null)
const [activeFilter, setActiveFilter] = useState(null)
const [editTopicId, setEditTopicId] = useState(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const { data, isLoading, isFetching } = useTopics({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(search && { name: search }),
...(categoryFilter && { category_id: Number(categoryFilter) }),
...(activeFilter !== null && { is_active: activeFilter }),
})
const { data: categories } = useCategories({ limit: 1000 })
const deleteTopic = useDeleteTopic()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const categoryOptions = categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
Вы уверены, что хотите удалить эту тему? Связанные данные (исполнители, иерархия) могут быть затронуты.
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteTopic.mutate(id),
})
}
return (
Темы согласований
Всего: {data?.total_count || 0}
}
onClick={() => setCreateModalOpened(true)}
>
Создать тему
{/* Фильтры */}
}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
style={{ flex: 1 }}
/>
{
setCategoryFilter(v)
setPage(1)
}}
clearable
searchable
style={{ minWidth: 200 }}
/>
{
setActiveFilter(e.currentTarget.checked ? true : null)
setPage(1)
}}
/>
{/* Таблица */}
{isLoading ? (
) : (
<>
ID
Название
Категория
Код
Параметры
Статус
Действия
{data?.data?.length === 0 ? (
Темы не найдены
) : (
(data?.data || []).map((topic) => (
{topic.id}
{topic.name}
{topic.category?.name || '—'}
{topic.code}
{topic.duration_type && (
{topic.duration_type}
)}
{topic.time_type && (
{topic.time_type}
)}
{topic.payment_type && (
{topic.payment_type}
)}
{topic.requires_file && (
Файл
)}
{topic.is_active ? 'Активна' : 'Неактивна'}
setEditTopicId(topic.id!)}
>
handleDelete(topic.id!)}
>
))
)}
{totalPages > 1 && (
Страница {page} из {totalPages}
)}
>
)}
{isFetching && !isLoading && (
)}
setEditTopicId(null)}
/>
setCreateModalOpened(false)}
/>
)
}
-----END src/pages/topics/TopicsPage.tsx-----
File: src/pages/topics/components/TopicEditModal.tsx
Lines: 348
-----BEGIN src/pages/topics/components/TopicEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Textarea,
Select,
Switch,
Group,
Button,
Text,
Loader,
Center,
Badge,
Paper,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
useTopic,
useCreateTopic,
useUpdateTopic
} from '@/features/topics/hooks/useTopics'
import { useCategories } from '@/features/categories/hooks/useCategories'
import {
DURATION_TYPES,
TIME_TYPES,
PAYMENT_TYPES,
APPROVAL_MODES,
} from '@/features/topics/constants'
interface TopicEditModalProps {
topicId: number | null
opened: boolean
onClose: () => void
}
export default function TopicEditModal({
topicId,
opened,
onClose
}: TopicEditModalProps) {
const { data: topic, isLoading: topicLoading } = useTopic(topicId)
const { data: categories } = useCategories({ limit: 1000 })
const createTopic = useCreateTopic()
const updateTopic = useUpdateTopic()
const isEditMode = topicId !== null
const form = useForm({
initialValues: {
category_id: null as number | null,
name: '',
code: '',
duration_type: '',
time_type: '',
payment_type: '',
template: '',
allows_file: false,
is_active: true,
allow_approver_selection: false,
first_approver_role_code: '',
allow_observer_selection: false,
// 🆕 Делегирование обязанностей на время отсутствия — актуально
// для тем категорий "Отгул"/"Отпуск"/"Больничный".
allow_delegation_selection: false,
approval_mode: 'sequential',
require_approver_comment: false,
requires_file: false,
require_observer_selection: false,
instructions: '',
is_tree_root: false,
},
validate: {
category_id: (v) => (v === null ? 'Выберите категорию' : null),
name: (v: string | any[]) => (v.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
code: (v: string | any[]) => {
if (v.length < 2) return 'Код должен содержать минимум 2 символа'
if (!/^[a-z0-9_]+$/.test(v as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
return null
},
},
})
useEffect(() => {
if (topic) {
form.setValues({
category_id: topic.category_id || null,
name: topic.name || '',
code: topic.code || '',
duration_type: topic.duration_type || '',
time_type: topic.time_type || '',
payment_type: topic.payment_type || '',
template: topic.template || '',
allows_file: topic.allows_file ?? false,
is_active: topic.is_active ?? true,
allow_approver_selection: topic.allow_approver_selection ?? false,
first_approver_role_code: topic.first_approver_role_code || '',
allow_observer_selection: topic.allow_observer_selection ?? false,
allow_delegation_selection: topic.allow_delegation_selection ?? false,
approval_mode: topic.approval_mode || 'sequential',
require_approver_comment: topic.require_approver_comment ?? false,
requires_file: topic.requires_file ?? false,
require_observer_selection: topic.require_observer_selection ?? false,
instructions: topic.instructions || '',
})
} else if (!isEditMode) {
form.reset()
}
}, [topic, isEditMode])
const categoryOptions = categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const handleSubmit = async (values: typeof form.values) => {
const payload = {
category_id: values.category_id!,
name: values.name,
code: values.code,
duration_type: values.duration_type || undefined,
time_type: values.time_type || undefined,
payment_type: values.payment_type || undefined,
template: values.template || null,
allows_file: values.allows_file,
is_active: values.is_active,
allow_approver_selection: values.allow_approver_selection,
first_approver_role_code: values.first_approver_role_code || null,
allow_observer_selection: values.allow_observer_selection,
allow_delegation_selection: values.allow_delegation_selection,
approval_mode: values.approval_mode,
require_approver_comment: values.require_approver_comment,
requires_file: values.requires_file,
require_observer_selection: values.require_observer_selection,
instructions: values.instructions || null,
}
if (isEditMode && topicId) {
await updateTopic.mutateAsync({ id: topicId, ...payload })
} else {
await createTopic.mutateAsync(payload)
}
onClose()
}
const isLoading = topicLoading
const isSubmitting = createTopic.isPending || updateTopic.isPending
return (
{isEditMode ? 'Редактирование темы' : 'Создание темы'}
{topic && ID: {topic.id} }
}
size="xl"
>
{isLoading ? (
) : (
{/* Основные поля */}
Основные параметры
form.setFieldValue('category_id', v ? Number(v) : null)}
searchable
required
/>
{/* Типы */}
Типы и параметры
form.setFieldValue('duration_type', v || '')}
clearable
/>
form.setFieldValue('time_type', v || '')}
clearable
/>
form.setFieldValue('payment_type', v || '')}
clearable
/>
form.setFieldValue('approval_mode', v || 'sequential')}
/>
{/* Настройки согласования */}
Настройки согласования
form.setFieldValue('allow_approver_selection', e.currentTarget.checked)}
/>
form.setFieldValue('first_approver_role_code', e.currentTarget.value)}
/>
form.setFieldValue('allow_observer_selection', e.currentTarget.checked)}
/>
form.setFieldValue('require_observer_selection', e.currentTarget.checked)}
disabled={!form.values.allow_observer_selection}
/>
form.setFieldValue('require_approver_comment', e.currentTarget.checked)}
/>
form.setFieldValue('allow_delegation_selection', e.currentTarget.checked)}
/>
{/* Файлы */}
Файлы
form.setFieldValue('allows_file', e.currentTarget.checked)}
/>
form.setFieldValue('requires_file', e.currentTarget.checked)}
disabled={!form.values.allows_file}
/>
{/* Статус */}
form.setFieldValue('is_active', e.currentTarget.checked)}
/>
Отмена
{isEditMode ? 'Сохранить' : 'Создать'}
)}
)
}
-----END src/pages/topics/components/TopicEditModal.tsx-----
File: src/pages/users/UsersPage.tsx
Lines: 330
-----BEGIN src/pages/users/UsersPage.tsx-----
import { useState, useMemo } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Text,
TextInput,
Select,
MultiSelect, // ✅ Добавлен
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Modal,
Button,
} from '@mantine/core'
import { 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 { useAuth } from '@/hooks/useAuth'
const LIMIT = 20
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 [editUserId, setEditUserId] = useState(null)
const [deleteUserId, setDeleteUserId] = useState(null)
const { user: currentUser } = useAuth()
const isRootAdmin = currentUser?.is_root === true
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 }), // ✅ Передаём массив
})
const { data: departments } = useDepartments()
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 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 handleDelete = async () => {
if (!deleteUserId) return
await deleteUser.mutateAsync(deleteUserId)
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',
},
}}
/>
{
setDepartmentFilter(v)
setPage(1)
}}
clearable
style={{ minWidth: 200 }}
/>
{
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}
)}
>
)}
{isFetching && !isLoading && (
)}
setEditUserId(null)}
/>
setDeleteUserId(null)}
title="Подтверждение удаления"
size="md"
>
Вы уверены, что хотите удалить пользователя? Это действие нельзя отменить.
setDeleteUserId(null)}>
Отмена
Удалить
)
}
function UserStatusBadge({ isBlocked, isFired }: { isBlocked?: boolean; isFired?: boolean }) {
if (isFired) return Уволен
if (isBlocked) return Заблокирован
return Активен
}
-----END src/pages/users/UsersPage.tsx-----
File: src/theme.ts
Lines: 17
-----BEGIN src/theme.ts-----
import { createTheme } from '@mantine/core'
export const theme = createTheme({
primaryColor: 'blue',
fontFamily: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif',
components: {
Button: {
defaultProps: {
size: 'sm',
},
},
Table: {
defaultProps: {
fontSize: 'sm',
},
},
},
})
-----END src/theme.ts-----
File: src/types/api.ts
Lines: 333
-----BEGIN src/types/api.ts-----
export interface User {
id?: number
telegram_id?: number
username?: string
full_name: string
language_code?: string
department_id?: number
is_blocked?: boolean
is_fired?: boolean
blocked_at?: string
last_login?: string
created_at?: string
updated_at?: string
department?: Department
user_roles?: UserRole[]
}
export interface Department {
id?: number
name: string
code: string
description?: string
is_active?: boolean
created_at?: string
updated_at?: string
}
export interface Role {
id?: number
name: string
code: string
is_default?: boolean
is_director?: boolean
is_approver?: boolean
is_controller?: boolean
is_observer?: boolean
is_executor?: boolean
description?: string
created_at?: string
updated_at?: string
}
export interface UserRole {
id?: number
user_id: number
role_id: number
created_at?: string
updated_at?: string
role?: Role
}
export interface Admin {
id?: number
login: string
name?: string
is_root?: boolean
is_observer?: boolean // 🆕
telegram_id?: number // 🆕
telegram_user?: User // 🆕
created_at?: string
last_login?: string
last_ip_login?: string
is_blocked?: boolean
password?: string
}
// 🆕 Типы для заявок
export interface ApprovalFile {
id?: number
approval_id?: number
file_base64?: string
file_name?: string
attached_by_id?: number
created_at?: string
}
export interface ApprovalStep {
id?: number
approval_id?: number
approver_id?: number
step_order?: number
status?: string
comment?: string
approver_name_snapshot?: string
approver_department_snapshot?: string
acted_at?: string
created_at?: string
updated_at?: string
returned_at?: string
approver?: User
}
export interface ApprovalTopicCategory {
id?: number
name: string
code: string
description?: string
is_active?: boolean
created_at?: string
updated_at?: string
topics?: ApprovalTopic[]
}
export interface ApprovalTopic {
id?: number
category_id?: number
name: string
code: string
approval_mode?: string
duration_type?: string
time_type?: string
payment_type?: string
template?: string
first_approver_role_code?: string
allows_file?: boolean
allow_approver_selection?: boolean
allow_observer_selection?: boolean
require_approver_comment?: boolean
requires_file?: boolean
require_observer_selection?: boolean
is_active?: boolean
created_at?: string
updated_at?: string
instructions?: string
category?: ApprovalTopicCategory
}
export interface Approval {
id?: number
initiator_id?: number
topic_id?: number
department_id?: number
content?: string
status?: string
revoked_by_id?: number
revoked_at?: string
created_at?: string
updated_at?: string
metadata?: string
revision_comment?: string
revision_by_id?: number
revision_at?: string
revision_count?: number
files?: ApprovalFile[]
initiator?: User
topic?: ApprovalTopic
department?: Department
revoked_by?: User
steps?: ApprovalStep[]
}
export interface ApiResponse {
data: T
total_count?: number
}
export interface LoginRequest {
login: string
password: string
}
export interface LoginResponse {
token: string
}
export interface Permission {
id?: number
role_id?: number
topic_category_id?: number | null
topic_id?: number | null
action?: string
created_at?: string
updated_at?: string
role?: Role
topic_category?: ApprovalTopicCategory
topic?: ApprovalTopic
}
export interface UserHierarchy {
id?: number
subordinate_id?: number
approver_id?: number
department_id?: number
topic_category_id?: number | null
topic_id?: number | null
priority?: number
created_at?: string
updated_at?: string
subordinate?: User
approver?: User
department?: Department
target_system?: string | null
}
export interface ApprovalTopicExecutor {
id?: number
topic_id?: number
user_id?: number
step_order?: number
require_file?: boolean
task_text?: string
is_active?: boolean
target_system?: string
created_at?: string
updated_at?: string
topic?: ApprovalTopic
user?: User
}
export interface ApprovalTopic {
id?: number
category_id?: number
name: string
code: string
duration_type?: string
time_type?: string
payment_type?: string
template?: string
allows_file?: boolean
is_active?: boolean
allow_approver_selection?: boolean
first_approver_role_code?: string
allow_observer_selection?: boolean
approval_mode?: string
allow_delegation_selection?: boolean
require_approver_comment?: boolean
requires_file?: boolean
require_observer_selection?: boolean
instructions?: string
created_at?: string
updated_at?: string
category?: ApprovalTopicCategory
}
export interface Admin {
id?: number
login: string
name?: string
is_root?: boolean
created_at?: string
last_login?: string
last_ip_login?: string
is_blocked?: boolean
password?: string
}
export interface ApprovalFile {
id?: number
approval_id?: number
file_base64?: string
file_name?: string
attached_by_id?: number
task_id?: number
created_at?: string
}
export interface ApprovalTask {
id?: number
approval_id?: number
executor_id?: number
task_text?: string
status?: string
step_order?: number
require_file?: boolean
topic_executor_id?: number
completed_at?: string
created_at?: string
updated_at?: string
approval?: Approval
executor?: User
files?: ApprovalFile[]
}
export interface ApprovalFlowNode {
id?: number
topic_id?: number
parent_id?: number | null
key: string
category_id: number
message_template?: string | null
code_template?: string | null
label: string
data_key?: string | null
data_value?: string | null
is_input?: boolean
input_key?: string | null
input_hint?: string | null
is_multi_select?: boolean
multi_select_key?: string | null
multi_select_value?: string | null
topic_code?: string | null
sort_order?: number
created_at?: string
updated_at?: string
children?: ApprovalFlowNode[]
}
export interface TargetFilters {
user_ids?: number[]
role_ids?: number[]
role_type_flags?: string[] // 'director' | 'approver' | 'observer' | 'executor' | 'controller'
department_ids?: number[]
}
export interface NotificationRecipient {
id?: number
notification_id?: number
user_id?: number
status?: string // pending | sent | failed
error_message?: string
telegram_message_id?: number
sent_at?: string
created_at?: string
user?: User
}
export interface Notification {
id?: number
title: string
message_html: string
photo_base64?: string
photo_file_name?: string
target_filters?: string // JSON-строка от бэкенда
status?: string // pending | sending | completed | failed
total_count?: number
sent_count?: number
failed_count?: number
created_by_id?: number
created_at?: string
updated_at?: string
sent_at?: string
recipients?: NotificationRecipient[]
}
-----END src/types/api.ts-----
File: src/utils/date.ts
Lines: 26
-----BEGIN src/utils/date.ts-----
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
import 'dayjs/locale/ru'
dayjs.extend(utc)
dayjs.extend(timezone)
dayjs.locale('ru')
export const MSK_TZ = 'Europe/Moscow'
// Даты с бэкенда обычно приходят в UTC (ISO-строка с 'Z') — если форматировать
// их через голый dayjs(date).format(...), время покажется в часовом поясе
// БРАУЗЕРА администратора, а не по МСК. Эта функция всегда приводит к
// Europe/Moscow независимо от того, где физически находится админ.
export function formatMsk(
date: string | Date | null | undefined,
fmt: string = 'DD.MM.YYYY HH:mm'
): string {
if (!date) return '—'
return dayjs(date).tz(MSK_TZ).format(fmt)
}
// Текущее время по МСК — например, для имени скачиваемого файла отчёта.
export function mskNow() {
return dayjs().tz(MSK_TZ)
}
-----END src/utils/date.ts-----
File: src/vite-env.d.ts
Lines: 11
-----BEGIN src/vite-env.d.ts-----
///
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string
readonly VITE_API_KEY: string
readonly VITE_APP_NAME: string
readonly VITE_APP_VERSION: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
-----END src/vite-env.d.ts-----
File: vite.config.ts
Lines: 50
-----BEGIN vite.config.ts-----
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
server: {
port: 3000,
allowedHosts: true,
proxy: {
'/api': {
target: 'http://0.0.0.0:1726', // Порт твоего бэкенда
changeOrigin: true,
secure: false,
// Раскомментируй, если нужно видеть реальные запросы:
// configure: (proxy, options) => {
// proxy.on('proxyReq', (proxyReq, req, res) => {
// console.log('Proxying:', req.method, req.url)
// })
// },
},
},
},
build: {
outDir: 'dist',
sourcemap: false,
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
if (id.includes('react') || id.includes('react-dom') || id.includes('react-router-dom')) {
return 'vendor'
}
if (id.includes('@mantine')) {
return 'ui'
}
if (id.includes('@tanstack') || id.includes('axios')) {
return 'query'
}
return 'vendor-misc'
}
},
},
},
},
})
-----END vite.config.ts-----