├── .env ├── .env.example ├── .gitea │ ├── workflows │ │ ├── deploy-frontend.yml ├── .gitignore ├── README.md ├── eslint.config.js ├── index.html ├── package-lock.json ├── package.json ├── public │ ├── favicon.svg │ ├── icons.svg ├── src │ ├── App.css │ ├── App.tsx │ ├── api │ │ ├── adminLogs.ts │ │ ├── admins.ts │ │ ├── approvalTasks.ts │ │ ├── approvals.ts │ │ ├── auth.ts │ │ ├── categories.ts │ │ ├── client.ts │ │ ├── dashboard.ts │ │ ├── departments.ts │ │ ├── flowNodes.ts │ │ ├── hierarchies.ts │ │ ├── notifications.ts │ │ ├── permissions.ts │ │ ├── roles.ts │ │ ├── time.ts │ │ ├── topicExecutors.ts │ │ ├── topics.ts │ │ ├── userRoles.ts │ │ ├── users.ts │ ├── assets │ │ ├── hero.png │ │ ├── react.svg │ │ ├── vite.svg │ ├── components │ │ ├── CopyRolesModal.tsx │ │ ├── DiagnosticErrorBoundary.tsx │ │ ├── Layout │ │ │ ├── Header.tsx │ │ │ ├── MainLayout.tsx │ │ │ ├── Sidebar.tsx │ │ ├── TopicGapsModal.tsx │ │ ├── UserEditModal.tsx │ ├── features │ │ ├── adminLogs │ │ │ ├── hooks │ │ │ │ ├── useAdminLogs.ts │ │ ├── admins │ │ │ ├── hooks │ │ │ │ ├── useAdmins.ts │ │ ├── approvalTasks │ │ │ ├── const.ts │ │ │ ├── hooks │ │ │ │ ├── useApprovalTasks.ts │ │ ├── approvals │ │ │ ├── hooks │ │ │ │ ├── useApprovals.ts │ │ ├── categories │ │ │ ├── hooks │ │ │ │ ├── useCategories.ts │ │ ├── departments │ │ │ ├── components │ │ │ │ ├── DepartmentEditModal.tsx │ │ │ ├── hooks │ │ │ │ ├── useDepartments.ts │ │ ├── flowNodes │ │ │ ├── hooks │ │ │ │ ├── useFlowNodes.ts │ │ │ ├── utils │ │ │ │ ├── flattenTree.ts │ │ │ │ ├── treeWalk.ts │ │ ├── hierarchies │ │ │ ├── hooks │ │ │ │ ├── useHierarchies.ts │ │ │ │ ├── useSystemOptions.ts │ │ │ ├── utils.ts │ │ ├── notifications │ │ │ ├── hooks │ │ │ │ ├── useNotifications.ts │ │ │ ├── utils │ │ │ │ ├── telegramHtml.ts │ │ ├── permissions │ │ │ ├── constants.ts │ │ │ ├── hooks │ │ │ │ ├── usePermissions.ts │ │ ├── roles │ │ │ ├── hooks │ │ │ │ ├── useAllRoles.ts │ │ │ │ ├── useRoles.ts │ │ ├── topicExecutors │ │ │ ├── hooks │ │ │ │ ├── useTopicExecutors.ts │ │ │ ├── utils.ts │ │ ├── topics │ │ │ ├── constants.ts │ │ │ ├── hooks │ │ │ │ ├── useTopics.ts │ │ ├── users │ │ │ ├── hooks │ │ │ │ ├── useDepartments.ts │ │ │ │ ├── useRoles.ts │ │ │ │ ├── useUserRoles.ts │ │ │ │ ├── useUsers.ts │ ├── hooks │ │ ├── useAuth.ts │ ├── index.css │ ├── main.tsx │ ├── pages │ │ ├── Dashboard.tsx │ │ ├── DepartmentsPage.tsx │ │ ├── Login.tsx │ │ ├── adminLogs │ │ │ ├── AdminLogsPage.tsx │ │ │ ├── components │ │ │ │ ├── AdminLogDetailModal.tsx │ │ ├── admins │ │ │ ├── AdminsPage.tsx │ │ │ ├── components │ │ │ │ ├── CreateAdminModal.tsx │ │ │ │ ├── EditAdminModal.tsx │ │ ├── approvalTasks │ │ │ ├── ApprovalTasksPage.tsx │ │ │ ├── components │ │ │ │ ├── ApprovalTaskDetailsModal.tsx │ │ ├── approvals │ │ │ ├── ApprovalsPage.tsx │ │ │ ├── components │ │ │ │ ├── ApprovalDetailsModal.tsx │ │ │ │ ├── FilePreviewModal.tsx │ │ ├── categories │ │ │ ├── CategoriesPage.tsx │ │ │ ├── components │ │ │ │ ├── CategoryEditModal.tsx │ │ ├── flowNodes │ │ │ ├── FlowTreeGuidePage.tsx │ │ │ ├── FlowTreePage.tsx │ │ │ ├── components │ │ │ │ ├── CategoryCreateModal.tsx │ │ │ │ ├── DataFlowExplainer.tsx │ │ │ │ ├── FlowNodeEditModal.tsx │ │ │ │ ├── SortableFlowTree.tsx │ │ │ │ ├── TreeHealthPanel.tsx │ │ ├── hierarchies │ │ │ ├── HierarchiesPage.tsx │ │ │ ├── components │ │ │ │ ├── ChainDuplicateModal.tsx │ │ │ │ ├── ChainVisualization.tsx │ │ │ │ ├── HierarchyEditModal.tsx │ │ │ │ ├── PersonDuplicateModal.tsx │ │ ├── notifications │ │ │ ├── NotificationsPage.tsx │ │ │ ├── components │ │ │ │ ├── NotificationDetailsModal.tsx │ │ │ │ ├── NotificationsHistoryTable.tsx │ │ │ │ ├── SendNotificationForm.tsx │ │ ├── permissions │ │ │ ├── PermissionsPage.tsx │ │ │ ├── components │ │ │ │ ├── PermissionEditModal.tsx │ │ ├── roles │ │ │ ├── RolesPage.tsx │ │ │ ├── components │ │ │ │ ├── RoleEditModal.tsx │ │ ├── settings │ │ │ ├── SettingsPage.tsx │ │ ├── topicExecutors │ │ │ ├── TopicExecutorsPage.tsx │ │ │ ├── components │ │ │ │ ├── TopicExecutorEditModal.tsx │ │ │ │ ├── TopicExecutorsCard.tsx │ │ ├── topics │ │ │ ├── TopicsPage.tsx │ │ │ ├── components │ │ │ │ ├── TopicEditModal.tsx │ │ ├── users │ │ │ ├── UsersPage.tsx │ ├── theme.ts │ ├── types │ │ ├── api.ts │ ├── utils │ │ ├── date.ts │ ├── vite-env.d.ts ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.node.json ├── vite.config.ts File: eslint.config.js Lines: 22 -----BEGIN eslint.config.js----- import js from '@eslint/js' import globals from 'globals' import reactHooks from 'eslint-plugin-react-hooks' import reactRefresh from 'eslint-plugin-react-refresh' import tseslint from 'typescript-eslint' import { defineConfig, globalIgnores } from 'eslint/config' export default defineConfig([ globalIgnores(['dist']), { files: ['**/*.{ts,tsx}'], extends: [ js.configs.recommended, tseslint.configs.recommended, reactHooks.configs.flat.recommended, reactRefresh.configs.vite, ], languageOptions: { globals: globals.browser, }, }, ]) -----END eslint.config.js----- File: src/App.css Lines: 184 -----BEGIN src/App.css----- .counter { font-size: 16px; padding: 5px 10px; border-radius: 5px; color: var(--accent); background: var(--accent-bg); border: 2px solid transparent; transition: border-color 0.3s; margin-bottom: 24px; &:hover { border-color: var(--accent-border); } &:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } } .hero { position: relative; .base, .framework, .vite { inset-inline: 0; margin: 0 auto; } .base { width: 170px; position: relative; z-index: 0; } .framework, .vite { position: absolute; } .framework { z-index: 1; top: 34px; height: 28px; transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg) scale(1.4); } .vite { z-index: 0; top: 107px; height: 26px; width: auto; transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg) scale(0.8); } } #center { display: flex; flex-direction: column; gap: 25px; place-content: center; place-items: center; flex-grow: 1; @media (max-width: 1024px) { padding: 32px 20px 24px; gap: 18px; } } #next-steps { display: flex; border-top: 1px solid var(--border); text-align: left; & > div { flex: 1 1 0; padding: 32px; @media (max-width: 1024px) { padding: 24px 20px; } } .icon { margin-bottom: 16px; width: 22px; height: 22px; } @media (max-width: 1024px) { flex-direction: column; text-align: center; } } #docs { border-right: 1px solid var(--border); @media (max-width: 1024px) { border-right: none; border-bottom: 1px solid var(--border); } } #next-steps ul { list-style: none; padding: 0; display: flex; gap: 8px; margin: 32px 0 0; .logo { height: 18px; } a { color: var(--text-h); font-size: 16px; border-radius: 6px; background: var(--social-bg); display: flex; padding: 6px 12px; align-items: center; gap: 8px; text-decoration: none; transition: box-shadow 0.3s; &:hover { box-shadow: var(--shadow); } .button-icon { height: 18px; width: 18px; } } @media (max-width: 1024px) { margin-top: 20px; flex-wrap: wrap; justify-content: center; li { flex: 1 1 calc(50% - 8px); } a { width: 100%; justify-content: center; box-sizing: border-box; } } } #spacer { height: 88px; border-top: 1px solid var(--border); @media (max-width: 1024px) { height: 48px; } } .ticks { position: relative; width: 100%; &::before, &::after { content: ''; position: absolute; top: -4.5px; border: 5px solid transparent; } &::before { left: 0; border-left-color: var(--border); } &::after { right: 0; border-right-color: var(--border); } } -----END src/App.css----- File: src/App.tsx Lines: 78 -----BEGIN src/App.tsx----- import { Routes, Route, Navigate } from 'react-router-dom' import MainLayout from './components/Layout/MainLayout' import Login from './pages/Login' import Dashboard from './pages/Dashboard' import UsersPage from './pages/users/UsersPage' import RolesPage from './pages/roles/RolesPage' import ApprovalsPage from './pages/approvals/ApprovalsPage' import { useAuth } from './hooks/useAuth' import { Loader, Center, Text } from '@mantine/core' import DepartmentsPage from "@/pages/DepartmentsPage.tsx" import PermissionsPage from './pages/permissions/PermissionsPage' import HierarchiesPage from './pages/hierarchies/HierarchiesPage' import TopicExecutorsPage from "@/pages/topicExecutors/TopicExecutorsPage.tsx" import CategoriesPage from "@/pages/categories/CategoriesPage.tsx" import React from "react" import TopicsPage from "@/pages/topics/TopicsPage.tsx" import SettingsPage from './pages/settings/SettingsPage' import AdminsPage from './pages/admins/AdminsPage' import ApprovalTasksPage from './pages/approvalTasks/ApprovalTasksPage' import FlowTreePage from "@/pages/flowNodes/FlowTreePage.tsx" import FlowTreeGuidePage from './pages/flowNodes/FlowTreeGuidePage' import NotificationsPage from "@/pages/notifications/NotificationsPage.tsx" import AdminLogsPage from './pages/adminLogs/AdminLogsPage' const Placeholder = ({ title }: { title: string }) => (
{title} Страница в разработке...
) function ProtectedRoute({ children }: { children: React.ReactNode }) { const { isAuthenticated, loading } = useAuth() if (loading) { return (
) } if (!isAuthenticated) { return } return <>{children} } function App() { return ( } /> }> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> ) } export default App -----END src/App.tsx----- File: src/api/adminLogs.ts Lines: 34 -----BEGIN src/api/adminLogs.ts----- import apiClient from './client' import type { ApiResponse } from '@/types/api' export interface AdminActionLog { id: number admin_id: number admin_login: string action: 'create' | 'update' | 'delete' entity_type: string entity_id?: number description: string metadata?: string created_at: string } export interface AdminLogsListParams { offset?: number limit?: number admin_id?: number admin_login?: string action?: string entity_type?: string entity_id?: number date_from?: string date_to?: string search?: string } export const adminLogsApi = { getList: (params: AdminLogsListParams = {}) => apiClient.get>('/admin-logs', { params }), delete: (id: number) => apiClient.delete(`/admin-logs/${id}`), } -----END src/api/adminLogs.ts----- File: src/api/admins.ts Lines: 39 -----BEGIN src/api/admins.ts----- import apiClient from './client' import type { Admin, ApiResponse } from '@/types/api' export interface AdminsListParams { offset?: number limit?: number is_blocked?: boolean login?: string } export interface CreateAdminRequest { login: string name?: string is_root?: boolean is_observer?: boolean // 🆕 telegram_id?: number // 🆕 } export interface UpdateAdminRequest { id: number name?: string is_blocked?: boolean is_root?: boolean is_observer?: boolean // 🆕 telegram_id?: number | null // 🆕 } export const adminsApi = { getList: (params: AdminsListParams = {}) => apiClient.get>('/admin', { params }), create: (data: CreateAdminRequest) => apiClient.post('/admin', data), update: (data: UpdateAdminRequest) => apiClient.put('/admin', data), delete: (id: number) => apiClient.delete('/admin', { data: { id } }), } -----END src/api/admins.ts----- File: src/api/approvalTasks.ts Lines: 31 -----BEGIN src/api/approvalTasks.ts----- import apiClient from './client' import type { ApprovalTask, ApiResponse } from '@/types/api' export interface ApprovalTasksListParams { offset?: number limit?: number status?: string executor_id?: number approval_id?: number require_file?: boolean } export interface UpdateApprovalTaskRequest { id: number status?: string task_text?: string require_file?: boolean } export const approvalTasksApi = { getList: (params: ApprovalTasksListParams = {}) => apiClient.get>('/approval-tasks', { params }), getById: (id: number) => apiClient.get(`/approval-tasks/${id}`), update: (data: UpdateApprovalTaskRequest) => apiClient.put('/approval-tasks', data), delete: (id: number) => apiClient.delete('/approval-tasks', { data: { id } }), } -----END src/api/approvalTasks.ts----- File: src/api/approvals.ts Lines: 197 -----BEGIN src/api/approvals.ts----- import apiClient from './client' import type { Approval, ApiResponse } from '@/types/api' export interface PlannedTask { id: number task_text: string executor_name?: string step_order: number } export interface ApprovalTaskItem { id: number task_text: string executor_name: string status: 'pending' | 'waiting' | 'completed' | 'cancelled' | 'cancellation' completed_at?: string } export interface ApprovalTasksResponse { topic_executors: PlannedTask[] tasks: ApprovalTaskItem[] has_task_error: boolean } export interface ApprovalsListParams { offset?: number limit?: number status?: string initiator_id?: number topic_id?: number // одиночный (для обратной совместимости) topic_ids?: number[] // 🆕 множественный выбор тем category_ids?: number[] // 🆕 множественный выбор категорий department_id?: number date_from?: string // 🆕 YYYY-MM-DD date_to?: string // 🆕 YYYY-MM-DD content?: string } export interface ApprovalsReportParams { user_id?: number date_from?: string // YYYY-MM-DD date_to?: string // YYYY-MM-DD all_access?: boolean } export interface UpdateApprovalRequest { id: number status?: string revision_comment?: string } export const approvalsApi = { getList: (params: ApprovalsListParams = {}) => { // Формируем query-параметры, корректно сериализуя массивы const query: Record = {} if (params.offset !== undefined) query.offset = params.offset if (params.limit !== undefined) query.limit = params.limit if (params.status) query.status = params.status if (params.initiator_id) query.initiator_id = params.initiator_id if (params.topic_id) query.topic_id = params.topic_id if (params.department_id) query.department_id = params.department_id if (params.content) query.content = params.content if (params.date_from) query.date_from = params.date_from if (params.date_to) query.date_to = params.date_to // 🆕 Массивы передаём через запятую: "1,2,3" if (params.topic_ids && params.topic_ids.length > 0) { query.topic_ids = params.topic_ids.join(',') } if (params.category_ids && params.category_ids.length > 0) { query.category_ids = params.category_ids.join(',') } return apiClient.get>('/approvals', { params: query }) }, getById: (id: number) => apiClient.get(`/approvals/${id}`), update: (data: UpdateApprovalRequest) => apiClient.put('/approvals', data), delete: (id: number) => apiClient.delete('/approvals', { data: { id } }), getTasks: (approvalId: number) => apiClient.get>(`/approvals/${approvalId}/tasks`), getForReport: (params: ApprovalsReportParams = {}) => apiClient.get>('/approvals/report', { params }), downloadReport: (params: ApprovalsReportParams = {}) => apiClient.get('/approvals/report/download', { params, responseType: 'blob', }), getAdditionalApprovers: (approvalId: number) => apiClient.get>(`/approvals/${approvalId}/additional-approvers`), getComments: (approvalId: number) => apiClient.get>(`/approvals/${approvalId}/comments`), getObservers: (approvalId: number) => apiClient.get>(`/approvals/${approvalId}/observers`), getRevocationRequest: (approvalId: number) => apiClient.get>(`/approvals/${approvalId}/revocation-request`), getFile: (approvalId: number, fileId: number) => apiClient.get(`/approvals/${approvalId}/files/${fileId}`, { responseType: 'blob', }), downloadFile: (approvalId: number, fileId: number, fileName: string) => { const token = localStorage.getItem('token') const timestamp = Math.floor(Date.now() / 1000).toString() const deviceId = localStorage.getItem('device_id') || 'admin-panel' const publicKey = import.meta.env.VITE_API_PUBLIC_KEY const privateKey = import.meta.env.VITE_API_PRIVATE_KEY const message = publicKey + ":" + timestamp const signature = CryptoJS.HmacSHA256(message, privateKey).toString(CryptoJS.enc.Hex) const url = `${apiClient.defaults.baseURL}/approvals/${approvalId}/files/${fileId}/download` const link = document.createElement('a') link.href = `${url}?_t=${timestamp}` link.setAttribute('download', fileName) fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, 'ApiKey': signature, 'X-Timestamp': timestamp, 'x-device-id': deviceId, }, }) .then(response => response.blob()) .then(blob => { const blobUrl = window.URL.createObjectURL(blob) link.href = blobUrl document.body.appendChild(link) link.click() link.remove() window.URL.revokeObjectURL(blobUrl) }) .catch(error => { console.error('Download error:', error) throw error }) }, } // ДОБАВИТЬ в src/api/approvals.ts (по образцу остальных методов approvalsApi // в этом файле — замените apiClient.get на ваш реальный вызов, если он // называется иначе): export interface AdditionalApprover { id: number approver_id: number approver_name: string status: 'pending' | 'approved' | 'rejected' comment?: string acted_at?: string } export interface ApprovalComment { id: number user_id: number user_name: string comment: string created_at?: string } export interface ApprovalObserver { id: number full_name: string } export interface RevocationApprover { approver_id: number approver_name: string status: 'pending' | 'approved' | 'rejected' } export interface RevocationRequest { id: number status: 'pending' | 'approved' | 'rejected' reason?: string requested_by_id: number requested_by_name: string approvers: RevocationApprover[] } -----END src/api/approvals.ts----- File: src/api/auth.ts Lines: 21 -----BEGIN src/api/auth.ts----- import apiClient from './client' import type { LoginRequest, LoginResponse, Admin } from '@/types/api' export interface UpdateProfileRequest { password?: string login?: string } export const authApi = { login: (data: LoginRequest) => apiClient.post('/auth/login', data), getProfile: () => apiClient.get('/admin/profile'), logout: () => apiClient.post('/auth/logout'), // 🆕 Смена пароля через существующий endpoint updateProfile: (data: UpdateProfileRequest) => apiClient.put('/admin/profile', data), } -----END src/api/auth.ts----- File: src/api/categories.ts Lines: 41 -----BEGIN src/api/categories.ts----- import apiClient from './client' import type { ApprovalTopicCategory, ApiResponse } from '@/types/api' export interface CategoriesListParams { offset?: number limit?: number is_active?: boolean name?: string code?: string } export interface CreateCategoryRequest { name: string code: string description?: string is_active?: boolean } export interface UpdateCategoryRequest { id: number name?: string code?: string description?: string is_active?: boolean } export const categoriesApi = { getList: (params: CategoriesListParams = {}) => apiClient.get>('/categories', { params }), getById: (id: number) => apiClient.get(`/categories/${id}`), create: (data: CreateCategoryRequest) => apiClient.post('/categories', data), update: (data: UpdateCategoryRequest) => apiClient.put('/categories', data), delete: (id: number) => apiClient.delete('/categories', { data: { id } }), } -----END src/api/categories.ts----- File: src/api/client.ts Lines: 166 -----BEGIN src/api/client.ts----- import axios from 'axios' import CryptoJS from 'crypto-js' import { timeApi } from './time' // 🔄 Offset между клиентом и сервером (в секундах) let serverTimeOffset = 0 let isSyncing = false let syncPromise: Promise | null = null // Функция генерации HMAC подписи function generateHmacSignature(publicKey: string, timestamp: string, privateKey: string): string { const message = publicKey + ":" + timestamp const hash = CryptoJS.HmacSHA256(message, privateKey) return hash.toString(CryptoJS.enc.Hex) } // 🆕 Функция для получения или создания device_id function getOrCreateDeviceId(): string { let deviceId = localStorage.getItem('device_id') if (!deviceId) { deviceId = crypto.randomUUID() localStorage.setItem('device_id', deviceId) } return deviceId } // 🆕 Синхронизация времени с сервером async function syncTimeWithServer(): Promise { if (isSyncing && syncPromise) { return syncPromise } isSyncing = true syncPromise = (async () => { try { const serverTime = await timeApi.getServerTime() const clientTimestamp = Math.floor(Date.now() / 1000) serverTimeOffset = serverTime.timestamp - clientTimestamp console.log('[Time] ✅ Synced with server', { serverTime: serverTime.iso, serverTimestamp: serverTime.timestamp, clientTimestamp, offset: serverTimeOffset, }) } catch (error) { console.warn('[Time] ⚠️ Failed to sync with server:', error) // При ошибке сбрасываем offset serverTimeOffset = 0 } finally { isSyncing = false syncPromise = null } })() return syncPromise } // 🆕 Получение timestamp с учётом offset function getCorrectedTimestamp(): string { return Math.floor(Date.now() / 1000 + serverTimeOffset).toString() } const apiClient = axios.create({ baseURL: '/api', headers: { 'Content-Type': 'application/json', }, }) // Interceptor для добавления токена и HMAC подписи apiClient.interceptors.request.use(async (config) => { console.log('[API] === Request interceptor started ===') // Добавляем JWT токен, если есть const token = localStorage.getItem('token') if (token) { config.headers.Authorization = `Bearer ${token}` console.log('[API] ✅ Added JWT token') } // Генерируем HMAC подпись с скорректированным timestamp const publicKey = import.meta.env.VITE_API_PUBLIC_KEY const privateKey = import.meta.env.VITE_API_PRIVATE_KEY const timestamp = getCorrectedTimestamp() if (!publicKey || !privateKey) { console.error('[API] ❌ Missing API keys in .env!') } else { const signature = generateHmacSignature(publicKey, timestamp, privateKey) config.headers.ApiKey = signature console.log('[API] ✅ Added HMAC signature') } config.headers['X-Timestamp'] = timestamp // Получаем или создаём device_id const deviceId = getOrCreateDeviceId() config.headers['x-device-id'] = deviceId console.log('[API] ✅ Added device_id:', deviceId) console.log('[API] 🕐 Using timestamp:', timestamp, 'offset:', serverTimeOffset) console.log('[API] === Request interceptor finished ===') return config }) // Interceptor для обработки ошибок apiClient.interceptors.response.use( (response) => { console.log('[API] ✅ Response success:', response.config.url) return response }, async (error) => { console.error('[API] ❌ Response error:', { status: error.response?.status, statusText: error.response?.statusText, data: error.response?.data, url: error.config?.url, }) // 🆕 При ошибке "Timestamp expired" — синхронизируем время и повторяем запрос if ( error.response?.status === 401 && error.response?.data === 'Timestamp expired\n' && !error.config._retry ) { console.warn('[API] ⚠️ Timestamp expired, syncing with server...') error.config._retry = true await syncTimeWithServer() // Пересоздаём подпись с новым timestamp const publicKey = import.meta.env.VITE_API_PUBLIC_KEY const privateKey = import.meta.env.VITE_API_PRIVATE_KEY const newTimestamp = getCorrectedTimestamp() error.config.headers['X-Timestamp'] = newTimestamp error.config.headers['ApiKey'] = generateHmacSignature( publicKey, newTimestamp, privateKey ) return apiClient(error.config) } if (error.response?.status === 401) { console.warn('[API] ⚠️ Unauthorized, redirecting to login') localStorage.removeItem('token') window.location.href = '/login' } return Promise.reject(error) } ) // 🆕 Синхронизируем время при загрузке модуля syncTimeWithServer() // 🆕 Периодическая синхронизация каждые 5 минут setInterval(() => { syncTimeWithServer() }, 5 * 60 * 1000) export default apiClient -----END src/api/client.ts----- File: src/api/dashboard.ts Lines: 56 -----BEGIN src/api/dashboard.ts----- import apiClient from './client' export interface DashboardStats { users: { total: number; active: number; blocked: number } approvals: { total: number; pending: number; revision: number; today: number } topics: { total: number; active: number } categories: number departments: number roles: number executors: number statusData: Array<{ status: string; count: number }> dailyData: Array<{ date: string; created: number; approved: number }> categoryBreakdown: Array<{ id: number name: string total_count: number pending_count: number }> bottleneckApprovers: Array<{ user_id: number full_name: string department_name: string pending_total: number overdue_count: number }> oldPendingCount: number // 🆕 Сколько дней считается "просрочкой" — приходит с бэкенда, чтобы // не дублировать магическое число 7 ещё и на фронте. oldPendingDays: number // 🆕 Задачи: тот же формат, что statusData/dailyData у заявок taskStatusData: Array<{ status: string; count: number }> taskDailyData: Array<{ date: string; created: number; completed: number }> // 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный) absentToday: Array<{ name: string; description: string }> // 🆕 Точечные пробелы: право создавать заявку по теме есть, но // порядок согласования для этого пользователя по ней не настроен. topicGaps: Array<{ user_id: number full_name: string department_name: string topic_id: number topic_name: string category_name: string }> // 🆕 Более базовый случай: у пользователя вообще нет ни одной // строки иерархии для его отдела (даже глобального правила). usersWithoutHierarchy: Array<{ user_id: number full_name: string department_name: string }> } export const dashboardApi = { // 🆕 Один endpoint — все данные сразу getStats: () => apiClient.get('/dashboard/stats'), } -----END src/api/dashboard.ts----- File: src/api/departments.ts Lines: 46 -----BEGIN src/api/departments.ts----- import apiClient from './client' import type { Department, ApiResponse } from '@/types/api' export interface DepartmentsListParams { offset?: number limit?: number is_active?: boolean name?: string code?: string } export interface CreateDepartmentRequest { name: string code: string description?: string is_active?: boolean } export interface UpdateDepartmentRequest { id: number name?: string code?: string description?: string is_active?: boolean } export const departmentsApi = { // Получить список отделов с пагинацией и фильтрами getList: (params: DepartmentsListParams = {}) => apiClient.get>('/departments', { params }), // Получить отдел по ID getById: (id: number) => apiClient.get(`/departments/${id}`), // Создать отдел create: (data: CreateDepartmentRequest) => apiClient.post('/departments', data), // Обновить отдел update: (data: UpdateDepartmentRequest) => apiClient.put('/departments', data), // Удалить отдел delete: (id: number) => apiClient.delete('/departments', { data: { id } }), } -----END src/api/departments.ts----- File: src/api/flowNodes.ts Lines: 99 -----BEGIN src/api/flowNodes.ts----- import apiClient from './client' import type { ApprovalFlowNode, ApiResponse } from '@/types/api' export interface CreateFlowNodeRequest { category_id: number parent_id?: number | null key: string 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 message_template?: string | null code_template?: string | null sort_order?: number } export interface UpdateFlowNodeRequest { id: number category_id?: number parent_id?: number | null key?: string 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 message_template?: string | null code_template?: string | null sort_order?: number } export interface MoveFlowNodeRequest { new_parent_id?: number | null new_sort_order?: number } export interface SaveTreeRequest { nodes: ApprovalFlowNode[] } // Живой предпросмотр: код темы + текст сообщения согласующему для // конкретного набора ответов (collected: data_key -> data_value), // посчитанные тем же движком, что использует боевой бот. export interface PreviewFlowRequest { collected: Record initiator_name?: string } export interface PreviewFlowResponse { code: string message: string incomplete: boolean topic_exists: boolean topic_id?: number topic_name?: string } export const flowNodesApi = { getTree: (categoryId: number) => apiClient.get>(`/flow-nodes/category/${categoryId}?limit=1000`), getById: (id: number) => apiClient.get(`/flow-nodes/${id}`), create: (data: CreateFlowNodeRequest) => apiClient.post('/flow-nodes/', data), update: (data: UpdateFlowNodeRequest) => apiClient.put('/flow-nodes/', data), delete: (id: number) => apiClient.delete('/flow-nodes/', { data: { id } }), saveTree: (categoryId: number, data: SaveTreeRequest) => apiClient.post(`/flow-nodes/category/${categoryId}/tree`, data), move: (id: number, data: MoveFlowNodeRequest) => apiClient.post(`/flow-nodes/${id}/move`, data), duplicate: (id: number) => apiClient.post(`/flow-nodes/${id}/duplicate`, {}), // НОВОЕ preview: (categoryId: number, data: PreviewFlowRequest) => apiClient.post(`/flow-nodes/category/${categoryId}/preview`, data), // НОВОЕ: форсировать обновление Registry в процессе бота (без перезапуска) reloadBot: () => apiClient.post('/flow-nodes/reload-bot', {}), } -----END src/api/flowNodes.ts----- File: src/api/hierarchies.ts Lines: 50 -----BEGIN src/api/hierarchies.ts----- import apiClient from './client' import type { UserHierarchy, ApiResponse } from '@/types/api' export interface HierarchiesListParams { offset?: number limit?: number subordinate_id?: number approver_id?: number department_id?: number topic_category_id?: number topic_id?: number target_system?: string | null } export interface CreateHierarchyRequest { subordinate_id: number approver_id: number department_id: number topic_category_id?: number | null topic_id?: number | null priority?: number target_system?: string | null } export interface UpdateHierarchyRequest { id: number subordinate_id?: number approver_id?: number department_id?: number topic_category_id?: number | null topic_id?: number | null priority?: number target_system?: string | null } export const hierarchiesApi = { getList: (params: HierarchiesListParams = {}) => apiClient.get>('/hierarchies', { params }), getById: (id: number) => apiClient.get(`/hierarchies/${id}`), create: (data: CreateHierarchyRequest) => apiClient.post('/hierarchies', data), update: (data: UpdateHierarchyRequest) => apiClient.put('/hierarchies', data), delete: (id: number) => apiClient.delete('/hierarchies', { data: { id } }), } -----END src/api/hierarchies.ts----- File: src/api/notifications.ts Lines: 26 -----BEGIN src/api/notifications.ts----- import apiClient from './client' import type { Notification, ApiResponse, TargetFilters } from '@/types/api' export interface NotificationsListParams { offset?: number limit?: number status?: string } export interface CreateNotificationRequest { title: string message_html: string photo_base64?: string photo_file_name?: string targets: TargetFilters } export const notificationsApi = { getList: (params: NotificationsListParams = {}) => apiClient.get>('/notifications', { params }), getById: (id: number) => apiClient.get(`/notifications/${id}`), create: (data: CreateNotificationRequest) => apiClient.post('/notifications', data), } -----END src/api/notifications.ts----- File: src/api/permissions.ts Lines: 42 -----BEGIN src/api/permissions.ts----- import apiClient from './client' import type { Permission, ApiResponse } from '@/types/api' export interface PermissionsListParams { offset?: number limit?: number role_id?: number action?: string topic_category_id?: number topic_id?: number } export interface CreatePermissionRequest { role_id: number topic_category_id?: number | null topic_id?: number | null action: string } export interface UpdatePermissionRequest { id: number role_id?: number topic_category_id?: number | null topic_id?: number | null action?: string } export const permissionsApi = { getList: (params: PermissionsListParams = {}) => apiClient.get>('/permissions', { params }), getById: (id: number) => apiClient.get(`/permissions/${id}`), create: (data: CreatePermissionRequest) => apiClient.post('/permissions', data), update: (data: UpdatePermissionRequest) => apiClient.put('/permissions', data), delete: (id: number) => apiClient.delete('/permissions', { data: { id } }), } -----END src/api/permissions.ts----- File: src/api/roles.ts Lines: 61 -----BEGIN src/api/roles.ts----- import apiClient from './client' import type { Role, ApiResponse } from '@/types/api' export interface RolesListParams { offset?: number limit?: number is_default?: boolean is_director?: boolean is_approver?: boolean is_observer?: boolean is_executor?: boolean is_controller?: boolean name?: string code?: string } export interface CreateRoleRequest { name: string code: string description?: string is_default?: boolean is_director?: boolean is_approver?: boolean is_observer?: boolean is_executor?: boolean is_controller?: boolean } export interface UpdateRoleRequest { id: number name?: string code?: string description?: string is_default?: boolean is_director?: boolean is_approver?: boolean is_observer?: boolean is_executor?: boolean is_controller?: boolean } export const rolesApi = { // Получить список ролей с пагинацией и фильтрами getList: (params: RolesListParams = {}) => apiClient.get>('/roles', { params }), // Получить роль по ID getById: (id: number) => apiClient.get(`/roles/${id}`), // Создать роль create: (data: CreateRoleRequest) => apiClient.post('/roles', data), // Обновить роль update: (data: UpdateRoleRequest) => apiClient.put('/roles', data), // Удалить роль delete: (id: number) => apiClient.delete('/roles', { data: { id } }), } -----END src/api/roles.ts----- File: src/api/time.ts Lines: 19 -----BEGIN src/api/time.ts----- import axios from 'axios' const publicApiClient = axios.create({ baseURL: '/api', headers: { 'Content-Type': 'application/json', }, }) export interface ServerTimeResponse { timestamp: number iso: string } export const timeApi = { getServerTime: async (): Promise => { const response = await publicApiClient.get('/time') return response.data }, } -----END src/api/time.ts----- File: src/api/topicExecutors.ts Lines: 48 -----BEGIN src/api/topicExecutors.ts----- import apiClient from './client' import type { ApprovalTopicExecutor, ApiResponse } from '@/types/api' export interface TopicExecutorsListParams { offset?: number limit?: number topic_id?: number user_id?: number is_active?: boolean target_system?: string } export interface CreateTopicExecutorRequest { topic_id: number user_id: number step_order?: number require_file?: boolean task_text?: string | null is_active?: boolean target_system?: string } export interface UpdateTopicExecutorRequest { id: number topic_id?: number user_id?: number step_order?: number require_file?: boolean task_text?: string | null is_active?: boolean target_system?: string } export const topicExecutorsApi = { getList: (params: TopicExecutorsListParams = {}) => apiClient.get>('/topic-executors', { params }), getById: (id: number) => apiClient.get(`/topic-executors/${id}`), create: (data: CreateTopicExecutorRequest) => apiClient.post('/topic-executors', data), update: (data: UpdateTopicExecutorRequest) => apiClient.put('/topic-executors', data), delete: (id: number) => apiClient.delete('/topic-executors', { data: { id } }), } -----END src/api/topicExecutors.ts----- File: src/api/topics.ts Lines: 78 -----BEGIN src/api/topics.ts----- import apiClient from './client' import type { ApprovalTopic, ApiResponse } from '@/types/api' export interface TopicsListParams { offset?: number limit?: number category_id?: number is_active?: boolean name?: string code?: string is_tree_root?: boolean } export interface CreateTopicRequest { category_id: number name: string code: string duration_type?: string time_type?: string is_tree_root?: boolean payment_type?: string template?: string | null allows_file?: boolean is_active?: boolean allow_approver_selection?: boolean first_approver_role_code?: string | null allow_observer_selection?: boolean allow_delegation_selection?: boolean approval_mode?: string require_approver_comment?: boolean requires_file?: boolean require_observer_selection?: boolean instructions?: string | null message_template?: string | null code_template?: string | null } export interface UpdateTopicRequest { id: number category_id?: number name?: string code?: string duration_type?: string time_type?: string payment_type?: string is_tree_root?: boolean template?: string | null allows_file?: boolean is_active?: boolean allow_approver_selection?: boolean first_approver_role_code?: string | null allow_observer_selection?: boolean // 🆕 см. CreateTopicRequest.allow_delegation_selection allow_delegation_selection?: boolean approval_mode?: string require_approver_comment?: boolean requires_file?: boolean require_observer_selection?: boolean instructions?: string | null message_template?: string | null code_template?: string | null } export const topicsApi = { getList: (params: TopicsListParams = {}) => apiClient.get>('/topics', { params }), getById: (id: number) => apiClient.get(`/topics/${id}`), create: (data: CreateTopicRequest) => apiClient.post('/topics', data), update: (data: UpdateTopicRequest) => apiClient.put('/topics', data), delete: (id: number) => apiClient.delete('/topics', { data: { id } }), } -----END src/api/topics.ts----- File: src/api/userRoles.ts Lines: 16 -----BEGIN src/api/userRoles.ts----- import apiClient from './client' import type { UserRole, ApiResponse } from '@/types/api' export interface BulkAssignRolesRequest { user_id: number role_ids: number[] } export const userRolesApi = { // Получить роли пользователя getByUserId: (userId: number) => apiClient.get>(`/users/${userId}/roles`), // Массовое назначение ролей (полная замена) bulkAssign: (data: BulkAssignRolesRequest) => apiClient.post>('/user-roles/bulk', data), } -----END src/api/userRoles.ts----- File: src/api/users.ts Lines: 33 -----BEGIN src/api/users.ts----- import apiClient from './client' import type { User, ApiResponse } from '@/types/api' export interface UsersListParams { offset?: number limit?: number is_blocked?: boolean is_fired?: boolean department_id?: number full_name?: string role_ids?: number[] } export interface UpdateUserRequest { id: number full_name?: string department_id?: number | null is_blocked?: boolean is_fired?: boolean } export const usersApi = { getList: (params: UsersListParams = {}) => apiClient.get>('/users', { params }), getById: (id: number) => apiClient.get(`/users/${id}`), update: (data: UpdateUserRequest) => apiClient.put('/users', data), delete: (id: number) => apiClient.delete(`/users/${id}`), } -----END src/api/users.ts----- File: src/components/CopyRolesModal.tsx Lines: 122 -----BEGIN src/components/CopyRolesModal.tsx----- import { useState } from 'react' import { Modal, Stack, TextInput, Text, Button, Group, Loader, Center, Paper, Badge, ScrollArea, Box, } from '@mantine/core' import { IconSearch, IconCopy } from '@tabler/icons-react' import { useUsers } from '@/features/users/hooks/useUsers' interface CopyRolesModalProps { opened: boolean onClose: () => void onCopy: (roleIds: number[]) => void currentUserId: number | null } export default function CopyRolesModal({ opened, onClose, onCopy, currentUserId }: CopyRolesModalProps) { const [search, setSearch] = useState('') const [selectedUserId, setSelectedUserId] = useState(null) const { data, isLoading } = useUsers({ offset: 0, limit: 100, ...(search && { full_name: search }), }) const users = Array.isArray(data?.data) ? data.data : [] const handleSelectUser = (userId: number) => { setSelectedUserId(userId) } const handleCopy = () => { if (!selectedUserId) return const selectedUser = users.find(u => u.id === selectedUserId) if (selectedUser && Array.isArray(selectedUser.user_roles)) { const roleIds = selectedUser.user_roles .map(ur => ur.role_id) .filter((id): id is number => !!id) onCopy(roleIds) } } return ( } value={search} onChange={(e) => setSearch(e.currentTarget.value)} /> {isLoading ? (
) : ( {users .filter(u => u.id !== currentUserId) .map((user) => ( handleSelectUser(user.id!)} > {user.full_name} {user.username ? `@${user.username}` : user.telegram_id} {Array.isArray(user.user_roles) ? user.user_roles.length : 0} ролей ))} )}
) } -----END src/components/CopyRolesModal.tsx----- File: src/components/DiagnosticErrorBoundary.tsx Lines: 90 -----BEGIN src/components/DiagnosticErrorBoundary.tsx----- import { Component, type ErrorInfo, type ReactNode } from 'react' import { Center, Stack, Title, Text, Button, Code, Box } from '@mantine/core' import { IconAlertTriangle } from '@tabler/icons-react' interface Props { children: ReactNode // Полноэкранный вариант — для самого верхнего "предохранителя" (main.tsx). // Без него — занимает высоту родителя (для page-level использования // внутри layout, где вокруг уже есть Header/Sidebar). fullPage?: boolean } interface State { error: Error | null componentStack: string | null } // Общий ErrorBoundary. Используется дважды: // 1) в main.tsx, оборачивая — последний рубеж на случай падения // чего угодно (в т.ч. самого layout/sidebar); // 2) в MainLayout.tsx, оборачивая , с key={location.pathname} — // тогда падение ОДНОЙ страницы не рушит весь интерфейс: Header и // Sidebar остаются рабочими, и переход на другую страницу сам // пересоздаёт boundary и сбрасывает ошибку — reload не нужен. export default class ErrorBoundary extends Component { state: State = { error: null, componentStack: null } static getDerivedStateFromError(error: Error) { return { error } } componentDidCatch(error: Error, info: ErrorInfo) { // 🆕 Логируем с максимумом контекста — пригодится и сейчас для // диагностики (например, бага "белый экран после правки // иерархии"), и впредь. Если подключите Sentry или аналог — // отправляйте error + info отсюда же. console.error('[ErrorBoundary] Необработанная ошибка рендера:', { message: error.message, stack: error.stack, componentStack: info.componentStack, url: window.location.href, timestamp: new Date().toISOString(), }) this.setState({ componentStack: info.componentStack ?? null }) } handleReload = () => { window.location.reload() } render() { const { error, componentStack } = this.state if (!error) { return this.props.children } return (
Произошла ошибка при загрузке страницы Попробуйте перейти на другую страницу через меню слева или перезагрузить страницу. Если ошибка повторяется — сообщите в техническую поддержку. {import.meta.env.DEV && ( Технические детали (видно только в dev-сборке): {error.message} {'\n\n'} {componentStack} )}
) } } -----END src/components/DiagnosticErrorBoundary.tsx----- File: src/components/Layout/Header.tsx Lines: 73 -----BEGIN src/components/Layout/Header.tsx----- import { Group, Burger, Text, Avatar, Menu, ActionIcon, } from '@mantine/core' import { IconLogout, IconUser } from '@tabler/icons-react' import { useAuth } from '@/hooks/useAuth' interface HeaderProps { toggleMobile: () => void toggleDesktop: () => void mobileOpened: boolean desktopOpened: boolean } export default function Header({ toggleMobile, toggleDesktop, mobileOpened, desktopOpened }: HeaderProps) { const { user, logout } = useAuth() return ( Панель управления администратора {user?.login?.charAt(0).toUpperCase() || 'A'} }> {user?.login || 'Admin'} } onClick={logout} color="red" > Выйти ) } -----END src/components/Layout/Header.tsx----- File: src/components/Layout/MainLayout.tsx Lines: 42 -----BEGIN src/components/Layout/MainLayout.tsx----- import { AppShell } from '@mantine/core' import { useDisclosure } from '@mantine/hooks' import { Outlet, useLocation } from 'react-router-dom' import Sidebar from './Sidebar' import Header from './Header' import ErrorBoundary from '../DiagnosticErrorBoundary' export default function MainLayout() { const [mobileOpened, { toggle: toggleMobile }] = useDisclosure() const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true) const location = useLocation() return (
) } -----END src/components/Layout/MainLayout.tsx----- File: src/components/Layout/Sidebar.tsx Lines: 211 -----BEGIN src/components/Layout/Sidebar.tsx----- import { useState, useMemo } from 'react' import { NavLink, Box, Text, Stack, Badge } from '@mantine/core' import { IconDashboard, IconFileCheck, IconSettings, IconChevronRight, IconList, IconUsers, IconBuilding, IconShield, IconKey, IconCategory, IconBriefcase, IconUserCheck, IconGitBranch, IconUserCog, IconCheck, IconBellRinging, IconBlocks, IconHistory, } from '@tabler/icons-react' import { useLocation, useNavigate } from 'react-router-dom' import { useAuth } from '@/hooks/useAuth' interface MenuItem { label: string icon?: any path?: string children?: MenuItem[] adminOnly?: boolean // скрывать от наблюдателей } const menuItems: MenuItem[] = [ { label: 'Обзор', icon: IconDashboard, path: '/' }, { label: 'Администраторы', icon: IconUserCog, path: '/admins', adminOnly: true }, { label: 'Уведомления', icon: IconBellRinging, path: '/notifications', adminOnly: true }, { label: 'Журнал действий', icon: IconHistory, path: '/logs', adminOnly: true }, { label: 'Система согласований', icon: IconFileCheck, children: [ { label: 'Панель управления', icon: IconDashboard, path: '/approval-dash' }, { label: 'Заявки', icon: IconList, path: '/approvals' }, { label: 'Задачи', icon: IconCheck, path: '/approval-tasks' }, { label: 'Пользователи', icon: IconUsers, path: '/users' }, { label: 'Отделы', icon: IconBuilding, path: '/departments', adminOnly: true }, { label: 'Роли', icon: IconShield, path: '/roles', adminOnly: true }, { label: 'Права', icon: IconKey, path: '/permissions', adminOnly: true }, { label: 'Темы согласований', icon: IconBriefcase, adminOnly: true, children: [ { label: 'Категории', icon: IconCategory, path: '/categories' }, { label: 'Темы', icon: IconBriefcase, path: '/topics' }, { label: 'Исполнители', icon: IconUserCheck, path: '/executors' }, ] }, { label: 'Конструктор тем', icon: IconBlocks, path: '/nodes', adminOnly: true }, { label: 'Иерархия', icon: IconGitBranch, path: '/hierarchies', adminOnly: true }, ] }, { label: 'Настройки', icon: IconSettings, path: '/settings'}, ] function filterMenuByRole(items: MenuItem[], isObserver: boolean): MenuItem[] { return items .filter((item) => { if (isObserver && item.adminOnly) return false return true }) .map((item) => { if (item.children) { const filteredChildren = filterMenuByRole(item.children, isObserver) // Если после фильтрации детей не осталось — скрываем родителя if (filteredChildren.length === 0) return null return { ...item, children: filteredChildren } } return item }) .filter((item): item is MenuItem => item !== null) } function MenuItemLink({ item, level }: { item: MenuItem; level: number }) { const location = useLocation() const navigate = useNavigate() const [opened, setOpened] = useState(false) const hasChildren = item.children && item.children.length > 0 const isActive = item.path ? location.pathname === item.path : false const hasActiveChild = item.children?.some(child => child.path ? location.pathname === child.path : false ) || false const paddingLeft = 16 + level * 20 if (hasChildren) { return ( : undefined} rightSection={ } active={hasActiveChild} onClick={() => setOpened(!opened)} styles={{ root: { paddingLeft, paddingRight: 12, borderRadius: '8px', marginBottom: 2, '&:hover': { backgroundColor: 'var(--mantine-color-gray-0)', }, }, }} /> {opened && ( {item.children!.map((child) => ( ))} )} ) } return ( : undefined} active={isActive} onClick={() => { if (item.path) navigate(item.path) }} styles={{ root: { paddingLeft, paddingRight: 12, borderRadius: '8px', marginBottom: 2, '&:hover': { backgroundColor: 'var(--mantine-color-gray-0)', }, }, label: { fontWeight: isActive ? 600 : 400, }, }} /> ) } export default function Sidebar() { const { user } = useAuth() const isObserver = user?.is_observer === true // 🆕 Фильтруем меню в зависимости от роли const filteredMenuItems = useMemo( () => filterMenuByRole(menuItems, isObserver), [isObserver] ) return ( Главное меню {/* 🆕 Индикатор режима наблюдателя */} {isObserver && ( Режим наблюдателя )} {filteredMenuItems.map((item) => ( ))} ) } -----END src/components/Layout/Sidebar.tsx----- File: src/components/TopicGapsModal.tsx Lines: 79 -----BEGIN src/components/TopicGapsModal.tsx----- import { Modal, Table, Text, Badge, Group, ScrollArea, Stack, Center } from '@mantine/core' import { IconAlertTriangle } from '@tabler/icons-react' interface TopicGap { user_id: number full_name: string department_name: string topic_id: number topic_name: string category_name: string } interface TopicGapsModalProps { opened: boolean onClose: () => void gaps: TopicGap[] } export default function TopicGapsModal({ opened, onClose, gaps }: TopicGapsModalProps) { return ( Темы без назначенного порядка согласования } size="xl" > У перечисленных сотрудников есть право создавать заявку по теме, но ни одно правило иерархии не назначает для них согласующего — при попытке отправить такую заявку в боте она не пройдёт. {gaps.length === 0 ? (
Пробелов не найдено — все настроено
) : ( Сотрудник Отдел Категория Тема {gaps.map((g, i) => ( {g.full_name || `ID: ${g.user_id}`} {g.department_name || '—'} {g.category_name || '—'} {g.topic_name || `ID: ${g.topic_id}`} ))}
)}
) } -----END src/components/TopicGapsModal.tsx----- File: src/components/UserEditModal.tsx Lines: 294 -----BEGIN src/components/UserEditModal.tsx----- import { useEffect, useState } from 'react' import { Modal, Stack, TextInput, Select, MultiSelect, Switch, Group, Button, Text, Divider, Loader, Center, Badge, Paper, Tabs, ActionIcon, Tooltip, Box, } from '@mantine/core' import { IconTrash, IconCopy, IconUser, IconSettings, IconShield } from '@tabler/icons-react' import { useForm } from '@mantine/form' import { useUser, useUpdateUser } from '@/features/users/hooks/useUsers' import { useDepartments } from '@/features/users/hooks/useDepartments' import { useRoles } from '@/features/users/hooks/useRoles' import { useUserRoles, useBulkAssignRoles } from '@/features/users/hooks/useUserRoles' import CopyRolesModal from './CopyRolesModal' interface UserEditModalProps { userId: number | null opened: boolean onClose: () => void } export default function UserEditModal({ userId, opened, onClose }: UserEditModalProps) { const { data: user, isLoading: userLoading } = useUser(userId) const { data: departments } = useDepartments() const { data: allRoles } = useRoles({ limit: 1000 }) const { data: userRoles, isLoading: rolesLoading } = useUserRoles(userId) const updateUser = useUpdateUser() const assignRoles = useBulkAssignRoles() const [copyRolesOpened, setCopyRolesOpened] = useState(false) const form = useForm({ initialValues: { full_name: '', department_id: null as number | null, is_blocked: false, is_fired: false, role_ids: [] as number[], }, }) useEffect(() => { if (user) { form.setValues({ full_name: user.full_name || '', department_id: user.department_id || null, is_blocked: user.is_blocked || false, is_fired: user.is_fired || false, role_ids: Array.isArray(user.user_roles) ? user.user_roles.map((ur) => ur.role_id!) : [], }) } }, [user]) useEffect(() => { if (Array.isArray(userRoles) && userRoles.length > 0) { const roleIds = userRoles .map((ur) => ur.role?.id || ur.role_id) .filter((id): id is number => !!id) form.setFieldValue('role_ids', roleIds) } }, [userRoles]) const handleSubmit = async (values: typeof form.values) => { if (!userId) return await updateUser.mutateAsync({ id: userId, full_name: values.full_name, department_id: values.department_id, is_blocked: values.is_blocked, is_fired: values.is_fired, }) await assignRoles.mutateAsync({ user_id: userId, role_ids: values.role_ids, }) onClose() } const handleClearAllRoles = () => { form.setFieldValue('role_ids', []) } const handleCopyRoles = (roleIds: number[]) => { form.setFieldValue('role_ids', roleIds) setCopyRolesOpened(false) } const departmentOptions = Array.isArray(departments) ? departments.map((d) => ({ value: String(d.id), label: d.name || '', })) : [] const roleOptions = Array.isArray(allRoles) ? allRoles.map((r) => ({ value: String(r.id), label: r.name || '', description: r.description, })) : [] const isLoading = userLoading || rolesLoading const isSubmitting = updateUser.isPending || assignRoles.isPending return ( <> Редактирование пользователя {user && ID: {user.id}} } size="xl" > {isLoading ? (
) : user ? (
}> Информация }> Роли ({form.values.role_ids.length}) }> Настройки {/* Вкладка: Информация */} Telegram ID: {user.telegram_id} {user.username && ( Username: @{user.username} )} {user.last_login && ( Последний вход: {new Date(user.last_login).toLocaleString('ru-RU')} )} form.setFieldValue('full_name', e.currentTarget.value)} required />