From 95e0ad3fcd532a115f0754e0067309b1296fcb00 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Tue, 25 Aug 2026 11:27:03 +0300 Subject: [PATCH] Added menthly order page --- communication_system_front.txt | 4580 +++++++++++++++++ src/App.tsx | 2 + src/api/admins.ts | 2 + src/api/monthlyOrders.ts | 10 + src/components/Layout/Sidebar.tsx | 10 +- .../hooks/useMonthlyOrderSettings.ts | 39 + src/pages/admins/AdminsPage.tsx | 11 +- .../admins/components/CreateAdminModal.tsx | 22 +- .../admins/components/EditAdminModal.tsx | 2 + .../MonthlyOrdersSettingsPage.tsx | 88 + src/types/api.ts | 17 +- 11 files changed, 4774 insertions(+), 9 deletions(-) create mode 100644 communication_system_front.txt create mode 100644 src/api/monthlyOrders.ts create mode 100644 src/features/monthlyOrders/hooks/useMonthlyOrderSettings.ts create mode 100644 src/pages/monthlyOrders/MonthlyOrdersSettingsPage.tsx diff --git a/communication_system_front.txt b/communication_system_front.txt new file mode 100644 index 0000000..9689556 --- /dev/null +++ b/communication_system_front.txt @@ -0,0 +1,4580 @@ +├── .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 +├── react_code.txt +├── 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: index.html +Lines: 13 +-----BEGIN index.html----- + + + + + + + Административная панель РусПЭТ + + +
+ + + + +-----END index.html----- + +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/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: 199 +-----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 + id?: 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.id) query.id = params.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/features/adminLogs/hooks/useAdminLogs.ts +Lines: 37 +-----BEGIN src/features/adminLogs/hooks/useAdminLogs.ts----- +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { adminLogsApi, type AdminLogsListParams } from '@/api/adminLogs' +import { notifications } from '@mantine/notifications' + +export const ADMIN_LOGS_QUERY_KEY = 'admin-logs' + +export function useAdminLogs(params: AdminLogsListParams = {}) { + return useQuery({ + queryKey: [ADMIN_LOGS_QUERY_KEY, params], + queryFn: async () => { + const response = await adminLogsApi.getList(params) + return response.data + }, + }) +} + +export function useDeleteAdminLog() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (id: number) => adminLogsApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [ADMIN_LOGS_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Запись журнала удалена', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось удалить запись (доступно только root-администратору)', + color: 'red', + }) + }, + }) +} +-----END src/features/adminLogs/hooks/useAdminLogs.ts----- + +File: src/features/admins/hooks/useAdmins.ts +Lines: 116 +-----BEGIN src/features/admins/hooks/useAdmins.ts----- +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { adminsApi, type AdminsListParams, type CreateAdminRequest, type UpdateAdminRequest } from '@/api/admins' +import { notifications } from '@mantine/notifications' + +export const ADMINS_QUERY_KEY = 'admins' + +export function useAdmins(params: AdminsListParams = {}) { + return useQuery({ + queryKey: [ADMINS_QUERY_KEY, params], + queryFn: async () => { + const response = await adminsApi.getList(params) + return response.data + }, + }) +} + +export function useCreateAdmin() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: async (data: CreateAdminRequest) => { + const response = await adminsApi.create(data) + return response.data + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [ADMINS_QUERY_KEY] }) + }, + onError: (error: any) => { + const errorMsg = error.response?.data?.error_description || '' + let message = 'Не удалось создать администратора' + + if (errorMsg === 'admin_is_not_available') { + message = 'Администратор с таким логином уже существует' + } else if (errorMsg === 'only_root_can_create_admins') { + message = 'Только root-администратор может создавать новых администраторов' + } else if (errorMsg === 'telegram_id_required_for_observer') { + message = 'Для наблюдателя необходимо указать Telegram-аккаунт' + } else if (errorMsg === 'telegram_user_not_found') { + message = 'Пользователь с таким Telegram ID не найден в боте' + } + + notifications.show({ + title: 'Ошибка', + message, + color: 'red', + }) + }, + }) +} + +export function useUpdateAdmin() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (data: UpdateAdminRequest) => adminsApi.update(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [ADMINS_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Администратор обновлен', + color: 'green', + }) + }, + onError: (error: any) => { + const errorMsg = error.response?.data?.error_description || '' + let message = 'Не удалось обновить администратора' + + if (errorMsg === 'cannot_block_root') { + message = 'Нельзя заблокировать root-администратора' + } else if (errorMsg === 'cannot_block_self') { + message = 'Нельзя заблокировать свой собственный аккаунт' + } else if (errorMsg === 'telegram_id_required_for_observer') { + message = 'Для наблюдателя необходимо указать Telegram-аккаунт' + } else if (errorMsg === 'telegram_user_not_found') { + message = 'Пользователь с таким Telegram ID не найден в боте' + } + + notifications.show({ + title: 'Ошибка', + message, + color: 'red', + }) + }, + }) +} + +export function useDeleteAdmin() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (id: number) => adminsApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [ADMINS_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Администратор удален', + color: 'green', + }) + }, + onError: (error: any) => { + const errorMsg = error.response?.data?.error_description || '' + let message = 'Не удалось удалить администратора' + + if (errorMsg === 'cannot_delete_self') { + message = 'Нельзя удалить свой собственный аккаунт' + } else if (errorMsg === 'cannot_delete_root') { + message = 'Нельзя удалить root-администратора' + } + + notifications.show({ + title: 'Ошибка', + message, + color: 'red', + }) + }, + }) +} +-----END src/features/admins/hooks/useAdmins.ts----- + +File: src/features/approvalTasks/const.ts +Lines: 19 +-----BEGIN src/features/approvalTasks/const.ts----- +export const TASK_STATUSES = [ + { value: 'pending', label: 'В ожидании', color: 'blue', icon: 'clock' }, + { value: 'waiting', label: 'Ожидает', color: 'orange', icon: 'hourglass' }, + { value: 'completed', label: 'Выполнена', color: 'green', icon: 'check' }, + { value: 'cancelled', label: 'Отменена', color: 'gray', icon: 'x' }, +] as const + +export const STATUS_COLORS: Record = { + pending: 'blue', + waiting: 'orange', + completed: 'green', + cancelled: 'gray', +} + +export const STATUS_LABELS: Record = { + pending: 'В ожидании', + waiting: 'Ожидает', + completed: 'Выполнена', + cancelled: 'Отменена', +} +-----END src/features/approvalTasks/const.ts----- + +File: src/features/approvalTasks/hooks/useApprovalTasks.ts +Lines: 76 +-----BEGIN src/features/approvalTasks/hooks/useApprovalTasks.ts----- +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { + approvalTasksApi, + type ApprovalTasksListParams, + type UpdateApprovalTaskRequest +} from '@/api/approvalTasks' +import { notifications } from '@mantine/notifications' + +export const APPROVAL_TASKS_QUERY_KEY = 'approval-tasks' + +export function useApprovalTasks(params: ApprovalTasksListParams = {}) { + return useQuery({ + queryKey: [APPROVAL_TASKS_QUERY_KEY, params], + queryFn: async () => { + const response = await approvalTasksApi.getList(params) + return response.data + }, + }) +} + +export function useApprovalTask(id: number | null) { + return useQuery({ + queryKey: ['approval-task', id], + queryFn: async () => { + if (!id) return null + const response = await approvalTasksApi.getById(id) + return response.data + }, + enabled: !!id, + }) +} + +export function useUpdateApprovalTask() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (data: UpdateApprovalTaskRequest) => approvalTasksApi.update(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [APPROVAL_TASKS_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Задача обновлена', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось обновить задачу', + color: 'red', + }) + }, + }) +} + +export function useDeleteApprovalTask() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (id: number) => approvalTasksApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [APPROVAL_TASKS_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/approvalTasks/hooks/useApprovalTasks.ts----- + +File: src/features/approvals/hooks/useApprovals.ts +Lines: 150 +-----BEGIN src/features/approvals/hooks/useApprovals.ts----- +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { + approvalsApi, + type ApprovalsListParams, + type ApprovalsReportParams, + type UpdateApprovalRequest +} from '@/api/approvals' +import { notifications } from '@mantine/notifications' + +export const APPROVALS_QUERY_KEY = 'approvals' + +export function useApprovals(params: ApprovalsListParams = {}) { + return useQuery({ + queryKey: [APPROVALS_QUERY_KEY, params], + queryFn: async () => { + const response = await approvalsApi.getList(params) + return response.data + }, + }) +} + +export function useApprovalTasks(approvalId: number | null) { + return useQuery({ + queryKey: ['approval-tasks', approvalId], + queryFn: async () => { + if (!approvalId) return null + const response = await approvalsApi.getTasks(approvalId) + return response.data + }, + enabled: !!approvalId, + }) +} + +export function useApproval(id: number | null) { + return useQuery({ + queryKey: ['approval', id], + queryFn: async () => { + if (!id) return null + const response = await approvalsApi.getById(id) + return response.data + }, + enabled: !!id, + }) +} + +// 🆕 Хук для получения заявок по отчёту (с фильтрами по датам) +export function useApprovalsReport(params: ApprovalsReportParams = {}) { + return useQuery({ + queryKey: ['approvals-report', params], + queryFn: async () => { + const response = await approvalsApi.getForReport(params) + return response.data.data || [] + }, + enabled: false, // Запускаем вручную + }) +} + +export function useUpdateApproval() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (data: UpdateApprovalRequest) => approvalsApi.update(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [APPROVALS_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Заявка обновлена', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось обновить заявку', + color: 'red', + }) + }, + }) +} + +export function useDeleteApproval() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (id: number) => approvalsApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [APPROVALS_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Заявка удалена', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось удалить заявку', + color: 'red', + }) + }, + }) +} + +export function useAdditionalApprovers(approvalId: number | null) { + return useQuery({ + queryKey: ['approval-additional-approvers', approvalId], + queryFn: async () => { + if (!approvalId) return null + const response = await approvalsApi.getAdditionalApprovers(approvalId) + return response.data + }, + enabled: !!approvalId, + }) +} + +export function useApprovalComments(approvalId: number | null) { + return useQuery({ + queryKey: ['approval-comments', approvalId], + queryFn: async () => { + if (!approvalId) return null + const response = await approvalsApi.getComments(approvalId) + return response.data + }, + enabled: !!approvalId, + }) +} + +export function useApprovalObservers(approvalId: number | null) { + return useQuery({ + queryKey: ['approval-observers', approvalId], + queryFn: async () => { + if (!approvalId) return null + const response = await approvalsApi.getObservers(approvalId) + return response.data + }, + enabled: !!approvalId, + }) +} + +export function useRevocationRequest(approvalId: number | null) { + return useQuery({ + queryKey: ['approval-revocation-request', approvalId], + queryFn: async () => { + if (!approvalId) return null + const response = await approvalsApi.getRevocationRequest(approvalId) + return response.data + }, + enabled: !!approvalId, + }) +} + +-----END src/features/approvals/hooks/useApprovals.ts----- + +File: src/features/categories/hooks/useCategories.ts +Lines: 100 +-----BEGIN src/features/categories/hooks/useCategories.ts----- +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { + categoriesApi, + type CategoriesListParams, + type CreateCategoryRequest, + type UpdateCategoryRequest +} from '@/api/categories' +import { notifications } from '@mantine/notifications' + +export const CATEGORIES_QUERY_KEY = 'categories' + +export function useCategories(params: CategoriesListParams = {}) { + return useQuery({ + queryKey: [CATEGORIES_QUERY_KEY, params], + queryFn: async () => { + const response = await categoriesApi.getList(params) + return response.data + }, + }) +} + +export function useCategory(id: number | null) { + return useQuery({ + queryKey: ['category', id], + queryFn: async () => { + if (!id) return null + const response = await categoriesApi.getById(id) + return response.data + }, + enabled: !!id, + }) +} + +export function useCreateCategory() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (data: CreateCategoryRequest) => categoriesApi.create(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [CATEGORIES_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Категория создана', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось создать категорию', + color: 'red', + }) + }, + }) +} + +export function useUpdateCategory() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (data: UpdateCategoryRequest) => categoriesApi.update(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [CATEGORIES_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Категория обновлена', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось обновить категорию', + color: 'red', + }) + }, + }) +} + +export function useDeleteCategory() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (id: number) => categoriesApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [CATEGORIES_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/categories/hooks/useCategories.ts----- + +File: src/features/departments/hooks/useDepartments.ts +Lines: 100 +-----BEGIN src/features/departments/hooks/useDepartments.ts----- +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { + departmentsApi, + type DepartmentsListParams, + type CreateDepartmentRequest, + type UpdateDepartmentRequest +} from '@/api/departments' +import { notifications } from '@mantine/notifications' + +export const DEPARTMENTS_QUERY_KEY = 'departments' + +export function useDepartments(params: DepartmentsListParams = {}) { + return useQuery({ + queryKey: [DEPARTMENTS_QUERY_KEY, params], + queryFn: async () => { + const response = await departmentsApi.getList(params) + return response.data + }, + }) +} + +export function useDepartment(id: number | null) { + return useQuery({ + queryKey: ['department', id], + queryFn: async () => { + if (!id) return null + const response = await departmentsApi.getById(id) + return response.data + }, + enabled: !!id, + }) +} + +export function useCreateDepartment() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (data: CreateDepartmentRequest) => departmentsApi.create(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [DEPARTMENTS_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Отдел создан', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось создать отдел', + color: 'red', + }) + }, + }) +} + +export function useUpdateDepartment() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (data: UpdateDepartmentRequest) => departmentsApi.update(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [DEPARTMENTS_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Отдел обновлен', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось обновить отдел', + color: 'red', + }) + }, + }) +} + +export function useDeleteDepartment() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (id: number) => departmentsApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [DEPARTMENTS_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/departments/hooks/useDepartments.ts----- + +File: src/features/flowNodes/hooks/useFlowNodes.ts +Lines: 179 +-----BEGIN src/features/flowNodes/hooks/useFlowNodes.ts----- +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { + flowNodesApi, + type CreateFlowNodeRequest, + type UpdateFlowNodeRequest, + type MoveFlowNodeRequest, + type PreviewFlowRequest, +} from '@/api/flowNodes' +import { notifications } from '@mantine/notifications' + +export const FLOW_NODES_QUERY_KEY = 'flowNodes' + +export function useFlowNodesTree(categoryId: number | null) { + return useQuery({ + queryKey: [FLOW_NODES_QUERY_KEY, categoryId], + queryFn: async () => { + if (!categoryId) return null + const response = await flowNodesApi.getTree(categoryId) + return response.data + }, + enabled: !!categoryId, + }) +} + +export function useCreateFlowNode() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (data: CreateFlowNodeRequest) => flowNodesApi.create(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] }) + notifications.show({ title: 'Готово', message: 'Кнопка/шаг добавлены', color: 'green' }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Не получилось', + message: error.response?.data?.error_description || 'Не удалось сохранить', + color: 'red', + }) + }, + }) +} + +export function useUpdateFlowNode() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (data: UpdateFlowNodeRequest) => flowNodesApi.update(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] }) + notifications.show({ title: 'Готово', message: 'Изменения сохранены', color: 'green' }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Не получилось', + message: error.response?.data?.error_description || 'Не удалось сохранить изменения', + color: 'red', + }) + }, + }) +} + +export function useDeleteFlowNode() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (id: number) => flowNodesApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] }) + notifications.show({ title: 'Готово', message: 'Шаг удалён', color: 'green' }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Не получилось', + message: error.response?.data?.error_description || 'Не удалось удалить', + color: 'red', + }) + }, + }) +} + +// Перемещение узла — используется для ↑/↓ среди соседей и для +// "поднять/опустить уровень" точечно (см. treeWalk.ts). +export function useMoveFlowNode() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: ({ id, data }: { id: number; data: MoveFlowNodeRequest }) => flowNodesApi.move(id, data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Не получилось', + message: error.response?.data?.error_description || 'Не удалось переместить', + color: 'red', + }) + }, + }) +} + +// НОВОЕ: пакетное перемещение для drag&drop — план из buildReorderPlan +// (см. treeFlatten.ts) может включать несколько узлов сразу (переиндексация +// старой и новой групп соседей). Отправляем всё параллельно и обновляем +// дерево ОДНИМ инвалидейтом в конце, а не на каждый отдельный вызов — +// иначе список будет дёргаться на каждом промежуточном ответе. +export function useReorderNodes() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: async (ops: { id: number; new_parent_id: number | null; new_sort_order: number }[]) => { + await Promise.all( + ops.map((op) => + flowNodesApi.move(op.id, { new_parent_id: op.new_parent_id, new_sort_order: op.new_sort_order }) + ) + ) + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Не получилось', + message: + error.response?.data?.error_description || 'Не удалось переместить шаг — дерево вернётся к прежнему виду', + color: 'red', + }) + queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] }) + }, + }) +} + +export function useDuplicateFlowNode() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (id: number) => flowNodesApi.duplicate(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] }) + notifications.show({ title: 'Готово', message: 'Шаг скопирован', color: 'green' }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Не получилось', + message: error.response?.data?.error_description || 'Не удалось скопировать', + color: 'red', + }) + }, + }) +} + +// НОВОЕ: живой предпросмотр — код темы + текст сообщения согласующему +// для конкретного набора выборов. Не мутирует данные, поэтому это +// useMutation, вызываемый вручную (а не useQuery), чтобы не дёргать +// сервер на каждое нажатие клавиши, а только по явному запросу/дебаунсу. +// НОВОЕ: кнопка "Обновить бота" — форсирует у бота перечитывание дерева тем +// из БД, не дожидаясь фонового тика (см. reload_watcher.go в telegram_service). +export function useReloadBot() { + return useMutation({ + mutationFn: () => flowNodesApi.reloadBot(), + onSuccess: () => { + notifications.show({ + title: 'Готово', + message: 'Бот обновит список тем в течение нескольких секунд', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Не получилось', + message: error.response?.data?.error_description || 'Не удалось обновить бота', + color: 'red', + }) + }, + }) +} + +export function usePreviewFlow(categoryId: number | null) { + return useMutation({ + mutationFn: async (data: PreviewFlowRequest) => { + if (!categoryId) throw new Error('categoryId is required') + const response = await flowNodesApi.preview(categoryId, data) + return response.data // разворачиваем AxiosResponse -> PreviewFlowResponse + }, + }) +} +-----END src/features/flowNodes/hooks/useFlowNodes.ts----- + +File: src/features/flowNodes/utils/flattenTree.ts +Lines: 127 +-----BEGIN src/features/flowNodes/utils/flattenTree.ts----- +import { arrayMove } from '@dnd-kit/sortable' +import type { ApprovalFlowNode } from '@/types/api' + +export interface FlatFlowNode extends ApprovalFlowNode { + depth: number +} + +// Разворачивает дерево в плоский список для отображения в виде сортируемого +// списка. parent_id уже есть на каждом узле (приходит с бэкенда) — отдельно +// его не вычисляем. +export function flattenTree(nodes: ApprovalFlowNode[], collapsed: Set): FlatFlowNode[] { + const result: FlatFlowNode[] = [] + const walk = (list: ApprovalFlowNode[], depth: number) => { + for (const node of list) { + result.push({ ...node, depth }) + if (node.children?.length && node.id != null && !collapsed.has(node.id)) { + walk(node.children, depth + 1) + } + } + } + walk(nodes, 0) + return result +} + +export interface Projection { + depth: number + parentId: number | null +} + +// Классический алгоритм проекции для sortable-дерева (как в примере +// "Sortable Tree" из документации dnd-kit): по горизонтальному смещению +// курсора во время перетаскивания решаем, на какую глубину и к какому +// родителю попадёт узел, если отпустить его над overId прямо сейчас. +// +// ВАЖНО: глубина никогда не может быть 0 — на верхнем уровне дерева +// категории всегда должен быть ровно один узел (корень с ключом, равным +// коду раздела), и он не участвует в перетаскивании. +export function getProjection( + items: FlatFlowNode[], + activeId: number, + overId: number, + dragOffsetX: number, + indentationWidth: number +): Projection { + const activeItemIndex = items.findIndex((n) => n.id === activeId) + const overItemIndex = items.findIndex((n) => n.id === overId) + if (activeItemIndex === -1 || overItemIndex === -1) { + return { depth: 1, parentId: null } + } + + const activeItem = items[activeItemIndex] + const newItems = arrayMove(items, activeItemIndex, overItemIndex) + const previousItem = newItems[overItemIndex - 1] + const nextItem = newItems[overItemIndex + 1] + + const dragDepthDelta = Math.round(dragOffsetX / indentationWidth) + const projectedDepth = activeItem.depth + dragDepthDelta + + const maxDepth = Math.max(previousItem ? previousItem.depth + 1 : 1, 1) + const minDepth = Math.max(nextItem ? nextItem.depth : 1, 1) + + let depth = projectedDepth + if (depth > maxDepth) depth = maxDepth + if (depth < minDepth) depth = minDepth + + let parentId: number | null = null + if (previousItem) { + if (depth === previousItem.depth) { + parentId = previousItem.parent_id ?? null + } else if (depth > previousItem.depth) { + parentId = previousItem.id ?? null + } else { + const newParent = [...newItems] + .slice(0, overItemIndex) + .reverse() + .find((n) => n.depth === depth) + parentId = newParent?.parent_id ?? null + } + } + + return { depth, parentId } +} + +export interface MoveOp { + id: number + new_parent_id: number | null + new_sort_order: number +} + +// Строит план обновлений после drag&drop одного узла: полностью +// переиндексирует группу соседей, откуда узел ушёл, и группу, куда он +// попал (несколько лишних вызовов API по сравнению со строгим минимумом, +// зато гарантированно нет дублей/дыр в sort_order). +export function buildReorderPlan( + tree: ApprovalFlowNode[], + activeId: number, + newParentId: number | null, + overId: number +): MoveOp[] { + const flat = flattenTree(tree, new Set()) + const active = flat.find((n) => n.id === activeId) + if (!active) return [] + + const oldParentId = active.parent_id ?? null + + const oldSiblings = flat.filter((n) => (n.parent_id ?? null) === oldParentId && n.id !== activeId) + const newSiblingsWithoutActive = flat.filter((n) => (n.parent_id ?? null) === newParentId && n.id !== activeId) + + const overIdx = newSiblingsWithoutActive.findIndex((n) => n.id === overId) + const insertAt = overIdx === -1 ? newSiblingsWithoutActive.length : overIdx + + const newSiblings = [...newSiblingsWithoutActive] + newSiblings.splice(insertAt, 0, active) + + const ops: MoveOp[] = newSiblings.map((n, idx) => ({ + id: n.id!, + new_parent_id: newParentId, + new_sort_order: idx, + })) + + if (oldParentId !== newParentId) { + oldSiblings.forEach((n, idx) => { + ops.push({ id: n.id!, new_parent_id: oldParentId, new_sort_order: idx }) + }) + } + + return ops +} +-----END src/features/flowNodes/utils/flattenTree.ts----- + +File: src/features/flowNodes/utils/treeWalk.ts +Lines: 222 +-----BEGIN src/features/flowNodes/utils/treeWalk.ts----- +import type { ApprovalFlowNode } from '@/types/api' + +// ============================================================ +// Базовый обход дерева +// ============================================================ + +export function findParent( + nodes: ApprovalFlowNode[], + targetId: number, + parent: ApprovalFlowNode | null = null +): ApprovalFlowNode | null { + for (const node of nodes) { + if (node.id === targetId) return parent + if (node.children) { + const found = findParent(node.children, targetId, node) + if (found) return found + } + } + return null +} + +export function findNodeById(nodes: ApprovalFlowNode[], targetId: number): ApprovalFlowNode | null { + for (const node of nodes) { + if (node.id === targetId) return node + if (node.children) { + const found = findNodeById(node.children, targetId) + if (found) return found + } + } + return null +} + +// Путь от корня дерева категории до узла (включительно). Нужен, чтобы +// посчитать, какие data_key/data_value уже "накопились" на этом пути — +// именно так реальный бот собирает `collected` при прохождении сценария. +export function getPathToNode(tree: ApprovalFlowNode[], targetId: number): ApprovalFlowNode[] { + const path: ApprovalFlowNode[] = [] + const walk = (nodes: ApprovalFlowNode[]): boolean => { + for (const n of nodes) { + path.push(n) + if (n.id === targetId) return true + if (n.children && walk(n.children)) return true + path.pop() + } + return false + } + walk(tree) + return path +} + +// Собирает collected (data_key -> data_value) по цепочке узлов пути. +// Мультиселект-узлы на одном пути объединяются через запятую — это +// приближение (реальный пользователь может выбрать несколько узлов +// мультиселекта одновременно), для целей предпросмотра/проверки этого +// достаточно. +export function collectFromPath(path: ApprovalFlowNode[]): Record { + const collected: Record = {} + for (const n of path) { + if (n.data_key && n.data_value) { + collected[n.data_key] = n.data_value + } + if (n.multi_select_key && n.multi_select_value) { + collected[n.multi_select_key] = collected[n.multi_select_key] + ? `${collected[n.multi_select_key]},${n.multi_select_value}` + : n.multi_select_value + } + } + return collected +} + +// Все пути от корня до "концов" дерева (узел без детей ИЛИ узел +// текстового ввода — именно на нём сценарий завершается и определяется +// тема заявки). +export function collectLeafPaths(tree: ApprovalFlowNode[]): ApprovalFlowNode[][] { + const leaves: ApprovalFlowNode[][] = [] + const walk = (nodes: ApprovalFlowNode[], path: ApprovalFlowNode[]) => { + for (const n of nodes) { + const nextPath = [...path, n] + if (n.is_input || !n.children || n.children.length === 0) { + leaves.push(nextPath) + } else { + walk(n.children, nextPath) + } + } + } + walk(tree, []) + return leaves +} + +export function pathLabel(path: ApprovalFlowNode[]): string { + return path.map((n) => n.label).join(' → ') +} + +// ============================================================ +// Перемещение по уровням ("поднять/опустить уровень") +// ============================================================ + +export interface MoveTarget { + new_parent_id: number | null + new_sort_order: number +} + +// "Поднять уровень": узел становится соседом своего текущего родителя +// (переходит на уровень выше), а не остаётся его ребёнком. +export function getPromoteMove(tree: ApprovalFlowNode[], node: ApprovalFlowNode): MoveTarget | null { + if (!node.id) return null + const parent = findParent(tree, node.id) + if (!parent || !parent.id) return null // узел уже на самом верхнем уровне + + const grandParent = findParent(tree, parent.id) + const grandSiblings = grandParent ? grandParent.children || [] : tree + const parentIndex = grandSiblings.findIndex((n) => n.id === parent.id) + + return { + new_parent_id: grandParent?.id ?? null, + new_sort_order: parentIndex + 1, + } +} + +// "Опустить уровень": узел становится последним ребёнком своего +// предыдущего соседа (вкладывается на уровень ниже). +export function getDemoteMove(tree: ApprovalFlowNode[], node: ApprovalFlowNode): MoveTarget | null { + if (!node.id) return null + const parent = findParent(tree, node.id) + const siblings = parent ? parent.children || [] : tree + const index = siblings.findIndex((n) => n.id === node.id) + if (index <= 0) return null // нет предыдущего соседа, чтобы вложиться в него + + const newParent = siblings[index - 1] + if (!newParent.id) return null + + return { + new_parent_id: newParent.id, + new_sort_order: newParent.children?.length ?? 0, + } +} + +// ============================================================ +// Черновик шаблона сообщения +// ============================================================ + +// Бэкенд теперь умеет подставлять "{{.key_label}}" для ЛЮБОГО DataKey — не +// только для зашитого в addLabelMappings списка (см. DYNAMIC_TOPIC_PATCH.txt: +// addTreeLabelMappings берёт подпись прямо из Label узла дерева, с приоритетом +// над старым хардкодом). Поэтому черновик сообщения теперь всегда предлагает +// "_label"-версию — она либо подставится из названия соответствующей кнопки, +// либо (для совсем старых зашитых значений) из старой карты addLabelMappings. +function placeholderFor(key: string): string { + return `{{.${key}_label}}` +} + +// Собирает ВСЕ DataKey/MultiSelectKey по всему дереву, а не только у +// прямых детей корня — на любой глубине вложенности. +export function collectAllDataKeys(node: ApprovalFlowNode): string[] { + const acc: string[] = [] + const walk = (n: ApprovalFlowNode) => { + for (const child of n.children || []) { + if (child.data_key) acc.push(child.data_key) + if (child.multi_select_key) acc.push(child.multi_select_key) + if (child.children?.length) walk(child) + } + } + walk(node) + return Array.from(new Set(acc)) +} + +// Ищет DataKey/MultiSelectKey, которые реально встречаются в дереве, но не +// упомянуты в шаблоне кода темы. Эвристика: ищем подстроку ".ключ" — +// покрывает и {{.branch}}, и {{if .branch}}, и {{if eq .branch "..."}}. +// Пустой шаблон означает автосборку кода (см. TopicCodeFromCollected на +// бэкенде) — она и так подхватывает любые ключи сама, предупреждать не о чем. +export function findMissingKeysInCodeTemplate(root: ApprovalFlowNode, codeTemplate: string): string[] { + if (!codeTemplate) return [] + return collectAllDataKeys(root).filter((k) => !codeTemplate.includes(`.${k}`)) +} + +// Строит кусок шаблона для одного "потерянного" ключа — оборачиваем в +// {{if}}, чтобы не сломать ветки, где этого ключа нет вообще (например, +// более старые темы категории, у которых на один уровень вложенности +// меньше). +export function buildMissingKeySegment(key: string): string { + return `{{if .${key}}}_{{.${key}}}{{end}}` +} + +// Генерирует ЧЕРНОВИК Go-шаблона сообщения согласующему. Это стартовая +// точка, а не готовое решение — админ должен проверить результат через +// живой предпросмотр и доработать формулировки при необходимости. +// +// Заголовок строится по первому уровню развилок (как раньше) — это +// обычно самое важное различие между ветками, поэтому его выносим в +// заголовок сообщения. А дальше — отдельной строкой на каждый DataKey, +// который вообще встречается в дереве, НА ЛЮБОЙ глубине. Каждая такая +// строка обёрнута в {{if .key}}...{{end}} и поэтому появляется в +// сообщении, только если сотрудник реально прошёл через тот шаг, где +// этот ключ собирается — остальные строки просто не покажутся, это +// нормально для дерева с разными по длине ветками. +export function generateDraftMessageTemplate(root: ApprovalFlowNode): string { + const children = root.children || [] + const withDataKey = children.filter((c) => c.data_key && c.data_value) + + let titleKey: string | undefined + let title = root.label + + if (withDataKey.length > 0) { + const dataKey = withDataKey[0].data_key + const uniform = withDataKey.every((c) => c.data_key === dataKey) + if (uniform && dataKey) { + titleKey = dataKey + let chain = '' + withDataKey.forEach((c, i) => { + const cond = `eq .${dataKey} "${c.data_value}"` + chain += i === 0 ? `{{if ${cond}}}${c.label}` : `{{else if ${cond}}}${c.label}` + }) + chain += `{{else}}${root.label}{{end}}` + title = chain + } + } + + const bodyKeys = collectAllDataKeys(root).filter((k) => k !== titleKey) + const bodyLines = bodyKeys.map((k) => `{{if .${k}}}${k}: ${placeholderFor(k)}\n{{end}}`).join('') + + return `📋 ${title}\n${bodyLines}\n{{.initiator_name}}:\n{{.content}}` +} +-----END src/features/flowNodes/utils/treeWalk.ts----- + +File: src/features/hierarchies/hooks/useHierarchies.ts +Lines: 88 +-----BEGIN src/features/hierarchies/hooks/useHierarchies.ts----- +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { + hierarchiesApi, + type HierarchiesListParams, + type CreateHierarchyRequest, + type UpdateHierarchyRequest +} from '@/api/hierarchies' +import { notifications } from '@mantine/notifications' + +export const HIERARCHIES_QUERY_KEY = 'hierarchies' + +export function useHierarchies(params: HierarchiesListParams = {}) { + return useQuery({ + queryKey: [HIERARCHIES_QUERY_KEY, params], + queryFn: async () => { + const response = await hierarchiesApi.getList({ limit: 1000, ...params }) + return response.data + }, + }) +} + +export function useCreateHierarchy() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (data: CreateHierarchyRequest) => hierarchiesApi.create(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Связь создана', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось создать связь', + color: 'red', + }) + }, + }) +} + +export function useUpdateHierarchy() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (data: UpdateHierarchyRequest) => hierarchiesApi.update(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Связь обновлена', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось обновить связь', + color: 'red', + }) + }, + }) +} + +export function useDeleteHierarchy() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (id: number) => hierarchiesApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [HIERARCHIES_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/hierarchies/hooks/useHierarchies.ts----- + +File: src/features/hierarchies/hooks/useSystemOptions.ts +Lines: 72 +-----BEGIN src/features/hierarchies/hooks/useSystemOptions.ts----- +import { useQuery } from '@tanstack/react-query' +import { useCategories } from '@/features/categories/hooks/useCategories' +import { useFlowNodesTree } from '@/features/flowNodes/hooks/useFlowNodes' +import { flowNodesApi } from '@/api/flowNodes' +import type { ApprovalFlowNode } from '@/types/api' + +export interface SystemOption { + value: string + label: string +} + +function extractSystemOptions(nodes: ApprovalFlowNode[] | null | undefined): SystemOption[] { + if (!nodes) return [] + const seen = new Map() + + // Рекурсивный обход всех вложенностей + function traverse(nodeList: ApprovalFlowNode[]) { + for (const n of nodeList) { + // Ищем мультиселект с ключом systems + if (n.is_multi_select && n.multi_select_key === 'systems' && n.multi_select_value) { + if (!seen.has(n.multi_select_value)) { + seen.set(n.multi_select_value, n.label || n.multi_select_value) + } + } + // Погружаемся в дочерние узлы + if (n.children && n.children.length > 0) { + traverse(n.children) + } + } + } + + traverse(nodes) + return Array.from(seen.entries()).map(([value, label]) => ({ value, label })) +} + +export function useCategorySystemOptions(categoryId: number | null) { + const { data, isLoading } = useFlowNodesTree(categoryId) + const options = extractSystemOptions(data?.data) + return { options, isLoading: categoryId ? isLoading : false } +} + +export function useAllSystemOptions(enabled: boolean = true) { + const { data: categories } = useCategories({ limit: 1000 }) + const categoryIds = (categories?.data ?? []) + .map((c) => c.id) + .filter((id): id is number => !!id) + + // Используем один запрос и последовательно опрашиваем категории, чтобы избежать 429 Too Many Requests + const { data: options = [], isLoading } = useQuery({ + queryKey: ['all-systems-scan', categoryIds], + queryFn: async () => { + const seen = new Map() + + for (const id of categoryIds) { + try { + const response = await flowNodesApi.getTree(id) + const opts = extractSystemOptions(response.data?.data) + opts.forEach(o => { + if (!seen.has(o.value)) seen.set(o.value, o.label) + }) + } catch (e) { + console.warn(`[useAllSystemOptions] Ошибка загрузки дерева для категории ${id}`, e) + } + } + return Array.from(seen.entries()).map(([value, label]) => ({ value, label })) + }, + enabled: enabled && categoryIds.length > 0, + }) + + return { options, isLoading } +} + +export const ALL_SYSTEMS_VALUE = 'all' +-----END src/features/hierarchies/hooks/useSystemOptions.ts----- + +File: src/features/hierarchies/utils.ts +Lines: 85 +-----BEGIN src/features/hierarchies/utils.ts----- +import type { UserHierarchy } from '@/types/api' + +// Тип области действия +export type ScopeType = 'global' | 'category' | 'topic' + +// Группа цепочек (по подчинённому + отделу + области действия) +export interface ChainGroup { + key: string + subordinateId: number + subordinateName: string + departmentId: number + departmentName: string + scopeType: ScopeType + scopeObjectId: number | null + scopeObjectName: string + steps: UserHierarchy[] // Отсортированы по priority +} + +// Определяем тип области действия +export function getScopeType(h: UserHierarchy): ScopeType { + if (h.topic_id) return 'topic' + if (h.topic_category_id) return 'category' + return 'global' +} + +// Группируем иерархии по цепочкам +export function groupHierarchiesIntoChains( + hierarchies: UserHierarchy[] +): ChainGroup[] { + const groups = new Map() + + for (const h of hierarchies) { + if (!h.subordinate_id || !h.department_id) continue + + const scopeType = getScopeType(h) + const scopeObjectId = scopeType === 'topic' ? h.topic_id : + scopeType === 'category' ? h.topic_category_id : null + + // Формируем ключ группы (добавляем target_system) + const targetSystemPart = h.target_system || 'all' + const key = `${h.subordinate_id}-${h.department_id}-${scopeType}-${scopeObjectId || 'null'}-${targetSystemPart}` + + if (!groups.has(key)) { + let scopeObjectName = 'Все темы' + if (scopeType === 'category' && h.subordinate) { + scopeObjectName = `Категория #${scopeObjectId}` + } else if (scopeType === 'topic') { + scopeObjectName = `Тема #${scopeObjectId}` + } + + groups.set(key, { + key, + subordinateId: h.subordinate_id, + subordinateName: h.subordinate?.full_name || `Пользователь #${h.subordinate_id}`, + departmentId: h.department_id, + departmentName: h.department?.name || `Отдел #${h.department_id}`, + scopeType, + scopeObjectId, + scopeObjectName, + steps: [], + }) + } + + groups.get(key)!.steps.push(h) + } + + // Сортируем шаги по priority внутри каждой группы + for (const group of groups.values()) { + group.steps.sort((a, b) => (a.priority || 0) - (b.priority || 0)) + } + + return Array.from(groups.values()) +} + +// Цвета для scope types +export const SCOPE_COLORS: Record = { + global: 'violet', + category: 'blue', + topic: 'orange', +} + +export const SCOPE_LABELS: Record = { + 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}>` + }) + + 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/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----- + diff --git a/src/App.tsx b/src/App.tsx index 7bc6c87..d2e487b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -21,6 +21,7 @@ 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' +import MonthlyOrdersSettingsPage from "@/pages/monthlyOrders/MonthlyOrdersSettingsPage.tsx"; const Placeholder = ({ title }: { title: string }) => (

@@ -58,6 +59,7 @@ function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/api/admins.ts b/src/api/admins.ts index ec2bd68..d32504f 100644 --- a/src/api/admins.ts +++ b/src/api/admins.ts @@ -13,6 +13,7 @@ export interface CreateAdminRequest { name?: string is_root?: boolean is_observer?: boolean // 🆕 + is_analyst?: boolean telegram_id?: number // 🆕 } @@ -22,6 +23,7 @@ export interface UpdateAdminRequest { is_blocked?: boolean is_root?: boolean is_observer?: boolean // 🆕 + is_analyst?: boolean telegram_id?: number | null // 🆕 } diff --git a/src/api/monthlyOrders.ts b/src/api/monthlyOrders.ts new file mode 100644 index 0000000..44b0600 --- /dev/null +++ b/src/api/monthlyOrders.ts @@ -0,0 +1,10 @@ +import apiClient from './client' +import type { MonthlyOrderSetting } from '@/types/api' + +export const monthlyOrdersApi = { + getSettings: () => + apiClient.get('/monthly-orders/settings'), + + saveSettings: (data: MonthlyOrderSetting) => + apiClient.post<{status: string}>('/monthly-orders/settings', data), +} \ No newline at end of file diff --git a/src/components/Layout/Sidebar.tsx b/src/components/Layout/Sidebar.tsx index 42b3c86..e4be7eb 100644 --- a/src/components/Layout/Sidebar.tsx +++ b/src/components/Layout/Sidebar.tsx @@ -18,7 +18,7 @@ import { IconCheck, IconBellRinging, IconBlocks, - IconHistory, + IconHistory, IconChartBar, } from '@tabler/icons-react' import { useLocation, useNavigate } from 'react-router-dom' import { useAuth } from '@/hooks/useAuth' @@ -36,6 +36,13 @@ const menuItems: MenuItem[] = [ { label: 'Администраторы', icon: IconUserCog, path: '/admins', adminOnly: true }, { label: 'Уведомления', icon: IconBellRinging, path: '/notifications', adminOnly: true }, { label: 'Журнал действий', icon: IconHistory, path: '/logs', adminOnly: true }, + { + label: 'Заказы на месяц', + icon: IconChartBar, + path: '/monthly-orders-settings', + adminOnly: true, // Скрываем от наблюдателей + // Если нужно скрыть от менеджеров, можно добавить флаг analystOnly: true и фильтровать + }, { label: 'Система согласований', icon: IconFileCheck, @@ -164,6 +171,7 @@ function MenuItemLink({ item, level }: { item: MenuItem; level: number }) { export default function Sidebar() { const { user } = useAuth() const isObserver = user?.is_observer === true + const isAnalyst = user?.is_analyst === true || user?.is_root === true // 🆕 Фильтруем меню в зависимости от роли const filteredMenuItems = useMemo( diff --git a/src/features/monthlyOrders/hooks/useMonthlyOrderSettings.ts b/src/features/monthlyOrders/hooks/useMonthlyOrderSettings.ts new file mode 100644 index 0000000..a110edf --- /dev/null +++ b/src/features/monthlyOrders/hooks/useMonthlyOrderSettings.ts @@ -0,0 +1,39 @@ +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { monthlyOrdersApi } from '@/api/monthlyOrders' +import { notifications } from '@mantine/notifications' +import type { MonthlyOrderSetting } from '@/types/api' + +export const MO_SETTINGS_QUERY_KEY = 'mo-settings' + +export function useMonthlyOrderSettings() { + return useQuery({ + queryKey: [MO_SETTINGS_QUERY_KEY], + queryFn: async () => { + const response = await monthlyOrdersApi.getSettings() + return response.data + }, + }) +} + +export function useSaveMonthlyOrderSettings() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (data: MonthlyOrderSetting) => monthlyOrdersApi.saveSettings(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [MO_SETTINGS_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Настройки заказов на месяц сохранены', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось сохранить настройки', + color: 'red', + }) + }, + }) +} \ No newline at end of file diff --git a/src/pages/admins/AdminsPage.tsx b/src/pages/admins/AdminsPage.tsx index 4cc3b55..037840e 100644 --- a/src/pages/admins/AdminsPage.tsx +++ b/src/pages/admins/AdminsPage.tsx @@ -24,7 +24,7 @@ import { IconLockOpen, IconPencil, IconShield, - IconUser, + IconUser, IconChartBar, } from '@tabler/icons-react' import { modals } from '@mantine/modals' import { notifications } from '@mantine/notifications' @@ -263,14 +263,19 @@ export default function AdminsPage() { ROOT )} + {admin.is_analyst && ( + }> + Аналитик + + )} {admin.is_observer && ( }> Наблюдатель )} - {!isAdminRoot && !admin.is_observer && ( + {!isAdminRoot && !admin.is_observer && !admin.is_analyst && ( - Админ + Менеджер / Админ )} diff --git a/src/pages/admins/components/CreateAdminModal.tsx b/src/pages/admins/components/CreateAdminModal.tsx index 0faaa7d..ff0ff0e 100644 --- a/src/pages/admins/components/CreateAdminModal.tsx +++ b/src/pages/admins/components/CreateAdminModal.tsx @@ -16,7 +16,7 @@ import { Select, } from '@mantine/core' import { useForm } from '@mantine/form' -import { IconCheck, IconCopy, IconKey, IconAlertCircle, IconShield, IconUser } from '@tabler/icons-react' +import {IconCheck, IconCopy, IconKey, IconAlertCircle, IconShield, IconUser, IconChartBar} from '@tabler/icons-react' import { useCreateAdmin } from '@/features/admins/hooks/useAdmins' import { useUsers } from '@/features/users/hooks/useUsers' import type { Admin } from '@/types/api' @@ -37,6 +37,7 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr name: '', is_root: false, is_observer: false, + is_analyst: false, telegram_id: null as number | null, }, validate: { @@ -75,6 +76,7 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr login: values.login, name: values.name || undefined, is_root: values.is_root, + is_analyst: values.is_analyst, is_observer: values.is_observer, telegram_id: values.is_observer ? values.telegram_id! : undefined, }) @@ -196,6 +198,22 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr /> + + + + Аналитик (Заказы) + + } + description="Имеет доступ к настройкам и просмотру всех заказов на месяц." + checked={form.values.is_analyst} + onChange={(e) => form.setFieldValue('is_analyst', e.currentTarget.checked)} + color="grape" + disabled={form.values.is_root || form.values.is_observer} + /> + + - {form.values.is_observer && ( + {form.values.is_observer || form.values.is_observer && (