admin_ruspet/react_code.txt

19592 lines
839 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

├── .env
├── .env.example
├── .gitea
│ ├── workflows
│ │ ├── deploy-frontend.yml
├── .gitignore
├── README.md
├── eslint.config.js
├── index.html
├── package-lock.json
├── package.json
├── public
│ ├── favicon.svg
│ ├── icons.svg
├── src
│ ├── App.css
│ ├── App.tsx
│ ├── api
│ │ ├── adminLogs.ts
│ │ ├── admins.ts
│ │ ├── approvalTasks.ts
│ │ ├── approvals.ts
│ │ ├── auth.ts
│ │ ├── categories.ts
│ │ ├── client.ts
│ │ ├── dashboard.ts
│ │ ├── departments.ts
│ │ ├── flowNodes.ts
│ │ ├── hierarchies.ts
│ │ ├── notifications.ts
│ │ ├── permissions.ts
│ │ ├── roles.ts
│ │ ├── time.ts
│ │ ├── topicExecutors.ts
│ │ ├── topics.ts
│ │ ├── userRoles.ts
│ │ ├── users.ts
│ ├── assets
│ │ ├── hero.png
│ │ ├── react.svg
│ │ ├── vite.svg
│ ├── components
│ │ ├── CopyRolesModal.tsx
│ │ ├── DiagnosticErrorBoundary.tsx
│ │ ├── Layout
│ │ │ ├── Header.tsx
│ │ │ ├── MainLayout.tsx
│ │ │ ├── Sidebar.tsx
│ │ ├── TopicGapsModal.tsx
│ │ ├── UserEditModal.tsx
│ ├── features
│ │ ├── adminLogs
│ │ │ ├── hooks
│ │ │ │ ├── useAdminLogs.ts
│ │ ├── admins
│ │ │ ├── hooks
│ │ │ │ ├── useAdmins.ts
│ │ ├── approvalTasks
│ │ │ ├── const.ts
│ │ │ ├── hooks
│ │ │ │ ├── useApprovalTasks.ts
│ │ ├── approvals
│ │ │ ├── hooks
│ │ │ │ ├── useApprovals.ts
│ │ ├── categories
│ │ │ ├── hooks
│ │ │ │ ├── useCategories.ts
│ │ ├── departments
│ │ │ ├── components
│ │ │ │ ├── DepartmentEditModal.tsx
│ │ │ ├── hooks
│ │ │ │ ├── useDepartments.ts
│ │ ├── flowNodes
│ │ │ ├── hooks
│ │ │ │ ├── useFlowNodes.ts
│ │ │ ├── utils
│ │ │ │ ├── flattenTree.ts
│ │ │ │ ├── treeWalk.ts
│ │ ├── hierarchies
│ │ │ ├── hooks
│ │ │ │ ├── useHierarchies.ts
│ │ │ │ ├── useSystemOptions.ts
│ │ │ ├── utils.ts
│ │ ├── notifications
│ │ │ ├── hooks
│ │ │ │ ├── useNotifications.ts
│ │ │ ├── utils
│ │ │ │ ├── telegramHtml.ts
│ │ ├── permissions
│ │ │ ├── constants.ts
│ │ │ ├── hooks
│ │ │ │ ├── usePermissions.ts
│ │ ├── roles
│ │ │ ├── hooks
│ │ │ │ ├── useAllRoles.ts
│ │ │ │ ├── useRoles.ts
│ │ ├── topicExecutors
│ │ │ ├── hooks
│ │ │ │ ├── useTopicExecutors.ts
│ │ │ ├── utils.ts
│ │ ├── topics
│ │ │ ├── constants.ts
│ │ │ ├── hooks
│ │ │ │ ├── useTopics.ts
│ │ ├── users
│ │ │ ├── hooks
│ │ │ │ ├── useDepartments.ts
│ │ │ │ ├── useRoles.ts
│ │ │ │ ├── useUserRoles.ts
│ │ │ │ ├── useUsers.ts
│ ├── hooks
│ │ ├── useAuth.ts
│ ├── index.css
│ ├── main.tsx
│ ├── pages
│ │ ├── Dashboard.tsx
│ │ ├── DepartmentsPage.tsx
│ │ ├── Login.tsx
│ │ ├── adminLogs
│ │ │ ├── AdminLogsPage.tsx
│ │ │ ├── components
│ │ │ │ ├── AdminLogDetailModal.tsx
│ │ ├── admins
│ │ │ ├── AdminsPage.tsx
│ │ │ ├── components
│ │ │ │ ├── CreateAdminModal.tsx
│ │ │ │ ├── EditAdminModal.tsx
│ │ ├── approvalTasks
│ │ │ ├── ApprovalTasksPage.tsx
│ │ │ ├── components
│ │ │ │ ├── ApprovalTaskDetailsModal.tsx
│ │ ├── approvals
│ │ │ ├── ApprovalsPage.tsx
│ │ │ ├── components
│ │ │ │ ├── ApprovalDetailsModal.tsx
│ │ │ │ ├── FilePreviewModal.tsx
│ │ ├── categories
│ │ │ ├── CategoriesPage.tsx
│ │ │ ├── components
│ │ │ │ ├── CategoryEditModal.tsx
│ │ ├── flowNodes
│ │ │ ├── FlowTreeGuidePage.tsx
│ │ │ ├── FlowTreePage.tsx
│ │ │ ├── components
│ │ │ │ ├── CategoryCreateModal.tsx
│ │ │ │ ├── DataFlowExplainer.tsx
│ │ │ │ ├── FlowNodeEditModal.tsx
│ │ │ │ ├── SortableFlowTree.tsx
│ │ │ │ ├── TreeHealthPanel.tsx
│ │ ├── hierarchies
│ │ │ ├── HierarchiesPage.tsx
│ │ │ ├── components
│ │ │ │ ├── ChainDuplicateModal.tsx
│ │ │ │ ├── ChainVisualization.tsx
│ │ │ │ ├── HierarchyEditModal.tsx
│ │ │ │ ├── PersonDuplicateModal.tsx
│ │ ├── notifications
│ │ │ ├── NotificationsPage.tsx
│ │ │ ├── components
│ │ │ │ ├── NotificationDetailsModal.tsx
│ │ │ │ ├── NotificationsHistoryTable.tsx
│ │ │ │ ├── SendNotificationForm.tsx
│ │ ├── permissions
│ │ │ ├── PermissionsPage.tsx
│ │ │ ├── components
│ │ │ │ ├── PermissionEditModal.tsx
│ │ ├── roles
│ │ │ ├── RolesPage.tsx
│ │ │ ├── components
│ │ │ │ ├── RoleEditModal.tsx
│ │ ├── settings
│ │ │ ├── SettingsPage.tsx
│ │ ├── topicExecutors
│ │ │ ├── TopicExecutorsPage.tsx
│ │ │ ├── components
│ │ │ │ ├── TopicExecutorEditModal.tsx
│ │ │ │ ├── TopicExecutorsCard.tsx
│ │ ├── topics
│ │ │ ├── TopicsPage.tsx
│ │ │ ├── components
│ │ │ │ ├── TopicEditModal.tsx
│ │ ├── users
│ │ │ ├── UsersPage.tsx
│ ├── theme.ts
│ ├── types
│ │ ├── api.ts
│ ├── utils
│ │ ├── date.ts
│ ├── vite-env.d.ts
├── tsconfig.app.json
├── tsconfig.json
├── tsconfig.node.json
├── vite.config.ts
File: eslint.config.js
Lines: 22
-----BEGIN eslint.config.js-----
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
globals: globals.browser,
},
},
])
-----END eslint.config.js-----
File: src/App.css
Lines: 184
-----BEGIN src/App.css-----
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}
-----END src/App.css-----
File: src/App.tsx
Lines: 78
-----BEGIN src/App.tsx-----
import { Routes, Route, Navigate } from 'react-router-dom'
import MainLayout from './components/Layout/MainLayout'
import Login from './pages/Login'
import Dashboard from './pages/Dashboard'
import UsersPage from './pages/users/UsersPage'
import RolesPage from './pages/roles/RolesPage'
import ApprovalsPage from './pages/approvals/ApprovalsPage'
import { useAuth } from './hooks/useAuth'
import { Loader, Center, Text } from '@mantine/core'
import DepartmentsPage from "@/pages/DepartmentsPage.tsx"
import PermissionsPage from './pages/permissions/PermissionsPage'
import HierarchiesPage from './pages/hierarchies/HierarchiesPage'
import TopicExecutorsPage from "@/pages/topicExecutors/TopicExecutorsPage.tsx"
import CategoriesPage from "@/pages/categories/CategoriesPage.tsx"
import React from "react"
import TopicsPage from "@/pages/topics/TopicsPage.tsx"
import SettingsPage from './pages/settings/SettingsPage'
import AdminsPage from './pages/admins/AdminsPage'
import ApprovalTasksPage from './pages/approvalTasks/ApprovalTasksPage'
import FlowTreePage from "@/pages/flowNodes/FlowTreePage.tsx"
import FlowTreeGuidePage from './pages/flowNodes/FlowTreeGuidePage'
import NotificationsPage from "@/pages/notifications/NotificationsPage.tsx"
import AdminLogsPage from './pages/adminLogs/AdminLogsPage'
const Placeholder = ({ title }: { title: string }) => (
<div style={{ padding: 40 }}>
<Text size="xl" fw={700} mb="md">{title}</Text>
<Text c="dimmed">Страница в разработке...</Text>
</div>
)
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated, loading } = useAuth()
if (loading) {
return (
<Center h="100vh">
<Loader />
</Center>
)
}
if (!isAuthenticated) {
return <Navigate to="/login" replace />
}
return <>{children}</>
}
function App() {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route element={<ProtectedRoute><MainLayout /></ProtectedRoute>}>
<Route path="/" element={<Placeholder title="Главная" />} />
<Route path="/notifications" element={<NotificationsPage />} />
<Route path="/approval-dash" element={<Dashboard />} />
<Route path="/nodes" element={<FlowTreePage />} />
<Route path="/users" element={<UsersPage />} />
<Route path="/departments" element={<DepartmentsPage />} />
<Route path="/roles" element={<RolesPage />} />
<Route path="/approvals" element={<ApprovalsPage />} />
<Route path="/permissions" element={<PermissionsPage />} />
<Route path="/categories" element={<CategoriesPage />} />
<Route path="/topics" element={<TopicsPage />} />
<Route path="/executors" element={<TopicExecutorsPage />} />
<Route path="/hierarchies" element={<HierarchiesPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="/admins" element={<AdminsPage />} />
<Route path="/logs" element={<AdminLogsPage />} />
<Route path="/approval-tasks" element={<ApprovalTasksPage />} />
<Route path="/guide/flow-trees" element={<FlowTreeGuidePage />} />
</Route>
</Routes>
)
}
export default App
-----END src/App.tsx-----
File: src/api/adminLogs.ts
Lines: 34
-----BEGIN src/api/adminLogs.ts-----
import apiClient from './client'
import type { ApiResponse } from '@/types/api'
export interface AdminActionLog {
id: number
admin_id: number
admin_login: string
action: 'create' | 'update' | 'delete'
entity_type: string
entity_id?: number
description: string
metadata?: string
created_at: string
}
export interface AdminLogsListParams {
offset?: number
limit?: number
admin_id?: number
admin_login?: string
action?: string
entity_type?: string
entity_id?: number
date_from?: string
date_to?: string
search?: string
}
export const adminLogsApi = {
getList: (params: AdminLogsListParams = {}) =>
apiClient.get<ApiResponse<AdminActionLog[]>>('/admin-logs', { params }),
delete: (id: number) =>
apiClient.delete<boolean>(`/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<ApiResponse<Admin[]>>('/admin', { params }),
create: (data: CreateAdminRequest) =>
apiClient.post<Admin>('/admin', data),
update: (data: UpdateAdminRequest) =>
apiClient.put<Admin>('/admin', data),
delete: (id: number) =>
apiClient.delete<boolean>('/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<ApiResponse<ApprovalTask[]>>('/approval-tasks', { params }),
getById: (id: number) =>
apiClient.get<ApprovalTask>(`/approval-tasks/${id}`),
update: (data: UpdateApprovalTaskRequest) =>
apiClient.put<ApprovalTask>('/approval-tasks', data),
delete: (id: number) =>
apiClient.delete<boolean>('/approval-tasks', { data: { id } }),
}
-----END src/api/approvalTasks.ts-----
File: src/api/approvals.ts
Lines: 197
-----BEGIN src/api/approvals.ts-----
import apiClient from './client'
import type { Approval, ApiResponse } from '@/types/api'
export interface PlannedTask {
id: number
task_text: string
executor_name?: string
step_order: number
}
export interface ApprovalTaskItem {
id: number
task_text: string
executor_name: string
status: 'pending' | 'waiting' | 'completed' | 'cancelled' | 'cancellation'
completed_at?: string
}
export interface ApprovalTasksResponse {
topic_executors: PlannedTask[]
tasks: ApprovalTaskItem[]
has_task_error: boolean
}
export interface ApprovalsListParams {
offset?: number
limit?: number
status?: string
initiator_id?: number
topic_id?: number // одиночный (для обратной совместимости)
topic_ids?: number[] // 🆕 множественный выбор тем
category_ids?: number[] // 🆕 множественный выбор категорий
department_id?: number
date_from?: string // 🆕 YYYY-MM-DD
date_to?: string // 🆕 YYYY-MM-DD
content?: string
}
export interface ApprovalsReportParams {
user_id?: number
date_from?: string // YYYY-MM-DD
date_to?: string // YYYY-MM-DD
all_access?: boolean
}
export interface UpdateApprovalRequest {
id: number
status?: string
revision_comment?: string
}
export const approvalsApi = {
getList: (params: ApprovalsListParams = {}) => {
// Формируем query-параметры, корректно сериализуя массивы
const query: Record<string, any> = {}
if (params.offset !== undefined) query.offset = params.offset
if (params.limit !== undefined) query.limit = params.limit
if (params.status) query.status = params.status
if (params.initiator_id) query.initiator_id = params.initiator_id
if (params.topic_id) query.topic_id = params.topic_id
if (params.department_id) query.department_id = params.department_id
if (params.content) query.content = params.content
if (params.date_from) query.date_from = params.date_from
if (params.date_to) query.date_to = params.date_to
// 🆕 Массивы передаём через запятую: "1,2,3"
if (params.topic_ids && params.topic_ids.length > 0) {
query.topic_ids = params.topic_ids.join(',')
}
if (params.category_ids && params.category_ids.length > 0) {
query.category_ids = params.category_ids.join(',')
}
return apiClient.get<ApiResponse<Approval[]>>('/approvals', { params: query })
},
getById: (id: number) =>
apiClient.get<Approval>(`/approvals/${id}`),
update: (data: UpdateApprovalRequest) =>
apiClient.put<Approval>('/approvals', data),
delete: (id: number) =>
apiClient.delete<boolean>('/approvals', { data: { id } }),
getTasks: (approvalId: number) =>
apiClient.get<ApiResponse<ApprovalTasksResponse>>(`/approvals/${approvalId}/tasks`),
getForReport: (params: ApprovalsReportParams = {}) =>
apiClient.get<ApiResponse<Approval[]>>('/approvals/report', { params }),
downloadReport: (params: ApprovalsReportParams = {}) =>
apiClient.get('/approvals/report/download', {
params,
responseType: 'blob',
}),
getAdditionalApprovers: (approvalId: number) =>
apiClient.get<ApiResponse<AdditionalApprover[]>>(`/approvals/${approvalId}/additional-approvers`),
getComments: (approvalId: number) =>
apiClient.get<ApiResponse<ApprovalComment[]>>(`/approvals/${approvalId}/comments`),
getObservers: (approvalId: number) =>
apiClient.get<ApiResponse<ApprovalObserver[]>>(`/approvals/${approvalId}/observers`),
getRevocationRequest: (approvalId: number) =>
apiClient.get<ApiResponse<RevocationRequest | null>>(`/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<LoginResponse>('/auth/login', data),
getProfile: () =>
apiClient.get<Admin>('/admin/profile'),
logout: () =>
apiClient.post('/auth/logout'),
// 🆕 Смена пароля через существующий endpoint
updateProfile: (data: UpdateProfileRequest) =>
apiClient.put<Admin>('/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<ApiResponse<ApprovalTopicCategory[]>>('/categories', { params }),
getById: (id: number) =>
apiClient.get<ApprovalTopicCategory>(`/categories/${id}`),
create: (data: CreateCategoryRequest) =>
apiClient.post<ApprovalTopicCategory>('/categories', data),
update: (data: UpdateCategoryRequest) =>
apiClient.put<ApprovalTopicCategory>('/categories', data),
delete: (id: number) =>
apiClient.delete<boolean>('/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<void> | 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<void> {
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<DashboardStats>('/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<ApiResponse<Department[]>>('/departments', { params }),
// Получить отдел по ID
getById: (id: number) =>
apiClient.get<Department>(`/departments/${id}`),
// Создать отдел
create: (data: CreateDepartmentRequest) =>
apiClient.post<Department>('/departments', data),
// Обновить отдел
update: (data: UpdateDepartmentRequest) =>
apiClient.put<Department>('/departments', data),
// Удалить отдел
delete: (id: number) =>
apiClient.delete<boolean>('/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<string, string>
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<ApiResponse<ApprovalFlowNode[]>>(`/flow-nodes/category/${categoryId}?limit=1000`),
getById: (id: number) =>
apiClient.get<ApprovalFlowNode>(`/flow-nodes/${id}`),
create: (data: CreateFlowNodeRequest) =>
apiClient.post<ApprovalFlowNode>('/flow-nodes/', data),
update: (data: UpdateFlowNodeRequest) =>
apiClient.put<ApprovalFlowNode>('/flow-nodes/', data),
delete: (id: number) =>
apiClient.delete<boolean>('/flow-nodes/', { data: { id } }),
saveTree: (categoryId: number, data: SaveTreeRequest) =>
apiClient.post<boolean>(`/flow-nodes/category/${categoryId}/tree`, data),
move: (id: number, data: MoveFlowNodeRequest) =>
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/move`, data),
duplicate: (id: number) =>
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/duplicate`, {}),
// НОВОЕ
preview: (categoryId: number, data: PreviewFlowRequest) =>
apiClient.post<PreviewFlowResponse>(`/flow-nodes/category/${categoryId}/preview`, data),
// НОВОЕ: форсировать обновление Registry в процессе бота (без перезапуска)
reloadBot: () => apiClient.post<boolean>('/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<ApiResponse<UserHierarchy[]>>('/hierarchies', { params }),
getById: (id: number) =>
apiClient.get<UserHierarchy>(`/hierarchies/${id}`),
create: (data: CreateHierarchyRequest) =>
apiClient.post<UserHierarchy>('/hierarchies', data),
update: (data: UpdateHierarchyRequest) =>
apiClient.put<UserHierarchy>('/hierarchies', data),
delete: (id: number) =>
apiClient.delete<boolean>('/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<ApiResponse<Notification[]>>('/notifications', { params }),
getById: (id: number) =>
apiClient.get<Notification>(`/notifications/${id}`),
create: (data: CreateNotificationRequest) =>
apiClient.post<Notification>('/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<ApiResponse<Permission[]>>('/permissions', { params }),
getById: (id: number) =>
apiClient.get<Permission>(`/permissions/${id}`),
create: (data: CreatePermissionRequest) =>
apiClient.post<Permission>('/permissions', data),
update: (data: UpdatePermissionRequest) =>
apiClient.put<Permission>('/permissions', data),
delete: (id: number) =>
apiClient.delete<boolean>('/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<ApiResponse<Role[]>>('/roles', { params }),
// Получить роль по ID
getById: (id: number) =>
apiClient.get<Role>(`/roles/${id}`),
// Создать роль
create: (data: CreateRoleRequest) =>
apiClient.post<Role>('/roles', data),
// Обновить роль
update: (data: UpdateRoleRequest) =>
apiClient.put<Role>('/roles', data),
// Удалить роль
delete: (id: number) =>
apiClient.delete<boolean>('/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<ServerTimeResponse> => {
const response = await publicApiClient.get<ServerTimeResponse>('/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<ApiResponse<ApprovalTopicExecutor[]>>('/topic-executors', { params }),
getById: (id: number) =>
apiClient.get<ApprovalTopicExecutor>(`/topic-executors/${id}`),
create: (data: CreateTopicExecutorRequest) =>
apiClient.post<ApprovalTopicExecutor>('/topic-executors', data),
update: (data: UpdateTopicExecutorRequest) =>
apiClient.put<ApprovalTopicExecutor>('/topic-executors', data),
delete: (id: number) =>
apiClient.delete<boolean>('/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<ApiResponse<ApprovalTopic[]>>('/topics', { params }),
getById: (id: number) =>
apiClient.get<ApprovalTopic>(`/topics/${id}`),
create: (data: CreateTopicRequest) =>
apiClient.post<ApprovalTopic>('/topics', data),
update: (data: UpdateTopicRequest) =>
apiClient.put<ApprovalTopic>('/topics', data),
delete: (id: number) =>
apiClient.delete<boolean>('/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<ApiResponse<UserRole[]>>(`/users/${userId}/roles`),
// Массовое назначение ролей (полная замена)
bulkAssign: (data: BulkAssignRolesRequest) =>
apiClient.post<ApiResponse<UserRole[]>>('/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<ApiResponse<User[]>>('/users', { params }),
getById: (id: number) =>
apiClient.get<User>(`/users/${id}`),
update: (data: UpdateUserRequest) =>
apiClient.put<User>('/users', data),
delete: (id: number) =>
apiClient.delete(`/users/${id}`),
}
-----END src/api/users.ts-----
File: src/components/CopyRolesModal.tsx
Lines: 122
-----BEGIN src/components/CopyRolesModal.tsx-----
import { useState } from 'react'
import {
Modal,
Stack,
TextInput,
Text,
Button,
Group,
Loader,
Center,
Paper,
Badge,
ScrollArea,
Box,
} from '@mantine/core'
import { IconSearch, IconCopy } from '@tabler/icons-react'
import { useUsers } from '@/features/users/hooks/useUsers'
interface CopyRolesModalProps {
opened: boolean
onClose: () => void
onCopy: (roleIds: number[]) => void
currentUserId: number | null
}
export default function CopyRolesModal({ opened, onClose, onCopy, currentUserId }: CopyRolesModalProps) {
const [search, setSearch] = useState('')
const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
const { data, isLoading } = useUsers({
offset: 0,
limit: 100,
...(search && { full_name: search }),
})
const users = Array.isArray(data?.data) ? data.data : []
const handleSelectUser = (userId: number) => {
setSelectedUserId(userId)
}
const handleCopy = () => {
if (!selectedUserId) return
const selectedUser = users.find(u => u.id === selectedUserId)
if (selectedUser && Array.isArray(selectedUser.user_roles)) {
const roleIds = selectedUser.user_roles
.map(ur => ur.role_id)
.filter((id): id is number => !!id)
onCopy(roleIds)
}
}
return (
<Modal
opened={opened}
onClose={onClose}
title="Скопировать роли от пользователя"
size="md"
>
<Stack gap="md">
<TextInput
placeholder="Поиск по имени..."
leftSection={<IconSearch size={16} />}
value={search}
onChange={(e) => setSearch(e.currentTarget.value)}
/>
{isLoading ? (
<Center p={40}>
<Loader />
</Center>
) : (
<ScrollArea.Autosize mah={400}>
<Stack gap="xs">
{users
.filter(u => u.id !== currentUserId)
.map((user) => (
<Paper
key={user.id}
withBorder
p="sm"
style={{
cursor: 'pointer',
backgroundColor: selectedUserId === user.id
? 'var(--mantine-color-blue-0)'
: undefined,
}}
onClick={() => handleSelectUser(user.id!)}
>
<Group justify="space-between">
<Box>
<Text fw={500} size="sm">{user.full_name}</Text>
<Text size="xs" c="dimmed">
{user.username ? `@${user.username}` : user.telegram_id}
</Text>
</Box>
<Badge variant="light" size="sm">
{Array.isArray(user.user_roles) ? user.user_roles.length : 0} ролей
</Badge>
</Group>
</Paper>
))}
</Stack>
</ScrollArea.Autosize>
)}
<Group justify="flex-end">
<Button variant="default" onClick={onClose}>
Отмена
</Button>
<Button
onClick={handleCopy}
disabled={!selectedUserId}
leftSection={<IconCopy size={16} />}
>
Скопировать роли
</Button>
</Group>
</Stack>
</Modal>
)
}
-----END src/components/CopyRolesModal.tsx-----
File: src/components/DiagnosticErrorBoundary.tsx
Lines: 90
-----BEGIN src/components/DiagnosticErrorBoundary.tsx-----
import { Component, type ErrorInfo, type ReactNode } from 'react'
import { Center, Stack, Title, Text, Button, Code, Box } from '@mantine/core'
import { IconAlertTriangle } from '@tabler/icons-react'
interface Props {
children: ReactNode
// Полноэкранный вариант — для самого верхнего "предохранителя" (main.tsx).
// Без него — занимает высоту родителя (для page-level использования
// внутри layout, где вокруг уже есть Header/Sidebar).
fullPage?: boolean
}
interface State {
error: Error | null
componentStack: string | null
}
// Общий ErrorBoundary. Используется дважды:
// 1) в main.tsx, оборачивая <App /> — последний рубеж на случай падения
// чего угодно (в т.ч. самого layout/sidebar);
// 2) в MainLayout.tsx, оборачивая <Outlet />, с key={location.pathname} —
// тогда падение ОДНОЙ страницы не рушит весь интерфейс: Header и
// Sidebar остаются рабочими, и переход на другую страницу сам
// пересоздаёт boundary и сбрасывает ошибку — reload не нужен.
export default class ErrorBoundary extends Component<Props, State> {
state: State = { error: null, componentStack: null }
static getDerivedStateFromError(error: Error) {
return { error }
}
componentDidCatch(error: Error, info: ErrorInfo) {
// 🆕 Логируем с максимумом контекста — пригодится и сейчас для
// диагностики (например, бага "белый экран после правки
// иерархии"), и впредь. Если подключите Sentry или аналог —
// отправляйте error + info отсюда же.
console.error('[ErrorBoundary] Необработанная ошибка рендера:', {
message: error.message,
stack: error.stack,
componentStack: info.componentStack,
url: window.location.href,
timestamp: new Date().toISOString(),
})
this.setState({ componentStack: info.componentStack ?? null })
}
handleReload = () => {
window.location.reload()
}
render() {
const { error, componentStack } = this.state
if (!error) {
return this.props.children
}
return (
<Center h={this.props.fullPage ? '100vh' : '100%'} p="xl">
<Stack gap="sm" maw={640} align="center">
<IconAlertTriangle size={40} color="var(--mantine-color-red-6)" />
<Title order={3} ta="center">
Произошла ошибка при загрузке страницы
</Title>
<Text c="dimmed" ta="center" size="sm">
Попробуйте перейти на другую страницу через меню слева или перезагрузить
страницу. Если ошибка повторяется — сообщите в техническую поддержку.
</Text>
<Button onClick={this.handleReload} mt="sm">
Перезагрузить страницу
</Button>
{import.meta.env.DEV && (
<Box mt="md" w="100%">
<Text size="xs" fw={600} c="dimmed" mb={4}>
Технические детали (видно только в dev-сборке):
</Text>
<Code
block
style={{ whiteSpace: 'pre-wrap', fontSize: 10, maxHeight: 240, overflow: 'auto' }}
>
{error.message}
{'\n\n'}
{componentStack}
</Code>
</Box>
)}
</Stack>
</Center>
)
}
}
-----END src/components/DiagnosticErrorBoundary.tsx-----
File: src/components/Layout/Header.tsx
Lines: 73
-----BEGIN src/components/Layout/Header.tsx-----
import {
Group,
Burger,
Text,
Avatar,
Menu,
ActionIcon,
} from '@mantine/core'
import { IconLogout, IconUser } from '@tabler/icons-react'
import { useAuth } from '@/hooks/useAuth'
interface HeaderProps {
toggleMobile: () => void
toggleDesktop: () => void
mobileOpened: boolean
desktopOpened: boolean
}
export default function Header({
toggleMobile,
toggleDesktop,
mobileOpened,
desktopOpened
}: HeaderProps) {
const { user, logout } = useAuth()
return (
<Group h="100%" px="md" justify="space-between">
<Group h="100%" gap={0}>
<Burger
opened={mobileOpened}
onClick={toggleMobile}
hiddenFrom="sm"
size="sm"
/>
<Burger
opened={desktopOpened}
onClick={toggleDesktop}
visibleFrom="sm"
size="sm"
/>
<Text ml="md" fw={700}>
Панель управления администратора
</Text>
</Group>
<Group>
<Menu shadow="md" width={200}>
<Menu.Target>
<ActionIcon variant="subtle" size="lg">
<Avatar size="sm" radius="xl">
{user?.login?.charAt(0).toUpperCase() || 'A'}
</Avatar>
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item leftSection={<IconUser size={14} />}>
{user?.login || 'Admin'}
</Menu.Item>
<Menu.Divider />
<Menu.Item
leftSection={<IconLogout size={14} />}
onClick={logout}
color="red"
>
Выйти
</Menu.Item>
</Menu.Dropdown>
</Menu>
</Group>
</Group>
)
}
-----END src/components/Layout/Header.tsx-----
File: src/components/Layout/MainLayout.tsx
Lines: 42
-----BEGIN src/components/Layout/MainLayout.tsx-----
import { AppShell } from '@mantine/core'
import { useDisclosure } from '@mantine/hooks'
import { Outlet, useLocation } from 'react-router-dom'
import Sidebar from './Sidebar'
import Header from './Header'
import ErrorBoundary from '../DiagnosticErrorBoundary'
export default function MainLayout() {
const [mobileOpened, { toggle: toggleMobile }] = useDisclosure()
const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true)
const location = useLocation()
return (
<AppShell
header={{ height: 60 }}
navbar={{
width: 280,
breakpoint: 'sm',
collapsed: { mobile: !mobileOpened, desktop: !desktopOpened },
}}
padding="md"
>
<AppShell.Header>
<Header
toggleMobile={toggleMobile}
toggleDesktop={toggleDesktop}
mobileOpened={mobileOpened}
desktopOpened={desktopOpened}
/>
</AppShell.Header>
<AppShell.Navbar p={0}>
<Sidebar />
</AppShell.Navbar>
<AppShell.Main bg="gray.0" miw={0}>
<ErrorBoundary key={location.pathname}>
<Outlet />
</ErrorBoundary>
</AppShell.Main>
</AppShell>
)
}
-----END src/components/Layout/MainLayout.tsx-----
File: src/components/Layout/Sidebar.tsx
Lines: 211
-----BEGIN src/components/Layout/Sidebar.tsx-----
import { useState, useMemo } from 'react'
import { NavLink, Box, Text, Stack, Badge } from '@mantine/core'
import {
IconDashboard,
IconFileCheck,
IconSettings,
IconChevronRight,
IconList,
IconUsers,
IconBuilding,
IconShield,
IconKey,
IconCategory,
IconBriefcase,
IconUserCheck,
IconGitBranch,
IconUserCog,
IconCheck,
IconBellRinging,
IconBlocks,
IconHistory,
} from '@tabler/icons-react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '@/hooks/useAuth'
interface MenuItem {
label: string
icon?: any
path?: string
children?: MenuItem[]
adminOnly?: boolean // скрывать от наблюдателей
}
const menuItems: MenuItem[] = [
{ label: 'Обзор', icon: IconDashboard, path: '/' },
{ label: 'Администраторы', icon: IconUserCog, path: '/admins', adminOnly: true },
{ label: 'Уведомления', icon: IconBellRinging, path: '/notifications', adminOnly: true },
{ label: 'Журнал действий', icon: IconHistory, path: '/logs', adminOnly: true },
{
label: 'Система согласований',
icon: IconFileCheck,
children: [
{ label: 'Панель управления', icon: IconDashboard, path: '/approval-dash' },
{ label: 'Заявки', icon: IconList, path: '/approvals' },
{ label: 'Задачи', icon: IconCheck, path: '/approval-tasks' },
{ label: 'Пользователи', icon: IconUsers, path: '/users' },
{ label: 'Отделы', icon: IconBuilding, path: '/departments', adminOnly: true },
{ label: 'Роли', icon: IconShield, path: '/roles', adminOnly: true },
{ label: 'Права', icon: IconKey, path: '/permissions', adminOnly: true },
{
label: 'Темы согласований',
icon: IconBriefcase,
adminOnly: true,
children: [
{ label: 'Категории', icon: IconCategory, path: '/categories' },
{ label: 'Темы', icon: IconBriefcase, path: '/topics' },
{ label: 'Исполнители', icon: IconUserCheck, path: '/executors' },
]
},
{ label: 'Конструктор тем', icon: IconBlocks, path: '/nodes', adminOnly: true },
{ label: 'Иерархия', icon: IconGitBranch, path: '/hierarchies', adminOnly: true },
]
},
{ label: 'Настройки', icon: IconSettings, path: '/settings'},
]
function filterMenuByRole(items: MenuItem[], isObserver: boolean): MenuItem[] {
return items
.filter((item) => {
if (isObserver && item.adminOnly) return false
return true
})
.map((item) => {
if (item.children) {
const filteredChildren = filterMenuByRole(item.children, isObserver)
// Если после фильтрации детей не осталось — скрываем родителя
if (filteredChildren.length === 0) return null
return { ...item, children: filteredChildren }
}
return item
})
.filter((item): item is MenuItem => item !== null)
}
function MenuItemLink({ item, level }: { item: MenuItem; level: number }) {
const location = useLocation()
const navigate = useNavigate()
const [opened, setOpened] = useState(false)
const hasChildren = item.children && item.children.length > 0
const isActive = item.path ? location.pathname === item.path : false
const hasActiveChild = item.children?.some(child =>
child.path ? location.pathname === child.path : false
) || false
const paddingLeft = 16 + level * 20
if (hasChildren) {
return (
<Box>
<NavLink
label={item.label}
leftSection={item.icon ? <item.icon size={18} /> : undefined}
rightSection={
<IconChevronRight
size={16}
style={{
transform: opened ? 'rotate(90deg)' : 'none',
transition: 'transform 0.2s ease',
}}
/>
}
active={hasActiveChild}
onClick={() => setOpened(!opened)}
styles={{
root: {
paddingLeft,
paddingRight: 12,
borderRadius: '8px',
marginBottom: 2,
'&:hover': {
backgroundColor: 'var(--mantine-color-gray-0)',
},
},
}}
/>
{opened && (
<Stack gap={2} mt={2}>
{item.children!.map((child) => (
<MenuItemLink key={child.label} item={child} level={level + 1} />
))}
</Stack>
)}
</Box>
)
}
return (
<NavLink
label={item.label}
leftSection={item.icon ? <item.icon size={18} /> : undefined}
active={isActive}
onClick={() => {
if (item.path) navigate(item.path)
}}
styles={{
root: {
paddingLeft,
paddingRight: 12,
borderRadius: '8px',
marginBottom: 2,
'&:hover': {
backgroundColor: 'var(--mantine-color-gray-0)',
},
},
label: {
fontWeight: isActive ? 600 : 400,
},
}}
/>
)
}
export default function Sidebar() {
const { user } = useAuth()
const isObserver = user?.is_observer === true
// 🆕 Фильтруем меню в зависимости от роли
const filteredMenuItems = useMemo(
() => filterMenuByRole(menuItems, isObserver),
[isObserver]
)
return (
<Box
style={{
padding: '12px 8px',
height: '100%',
overflowY: 'auto',
}}
>
<Text
size="xs"
c="dimmed"
fw={700}
mb="md"
px="sm"
style={{
textTransform: 'uppercase',
letterSpacing: '0.5px',
}}
>
Главное меню
</Text>
{/* 🆕 Индикатор режима наблюдателя */}
{isObserver && (
<Box px="sm" mb="md">
<Badge color="blue" variant="light" size="sm" fullWidth>
Режим наблюдателя
</Badge>
</Box>
)}
<Stack gap={4}>
{filteredMenuItems.map((item) => (
<MenuItemLink key={item.label} item={item} level={0} />
))}
</Stack>
</Box>
)
}
-----END src/components/Layout/Sidebar.tsx-----
File: src/components/TopicGapsModal.tsx
Lines: 79
-----BEGIN src/components/TopicGapsModal.tsx-----
import { Modal, Table, Text, Badge, Group, ScrollArea, Stack, Center } from '@mantine/core'
import { IconAlertTriangle } from '@tabler/icons-react'
interface TopicGap {
user_id: number
full_name: string
department_name: string
topic_id: number
topic_name: string
category_name: string
}
interface TopicGapsModalProps {
opened: boolean
onClose: () => void
gaps: TopicGap[]
}
export default function TopicGapsModal({ opened, onClose, gaps }: TopicGapsModalProps) {
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group gap="xs">
<IconAlertTriangle size={18} color="var(--mantine-color-orange-6)" />
<Text fw={700}>Темы без назначенного порядка согласования</Text>
</Group>
}
size="xl"
>
<Stack gap="md">
<Text size="sm" c="dimmed">
У перечисленных сотрудников есть право создавать заявку по теме, но
ни одно правило иерархии не назначает для них согласующего — при
попытке отправить такую заявку в боте она не пройдёт.
</Text>
{gaps.length === 0 ? (
<Center p={40}>
<Text c="dimmed">Пробелов не найдено — все настроено</Text>
</Center>
) : (
<ScrollArea.Autosize mah={480}>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>Сотрудник</Table.Th>
<Table.Th>Отдел</Table.Th>
<Table.Th>Категория</Table.Th>
<Table.Th>Тема</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{gaps.map((g, i) => (
<Table.Tr key={`${g.user_id}-${g.topic_id}-${i}`}>
<Table.Td>
<Text size="sm" fw={500}>{g.full_name || `ID: ${g.user_id}`}</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">{g.department_name || '—'}</Text>
</Table.Td>
<Table.Td>
<Badge size="sm" variant="light" color="violet">
{g.category_name || '—'}
</Badge>
</Table.Td>
<Table.Td>
<Text size="sm">{g.topic_name || `ID: ${g.topic_id}`}</Text>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</ScrollArea.Autosize>
)}
</Stack>
</Modal>
)
}
-----END src/components/TopicGapsModal.tsx-----
File: src/components/UserEditModal.tsx
Lines: 294
-----BEGIN src/components/UserEditModal.tsx-----
import { useEffect, useState } from 'react'
import {
Modal,
Stack,
TextInput,
Select,
MultiSelect,
Switch,
Group,
Button,
Text,
Divider,
Loader,
Center,
Badge,
Paper,
Tabs,
ActionIcon,
Tooltip,
Box,
} from '@mantine/core'
import { IconTrash, IconCopy, IconUser, IconSettings, IconShield } from '@tabler/icons-react'
import { useForm } from '@mantine/form'
import { useUser, useUpdateUser } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/users/hooks/useDepartments'
import { useRoles } from '@/features/users/hooks/useRoles'
import { useUserRoles, useBulkAssignRoles } from '@/features/users/hooks/useUserRoles'
import CopyRolesModal from './CopyRolesModal'
interface UserEditModalProps {
userId: number | null
opened: boolean
onClose: () => void
}
export default function UserEditModal({ userId, opened, onClose }: UserEditModalProps) {
const { data: user, isLoading: userLoading } = useUser(userId)
const { data: departments } = useDepartments()
const { data: allRoles } = useRoles({ limit: 1000 })
const { data: userRoles, isLoading: rolesLoading } = useUserRoles(userId)
const updateUser = useUpdateUser()
const assignRoles = useBulkAssignRoles()
const [copyRolesOpened, setCopyRolesOpened] = useState(false)
const form = useForm({
initialValues: {
full_name: '',
department_id: null as number | null,
is_blocked: false,
is_fired: false,
role_ids: [] as number[],
},
})
useEffect(() => {
if (user) {
form.setValues({
full_name: user.full_name || '',
department_id: user.department_id || null,
is_blocked: user.is_blocked || false,
is_fired: user.is_fired || false,
role_ids: Array.isArray(user.user_roles)
? user.user_roles.map((ur) => ur.role_id!)
: [],
})
}
}, [user])
useEffect(() => {
if (Array.isArray(userRoles) && userRoles.length > 0) {
const roleIds = userRoles
.map((ur) => ur.role?.id || ur.role_id)
.filter((id): id is number => !!id)
form.setFieldValue('role_ids', roleIds)
}
}, [userRoles])
const handleSubmit = async (values: typeof form.values) => {
if (!userId) return
await updateUser.mutateAsync({
id: userId,
full_name: values.full_name,
department_id: values.department_id,
is_blocked: values.is_blocked,
is_fired: values.is_fired,
})
await assignRoles.mutateAsync({
user_id: userId,
role_ids: values.role_ids,
})
onClose()
}
const handleClearAllRoles = () => {
form.setFieldValue('role_ids', [])
}
const handleCopyRoles = (roleIds: number[]) => {
form.setFieldValue('role_ids', roleIds)
setCopyRolesOpened(false)
}
const departmentOptions = Array.isArray(departments)
? departments.map((d) => ({
value: String(d.id),
label: d.name || '',
}))
: []
const roleOptions = Array.isArray(allRoles)
? allRoles.map((r) => ({
value: String(r.id),
label: r.name || '',
description: r.description,
}))
: []
const isLoading = userLoading || rolesLoading
const isSubmitting = updateUser.isPending || assignRoles.isPending
return (
<>
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>Редактирование пользователя</Text>
{user && <Badge variant="light">ID: {user.id}</Badge>}
</Group>
}
size="xl"
>
{isLoading ? (
<Center p={40}>
<Loader />
</Center>
) : user ? (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Tabs defaultValue="info" variant="outline">
<Tabs.List mb="md">
<Tabs.Tab value="info" leftSection={<IconUser size={14} />}>
Информация
</Tabs.Tab>
<Tabs.Tab value="roles" leftSection={<IconShield size={14} />}>
Роли ({form.values.role_ids.length})
</Tabs.Tab>
<Tabs.Tab value="settings" leftSection={<IconSettings size={14} />}>
Настройки
</Tabs.Tab>
</Tabs.List>
{/* Вкладка: Информация */}
<Tabs.Panel value="info">
<Stack gap="md">
<Paper withBorder p="md" bg="gray.0">
<Stack gap="xs">
<Group justify="space-between">
<Text size="sm" c="dimmed">Telegram ID:</Text>
<Text ff="monospace">{user.telegram_id}</Text>
</Group>
{user.username && (
<Group justify="space-between">
<Text size="sm" c="dimmed">Username:</Text>
<Text>@{user.username}</Text>
</Group>
)}
{user.last_login && (
<Group justify="space-between">
<Text size="sm" c="dimmed">Последний вход:</Text>
<Text size="sm">
{new Date(user.last_login).toLocaleString('ru-RU')}
</Text>
</Group>
)}
</Stack>
</Paper>
<TextInput
label="ФИО"
placeholder="Иванов Иван Иванович"
value={form.values.full_name}
onChange={(e) => form.setFieldValue('full_name', e.currentTarget.value)}
required
/>
<Select
label="Отдел"
placeholder="Не назначен"
data={departmentOptions}
value={form.values.department_id ? String(form.values.department_id) : null}
onChange={(v) => form.setFieldValue('department_id', v ? Number(v) : null)}
clearable
/>
</Stack>
</Tabs.Panel>
{/* Вкладка: Роли */}
<Tabs.Panel value="roles">
<Stack gap="md">
<Group justify="space-between">
<Text size="sm" fw={500}>
Выбрано ролей: {form.values.role_ids.length}
</Text>
<Group gap="xs">
<Tooltip label="Снять все роли">
<ActionIcon
variant="light"
color="red"
onClick={handleClearAllRoles}
disabled={form.values.role_ids.length === 0}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Скопировать роли от другого пользователя">
<ActionIcon
variant="light"
color="blue"
onClick={() => setCopyRolesOpened(true)}
>
<IconCopy size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Group>
<MultiSelect
label="Роли"
placeholder="Выберите роли"
data={roleOptions}
value={form.values.role_ids.map(String)}
onChange={(v) => form.setFieldValue('role_ids', v.map(Number))}
searchable
clearable
description="Пользователь может иметь несколько ролей"
maxDropdownHeight={300}
/>
</Stack>
</Tabs.Panel>
{/* Вкладка: Настройки */}
<Tabs.Panel value="settings">
<Stack gap="md">
<Switch
label="Заблокирован"
description="Пользователь не сможет пользоваться системой"
checked={form.values.is_blocked}
onChange={(e) => form.setFieldValue('is_blocked', e.currentTarget.checked)}
color="red"
/>
<Switch
label="Уволен"
description="Пользователь больше не работает в компании"
checked={form.values.is_fired}
onChange={(e) => form.setFieldValue('is_fired', e.currentTarget.checked)}
color="gray"
/>
</Stack>
</Tabs.Panel>
</Tabs>
<Divider my="md" />
<Group justify="flex-end">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
Сохранить
</Button>
</Group>
</form>
) : (
<Center p={40}>
<Text c="dimmed">Пользователь не найден</Text>
</Center>
)}
</Modal>
<CopyRolesModal
opened={copyRolesOpened}
onClose={() => setCopyRolesOpened(false)}
onCopy={handleCopyRoles}
currentUserId={userId}
/>
</>
)
}
-----END src/components/UserEditModal.tsx-----
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<string, string> = {
pending: 'blue',
waiting: 'orange',
completed: 'green',
cancelled: 'gray',
}
export const STATUS_LABELS: Record<string, string> = {
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/components/DepartmentEditModal.tsx
Lines: 151
-----BEGIN src/features/departments/components/DepartmentEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Textarea,
Switch,
Group,
Button,
Text,
Loader,
Center,
Badge,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
useDepartment,
useCreateDepartment,
useUpdateDepartment
} from '@/features/departments/hooks/useDepartments'
interface DepartmentEditModalProps {
departmentId: number | null
opened: boolean
onClose: () => void
}
export default function DepartmentEditModal({
departmentId,
opened,
onClose
}: DepartmentEditModalProps) {
const { data: department, isLoading: departmentLoading } = useDepartment(departmentId)
const createDepartment = useCreateDepartment()
const updateDepartment = useUpdateDepartment()
const isEditMode = departmentId !== null
const form = useForm({
initialValues: {
name: '',
code: '',
description: '',
is_active: true,
},
validate: {
name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
code: (value: string | any[]) => {
if (value.length < 2) return 'Код должен содержать минимум 2 символа'
if (!/^[a-z0-9_]+$/.test(value as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
return null
},
},
})
// Заполняем форму данными отдела
useEffect(() => {
if (department) {
form.setValues({
name: department.name || '',
code: department.code || '',
description: department.description || '',
is_active: department.is_active ?? true,
})
} else if (!isEditMode) {
form.reset()
}
}, [department, isEditMode])
const handleSubmit = async (values: typeof form.values) => {
if (isEditMode && departmentId) {
// Режим редактирования
await updateDepartment.mutateAsync({
id: departmentId,
...values,
})
} else {
// Режим создания
await createDepartment.mutateAsync(values)
}
onClose()
}
const isLoading = departmentLoading
const isSubmitting = createDepartment.isPending || updateDepartment.isPending
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>
{isEditMode ? 'Редактирование отдела' : 'Создание отдела'}
</Text>
{department && <Badge variant="light">ID: {department.id}</Badge>}
</Group>
}
size="md"
>
{isLoading ? (
<Center p={40}>
<Loader />
</Center>
) : (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<TextInput
label="Название"
placeholder="Отдел продаж"
required
{...form.getInputProps('name')}
/>
<TextInput
label="Код"
placeholder="sales"
required
description="Уникальный идентификатор отдела (lowercase, цифры, подчеркивания)"
disabled={isEditMode}
{...form.getInputProps('code')}
/>
<Textarea
label="Описание"
placeholder="Описание отдела..."
minRows={3}
{...form.getInputProps('description')}
/>
<Switch
label="Активен"
description="Неактивные отделы не будут доступны для выбора"
checked={form.values.is_active}
onChange={(e) => form.setFieldValue('is_active', e.currentTarget.checked)}
/>
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
{isEditMode ? 'Сохранить' : 'Создать'}
</Button>
</Group>
</Stack>
</form>
)}
</Modal>
)
}
-----END src/features/departments/components/DepartmentEditModal.tsx-----
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<number>): 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<string, string> {
const collected: Record<string, string> = {}
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 `📋 <b>${title}</b>\n${bodyLines}\n<b>{{.initiator_name}}</b>:\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<string, string>()
// Рекурсивный обход всех вложенностей
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<string, string>()
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<string, ChainGroup>()
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, <ChainGroup>{
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<ScopeType, string> = {
global: 'violet',
category: 'blue',
topic: 'orange',
}
export const SCOPE_LABELS: Record<ScopeType, string> = {
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*<p>/gi, '\n\n')
result = result.replace(/<\/?p>/gi, '')
result = result.replace(/<br\s*\/?>/gi, '\n')
// Синонимы тегов из Tiptap -> Telegram-теги
result = result
.replace(/<strong>/gi, '<b>').replace(/<\/strong>/gi, '</b>')
.replace(/<em>/gi, '<i>').replace(/<\/em>/gi, '</i>')
.replace(/<strike>/gi, '<s>').replace(/<\/strike>/gi, '</s>')
// Ссылки: сохраняем только href, убираем target/rel/class и т.п.
result = result.replace(/<a\s+[^>]*href="([^"]*)"[^>]*>/gi, '<a href="$1">')
// Убираем все теги, не входящие в белый список Telegram
result = result.replace(/<(\/?)([a-zA-Z0-9-]+)([^>]*)>/g, (match, closing, rawTag) => {
const tag = rawTag.toLowerCase()
if (!ALLOWED_TAGS.has(tag)) return ''
if (tag === 'a' && !closing) return match // href уже нормализован выше
return closing ? `</${tag}>` : `<${tag}>`
})
return result.trim()
}
-----END src/features/notifications/utils/telegramHtml.ts-----
File: src/features/permissions/constants.ts
Lines: 28
-----BEGIN src/features/permissions/constants.ts-----
export const PERMISSION_ACTIONS = [
{ value: 'create', label: 'Создание', description: 'Создание заявок по теме', color: 'blue' },
{ value: 'read', label: 'Просмотр', description: 'Просмотр заявок', color: 'gray' },
{ value: 'update', label: 'Редактирование', description: 'Редактирование заявок', color: 'cyan' },
{ value: 'delete', label: 'Удаление', description: 'Удаление заявок', color: 'red' },
{ value: 'approve', label: 'Согласование', description: 'Согласование заявок', color: 'green' },
{ value: 'revoke', label: 'Отзыв', description: 'Отзыв заявок', color: 'orange' },
{ value: 'observe', label: 'Наблюдение', description: 'Наблюдение за заявками', color: 'violet' },
] as const
export const ACTION_COLORS: Record<string, string> = {
create: 'blue',
read: 'gray',
update: 'cyan',
delete: 'red',
approve: 'green',
revoke: 'orange',
observe: 'violet',
}
export const ACTION_LABELS: Record<string, string> = {
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<Role[]> => {
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<string, string> = {
all: 'Все системы',
okb: 'ОКБ',
'1c': '1С',
}
export const TARGET_SYSTEM_COLORS: Record<string, string> = {
all: 'blue',
okb: 'green',
'1c': 'orange',
}
// Группируем исполнителей по темам
export function groupExecutorsByTopic(
executors: ApprovalTopicExecutor[]
): TopicExecutorsGroup[] {
const groups = new Map<number, TopicExecutorsGroup>()
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<string, string> = {
single_day: 'Один день',
multi_day: 'Несколько дней',
date_range: 'Диапазон',
}
export const TIME_LABELS: Record<string, string> = {
partial: 'Частично',
full_day: 'Весь день',
}
export const PAYMENT_LABELS: Record<string, string> = {
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<Admin | null>(null)
const [loading, setLoading] = useState(true)
const navigate = useNavigate()
useEffect(() => {
const token = localStorage.getItem('token')
if (token) {
loadUser()
} else {
setLoading(false)
}
}, [])
const loadUser = async () => {
try {
const response = await authApi.getProfile()
setUser(response.data)
} catch (error) {
console.error('Failed to load user:', error)
localStorage.removeItem('token')
} finally {
setLoading(false)
}
}
const login = async (login: string, password: string) => {
const response = await authApi.login({ login, password })
localStorage.setItem('token', response.data.token)
// ✅ НЕ создаём новый device_id здесь!
// Он уже создан в client.ts и сохранён в localStorage
// localStorage.setItem('device_id', crypto.randomUUID()) // ← УДАЛЕНО
await loadUser()
navigate('/')
}
const logout = async () => {
try {
await authApi.logout()
} catch (error) {
console.error('Logout error:', error)
} finally {
localStorage.removeItem('token')
localStorage.removeItem('user')
setUser(null)
navigate('/login')
}
}
return { user, loading, login, logout, isAuthenticated: !!user }
}
-----END src/hooks/useAuth.ts-----
File: src/index.css
Lines: 111
-----BEGIN src/index.css-----
:root {
--text: #6b6375;
--text-h: #08060d;
--bg: #fff;
--border: #e5e4e7;
--code-bg: #f4f3ec;
--accent: #aa3bff;
--accent-bg: rgba(170, 59, 255, 0.1);
--accent-border: rgba(170, 59, 255, 0.5);
--social-bg: rgba(244, 243, 236, 0.5);
--shadow:
rgba(0, 0, 0, 0.1) 0 10px 15px -3px, rgba(0, 0, 0, 0.05) 0 4px 6px -2px;
--sans: system-ui, 'Segoe UI', Roboto, sans-serif;
--heading: system-ui, 'Segoe UI', Roboto, sans-serif;
--mono: ui-monospace, Consolas, monospace;
font: 18px/145% var(--sans);
letter-spacing: 0.18px;
color-scheme: light dark;
color: var(--text);
background: var(--bg);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@media (max-width: 1024px) {
font-size: 16px;
}
}
@media (prefers-color-scheme: dark) {
:root {
--text: #9ca3af;
--text-h: #f3f4f6;
--bg: #16171d;
--border: #2e303a;
--code-bg: #1f2028;
--accent: #c084fc;
--accent-bg: rgba(192, 132, 252, 0.15);
--accent-border: rgba(192, 132, 252, 0.5);
--social-bg: rgba(47, 48, 58, 0.5);
--shadow:
rgba(0, 0, 0, 0.4) 0 10px 15px -3px, rgba(0, 0, 0, 0.25) 0 4px 6px -2px;
}
#social .button-icon {
filter: invert(1) brightness(2);
}
}
#root {
width: 1126px;
max-width: 100%;
margin: 0 auto;
text-align: center;
border-inline: 1px solid var(--border);
min-height: 100svh;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
body {
margin: 0;
}
h1,
h2 {
font-family: var(--heading);
font-weight: 500;
color: var(--text-h);
}
h1 {
font-size: 56px;
letter-spacing: -1.68px;
margin: 32px 0;
@media (max-width: 1024px) {
font-size: 36px;
margin: 20px 0;
}
}
h2 {
font-size: 24px;
line-height: 118%;
letter-spacing: -0.24px;
margin: 0 0 8px;
@media (max-width: 1024px) {
font-size: 20px;
}
}
p {
margin: 0;
}
code,
.counter {
font-family: var(--mono);
display: inline-flex;
border-radius: 4px;
color: var(--text-h);
}
code {
font-size: 15px;
line-height: 135%;
padding: 4px 8px;
background: var(--code-bg);
}
-----END src/index.css-----
File: src/main.tsx
Lines: 38
-----BEGIN src/main.tsx-----
import React from 'react'
import ReactDOM from 'react-dom/client'
import { MantineProvider } from '@mantine/core'
import { Notifications } from '@mantine/notifications'
import { ModalsProvider } from '@mantine/modals'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import { theme } from './theme'
import '@mantine/core/styles.css'
import '@mantine/notifications/styles.css'
import '@mantine/dates/styles.css'
import ErrorBoundary from './components/DiagnosticErrorBoundary'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: 1,
},
},
})
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<QueryClientProvider client={queryClient}>
<MantineProvider theme={theme}>
<ModalsProvider>
<Notifications position="top-right" />
<ErrorBoundary fullPage>
<App />
</ErrorBoundary>
</ModalsProvider>
</MantineProvider>
</QueryClientProvider>
</BrowserRouter>
</React.StrictMode>
)
-----END src/main.tsx-----
File: src/pages/Dashboard.tsx
Lines: 601
-----BEGIN src/pages/Dashboard.tsx-----
import { useEffect, useState } from 'react'
import {
SimpleGrid,
Paper,
Text,
Group,
Stack,
Loader,
Center,
Badge,
Progress,
Alert,
Box,
ThemeIcon,
UnstyledButton,
} from '@mantine/core'
import {
IconUsers,
IconFileCheck,
IconBuilding,
IconCategory,
IconAlertTriangle,
IconAlertOctagon,
IconClock,
IconAlertCircle,
IconCircleCheck,
IconChecklist,
IconCalendarOff,
IconChevronRight,
IconUserExclamation,
} from '@tabler/icons-react'
import {
PieChart,
Pie,
Cell,
ResponsiveContainer,
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from 'recharts'
import { useNavigate } from 'react-router-dom'
import { dashboardApi } from '@/api/dashboard'
import type { DashboardStats } from '@/api/dashboard'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
import TopicGapsModal from "@/components/TopicGapsModal.tsx";
dayjs.locale('ru')
const STATUS_COLORS: Record<string, string> = {
draft: '#868e96',
pending: '#228be6',
approved: '#40c057',
rejected: '#fa5252',
revoked: '#fd7e14',
revision: '#7950f2',
}
const STATUS_LABELS: Record<string, string> = {
draft: 'Черновики',
pending: 'На согласовании',
approved: 'Согласованы',
rejected: 'Отклонены',
revoked: 'Отозваны',
revision: 'На доработке',
}
const TASK_STATUS_COLORS: Record<string, string> = {
pending: '#228be6',
waiting: '#868e96',
completed: '#40c057',
cancelled: '#fa5252',
}
const TASK_STATUS_LABELS: Record<string, string> = {
pending: 'В работе',
waiting: 'В очереди',
completed: 'Выполнены',
cancelled: 'Отменены',
}
export default function Dashboard() {
const navigate = useNavigate()
const [stats, setStats] = useState<DashboardStats | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [topicGapsOpened, setTopicGapsOpened] = useState(false)
useEffect(() => {
const loadData = async () => {
try {
const response = await dashboardApi.getStats()
setStats(response.data)
} catch (err: any) {
setError(err.response?.data?.error_description || 'Ошибка загрузки')
} finally {
setLoading(false)
}
}
loadData()
}, [])
if (loading) {
return (
<Center h={400}>
<Loader size="xl" />
</Center>
)
}
if (error || !stats) {
return (
<Alert icon={<IconAlertCircle size={16} />} color="red" title="Ошибка">
{error || 'Не удалось загрузить данные'}
</Alert>
)
}
// Фильтруем нулевые значения для pie chart
const chartData = stats.statusData.filter(s => s.count > 0)
const totalApprovals = chartData.reduce((sum, s) => sum + s.count, 0)
const taskChartData = stats.taskStatusData.filter(s => s.count > 0)
const totalTasks = taskChartData.reduce((sum, s) => sum + s.count, 0)
// 🆕 Клик по алерту "просрочены" — ведёт на заявки со status=pending
// и date_to = сегодня минус oldPendingDays (те же самые заявки, что
// посчитаны в oldPendingCount на бэкенде — общее определение "просрочки").
const goToOldPending = () => {
const cutoff = dayjs().subtract(stats.oldPendingDays, 'day').format('YYYY-MM-DD')
navigate(`/approvals?status=pending&date_to=${cutoff}`)
}
const goToRevision = () => {
navigate('/approvals?status=revision')
}
const goToTasksByStatus = (status: string) => {
navigate(`/approval-tasks?status=${status}`)
}
return (
<Stack gap="lg">
{/* Заголовок */}
<Group justify="space-between">
<div>
<Text size="xl" fw={700}>Dashboard</Text>
<Text size="sm" c="dimmed">Обзор системы согласований</Text>
</div>
<Badge size="lg" variant="light" color="blue">
{dayjs().format('DD MMMM YYYY')}
</Badge>
</Group>
{/* 🆕 Alert теперь кликабельный — ведёт на отфильтрованный список заявок */}
{stats.oldPendingCount > 0 && (
<UnstyledButton onClick={goToOldPending} style={{ width: '100%' }}>
<Alert
icon={<IconAlertTriangle size={16} />}
color="orange"
variant="light"
title={`⚠️ ${stats.oldPendingCount} заявок требуют внимания`}
style={{ cursor: 'pointer' }}
>
<Group justify="space-between">
<Text size="sm">
Есть заявки, которые находятся на согласовании более {stats.oldPendingDays} дней.
</Text>
<Group gap={4} c="orange">
<Text size="xs" fw={600}>Посмотреть список</Text>
<IconChevronRight size={14} />
</Group>
</Group>
</Alert>
</UnstyledButton>
)}
{/* 🆕 Проблемы конфигурации инициаторов */}
{stats.topicGaps.length > 0 && (
<UnstyledButton onClick={() => setTopicGapsOpened(true)} style={{ width: '100%' }}>
<Paper withBorder p="md" radius="md" style={{ cursor: 'pointer' }}>
<Group justify="space-between">
<Group>
<ThemeIcon variant="light" color="orange" size="lg">
<IconAlertTriangle size={18} />
</ThemeIcon>
<div>
<Text fw={600}>
{stats.topicGaps.length} {stats.topicGaps.length === 1 ? 'тема без' : 'тем без'} назначенного порядка согласования
</Text>
<Text size="sm" c="dimmed">
Есть право создать заявку, но некому её согласовать — сотрудник наткнётся на ошибку в боте.
</Text>
</div>
</Group>
<Group gap={4} c="orange">
<Text size="xs" fw={600}>Показать список</Text>
<IconChevronRight size={14} />
</Group>
</Group>
</Paper>
</UnstyledButton>
)}
{stats.usersWithoutHierarchy.length > 0 && (
<Alert
icon={<IconUserExclamation size={16} />}
color="red"
variant="light"
title={`${stats.usersWithoutHierarchy.length} сотрудник(ов) без настроенной иерархии`}
>
<Text size="sm">
У перечисленных ниже есть право создавать заявки, но для их отдела не
настроено вообще ни одного правила согласования:{' '}
<Text span fw={600}>
{stats.usersWithoutHierarchy.map(u => u.full_name || `ID ${u.user_id}`).join(', ')}
</Text>
</Text>
</Alert>
)}
<TopicGapsModal
opened={topicGapsOpened}
onClose={() => setTopicGapsOpened(false)}
gaps={stats.topicGaps}
/>
{/* 🆕 Alert теперь кликабельный — ведёт на заявки на доработке */}
{stats.approvals.revision > 0 && (
<UnstyledButton onClick={goToRevision} style={{ width: '100%' }}>
<Paper withBorder p="md" radius="md" style={{ cursor: 'pointer' }}>
<Group justify="space-between">
<Group>
<ThemeIcon variant="light" color="orange" size="lg">
<IconClock size={18} />
</ThemeIcon>
<div>
<Text fw={600}>Требуют внимания: {stats.approvals.revision} заявок на доработке</Text>
<Text size="sm" c="dimmed">
Эти заявки были возвращены согласующими на доработку и требуют действий от инициаторов.
</Text>
</div>
</Group>
<IconChevronRight size={18} color="var(--mantine-color-gray-5)" />
</Group>
</Paper>
</UnstyledButton>
)}
{/* 🆕 Кто отсутствует сегодня */}
<Paper withBorder p="md" radius="md">
<Group mb="md">
<ThemeIcon variant="light" color="gray" size="lg">
<IconCalendarOff size={18} />
</ThemeIcon>
<Text fw={600}>
Отсутствуют сегодня{stats.absentToday.length > 0 ? ` (${stats.absentToday.length})` : ''}
</Text>
</Group>
{stats.absentToday.length === 0 ? (
<Text c="dimmed" size="sm">Сегодня все на месте</Text>
) : (
<SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="xs">
{stats.absentToday.map((person, i) => (
<Group key={i} gap="xs" wrap="nowrap">
<Text size="sm" fw={500} truncate>{person.name}</Text>
<Text size="xs" c="dimmed" truncate>— {person.description}</Text>
</Group>
))}
</SimpleGrid>
)}
</Paper>
{/* KPI карточки */}
<SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }} spacing="md">
<StatCard
title="Пользователи"
value={stats.users.total}
subtitle={`${stats.users.active} активных`}
icon={IconUsers}
color="blue"
trend={stats.users.blocked > 0 ? `${stats.users.blocked} заблокировано` : undefined}
/>
<StatCard
title="Заявки"
value={stats.approvals.total}
subtitle={`${stats.approvals.today} за сегодня`}
icon={IconFileCheck}
color="green"
trend={stats.approvals.pending > 0 ? `${stats.approvals.pending} в работе` : undefined}
/>
<StatCard
title="Темы"
value={stats.topics.total}
subtitle={`${stats.topics.active} активных`}
icon={IconCategory}
color="violet"
trend={`${stats.categories} категорий`}
/>
<StatCard
title="Отделы / Роли"
value={stats.departments}
subtitle={`${stats.roles} ролей`}
icon={IconBuilding}
color="orange"
trend={`${stats.executors} исполнителей`}
/>
</SimpleGrid>
{/* Графики по заявкам */}
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
{/* Pie chart */}
<Paper withBorder p="md" radius="md">
<Group justify="space-between" mb="md">
<Text fw={600}>Распределение заявок по статусам</Text>
<Badge variant="light">{totalApprovals} всего</Badge>
</Group>
{chartData.length === 0 ? (
<Center h={250}>
<Text c="dimmed">Нет данных</Text>
</Center>
) : (
<ResponsiveContainer width="100%" height={250}>
<PieChart>
<Pie
data={chartData}
dataKey="count"
nameKey="status"
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={90}
paddingAngle={2}
label={(entry: any) => STATUS_LABELS[entry.payload?.status] || entry.payload?.status}
onClick={(entry: any) => navigate(`/approvals?status=${entry.status}`)}
style={{ cursor: 'pointer' }}
>
{chartData.map((entry, index) => (
<Cell
key={`cell-${index}`}
fill={STATUS_COLORS[entry.status] || '#868e96'}
/>
))}
</Pie>
<Tooltip
formatter={(value: any, name: any) => [
value,
STATUS_LABELS[name] || name
]}
/>
</PieChart>
</ResponsiveContainer>
)}
</Paper>
{/* Line chart */}
<Paper withBorder p="md" radius="md">
<Group justify="space-between" mb="md">
<Text fw={600}>Динамика за 7 дней</Text>
<Badge variant="light" color="blue">Заявки</Badge>
</Group>
<ResponsiveContainer width="100%" height={250}>
<LineChart data={stats.dailyData}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
dataKey="date"
tickFormatter={(d) => dayjs(d).format('DD.MM')}
/>
<YAxis />
<Tooltip
labelFormatter={(d) => dayjs(d).format('DD.MM.YYYY')}
formatter={(value: any, name: any) => [
value,
name === 'created' ? 'Создано' : 'Согласовано'
]}
/>
<Legend
formatter={(value) =>
value === 'created' ? 'Создано' : 'Согласовано'
}
/>
<Line
type="monotone"
dataKey="created"
stroke="#228be6"
strokeWidth={2}
dot={{ r: 4 }}
/>
<Line
type="monotone"
dataKey="approved"
stroke="#40c057"
strokeWidth={2}
dot={{ r: 4 }}
/>
</LineChart>
</ResponsiveContainer>
</Paper>
</SimpleGrid>
{/* 🆕 Задачи — те же два графика, что у заявок выше */}
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
<Paper withBorder p="md" radius="md">
<Group justify="space-between" mb="md">
<Group gap="xs">
<ThemeIcon variant="light" color="teal" size="lg">
<IconChecklist size={18} />
</ThemeIcon>
<Text fw={600}>Задачи по статусам</Text>
</Group>
<Badge variant="light">{totalTasks} всего</Badge>
</Group>
{taskChartData.length === 0 ? (
<Center h={250}>
<Text c="dimmed">Нет данных</Text>
</Center>
) : (
<ResponsiveContainer width="100%" height={250}>
<PieChart>
<Pie
data={taskChartData}
dataKey="count"
nameKey="status"
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={90}
paddingAngle={2}
label={(entry: any) => TASK_STATUS_LABELS[entry.payload?.status] || entry.payload?.status}
onClick={(entry: any) => goToTasksByStatus(entry.status)}
style={{ cursor: 'pointer' }}
>
{taskChartData.map((entry, index) => (
<Cell
key={`task-cell-${index}`}
fill={TASK_STATUS_COLORS[entry.status] || '#868e96'}
/>
))}
</Pie>
<Tooltip
formatter={(value: any, name: any) => [
value,
TASK_STATUS_LABELS[name] || name
]}
/>
</PieChart>
</ResponsiveContainer>
)}
</Paper>
<Paper withBorder p="md" radius="md">
<Group justify="space-between" mb="md">
<Text fw={600}>Динамика задач за 7 дней</Text>
<Badge variant="light" color="teal">Задачи</Badge>
</Group>
<ResponsiveContainer width="100%" height={250}>
<LineChart data={stats.taskDailyData}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
dataKey="date"
tickFormatter={(d) => dayjs(d).format('DD.MM')}
/>
<YAxis />
<Tooltip
labelFormatter={(d) => dayjs(d).format('DD.MM.YYYY')}
formatter={(value: any, name: any) => [
value,
name === 'created' ? 'Создано' : 'Выполнено'
]}
/>
<Legend
formatter={(value) =>
value === 'created' ? 'Создано' : 'Выполнено'
}
/>
<Line
type="monotone"
dataKey="created"
stroke="#228be6"
strokeWidth={2}
dot={{ r: 4 }}
/>
<Line
type="monotone"
dataKey="completed"
stroke="#12b886"
strokeWidth={2}
dot={{ r: 4 }}
/>
</LineChart>
</ResponsiveContainer>
</Paper>
</SimpleGrid>
{/* Разбивка по категориям + узкие места */}
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
{/* Разбивка по категориям */}
<Paper withBorder p="md" radius="md">
<Group mb="md">
<ThemeIcon variant="light" color="violet" size="lg">
<IconCategory size={18} />
</ThemeIcon>
<Text fw={600}>Заявки по категориям</Text>
</Group>
{stats.categoryBreakdown.length === 0 ? (
<Center h={200}>
<Text c="dimmed">Нет данных</Text>
</Center>
) : (
<Stack gap="sm">
{stats.categoryBreakdown.map((cat) => {
const maxCount = Math.max(...stats.categoryBreakdown.map(c => c.total_count))
const percent = maxCount > 0 ? (cat.total_count / maxCount) * 100 : 0
return (
<Box key={cat.id}>
<Group justify="space-between" mb={4}>
<Text size="sm" fw={500}>{cat.name}</Text>
<Group gap="xs">
<Text size="sm" fw={600}>{cat.total_count}</Text>
{cat.pending_count > 0 && (
<Badge size="xs" color="blue" variant="light">
{cat.pending_count} в работе
</Badge>
)}
</Group>
</Group>
<Progress value={percent} size="sm" color="violet" />
</Box>
)
})}
</Stack>
)}
</Paper>
</SimpleGrid>
</Stack>
)
}
// Компонент карточки статистики
interface StatCardProps {
title: string
value: number | string
subtitle?: string
icon: any
color: string
trend?: string
}
function StatCard({ title, value, subtitle, icon: Icon, color, trend }: StatCardProps) {
return (
<Paper withBorder p="md" radius="md">
<Group justify="space-between" align="flex-start">
<Stack gap={4}>
<Text c="dimmed" size="xs" tt="uppercase" fw={700}>
{title}
</Text>
<Text size="xl" fw={700} c={color}>
{value}
</Text>
{subtitle && (
<Text size="xs" c="dimmed">
{subtitle}
</Text>
)}
</Stack>
<ThemeIcon
variant="light"
color={color}
size="xl"
radius="md"
>
<Icon size={24} />
</ThemeIcon>
</Group>
{trend && (
<Box
mt="md"
pt="md"
style={{
borderTop: '1px solid var(--mantine-color-gray-3)',
}}
>
<Text size="xs" c="dimmed">{trend}</Text>
</Box>
)}
</Paper>
)
}
-----END src/pages/Dashboard.tsx-----
File: src/pages/DepartmentsPage.tsx
Lines: 230
-----BEGIN src/pages/DepartmentsPage.tsx-----
import { useState } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Switch,
} from '@mantine/core'
import { IconPencil, IconTrash, IconPlus, IconSearch } from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { useDepartments, useDeleteDepartment } from '@/features/departments/hooks/useDepartments'
import DepartmentEditModal from "@/features/departments/components/DepartmentEditModal.tsx";
const LIMIT = 20
export default function DepartmentsPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [activeFilter, setActiveFilter] = useState<boolean | null>(null)
const [editDepartmentId, setEditDepartmentId] = useState<number | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const { data, isLoading, isFetching } = useDepartments({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(search && { name: search }),
...(activeFilter !== null && { is_active: activeFilter }),
})
const deleteDepartment = useDeleteDepartment()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить этот отдел? Это действие нельзя отменить.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteDepartment.mutate(id),
})
}
return (
<Stack gap="md">
<Group justify="space-between">
<Text size="xl" fw={700}>Отделы</Text>
<Group>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
<Button
leftSection={<IconPlus size={16} />}
onClick={() => setCreateModalOpened(true)}
>
Создать отдел
</Button>
</Group>
</Group>
{/* Фильтры */}
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<TextInput
label="Поиск по названию"
placeholder="Отдел продаж..."
leftSection={<IconSearch size={16} />}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
style={{ flex: 1 }}
/>
<Switch
label="Только активные"
checked={activeFilter === true}
onChange={(e) => {
setActiveFilter(e.currentTarget.checked ? true : null)
setPage(1)
}}
/>
</Group>
</Paper>
{/* Таблица */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Название</Table.Th>
<Table.Th>Код</Table.Th>
<Table.Th>Описание</Table.Th>
<Table.Th style={{ width: 100 }}>Статус</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={6}>
<Center p={40}>
<Text c="dimmed">Отделы не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).map((department) => (
<Table.Tr key={department.id}>
<Table.Td>{department.id}</Table.Td>
<Table.Td>
<Text fw={500}>{department.name}</Text>
</Table.Td>
<Table.Td>
<Text size="sm" ff="monospace" c="dimmed">
{department.code}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" lineClamp={2}>
{department.description || '—'}
</Text>
</Table.Td>
<Table.Td>
<Badge
color={department.is_active ? 'green' : 'gray'}
variant={department.is_active ? 'light' : 'filled'}
>
{department.is_active ? 'Активен' : 'Неактивен'}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs">
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditDepartmentId(department.id!)}
>
<IconPencil size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="light"
color="red"
onClick={() => handleDelete(department.id!)}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Table.Td>
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
{/* Пагинация */}
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={setPage}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</>
)}
</Paper>
{/* Индикатор обновления */}
{isFetching && !isLoading && (
<Box
style={{
position: 'fixed',
top: 70,
right: 20,
zIndex: 1000
}}
>
<Loader size="xs" />
</Box>
)}
{/* Модальное окно редактирования */}
<DepartmentEditModal
departmentId={editDepartmentId}
opened={editDepartmentId !== null}
onClose={() => setEditDepartmentId(null)}
/>
{/* Модальное окно создания */}
<DepartmentEditModal
departmentId={null}
opened={createModalOpened}
onClose={() => setCreateModalOpened(false)}
/>
</Stack>
)
}
-----END src/pages/DepartmentsPage.tsx-----
File: src/pages/Login.tsx
Lines: 85
-----BEGIN src/pages/Login.tsx-----
import { useState } from 'react'
import {
Container,
Paper,
Title,
Text,
TextInput,
PasswordInput,
Button,
Group,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import { useAuth } from '@/hooks/useAuth'
export default function Login() {
const { login } = useAuth()
const [loading, setLoading] = useState(false)
const form = useForm({
initialValues: {
login: '',
password: '',
},
validate: {
login: (value: string | any[]) => (value.length < 3 ? 'Логин должен содержать минимум 3 символа' : null),
password: (value: string | any[]) => (value.length < 4 ? 'Пароль должен содержать минимум 4 символа' : null),
},
})
const handleSubmit = async (values: typeof form.values) => {
setLoading(true)
try {
await login(values.login, values.password)
notifications.show({
title: 'Успешный вход',
message: `Добро пожаловать, ${values.login}!`,
color: 'green',
})
} catch (error: any) {
notifications.show({
title: 'Ошибка входа',
message: error.response?.data?.error_description || 'Неверный логин или пароль',
color: 'red',
})
} finally {
setLoading(false)
}
}
return (
<Container size={420} my={40}>
<Title ta="center" mb="md">
Корпоративная панель администратора
</Title>
<Text c="dimmed" size="sm" ta="center" mb="xl">
Введите свои данные для входа в систему
</Text>
<Paper withBorder shadow="md" p={30} mt={30} radius="md">
<form onSubmit={form.onSubmit(handleSubmit)}>
<TextInput
label="Логин"
placeholder="admin"
required
{...form.getInputProps('login')}
/>
<PasswordInput
label="Пароль"
placeholder="your password"
required
mt="md"
{...form.getInputProps('password')}
/>
<Group justify="space-between" mt="xl">
<Button type="submit" fullWidth loading={loading}>
Войти
</Button>
</Group>
</form>
</Paper>
</Container>
)
}
-----END src/pages/Login.tsx-----
File: src/pages/adminLogs/AdminLogsPage.tsx
Lines: 331
-----BEGIN src/pages/adminLogs/AdminLogsPage.tsx-----
import { useState } from 'react'
import {
Paper,
Table,
Group,
ActionIcon,
Text,
TextInput,
Select,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Badge,
} from '@mantine/core'
import { DatePickerInput } from '@mantine/dates'
import { IconTrash, IconSearch, IconX, IconEye } from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { useAuth } from '@/hooks/useAuth'
import { useAdminLogs, useDeleteAdminLog } from '@/features/adminLogs/hooks/useAdminLogs'
import type { AdminActionLog } from '@/api/adminLogs'
import AdminLogDetailModal from './components/AdminLogDetailModal'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
dayjs.locale('ru')
const LIMIT = 50
const ACTION_COLORS: Record<string, string> = {
create: 'green',
update: 'blue',
delete: 'red',
}
const ACTION_LABELS: Record<string, string> = {
create: 'Создание',
update: 'Изменение',
delete: 'Удаление',
}
const ENTITY_TYPE_OPTIONS = [
{ value: 'user', label: 'Пользователь' },
{ value: 'admin', label: 'Администратор' },
{ value: 'department', label: 'Отдел' },
{ value: 'role', label: 'Роль' },
{ value: 'permission', label: 'Право' },
{ value: 'category', label: 'Категория' },
{ value: 'topic', label: 'Тема' },
{ value: 'topic_executor', label: 'Исполнитель темы' },
{ value: 'hierarchy', label: 'Иерархия' },
{ value: 'flow_node', label: 'Узел дерева' },
{ value: 'flow_tree', label: 'Дерево категории' },
{ value: 'user_role', label: 'Роль пользователя' },
{ value: 'user_roles', label: 'Роли пользователя (массово)' },
{ value: 'approval_task', label: 'Задача' },
{ value: 'notification', label: 'Рассылка' },
]
export default function AdminLogPage() {
const { user: currentUser } = useAuth()
const isRoot = currentUser?.is_root === true
const [page, setPage] = useState(1)
const [adminLogin, setAdminLogin] = useState('')
const [action, setAction] = useState<string | null>(null)
const [entityType, setEntityType] = useState<string | null>(null)
const [entityId, setEntityId] = useState('')
const [search, setSearch] = useState('')
const [dateFrom, setDateFrom] = useState<Date | null>(null)
const [dateTo, setDateTo] = useState<Date | null>(null)
const [selectedLog, setSelectedLog] = useState<AdminActionLog | null>(null)
const { data, isLoading, isFetching } = useAdminLogs({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(adminLogin && { admin_login: adminLogin }),
...(action && { action }),
...(entityType && { entity_type: entityType }),
...(entityId && { entity_id: Number(entityId) }),
...(search && { search }),
...(dateFrom && { date_from: dayjs(dateFrom).format('YYYY-MM-DD') }),
...(dateTo && { date_to: dayjs(dateTo).format('YYYY-MM-DD') }),
})
const deleteLog = useDeleteAdminLog()
const logs = data?.data || []
const totalCount = data?.total_count || 0
const totalPages = totalCount ? Math.ceil(totalCount / LIMIT) : 1
const hasActiveFilters = adminLogin || action || entityType || entityId || search || dateFrom || dateTo
const handleResetFilters = () => {
setAdminLogin('')
setAction(null)
setEntityType(null)
setEntityId('')
setSearch('')
setDateFrom(null)
setDateTo(null)
setPage(1)
}
const handleDelete = (entry: AdminActionLog) => {
modals.openConfirmModal({
title: 'Удалить запись журнала?',
children: (
<Text size="sm">
Это действие доступно только root-администратору и необратимо.
Обычно записи журнала не удаляют — используйте только если запись
ошибочна или содержит чувствительные данные, которые нужно убрать.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteLog.mutate(entry.id),
})
}
return (
<Stack gap="md">
<Group justify="space-between">
<Text size="xl" fw={700}>Журнал действий администраторов</Text>
<Text c="dimmed" size="sm">Всего: {totalCount}</Text>
</Group>
<Paper withBorder p="md">
<Stack gap="md">
<Group gap="md" align="flex-end" grow>
<TextInput
label="Администратор"
placeholder="Логин..."
leftSection={<IconSearch size={16} />}
value={adminLogin}
onChange={(e) => {
setAdminLogin(e.currentTarget.value)
setPage(1)
}}
/>
<Select
label="Действие"
placeholder="Все"
data={[
{ value: 'create', label: 'Создание' },
{ value: 'update', label: 'Изменение' },
{ value: 'delete', label: 'Удаление' },
]}
value={action}
onChange={(v) => {
setAction(v)
setPage(1)
}}
clearable
/>
<Select
label="Тип сущности"
placeholder="Все"
data={ENTITY_TYPE_OPTIONS}
value={entityType}
onChange={(v) => {
setEntityType(v)
setPage(1)
}}
clearable
searchable
/>
<TextInput
label="ID сущности"
placeholder="Например, 19"
value={entityId}
onChange={(e) => {
setEntityId(e.currentTarget.value.replace(/\D/g, ''))
setPage(1)
}}
/>
</Group>
<Group gap="md" align="flex-end" grow>
<TextInput
label="Поиск по описанию"
placeholder="Введите текст..."
leftSection={<IconSearch size={16} />}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
rightSection={
search && (
<ActionIcon variant="subtle" onClick={() => setSearch('')}>
<IconX size={14} />
</ActionIcon>
)
}
/>
<DatePickerInput
label="С даты"
placeholder="Выберите дату"
value={dateFrom}
onChange={(val) => {
setDateFrom(val as Date | null)
setPage(1)
}}
clearable
maxDate={dateTo || undefined}
/>
<DatePickerInput
label="По дату"
placeholder="Выберите дату"
value={dateTo}
onChange={(val) => {
setDateTo(val as Date | null)
setPage(1)
}}
clearable
minDate={dateFrom || undefined}
/>
<Box>
{hasActiveFilters && (
<ActionIcon variant="light" color="gray" size="lg" onClick={handleResetFilters} title="Сбросить фильтры">
<IconX size={16} />
</ActionIcon>
)}
</Box>
</Group>
</Stack>
</Paper>
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 160 }}>Когда</Table.Th>
<Table.Th>Администратор</Table.Th>
<Table.Th style={{ width: 120 }}>Действие</Table.Th>
<Table.Th style={{ width: 160 }}>Сущность</Table.Th>
<Table.Th>Описание</Table.Th>
<Table.Th style={{ width: 90 }}>—</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{logs.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={6}>
<Center p={40}>
<Text c="dimmed">Записей не найдено</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
logs.map((entry) => (
<Table.Tr key={entry.id} style={{ cursor: 'pointer' }} onClick={() => setSelectedLog(entry)}>
<Table.Td>
<Text size="xs" c="dimmed">
{dayjs(entry.created_at).format('DD.MM.YYYY HH:mm')}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" fw={500}>{entry.admin_login}</Text>
</Table.Td>
<Table.Td>
<Badge size="sm" color={ACTION_COLORS[entry.action] || 'gray'} variant="light">
{ACTION_LABELS[entry.action] || entry.action}
</Badge>
</Table.Td>
<Table.Td>
<Badge size="sm" variant="outline" color="gray">
{entry.entity_type}{entry.entity_id ? ` #${entry.entity_id}` : ''}
</Badge>
</Table.Td>
<Table.Td>
<Text size="sm" lineClamp={1}>{entry.description}</Text>
</Table.Td>
<Table.Td onClick={(e) => e.stopPropagation()}>
<Group gap="xs">
<Tooltip label="Детали">
<ActionIcon variant="light" color="blue" onClick={() => setSelectedLog(entry)}>
<IconEye size={14} />
</ActionIcon>
</Tooltip>
{isRoot && (
<Tooltip label="Удалить (только root)">
<ActionIcon variant="light" color="red" onClick={() => handleDelete(entry)}>
<IconTrash size={14} />
</ActionIcon>
</Tooltip>
)}
</Group>
</Table.Td>
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">Страница {page} из {totalPages}</Text>
<Pagination value={page} onChange={setPage} total={totalPages} withEdges />
</Group>
</Box>
)}
</>
)}
</Paper>
{isFetching && !isLoading && (
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
<Loader size="xs" />
</Box>
)}
<AdminLogDetailModal
log={selectedLog}
opened={selectedLog !== null}
onClose={() => setSelectedLog(null)}
/>
</Stack>
)
}
-----END src/pages/adminLogs/AdminLogsPage.tsx-----
File: src/pages/adminLogs/components/AdminLogDetailModal.tsx
Lines: 104
-----BEGIN src/pages/adminLogs/components/AdminLogDetailModal.tsx-----
import { useMemo } from 'react'
import { Modal, Stack, Text, Table, Badge, Group, Code, Center } from '@mantine/core'
import type { AdminActionLog } from '@/api/adminLogs'
interface FieldChange {
field: string
old: unknown
new: unknown
}
interface AdminLogDetailModalProps {
log: AdminActionLog | null
opened: boolean
onClose: () => void
}
function formatValue(v: unknown): string {
if (v === null || v === undefined || v === '') return '—'
if (typeof v === 'boolean') return v ? 'да' : 'нет'
if (Array.isArray(v)) return v.length ? v.join(', ') : '—'
return String(v)
}
export default function AdminLogDetailModal({ log, opened, onClose }: AdminLogDetailModalProps) {
const parsed = useMemo(() => {
if (!log?.metadata) return null
try {
return JSON.parse(log.metadata) as {
changes?: FieldChange[]
snapshot?: Record<string, unknown>
[key: string]: unknown
}
} catch {
return null
}
}, [log])
return (
<Modal opened={opened} onClose={onClose} title="Детали действия" size="lg">
{!log ? null : (
<Stack gap="md">
<Group justify="space-between">
<Text size="sm" c="dimmed">{log.admin_login}</Text>
<Badge variant="light">{log.entity_type}</Badge>
</Group>
<Text>{log.description}</Text>
{parsed?.changes && parsed.changes.length > 0 && (
<Table striped withTableBorder>
<Table.Thead>
<Table.Tr>
<Table.Th>Поле</Table.Th>
<Table.Th>Было</Table.Th>
<Table.Th>Стало</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{parsed.changes.map((c, i) => (
<Table.Tr key={i}>
<Table.Td>
<Text size="sm" ff="monospace">{c.field}</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="red">{formatValue(c.old)}</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="green">{formatValue(c.new)}</Text>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
)}
{parsed?.snapshot && (
<Table striped withTableBorder>
<Table.Tbody>
{Object.entries(parsed.snapshot).map(([key, value]) => (
<Table.Tr key={key}>
<Table.Td>
<Text size="sm" ff="monospace" c="dimmed">{key}</Text>
</Table.Td>
<Table.Td>
<Text size="sm">{formatValue(value)}</Text>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
)}
{!parsed?.changes && !parsed?.snapshot && parsed && (
<Code block>{JSON.stringify(parsed, null, 2)}</Code>
)}
{!log.metadata && (
<Center p="md">
<Text c="dimmed" size="sm">Дополнительных данных нет</Text>
</Center>
)}
</Stack>
)}
</Modal>
)
}
-----END src/pages/adminLogs/components/AdminLogDetailModal.tsx-----
File: src/pages/admins/AdminsPage.tsx
Lines: 398
-----BEGIN src/pages/admins/AdminsPage.tsx-----
import { useState } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Switch,
} from '@mantine/core'
import {
IconTrash,
IconPlus,
IconSearch,
IconLock,
IconLockOpen,
IconPencil,
IconShield,
IconUser,
} from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { notifications } from '@mantine/notifications'
import {
useAdmins,
useDeleteAdmin,
useUpdateAdmin
} from '@/features/admins/hooks/useAdmins'
import { useAuth } from '@/hooks/useAuth'
import CreateAdminModal from './components/CreateAdminModal'
import EditAdminModal from './components/EditAdminModal'
import type { Admin } from '@/types/api'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
dayjs.locale('ru')
const LIMIT = 20
export default function AdminsPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [blockedFilter, setBlockedFilter] = useState<boolean | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const [editAdmin, setEditAdmin] = useState<Admin | null>(null)
const { user: currentUser } = useAuth()
const { data, isLoading, isFetching } = useAdmins({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(search && { login: search }),
...(blockedFilter !== null && { is_blocked: blockedFilter }),
})
const deleteAdmin = useDeleteAdmin()
const updateAdmin = useUpdateAdmin()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
// 🆕 Проверка, является ли текущий пользователь root
const isRoot = currentUser?.is_root === true
const handleDelete = (id: number, login: string, isAdminRoot: boolean) => {
// Нельзя удалить себя
if (currentUser?.id === id) {
notifications.show({
title: 'Ошибка',
message: 'Вы не можете удалить свой собственный аккаунт',
color: 'red',
})
return
}
// Нельзя удалить root-админа (если текущий не root)
if (isAdminRoot && !isRoot) {
notifications.show({
title: 'Ошибка',
message: 'Только root-администратор может удалять других root-администраторов',
color: 'red',
})
return
}
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить администратора <b>{login}</b>?
Это действие нельзя отменить.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteAdmin.mutate(id),
})
}
const handleToggleBlock = (id: number, login: string, isBlocked: boolean, isAdminRoot: boolean) => {
// Нельзя заблокировать себя
if (currentUser?.id === id) {
notifications.show({
title: 'Ошибка',
message: 'Вы не можете заблокировать свой собственный аккаунт',
color: 'red',
})
return
}
// Нельзя заблокировать root-админа (если текущий не root)
if (isAdminRoot && !isRoot) {
notifications.show({
title: 'Ошибка',
message: 'Только root-администратор может блокировать других root-администраторов',
color: 'red',
})
return
}
const action = isBlocked ? 'разблокировать' : 'заблокировать'
modals.openConfirmModal({
title: 'Подтвердите действие',
children: (
<Text size="sm">
Вы уверены, что хотите {action} администратора <b>{login}</b>?
</Text>
),
labels: { confirm: action.charAt(0).toUpperCase() + action.slice(1), cancel: 'Отмена' },
confirmProps: { color: isBlocked ? 'green' : 'red' },
onConfirm: () => updateAdmin.mutate({ id, is_blocked: !isBlocked }),
})
}
return (
<Stack gap="md">
{/* Заголовок */}
<Group justify="space-between">
<Text size="xl" fw={700}>Администраторы</Text>
<Group>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
{isRoot && (
<Button
leftSection={<IconPlus size={16} />}
onClick={() => setCreateModalOpened(true)}
>
Создать администратора
</Button>
)}
</Group>
</Group>
{/* Предупреждение для не-root пользователей */}
{!isRoot && (
<Paper withBorder p="md" bg="yellow.0">
<Text size="sm">
⚠️ Создание новых администраторов доступно только для root-администратора.
</Text>
</Paper>
)}
{/* Фильтры */}
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<TextInput
label="Поиск по логину"
placeholder="admin_user..."
leftSection={<IconSearch size={16} />}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
style={{ flex: 1 }}
/>
<Switch
label="Только заблокированные"
checked={blockedFilter === true}
onChange={(e) => {
setBlockedFilter(e.currentTarget.checked ? true : null)
setPage(1)
}}
/>
</Group>
</Paper>
{/* Таблица */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Логин</Table.Th>
<Table.Th>Имя</Table.Th>
<Table.Th>Роль</Table.Th>
<Table.Th>Telegram</Table.Th>
<Table.Th>Создан</Table.Th>
<Table.Th>Последний вход</Table.Th>
<Table.Th>Последний IP</Table.Th>
<Table.Th style={{ width: 100 }}>Статус</Table.Th>
<Table.Th style={{ width: 140 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={10}>
<Center p={40}>
<Text c="dimmed">Администраторы не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).map((admin) => {
const isCurrentUser = currentUser?.id === admin.id
const isAdminRoot = admin.is_root === true
return (
<Table.Tr key={admin.id}>
<Table.Td>{admin.id}</Table.Td>
<Table.Td>
<Group gap="xs">
<Text fw={500}>{admin.login}</Text>
{isCurrentUser && (
<Badge size="xs" color="blue" variant="light">
Вы
</Badge>
)}
{isAdminRoot && (
<Badge
size="xs"
color="red"
variant="filled"
leftSection={<IconShield size={10} />}
>
ROOT
</Badge>
)}
</Group>
</Table.Td>
<Table.Td>
<Text size="sm">{admin.name || '—'}</Text>
</Table.Td>
<Table.Td>
<Group gap={4}>
{isAdminRoot && (
<Badge size="xs" color="red" variant="filled" leftSection={<IconShield size={10} />}>
ROOT
</Badge>
)}
{admin.is_observer && (
<Badge size="xs" color="blue" variant="filled" leftSection={<IconUser size={10} />}>
Наблюдатель
</Badge>
)}
{!isAdminRoot && !admin.is_observer && (
<Badge size="xs" color="gray" variant="light">
Админ
</Badge>
)}
</Group>
</Table.Td>
<Table.Td>
{admin.telegram_user ? (
<Text size="sm">{admin.telegram_user.full_name || admin.telegram_user.username || '—'}</Text>
) : admin.telegram_id ? (
<Text size="sm" c="dimmed">ID: {admin.telegram_id}</Text>
) : (
<Text size="sm" c="dimmed">—</Text>
)}
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">
{admin.created_at
? dayjs(admin.created_at).format('DD.MM.YYYY')
: '—'}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">
{admin.last_login
? dayjs(admin.last_login).format('DD.MM.YYYY HH:mm')
: '—'}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" ff="monospace" c="dimmed">
{admin.last_ip_login || '—'}
</Text>
</Table.Td>
<Table.Td>
<Badge
color={admin.is_blocked ? 'red' : 'green'}
variant={admin.is_blocked ? 'filled' : 'light'}
>
{admin.is_blocked ? 'Заблокирован' : 'Активен'}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs">
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditAdmin(admin)}
>
<IconPencil size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label={admin.is_blocked ? 'Разблокировать' : 'Заблокировать'}>
<ActionIcon
variant="light"
color={admin.is_blocked ? 'green' : 'orange'}
onClick={() => handleToggleBlock(
admin.id!,
admin.login,
admin.is_blocked || false,
isAdminRoot
)}
disabled={isCurrentUser || (isAdminRoot && !isRoot)}
>
{admin.is_blocked ? <IconLockOpen size={16} /> : <IconLock size={16} />}
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="light"
color="red"
onClick={() => handleDelete(admin.id!, admin.login, isAdminRoot)}
disabled={isCurrentUser || (isAdminRoot && !isRoot)}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Table.Td>
</Table.Tr>
)
})
)}
</Table.Tbody>
</Table>
{/* Пагинация */}
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={setPage}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</>
)}
</Paper>
{/* Индикатор обновления */}
{isFetching && !isLoading && (
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
<Loader size="xs" />
</Box>
)}
{/* Модальные окна */}
<CreateAdminModal
opened={createModalOpened}
onClose={() => setCreateModalOpened(false)}
/>
<EditAdminModal
admin={editAdmin}
opened={editAdmin !== null}
onClose={() => setEditAdmin(null)}
/>
</Stack>
)
}
-----END src/pages/admins/AdminsPage.tsx-----
File: src/pages/admins/components/CreateAdminModal.tsx
Lines: 258
-----BEGIN src/pages/admins/components/CreateAdminModal.tsx-----
import { useState, useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Button,
Text,
Alert,
CopyButton,
ActionIcon,
Tooltip,
Group,
Paper,
Code,
Switch,
Select,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconCheck, IconCopy, IconKey, IconAlertCircle, IconShield, IconUser } from '@tabler/icons-react'
import { useCreateAdmin } from '@/features/admins/hooks/useAdmins'
import { useUsers } from '@/features/users/hooks/useUsers'
import type { Admin } from '@/types/api'
interface CreateAdminModalProps {
opened: boolean
onClose: () => void
}
export default function CreateAdminModal({ opened, onClose }: CreateAdminModalProps) {
const [createdAdmin, setCreatedAdmin] = useState<Admin | null>(null)
const createAdmin = useCreateAdmin()
const { data: usersData } = useUsers({ limit: 1000 })
const form = useForm({
initialValues: {
login: '',
name: '',
is_root: false,
is_observer: false,
telegram_id: null as number | null,
},
validate: {
login: (value) => {
if (value.length < 3) return 'Логин должен содержать минимум 3 символа'
if (!/^[a-zA-Z0-9_]+$/.test(value)) return 'Логин может содержать только буквы, цифры и подчеркивания'
return null
},
telegram_id: (value, values) => {
if (values.is_observer && !value) {
return 'Для наблюдателя обязательно выберите Telegram-аккаунт'
}
return null
},
},
})
// Сброс telegram_id при снятии галочки наблюдателя
useEffect(() => {
if (!form.values.is_observer) {
form.setFieldValue('telegram_id', null)
}
}, [form.values.is_observer])
// Опции пользователей Telegram (только те, у кого есть telegram_id)
const userOptions = usersData?.data
?.filter((u) => u.telegram_id && u.telegram_id > 0)
.map((u) => ({
value: String(u.telegram_id),
label: u.full_name || u.username || `ID: ${u.telegram_id}`,
})) || []
const handleSubmit = async (values: typeof form.values) => {
try {
const admin = await createAdmin.mutateAsync({
login: values.login,
name: values.name || undefined,
is_root: values.is_root,
is_observer: values.is_observer,
telegram_id: values.is_observer ? values.telegram_id! : undefined,
})
setCreatedAdmin(admin)
form.reset()
} catch (error) {
// Ошибка уже обработана в хуке
}
}
const handleClose = () => {
setCreatedAdmin(null)
form.reset()
onClose()
}
return (
<Modal
opened={opened}
onClose={handleClose}
title="Создание администратора"
size="md"
>
{createdAdmin ? (
<Stack gap="md">
<Alert
icon={<IconKey size={16} />}
title="Администратор создан"
color="green"
variant="light"
>
<Text size="sm">
Администратор <Code>{createdAdmin.login}</Code> успешно создан.
{createdAdmin.is_root && (
<Text size="sm" fw={600} mt={4}>
Выданы root-права 👑
</Text>
)}
{createdAdmin.is_observer && (
<Text size="sm" fw={600} mt={4}>
Роль: Наблюдатель 👁
</Text>
)}
</Text>
</Alert>
<Paper withBorder p="md" bg="yellow.0">
<Stack gap="xs">
<Group gap="xs">
<IconAlertCircle size={20} color="orange" />
<Text fw={600} size="sm">Временный пароль</Text>
</Group>
<Text size="sm" c="dimmed">
Сохраните этот пароль! После закрытия окна он больше не будет доступен.
</Text>
<Group gap="xs">
<Code
block
style={{
flex: 1,
padding: '12px',
fontSize: '16px',
fontWeight: 600,
letterSpacing: '1px',
}}
>
{createdAdmin.password || '—'}
</Code>
<CopyButton value={createdAdmin.password || ''} timeout={2000}>
{({ copied, copy }) => (
<Tooltip label={copied ? 'Скопировано' : 'Копировать'} withArrow position="right">
<ActionIcon color={copied ? 'teal' : 'gray'} variant="subtle" onClick={copy}>
{copied ? <IconCheck size={16} /> : <IconCopy size={16} />}
</ActionIcon>
</Tooltip>
)}
</CopyButton>
</Group>
</Stack>
</Paper>
<Button onClick={handleClose} fullWidth>
Закрыть
</Button>
</Stack>
) : (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<TextInput
label="Логин"
placeholder="admin_user"
required
description="Уникальный идентификатор (буквы, цифры, подчеркивания)"
{...form.getInputProps('login')}
/>
<TextInput
label="Имя (опционально)"
placeholder="Иванов Иван"
description="Отображаемое имя администратора"
{...form.getInputProps('name')}
/>
<Paper withBorder p="md" bg={form.values.is_root ? 'red.0' : 'gray.0'}>
<Switch
label={
<Group gap="xs">
<IconShield size={16} color="red" />
<Text fw={600}>Выдать root-права</Text>
</Group>
}
description="Администратор сможет создавать других администраторов и управлять root-правами"
checked={form.values.is_root}
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
color="red"
disabled={form.values.is_observer}
/>
</Paper>
<Paper withBorder p="md" bg={form.values.is_observer ? 'blue.0' : 'gray.0'}>
<Switch
label={
<Group gap="xs">
<IconUser size={16} color="blue" />
<Text fw={600}>Наблюдатель</Text>
</Group>
}
description="Ограниченный доступ: только пользователи, заявки и задачи. Обязательна привязка к Telegram-аккаунту"
checked={form.values.is_observer}
onChange={(e) => form.setFieldValue('is_observer', e.currentTarget.checked)}
color="blue"
disabled={form.values.is_root}
/>
</Paper>
{form.values.is_observer && (
<Select
label="Telegram-аккаунт"
placeholder="Выберите пользователя"
data={userOptions}
value={form.values.telegram_id ? String(form.values.telegram_id) : null}
onChange={(v) => form.setFieldValue('telegram_id', v ? Number(v) : null)}
searchable
required
error={form.errors.telegram_id}
description="Пользователь бота, от имени которого будут выгружаться данные"
nothingFoundMessage="Пользователи не найдены"
/>
)}
{form.values.is_root && (
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
<Text size="sm">
<b>Внимание!</b> Root-права дают полный доступ к системе, включая создание и удаление других администраторов.
</Text>
</Alert>
)}
{form.values.is_observer && (
<Alert icon={<IconAlertCircle size={16} />} color="blue" variant="light">
<Text size="sm">
<b>Наблюдатель</b> видит только пользователей, заявки и задачи. Данные выгружаются только те, что доступны выбранному Telegram-аккаунту в боте.
</Text>
</Alert>
)}
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={handleClose} disabled={createAdmin.isPending}>
Отмена
</Button>
<Button type="submit" loading={createAdmin.isPending}>
Создать
</Button>
</Group>
</Stack>
</form>
)}
</Modal>
)
}
-----END src/pages/admins/components/CreateAdminModal.tsx-----
File: src/pages/admins/components/EditAdminModal.tsx
Lines: 202
-----BEGIN src/pages/admins/components/EditAdminModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Button,
Text,
Group,
Badge,
Switch,
Paper,
Alert,
Select,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconShield, IconAlertCircle, IconUser } from '@tabler/icons-react'
import { useUpdateAdmin } from '@/features/admins/hooks/useAdmins'
import { useAuth } from '@/hooks/useAuth'
import { useUsers } from '@/features/users/hooks/useUsers'
import type { Admin } from '@/types/api'
interface EditAdminModalProps {
admin: Admin | null
opened: boolean
onClose: () => void
}
export default function EditAdminModal({ admin, opened, onClose }: EditAdminModalProps) {
const updateAdmin = useUpdateAdmin()
const { user: currentUser } = useAuth()
const { data: usersData } = useUsers({ limit: 1000 })
const form = useForm({
initialValues: {
name: '',
is_root: false,
is_observer: false,
telegram_id: null as number | null,
},
validate: {
telegram_id: (value, values) => {
if (values.is_observer && !value) {
return 'Для наблюдателя обязательно выберите Telegram-аккаунт'
}
return null
},
},
})
useEffect(() => {
if (admin) {
form.setValues({
name: admin.name || '',
is_root: admin.is_root ?? false,
is_observer: admin.is_observer ?? false,
telegram_id: admin.telegram_id || null,
})
}
}, [admin])
useEffect(() => {
if (!form.values.is_observer) {
form.setFieldValue('telegram_id', null)
}
}, [form.values.is_observer])
const isCurrentUser = currentUser?.id === admin?.id
const userOptions = usersData?.data
?.filter((u) => u.telegram_id && u.telegram_id > 0)
.map((u) => ({
value: String(u.telegram_id),
label: u.full_name || u.username || `ID: ${u.telegram_id}`,
})) || []
const handleSubmit = async (values: typeof form.values) => {
if (!admin?.id) return
await updateAdmin.mutateAsync({
id: admin.id,
name: values.name || undefined,
is_root: values.is_root,
is_observer: values.is_observer,
telegram_id: values.is_observer ? values.telegram_id! : null,
})
onClose()
}
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>Редактирование администратора</Text>
{admin && <Badge variant="light">{admin.login}</Badge>}
{admin?.is_root && (
<Badge color="red" variant="filled" leftSection={<IconShield size={12} />}>
ROOT
</Badge>
)}
{admin?.is_observer && (
<Badge color="blue" variant="filled" leftSection={<IconUser size={12} />}>
Наблюдатель
</Badge>
)}
</Group>
}
size="md"
>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<TextInput
label="Логин"
value={admin?.login || ''}
disabled
description="Логин нельзя изменить"
/>
<TextInput
label="Имя"
placeholder="Иванов Иван"
description="Отображаемое имя администратора"
{...form.getInputProps('name')}
/>
<Paper withBorder p="md" bg={form.values.is_root ? 'red.0' : 'gray.0'}>
<Switch
label={
<Group gap="xs">
<IconShield size={16} color="red" />
<Text fw={600}>Root-права</Text>
</Group>
}
description="Может создавать администраторов и управлять root-правами"
checked={form.values.is_root}
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
color="red"
disabled={isCurrentUser || form.values.is_observer}
/>
</Paper>
<Paper withBorder p="md" bg={form.values.is_observer ? 'blue.0' : 'gray.0'}>
<Switch
label={
<Group gap="xs">
<IconUser size={16} color="blue" />
<Text fw={600}>Наблюдатель</Text>
</Group>
}
description="Ограниченный доступ: только пользователи, заявки и задачи"
checked={form.values.is_observer}
onChange={(e) => form.setFieldValue('is_observer', e.currentTarget.checked)}
color="blue"
disabled={isCurrentUser || form.values.is_root}
/>
</Paper>
{form.values.is_observer && (
<Select
label="Telegram-аккаунт"
placeholder="Выберите пользователя"
data={userOptions}
value={form.values.telegram_id ? String(form.values.telegram_id) : null}
onChange={(v) => form.setFieldValue('telegram_id', v ? Number(v) : null)}
searchable
required
error={form.errors.telegram_id}
description="Пользователь бота, от имени которого будут выгружаться данные"
nothingFoundMessage="Пользователи не найдены"
/>
)}
{isCurrentUser && (
<Alert icon={<IconAlertCircle size={16} />} color="yellow" variant="light">
<Text size="sm">
Вы не можете изменить свои собственные права.
</Text>
</Alert>
)}
{form.values.is_root !== (admin?.is_root ?? false) && !isCurrentUser && (
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
<Text size="sm">
<b>Внимание!</b> Вы изменяете root-права. {form.values.is_root
? 'Этот администратор получит полный доступ к системе.'
: 'Этот администратор потеряет возможность создавать других администраторов.'}
</Text>
</Alert>
)}
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose} disabled={updateAdmin.isPending}>
Отмена
</Button>
<Button type="submit" loading={updateAdmin.isPending}>
Сохранить
</Button>
</Group>
</Stack>
</form>
</Modal>
)
}
-----END src/pages/admins/components/EditAdminModal.tsx-----
File: src/pages/approvalTasks/ApprovalTasksPage.tsx
Lines: 284
-----BEGIN src/pages/approvalTasks/ApprovalTasksPage.tsx-----
import { useState } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
Select,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Switch,
} from '@mantine/core'
import { IconEye, IconTrash, IconSearch } from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { useSearchParams } from 'react-router-dom'
import { useApprovalTasks, useDeleteApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
import { useUsers } from '@/features/users/hooks/useUsers'
import { TASK_STATUSES, STATUS_COLORS, STATUS_LABELS } from '@/features/approvalTasks/const'
import ApprovalTaskDetailsModal from './components/ApprovalTaskDetailsModal'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
dayjs.locale('ru')
const LIMIT = 20
export default function ApprovalTasksPage() {
// 🆕 Начальный статус берём из URL (например, с дашборда:
// /approval-tasks?status=completed) — читаем один раз при монтировании.
const [searchParams] = useSearchParams()
const [page, setPage] = useState(1)
const [statusFilter, setStatusFilter] = useState<string | null>(
() => searchParams.get('status')
)
const [executorFilter, setExecutorFilter] = useState<string | null>(null)
const [requireFileFilter, setRequireFileFilter] = useState<boolean | null>(null)
const [selectedTaskId, setSelectedTaskId] = useState<number | null>(null)
const { data, isLoading, isFetching } = useApprovalTasks({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(statusFilter && { status: statusFilter }),
...(executorFilter && { executor_id: Number(executorFilter) }),
...(requireFileFilter !== null && { require_file: requireFileFilter }),
})
const { data: users } = useUsers({ limit: 1000 })
const deleteTask = useDeleteApprovalTask()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const executorOptions = users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || '',
})) || []
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить эту задачу? Это действие нельзя отменить.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteTask.mutate(id),
})
}
return (
<Stack gap="md">
<Group justify="space-between">
<Text size="xl" fw={700}>Задачи по заявкам</Text>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
</Group>
{/* Фильтры */}
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<Select
label="Статус"
placeholder="Все статусы"
data={TASK_STATUSES.map((s) => ({ value: s.value, label: s.label }))}
value={statusFilter}
onChange={(v) => {
setStatusFilter(v)
setPage(1)
}}
clearable
style={{ minWidth: 180 }}
/>
<Select
label="Исполнитель"
placeholder="Все исполнители"
data={executorOptions}
value={executorFilter}
onChange={(v) => {
setExecutorFilter(v)
setPage(1)
}}
clearable
searchable
style={{ minWidth: 200 }}
/>
<Switch
label="Требуют файл"
checked={requireFileFilter === true}
onChange={(e) => {
setRequireFileFilter(e.currentTarget.checked ? true : null)
setPage(1)
}}
/>
</Group>
</Paper>
{/* Таблица */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Заявка</Table.Th>
<Table.Th>Исполнитель</Table.Th>
<Table.Th>Текст задачи</Table.Th>
<Table.Th style={{ width: 80 }}>Шаг</Table.Th>
<Table.Th style={{ width: 120 }}>Статус</Table.Th>
<Table.Th style={{ width: 80 }}>Файл</Table.Th>
<Table.Th>Создана</Table.Th>
<Table.Th>Выполнена</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={10}>
<Center p={40}>
<Text c="dimmed">Задачи не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).map((task) => (
<Table.Tr key={task.id}>
<Table.Td>
<Text fw={500}>#{task.id}</Text>
</Table.Td>
<Table.Td>
<Stack gap={0}>
<Text size="xs" c="dimmed">
#{task.approval_id}
</Text>
<Text size="sm" lineClamp={1}>
{task.approval?.topic?.name || '—'}
</Text>
</Stack>
</Table.Td>
<Table.Td>
<Text size="sm">
{task.executor?.full_name || '—'}
</Text>
<Text size="xs" c="dimmed">
{task.executor?.department?.name}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" lineClamp={2}>
{task.task_text || '—'}
</Text>
</Table.Td>
<Table.Td>
<Badge variant="light" color="gray">
#{task.step_order}
</Badge>
</Table.Td>
<Table.Td>
<Badge
color={STATUS_COLORS[task.status || ''] || 'gray'}
variant={task.status === 'completed' ? 'filled' : 'light'}
>
{STATUS_LABELS[task.status || ''] || task.status}
</Badge>
</Table.Td>
<Table.Td>
{task.require_file ? (
<Badge size="xs" color="violet" variant="light">
Да
</Badge>
) : (
<Text size="xs" c="dimmed">—</Text>
)}
</Table.Td>
<Table.Td>
<Text size="xs" c="dimmed">
{task.created_at
? dayjs(task.created_at).format('DD.MM.YYYY HH:mm')
: '—'}
</Text>
</Table.Td>
<Table.Td>
<Text size="xs" c="dimmed">
{task.completed_at
? dayjs(task.completed_at).format('DD.MM.YYYY HH:mm')
: '—'}
</Text>
</Table.Td>
<Table.Td>
<Group gap="xs">
<Tooltip label="Просмотреть">
<ActionIcon
variant="light"
color="blue"
onClick={() => setSelectedTaskId(task.id!)}
>
<IconEye size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="light"
color="red"
onClick={() => handleDelete(task.id!)}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Table.Td>
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={setPage}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</>
)}
</Paper>
{isFetching && !isLoading && (
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
<Loader size="xs" />
</Box>
)}
<ApprovalTaskDetailsModal
taskId={selectedTaskId}
opened={selectedTaskId !== null}
onClose={() => setSelectedTaskId(null)}
/>
</Stack>
)
}
-----END src/pages/approvalTasks/ApprovalTasksPage.tsx-----
File: src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx
Lines: 396
-----BEGIN src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx-----
import { useState } from 'react'
import {
Modal,
Stack,
Text,
Group,
Badge,
Paper,
Loader,
Center,
ScrollArea,
Select,
Button,
Box,
ActionIcon,
Tooltip,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import {
IconUser,
IconBuilding,
IconCalendar,
IconFileText,
IconCheck,
IconEye,
IconDownload,
} from '@tabler/icons-react'
import { useApprovalTask, useUpdateApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
import { TASK_STATUSES, STATUS_COLORS, STATUS_LABELS } from '@/features/approvalTasks/const'
import FilePreviewModal from '@/pages/approvals/components/FilePreviewModal'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
dayjs.locale('ru')
interface ApprovalTaskDetailsModalProps {
taskId: number | null
opened: boolean
onClose: () => void
}
// Определение MIME типа по расширению
const getMimeType = (fileName: string): string => {
const ext = fileName.split('.').pop()?.toLowerCase() || ''
const mimeTypes: Record<string, string> = {
'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'png': 'image/png',
'gif': 'image/gif', 'webp': 'image/webp', 'svg': 'image/svg+xml',
'pdf': 'application/pdf', 'txt': 'text/plain',
'doc': 'application/msword',
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'xls': 'application/vnd.ms-excel',
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}
return mimeTypes[ext] || 'application/octet-stream'
}
const PREVIEWABLE_TYPES = [
'image/jpeg', 'image/png', 'image/gif', 'image/webp',
'image/svg+xml', 'application/pdf', 'text/plain',
]
export default function ApprovalTaskDetailsModal({
taskId,
opened,
onClose
}: ApprovalTaskDetailsModalProps) {
const { data: task, isLoading } = useApprovalTask(taskId)
const updateTask = useUpdateApprovalTask()
// Состояние для предпросмотра файла
const [previewFileId, setPreviewFileId] = useState<number | null>(null)
const [previewFileName, setPreviewFileName] = useState('')
const [previewFileType, setPreviewFileType] = useState('')
const form = useForm({
initialValues: {
status: '',
},
})
const handleFilePreview = (fileId: number, fileName: string) => {
setPreviewFileId(fileId)
setPreviewFileName(fileName)
setPreviewFileType(getMimeType(fileName))
}
const handleFileDownload = async (fileId: number, fileName: string) => {
try {
const token = localStorage.getItem('token')
const timestamp = Math.floor(Date.now() / 1000).toString()
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
const message = publicKey + ':' + timestamp
const CryptoJS = await import('crypto-js')
const signature = CryptoJS.HmacSHA256(message, privateKey).toString(CryptoJS.enc.Hex)
const deviceId = localStorage.getItem('device_id') || 'admin-panel'
// 🆕 Используем URL для задач
const url = `/api/approval-tasks/${taskId}/files/${fileId}/download`
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'ApiKey': signature,
'X-Timestamp': timestamp,
'x-device-id': deviceId,
},
})
if (!response.ok) throw new Error('Failed to download file')
const blob = await response.blob()
const blobUrl = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = blobUrl
link.download = fileName
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(blobUrl)
notifications.show({
title: 'Успешно',
message: 'Файл скачан',
color: 'green',
})
} catch (error) {
notifications.show({
title: 'Ошибка',
message: 'Не удалось скачать файл',
color: 'red',
})
}
}
const handleSubmit = async (values: typeof form.values) => {
if (!task?.id) return
await updateTask.mutateAsync({
id: task.id,
status: values.status,
})
onClose()
}
return (
<>
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>Задача #{taskId}</Text>
{task && (
<Badge color={STATUS_COLORS[task.status || ''] || 'gray'}>
{STATUS_LABELS[task.status || ''] || task.status}
</Badge>
)}
</Group>
}
size="xl"
styles={{
body: {
height: 'calc(80vh - 120px)',
padding: 0,
},
}}
>
{isLoading ? (
<Center p={40}>
<Loader />
</Center>
) : task ? (
<ScrollArea
style={{ height: 'calc(80vh - 120px)' }}
offsetScrollbars
>
<Box p="md">
<Stack gap="md">
{/* Информация о задаче */}
<Paper withBorder p="md">
<Text size="sm" c="dimmed" mb="xs">Информация о задаче</Text>
<Stack gap="sm">
<Text size="sm" c="dimmed">Текст задачи:</Text>
<Text size="sm" style={{ whiteSpace: 'pre-wrap' }}>
{task.task_text || '—'}
</Text>
<Group justify="space-between">
<Text size="sm" c="dimmed">Шаг:</Text>
<Badge variant="light">#{task.step_order}</Badge>
</Group>
<Group justify="space-between">
<Text size="sm" c="dimmed">Требует файл:</Text>
<Badge color={task.require_file ? 'violet' : 'gray'} variant="light">
{task.require_file ? 'Да' : 'Нет'}
</Badge>
</Group>
</Stack>
</Paper>
{/* 🆕 Прикреплённые файлы */}
{task.files && task.files.length > 0 && (
<Paper withBorder p="md">
<Text size="sm" c="dimmed" mb="xs">Прикреплённые файлы</Text>
<Stack gap="xs">
{task.files.map((file) => {
const mimeType = getMimeType(file.file_name || '')
const canPreview = PREVIEWABLE_TYPES.includes(mimeType)
const fileSizeKB = file.file_base64
? Math.round((file.file_base64.length * 3 / 4) / 1024)
: 0
return (
<Paper key={file.id} withBorder p="sm">
<Group justify="space-between">
<Group gap="sm">
<IconFileText size={20} color="blue" />
<Stack gap={0}>
<Text size="sm" fw={500}>
{file.file_name || 'Без имени'}
</Text>
{fileSizeKB > 0 && (
<Text size="xs" c="dimmed">
{fileSizeKB} KB
</Text>
)}
</Stack>
</Group>
<Group gap="xs">
{canPreview && (
<Tooltip label="Предпросмотр">
<ActionIcon
variant="light"
color="blue"
onClick={() => handleFilePreview(file.id!, file.file_name || '')}
>
<IconEye size={16} />
</ActionIcon>
</Tooltip>
)}
<Tooltip label="Скачать">
<ActionIcon
variant="light"
color="green"
onClick={() => handleFileDownload(file.id!, file.file_name || '')}
>
<IconDownload size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Group>
</Paper>
)
})}
</Stack>
</Paper>
)}
{/* Связанная заявка */}
{task.approval && (
<Paper withBorder p="md">
<Text size="sm" c="dimmed" mb="xs">Связанная заявка</Text>
<Stack gap="sm">
<Group justify="space-between">
<Text size="sm" c="dimmed">ID заявки:</Text>
<Text fw={500}>#{task.approval.id}</Text>
</Group>
<Group justify="space-between">
<Text size="sm" c="dimmed">Тема:</Text>
<Text>{task.approval.topic?.name || '—'}</Text>
</Group>
<Group justify="space-between">
<Text size="sm" c="dimmed">Инициатор:</Text>
<Group gap="xs">
<IconUser size={16} />
<Text>{task.approval.initiator?.full_name || '—'}</Text>
</Group>
</Group>
<Group justify="space-between">
<Text size="sm" c="dimmed">Статус заявки:</Text>
<Badge>{task.approval.status}</Badge>
</Group>
</Stack>
</Paper>
)}
{/* Исполнитель */}
{task.executor && (
<Paper withBorder p="md">
<Text size="sm" c="dimmed" mb="xs">Исполнитель</Text>
<Stack gap="sm">
<Group justify="space-between">
<Text size="sm" c="dimmed">Имя:</Text>
<Group gap="xs">
<IconUser size={16} />
<Text fw={500}>{task.executor.full_name}</Text>
</Group>
</Group>
{task.executor.department && (
<Group justify="space-between">
<Text size="sm" c="dimmed">Отдел:</Text>
<Group gap="xs">
<IconBuilding size={16} />
<Text>{task.executor.department.name}</Text>
</Group>
</Group>
)}
</Stack>
</Paper>
)}
{/* Даты */}
<Paper withBorder p="md">
<Text size="sm" c="dimmed" mb="xs">Временные метки</Text>
<Stack gap="sm">
<Group justify="space-between">
<Text size="sm" c="dimmed">Создана:</Text>
<Group gap="xs">
<IconCalendar size={16} />
<Text>
{task.created_at
? dayjs(task.created_at).format('DD.MM.YYYY HH:mm')
: '—'}
</Text>
</Group>
</Group>
<Group justify="space-between">
<Text size="sm" c="dimmed">Обновлена:</Text>
<Text>
{task.updated_at
? dayjs(task.updated_at).format('DD.MM.YYYY HH:mm')
: '—'}
</Text>
</Group>
{task.completed_at && (
<Group justify="space-between">
<Text size="sm" c="dimmed">Выполнена:</Text>
<Group gap="xs">
<IconCheck size={16} color="green" />
<Text c="green">
{dayjs(task.completed_at).format('DD.MM.YYYY HH:mm')}
</Text>
</Group>
</Group>
)}
</Stack>
</Paper>
{/* Форма обновления статуса */}
<Paper withBorder p="md" bg="blue.0">
<Text size="sm" fw={600} mb="sm">Изменить статус</Text>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<Select
label="Новый статус"
placeholder="Выберите статус"
data={TASK_STATUSES.map((s) => ({ value: s.value, label: s.label }))}
value={form.values.status || task.status}
onChange={(v) => form.setFieldValue('status', v || '')}
required
/>
<Group justify="flex-end">
<Button
type="submit"
loading={updateTask.isPending}
leftSection={<IconCheck size={16} />}
>
Обновить статус
</Button>
</Group>
</Stack>
</form>
</Paper>
</Stack>
</Box>
</ScrollArea>
) : (
<Center p={40}>
<Text c="dimmed">Задача не найдена</Text>
</Center>
)}
</Modal>
{previewFileId && taskId && (
<FilePreviewModal
taskId={taskId}
fileId={previewFileId}
fileName={previewFileName}
fileType={previewFileType}
opened={!!previewFileId}
onClose={() => setPreviewFileId(null)}
/>
)}
</>
)
}
-----END src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx-----
File: src/pages/approvals/ApprovalsPage.tsx
Lines: 614
-----BEGIN src/pages/approvals/ApprovalsPage.tsx-----
import { useEffect, useState, useMemo } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Select,
MultiSelect,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Divider,
Alert,
} from '@mantine/core'
import { DatePickerInput } from '@mantine/dates'
import {
IconEye,
IconSearch,
IconFileText,
IconFileExcel,
IconInfoCircle,
IconX,
IconFilter,
} from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import { useSearchParams } from 'react-router-dom'
import { useApprovals } from '@/features/approvals/hooks/useApprovals'
import { useTopics } from '@/features/topics/hooks/useTopics'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useUsers } from '@/features/users/hooks/useUsers'
import { approvalsApi } from '@/api/approvals'
import ApprovalDetailsModal from './components/ApprovalDetailsModal'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
import { useDebouncedValue } from '@mantine/hooks'
dayjs.locale('ru')
const LIMIT = 20
const STATUS_COLORS: Record<string, string> = {
pending: 'blue',
approved: 'green',
rejected: 'red',
revoked: 'orange',
revision: 'violet',
}
const STATUS_LABELS: Record<string, string> = {
pending: 'На согласовании',
approved: 'Согласована',
rejected: 'Отклонена',
revoked: 'Отозвана',
revision: 'На доработке',
}
export default function ApprovalsPage() {
// 🆕 Значения фильтров, с которыми пришли по ссылке (например, с
// дашборда: /approvals?status=pending&date_to=2026-07-20). Читаем
// только один раз при монтировании — страница не синхронизирует
// фильтры с URL постоянно, только принимает начальное состояние.
const [searchParams] = useSearchParams()
// === Состояния фильтров ===
const [page, setPage] = useState(1)
const [searchInput, setSearchInput] = useState('')
const [search, setSearch] = useState('')
const [searchError, setSearchError] = useState<string | null>(null)
const [debouncedSearch] = useDebouncedValue(searchInput, 400)
const [statusFilter, setStatusFilter] = useState<string | null>(
() => searchParams.get('status')
)
const [categoryFilter, setCategoryFilter] = useState<string[]>([])
const [topicFilter, setTopicFilter] = useState<string[]>([])
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
const [initiatorFilter, setInitiatorFilter] = useState<string | null>(null)
const [dateFrom, setDateFrom] = useState<Date | null>(() => {
const v = searchParams.get('date_from')
return v ? dayjs(v).toDate() : null
})
const [dateTo, setDateTo] = useState<Date | null>(() => {
const v = searchParams.get('date_to')
return v ? dayjs(v).toDate() : null
})
// === Отчёт ===
const [reportDateFrom, setReportDateFrom] = useState<Date | null>(null)
const [reportDateTo, setReportDateTo] = useState<Date | null>(null)
const [reportLoading, setReportLoading] = useState(false)
const [selectedApprovalId, setSelectedApprovalId] = useState<number | null>(null)
// === Обработка поиска ===
useEffect(() => {
if (debouncedSearch === '') {
setSearch('')
setSearchError(null)
setPage(1)
return
}
if (debouncedSearch.length < 2) {
setSearchError('Введите минимум 2 символа')
return
}
setSearchError(null)
setSearch(debouncedSearch)
setPage(1)
}, [debouncedSearch])
// === Загрузка справочников ===
const { data: categories } = useCategories({ limit: 1000 })
const { data: allTopics } = useTopics({ limit: 1000 })
const { data: departments } = useDepartments()
const { data: users } = useUsers({ limit: 1000 })
// === Темы, отфильтрованные по выбранным категориям ===
const filteredTopics = useMemo(() => {
if (!allTopics?.data) return []
if (categoryFilter.length === 0) return allTopics.data
const categoryIds = categoryFilter.map(Number)
return allTopics.data.filter((t) =>
t.category_id && categoryIds.includes(t.category_id)
)
}, [allTopics, categoryFilter])
// === Сброс невалидных тем при изменении категорий ===
useEffect(() => {
if (categoryFilter.length > 0 && topicFilter.length > 0) {
const validTopicIds = new Set(filteredTopics.map((t) => String(t.id)))
const validSelected = topicFilter.filter((id) => validTopicIds.has(id))
if (validSelected.length !== topicFilter.length) {
setTopicFilter(validSelected)
}
}
// Если категории сброшены — темы остаются как есть
}, [categoryFilter, filteredTopics, topicFilter])
// === Опции для Select/MultiSelect ===
const categoryOptions = useMemo(
() =>
categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || [],
[categories]
)
const topicOptions = useMemo(
() =>
filteredTopics.map((t) => ({
value: String(t.id),
label: `${t.category?.name || '—'} / ${t.name || ''}`,
})),
[filteredTopics]
)
const departmentOptions = useMemo(
() =>
departments?.data?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || [],
[departments]
)
const userOptions = useMemo(
() =>
users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || u.username || `ID: ${u.id}`,
})) || [],
[users]
)
// === Формирование параметров запроса ===
const requestParams = useMemo(() => {
const params: any = {
offset: (page - 1) * LIMIT,
limit: LIMIT,
}
if (search) params.content = search
if (statusFilter) params.status = statusFilter
if (departmentFilter) params.department_id = Number(departmentFilter)
if (initiatorFilter) params.initiator_id = Number(initiatorFilter)
if (categoryFilter.length > 0) {
params.category_ids = categoryFilter.map(Number)
}
if (topicFilter.length > 0) {
params.topic_ids = topicFilter.map(Number)
}
if (dateFrom) params.date_from = dayjs(dateFrom).format('YYYY-MM-DD')
if (dateTo) params.date_to = dayjs(dateTo).format('YYYY-MM-DD')
return params
}, [
page, search, statusFilter, departmentFilter,
initiatorFilter, categoryFilter, topicFilter, dateFrom, dateTo,
])
// === Запрос списка заявок ===
const { data, isLoading, isFetching } = useApprovals(requestParams)
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
// === Сброс фильтров ===
const handleResetFilters = () => {
setSearchInput('')
setSearch('')
setStatusFilter(null)
setCategoryFilter([])
setTopicFilter([])
setDepartmentFilter(null)
setInitiatorFilter(null)
setDateFrom(null)
setDateTo(null)
setPage(1)
}
const hasActiveFilters =
search ||
statusFilter ||
categoryFilter.length > 0 ||
topicFilter.length > 0 ||
departmentFilter ||
initiatorFilter ||
dateFrom ||
dateTo
// === Генерация отчёта ===
const handleGenerateReport = async () => {
setReportLoading(true)
try {
const params: any = { all_access: true }
if (reportDateFrom) params.date_from = dayjs(reportDateFrom).format('YYYY-MM-DD')
if (reportDateTo) params.date_to = dayjs(reportDateTo).format('YYYY-MM-DD')
const response = await approvalsApi.downloadReport(params)
const blob = new Blob([response.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
})
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
const now = dayjs()
link.setAttribute(
'download',
`Согласования_${now.format('DD.MM.YYYY')}_${now.format('HH-mm')}.xlsx`
)
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(url)
notifications.show({
title: 'Успешно',
message: 'Отчёт сформирован и скачан',
color: 'green',
})
} catch (error: any) {
notifications.show({
title: 'Ошибка',
message: error.response?.data?.error_description || 'Не удалось сформировать отчёт',
color: 'red',
})
} finally {
setReportLoading(false)
}
}
return (
<Stack gap="md">
{/* Заголовок */}
<Group justify="space-between">
<Text size="xl" fw={700}>Заявки</Text>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
</Group>
{/* Секция отчёта */}
<Paper withBorder p="md" bg="blue.0">
<Stack gap="sm">
<Group justify="space-between">
<Group gap="xs">
<IconFileExcel size={20} color="blue" />
<Text fw={600} size="lg">Формирование отчёта</Text>
</Group>
<Button
leftSection={<IconFileExcel size={16} />}
color="green"
onClick={handleGenerateReport}
loading={reportLoading}
size="sm"
>
Скачать XLSX
</Button>
</Group>
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light" p="xs">
<Text size="sm">
Выберите период для выгрузки отчёта. Если даты не указаны — будут выгружены все заявки.
</Text>
</Alert>
<Group gap="md" align="flex-end">
<DatePickerInput
label="Дата начала периода"
placeholder="Выберите дату"
value={reportDateFrom}
onChange={(val) => setReportDateFrom(val as Date | null)}
clearable
style={{ flex: 1 }}
/>
<DatePickerInput
label="Дата окончания периода"
placeholder="Выберите дату"
value={reportDateTo}
onChange={(val) => setReportDateTo(val as Date | null)}
clearable
minDate={reportDateFrom || undefined}
style={{ flex: 1 }}
/>
</Group>
</Stack>
</Paper>
<Divider />
{/* Фильтры списка */}
<Paper withBorder p="md">
<Group justify="space-between" mb="sm">
<Group gap="xs">
<IconFilter size={20} />
<Text fw={600} size="lg">Фильтры</Text>
</Group>
{hasActiveFilters && (
<Button
variant="subtle"
color="gray"
size="xs"
leftSection={<IconX size={14} />}
onClick={handleResetFilters}
>
Сбросить фильтры
</Button>
)}
</Group>
<Stack gap="md">
{/* Строка 1: Поиск + Статус + Инициатор */}
<Group gap="md" align="flex-end" grow>
<TextInput
label="Поиск по тексту"
placeholder="Введите 2+ символа..."
leftSection={<IconSearch size={16} />}
value={searchInput}
onChange={(e) => setSearchInput(e.currentTarget.value)}
error={searchError}
rightSection={
searchInput && (
<ActionIcon
variant="subtle"
onClick={() => setSearchInput('')}
>
<IconX size={14} />
</ActionIcon>
)
}
/>
<Select
label="Статус"
placeholder="Все статусы"
data={[
{ value: 'pending', label: 'На согласовании' },
{ value: 'approved', label: 'Согласована' },
{ value: 'rejected', label: 'Отклонена' },
{ value: 'revoked', label: 'Отозвана' },
{ value: 'revision', label: 'На доработке' },
]}
value={statusFilter}
onChange={(v) => {
setStatusFilter(v)
setPage(1)
}}
clearable
/>
<Select
label="Инициатор"
placeholder="Все инициаторы"
data={userOptions}
value={initiatorFilter}
onChange={(v) => {
setInitiatorFilter(v)
setPage(1)
}}
clearable
searchable
/>
</Group>
{/* Строка 2: Категории + Темы + Отдел */}
<Group gap="md" align="flex-end" grow>
<MultiSelect
label="Категории"
placeholder="Все категории"
data={categoryOptions}
value={categoryFilter}
onChange={(v) => {
setCategoryFilter(v)
setPage(1)
}}
clearable
searchable
nothingFoundMessage="Категории не найдены"
/>
<MultiSelect
label="Темы"
placeholder={
categoryFilter.length > 0
? 'Выберите темы'
: 'Все темы'
}
data={topicOptions}
value={topicFilter}
onChange={(v) => {
setTopicFilter(v)
setPage(1)
}}
clearable
searchable
disabled={filteredTopics.length === 0}
nothingFoundMessage="Темы не найдены"
description={
categoryFilter.length > 0
? `Показаны темы выбранных категорий (${filteredTopics.length})`
: undefined
}
/>
<Select
label="Отдел"
placeholder="Все отделы"
data={departmentOptions}
value={departmentFilter}
onChange={(v) => {
setDepartmentFilter(v)
setPage(1)
}}
clearable
/>
</Group>
{/* Строка 3: Период дат */}
<Group gap="md" align="flex-end" grow>
<DatePickerInput
label="Дата создания от"
placeholder="Выберите дату"
value={dateFrom}
onChange={(val) => {
setDateFrom(val as Date | null)
setPage(1)
}}
clearable
maxDate={dateTo || undefined}
/>
<DatePickerInput
label="Дата создания до"
placeholder="Выберите дату"
value={dateTo}
onChange={(val) => {
setDateTo(val as Date | null)
setPage(1)
}}
clearable
minDate={dateFrom || undefined}
/>
<Box style={{ flex: 1 }} />
</Group>
</Stack>
</Paper>
{/* Таблица */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Категория / Тема</Table.Th>
<Table.Th>Инициатор</Table.Th>
<Table.Th>Отдел</Table.Th>
<Table.Th>Дата создания</Table.Th>
<Table.Th style={{ width: 150 }}>Статус</Table.Th>
<Table.Th style={{ width: 80 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={7}>
<Center p={40}>
<Text c="dimmed">Заявки не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).map((approval) => (
<Table.Tr key={approval.id}>
<Table.Td>
<Text fw={500}>#{approval.id}</Text>
</Table.Td>
<Table.Td>
<Stack gap={0}>
<Text size="xs" c="dimmed">
{approval.topic?.category?.name || '—'}
</Text>
<Group gap="xs">
<IconFileText size={14} color="gray" />
<Text size="sm" lineClamp={1}>
{approval.topic?.name || 'Тема не указана'}
</Text>
</Group>
</Stack>
</Table.Td>
<Table.Td>
<Text size="sm">
{approval.initiator?.full_name || '—'}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">
{approval.department?.name || '—'}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">
{approval.created_at
? dayjs(approval.created_at).format('DD.MM.YYYY HH:mm')
: '—'}
</Text>
</Table.Td>
<Table.Td>
<Badge
color={STATUS_COLORS[approval.status || ''] || 'gray'}
variant={approval.status === 'pending' ? 'light' : 'filled'}
>
{STATUS_LABELS[approval.status || ''] || approval.status}
</Badge>
</Table.Td>
<Table.Td>
<Tooltip label="Просмотреть детали">
<ActionIcon
variant="light"
color="blue"
onClick={() => setSelectedApprovalId(approval.id!)}
>
<IconEye size={16} />
</ActionIcon>
</Tooltip>
</Table.Td>
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={setPage}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</>
)}
</Paper>
{isFetching && !isLoading && (
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
<Loader size="xs" />
</Box>
)}
<ApprovalDetailsModal
approvalId={selectedApprovalId}
opened={selectedApprovalId !== null}
onClose={() => setSelectedApprovalId(null)}
/>
</Stack>
)
}
-----END src/pages/approvals/ApprovalsPage.tsx-----
File: src/pages/approvals/components/ApprovalDetailsModal.tsx
Lines: 690
-----BEGIN src/pages/approvals/components/ApprovalDetailsModal.tsx-----
import { useState } from 'react'
import {
Modal,
Stack,
Text,
Group,
Badge,
Paper,
Loader,
Center,
Timeline,
ScrollArea,
Box,
ActionIcon,
Tooltip,
Alert,
Divider,
} from '@mantine/core'
import {
IconUser,
IconBuilding,
IconCalendar,
IconFileText,
IconCheck,
IconX,
IconClock,
IconAlertCircle,
IconEye,
IconDownload,
IconMessageCircle,
IconUserPlus,
IconEyeglass,
IconRotate,
IconChecklist,
IconAlertTriangle,
} from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import {
useApproval,
useAdditionalApprovers,
useApprovalComments,
useApprovalObservers,
useRevocationRequest,
useApprovalTasks,
} from '@/features/approvals/hooks/useApprovals'
import { useCategories } from '@/features/categories/hooks/useCategories'
import FilePreviewModal from './FilePreviewModal'
import { formatMsk } from '@/utils/date'
interface ApprovalDetailsModalProps {
approvalId: number | null
opened: boolean
onClose: () => void
}
const STATUS_COLORS: Record<string, string> = {
draft: 'gray',
pending: 'blue',
approved: 'green',
rejected: 'red',
revoked: 'orange',
revision: 'violet',
}
const STATUS_LABELS: Record<string, string> = {
pending: 'На согласовании',
approved: 'Согласована',
rejected: 'Отклонена',
revoked: 'Отозвана',
revision: 'На доработке',
}
const STEP_STATUS_ICONS: Record<string, any> = {
pending: IconClock,
approved: IconCheck,
rejected: IconX,
waiting: IconClock,
cancelled_any_of: IconAlertCircle,
}
const STEP_STATUS_COLORS: Record<string, string> = {
pending: 'blue',
approved: 'green',
rejected: 'red',
waiting: 'gray',
cancelled_any_of: 'orange',
}
// Статусы "доп. согласующего" — те же значения, что в handleDecision
// (isAdditionalApprover): "pending" / "approved" / "rejected".
const ADDITIONAL_APPROVER_LABELS: Record<string, string> = {
pending: 'Ожидает решения',
approved: 'Одобрил',
rejected: 'Отклонил',
}
const ADDITIONAL_APPROVER_COLORS: Record<string, string> = {
pending: 'blue',
approved: 'green',
rejected: 'red',
}
// Статусы согласующего на запрос отзыва (см. HandleRevocationApproverDecision
// в telegram_service).
const REVOCATION_APPROVER_LABELS: Record<string, string> = {
pending: 'Ещё не ответил',
approved: 'Согласен на отзыв',
rejected: 'Против отзыва',
}
const REVOCATION_APPROVER_COLORS: Record<string, string> = {
pending: 'gray',
approved: 'green',
rejected: 'red',
}
const APPROVAL_MODE_LABELS: Record<string, string> = {
sequential: 'Последовательно',
any_of: 'Любой из согласующих',
}
// Статусы задач — те же значения и подписи, что в отчёте (reportcore.go)
// и в "Стадиях согласования" бота.
const TASK_STATUS_LABELS: Record<string, string> = {
pending: 'В работе',
waiting: 'Ожидает',
completed: 'Выполнена',
cancelled: 'Отменена',
cancellation: 'Требует отмены изменений',
}
const TASK_STATUS_COLORS: Record<string, string> = {
pending: 'blue',
waiting: 'gray',
completed: 'green',
cancelled: 'red',
cancellation: 'orange',
}
const PREVIEWABLE_TYPES = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/svg+xml',
'application/pdf',
'text/plain',
]
const getMimeType = (fileName: string): string => {
const ext = fileName.split('.').pop()?.toLowerCase() || ''
const mimeTypes: Record<string, string> = {
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
png: 'image/png',
gif: 'image/gif',
webp: 'image/webp',
svg: 'image/svg+xml',
pdf: 'application/pdf',
txt: 'text/plain',
doc: 'application/msword',
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
xls: 'application/vnd.ms-excel',
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}
return mimeTypes[ext] || 'application/octet-stream'
}
const generateSignature = async (): Promise<{ signature: string; timestamp: string; deviceId: string }> => {
const timestamp = Math.floor(Date.now() / 1000).toString()
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
const message = publicKey + ':' + timestamp
const CryptoJS = await import('crypto-js')
const signature = CryptoJS.HmacSHA256(message, privateKey).toString(CryptoJS.enc.Hex)
const deviceId = localStorage.getItem('device_id') || 'admin-panel'
return { signature, timestamp, deviceId }
}
const getAuthHeaders = async () => {
const token = localStorage.getItem('token')
const { signature, timestamp, deviceId } = await generateSignature()
return {
Authorization: `Bearer ${token}`,
ApiKey: signature,
'X-Timestamp': timestamp,
'x-device-id': deviceId,
}
}
export default function ApprovalDetailsModal({
approvalId,
opened,
onClose,
}: ApprovalDetailsModalProps) {
const { data: approval, isLoading } = useApproval(approvalId)
const { data: categories } = useCategories({ limit: 1000 })
// Хуки отдают ApiResponse<T> целиком (как useFlowNodesTree раньше) —
// разворачиваем здесь, а не в самих хуках, чтобы не плодить два разных
// соглашения об обёртке в одном проекте.
const { data: additionalApproversResponse } = useAdditionalApprovers(approvalId)
const { data: commentsResponse } = useApprovalComments(approvalId)
const { data: observersResponse } = useApprovalObservers(approvalId)
const { data: revocationRequestResponse } = useRevocationRequest(approvalId)
const { data: tasksResponse } = useApprovalTasks(approvalId)
const additionalApprovers = additionalApproversResponse?.data
const comments = commentsResponse?.data
const observers = observersResponse?.data
const revocationRequest = revocationRequestResponse?.data
const tasksData = tasksResponse?.data
const [previewFileId, setPreviewFileId] = useState<number | null>(null)
const [previewFileName, setPreviewFileName] = useState('')
const [previewFileType, setPreviewFileType] = useState('')
const category = approval?.topic?.category_id && categories?.data
? categories.data.find((c) => c.id === approval.topic?.category_id)
: null
const handleFilePreview = (fileId: number, fileName: string) => {
setPreviewFileId(fileId)
setPreviewFileName(fileName)
setPreviewFileType(getMimeType(fileName))
}
const handleFileDownload = async (fileId: number, fileName: string) => {
try {
const headers = await getAuthHeaders()
const url = `/api/approvals/${approvalId}/files/${fileId}/download`
const response = await fetch(url, { method: 'GET', headers })
if (!response.ok) {
throw new Error('Failed to download file')
}
const blob = await response.blob()
const blobUrl = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = blobUrl
link.download = fileName
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(blobUrl)
notifications.show({ title: 'Успешно', message: 'Файл скачан', color: 'green' })
} catch (error) {
console.error('Download error:', error)
notifications.show({ title: 'Ошибка', message: 'Не удалось скачать файл', color: 'red' })
}
}
// Показываем превью "что будет поставлено" только пока заявка ещё не
// согласована И задачи по факту ещё не созданы — как только появились
// реальные ApprovalTask, показываем уже их (ниже), а не план.
const showPlannedTasks =
approval?.status === 'pending' &&
!!tasksData?.topic_executors?.length &&
!tasksData?.tasks?.length
return (
<>
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>Заявка #{approvalId}</Text>
{approval && (
<Badge color={STATUS_COLORS[approval.status || ''] || 'gray'}>
{STATUS_LABELS[approval.status || ''] || approval.status}
</Badge>
)}
</Group>
}
size="xl"
styles={{ body: { height: 'calc(80vh - 120px)', padding: 0 } }}
>
{isLoading ? (
<Center p={40}>
<Loader />
</Center>
) : approval ? (
<ScrollArea style={{ height: 'calc(80vh - 120px)' }} offsetScrollbars>
<Box p="md">
<Stack gap="md">
{/* НОВОЕ: ошибка создания задач — та же логика, что в отчёте
(reportcore.go: hasTaskError). Ставим у самого верха, это
требует внимания администратора, а не просто информация. */}
{tasksData?.has_task_error && (
<Alert icon={<IconAlertTriangle size={16} />} color="red" variant="filled">
<Text size="sm" fw={600}>
Ошибка при создании задачи
</Text>
<Text size="xs">
Для темы этой заявки настроены исполнители, заявка согласована, но ни
одной задачи по факту не создано — стоит проверить вручную.
</Text>
</Alert>
)}
{/* НОВОЕ: активный запрос на отзыв — самое "срочное", поэтому
сверху, ещё до общей информации. Показывается, только если
такой запрос реально есть (backend отдаёт data: null иначе) */}
{revocationRequest && (
<Alert icon={<IconRotate size={16} />} color="orange" variant="light">
<Stack gap={6}>
<Text size="sm" fw={600}>
Идёт запрос на отзыв этой заявки
</Text>
<Text size="xs">
Инициатор запроса: {revocationRequest.requested_by_name}
</Text>
{revocationRequest.reason && (
<Text size="xs">Причина: {revocationRequest.reason}</Text>
)}
<Stack gap={4} mt={4}>
{revocationRequest.approvers.map((a) => (
<Group key={a.approver_id} justify="space-between" gap="xs">
<Text size="xs">{a.approver_name}</Text>
<Badge
size="xs"
color={REVOCATION_APPROVER_COLORS[a.status] || 'gray'}
>
{REVOCATION_APPROVER_LABELS[a.status] || a.status}
</Badge>
</Group>
))}
</Stack>
</Stack>
</Alert>
)}
{/* Основная информация */}
<Paper withBorder p="md">
<Text size="sm" c="dimmed" mb="xs">Основная информация</Text>
<Stack gap="sm">
<Group justify="space-between">
<Text size="sm" c="dimmed">Категория:</Text>
<Text fw={500}>{category?.name || '—'}</Text>
</Group>
<Group justify="space-between">
<Text size="sm" c="dimmed">Тема:</Text>
<Text>{approval.topic?.name || '—'}</Text>
</Group>
{/* Режим согласования — лежит на теме */}
{approval.topic?.approval_mode && (
<Group justify="space-between">
<Text size="sm" c="dimmed">Режим согласования:</Text>
<Text>
{APPROVAL_MODE_LABELS[approval.topic.approval_mode] ||
approval.topic.approval_mode}
</Text>
</Group>
)}
<Group justify="space-between">
<Text size="sm" c="dimmed">Инициатор:</Text>
<Group gap="xs">
<IconUser size={16} />
<Text>{approval.initiator?.full_name || '—'}</Text>
</Group>
</Group>
<Group justify="space-between">
<Text size="sm" c="dimmed">Отдел:</Text>
<Group gap="xs">
<IconBuilding size={16} />
<Text>{approval.department?.name || '—'}</Text>
</Group>
</Group>
<Group justify="space-between">
<Text size="sm" c="dimmed">Дата создания (МСК):</Text>
<Group gap="xs">
<IconCalendar size={16} />
<Text>{formatMsk(approval.created_at)}</Text>
</Group>
</Group>
</Stack>
</Paper>
{/* НОВОЕ: превью "что будет поставлено" — только для pending-заявок,
пока реальных задач ещё нет. Данные берём из ApprovalTopicExecutor
(настройка темы), а не из ApprovalTask (их ещё физически не существует). */}
{showPlannedTasks && (
<Paper withBorder p="md" bg="blue.0">
<Group gap="xs" mb="xs">
<IconChecklist size={16} />
<Text size="sm" c="dimmed">
Какие задачи будут поставлены после согласования
</Text>
</Group>
<Stack gap="xs">
{tasksData!.topic_executors
.slice()
.sort((a, b) => a.step_order - b.step_order)
.map((te) => (
<Group key={te.id} justify="space-between" wrap="nowrap">
<Text size="sm" style={{ flex: 1 }}>
{te.task_text || '—'}
</Text>
<Badge variant="light" color="blue">
{te.executor_name || 'Исполнитель не назначен'}
</Badge>
</Group>
))}
</Stack>
<Text size="xs" c="dimmed" mt="xs">
Появится автоматически, как только заявку согласуют полностью.
</Text>
</Paper>
)}
{/* НОВОЕ: уже реально выставленные задачи */}
{!!tasksData?.tasks?.length && (
<Paper withBorder p="md">
<Group gap="xs" mb="xs">
<IconChecklist size={16} />
<Text size="sm" c="dimmed">Задачи</Text>
</Group>
<Stack gap="xs">
{tasksData.tasks.map((task, i) => (
<Paper key={task.id} withBorder p="sm">
<Group justify="space-between" wrap="nowrap" mb={4}>
<Text size="sm" fw={500}>
Выставлена задача №{i + 1}
</Text>
<Badge size="xs" color={TASK_STATUS_COLORS[task.status] || 'gray'}>
{TASK_STATUS_LABELS[task.status] || task.status}
</Badge>
</Group>
<Text size="sm">{task.task_text || '—'}</Text>
<Text size="xs" c="dimmed" mt={4}>
Исполнитель: {task.executor_name || '—'}
{task.completed_at && <> · Выполнена {formatMsk(task.completed_at)}</>}
</Text>
</Paper>
))}
</Stack>
</Paper>
)}
{/* Наблюдатели — вычисляются динамически по категории/теме
(не хранимая связь), поэтому отдельным запросом */}
{observers && observers.length > 0 && (
<Paper withBorder p="md">
<Group gap="xs" mb="xs">
<IconEyeglass size={16} />
<Text size="sm" c="dimmed">Наблюдатели</Text>
</Group>
<Group gap="xs">
{observers.map((o) => (
<Badge key={o.id} variant="light" color="gray">
{o.full_name}
</Badge>
))}
</Group>
</Paper>
)}
{/* Текст заявки */}
{approval.content && (
<Paper withBorder p="md">
<Text size="sm" c="dimmed" mb="xs">Текст заявки</Text>
<Text>{approval.content}</Text>
</Paper>
)}
{/* Метаданные */}
{approval.metadata && (
<Paper withBorder p="md">
<Text size="sm" c="dimmed" mb="xs">Метаданные</Text>
<Text size="sm" style={{ fontFamily: 'monospace', whiteSpace: 'pre-wrap' }}>
{(() => {
try {
return JSON.stringify(JSON.parse(approval.metadata), null, 2)
} catch {
return approval.metadata
}
})()}
</Text>
</Paper>
)}
{/* Файлы */}
{approval.files && approval.files.length > 0 && (
<Paper withBorder p="md">
<Text size="sm" c="dimmed" mb="xs">Прикреплённые файлы</Text>
<Stack gap="xs">
{approval.files.map((file) => {
const mimeType = getMimeType(file.file_name || '')
const canPreview = PREVIEWABLE_TYPES.includes(mimeType)
const fileSizeKB = file.file_base64
? Math.round((file.file_base64.length * 3) / 4 / 1024)
: 0
return (
<Paper key={file.id} withBorder p="sm">
<Group justify="space-between">
<Group gap="sm">
<IconFileText size={20} color="blue" />
<Stack gap={0}>
<Text size="sm" fw={500}>
{file.file_name || 'Без имени'}
</Text>
{fileSizeKB > 0 && (
<Text size="xs" c="dimmed">
{fileSizeKB} KB
</Text>
)}
</Stack>
</Group>
<Group gap="xs">
{canPreview && (
<Tooltip label="Предпросмотр">
<ActionIcon
variant="light"
color="blue"
onClick={() => handleFilePreview(file.id!, file.file_name || '')}
>
<IconEye size={16} />
</ActionIcon>
</Tooltip>
)}
<Tooltip label="Скачать">
<ActionIcon
variant="light"
color="green"
onClick={() => handleFileDownload(file.id!, file.file_name || '')}
>
<IconDownload size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Group>
</Paper>
)
})}
</Stack>
</Paper>
)}
{/* Шаги согласования */}
{approval.steps && approval.steps.length > 0 && (
<Paper withBorder p="md">
<Text size="sm" c="dimmed" mb="xs">Шаги согласования</Text>
<Timeline active={-1} bulletSize={24} lineWidth={2}>
{approval.steps
.sort((a, b) => (a.step_order || 0) - (b.step_order || 0))
.map((step, index) => {
const StatusIcon = STEP_STATUS_ICONS[step.status || ''] || IconClock
return (
<Timeline.Item
key={step.id}
bullet={<StatusIcon size={14} />}
title={
<Group gap="xs">
<Text size="sm" fw={500}>
Шаг {index + 1}: {step.approver_name_snapshot || 'Согласующий'}
</Text>
<Badge size="xs" color={STEP_STATUS_COLORS[step.status || ''] || 'gray'}>
{step.status}
</Badge>
</Group>
}
>
<Text size="xs" c="dimmed">
{step.approver?.full_name || '—'}
{step.acted_at && (
<>
{' • '}
{formatMsk(step.acted_at)}
</>
)}
</Text>
{step.comment && (
<Text size="xs" mt={4}>
Комментарий: {step.comment}
</Text>
)}
</Timeline.Item>
)
})}
</Timeline>
</Paper>
)}
{/* Дополнительные согласующие */}
{additionalApprovers && additionalApprovers.length > 0 && (
<Paper withBorder p="md">
<Group gap="xs" mb="xs">
<IconUserPlus size={16} />
<Text size="sm" c="dimmed">Дополнительные согласующие</Text>
</Group>
<Stack gap="xs">
{additionalApprovers.map((aa) => (
<Group key={aa.id} justify="space-between">
<Text size="sm">{aa.approver_name}</Text>
<Group gap="xs">
{aa.acted_at && (
<Text size="xs" c="dimmed">{formatMsk(aa.acted_at)}</Text>
)}
<Badge size="xs" color={ADDITIONAL_APPROVER_COLORS[aa.status] || 'blue'}>
{ADDITIONAL_APPROVER_LABELS[aa.status] || aa.status}
</Badge>
</Group>
</Group>
))}
</Stack>
</Paper>
)}
{/* Комментарии */}
{comments && comments.length > 0 && (
<Paper withBorder p="md">
<Group gap="xs" mb="xs">
<IconMessageCircle size={16} />
<Text size="sm" c="dimmed">Комментарии ({comments.length})</Text>
</Group>
<Stack gap="sm">
{comments.map((c, i) => (
<Box key={c.id}>
<Group justify="space-between" gap="xs">
<Text size="xs" fw={600}>{c.user_name}</Text>
{c.created_at && (
<Text size="xs" c="dimmed">{formatMsk(c.created_at)}</Text>
)}
</Group>
<Text size="sm">{c.comment}</Text>
{i < comments.length - 1 && <Divider mt="sm" />}
</Box>
))}
</Stack>
</Paper>
)}
{/* Информация об отзыве */}
{approval.status === 'revoked' && approval.revoked_by && (
<Paper withBorder p="md" bg="orange.0">
<Text size="sm" c="dimmed" mb="xs">Информация об отзыве</Text>
<Group gap="sm">
<IconAlertCircle size={16} />
<Text size="sm">
Отозвана: {approval.revoked_by.full_name}
{approval.revoked_at && <> {formatMsk(approval.revoked_at)}</>}
</Text>
</Group>
</Paper>
)}
{/* Информация о доработке */}
{approval.status === 'revision' && (
<Paper withBorder p="md" bg="violet.0">
<Text size="sm" c="dimmed" mb="xs">Информация о доработке</Text>
<Stack gap="xs">
{approval.revision_comment && (
<Text size="sm">
<Text fw={500} component="span">Комментарий:</Text> {approval.revision_comment}
</Text>
)}
{approval.revision_count !== undefined && approval.revision_count > 0 && (
<Text size="sm">
<Text fw={500} component="span">Количество доработок:</Text> {approval.revision_count}
</Text>
)}
</Stack>
</Paper>
)}
</Stack>
</Box>
</ScrollArea>
) : (
<Center p={40}>
<Text c="dimmed">Заявка не найдена</Text>
</Center>
)}
</Modal>
{previewFileId && approvalId && (
<FilePreviewModal
approvalId={approvalId}
fileId={previewFileId}
fileName={previewFileName}
fileType={previewFileType}
opened={!!previewFileId}
onClose={() => setPreviewFileId(null)}
/>
)}
</>
)
}
-----END src/pages/approvals/components/ApprovalDetailsModal.tsx-----
File: src/pages/approvals/components/FilePreviewModal.tsx
Lines: 266
-----BEGIN src/pages/approvals/components/FilePreviewModal.tsx-----
import { useState, useEffect } from 'react'
import { Modal, Group, Text, Loader, Center, Paper, ActionIcon, Stack, Box } from '@mantine/core'
import { IconDownload } from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
interface FilePreviewModalProps {
approvalId?: number // Теперь опционально
fileId: number
fileName: string
fileType: string
opened: boolean
onClose: () => void
taskId?: number // 🆕 Для файлов задач
}
// 🆕 Тип сущности
type EntityType = 'approval' | 'task'
const getAuthHeaders = async () => {
const token = localStorage.getItem('token')
const timestamp = Math.floor(Date.now() / 1000).toString()
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
const message = publicKey + ':' + timestamp
const CryptoJS = await import('crypto-js')
const signature = CryptoJS.HmacSHA256(message, privateKey).toString(CryptoJS.enc.Hex)
const deviceId = localStorage.getItem('device_id') || 'admin-panel'
return {
'Authorization': `Bearer ${token}`,
'ApiKey': signature,
'X-Timestamp': timestamp,
'x-device-id': deviceId,
}
}
export default function FilePreviewModal({
approvalId,
fileId,
fileName,
fileType,
opened,
onClose,
taskId, // 🆕
}: FilePreviewModalProps) {
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [fileUrl, setFileUrl] = useState<string | null>(null)
// 🆕 Определяем тип сущности
const entityType: EntityType = taskId ? 'task' : 'approval'
const entityId = taskId || approvalId
// 🆕 Формируем URL в зависимости от типа сущности
const getPreviewUrl = () => {
if (entityType === 'task') {
return `/api/approval-tasks/${taskId}/files/${fileId}`
}
return `/api/approvals/${approvalId}/files/${fileId}`
}
const getDownloadUrl = () => {
if (entityType === 'task') {
return `/api/approval-tasks/${taskId}/files/${fileId}/download`
}
return `/api/approvals/${approvalId}/files/${fileId}/download`
}
const canPreview = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/svg+xml',
'application/pdf',
'text/plain',
].includes(fileType)
useEffect(() => {
if (!opened || !canPreview || !entityId) return
let objectUrl: string | null = null
const loadFile = async () => {
setLoading(true)
setError(null)
try {
const headers = await getAuthHeaders()
const url = getPreviewUrl()
const response = await fetch(url, {
method: 'GET',
headers,
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
const blob = await response.blob()
objectUrl = window.URL.createObjectURL(blob)
setFileUrl(objectUrl)
} catch (err) {
console.error('File load error:', err)
setError('Не удалось загрузить файл')
} finally {
setLoading(false)
}
}
loadFile()
return () => {
if (objectUrl) {
window.URL.revokeObjectURL(objectUrl)
}
}
}, [opened, entityId, fileId, canPreview])
const handleDownload = async () => {
try {
const headers = await getAuthHeaders()
const url = getDownloadUrl()
const response = await fetch(url, {
method: 'GET',
headers,
})
if (!response.ok) {
throw new Error('Failed to download file')
}
const blob = await response.blob()
const blobUrl = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = blobUrl
link.download = fileName
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(blobUrl)
notifications.show({
title: 'Успешно',
message: 'Файл скачан',
color: 'green',
})
} catch (err) {
console.error('Download error:', err)
notifications.show({
title: 'Ошибка',
message: 'Не удалось скачать файл',
color: 'red',
})
}
}
if (!canPreview) {
return (
<Modal opened={opened} onClose={onClose} title="Предпросмотр недоступен" size="md">
<Paper p="md" withBorder>
<Stack gap="md">
<Text>
Предпросмотр этого типа файла не поддерживается.
<br />
Вы можете скачать файл.
</Text>
<Group justify="flex-end">
<ActionIcon
variant="light"
color="blue"
size="lg"
onClick={handleDownload}
>
<IconDownload size={20} />
</ActionIcon>
</Group>
</Stack>
</Paper>
</Modal>
)
}
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group justify="space-between" style={{ flex: 1 }}>
<Text fw={600} lineClamp={1}>{fileName}</Text>
<ActionIcon
variant="light"
color="blue"
onClick={handleDownload}
>
<IconDownload size={20} />
</ActionIcon>
</Group>
}
size="xl"
styles={{
body: {
height: 'calc(80vh - 120px)',
padding: 0,
},
}}
>
<Box style={{ height: '100%', width: '100%', position: 'relative' }}>
{loading && (
<Center style={{ position: 'absolute', inset: 0, zIndex: 1 }}>
<Stack align="center" gap="xs">
<Loader size="lg" />
<Text size="sm" c="dimmed">Загрузка файла...</Text>
</Stack>
</Center>
)}
{error && (
<Center h="100%">
<Text c="red">{error}</Text>
</Center>
)}
{fileUrl && !error && (
<>
{fileType.startsWith('image/') ? (
<Center style={{ height: '100%', background: '#f5f5f5' }}>
<img
src={fileUrl}
alt={fileName}
style={{
maxWidth: '100%',
maxHeight: '100%',
objectFit: 'contain',
}}
/>
</Center>
) : fileType === 'application/pdf' ? (
<iframe
src={fileUrl}
style={{
width: '100%',
height: '100%',
border: 'none',
}}
title={fileName}
/>
) : fileType === 'text/plain' ? (
<iframe
src={fileUrl}
style={{
width: '100%',
height: '100%',
border: 'none',
background: 'white',
}}
title={fileName}
/>
) : null}
</>
)}
</Box>
</Modal>
)
}
-----END src/pages/approvals/components/FilePreviewModal.tsx-----
File: src/pages/categories/CategoriesPage.tsx
Lines: 230
-----BEGIN src/pages/categories/CategoriesPage.tsx-----
import { useState } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Switch,
} from '@mantine/core'
import { IconPencil, IconTrash, IconPlus, IconSearch } from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { useCategories, useDeleteCategory } from '@/features/categories/hooks/useCategories'
import CategoryEditModal from './components/CategoryEditModal'
const LIMIT = 20
export default function CategoriesPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [activeFilter, setActiveFilter] = useState<boolean | null>(null)
const [editCategoryId, setEditCategoryId] = useState<number | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const { data, isLoading, isFetching } = useCategories({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(search && { name: search }),
...(activeFilter !== null && { is_active: activeFilter }),
})
const deleteCategory = useDeleteCategory()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить эту категорию? Все темы этой категории останутся без категории.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteCategory.mutate(id),
})
}
return (
<Stack gap="md">
<Group justify="space-between">
<Text size="xl" fw={700}>Категории тем</Text>
<Group>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
<Button
leftSection={<IconPlus size={16} />}
onClick={() => setCreateModalOpened(true)}
>
Создать категорию
</Button>
</Group>
</Group>
{/* Фильтры */}
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<TextInput
label="Поиск по названию"
placeholder="Отпуска, больничные..."
leftSection={<IconSearch size={16} />}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
style={{ flex: 1 }}
/>
<Switch
label="Только активные"
checked={activeFilter === true}
onChange={(e) => {
setActiveFilter(e.currentTarget.checked ? true : null)
setPage(1)
}}
/>
</Group>
</Paper>
{/* Таблица */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Название</Table.Th>
<Table.Th>Код</Table.Th>
<Table.Th>Описание</Table.Th>
<Table.Th style={{ width: 100 }}>Статус</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={6}>
<Center p={40}>
<Text c="dimmed">Категории не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).map((category) => (
<Table.Tr key={category.id}>
<Table.Td>{category.id}</Table.Td>
<Table.Td>
<Text fw={500}>{category.name}</Text>
</Table.Td>
<Table.Td>
<Text size="sm" ff="monospace" c="dimmed">
{category.code}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" lineClamp={2}>
{category.description || '—'}
</Text>
</Table.Td>
<Table.Td>
<Badge
color={category.is_active ? 'green' : 'gray'}
variant={category.is_active ? 'light' : 'filled'}
>
{category.is_active ? 'Активна' : 'Неактивна'}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs">
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditCategoryId(category.id!)}
>
<IconPencil size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="light"
color="red"
onClick={() => handleDelete(category.id!)}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Table.Td>
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
{/* Пагинация */}
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={setPage}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</>
)}
</Paper>
{/* Индикатор обновления */}
{isFetching && !isLoading && (
<Box
style={{
position: 'fixed',
top: 70,
right: 20,
zIndex: 1000
}}
>
<Loader size="xs" />
</Box>
)}
{/* Модальное окно редактирования */}
<CategoryEditModal
categoryId={editCategoryId}
opened={editCategoryId !== null}
onClose={() => setEditCategoryId(null)}
/>
{/* Модальное окно создания */}
<CategoryEditModal
categoryId={null}
opened={createModalOpened}
onClose={() => setCreateModalOpened(false)}
/>
</Stack>
)
}
-----END src/pages/categories/CategoriesPage.tsx-----
File: src/pages/categories/components/CategoryEditModal.tsx
Lines: 151
-----BEGIN src/pages/categories/components/CategoryEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Textarea,
Switch,
Group,
Button,
Text,
Loader,
Center,
Badge,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
useCategory,
useCreateCategory,
useUpdateCategory
} from '@/features/categories/hooks/useCategories'
interface CategoryEditModalProps {
categoryId: number | null
opened: boolean
onClose: () => void
}
export default function CategoryEditModal({
categoryId,
opened,
onClose
}: CategoryEditModalProps) {
const { data: category, isLoading: categoryLoading } = useCategory(categoryId)
const createCategory = useCreateCategory()
const updateCategory = useUpdateCategory()
const isEditMode = categoryId !== null
const form = useForm({
initialValues: {
name: '',
code: '',
description: '',
is_active: true,
},
validate: {
name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
code: (value: string | any[]) => {
if (value.length < 2) return 'Код должен содержать минимум 2 символа'
if (!/^[a-z0-9_]+$/.test(value as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
return null
},
},
})
// Заполняем форму данными категории
useEffect(() => {
if (category) {
form.setValues({
name: category.name || '',
code: category.code || '',
description: category.description || '',
is_active: category.is_active ?? true,
})
} else if (!isEditMode) {
form.reset()
}
}, [category, isEditMode])
const handleSubmit = async (values: typeof form.values) => {
if (isEditMode && categoryId) {
// Режим редактирования
await updateCategory.mutateAsync({
id: categoryId,
...values,
})
} else {
// Режим создания
await createCategory.mutateAsync(values)
}
onClose()
}
const isLoading = categoryLoading
const isSubmitting = createCategory.isPending || updateCategory.isPending
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>
{isEditMode ? 'Редактирование категории' : 'Создание категории'}
</Text>
{category && <Badge variant="light">ID: {category.id}</Badge>}
</Group>
}
size="md"
>
{isLoading ? (
<Center p={40}>
<Loader />
</Center>
) : (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<TextInput
label="Название"
placeholder="Отпуска и отгулы"
required
{...form.getInputProps('name')}
/>
<TextInput
label="Код"
placeholder="vacation"
required
description="Уникальный идентификатор категории (lowercase, цифры, подчеркивания)"
disabled={isEditMode}
{...form.getInputProps('code')}
/>
<Textarea
label="Описание"
placeholder="Описание категории..."
minRows={3}
{...form.getInputProps('description')}
/>
<Switch
label="Активна"
description="Неактивные категории не будут доступны для выбора при создании тем"
checked={form.values.is_active}
onChange={(e) => form.setFieldValue('is_active', e.currentTarget.checked)}
/>
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
{isEditMode ? 'Сохранить' : 'Создать'}
</Button>
</Group>
</Stack>
</form>
)}
</Modal>
)
}
-----END src/pages/categories/components/CategoryEditModal.tsx-----
File: src/pages/flowNodes/FlowTreeGuidePage.tsx
Lines: 766
-----BEGIN src/pages/flowNodes/FlowTreeGuidePage.tsx-----
import { useState, useEffect } from 'react'
import {
Stack,
Text,
Code,
Paper,
Group,
Box,
Title,
Table,
Divider,
ActionIcon,
Tooltip,
CopyButton,
ScrollArea,
Badge,
Alert,
UnstyledButton,
Timeline,
ThemeIcon,
} from '@mantine/core'
import {
IconArrowLeft,
IconCopy,
IconCheck,
IconBulb,
IconAlertTriangle,
} from '@tabler/icons-react'
import { useNavigate } from 'react-router-dom'
// ================================================================
// Структура документации
// ================================================================
interface DocSection {
id: string
title: string
level: number
}
const SECTIONS: DocSection[] = [
{ id: 'overview', title: 'Что это такое', level: 1 },
{ id: 'terms', title: 'Три простых понятия', level: 1 },
{ id: 'howto', title: 'Как создать дерево — по шагам', level: 1 },
{ id: 'step-1', title: ' 1. Выбрать категорию', level: 2 },
{ id: 'step-2', title: ' 2. Создать первый узел', level: 2 },
{ id: 'step-3', title: ' 3. Добавить варианты (ветки)', level: 2 },
{ id: 'step-4', title: ' 4. Завершить ветку вводом текста', level: 2 },
{ id: 'step-5', title: ' 5. Настроить сообщение согласующему', level: 2 },
{ id: 'step-6', title: ' 6. Проверить результат', level: 2 },
{ id: 'node-types', title: 'Три типа узлов', level: 1 },
{ id: 'example-1', title: 'Пример: «Отпуска»', level: 1 },
{ id: 'example-2', title: 'Пример: выбор из нескольких списков', level: 1 },
{ id: 'template-basics', title: 'Как писать сообщение согласующему', level: 1 },
{ id: 'tips', title: 'Советы и правила', level: 1 },
{ id: 'troubleshooting', title: 'Если что-то не работает', level: 1 },
]
export default function FlowTreeGuidePage() {
const navigate = useNavigate()
const [activeSection, setActiveSection] = useState('overview')
useEffect(() => {
const handleScroll = () => {
const scrollPosition = window.scrollY + 100
for (const section of [...SECTIONS].reverse()) {
const element = document.getElementById(section.id)
if (element && element.offsetTop <= scrollPosition) {
setActiveSection(section.id)
break
}
}
}
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
}, [])
const scrollTo = (id: string) => {
document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' })
setActiveSection(id)
}
return (
<Box style={{ display: 'flex', gap: 32, alignItems: 'flex-start' }}>
<Box
style={{
width: 260,
flexShrink: 0,
position: 'sticky',
top: 20,
maxHeight: 'calc(100vh - 40px)',
}}
>
<Stack gap={0}>
<Group justify="space-between" mb="md">
<Text size="xs" fw={600} c="dimmed" tt="uppercase" lts={1}>
Руководство
</Text>
<ActionIcon
variant="subtle"
size="sm"
onClick={() => navigate('/nodes')}
>
<IconArrowLeft size={16} />
</ActionIcon>
</Group>
<ScrollArea style={{ maxHeight: 'calc(100vh - 120px)' }}>
<Stack gap={2}>
{SECTIONS.map((section) => (
<UnstyledButton
key={section.id}
onClick={() => scrollTo(section.id)}
px={section.level === 2 ? 20 : 12}
py={6}
style={{
borderRadius: 4,
backgroundColor:
activeSection === section.id
? 'var(--mantine-color-blue-0)'
: 'transparent',
borderLeft:
activeSection === section.id
? '2px solid var(--mantine-color-blue-6)'
: '2px solid transparent',
}}
>
<Text
size={section.level === 2 ? 'xs' : 'sm'}
c={activeSection === section.id ? 'blue.7' : 'dimmed'}
fw={activeSection === section.id ? 600 : 400}
>
{section.title}
</Text>
</UnstyledButton>
))}
</Stack>
</ScrollArea>
</Stack>
</Box>
{/* ============================================================ */}
{/* Основной контент */}
{/* ============================================================ */}
<Box style={{ flex: 1, maxWidth: 880, minWidth: 0 }}>
<Stack gap={48} pb={120}>
{/* Заголовок */}
<Box>
<Title order={1}>Как настроить дерево согласования</Title>
<Text c="dimmed" mt="sm" size="lg">
Это руководство для тех, кто настраивает бота — без программирования.
Здесь пошагово показано, как собрать «дерево» вопросов, которые бот задаёт
сотруднику, когда тот создаёт заявку: например, «Какой регион?» →
«Какая причина?» → «Опишите заявку».
</Text>
</Box>
<Divider />
{/* ============================================================ */}
{/* ОБЗОР */}
{/* ============================================================ */}
<DocSection id="overview" title="Что это такое" />
<Text>
Когда сотрудник создаёт заявку в Telegram-боте, бот задаёт ему вопросы по
очереди и предлагает варианты ответов кнопками. Например: «Выберите
регион» → «Крым» или «Краснодар» → «Опишите заявку текстом». Эта
последовательность вопросов и есть <b>дерево</b>.
</Text>
<Text>
Вы настраиваете это дерево в разделе «Конструктор деревьев» — без единой
строчки кода. Каждый вопрос и каждая кнопка — это отдельный «узел», который
вы добавляете через простую форму.
</Text>
<Callout title="Зачем это нужно">
Так настраиваются любые сценарии: отпуска, больничные, внебюджетные
расходы, возвраты и любые другие заявки. Если появится новый вид заявки —
не нужно ничего программировать, достаточно собрать новое дерево здесь.
</Callout>
{/* ============================================================ */}
{/* ТРИ ПОНЯТИЯ */}
{/* ============================================================ */}
<DocSection id="terms" title="Три простых понятия" />
<Text>
Прежде чем начать, важно понимать всего три вещи:
</Text>
<Table withTableBorder withColumnBorders mt="md">
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 180 }}>Понятие</Table.Th>
<Table.Th>Что это простыми словами</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
<Table.Tr>
<Table.Td><b>Категория</b></Table.Td>
<Table.Td>
Раздел заявок, который вы выбираете вверху страницы («Отпуска»,
«Внебюджетные расходы» и т.д.). Одно дерево всегда строится
внутри одной категории.
</Table.Td>
</Table.Tr>
<Table.Tr>
<Table.Td><b>Узел</b></Table.Td>
<Table.Td>
Один шаг в дереве: кнопка с вариантом ответа, поле ввода текста
или список для множественного выбора. Узлы соединяются друг с
другом — у каждого может быть несколько «детей» (следующих
шагов).
</Table.Td>
</Table.Tr>
<Table.Tr>
<Table.Td><b>Тема заявки</b></Table.Td>
<Table.Td>
То, во что в итоге превращается пройденный сотрудником путь по
дереву. Например, путь «Крым → За свой счёт» превращается в
конкретную тему заявки со своими согласующими.
</Table.Td>
</Table.Tr>
</Table.Tbody>
</Table>
<Callout title="Главное правило">
Дерево — это как схема метро: от начальной станции (первого вопроса) до
конечной (поля ввода текста) должен существовать путь через любые
промежуточные станции (кнопки-варианты). Ваша задача — построить эти пути.
</Callout>
{/* ============================================================ */}
{/* ПОРЯДОК СОЗДАНИЯ */}
{/* ============================================================ */}
<DocSection id="howto" title="Как создать дерево — по шагам" />
<Text>
Ниже — точный порядок действий от пустой категории до готового,
работающего дерева.
</Text>
<DocSection id="step-1" title="Шаг 1. Выбрать категорию" level={2} />
<Text>
Откройте страницу «Конструктор деревьев» и в выпадающем списке «Категория»
выберите нужный раздел. Если подходящей категории ещё нет — обратитесь к
администратору, чтобы её создали (это отдельная настройка, не относится к
дереву).
</Text>
<Callout title="Совет">
Если дерево для этой категории уже существует, вы увидите его сразу после
выбора. Можно смело редактировать — все изменения сохраняются
автоматически, ничего не потеряется.
</Callout>
<DocSection id="step-2" title="Шаг 2. Создать первый узел" level={2} />
<Text>
Нажмите кнопку «Добавить корневой узел». Это будет самый первый вопрос,
который увидит сотрудник. Откроется окно с тремя полями:
</Text>
<Table withTableBorder withColumnBorders mt="xs">
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 180 }}>Поле</Table.Th>
<Table.Th>Что писать</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
<Table.Tr>
<Table.Td>Тип узла</Table.Td>
<Table.Td>Оставьте «Кнопка» — для первого шага почти всегда нужна кнопка</Table.Td>
</Table.Tr>
<Table.Tr>
<Table.Td>Название</Table.Td>
<Table.Td>То, что увидит сотрудник, например «Отпуска»</Table.Td>
</Table.Tr>
<Table.Tr>
<Table.Td>Ключ</Table.Td>
<Table.Td>
Не трогайте — заполняется автоматически из названия
</Table.Td>
</Table.Tr>
</Table.Tbody>
</Table>
<Text mt="sm">
Нажмите «Создать». Узел появится в дереве — с него всё и начинается.
</Text>
<DocSection id="step-3" title="Шаг 3. Добавить варианты (ветки)" level={2} />
<Text>
Наведите на созданный узел — рядом появятся кнопки. Нажмите «+», чтобы
добавить к нему дочерний узел — следующий шаг вопроса. Повторяйте это для
каждого варианта ответа.
</Text>
<Text>
Например, если первый узел — «Тип отпуска», добавьте к нему детей:
«Отпуск», «Отгул», «Больничный». Каждый из них — отдельная кнопка, которую
увидит сотрудник после выбора первого шага.
</Text>
<Callout title="Важно про DataKey и DataValue" mt="md">
Для узлов-кнопок в форме есть два поля: <b>DataKey</b> — название того, что
мы запоминаем (например «тип отпуска»), и <b>DataValue</b> — конкретное
значение этой кнопки (например «отпуск»). У всех кнопок-веток одного и того
же вопроса DataKey должен быть одинаковым, а DataValue — у каждой свой.
Смотрите готовый пример ниже — там всё видно на конкретных значениях.
</Callout>
<DocSection id="step-4" title="Шаг 4. Завершить ветку вводом текста" level={2} />
<Text>
Каждая ветка дерева обязательно должна заканчиваться узлом «Текстовый
ввод» — это последний шаг, где сотрудник пишет саму заявку своими словами.
Добавьте такой узел к каждому «листу» дерева (к узлу, у которого больше нет
вариантов выбора).
</Text>
<Text>
В форме выберите тип узла «Текстовый ввод» и заполните поле «Подсказка» —
это пример того, что должен написать сотрудник, чтобы ему было понятнее.
</Text>
<Callout title="Как проверить, что дерево готово">
Пройдите мысленно (или на бумаге) каждый путь от первого узла до конца.
Если какой-то путь обрывается на кнопке, не доходя до текстового ввода —
сотрудник не сможет завершить заявку. Добавьте туда узел ввода.
</Callout>
<DocSection id="step-5" title="Шаг 5. Настроить сообщение согласующему" level={2} />
<Text>
На узле, где заявка «превращается» в конкретную тему (обычно это последний
узел-кнопка перед вводом текста), можно раскрыть блок «Шаблоны сообщения и
кода темы» и задать, как будет выглядеть уведомление у согласующего в
Telegram. Подробно про это — в разделе{' '}
<Text component="span" fw={600}>«Как писать сообщение согласующему»</Text>{' '}
ниже. Если ничего не менять — сработает оформление по умолчанию.
</Text>
<DocSection id="step-6" title="Шаг 6. Проверить результат" level={2} />
<Text>
Дерево сохраняется автоматически после каждого действия — отдельной кнопки
«Сохранить всё» нажимать не нужно. Лучший способ проверить готовое дерево —
попросить коллегу создать тестовую заявку через бота и убедиться, что все
вопросы задаются в правильном порядке, а итоговое сообщение согласующему
выглядит понятно.
</Text>
{/* ============================================================ */}
{/* ТИПЫ УЗЛОВ */}
{/* ============================================================ */}
<DocSection id="node-types" title="Три типа узлов" />
<Text>
При создании или редактировании узла вы выбираете один из трёх типов:
</Text>
<Stack gap="sm" mt="md">
<Paper withBorder p="md">
<Group gap="xs" mb={4}>
<Text size="lg">🔘</Text>
<Text fw={600}>Кнопка</Text>
</Group>
<Text size="sm" c="dimmed">
Сотрудник нажимает и переходит к следующему шагу. Используется для
любого выбора из вариантов: регион, тип заявки, филиал и т.д.
Требует заполнения DataKey и DataValue.
</Text>
</Paper>
<Paper withBorder p="md">
<Group gap="xs" mb={4}>
<Text size="lg">📝</Text>
<Text fw={600}>Текстовый ввод</Text>
</Group>
<Text size="sm" c="dimmed">
Сотрудник печатает текст. Всегда завершает ветку дерева — после
него бот создаёт заявку. Требует заполнения «Подсказки» —
примера того, что нужно написать.
</Text>
</Paper>
<Paper withBorder p="md">
<Group gap="xs" mb={4}>
<Text size="lg">☑️</Text>
<Text fw={600}>Мультивыбор</Text>
</Group>
<Text size="sm" c="dimmed">
Сотрудник может отметить сразу несколько вариантов (например,
несколько систем: «ОКБ» и «1С»). Все отмеченные варианты
сохранятся вместе, через запятую.
</Text>
</Paper>
</Stack>
{/* ============================================================ */}
{/* ПРИМЕР 1 */}
{/* ============================================================ */}
<DocSection id="example-1" title="Пример: дерево «Отпуска»" />
<Text>
Разберём готовый пример целиком — от первого узла до отправки заявки.
Сценарий: сотрудник выбирает тип отсутствия, затем способ оплаты, затем
пишет причину.
</Text>
<Timeline active={5} bulletSize={28} lineWidth={2} mt="md">
<Timeline.Item title="Корневой узел">
<Text size="sm" c="dimmed">
Название: <Code>Тип отсутствия</Code>. Тип узла: Кнопка. Это
«заголовок» дерева — сам по себе кнопкой сотруднику не показывается,
но от него отходят первые варианты.
</Text>
</Timeline.Item>
<Timeline.Item title="Три дочерних узла-кнопки">
<Text size="sm" c="dimmed">
Добавляем к корню три узла: <Code>Отпуск</Code>, <Code>Отгул</Code>,{' '}
<Code>Больничный</Code>. У всех трёх DataKey одинаковый —{' '}
<Code>absence_type</Code>, а DataValue разный: <Code>vacation</Code>,{' '}
<Code>timeoff</Code>, <Code>sickleave</Code>.
</Text>
</Timeline.Item>
<Timeline.Item title="Способ оплаты — для каждой ветки">
<Text size="sm" c="dimmed">
К узлу «Отпуск» добавляем два дочерних узла: <Code>За свой счёт</Code>{' '}
и <Code>В счёт отпуска</Code>. DataKey у обоих —{' '}
<Code>payment_type</Code>, DataValue — <Code>own_expense</Code> и{' '}
<Code>vacation_account</Code> соответственно. Аналогично поступаем с
ветками «Отгул» и «Больничный».
</Text>
</Timeline.Item>
<Timeline.Item title="Текстовый ввод — конец каждой ветки">
<Text size="sm" c="dimmed">
К каждому из узлов способа оплаты добавляем узел «Текстовый ввод» с
подсказкой: <Code>Укажите даты отпуска, например: 22.02.2026 — 25.02.2026</Code>.
</Text>
</Timeline.Item>
<Timeline.Item title="Сообщение согласующему">
<Text size="sm" c="dimmed">
На узле способа оплаты (там, где заявка уже точно определена)
открываем «Шаблоны сообщения и кода темы» и вписываем текст — см.
пример ниже.
</Text>
</Timeline.Item>
</Timeline>
<CodeBlock
title="Дерево целиком выглядит так"
code={`Тип отсутствия
├── Отпуск (absence_type = vacation)
│ ├── За свой счёт (payment_type = own_expense) → Ввод текста
│ └── В счёт отпуска (payment_type = vacation_account) → Ввод текста
├── Отгул (absence_type = timeoff)
│ ├── За свой счёт (payment_type = own_expense) → Ввод текста
│ └── В счёт отпуска (payment_type = vacation_account) → Ввод текста
└── Больничный (absence_type = sickleave)
└── Официальный (payment_type = official) → Ввод текста`}
/>
<Text mt="sm">
Что увидит сотрудник в боте: сначала кнопки «Отпуск / Отгул /
Больничный», затем — «За свой счёт / В счёт отпуска», затем поле для
ввода дат. Три нажатия и один текст — заявка готова.
</Text>
<CodeBlock
title="Пример текста сообщения согласующему (поле «Шаблон сообщения»)"
code={`📋 <b>Тип: {{.absence_type_label}}</b>
<b>{{.initiator_name}}</b> просит согласовать: {{.payment_type_label}}
{{.content}}`}
/>
<Text size="sm" c="dimmed" mt="xs">
Всё, что в фигурных скобках — подставится автоматически: название узла,
который выбрал сотрудник, его имя и текст, который он написал. Про этот
синтаксис подробнее — в разделе ниже.
</Text>
{/* ============================================================ */}
{/* ПРИМЕР 2 */}
{/* ============================================================ */}
<DocSection id="example-2" title="Пример: выбор из нескольких списков" />
<Text>
Более сложный, но частый случай: нужно спросить у сотрудника два
независимых параметра подряд — например, филиал и тип расхода.
</Text>
<CodeBlock
title="Структура"
code={`Внебюджетные расходы
├── Филиал 1 (branch = f1)
│ ├── ТМЦ (expense_type = tmc) → Ввод текста
│ └── Расходы (expense_type = expense) → Ввод текста
└── Филиал 2 (branch = f2)
├── ТМЦ (expense_type = tmc) → Ввод текста
└── Расходы (expense_type = expense) → Ввод текста`}
/>
<Text mt="sm">
Обратите внимание: узел «ТМЦ» повторяется дважды — под «Филиал 1» и под
«Филиал 2». Это нормально: узлы с одинаковым названием на разных ветках
дерева — это разные, независимые узлы, у каждого свой ключ (система
добавляет к ключу префикс родителя автоматически).
</Text>
<CodeBlock
title="Пример сообщения согласующему"
code={`📋 <b>Внебюджетные расходы — {{.branch_label}} ({{.expense_type_label}})</b>
<b>{{.initiator_name}}</b>:
{{.content}}`}
/>
{/* ============================================================ */}
{/* ШАБЛОНЫ */}
{/* ============================================================ */}
<DocSection id="template-basics" title="Как писать сообщение согласующему" />
<Text>
В блоке «Шаблоны сообщения и кода темы» вы пишете обычный текст с
HTML-разметкой (<Code>&lt;b&gt;жирный&lt;/b&gt;</Code>,{' '}
<Code>&lt;i&gt;курсив&lt;/i&gt;</Code>) — так, как хотите видеть уведомление
у согласующего. В нужных местах вставляете «плейсхолдеры» в фигурных
скобках — они подставляются автоматически.
</Text>
<Table withTableBorder withColumnBorders mt="md">
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 260 }}>Что написать</Table.Th>
<Table.Th>Что подставится</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
<Table.Tr>
<Table.Td><Code>{`{{.initiator_name}}`}</Code></Table.Td>
<Table.Td>Имя сотрудника, который создал заявку</Table.Td>
</Table.Tr>
<Table.Tr>
<Table.Td><Code>{`{{.content}}`}</Code></Table.Td>
<Table.Td>Текст, который сотрудник ввёл на последнем шаге</Table.Td>
</Table.Tr>
<Table.Tr>
<Table.Td><Code>{`{{.название_кнопки_label}}`}</Code></Table.Td>
<Table.Td>
Название выбранной сотрудником кнопки. Например, если DataKey
кнопки — <Code>region</Code>, пишите{' '}
<Code>{`{{.region_label}}`}</Code>, и туда подставится «Крым» или
«Краснодар» — смотря что выбрал сотрудник
</Table.Td>
</Table.Tr>
</Table.Tbody>
</Table>
<Callout title="Проще всего — по аналогии" mt="md">
Не нужно запоминать синтаксис. Откройте похожий уже настроенный узел (в
этой же или другой категории), скопируйте оттуда шаблон и замените
плейсхолдеры на DataKey ваших узлов.
</Callout>
<Text mt="md">
Дополнительно доступны несколько простых условий — пригодятся, если
сообщение должно немного отличаться в зависимости от выбора:
</Text>
<CodeBlock
title="Показать текст, только если поле заполнено"
code={`{{if .payment_type_label}}Способ оплаты: {{.payment_type_label}}{{end}}`}
/>
<CodeBlock
title="Показать разный текст в зависимости от выбора"
code={`{{if eq .absence_type "vacation"}}Отпуск{{else}}Отгул{{end}}`}
/>
<Text size="sm" c="dimmed" mt="xs">
Поле «Шаблон кода темы» обычно можно не трогать — если оставить пустым,
система сама соберёт код заявки из всех выборов сотрудника. Заполняйте его
только если вам явно сказали, что для этой темы нужен особый код
(например, если это уже настроенная в системе тема с заранее заданным
названием).
</Text>
{/* ============================================================ */}
{/* СОВЕТЫ */}
{/* ============================================================ */}
<DocSection id="tips" title="Советы и правила" />
<Stack gap="sm" mt="md">
<TipEntry
title="Одинаковый DataKey у братьев"
text="Все узлы-кнопки, отходящие от одного и того же родителя, должны иметь одинаковый DataKey (например, все — region), а DataValue у каждого — свой (crimea, krasnodar). Иначе бот запутается, какой ответ на какой вопрос сохранён."
/>
<TipEntry
title="Каждая ветка должна заканчиваться вводом текста"
text="Если ветка обрывается на кнопке — сотрудник не сможет закончить заявку. Всегда добавляйте узел «Текстовый ввод» в конце каждого пути."
/>
<TipEntry
title="Название узла — то, что видит сотрудник"
text="Пишите названия узлов понятно и коротко: то, что вы вводите в поле «Название», один в один появится кнопкой в Telegram."
/>
<TipEntry
title="Ключ трогать не обязательно"
text="Поле «Ключ» заполняется автоматически из названия — это техническая метка, которую использует система внутри себя. Менять его вручную нужно, только если он получился слишком длинным или непонятным."
/>
<TipEntry
title="Изменения сохраняются сразу"
text="Не нужно искать кнопку «Сохранить дерево» — каждое действие (добавление, редактирование, перемещение, удаление узла) применяется мгновенно."
/>
<TipEntry
title="Удаление узла удаляет и всё, что под ним"
text="Если вы удаляете узел, у которого есть дочерние узлы — они удалятся вместе с ним. Система предупредит об этом перед удалением."
/>
</Stack>
{/* ============================================================ */}
{/* ДИАГНОСТИКА */}
{/* ============================================================ */}
<DocSection id="troubleshooting" title="Если что-то не работает" />
<Text>
Частые ситуации и что с ними делать:
</Text>
<Stack gap="md" mt="md">
<ErrorEntry
title="Бот не находит тему заявки после всех вопросов"
description="Это значит, что набор выборов сотрудника не совпал ни с одной настроенной темой в системе."
resolution="Проверьте узел, где задан код темы (поле «Код темы» или шаблон кода) — сверьте его с администратором системы, который заводит темы заявок."
/>
<ErrorEntry
title="В сообщении согласующему вместо текста написано «<no value>»"
description="Шаблон сообщения ссылается на вариант, который сотрудник не выбирал на этом пути."
resolution="Проверьте, что в дереве действительно есть узел с таким DataKey на пути к этому сообщению, и уберите из шаблона лишние плейсхолдеры."
/>
<ErrorEntry
title="Система не даёт сохранить узел — «ключ уже используется»"
description="В этой же категории уже есть узел с таким же техническим ключом."
resolution="Измените название узла (ключ сгенерируется заново) или вручную поправьте поле «Ключ» на уникальное значение."
/>
<ErrorEntry
title="Не получается переместить узел"
description="Система не разрешает сделать узел «родителем самого себя» — например, перетащить ветку внутрь её же собственного потомка."
resolution="Выберите другого родителя, который не находится ниже перемещаемого узла по дереву."
/>
<ErrorEntry
title="Сотрудник дошёл до конца, а кнопки «Отправить» нет"
description="Скорее всего, эта ветка дерева не заканчивается узлом «Текстовый ввод»."
resolution="Найдите последнюю кнопку в этой ветке и добавьте к ней дочерний узел типа «Текстовый ввод»."
/>
</Stack>
<Divider mt="xl" />
<Text size="sm" c="dimmed" ta="center">
Остались вопросы — обратитесь к администратору системы согласований.
</Text>
</Stack>
</Box>
</Box>
)
}
// ================================================================
// Вспомогательные компоненты
// ================================================================
function DocSection({ id, title, level = 1 }: { id: string; title: string; level?: number }) {
return (
<Box id={id} pt={8}>
{level === 1 ? (
<Title order={2}>{title}</Title>
) : (
<Title order={3} c="dimmed">{title}</Title>
)}
</Box>
)
}
function CodeBlock({ title, code }: { title: string; code: string }) {
return (
<Paper withBorder mt="md">
<Group justify="space-between" px="sm" py={6} style={{ borderBottom: '1px solid var(--mantine-color-gray-3)' }}>
<Text size="xs" fw={600} c="dimmed" tt="uppercase" lts={0.5}>{title}</Text>
<CopyButton value={code}>
{({ copied, copy }) => (
<Tooltip label={copied ? 'Скопировано' : 'Копировать'}>
<ActionIcon
size="xs"
variant="subtle"
color={copied ? 'teal' : 'gray'}
onClick={copy}
>
{copied ? <IconCheck size={14} /> : <IconCopy size={14} />}
</ActionIcon>
</Tooltip>
)}
</CopyButton>
</Group>
<Box p="sm">
<Code block style={{ fontSize: 12, whiteSpace: 'pre-wrap', lineHeight: 1.5 }}>
{code}
</Code>
</Box>
</Paper>
)
}
function Callout({ title, children, mt = 'md' }: { title: string; children: React.ReactNode; mt?: string }) {
return (
<Alert
variant="light"
color="blue"
icon={<IconBulb size={16} />}
title={title}
mt={mt}
styles={{
title: { fontSize: 13, fontWeight: 600 },
message: { fontSize: 13 },
}}
>
{children}
</Alert>
)
}
function TipEntry({ title, text }: { title: string; text: string }) {
return (
<Group gap="md" align="flex-start" wrap="nowrap">
<ThemeIcon variant="light" color="teal" size={28} radius="xl" style={{ flexShrink: 0 }}>
<IconBulb size={16} />
</ThemeIcon>
<Box>
<Text size="sm" fw={600}>{title}</Text>
<Text size="sm" c="dimmed">{text}</Text>
</Box>
</Group>
)
}
function ErrorEntry({ title, description, resolution }: { title: string; description: string; resolution: string }) {
return (
<Paper withBorder p="sm">
<Group gap="xs" mb={4}>
<ThemeIcon variant="light" color="orange" size={22} radius="xl">
<IconAlertTriangle size={13} />
</ThemeIcon>
<Text size="sm" fw={600}>{title}</Text>
</Group>
<Text size="sm" c="dimmed">{description}</Text>
<Text size="sm" mt={4}>
<Text span fw={600}>Что делать: </Text>
<Text span c="dimmed">{resolution}</Text>
</Text>
</Paper>
)
}
-----END src/pages/flowNodes/FlowTreeGuidePage.tsx-----
File: src/pages/flowNodes/FlowTreePage.tsx
Lines: 210
-----BEGIN src/pages/flowNodes/FlowTreePage.tsx-----
import { useState, useMemo } from 'react'
import {
Paper,
Group,
Button,
Text,
Select,
Loader,
Center,
Stack,
Badge,
Alert,
Tooltip,
} from '@mantine/core'
import { IconPlus, IconInfoCircle, IconBook, IconFolderPlus, IconRefresh } from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { useCategories } from '@/features/categories/hooks/useCategories'
import {
useFlowNodesTree,
useDeleteFlowNode,
useDuplicateFlowNode,
useReloadBot,
} from '@/features/flowNodes/hooks/useFlowNodes'
import { findParent } from '@/features/flowNodes/utils/treeWalk'
import type { ApprovalFlowNode, ApprovalTopicCategory } from '@/types/api'
import { useNavigate } from 'react-router-dom'
import CategoryCreateModal from "@/pages/flowNodes/components/CategoryCreateModal.tsx";
import FlowNodeEditModal from "@/pages/flowNodes/components/FlowNodeEditModal.tsx";
import SortableFlowTree from "@/pages/flowNodes/components/SortableFlowTree.tsx";
import TreeHealthPanel from "@/pages/flowNodes/components/TreeHealthPanel.tsx";
export default function FlowTreePage() {
const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null)
const [categoryModalOpened, setCategoryModalOpened] = useState(false)
const [editModal, setEditModal] = useState<{
opened: boolean
parentNode: ApprovalFlowNode | null
editNode: ApprovalFlowNode | null
}>({ opened: false, parentNode: null, editNode: null })
const { data: categoriesData } = useCategories({ limit: 1000, is_active: true })
const categories = categoriesData?.data || []
const { data: treeData, isLoading: treeLoading } = useFlowNodesTree(selectedCategoryId)
const tree = treeData?.data || []
const deleteFlowNode = useDeleteFlowNode()
const duplicateFlowNode = useDuplicateFlowNode()
const reloadBot = useReloadBot()
const navigate = useNavigate()
const selectedCategory = useMemo<ApprovalTopicCategory | null>(
() => categories.find((c) => c.id === selectedCategoryId) || null,
[categories, selectedCategoryId]
)
const categoryOptions = categories.map((c) => ({ value: String(c.id), label: `${c.name} (${c.code})` }))
const countNodes = (nodes: ApprovalFlowNode[]): number => {
let count = nodes.length
for (const n of nodes) if (n.children) count += countNodes(n.children)
return count
}
const totalNodes = countNodes(tree)
const handleEdit = (node: ApprovalFlowNode) => {
const parent = findParent(tree, node.id!)
setEditModal({ opened: true, parentNode: parent, editNode: node })
}
const handleAddChild = (parent: ApprovalFlowNode) => {
setEditModal({ opened: true, parentNode: parent, editNode: null })
}
const handleAddRoot = () => {
setEditModal({ opened: true, parentNode: null, editNode: null })
}
const handleDelete = (node: ApprovalFlowNode) => {
modals.openConfirmModal({
title: 'Удалить этот шаг?',
children: (
<Text size="sm">
Удалить шаг <b>{node.label}</b>? Все шаги, которые идут после него, тоже удалятся.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteFlowNode.mutate(node.id!),
})
}
const handleDuplicate = (node: ApprovalFlowNode) => duplicateFlowNode.mutate(node.id!)
return (
<Stack gap="md">
<Group justify="space-between">
<Text size="xl" fw={700}>
Конструктор тем
</Text>
<Group>
{selectedCategory && <Badge size="lg" variant="light">{totalNodes} шагов</Badge>}
<Tooltip label="Заставить бота немедленно перечитать разделы/деревья/темы из базы, не дожидаясь автоматической проверки">
<Button
variant="light"
color="orange"
leftSection={<IconRefresh size={16} />}
onClick={() => reloadBot.mutate()}
loading={reloadBot.isPending}
>
Обновить бота
</Button>
</Tooltip>
<Button variant="light" leftSection={<IconBook size={16} />} onClick={() => navigate('/guide/flow-trees')}>
Руководство
</Button>
</Group>
</Group>
<Paper withBorder p="md">
<Group align="end" gap="sm">
<Select
label="Раздел заявок"
placeholder="Выберите раздел, дерево которого будете настраивать"
data={categoryOptions}
value={selectedCategoryId ? String(selectedCategoryId) : null}
onChange={(v) => setSelectedCategoryId(v ? Number(v) : null)}
searchable
style={{ flex: 1 }}
/>
<Tooltip label="Завести новый раздел заявок, не выходя отсюда">
<Button
variant="default"
leftSection={<IconFolderPlus size={16} />}
onClick={() => setCategoryModalOpened(true)}
>
Новый раздел
</Button>
</Tooltip>
</Group>
</Paper>
{selectedCategoryId && (
<Paper withBorder p="md">
<Stack gap="md">
<Group justify="space-between">
<Group gap="xs">
{treeLoading && <Loader size="xs" />}
</Group>
<Button leftSection={<IconPlus size={16} />} onClick={handleAddRoot} disabled={tree.length > 0}>
Добавить первый вопрос
</Button>
</Group>
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
<Text size="sm">
Перетаскивайте шаги за значок ⠿ слева, чтобы менять порядок и вложенность — тяните
влево/вправо во время перетаскивания, чтобы изменить уровень. Первый шаг дерева
(с пометкой «начало дерева») не перетаскивается.
</Text>
</Alert>
{treeLoading ? (
<Center p={40}>
<Loader />
</Center>
) : tree.length === 0 ? (
<Center p={40}>
<Stack gap="sm" align="center">
<Text c="dimmed">В этом разделе пока нет вопросов</Text>
<Button leftSection={<IconPlus size={16} />} onClick={handleAddRoot}>
Добавить первый вопрос
</Button>
</Stack>
</Center>
) : (
<SortableFlowTree
tree={tree}
onEdit={handleEdit}
onAddChild={handleAddChild}
onDelete={handleDelete}
onDuplicate={handleDuplicate}
/>
)}
</Stack>
</Paper>
)}
{selectedCategoryId && tree.length > 0 && <TreeHealthPanel categoryId={selectedCategoryId} tree={tree} />}
{selectedCategoryId && (
<FlowNodeEditModal
categoryId={selectedCategoryId}
tree={tree}
parentNode={editModal.parentNode}
editNode={editModal.editNode}
opened={editModal.opened}
onClose={() => setEditModal({ opened: false, parentNode: null, editNode: null })}
/>
)}
<CategoryCreateModal
opened={categoryModalOpened}
onClose={() => setCategoryModalOpened(false)}
onCreated={(newId) => setSelectedCategoryId(newId)}
/>
</Stack>
)
}
-----END src/pages/flowNodes/FlowTreePage.tsx-----
File: src/pages/flowNodes/components/CategoryCreateModal.tsx
Lines: 120
-----BEGIN src/pages/flowNodes/components/CategoryCreateModal.tsx-----
import { useEffect } from 'react'
import { Modal, Stack, TextInput, Textarea, Group, Button, Text, Alert } from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconInfoCircle } from '@tabler/icons-react'
import { useCreateCategory } from '@/features/categories/hooks/useCategories'
import type { CreateCategoryRequest } from '@/api/categories'
interface CategoryCreateModalProps {
opened: boolean
onClose: () => void
onCreated: (categoryId: number) => void
}
const translitMap: Record<string, string> = {
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'yo', ж: 'zh', з: 'z', и: 'i', й: 'y',
к: 'k', л: 'l', м: 'm', н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f',
х: 'h', ц: 'ts', ч: 'ch', ш: 'sh', щ: 'sch', ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
}
function slugify(text: string): string {
return text
.toLowerCase()
.split('')
.map((ch) => translitMap[ch] ?? ch)
.join('')
.replace(/[\s-]+/g, '_')
.replace(/[^a-z0-9_]/g, '')
.replace(/_+/g, '_')
.replace(/^_+|_+$/g, '')
// Код раздела попадает в Telegram callback_data КАЖДОЙ кнопки внутри
// этой категории (формат "appr:{код_раздела}:{ключ_шага}", лимит
// Telegram — 64 байта на всю строку) — держим его коротким, иначе
// он съедает бюджет, который нужен для ключей узлов вглубь дерева.
.substring(0, 20)
}
// Создание новой категории (раздела заявок) прямо из конструктора дерева —
// требование "полной автономности": админ не должен переходить в другой
// раздел, чтобы завести новый вид заявки.
export default function CategoryCreateModal({ opened, onClose, onCreated }: CategoryCreateModalProps) {
const createCategory = useCreateCategory()
const form = useForm({
initialValues: { name: '', code: '', description: '' },
validate: {
name: (v) => (!v || v.length < 2 ? 'Введите название раздела' : null),
code: (v) => (!v || v.length < 2 ? 'Технический код должен быть заполнен' : null),
},
})
useEffect(() => {
if (opened) form.reset()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [opened])
useEffect(() => {
form.setFieldValue('code', slugify(form.values.name))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [form.values.name])
const handleSubmit = async (values: typeof form.values) => {
const payload: CreateCategoryRequest = {
name: values.name,
code: values.code,
description: values.description || undefined,
is_active: true,
}
const result = await createCategory.mutateAsync(payload)
// categoriesApi.create возвращает ApprovalTopicCategory без обёртки
// (apiClient.post<ApprovalTopicCategory>), axios кладёт его в response.data.
const newId = result?.data?.id
if (newId) onCreated(newId)
onClose()
}
return (
<Modal opened={opened} onClose={onClose} title={<Text fw={700}>Новый раздел заявок</Text>}>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
<Text size="xs">
Раздел — это то, что сотрудник увидит в главном меню бота (например, «Отпуска» или
«Возвраты»). Внутри одного раздела вы потом соберёте дерево вопросов.
</Text>
</Alert>
<TextInput
label="Название раздела"
placeholder="Например: Возвраты товара"
description="То, что увидит сотрудник в списке заявок"
required
{...form.getInputProps('name')}
/>
<TextInput
label="Технический код"
description="Заполняется само из названия. Трогать не нужно."
disabled
{...form.getInputProps('code')}
/>
<Textarea
label="Описание (необязательно)"
placeholder="Короткая заметка для себя, сотрудники её не видят"
minRows={2}
{...form.getInputProps('description')}
/>
<Group justify="flex-end" mt="sm">
<Button variant="default" onClick={onClose}>
Отмена
</Button>
<Button type="submit" loading={createCategory.isPending}>
Создать раздел
</Button>
</Group>
</Stack>
</form>
</Modal>
)
}
-----END src/pages/flowNodes/components/CategoryCreateModal.tsx-----
File: src/pages/flowNodes/components/DataFlowExplainer.tsx
Lines: 462
-----BEGIN src/pages/flowNodes/components/DataFlowExplainer.tsx-----
import {
Paper,
Stack,
Text,
Code,
Box,
Group,
Badge,
Alert,
Divider,
Table,
ThemeIcon,
Collapse,
ActionIcon,
} from '@mantine/core'
import { useState } from 'react'
import {
IconArrowRight,
IconDatabase,
IconCode,
IconMessage,
IconAlertTriangle,
IconCheck,
IconChevronDown,
IconChevronRight, IconBulb,
} from '@tabler/icons-react'
interface DataFlowExplainerProps {
dataKey?: string
dataValue?: string
label?: string
nodeType: 'button' | 'input' | 'multiselect'
}
export default function DataFlowExplainer({
dataKey,
dataValue,
label,
nodeType,
}: DataFlowExplainerProps) {
const [showDetails, setShowDetails] = useState(false)
// Примеры из реальных тем
const examples = [
{
label: 'Крым',
dataKey: 'region',
dataValue: 'crimea',
description: 'Выбор региона',
category: 'region',
},
{
label: 'Ф1',
dataKey: 'branch',
dataValue: 'f1',
description: 'Выбор филиала',
category: 'branch',
},
{
label: 'За свой счёт',
dataKey: 'payment_type',
dataValue: 'own_expense',
description: 'Тип оплаты',
category: 'payment',
},
{
label: 'ТМЦ',
dataKey: 'expense_type',
dataValue: 'tmc',
description: 'Тип расхода',
category: 'expense',
},
{
label: 'На один день',
dataKey: 'duration_type',
dataValue: 'single_day',
description: 'Длительность',
category: 'duration',
},
]
// Определяем, есть ли конфликт с существующими ключами
const isDuplicateKey = examples.some(
(e) => e.dataKey === dataKey && e.dataValue === dataValue
)
return (
<Paper withBorder p="md" bg="blue.0">
<Stack gap="md">
{/* Заголовок */}
<Group justify="space-between">
<Group gap="xs">
<ThemeIcon color="blue" variant="light" size="lg">
<IconBulb size={20} />
</ThemeIcon>
<div>
<Text fw={600} size="sm">
Что такое DataKey и DataValue?
</Text>
<Text size="xs" c="dimmed">
Краткое объяснение — нажми, чтобы узнать больше
</Text>
</div>
</Group>
<ActionIcon
variant="subtle"
onClick={() => setShowDetails(!showDetails)}
>
{showDetails ? (
<IconChevronDown size={20} />
) : (
<IconChevronRight size={20} />
)}
</ActionIcon>
</Group>
{/* Краткое объяснение (всегда видно) */}
<Box>
<Text size="sm" mb="xs">
<b>DataKey</b> и <b>DataValue</b> — это пара "ключ-значение", которая
сохраняется в память пользователя, когда он нажимает на этот узел.
</Text>
<Text size="sm">
Позже эти значения используются для:
</Text>
<Group gap="xs" mt="xs">
<Badge color="green" variant="light" leftSection={<IconCode size={12} />}>
Формирования кода темы
</Badge>
<Badge color="violet" variant="light" leftSection={<IconMessage size={12} />}>
Сообщения согласующему
</Badge>
<Badge color="orange" variant="light" leftSection={<IconDatabase size={12} />}>
Сохранения в заявке
</Badge>
</Group>
</Box>
{/* Интерактивный превью */}
{dataKey && dataValue && (
<Paper withBorder p="sm" bg="white">
<Text size="xs" fw={600} c="dimmed" mb="xs">
📊 Что произойдёт, когда пользователь нажмёт "{label || 'этот узел'}":
</Text>
{/* Поток данных */}
<Stack gap="xs">
{/* Шаг 1: Нажатие */}
<Group gap="xs" wrap="nowrap">
<ThemeIcon size="sm" color="blue" variant="light">
<Text size="xs" fw={700}>1</Text>
</ThemeIcon>
<Text size="xs" style={{ flex: 1 }}>
Пользователь нажимает <b>"{label || '...'}"</b>
</Text>
</Group>
<Box ml={20}>
<IconArrowRight size={14} style={{ color: 'gray' }} />
</Box>
{/* Шаг 2: Сохранение */}
<Group gap="xs" wrap="nowrap">
<ThemeIcon size="sm" color="green" variant="light">
<Text size="xs" fw={700}>2</Text>
</ThemeIcon>
<Text size="xs" style={{ flex: 1 }}>
В память сохраняется:{' '}
<Code>{dataKey} = "{dataValue}"</Code>
</Text>
</Group>
<Box ml={20}>
<IconArrowRight size={14} style={{ color: 'gray' }} />
</Box>
{/* Шаг 3: Автоматический label */}
<Group gap="xs" wrap="nowrap">
<ThemeIcon size="sm" color="cyan" variant="light">
<Text size="xs" fw={700}>3</Text>
</ThemeIcon>
<Text size="xs" style={{ flex: 1 }}>
Автоматически добавляется:{' '}
<Code>{dataKey}_label = "{label || '...'}"</Code>
</Text>
</Group>
<Box ml={20}>
<IconArrowRight size={14} style={{ color: 'gray' }} />
</Box>
{/* Шаг 4: Использование */}
<Group gap="xs" wrap="nowrap">
<ThemeIcon size="sm" color="violet" variant="light">
<Text size="xs" fw={700}>4</Text>
</ThemeIcon>
<Text size="xs" style={{ flex: 1 }}>
Эти значения можно использовать в шаблонах темы:
</Text>
</Group>
<Box ml={36}>
<Code block style={{ fontSize: 11 }}>
{`В message_template:
"{{.${dataKey}}}" → "${dataValue}"
"{{.${dataKey}_label}}" → "${label || '...'}"
В code_template:
"{{.${dataKey}}}" → "${dataValue}"`}
</Code>
</Box>
</Stack>
</Paper>
)}
{/* Развёрнутое объяснение */}
<Collapse expanded={showDetails}>
<Stack gap="md" mt="md">
<Divider label="Подробное объяснение" labelPosition="center" />
{/* Зачем это нужно */}
<Box>
<Text size="sm" fw={600} mb="xs">
🎯 Зачем это нужно?
</Text>
<Text size="xs" mb="xs">
Представьте, что пользователь создаёт заявку "Отпуск на один день за свой счёт".
Система должна понять, <b>какую именно тему</b> использовать и <b>как отформатировать
сообщение</b> для согласующего. Для этого она собирает "память" пользователя —
map <Code>collected</Code>, куда по пути попадают все DataKey/DataValue.
</Text>
</Box>
{/* Реальный пример */}
<Box>
<Text size="sm" fw={600} mb="xs">
📖 Реальный пример (тема "Отпуск")
</Text>
<Text size="xs" mb="xs">
Пользователь проходит путь: <b>Отпуск → На один день → За свой счёт → Ввод текста</b>
</Text>
<Table withTableBorder withColumnBorders>
<Table.Thead>
<Table.Tr>
<Table.Th>Шаг</Table.Th>
<Table.Th>Узел (Label)</Table.Th>
<Table.Th>DataKey</Table.Th>
<Table.Th>DataValue</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
<Table.Tr>
<Table.Td>1</Table.Td>
<Table.Td>Отпуск</Table.Td>
<Table.Td><Code>absence_type</Code></Table.Td>
<Table.Td><Code>vacation</Code></Table.Td>
</Table.Tr>
<Table.Tr>
<Table.Td>2</Table.Td>
<Table.Td>На один день</Table.Td>
<Table.Td><Code>duration_type</Code></Table.Td>
<Table.Td><Code>single_day</Code></Table.Td>
</Table.Tr>
<Table.Tr>
<Table.Td>3</Table.Td>
<Table.Td>За свой счёт</Table.Td>
<Table.Td><Code>payment_type</Code></Table.Td>
<Table.Td><Code>own_expense</Code></Table.Td>
</Table.Tr>
<Table.Tr>
<Table.Td>4</Table.Td>
<Table.Td>Ввод текста</Table.Td>
<Table.Td><Code>content</Code></Table.Td>
<Table.Td><i>(текст пользователя)</i></Table.Td>
</Table.Tr>
</Table.Tbody>
</Table>
<Text size="xs" mt="xs" fw={600}>
Итоговый collected:
</Text>
<Code block style={{ fontSize: 11 }}>
{`{
"absence_type": "vacation",
"absence_type_label": "Отпуск", ← автоматически из Label
"duration_type": "single_day",
"duration_type_label": "На один день", ← автоматически
"payment_type": "own_expense",
"payment_type_label": "За свой счёт", ← автоматически
"content": "22.02.2026"
}`}
</Code>
</Box>
{/* Как это используется */}
<Box>
<Text size="sm" fw={600} mb="xs">
🔧 Как это используется?
</Text>
<Text size="xs" fw={600} mt="xs" mb={4}>
1. Формирование кода темы (code_template):
</Text>
<Code block style={{ fontSize: 11 }}>
{`Шаблон: vacation_{{.duration_type}}_full_day_{{.payment_type}}
Результат: vacation_single_day_full_day_own_expense
Этот код ищет в БД конкретную тему для заявки.`}
</Code>
<Text size="xs" fw={600} mt="xs" mb={4}>
2. Сообщение согласующему (message_template):
</Text>
<Code block style={{ fontSize: 11 }}>
{`Шаблон:
📋 <b>Тип: Отпуск</b>
<b>{{.initiator_name}}</b>: прошу согласовать отпуск
{{.content}}
<i>{{.payment_type_label}}</i>
Результат:
📋 <b>Тип: Отпуск</b>
<b>Иванов И.И.</b>: прошу согласовать отпуск
22.02.2026
<i>За свой счёт</i>`}
</Code>
</Box>
{/* Правила */}
<Alert icon={<IconAlertTriangle size={16} />} color="yellow" variant="light">
<Text size="xs" fw={600} mb="xs">
⚠️ Правила, которые нужно соблюдать:
</Text>
<Stack gap={4}>
<Text size="xs">
<b>1. DataKey должен быть осмысленным.</b> Используйте понятные имена:{' '}
<Code>region</Code>, <Code>branch</Code>, <Code>payment_type</Code>.
Не используйте <Code>x</Code>, <Code>val</Code>, <Code>data</Code>.
</Text>
<Text size="xs">
<b>2. DataValue должен быть уникальным в рамках одного DataKey.</b>{' '}
Если у вас есть два узла с <Code>region=crimea</Code> и{' '}
<Code>region=krasnodar</Code> — это правильно. Но если оба будут{' '}
<Code>region=crimea</Code> — система не сможет их различить.
</Text>
<Text size="xs">
<b>3. Используйте snake_case.</b> Только lowercase, цифры и подчёркивания:{' '}
<Code>own_expense</Code> ✅, <Code>OwnExpense</Code> ❌,{' '}
<Code>own-expense</Code> ❌.
</Text>
<Text size="xs">
<b>4. Один DataKey на одном уровне дерева.</b> Если на одном уровне
несколько кнопок — у всех должен быть одинаковый DataKey, но разные DataValue.
Например, три кнопки "Крым/Краснодар/Беларусь" — все с <Code>region</Code>,
но с разными значениями.
</Text>
<Text size="xs">
<b>5. Label — это то, что видит пользователь.</b> DataValue — техническое
значение. Они могут отличаться: Label="За свой счёт", DataValue="own_expense".
</Text>
</Stack>
</Alert>
{/* Типичные ошибки */}
<Box>
<Text size="sm" fw={600} mb="xs">
❌ Типичные ошибки:
</Text>
<Stack gap="xs">
<Paper withBorder p="xs" bg="red.0">
<Text size="xs">
<b>Ошибка:</b> Два узла на одном уровне с одинаковыми DataKey и DataValue
</Text>
<Text size="xs" c="dimmed">
Последствие: система не сможет различить, какую ветку выбрал пользователь
</Text>
</Paper>
<Paper withBorder p="xs" bg="red.0">
<Text size="xs">
<b>Ошибка:</b> Разные DataKey на одном уровне (например, у одной кнопки{' '}
<Code>region</Code>, у другой <Code>area</Code>)
</Text>
<Text size="xs" c="dimmed">
Последствие: в collected появятся два разных ключа, что сломает шаблоны
</Text>
</Paper>
<Paper withBorder p="xs" bg="red.0">
<Text size="xs">
<b>Ошибка:</b> DataValue с пробелами или заглавными буквами
</Text>
<Text size="xs" c="dimmed">
Последствие: код темы будет некорректным, заявка не создастся
</Text>
</Paper>
<Paper withBorder p="xs" bg="red.0">
<Text size="xs">
<b>Ошибка:</b> Пустой DataKey или DataValue у кнопки
</Text>
<Text size="xs" c="dimmed">
Последствие: данные не сохранятся, шаблон не сможет их использовать
</Text>
</Paper>
</Stack>
</Box>
{/* Правильные примеры */}
<Box>
<Text size="sm" fw={600} mb="xs">
✅ Правильные примеры из реальных тем:
</Text>
<Table withTableBorder withColumnBorders>
<Table.Thead>
<Table.Tr>
<Table.Th>Label</Table.Th>
<Table.Th>DataKey</Table.Th>
<Table.Th>DataValue</Table.Th>
<Table.Th>Комментарий</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{examples.map((ex, i) => (
<Table.Tr key={i}>
<Table.Td>{ex.label}</Table.Td>
<Table.Td><Code>{ex.dataKey}</Code></Table.Td>
<Table.Td><Code>{ex.dataValue}</Code></Table.Td>
<Table.Td>{ex.description}</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</Box>
{/* Подсказка по текущему узлу */}
{dataKey && dataValue && label && (
<Alert
icon={<IconCheck size={16} />}
color={isDuplicateKey ? 'blue' : 'green'}
variant="light"
>
<Text size="xs">
{isDuplicateKey ? (
<>
💡 Ваш узел похож на существующий пример. Убедитесь, что это именно то,
что вам нужно.
</>
) : (
<>
✅ Отлично! Ваш узел <b>"{label}"</b> с{' '}
<Code>{dataKey}="{dataValue}"</Code> выглядит корректно.
В шаблонах можно использовать <Code>{`{{.${dataKey}}}`}</Code> и{' '}
<Code>{`{{.${dataKey}_label}}`}</Code>.
</>
)}
</Text>
</Alert>
)}
</Stack>
</Collapse>
</Stack>
</Paper>
)
}
-----END src/pages/flowNodes/components/DataFlowExplainer.tsx-----
File: src/pages/flowNodes/components/FlowNodeEditModal.tsx
Lines: 833
-----BEGIN src/pages/flowNodes/components/FlowNodeEditModal.tsx-----
import { useEffect, useMemo, useState } from 'react'
import {
Modal,
Stack,
TextInput,
Textarea,
Group,
Button,
Text,
Badge,
Paper,
Select,
Code,
Alert,
Box,
Collapse,
ActionIcon,
Divider,
Loader,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
IconAlertCircle,
IconAlertTriangle,
IconInfoCircle,
IconChevronDown,
IconChevronRight,
IconWand,
IconEye,
IconCircleCheck,
IconCirclePlus,
IconPlus,
} from '@tabler/icons-react'
import { useCreateFlowNode, useUpdateFlowNode, usePreviewFlow } from '@/features/flowNodes/hooks/useFlowNodes'
import { useCreateTopic } from '@/features/topics/hooks/useTopics'
import { useCategory } from '@/features/categories/hooks/useCategories'
import type { CreateTopicRequest } from '@/api/topics'
import {
collectFromPath,
collectLeafPaths,
generateDraftMessageTemplate,
getPathToNode,
pathLabel,
findMissingKeysInCodeTemplate,
buildMissingKeySegment,
} from '@/features/flowNodes/utils/treeWalk'
import type { ApprovalFlowNode } from '@/types/api'
interface FlowNodeEditModalProps {
categoryId: number
tree: ApprovalFlowNode[]
parentNode: ApprovalFlowNode | null
editNode: ApprovalFlowNode | null
opened: boolean
onClose: () => void
}
const NODE_TYPE_OPTIONS = [
{ value: 'button', label: '🔘 Кнопка — сотрудник нажимает и переходит к следующему вопросу' },
{ value: 'input', label: '📝 Текстовый ввод — сотрудник пишет заявку своими словами (конец пути)' },
{ value: 'multiselect', label: '☑️ Можно выбрать несколько вариантов сразу' },
]
const TRANSLIT_MAP: Record<string, string> = {
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'yo', ж: 'zh', з: 'z', и: 'i', й: 'y',
к: 'k', л: 'l', м: 'm', н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f',
х: 'h', ц: 'ts', ч: 'ch', ш: 'sh', щ: 'sch', ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
}
function transliterate(text: string): string {
return text.toLowerCase().split('').map((ch) => TRANSLIT_MAP[ch] ?? ch).join('')
}
function slugify(label: string): string {
if (!label?.trim()) return ''
return transliterate(label.trim())
.replace(/[\s-]+/g, '_')
.replace(/[^a-z0-9_]/g, '')
.replace(/_+/g, '_')
.replace(/^_+|_+$/g, '')
.substring(0, 50)
}
// Ключ узла попадает в Telegram callback_data ("appr:{код_раздела}:{ключ}"),
// а у него жёсткий лимит 64 байта на всю строку. Поэтому ключ короче и НЕ
// собирается из цепочки всех родителей (иначе длина растёт с каждым уровнем
// вложенности и легко перешагивает лимит на 4-5 шаге — именно так ломался
// ваш тест: "категория_кнопка1_вложенная1" вышло за 64 байта, Telegram
// отклонил сообщение целиком, а ошибка нигде не показывалась).
const KEY_MAX_LEN = 20
function shortSlug(label: string): string {
return slugify(label).substring(0, KEY_MAX_LEN)
}
// Уникальный короткий ключ в пределах категории: если базовый слаг уже
// занят (например, два узла с одинаковым названием "Вложенная 1" на разных
// ветках — это нормально и допустимо), добавляем числовой суффикс.
function uniqueShortKey(label: string, existingKeys: string[], skipKey?: string): string {
const base = shortSlug(label) || 'shag'
if (!existingKeys.includes(base) || base === skipKey) return base
let n = 2
while (existingKeys.includes(`${base}_${n}`) && `${base}_${n}` !== skipKey) {
n++
}
return `${base}_${n}`
}
function collectAllKeys(nodes: ApprovalFlowNode[]): string[] {
const keys: string[] = []
for (const node of nodes) {
if (node.key) keys.push(node.key)
if (node.children) keys.push(...collectAllKeys(node.children))
}
return keys
}
export default function FlowNodeEditModal({
categoryId,
tree,
parentNode,
editNode,
opened,
onClose,
}: FlowNodeEditModalProps) {
const createFlowNode = useCreateFlowNode()
const updateFlowNode = useUpdateFlowNode()
const createTopic = useCreateTopic()
const previewFlow = usePreviewFlow(categoryId)
const { data: category } = useCategory(categoryId)
const [showAdvanced, setShowAdvanced] = useState(false)
const [showTemplates, setShowTemplates] = useState(false)
const [previewLeafKey, setPreviewLeafKey] = useState<string | null>(null)
const isEditMode = editNode !== null
// Корень дерева категории — узел без родителя. Только на нём имеют
// смысл шаблоны сообщения/кода: DynamicTopic на бэкенде читает их
// ИСКЛЮЧИТЕЛЬНО с узла с parent_id = null (см. approvalflow.NewDynamicTopic).
const isRootNode = parentNode === null
const form = useForm({
initialValues: {
key: '',
label: '',
nodeType: 'button' as 'button' | 'input' | 'multiselect',
data_key: '',
data_value: '',
input_key: 'content',
input_hint: '',
multi_select_key: '',
multi_select_value: '',
topic_code: '',
message_template: '',
code_template: '',
auto_generate_key: true,
},
validate: {
key: (v) => {
if (!v || v.length < 2) return 'Слишком короткий технический ключ'
if (!/^[a-z0-9_]+$/.test(v)) return 'Только латинские буквы, цифры и подчёркивания'
if (isRootNode && category?.code && v !== category.code) {
return 'Подождите загрузку раздела — ключ первого шага подставится сам'
}
// "appr:" + код раздела + ":" + ключ уходит в Telegram callback_data,
// у которого жёсткий лимит 64 байта. 60 вместо 64 — небольшой запас.
const categoryCodeLen = category?.code?.length || 0
const callbackLen = 'appr:'.length + categoryCodeLen + 1 + v.length
if (callbackLen > 60) {
return `Ключ слишком длинный для Telegram (осталось ${60 - 'appr:'.length - categoryCodeLen - 1} символов) — сократите название`
}
const existingKeys = collectAllKeys(tree)
if (existingKeys.includes(v) && (!editNode || editNode.key !== v)) {
return 'Такой ключ уже есть в этой категории — измените название'
}
return null
},
label: (v, values) => {
// У узла "текстовый ввод" название нигде не показывается
// сотруднику — бот выводит InputHint, а не Label. Название
// тут чисто для вашего удобства в конструкторе, необязательно.
if (values.nodeType === 'input') return null
return !v || v.length < 1 ? 'Название обязательно' : null
},
data_key: (v, values) => {
// Раньше это была декоративная проверка, которая ничего не
// блокировала (только жёлтое предупреждение) — из-за этого
// можно было сохранить кнопку без "что запомнить", и тогда
// РАЗНЫЕ кнопки на бэкенде дают ОДИНАКОВЫЙ код темы (бот не
// видит разницы между ними). Теперь это жёсткая проверка.
if (values.nodeType === 'button' && !v) {
return 'Обязательно для кнопки — иначе бот не отличит эту кнопку от других, и разные пути могут привести к одной и той же теме'
}
return null
},
data_value: (v, values) => {
if (values.nodeType === 'button' && !v) {
return 'Обязательно для кнопки — у каждой кнопки должно быть своё значение'
}
return null
},
multi_select_key: (v, values) =>
values.nodeType === 'multiselect' && !v
? 'Обязательно для мультивыбора — иначе бот не запомнит выбранные варианты'
: null,
multi_select_value: (v, values) =>
values.nodeType === 'multiselect' && !v
? 'Обязательно для мультивыбора — у каждого варианта должно быть своё значение'
: null,
input_hint: (v, values) =>
values.nodeType === 'input' && (!v || v.length < 5) ? 'Подсказка должна быть не короче 5 символов' : null,
},
})
// Ближайшие "братья" (уже существующие соседние кнопки того же родителя) —
// используем, чтобы подсказать DataKey автоматически: у всех кнопок
// одного вопроса DataKey обязан совпадать.
const siblingDataKey = useMemo(() => {
const siblings = parentNode?.children || (parentNode === null ? [] : [])
const withKey = siblings.find((s) => s.data_key)
return withKey?.data_key || ''
}, [parentNode])
const siblingMultiKey = useMemo(() => {
const siblings = parentNode?.children || []
const withKey = siblings.find((s) => s.multi_select_key)
return withKey?.multi_select_key || ''
}, [parentNode])
// Автогенерация ключа из названия — КРОМЕ корневого узла: его ключ
// ОБЯЗАН совпадать с кодом категории. Причина: когда сотрудник нажимает
// кнопку раздела в главном меню бота, бот ищет самый первый узел дерева
// по nodeKey == код категории (см. HandleCallback в telegram_service) —
// у Topic просто нет отдельного способа узнать реальный ключ корня.
// Если ключ корня не совпадёт с кодом раздела — бот не найдёт начало
// дерева и покажет "node not found" в логах, а сотрудник не увидит
// следующий шаг после нажатия кнопки раздела.
useEffect(() => {
if (isRootNode) {
if (category?.code && form.values.key !== category.code) {
form.setFieldValue('key', category.code)
}
return
}
if (form.values.auto_generate_key) {
// Для текстового ввода название необязательно — если его нет,
// используем понятный технический суффикс вместо пустого ключа.
const baseLabel = form.values.label || (form.values.nodeType === 'input' ? 'Текст' : '')
if (baseLabel) {
const existingKeys = collectAllKeys(tree)
const key = uniqueShortKey(baseLabel, existingKeys, editNode?.key)
if (key !== form.values.key) {
form.setFieldValue('key', key)
}
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [form.values.label, form.values.nodeType, form.values.auto_generate_key, isRootNode, category?.code, tree, editNode])
// Автоподстановка DataKey/DataValue при смене типа/названия
useEffect(() => {
if (form.values.nodeType === 'button') {
if (!form.values.data_key) form.setFieldValue('data_key', siblingDataKey || '')
if (!form.values.data_value) form.setFieldValue('data_value', slugify(form.values.label))
} else if (form.values.nodeType === 'multiselect') {
if (!form.values.multi_select_key) form.setFieldValue('multi_select_key', siblingMultiKey || '')
if (!form.values.multi_select_value) form.setFieldValue('multi_select_value', slugify(form.values.label))
} else if (form.values.nodeType === 'input') {
if (!form.values.input_key) form.setFieldValue('input_key', 'content')
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [form.values.nodeType, form.values.label, siblingDataKey, siblingMultiKey])
// Заполнение формы при редактировании / сброс при создании
useEffect(() => {
if (editNode) {
let nodeType: 'button' | 'input' | 'multiselect' = 'button'
if (editNode.is_input) nodeType = 'input'
else if (editNode.is_multi_select) nodeType = 'multiselect'
form.setValues({
key: editNode.key || '',
label: editNode.label || '',
nodeType,
data_key: editNode.data_key || '',
data_value: editNode.data_value || '',
input_key: editNode.input_key || 'content',
input_hint: editNode.input_hint || '',
multi_select_key: editNode.multi_select_key || '',
multi_select_value: editNode.multi_select_value || '',
topic_code: editNode.topic_code || '',
message_template: editNode.message_template || '',
code_template: editNode.code_template || '',
auto_generate_key: false,
})
setShowTemplates(!!(editNode.message_template || editNode.code_template))
setShowAdvanced(!!editNode.topic_code)
} else {
form.reset()
const baseKey = parentNode?.key || ''
form.setValues({
key: baseKey ? `${baseKey}_new` : 'new_node',
label: '',
nodeType: 'button',
data_key: '',
data_value: '',
input_key: 'content',
input_hint: '',
multi_select_key: '',
multi_select_value: '',
topic_code: '',
message_template: '',
code_template: '',
auto_generate_key: true,
})
setShowTemplates(false)
setShowAdvanced(false)
}
previewFlow.reset()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editNode, parentNode, opened])
const handleSubmit = async (values: typeof form.values) => {
const payload = {
key: values.key,
// label в БД NOT NULL — если оставили пустым (разрешено только
// для текстового ввода), подставляем нейтральное значение.
label: values.label || (values.nodeType === 'input' ? 'Текст' : values.label),
data_key: values.data_key || null,
data_value: values.data_value || null,
is_input: values.nodeType === 'input',
input_key: values.nodeType === 'input' ? values.input_key : null,
input_hint: values.nodeType === 'input' ? values.input_hint : null,
is_multi_select: values.nodeType === 'multiselect',
multi_select_key: values.nodeType === 'multiselect' ? values.multi_select_key : null,
multi_select_value: values.nodeType === 'multiselect' ? values.multi_select_value : null,
topic_code: values.topic_code || null,
message_template: isRootNode ? values.message_template || null : null,
code_template: isRootNode ? values.code_template || null : null,
}
if (isEditMode && editNode?.id) {
await updateFlowNode.mutateAsync({ id: editNode.id, ...payload })
} else {
await createFlowNode.mutateAsync({
category_id: categoryId,
parent_id: parentNode?.id || null,
...payload,
})
}
onClose()
}
const isSubmitting = createFlowNode.isPending || updateFlowNode.isPending
const nodeType = form.values.nodeType
const warnings = useMemo(() => {
const warns: string[] = []
if (nodeType === 'button' && !form.values.data_key) {
warns.push('У кнопки нет «что запомнить» — без этого бот не поймёт, что выбрал сотрudnik. Заполните поля ниже.')
}
if (nodeType === 'multiselect' && !form.values.multi_select_key) {
warns.push('Не заполнено, что запоминать при мультивыборе.')
}
return warns
}, [nodeType, form.values.data_key, form.values.multi_select_key])
// ============================================================
// Черновик пути для предпросмотра (виртуальный узел = текущие
// значения формы, ещё не сохранённые)
// ============================================================
const pathToParent = useMemo(() => {
if (!parentNode?.id) return []
return getPathToNode(tree, parentNode.id)
}, [tree, parentNode])
const virtualNode: ApprovalFlowNode = {
...(editNode || {}),
data_key: form.values.data_key || undefined,
data_value: form.values.data_value || undefined,
multi_select_key: form.values.multi_select_key || undefined,
multi_select_value: form.values.multi_select_value || undefined,
is_input: nodeType === 'input',
} as ApprovalFlowNode
const currentPathCollected = useMemo(
() => collectFromPath([...pathToParent, virtualNode]),
// eslint-disable-next-line react-hooks/exhaustive-deps
[pathToParent, form.values.data_key, form.values.data_value, form.values.multi_select_key, form.values.multi_select_value, nodeType]
)
const handleCheckThisStep = () => {
previewFlow.mutate({ collected: currentPathCollected })
}
const handleCreateTopicFromPreview = async () => {
if (!previewFlow.data?.code) return
// Намеренно НЕ передаём message_template/code_template/is_tree_root на
// самой теме: боевой код (approvalflow.DynamicTopic) читает шаблоны
// только с корневого узла дерева, а не с ApprovalTopic — см. FlowNodeEditModal
// раздел "Сообщение согласующему" (isRootNode). Заполнение этих полей
// здесь ничего бы не включило и только запутало бы админа.
const payload: CreateTopicRequest = {
category_id: categoryId,
code: previewFlow.data.code,
name: form.values.label || previewFlow.data.code,
is_active: true,
}
await createTopic.mutateAsync(payload)
previewFlow.mutate({ collected: currentPathCollected })
}
// ============================================================
// Для корневого узла: список готовых веток дерева для предпросмотра
// ============================================================
const leafOptions = useMemo(() => {
if (!isRootNode) return []
return collectLeafPaths(tree).map((path) => ({
value: path.map((n) => n.id).join('-'),
label: pathLabel(path),
collected: collectFromPath(path),
}))
}, [isRootNode, tree])
// НОВОЕ: автообнаружение "в дереве есть данные, которых нет в шаблоне
// кода" — то, что раньше приходилось замечать самому и чинить руками
// (см. случай с filiale Ф1/Ф2, которые не попадали в код темы).
const missingCodeKeys = useMemo(() => {
if (!isRootNode || !editNode) return []
return findMissingKeysInCodeTemplate(editNode, form.values.code_template)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isRootNode, editNode, form.values.code_template])
const handleAddMissingKey = (key: string) => {
form.setFieldValue('code_template', (form.values.code_template || '') + buildMissingKeySegment(key))
}
const handleAddAllMissingKeys = () => {
const addition = missingCodeKeys.map(buildMissingKeySegment).join('')
form.setFieldValue('code_template', (form.values.code_template || '') + addition)
}
const handleGenerateDraft = () => {
if (!editNode && !parentNode) return
const rootForDraft = editNode || { label: form.values.label, children: [] }
form.setFieldValue('message_template', generateDraftMessageTemplate(rootForDraft as ApprovalFlowNode))
}
const handlePreviewLeaf = (leafKey: string | null) => {
setPreviewLeafKey(leafKey)
const option = leafOptions.find((o) => o.value === leafKey)
if (option) {
previewFlow.mutate({ collected: option.collected })
}
}
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>{isEditMode ? 'Изменить шаг' : 'Новый шаг'}</Text>
{parentNode && (
<Badge variant="light" color="gray">
после: {parentNode.label}
</Badge>
)}
</Group>
}
size="lg"
>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
{warnings.length > 0 && (
<Alert icon={<IconAlertCircle size={16} />} color="yellow" variant="light">
<Stack gap={4}>
{warnings.map((w, i) => (
<Text key={i} size="sm">
⚠️ {w}
</Text>
))}
</Stack>
</Alert>
)}
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm">
1. Тип шага
</Text>
<Select
data={NODE_TYPE_OPTIONS}
value={form.values.nodeType}
onChange={(v) => form.setFieldValue('nodeType', (v as any) || 'button')}
/>
</Paper>
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm">
{nodeType === 'input' ? '2. Название шага (для вас, необязательно)' : '2. Что увидит сотрудник'}
</Text>
<Stack gap="sm">
<TextInput
label="Название"
placeholder={nodeType === 'input' ? 'Текст' : 'Крым, ТМЦ, В счёт отпуска...'}
description={
nodeType === 'input'
? 'Сотрудник это не видит — бот показывает подсказку из следующего блока. Можно оставить пустым, тогда шаг просто назовётся «Текст»'
: 'Текст на кнопке (или заголовок вопроса для первого шага)'
}
required={nodeType !== 'input'}
{...form.getInputProps('label')}
/>
{isRootNode && (
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
<Text size="xs">
Это первый шаг дерева — по нему бот находит начало сценария, когда
сотрудник нажимает кнопку раздела в главном меню. Технический ключ этого
шага всегда равен коду раздела:{' '}
<Code>{category?.code || '…'}</Code> — менять его нельзя, это сделано
автоматически.
</Text>
</Alert>
)}
</Stack>
</Paper>
{(nodeType === 'button' || nodeType === 'multiselect') && (
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm">
3. Что запомнить при нажатии
</Text>
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light" mb="sm">
<Text size="xs">
Если у этого вопроса уже есть другие варианты ответа — поле «что запомнить» уже
подставлено само (оно должно быть одинаковым у всех кнопок одного вопроса).
Меняйте только «значение» — оно у каждой кнопки своё.
</Text>
<Text size="xs" mt={4}>
«Название» этой кнопки (из блока выше) — это то, что покажется согласующему
в сообщении, если в шаблоне используется <Code>{`{{.${form.values.data_key || 'ключ'}_label}}`}</Code>.
Переименуете кнопку — текст сообщения обновится сам, без правки шаблона.
</Text>
</Alert>
{nodeType === 'button' ? (
<Group gap="sm" align="end">
<TextInput
label="Что запомнить (например: регион)"
style={{ flex: 1 }}
{...form.getInputProps('data_key')}
/>
<TextInput
label="Значение этой кнопки (например: crimea)"
style={{ flex: 1 }}
{...form.getInputProps('data_value')}
/>
</Group>
) : (
<Group gap="sm" align="end">
<TextInput
label="Что запомнить (например: системы)"
style={{ flex: 1 }}
{...form.getInputProps('multi_select_key')}
/>
<TextInput
label="Значение этого варианта"
style={{ flex: 1 }}
{...form.getInputProps('multi_select_value')}
/>
</Group>
)}
</Paper>
)}
{nodeType === 'input' && (
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm">
3. Подсказка для сотрудника
</Text>
<Textarea
label="Пример того, что нужно написать"
placeholder="Опишите изменения: текущие данные → новые данные"
minRows={3}
required
{...form.getInputProps('input_hint')}
/>
</Paper>
)}
{/* Живой предпросмотр этого конкретного шага — только там, где уже
можно посчитать код (обычно на текстовом вводе, но доступно и раньше) */}
<Paper withBorder p="md" bg="gray.0">
<Group justify="space-between" mb="xs">
<Text size="sm" fw={600}>
Проверка: что получится на этом пути
</Text>
<Button
size="xs"
variant="light"
leftSection={<IconEye size={14} />}
onClick={handleCheckThisStep}
loading={previewFlow.isPending}
>
Проверить
</Button>
</Group>
{previewFlow.data && (
<Stack gap={6}>
{previewFlow.data.incomplete ? (
<Text size="xs" c="dimmed">
Пока не хватает выборов на предыдущих шагах, чтобы определить тему заявки —
это нормально, если вы ещё не дошли до конца ветки.
</Text>
) : (
<>
<Text size="xs">
Код темы: <Code>{previewFlow.data.code}</Code>
</Text>
{previewFlow.data.topic_exists ? (
<Group gap={4}>
<IconCircleCheck size={14} color="var(--mantine-color-teal-6)" />
<Text size="xs" c="teal">
Такая тема уже настроена в системе ({previewFlow.data.topic_name})
</Text>
</Group>
) : (
<Group gap="xs">
<Text size="xs" c="orange">
⚠️ Темы с таким кодом пока нет — без неё бот не сможет отправить
заявку согласующим.
</Text>
<Button
size="compact-xs"
leftSection={<IconCirclePlus size={12} />}
onClick={handleCreateTopicFromPreview}
loading={createTopic.isPending}
>
Создать тему
</Button>
</Group>
)}
<Divider my={4} />
<Text size="xs" fw={600}>
Так будет выглядеть сообщение согласующему:
</Text>
<Paper withBorder p={6} bg="white">
<Text size="xs" style={{ whiteSpace: 'pre-wrap' }}>
{previewFlow.data.message}
</Text>
</Paper>
</>
)}
</Stack>
)}
</Paper>
{/* Дополнительно: технический ключ + код проверки прав */}
<Paper withBorder p="md">
<Group
justify="space-between"
style={{ cursor: 'pointer' }}
onClick={() => setShowAdvanced(!showAdvanced)}
>
<Group gap="xs">
{showAdvanced ? <IconChevronDown size={16} /> : <IconChevronRight size={16} />}
<Text size="sm" fw={600}>
Дополнительно (обычно не нужно трогать)
</Text>
</Group>
</Group>
<Collapse expanded={showAdvanced}>
<Stack gap="sm" mt="sm">
<TextInput
label="Технический ключ"
description={
isRootNode
? 'Всегда равен коду раздела — не редактируется'
: 'Заполняется само из названия'
}
disabled={isRootNode || form.values.auto_generate_key}
{...form.getInputProps('key')}
/>
<TextInput
label="Кто видит эту кнопку (необязательно)"
placeholder="non_budget_f1"
description={
<Text size="xs">
Если заполнить — эту конкретную кнопку увидят только сотрудники, у
которых есть право на такую тему. Не влияет на то, в какую тему попадёт
заявка — код темы считается автоматически по всем ответам сотрудника.
</Text>
}
{...form.getInputProps('topic_code')}
/>
{nodeType === 'input' && (
<TextInput
label="Куда сохранить введённый текст"
description="Обычно content — меняйте, только если знаете зачем"
{...form.getInputProps('input_key')}
/>
)}
</Stack>
</Collapse>
</Paper>
{/* Шаблоны — ТОЛЬКО на корневом узле дерева */}
{isRootNode && (
<Paper withBorder p="md">
<Group
justify="space-between"
style={{ cursor: 'pointer' }}
onClick={() => setShowTemplates(!showTemplates)}
>
<Group gap="xs">
{showTemplates ? <IconChevronDown size={16} /> : <IconChevronRight size={16} />}
<Text size="sm" fw={600}>
Сообщение согласующему и код темы
</Text>
</Group>
</Group>
<Collapse expanded={showTemplates}>
<Stack gap="sm" mt="sm">
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
<Text size="xs">
Это ОДНО сообщение на всё дерево этого раздела, а не на одну ветку.
Чтобы текст отличался в зависимости от выбора сотрудника — используйте
условия (кнопка ниже сама расставит их за вас на основе первого вопроса
в дереве, дальше можно поправить руками).
</Text>
</Alert>
<Group justify="flex-end">
<Button
size="xs"
variant="light"
leftSection={<IconWand size={14} />}
onClick={handleGenerateDraft}
>
Сформировать черновик
</Button>
</Group>
<Textarea
label="Текст сообщения согласующему"
minRows={6}
styles={{ input: { fontFamily: 'monospace', fontSize: 12 } }}
{...form.getInputProps('message_template')}
/>
<Textarea
label="Код темы (обычно оставляйте пустым)"
description="Если не трогать — система сама соберёт код из всех выборов сотрудника"
minRows={2}
styles={{ input: { fontFamily: 'monospace', fontSize: 12 } }}
{...form.getInputProps('code_template')}
/>
{missingCodeKeys.length > 0 && (
<Alert icon={<IconAlertTriangle size={16} />} color="orange" variant="light">
<Stack gap={6}>
<Text size="xs">
В дереве есть шаги, запоминающие данные, которых нет в шаблоне
кода выше — темы для таких веток могут случайно совпасть с
другими (бот их не различит):
</Text>
<Group gap={6}>
{missingCodeKeys.map((key) => (
<Badge
key={key}
variant="light"
color="orange"
style={{ cursor: 'pointer' }}
rightSection={<IconPlus size={10} />}
onClick={() => handleAddMissingKey(key)}
>
{key}
</Badge>
))}
</Group>
{missingCodeKeys.length > 1 && (
<Button
size="compact-xs"
variant="light"
color="orange"
onClick={handleAddAllMissingKeys}
>
Добавить все в шаблон
</Button>
)}
</Stack>
</Alert>
)}
{leafOptions.length > 0 && (
<>
<Divider label="Проверить готовую ветку" />
<Select
placeholder="Выберите путь для проверки"
data={leafOptions.map((o) => ({ value: o.value, label: o.label }))}
value={previewLeafKey}
onChange={handlePreviewLeaf}
searchable
/>
{previewFlow.isPending && <Loader size="xs" />}
{previewFlow.data && !previewFlow.data.incomplete && (
<Paper withBorder p={6} bg="white">
<Text size="xs" c="dimmed">
Код: <Code>{previewFlow.data.code}</Code>
</Text>
<Text size="xs" mt={4} style={{ whiteSpace: 'pre-wrap' }}>
{previewFlow.data.message}
</Text>
</Paper>
)}
</>
)}
</Stack>
</Collapse>
</Paper>
)}
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
{isEditMode ? 'Сохранить' : 'Создать'}
</Button>
</Group>
</Stack>
</form>
</Modal>
)
}
-----END src/pages/flowNodes/components/FlowNodeEditModal.tsx-----
File: src/pages/flowNodes/components/SortableFlowTree.tsx
Lines: 268
-----BEGIN src/pages/flowNodes/components/SortableFlowTree.tsx-----
import { useMemo, useState } from 'react'
import {
DndContext,
DragOverlay,
PointerSensor,
useSensor,
useSensors,
closestCenter,
type DragStartEvent,
type DragMoveEvent,
type DragOverEvent,
type DragEndEvent,
} from '@dnd-kit/core'
import { SortableContext, verticalListSortingStrategy, useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { Paper, Group, Text, ActionIcon, Tooltip, Badge, Box, Alert } from '@mantine/core'
import {
IconGripVertical,
IconPlus,
IconEdit,
IconTrash,
IconCopy,
IconChevronDown,
IconChevronRight,
IconArrowsMove,
} from '@tabler/icons-react'
import type { ApprovalFlowNode } from '@/types/api'
import { useReorderNodes } from '@/features/flowNodes/hooks/useFlowNodes'
import {buildReorderPlan, FlatFlowNode, flattenTree, getProjection} from "@/features/flowNodes/utils/flattenTree.ts";
const INDENTATION = 24
interface SortableFlowTreeProps {
tree: ApprovalFlowNode[]
onEdit: (node: ApprovalFlowNode) => void
onAddChild: (parent: ApprovalFlowNode) => void
onDelete: (node: ApprovalFlowNode) => void
onDuplicate: (node: ApprovalFlowNode) => void
}
function nodeIcon(node: ApprovalFlowNode): string {
if (node.is_input) return '📝'
if (node.is_multi_select) return '☑️'
return '🔘'
}
function nodeKindLabel(node: ApprovalFlowNode): string {
if (node.is_input) return 'Текстовый ввод — здесь сотрудник пишет заявку'
if (node.is_multi_select) return 'Можно выбрать несколько вариантов'
return 'Кнопка'
}
export default function SortableFlowTree({ tree, onEdit, onAddChild, onDelete, onDuplicate }: SortableFlowTreeProps) {
const [collapsed, setCollapsed] = useState<Set<number>>(new Set())
const [activeId, setActiveId] = useState<number | null>(null)
const [overId, setOverId] = useState<number | null>(null)
const [offsetX, setOffsetX] = useState(0)
const reorder = useReorderNodes()
const flatItems = useMemo(() => flattenTree(tree, collapsed), [tree, collapsed])
const sortableIds = useMemo(() => flatItems.map((n) => n.id!), [flatItems])
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))
const projected = useMemo(() => {
if (activeId == null || overId == null) return null
return getProjection(flatItems, activeId, overId, offsetX, INDENTATION)
}, [flatItems, activeId, overId, offsetX])
const activeNode = flatItems.find((n) => n.id === activeId) || null
const projectedParentLabel = projected
? flatItems.find((n) => n.id === projected.parentId)?.label || null
: null
const toggleCollapse = (id: number) => {
setCollapsed((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
const handleDragStart = (event: DragStartEvent) => {
setActiveId(event.active.id as number)
setOverId(event.active.id as number)
setOffsetX(0)
}
const handleDragMove = (event: DragMoveEvent) => {
setOffsetX(event.delta.x)
}
const handleDragOver = (event: DragOverEvent) => {
setOverId((event.over?.id as number) ?? null)
}
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event
const currentProjected = projected
setActiveId(null)
setOverId(null)
setOffsetX(0)
if (!over || !currentProjected) return
const activeIdNum = active.id as number
const overIdNum = over.id as number
const activeNodeBefore = flatItems.find((n) => n.id === activeIdNum)
if (!activeNodeBefore) return
const noParentChange = (activeNodeBefore.parent_id ?? null) === currentProjected.parentId
const droppedOnSelf = activeIdNum === overIdNum
if (noParentChange && droppedOnSelf) return
const ops = buildReorderPlan(tree, activeIdNum, currentProjected.parentId, overIdNum)
if (ops.length > 0) {
reorder.mutate(ops)
}
}
return (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragMove={handleDragMove}
onDragOver={handleDragOver}
onDragEnd={handleDragEnd}
>
{activeNode && (
<Alert color="blue" variant="light" mb={6} icon={<IconArrowsMove size={16} />}>
<Text size="xs">
«{activeNode.label}» станет шагом внутри «{projectedParentLabel || '…'}» — потяните влево/вправо,
чтобы поменять уровень вложенности
</Text>
</Alert>
)}
<SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>
<Box>
{flatItems.map((node) => (
<SortableRow
key={node.id}
node={node}
hasChildren={!!node.children?.length}
collapsed={node.id != null && collapsed.has(node.id)}
onToggleCollapse={() => node.id != null && toggleCollapse(node.id)}
onEdit={onEdit}
onAddChild={onAddChild}
onDelete={onDelete}
onDuplicate={onDuplicate}
/>
))}
</Box>
</SortableContext>
<DragOverlay>
{activeNode ? (
<Paper withBorder p="xs" shadow="md">
<Group gap={6}>
<IconGripVertical size={14} />
<Text size="lg">{nodeIcon(activeNode)}</Text>
<Text fw={600}>{activeNode.label}</Text>
</Group>
</Paper>
) : null}
</DragOverlay>
</DndContext>
)
}
interface SortableRowProps {
node: FlatFlowNode
hasChildren: boolean
collapsed: boolean
onToggleCollapse: () => void
onEdit: (node: ApprovalFlowNode) => void
onAddChild: (parent: ApprovalFlowNode) => void
onDelete: (node: ApprovalFlowNode) => void
onDuplicate: (node: ApprovalFlowNode) => void
}
function SortableRow({ node, hasChildren, collapsed, onToggleCollapse, onEdit, onAddChild, onDelete, onDuplicate }: SortableRowProps) {
const isRoot = node.depth === 0
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: node.id!,
disabled: isRoot, // корень дерева не перетаскивается — его ключ жёстко привязан к коду раздела
})
const style = {
transform: CSS.Translate.toString(transform),
transition,
marginLeft: node.depth * INDENTATION,
opacity: isDragging ? 0.4 : 1,
}
return (
<div ref={setNodeRef} style={style}>
<Paper withBorder p="xs" mb={4} bg={isRoot ? 'var(--mantine-color-blue-0)' : undefined}>
<Group justify="space-between" wrap="nowrap">
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
{!isRoot ? (
<ActionIcon
variant="subtle"
size="sm"
{...attributes}
{...listeners}
style={{ cursor: 'grab', touchAction: 'none' }}
>
<IconGripVertical size={14} />
</ActionIcon>
) : (
<Tooltip label="Первый шаг дерева нельзя перемещать">
<Box w={28} />
</Tooltip>
)}
{hasChildren ? (
<ActionIcon size="sm" variant="subtle" onClick={onToggleCollapse}>
{collapsed ? <IconChevronRight size={14} /> : <IconChevronDown size={14} />}
</ActionIcon>
) : (
<Box w={22} />
)}
<Text size="lg">{nodeIcon(node)}</Text>
<Box style={{ minWidth: 0 }}>
<Group gap={6}>
<Text fw={600} truncate>
{node.label}
</Text>
{isRoot && (
<Badge size="xs" color="blue" variant="light">
начало дерева
</Badge>
)}
</Group>
<Text size="xs" c="dimmed">
{nodeKindLabel(node)}
{node.data_key ? ` · запоминает: ${node.data_key} = ${node.data_value}` : ''}
</Text>
</Box>
</Group>
<Group gap={2} wrap="nowrap">
<Tooltip label="Добавить следующий шаг после этой кнопки">
<ActionIcon variant="subtle" size="sm" color="blue" onClick={() => onAddChild(node)}>
<IconPlus size={14} />
</ActionIcon>
</Tooltip>
<Tooltip label="Изменить">
<ActionIcon variant="subtle" size="sm" onClick={() => onEdit(node)}>
<IconEdit size={14} />
</ActionIcon>
</Tooltip>
<Tooltip label="Сделать копию этого шага со всеми вложенными">
<ActionIcon variant="subtle" size="sm" onClick={() => onDuplicate(node)}>
<IconCopy size={14} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить (вместе со всеми вложенными шагами)">
<ActionIcon variant="subtle" size="sm" color="red" onClick={() => onDelete(node)}>
<IconTrash size={14} />
</ActionIcon>
</Tooltip>
</Group>
</Group>
</Paper>
</div>
)
}
-----END src/pages/flowNodes/components/SortableFlowTree.tsx-----
File: src/pages/flowNodes/components/TreeHealthPanel.tsx
Lines: 151
-----BEGIN src/pages/flowNodes/components/TreeHealthPanel.tsx-----
import { useState } from 'react'
import { Paper, Group, Text, Button, Table, Badge, Loader, Alert } from '@mantine/core'
import { IconStethoscope, IconInfoCircle, IconCirclePlus } from '@tabler/icons-react'
import { flowNodesApi, type PreviewFlowResponse } from '@/api/flowNodes'
import { useCreateTopic } from '@/features/topics/hooks/useTopics'
import type { CreateTopicRequest } from '@/api/topics'
import { collectFromPath, collectLeafPaths, pathLabel } from '@/features/flowNodes/utils/treeWalk'
import type { ApprovalFlowNode } from '@/types/api'
interface TreeHealthPanelProps {
categoryId: number
tree: ApprovalFlowNode[]
}
interface HealthRow {
key: string
label: string
result: PreviewFlowResponse | null
error?: boolean
}
// Проходит по каждой готовой ветке дерева ("от начала до текстового ввода")
// и проверяет через реальный движок бэкенда, есть ли для неё настроенная
// тема. Так администратор видит проблему ДО того, как сотрудник наткнётся
// на неё в боте — а не после жалобы, что "заявка не отправляется".
export default function TreeHealthPanel({ categoryId, tree }: TreeHealthPanelProps) {
const [rows, setRows] = useState<HealthRow[] | null>(null)
const [checking, setChecking] = useState(false)
const createTopic = useCreateTopic()
const runCheck = async () => {
setChecking(true)
const leafPaths = collectLeafPaths(tree)
const results = await Promise.all(
leafPaths.map(async (path) => {
const key = path.map((n) => n.id).join('-')
const label = pathLabel(path)
try {
const response = await flowNodesApi.preview(categoryId, {
collected: collectFromPath(path),
})
return { key, label, result: response.data } as HealthRow
} catch {
return { key, label, result: null, error: true } as HealthRow
}
})
)
setRows(results)
setChecking(false)
}
const handleCreateTopic = async (row: HealthRow) => {
if (!row.result?.code) return
const payload: CreateTopicRequest = {
category_id: categoryId,
code: row.result.code,
name: row.label,
is_active: true,
}
await createTopic.mutateAsync(payload)
runCheck()
}
const missingCount = rows?.filter((r) => r.result && !r.result.incomplete && !r.result.topic_exists).length || 0
return (
<Paper withBorder p="md">
<Group justify="space-between" mb="sm">
<Text fw={600}>Проверка дерева</Text>
<Button
size="xs"
variant="light"
leftSection={<IconStethoscope size={14} />}
onClick={runCheck}
loading={checking}
>
Проверить все ветки
</Button>
</Group>
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light" mb="sm">
<Text size="xs">
Пройдёт по каждому возможному пути в дереве и проверит, для всех ли есть настроенная тема
заявки. Если для какого-то пути темы нет — заявку по нему бот не сможет отправить.
</Text>
</Alert>
{rows && missingCount > 0 && (
<Alert color="orange" variant="light" mb="sm">
<Text size="sm">Не хватает тем для {missingCount} путей — см. таблицу ниже.</Text>
</Alert>
)}
{rows && missingCount === 0 && (
<Alert color="teal" variant="light" mb="sm">
<Text size="sm">Все ветки дерева ведут к настроенным темам ✅</Text>
</Alert>
)}
{checking && <Loader size="sm" />}
{rows && (
<Table striped withTableBorder>
<Table.Thead>
<Table.Tr>
<Table.Th>Путь</Table.Th>
<Table.Th>Код темы</Table.Th>
<Table.Th>Статус</Table.Th>
<Table.Th />
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{rows.map((row) => (
<Table.Tr key={row.key}>
<Table.Td>
<Text size="xs">{row.label}</Text>
</Table.Td>
<Table.Td>
<Text size="xs" ff="monospace">
{row.result?.code || '—'}
</Text>
</Table.Td>
<Table.Td>
{row.error ? (
<Badge color="red">Ошибка проверки</Badge>
) : row.result?.incomplete ? (
<Badge color="gray">Путь не завершён</Badge>
) : row.result?.topic_exists ? (
<Badge color="teal">Есть тема</Badge>
) : (
<Badge color="orange">Темы нет</Badge>
)}
</Table.Td>
<Table.Td>
{row.result && !row.result.incomplete && !row.result.topic_exists && (
<Button
size="compact-xs"
leftSection={<IconCirclePlus size={12} />}
onClick={() => handleCreateTopic(row)}
loading={createTopic.isPending}
>
Создать
</Button>
)}
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
)}
</Paper>
)
}
-----END src/pages/flowNodes/components/TreeHealthPanel.tsx-----
File: src/pages/hierarchies/HierarchiesPage.tsx
Lines: 631
-----BEGIN src/pages/hierarchies/HierarchiesPage.tsx-----
import { useState, useMemo } from 'react'
import {
Paper,
Table,
Group,
ActionIcon,
Button,
Text,
Select,
Loader,
Center,
Tooltip,
Box,
Stack,
SegmentedControl,
Badge,
Alert,
ScrollArea,
Pagination,
Checkbox,
} from '@mantine/core'
import {
IconPencil,
IconTrash,
IconPlus,
IconInfoCircle,
IconUsers,
} from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { notifications } from '@mantine/notifications'
import {
useHierarchies,
useDeleteHierarchy,
useUpdateHierarchy, HIERARCHIES_QUERY_KEY,
} from '@/features/hierarchies/hooks/useHierarchies'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
import {
groupHierarchiesIntoChains,
SCOPE_COLORS,
SCOPE_LABELS,
type ChainGroup,
} from '@/features/hierarchies/utils'
import ChainVisualization from './components/ChainVisualization'
import ChainDuplicateModal from './components/ChainDuplicateModal'
import HierarchyEditModal from './components/HierarchyEditModal'
import PersonDuplicateModal from './components/PersonDuplicateModal'
import type { UserHierarchy } from '@/types/api'
import { hierarchiesApi } from '@/api/hierarchies'
import { useQueryClient } from '@tanstack/react-query'
const LIMIT = 20
type ViewMode = 'chains' | 'table'
export default function HierarchiesPage() {
const [viewMode, setViewMode] = useState<ViewMode>('chains')
const [page, setPage] = useState(1)
// Фильтры
const [subordinateFilter, setSubordinateFilter] = useState<string | null>(null)
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
const [categoryFilter, setCategoryFilter] = useState<string | null>(null)
const [topicFilter, setTopicFilter] = useState<string | null>(null)
// Массовое удаление
const [selectedIds, setSelectedIds] = useState<number[]>([])
const [isDeleting, setIsDeleting] = useState(false)
// Модалки
const [editHierarchy, setEditHierarchy] = useState<UserHierarchy | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const [presetGroup, setPresetGroup] = useState<ChainGroup | null>(null)
const [duplicateGroup, setDuplicateGroup] = useState<ChainGroup | null>(null)
const [duplicateModalOpened, setDuplicateModalOpened] = useState(false)
const [personDuplicateOpened, setPersonDuplicateOpened] = useState(false)
const { data: categoryTopics } = useTopics({
limit: 1000,
...(categoryFilter && { category_id: Number(categoryFilter) }),
})
const { data, isLoading, isFetching } = useHierarchies({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(subordinateFilter && { subordinate_id: Number(subordinateFilter) }),
...(departmentFilter && { department_id: Number(departmentFilter) }),
...(categoryFilter && { topic_category_id: Number(categoryFilter) }),
...(topicFilter && { topic_id: Number(topicFilter) }),
})
const { data: users } = useUsers({ limit: 1000 })
const { data: departments } = useDepartments()
const { data: categories } = useCategories({ limit: 1000 })
const { data: topics } = useTopics({ limit: 1000 })
const deleteHierarchy = useDeleteHierarchy()
const updateHierarchy = useUpdateHierarchy()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const chains = useMemo(() => {
if (!data?.data) return []
return groupHierarchiesIntoChains(data.data)
}, [data])
const enrichedChains = useMemo(() => {
return chains.map((chain) => {
let scopeObjectName = 'Все темы'
if (chain.scopeType === 'category' && chain.scopeObjectId) {
const cat = categories?.data?.find((c) => c.id === chain.scopeObjectId)
scopeObjectName = cat?.name || `Категория #${chain.scopeObjectId}`
} else if (chain.scopeType === 'topic' && chain.scopeObjectId) {
const topic = topics?.data?.find((t) => t.id === chain.scopeObjectId)
scopeObjectName = topic?.name || `Тема #${chain.scopeObjectId}`
}
return { ...chain, scopeObjectName }
})
}, [chains, categories, topics])
const userOptions =
users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const departmentOptions =
departments?.data?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || []
const categoryOptions =
categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions =
(categoryFilter ? categoryTopics?.data : topics?.data)?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const handleSelectAll = () => {
if (selectedIds.length === data?.data?.length) {
setSelectedIds([])
} else {
setSelectedIds(data?.data?.map((h) => h.id!) || [])
}
}
const handleSelectOne = (id: number) => {
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
)
}
const handleFilterChange =
(setter: (value: string | null) => void) => (value: string | null) => {
setter(value)
setPage(1)
setSelectedIds([])
}
const queryClient = useQueryClient()
const handleBulkDelete = () => {
modals.openConfirmModal({
title: 'Подтвердите массовое удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить <strong>{selectedIds.length}</strong>{' '}
записей? Это действие необратимо.
</Text>
),
labels: { confirm: 'Удалить все', cancel: 'Отмена' },
confirmProps: { color: 'red', loading: isDeleting },
onConfirm: async () => {
setIsDeleting(true)
try {
// Удаляем напрямую через API, не вызывая мутацию поштучно
await Promise.all(selectedIds.map((id) => hierarchiesApi.delete(id)))
// Обновляем список один раз
queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] })
notifications.show({
title: 'Успешно',
message: `Успешно удалено записей: ${selectedIds.length}`,
color: 'green',
})
setSelectedIds([])
} catch (error) {
notifications.show({
title: 'Ошибка',
message: 'Не удалось удалить некоторые записи',
color: 'red',
})
} finally {
setIsDeleting(false)
}
},
})
}
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить эту связь?
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: async () => {
await deleteHierarchy.mutateAsync(id)
},
})
}
const handleEditStep = (id: number) => {
const hierarchy = data?.data?.find((h) => h.id === id)
if (hierarchy) {
setEditHierarchy(hierarchy)
}
}
const handleAddStep = (group: ChainGroup) => {
setPresetGroup(group)
setCreateModalOpened(true)
}
const handleDuplicateChain = (group: ChainGroup) => {
setDuplicateGroup(group)
setDuplicateModalOpened(true)
}
const handleCloseModal = () => {
setEditHierarchy(null)
setCreateModalOpened(false)
setPresetGroup(null)
}
const handleCloseDuplicateModal = () => {
setDuplicateGroup(null)
setDuplicateModalOpened(false)
}
const isAllSelected =
(data?.data?.length ?? 0) > 0 && selectedIds.length === (data?.data?.length ?? 0)
const isIndeterminate =
selectedIds.length > 0 && selectedIds.length < (data?.data?.length || 0)
const handleBulkUpdateSystem = async (group: ChainGroup, targetSystem: string | null) => {
try {
// Обновляем все шаги в выбранной цепочке асинхронно
await Promise.all(
group.steps.map((step) =>
updateHierarchy.mutateAsync({
id: step.id!,
subordinate_id: step.subordinate_id,
approver_id: step.approver_id,
department_id: step.department_id,
topic_category_id: step.topic_category_id,
topic_id: step.topic_id,
priority: step.priority,
target_system: targetSystem, // Применяем новую систему
})
)
)
} catch (error) {
console.error("Ошибка при массовом обновлении систем цепочки", error)
}
}
return (
<Stack gap="md">
{/* Заголовок */}
<Group justify="space-between">
<Text size="xl" fw={700}>Иерархия согласований</Text>
<Group>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
<SegmentedControl
value={viewMode}
onChange={(v) => {
setViewMode(v as ViewMode)
setSelectedIds([])
}}
data={[
{ value: 'chains', label: 'Цепочки' },
{ value: 'table', label: 'Таблица' },
]}
/>
<Tooltip label="Скопировать все цепочки одного сотрудника для другого — например, для нового сотрудника с такой же ролью">
<Button
variant="light"
leftSection={<IconUsers size={16} />}
onClick={() => setPersonDuplicateOpened(true)}
>
Дублировать по сотруднику
</Button>
</Tooltip>
<Button
leftSection={<IconPlus size={16} />}
onClick={() => {
setPresetGroup(null)
setCreateModalOpened(true)
}}
>
Добавить связь
</Button>
</Group>
</Group>
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
<Text size="sm">
Иерархия определяет порядок согласования заявок. Каждая цепочка показывает,
через каких согласующих проходит заявка от конкретного сотрудника.
</Text>
</Alert>
{/* Фильтры */}
<Paper withBorder p="md">
<Stack gap="md">
<Group gap="md" align="flex-end">
<Select
label="Сотрудник"
placeholder="Все пользователи"
data={userOptions}
value={subordinateFilter}
onChange={handleFilterChange(setSubordinateFilter)}
clearable
searchable
style={{ flex: 1, minWidth: 250 }}
/>
<Select
label="Отдел"
placeholder="Все отделы"
data={departmentOptions}
value={departmentFilter}
onChange={handleFilterChange(setDepartmentFilter)}
clearable
style={{ flex: 1, minWidth: 200 }}
/>
</Group>
<Group gap="md" align="flex-end">
<Select
label="Категория"
placeholder="Все категории"
data={categoryOptions}
value={categoryFilter}
onChange={(v) => {
handleFilterChange(setCategoryFilter)(v)
setTopicFilter(null)
}}
clearable
searchable
style={{ flex: 1, minWidth: 200 }}
/>
<Select
label="Тема"
placeholder="Все темы"
data={topicOptions}
value={topicFilter}
onChange={handleFilterChange(setTopicFilter)}
clearable
searchable
style={{ flex: 1, minWidth: 200 }}
/>
</Group>
</Stack>
</Paper>
{/* Контент */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : viewMode === 'chains' ? (
<ScrollArea p="md">
<Stack gap="md">
{enrichedChains.length === 0 ? (
<Center p={40}>
<Text c="dimmed">Связи не найдены</Text>
</Center>
) : (
enrichedChains.map((chain) => (
<ChainVisualization
key={chain.key}
group={chain}
onEditStep={handleEditStep}
onDeleteStep={handleDelete}
onAddStep={handleAddStep}
onDuplicateChain={handleDuplicateChain}
onBulkUpdateSystem={handleBulkUpdateSystem}
/>
))
)}
</Stack>
</ScrollArea>
) : (
<>
{selectedIds.length > 0 && (
<Box
p="sm"
bg="red.0"
style={{ borderBottom: '1px solid var(--mantine-color-red-3)' }}
>
<Group justify="space-between">
<Text size="sm" fw={500}>
Выбрано записей: <strong>{selectedIds.length}</strong>
</Text>
<Group gap="xs">
<Button
variant="subtle"
size="xs"
onClick={() => setSelectedIds([])}
>
Снять выделение
</Button>
<Button
color="red"
size="xs"
leftSection={<IconTrash size={14} />}
onClick={handleBulkDelete}
loading={isDeleting}
>
Удалить выбранные
</Button>
</Group>
</Group>
</Box>
)}
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 50 }}>
<Checkbox
checked={isAllSelected}
indeterminate={isIndeterminate}
onChange={handleSelectAll}
/>
</Table.Th>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Подчинённый</Table.Th>
<Table.Th>Согласующий</Table.Th>
<Table.Th>Отдел</Table.Th>
<Table.Th>Область</Table.Th>
<Table.Th>Объект</Table.Th>
<Table.Th style={{ width: 80 }}>Порядок</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={9}>
<Center p={40}>
<Text c="dimmed">Связи не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
data?.data?.map((h) => {
const scopeType = h.topic_id
? 'topic'
: h.topic_category_id
? 'category'
: 'global'
let scopeObjectName = 'Все темы'
if (scopeType === 'category' && h.topic_category_id) {
const cat = categories?.data?.find(
(c) => c.id === h.topic_category_id
)
scopeObjectName = cat?.name || `#${h.topic_category_id}`
} else if (scopeType === 'topic' && h.topic_id) {
const topic = topics?.data?.find(
(t) => t.id === h.topic_id
)
scopeObjectName = topic?.name || `#${h.topic_id}`
}
return (
<Table.Tr
key={h.id}
style={{
backgroundColor: selectedIds.includes(h.id!)
? 'var(--mantine-color-blue-0)'
: undefined,
}}
>
<Table.Td>
<Checkbox
checked={selectedIds.includes(h.id!)}
onChange={() => handleSelectOne(h.id!)}
/>
</Table.Td>
<Table.Td>{h.id}</Table.Td>
<Table.Td>
<Text size="sm" fw={500}>
{h.subordinate?.full_name || '—'}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" fw={500}>
{h.approver?.full_name || '—'}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm">
{h.department?.name || '—'}
</Text>
</Table.Td>
<Table.Td>
<Badge
size="xs"
color={
SCOPE_COLORS[
scopeType as keyof typeof SCOPE_COLORS
]
}
variant="light"
>
{
SCOPE_LABELS[
scopeType as keyof typeof SCOPE_LABELS
]
}
</Badge>
</Table.Td>
<Table.Td>
<Text size="sm" lineClamp={1}>
{scopeObjectName}
</Text>
</Table.Td>
<Table.Td>
<Badge variant="light" color="gray">
#{h.priority}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs">
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditHierarchy(h)}
>
<IconPencil size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="light"
color="red"
onClick={() => handleDelete(h.id!)}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Table.Td>
</Table.Tr>
)
})
)}
</Table.Tbody>
</Table>
</>
)}
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={(newPage) => {
setPage(newPage)
setSelectedIds([])
}}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</Paper>
{isFetching && !isLoading && (
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
<Loader size="xs" />
</Box>
)}
{/* Модалки */}
<HierarchyEditModal
hierarchy={editHierarchy}
opened={editHierarchy !== null}
onClose={handleCloseModal}
/>
<HierarchyEditModal
hierarchy={null}
presetGroup={presetGroup}
opened={createModalOpened}
onClose={handleCloseModal}
/>
<ChainDuplicateModal
group={duplicateGroup}
opened={duplicateModalOpened}
onClose={handleCloseDuplicateModal}
/>
<PersonDuplicateModal
opened={personDuplicateOpened}
onClose={() => setPersonDuplicateOpened(false)}
/>
</Stack>
)
}
-----END src/pages/hierarchies/HierarchiesPage.tsx-----
File: src/pages/hierarchies/components/ChainDuplicateModal.tsx
Lines: 526
-----BEGIN src/pages/hierarchies/components/ChainDuplicateModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
Select,
Group,
Button,
Text,
Paper,
Divider,
ActionIcon,
Badge,
Avatar,
Box,
Radio,
Alert,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
IconInfoCircle,
IconPlus,
IconTrash,
IconCopy,
IconChevronRight,
} from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import { useCreateHierarchy } from '@/features/hierarchies/hooks/useHierarchies'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
import { useAllSystemOptions } from '@/features/hierarchies/hooks/useSystemOptions' // 👈 ИМПОРТИРОВАЛИ ХУК
import type { ChainGroup } from '@/features/hierarchies/utils'
interface ChainDuplicateModalProps {
group: ChainGroup | null
opened: boolean
onClose: () => void
}
type ScopeType = 'global' | 'category' | 'topic'
interface StepForm {
approver_id: number | null
priority: number
target_system: string | null // 👈 ДОБАВИЛИ ПОЛЕ В ИНТЕРФЕЙС
}
export default function ChainDuplicateModal({
group,
opened,
onClose,
}: ChainDuplicateModalProps) {
const createHierarchy = useCreateHierarchy()
const { data: users } = useUsers({ limit: 1000 })
const { data: departments } = useDepartments()
const { data: categories } = useCategories({ limit: 1000 })
// Подтягиваем доступные системы
const { options: systemOptions } = useAllSystemOptions()
const { data: allTopics } = useTopics({ limit: 1000 })
const form = useForm({
initialValues: {
subordinate_id: null as number | null,
department_id: null as number | null,
scope_type: 'global' as ScopeType,
topic_category_id: null as number | null,
topic_id: null as number | null,
steps: [] as StepForm[],
},
validate: {
subordinate_id: (v) => (v === null ? 'Выберите инициатора' : null),
department_id: (v) => (v === null ? 'Выберите отдел' : null),
topic_category_id: (v, values) => {
if (
(values.scope_type === 'category' || values.scope_type === 'topic') &&
v === null
) {
return 'Выберите категорию'
}
return null
},
topic_id: (v, values) => {
if (values.scope_type === 'topic' && v === null) {
return 'Выберите тему'
}
return null
},
steps: {
approver_id: (v) => (v === null ? 'Выберите согласующего' : null),
},
},
})
const { data: categoryTopics } = useTopics({
limit: 1000,
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
})
useEffect(() => {
if (group && opened) {
let resolvedCategoryId: number | null = null
if (group.scopeType === 'category') {
resolvedCategoryId = group.scopeObjectId
} else if (group.scopeType === 'topic') {
const matchedTopic = allTopics?.data?.find((t) => t.id === group.scopeObjectId)
resolvedCategoryId = matchedTopic?.category_id || null
}
form.setValues({
subordinate_id: group.subordinateId,
department_id: group.departmentId,
scope_type: group.scopeType,
topic_category_id: resolvedCategoryId,
topic_id: group.scopeType === 'topic' ? group.scopeObjectId : null,
steps: group.steps.map((s, idx) => ({
approver_id: s.approver_id || null,
priority: idx,
target_system: s.target_system || null, // 👈 ИНИЦИАЛИЗИРУЕМ ИЗ БД
})),
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [group, opened, allTopics])
const handleScopeTypeChange = (value: ScopeType) => {
form.setFieldValue('scope_type', value)
if (value === 'global') {
form.setFieldValue('topic_category_id', null)
form.setFieldValue('topic_id', null)
} else if (value === 'category') {
form.setFieldValue('topic_id', null)
}
}
const addStep = () => {
form.insertListItem('steps', {
approver_id: null,
priority: form.values.steps.length,
target_system: null, // 👈 ИНИЦИАЛИЗИРУЕМ ДЛЯ НОВОГО ШАГА
})
}
const removeStep = (index: number) => {
form.removeListItem('steps', index)
form.values.steps.forEach((_, idx) => {
form.setFieldValue(`steps.${idx}.priority`, idx)
})
}
const userOptions =
users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const departmentOptions =
departments?.data?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || []
const categoryOptions =
categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions =
categoryTopics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const handleSubmit = async (values: typeof form.values) => {
if (values.steps.length === 0) {
notifications.show({
title: 'Ошибка',
message: 'Добавьте хотя бы один шаг согласования',
color: 'red',
})
return
}
try {
for (const step of values.steps) {
await createHierarchy.mutateAsync({
subordinate_id: values.subordinate_id!,
approver_id: step.approver_id!,
department_id: values.department_id!,
priority: step.priority,
target_system: step.target_system || null, // 👈 ОТПРАВЛЯЕМ СИСТЕМУ
topic_category_id:
values.scope_type === 'global'
? null
: values.scope_type === 'category'
? values.topic_category_id
: null,
topic_id: values.scope_type === 'topic' ? values.topic_id : null,
})
}
notifications.show({
title: 'Успешно',
message: `Цепочка дублирована (${values.steps.length} шагов)`,
color: 'green',
})
onClose()
} catch (error) {
notifications.show({
title: 'Ошибка',
message: 'Не удалось дублировать цепочку',
color: 'red',
})
}
}
const isSubmitting = createHierarchy.isPending
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group gap="xs">
<IconCopy size={20} />
<Text fw={600}>Дублирование цепочки</Text>
</Group>
}
size="lg"
centered
>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
<Text size="sm">
Создайте новую цепочку на основе существующей. Вы можете изменить
инициатора, отдел, область действия и согласующих.
</Text>
</Alert>
{/* Общие параметры */}
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm" c="dark">
Общие параметры
</Text>
<Stack gap="sm">
<Select
label="Инициатор"
placeholder="Выберите пользователя"
data={userOptions}
value={
form.values.subordinate_id
? String(form.values.subordinate_id)
: null
}
onChange={(v) =>
form.setFieldValue(
'subordinate_id',
v ? Number(v) : null
)
}
searchable
required
error={form.errors.subordinate_id}
/>
<Select
label="Отдел"
placeholder="Выберите отдел"
data={departmentOptions}
value={
form.values.department_id
? String(form.values.department_id)
: null
}
onChange={(v) =>
form.setFieldValue(
'department_id',
v ? Number(v) : null
)
}
searchable
required
error={form.errors.department_id}
/>
</Stack>
</Paper>
{/* Область действия */}
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm" c="dark">
Область действия
</Text>
<Stack gap="sm">
<Radio.Group
value={form.values.scope_type}
onChange={(v) => handleScopeTypeChange(v as ScopeType)}
>
<Stack gap="xs">
<Radio
value="global"
label="Глобальное правило"
description="Для всех тем согласований"
/>
<Radio
value="category"
label="Для категории тем"
description="Только для тем выбранной категории"
/>
<Radio
value="topic"
label="Для конкретной темы"
description="Только для выбранной темы"
/>
</Stack>
</Radio.Group>
{(form.values.scope_type === 'category' ||
form.values.scope_type === 'topic') && (
<Select
label="Категория"
placeholder="Выберите категорию"
data={categoryOptions}
value={
form.values.topic_category_id
? String(form.values.topic_category_id)
: null
}
onChange={(v) => {
form.setFieldValue(
'topic_category_id',
v ? Number(v) : null
)
form.setFieldValue('topic_id', null)
}}
searchable
required
error={form.errors.topic_category_id}
/>
)}
{form.values.scope_type === 'topic' && (
<Select
label="Тема"
placeholder="Выберите тему"
data={topicOptions}
value={
form.values.topic_id
? String(form.values.topic_id)
: null
}
onChange={(v) =>
form.setFieldValue('topic_id', v ? Number(v) : null)
}
searchable
required
disabled={!form.values.topic_category_id}
error={form.errors.topic_id}
/>
)}
</Stack>
</Paper>
{/* Шаги согласования */}
<Paper withBorder p="md">
<Group justify="space-between" mb="sm">
<Text size="sm" fw={600} c="dark">
Шаги согласования
</Text>
<Button
variant="subtle"
size="xs"
leftSection={<IconPlus size={14} />}
onClick={addStep}
>
Добавить шаг
</Button>
</Group>
<Stack gap="sm">
{form.values.steps.length === 0 ? (
<Box py="md">
<Text size="sm" c="dimmed" ta="center">
Нет шагов согласования. Добавьте хотя бы один.
</Text>
</Box>
) : (
form.values.steps.map((step, index) => (
<Paper
key={index}
withBorder
p="sm"
style={{
borderColor: 'var(--mantine-color-gray-3)',
backgroundColor: 'var(--mantine-color-gray-0)',
}}
>
<Group gap="sm" align="flex-start">
<Avatar
size="sm"
radius="xl"
color="blue"
variant="filled"
mt={4}
>
{index + 1}
</Avatar>
<Stack gap="xs" style={{ flex: 1 }}>
<Group gap="xs">
<Badge
size="xs"
variant="light"
color="gray"
tt="none"
>
Шаг {index + 1}
</Badge>
<Badge
size="xs"
variant="light"
color="gray"
tt="none"
>
Priority: {step.priority}
</Badge>
</Group>
<Group grow gap="xs">
<Select
placeholder="Выберите согласующего"
data={userOptions}
value={step.approver_id ? String(step.approver_id) : null}
onChange={(v) =>
form.setFieldValue(`steps.${index}.approver_id`, v ? Number(v) : null)
}
searchable
error={
Array.isArray(form.errors.steps) && form.errors.steps[index]
? (form.errors.steps[index] as any)?.approver_id
: undefined
}
/>
{/* 👈 ДОБАВЛЕННЫЙ ВЫБОР СИСТЕМЫ */}
<Select
placeholder="Система: Все (по умолчанию)"
data={[
{ value: 'all', label: 'Система: Все' },
...systemOptions.map((s) => ({ value: s.value, label: `Система: ${s.label}` })),
]}
value={step.target_system || 'all'}
onChange={(v) =>
form.setFieldValue(
`steps.${index}.target_system`,
(v === 'all' || !v) ? null : v
)
}
clearable
/>
</Group>
</Stack>
<ActionIcon
variant="subtle"
color="red"
size="md"
mt={4}
onClick={() => removeStep(index)}
>
<IconTrash size={16} />
</ActionIcon>
</Group>
</Paper>
))
)}
</Stack>
</Paper>
{/* Предпросмотр */}
{form.values.steps.length > 0 && (
<Paper withBorder p="md" bg="gray.0">
<Text size="xs" fw={600} c="dimmed" mb="xs" tt="uppercase">
Предпросмотр цепочки
</Text>
<Group gap="xs" wrap="nowrap" style={{ overflowX: 'auto' }}>
<Badge variant="light" color="gray" tt="none">
{users?.data?.find(
(u) => u.id === form.values.subordinate_id
)?.full_name || 'Инициатор'}
</Badge>
{form.values.steps.map((step, index) => (
<Group key={index} gap={4} wrap="nowrap">
<IconChevronRight
size={14}
color="var(--mantine-color-gray-5)"
/>
<Badge variant="light" color="blue" tt="none">
{users?.data?.find(
(u) => u.id === step.approver_id
)?.full_name || `Шаг ${index + 1}`}
{step.target_system && ` (${step.target_system})`}
</Badge>
</Group>
))}
</Group>
</Paper>
)}
<Divider />
<Group justify="flex-end" gap="sm">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
Дублировать цепочку
</Button>
</Group>
</Stack>
</form>
</Modal>
)
}
-----END src/pages/hierarchies/components/ChainDuplicateModal.tsx-----
File: src/pages/hierarchies/components/ChainVisualization.tsx
Lines: 323
-----BEGIN src/pages/hierarchies/components/ChainVisualization.tsx-----
// ChainVisualization.tsx
import {useMemo, useState} from 'react'
import {
Paper,
Group,
Stack,
Text,
Badge,
ActionIcon,
Avatar,
Box,
Divider,
Tooltip,
Select,
} from '@mantine/core'
import {
IconChevronRight,
IconPencil,
IconTrash,
IconWorld,
IconCategory,
IconFileText,
IconCopy,
IconPlus,
IconServer,
} from '@tabler/icons-react'
import type { ChainGroup } from '@/features/hierarchies/utils'
import { SCOPE_COLORS, SCOPE_LABELS } from '@/features/hierarchies/utils'
import {
useCategorySystemOptions,
ALL_SYSTEMS_VALUE,
useAllSystemOptions
} from '@/features/hierarchies/hooks/useSystemOptions'
import {useTopics} from "@/features/topics/hooks/useTopics.ts";
interface ChainVisualizationProps {
group: ChainGroup
onEditStep: (hierarchyId: number) => void
onDeleteStep: (hierarchyId: number) => void
onAddStep: (group: ChainGroup) => void
onDuplicateChain: (group: ChainGroup) => void
onBulkUpdateSystem?: (group: ChainGroup, targetSystem: string | null) => void
}
const ScopeIcon = ({ type }: { type: string }) => {
switch (type) {
case 'global':
return <IconWorld size={13} />
case 'category':
return <IconCategory size={13} />
case 'topic':
return <IconFileText size={13} />
default:
return <IconWorld size={13} />
}
}
// Внутри компонента ChainVisualization:
export default function ChainVisualization({
group,
onEditStep,
onDeleteStep,
onAddStep,
onDuplicateChain,
onBulkUpdateSystem,
}: ChainVisualizationProps) {
// Получаем все темы, чтобы уметь мапить topicId -> categoryId, если scopeType === 'topic'
const { data: allTopics } = useTopics({ limit: 1000 })
const resolvedCategoryId = useMemo(() => {
if (group.scopeType === 'category') {
return group.scopeObjectId
}
if (group.scopeType === 'topic' && group.scopeObjectId && allTopics?.data) {
const foundTopic = allTopics.data.find(t => t.id === group.scopeObjectId)
return foundTopic?.category_id || null
}
return null
}, [group.scopeType, group.scopeObjectId, allTopics?.data])
// Если цепочка глобальная (resolvedCategoryId === null), берем вообще все системы через useAllSystemOptions,
// иначе — системы конкретной категории через useCategorySystemOptions.
const categoryOptionsResult = useCategorySystemOptions(resolvedCategoryId)
const allOptionsResult = useAllSystemOptions(group.scopeType === 'global')
const systemOptions = group.scopeType === 'global' ? allOptionsResult.options : categoryOptionsResult.options
console.log(`[ChainVisualization] Группа ${group.key} (scope: ${group.scopeType}): resolvedCategoryId = ${resolvedCategoryId}, доступно систем:`, systemOptions)
// Текущая система цепочки (если у всех шагов одинаковая система, иначе 'all')
const currentChainSystem = group.steps.every(
(s) => s.target_system === group.steps[0]?.target_system
)
? group.steps[0]?.target_system || ALL_SYSTEMS_VALUE
: ALL_SYSTEMS_VALUE
// Формируем опции для Select
const selectData = [
{ value: ALL_SYSTEMS_VALUE, label: 'Система: Все' },
...systemOptions.map((opt) => ({
value: opt.value,
label: `Система: ${opt.label}`,
})),
]
return (
<Paper
withBorder
p="lg"
style={{
backgroundColor: 'var(--mantine-color-white)',
borderColor: 'var(--mantine-color-gray-3)',
}}
>
{/* Заголовок группы */}
<Group justify="space-between" mb="lg">
<Group gap="md">
<Avatar size="md" radius="xl" color="gray" variant="filled">
{group.subordinateName.charAt(0).toUpperCase()}
</Avatar>
<Stack gap={0}>
<Text fw={600} size="sm" c="dark">
{group.subordinateName}
</Text>
<Text size="xs" c="dimmed">
{group.departmentName}
</Text>
</Stack>
<Divider orientation="vertical" />
<Badge
variant="outline"
color={SCOPE_COLORS[group.scopeType]}
leftSection={<ScopeIcon type={group.scopeType} />}
size="sm"
tt="none"
>
{SCOPE_LABELS[group.scopeType]}: {group.scopeObjectName}
</Badge>
{/* Выпадающий список систем отображается ТОЛЬКО если у темы/категории есть заданные systems */}
{systemOptions.length > 0 && (
<Select
size="xs"
leftSection={<IconServer size={14} />}
data={selectData}
value={currentChainSystem}
onChange={(val) => {
const newSystem = val === ALL_SYSTEMS_VALUE ? "" : val
if (onBulkUpdateSystem) {
onBulkUpdateSystem(group, newSystem)
}
}}
style={{ width: 180 }}
/>
)}
</Group>
<Group gap="xs">
<Tooltip label="Добавить шаг" withArrow>
<ActionIcon
variant="subtle"
color="gray"
size="md"
onClick={() => onAddStep(group)}
>
<IconPlus size={18} />
</ActionIcon>
</Tooltip>
<Tooltip label="Дублировать цепочку" withArrow>
<ActionIcon
variant="subtle"
color="gray"
size="md"
onClick={() => onDuplicateChain(group)}
>
<IconCopy size={18} />
</ActionIcon>
</Tooltip>
</Group>
</Group>
<Divider mb="lg" />
{/* Цепочка согласования */}
<Box style={{ overflowX: 'auto' }}>
<Group gap={0} wrap="nowrap" align="stretch">
{/* Карточка инициатора */}
<Paper
withBorder
p="md"
style={{
minWidth: 180,
borderColor: 'var(--mantine-color-gray-3)',
backgroundColor: 'var(--mantine-color-gray-0)',
}}
>
<Stack gap="xs" align="center">
<Text
size="xs"
fw={600}
c="dimmed"
tt="uppercase"
style={{ letterSpacing: '0.5px' }}
>
Инициатор
</Text>
<Avatar size="md" radius="xl" color="gray" variant="filled">
{group.subordinateName.charAt(0).toUpperCase()}
</Avatar>
<Text size="sm" fw={500} ta="center" lineClamp={2} c="dark">
{group.subordinateName}
</Text>
</Stack>
</Paper>
{/* Шаги согласования */}
{group.steps.map((step, index) => (
<Group key={step.id} gap={0} wrap="nowrap" align="stretch">
<Stack
gap={2}
align="center"
justify="center"
px="xs"
style={{ minWidth: 60 }}
>
<IconChevronRight size={20} color="var(--mantine-color-gray-5)" />
<Badge size="xs" variant="light" color="gray" tt="none">
{index + 1}
</Badge>
</Stack>
{/* Карточка согласующего */}
<Paper
withBorder
p="md"
style={{
minWidth: 180,
borderColor: 'var(--mantine-color-gray-3)',
backgroundColor: 'var(--mantine-color-white)',
cursor: 'pointer',
transition: 'border-color 0.15s ease',
position: 'relative',
}}
onClick={() => onEditStep(step.id!)}
onMouseEnter={(e) => {
e.currentTarget.style.borderColor = 'var(--mantine-color-blue-5)'
}}
onMouseLeave={(e) => {
e.currentTarget.style.borderColor = 'var(--mantine-color-gray-3)'
}}
>
<Stack gap="xs" align="center">
<Group gap={6}>
<Text
size="xs"
fw={600}
c="dimmed"
tt="uppercase"
style={{ letterSpacing: '0.5px' }}
>
Шаг {index + 1}
</Text>
<Badge size="xs" variant="light" color="gray" tt="none">
#{step.priority}
</Badge>
</Group>
<Avatar size="md" radius="xl" color="blue" variant="filled">
{step.approver?.full_name?.charAt(0).toUpperCase() || '?'}
</Avatar>
<Text size="sm" fw={500} ta="center" lineClamp={2} c="dark">
{step.approver?.full_name || '—'}
</Text>
{/* Бейдж конкретной целевой системы для шага (если выбрано) */}
{step.target_system && (
<Badge size="xs" color="cyan" variant="light">
Система: {step.target_system}
</Badge>
)}
<Divider style={{ width: '100%', margin: '4px 0' }} />
<Group gap="xs" justify="center">
<Tooltip label="Редактировать" withArrow>
<ActionIcon
variant="subtle"
color="gray"
size="sm"
onClick={(e) => {
e.stopPropagation()
onEditStep(step.id!)
}}
>
<IconPencil size={14} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить" withArrow>
<ActionIcon
variant="subtle"
color="red"
size="sm"
onClick={(e) => {
e.stopPropagation()
onDeleteStep(step.id!)
}}
>
<IconTrash size={14} />
</ActionIcon>
</Tooltip>
</Group>
</Stack>
</Paper>
</Group>
))}
</Group>
</Box>
</Paper>
)
}
-----END src/pages/hierarchies/components/ChainVisualization.tsx-----
File: src/pages/hierarchies/components/HierarchyEditModal.tsx
Lines: 420
-----BEGIN src/pages/hierarchies/components/HierarchyEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
Select,
NumberInput,
Group,
Button,
Text,
Badge,
Paper,
Alert,
Radio,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconInfoCircle, IconAlertCircle, IconCopy } from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import {
useCreateHierarchy,
useUpdateHierarchy
} from '@/features/hierarchies/hooks/useHierarchies'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
import type { UserHierarchy } from '@/types/api'
import type { ChainGroup } from '@/features/hierarchies/utils'
import { useAllSystemOptions } from '@/features/hierarchies/hooks/useSystemOptions'
interface HierarchyEditModalProps {
hierarchy: UserHierarchy | null
presetGroup?: ChainGroup | null // Для добавления шага в существующую группу
opened: boolean
onClose: () => void
}
type ScopeType = 'global' | 'category' | 'topic'
export default function HierarchyEditModal({
hierarchy,
presetGroup,
opened,
onClose
}: HierarchyEditModalProps) {
const createHierarchy = useCreateHierarchy()
const updateHierarchy = useUpdateHierarchy()
const { data: users } = useUsers({ limit: 1000 })
const { data: departments } = useDepartments()
const { data: categories } = useCategories({ limit: 1000 })
const { options: systemOptions } = useAllSystemOptions()
const isEditMode = hierarchy !== null
const form = useForm({
initialValues: {
subordinate_id: null as number | null,
approver_id: null as number | null,
department_id: null as number | null,
scope_type: 'global' as ScopeType,
topic_category_id: null as number | null,
topic_id: null as number | null,
priority: 0,
target_system: null as string | null
},
validate: {
subordinate_id: (v) => (v === null ? 'Выберите подчинённого' : null),
approver_id: (v) => (v === null ? 'Выберите согласующего' : null),
// department_id/topic_category_id/topic_id заблокированы в режиме
// редактирования (см. disabled ниже) — если их всё же валидировать
// как обязательные, а на самой записи значение почему-то пустое,
// форма зависает намертво: поле нельзя ни заполнить (заблокировано),
// ни пропустить (обязательное).
department_id: (v) => (!isEditMode && v === null ? 'Выберите отдел' : null),
topic_category_id: (v, values) => {
if (isEditMode) return null
if ((values.scope_type === 'category' || values.scope_type === 'topic') && v === null) {
return 'Выберите категорию'
}
return null
},
topic_id: (v, values) => {
if (isEditMode) return null
if (values.scope_type === 'topic' && v === null) {
return 'Выберите тему'
}
return null
},
},
})
// Темы выбранной категории — для выпадающего списка "Тема" при создании.
const { data: categoryTopics } = useTopics({
limit: 1000,
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
})
// Полный список тем без фильтра — нужен, чтобы восстановить
// topic_category_id по topic_id (см. useEffect ниже), когда сама
// категория не сохранена явно — и на записи из БД (режим редактирования),
// и в presetGroup (добавление шага в существующую цепочку с областью
// действия "тема" — это и был баг №5).
const { data: allTopics } = useTopics({ limit: 1000 })
// Заполняем форму данными
useEffect(() => {
if (hierarchy) {
let scopeType: ScopeType = 'global'
if (hierarchy.topic_id) scopeType = 'topic'
else if (hierarchy.topic_category_id) scopeType = 'category'
let resolvedCategoryId = hierarchy.topic_category_id || null
if (scopeType === 'topic' && !resolvedCategoryId && allTopics?.data) {
const matchedTopic = allTopics.data.find((t) => t.id === hierarchy.topic_id)
resolvedCategoryId = matchedTopic?.category_id || null
}
form.setValues({
subordinate_id: hierarchy.subordinate_id || null,
approver_id: hierarchy.approver_id || null,
department_id: hierarchy.department_id || null,
scope_type: scopeType,
topic_category_id: resolvedCategoryId,
topic_id: hierarchy.topic_id || null,
target_system: hierarchy.target_system || null,
priority: hierarchy.priority ?? 0,
})
} else if (presetGroup) {
let resolvedCategoryId: number | null = null
if (presetGroup.scopeType === 'category') {
resolvedCategoryId = presetGroup.scopeObjectId
} else if (presetGroup.scopeType === 'topic') {
const matchedTopic = allTopics?.data?.find((t) => t.id === presetGroup.scopeObjectId)
resolvedCategoryId = matchedTopic?.category_id || null
}
form.setValues({
subordinate_id: presetGroup.subordinateId,
department_id: presetGroup.departmentId,
scope_type: presetGroup.scopeType,
topic_category_id: resolvedCategoryId,
topic_id: presetGroup.scopeType === 'topic' ? presetGroup.scopeObjectId : null,
priority: presetGroup.steps.length, // Следующий priority
approver_id: null,
})
} else {
form.reset()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hierarchy, presetGroup, opened, allTopics])
const handleScopeTypeChange = (value: ScopeType) => {
form.setFieldValue('scope_type', value)
if (value === 'global') {
form.setFieldValue('topic_category_id', null)
form.setFieldValue('topic_id', null)
} else if (value === 'category') {
form.setFieldValue('topic_id', null)
}
}
// Опции
const userOptions = users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const departmentOptions = departments?.data?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || []
const categoryOptions = categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions = categoryTopics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const buildPayload = (values: typeof form.values) => ({
subordinate_id: values.subordinate_id!,
approver_id: values.approver_id!,
department_id: values.department_id!,
priority: values.priority,
target_system: values.target_system || null,
topic_category_id: values.scope_type === 'global' ? null :
values.scope_type === 'category' ? values.topic_category_id : null,
topic_id: values.scope_type === 'topic' ? values.topic_id : null,
})
const handleSubmit = async (values: typeof form.values) => {
const payload = buildPayload(values)
if (isEditMode && hierarchy?.id) {
await updateHierarchy.mutateAsync({
id: hierarchy.id,
...payload,
})
} else {
await createHierarchy.mutateAsync(payload)
}
onClose()
}
// НОВОЕ (пункт 3): дублирование прямо из окна редактирования — создаёт
// новую запись с теми же значениями, что сейчас на экране, не трогая
// ту, что редактируется. Доступно только в режиме редактирования —
// дублировать ещё не сохранённую форму нечего.
const handleDuplicate = async () => {
if (!isEditMode) return
try {
await createHierarchy.mutateAsync(buildPayload(form.values))
notifications.show({
title: 'Успешно',
message: 'Связь продублирована — можно найти копию в списке и отредактировать при необходимости',
color: 'green',
})
onClose()
} catch (error) {
notifications.show({
title: 'Ошибка',
message: 'Не удалось продублировать связь',
color: 'red',
})
}
}
const isSubmitting = createHierarchy.isPending || updateHierarchy.isPending
const hasErrors = Object.keys(form.errors).length > 0
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>
{isEditMode ? 'Редактирование связи' : 'Добавление связи'}
</Text>
{hierarchy && <Badge variant="light">ID: {hierarchy.id}</Badge>}
</Group>
}
size="lg"
>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
{hasErrors && (
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
<Text size="sm">Проверьте поля, отмеченные красным, ниже.</Text>
</Alert>
)}
<Select
label="Сотрудник (инициатор)"
placeholder="Выберите пользователя"
data={userOptions}
value={form.values.subordinate_id ? String(form.values.subordinate_id) : null}
onChange={(v) => form.setFieldValue('subordinate_id', v ? Number(v) : null)}
searchable
required
disabled={!!presetGroup}
description="Пользователь, для которого настраивается согласование"
error={form.errors.subordinate_id}
/>
{/* Отдел */}
<Select
label="Отдел"
placeholder="Выберите отдел"
data={departmentOptions}
value={form.values.department_id ? String(form.values.department_id) : null}
onChange={(v) => form.setFieldValue('department_id', v ? Number(v) : null)}
searchable
required={!isEditMode}
disabled={isEditMode || !!presetGroup}
error={form.errors.department_id}
/>
{/* Согласующий */}
<Select
label="Согласующий"
placeholder="Выберите пользователя"
data={userOptions}
value={form.values.approver_id ? String(form.values.approver_id) : null}
onChange={(v) => form.setFieldValue('approver_id', v ? Number(v) : null)}
searchable
required
description="Пользователь, который будет согласовывать заявки"
error={form.errors.approver_id}
/>
{/* Область действия */}
<Paper withBorder p="md">
<Text size="sm" fw={500} mb="sm">
Область действия
</Text>
<Radio.Group
value={form.values.scope_type}
onChange={(v) => handleScopeTypeChange(v as ScopeType)}
>
<Stack gap="xs">
<Radio
value="global"
label="Глобальное правило"
description="Для всех тем согласований"
disabled={isEditMode}
/>
<Radio
value="category"
label="Для категории тем"
description="Только для тем выбранной категории"
disabled={isEditMode}
/>
<Radio
value="topic"
label="Для конкретной темы"
description="Только для выбранной темы"
disabled={isEditMode}
/>
</Stack>
</Radio.Group>
</Paper>
{/* Категория */}
{(form.values.scope_type === 'category' || form.values.scope_type === 'topic') && (
<Select
label="Категория"
placeholder="Выберите категорию"
data={categoryOptions}
value={form.values.topic_category_id ? String(form.values.topic_category_id) : null}
onChange={(v) => {
form.setFieldValue('topic_category_id', v ? Number(v) : null)
form.setFieldValue('topic_id', null)
}}
searchable
required={!isEditMode}
disabled={isEditMode || !!presetGroup}
error={form.errors.topic_category_id}
/>
)}
{/* Тема */}
{form.values.scope_type === 'topic' && (
<Select
label="Тема"
placeholder="Выберите тему"
data={topicOptions}
value={form.values.topic_id ? String(form.values.topic_id) : null}
onChange={(v) => form.setFieldValue('topic_id', v ? Number(v) : null)}
searchable
required={!isEditMode}
disabled={!form.values.topic_category_id || isEditMode || !!presetGroup}
description={!form.values.topic_category_id && !isEditMode ? 'Сначала выберите категорию' : undefined}
error={form.errors.topic_id}
/>
)}
<Select
label="Целевая система шага"
placeholder="Все системы (по умолчанию)"
data={[
{ value: 'all', label: 'Все системы' },
...systemOptions.map((s) => ({ value: s.value, label: s.label })),
]}
value={form.values.target_system || 'all'}
onChange={(v) => form.setFieldValue('target_system', (v === 'all' || !v) ? "" : v)}
description="Укажите систему, если данный шаг согласующего применяется только к определенной системе"
/>
{/* Priority */}
<NumberInput
label="Порядок шага (priority)"
description="0 = первый шаг, 1 = второй и т.д."
value={form.values.priority}
onChange={(v) => form.setFieldValue('priority', Number(v) || 0)}
min={0}
required
/>
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
<Text size="sm">
Шаги выполняются последовательно в порядке возрастания priority.
Заявка переходит к следующему согласующему только после одобрения предыдущим.
{isEditMode && ' Область действия и отдел при редактировании не меняются — чтобы поменять их, удалите связь и создайте новую.'}
</Text>
</Alert>
{/* Кнопки */}
<Group justify="space-between" mt="md">
{isEditMode ? (
<Button
variant="light"
color="teal"
leftSection={<IconCopy size={16} />}
onClick={handleDuplicate}
disabled={isSubmitting}
>
Дублировать
</Button>
) : (
<div />
)}
<Group>
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
{isEditMode ? 'Сохранить' : 'Создать'}
</Button>
</Group>
</Group>
</Stack>
</form>
</Modal>
)
}
-----END src/pages/hierarchies/components/HierarchyEditModal.tsx-----
File: src/pages/hierarchies/components/PersonDuplicateModal.tsx
Lines: 197
-----BEGIN src/pages/hierarchies/components/PersonDuplicateModal.tsx-----
import { useState } from 'react'
import {
Modal,
Stack,
Select,
Group,
Button,
Text,
Paper,
Alert,
Badge,
Loader,
Center,
} from '@mantine/core'
import { IconInfoCircle, IconUsers } from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import { useHierarchies, useCreateHierarchy } from '@/features/hierarchies/hooks/useHierarchies'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
interface PersonDuplicateModalProps {
opened: boolean
onClose: () => void
}
// 0 — заведомо несуществующий id пользователя, чтобы не дёргать хук
// условно (нарушает Rules of Hooks) и не гадать, как бэкенд обработает
// limit:0 — просто явно просим "ничего не найдётся".
const NO_USER_SENTINEL = 0
export default function PersonDuplicateModal({ opened, onClose }: PersonDuplicateModalProps) {
const [sourceId, setSourceId] = useState<string | null>(null)
const [targetId, setTargetId] = useState<string | null>(null)
const [isDuplicating, setIsDuplicating] = useState(false)
const { data: users } = useUsers({ limit: 1000 })
const { data: categories } = useCategories({ limit: 1000 })
const { data: topics } = useTopics({ limit: 1000 })
const createHierarchy = useCreateHierarchy()
// Все связи исходного сотрудника — по всем областям действия сразу
// (глобальные + по категориям + по темам), без пагинации.
const { data: sourceHierarchies, isLoading: sourceLoading } = useHierarchies({
subordinate_id: sourceId ? Number(sourceId) : NO_USER_SENTINEL,
limit: 1000,
})
const sourceRows = sourceId ? sourceHierarchies?.data || [] : []
const userOptions = users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const describeScope = (h: { topic_id?: number | null; topic_category_id?: number | null }) => {
if (h.topic_id) {
const t = topics?.data?.find((t) => t.id === h.topic_id)
return `Тема: ${t?.name || `#${h.topic_id}`}`
}
if (h.topic_category_id) {
const c = categories?.data?.find((c) => c.id === h.topic_category_id)
return `Категория: ${c?.name || `#${h.topic_category_id}`}`
}
return 'Глобально'
}
const handleClose = () => {
setSourceId(null)
setTargetId(null)
onClose()
}
const handleDuplicate = async () => {
if (!sourceId || !targetId || sourceRows.length === 0) return
setIsDuplicating(true)
try {
// Последовательно, а не Promise.all — чтобы не заваливать API
// залпом при большом количестве связей у сотрудника, и чтобы
// при ошибке было понятно, на какой именно записи остановились.
for (const h of sourceRows) {
if (!h.approver_id || !h.department_id) continue
await createHierarchy.mutateAsync({
subordinate_id: Number(targetId),
approver_id: h.approver_id,
department_id: h.department_id,
priority: h.priority ?? 0,
topic_category_id: h.topic_category_id ?? null,
topic_id: h.topic_id ?? null,
})
}
notifications.show({
title: 'Успешно',
message: `Продублировано связей: ${sourceRows.length}`,
color: 'green',
})
handleClose()
} catch (error) {
notifications.show({
title: 'Ошибка',
message: 'Не удалось продублировать связи — часть могла успеть создаться, проверьте список',
color: 'red',
})
} finally {
setIsDuplicating(false)
}
}
return (
<Modal
opened={opened}
onClose={handleClose}
title={
<Group gap="xs">
<IconUsers size={20} />
<Text fw={600}>Дублировать все связи сотрудника</Text>
</Group>
}
size="lg"
centered
>
<Stack gap="md">
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
<Text size="sm">
Скопирует ВСЕ цепочки согласования выбранного сотрудника — глобальные, по
категориям и по темам — для нового сотрудника. Отдел, согласующие,
категории/темы и порядок шагов сохранятся как на образце.
</Text>
</Alert>
<Select
label="От кого копировать (образец)"
placeholder="Выберите сотрудника, чьи связи нужно скопировать"
data={userOptions.filter((o) => o.value !== targetId)}
value={sourceId}
onChange={setSourceId}
searchable
required
/>
<Select
label="Кому назначить такие же связи"
placeholder="Выберите нового сотрудника"
data={userOptions.filter((o) => o.value !== sourceId)}
value={targetId}
onChange={setTargetId}
searchable
required
disabled={!sourceId}
/>
{sourceId && (
<Paper withBorder p="md" bg="gray.0">
<Text size="xs" fw={600} c="dimmed" mb="xs" tt="uppercase">
Будет продублировано
</Text>
{sourceLoading ? (
<Center p="md">
<Loader size="sm" />
</Center>
) : sourceRows.length === 0 ? (
<Text size="sm" c="dimmed">
У этого сотрудника нет ни одной настроенной связи — дублировать нечего.
</Text>
) : (
<Stack gap={6}>
{sourceRows.map((h) => (
<Group key={h.id} justify="space-between" wrap="nowrap">
<Text size="sm">
{h.approver?.full_name || `Согласующий #${h.approver_id}`}
</Text>
<Badge size="xs" variant="light" color="gray" tt="none">
{describeScope(h)}
</Badge>
</Group>
))}
</Stack>
)}
</Paper>
)}
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={handleClose} disabled={isDuplicating}>
Отмена
</Button>
<Button
onClick={handleDuplicate}
loading={isDuplicating}
disabled={!sourceId || !targetId || sourceRows.length === 0}
>
{sourceRows.length > 0 ? `Продублировать (${sourceRows.length})` : 'Продублировать'}
</Button>
</Group>
</Stack>
</Modal>
)
}
-----END src/pages/hierarchies/components/PersonDuplicateModal.tsx-----
File: src/pages/notifications/NotificationsPage.tsx
Lines: 44
-----BEGIN src/pages/notifications/NotificationsPage.tsx-----
import { Stack, Tabs, Text, Alert } from '@mantine/core'
import { IconSend, IconHistory, IconLock } from '@tabler/icons-react'
import { useAuth } from '@/hooks/useAuth'
import SendNotificationForm from './components/SendNotificationForm'
import NotificationsHistoryTable from './components/NotificationsHistoryTable'
export default function NotificationsPage() {
const { user } = useAuth()
const isObserver = user?.is_observer === true
return (
<Stack gap="md">
<Text size="xl" fw={700}>Уведомления</Text>
<Tabs defaultValue={isObserver ? 'history' : 'send'}>
<Tabs.List>
{!isObserver && (
<Tabs.Tab value="send" leftSection={<IconSend size={16} />}>
Отправить
</Tabs.Tab>
)}
<Tabs.Tab value="history" leftSection={<IconHistory size={16} />}>
История
</Tabs.Tab>
</Tabs.List>
{!isObserver && (
<Tabs.Panel value="send" pt="md">
<SendNotificationForm />
</Tabs.Panel>
)}
<Tabs.Panel value="history" pt="md">
<NotificationsHistoryTable />
</Tabs.Panel>
</Tabs>
{isObserver && (
<Alert color="blue" variant="light" icon={<IconLock size={16} />}>
В режиме наблюдателя доступен только просмотр истории уведомлений
</Alert>
)}
</Stack>
)
}
-----END src/pages/notifications/NotificationsPage.tsx-----
File: src/pages/notifications/components/NotificationDetailsModal.tsx
Lines: 74
-----BEGIN src/pages/notifications/components/NotificationDetailsModal.tsx-----
import { useNotification } from '@/features/notifications/hooks/useNotifications'
import { Modal, Stack, Text, Badge, ScrollArea, Table, Divider, Loader, Center } from '@mantine/core'
interface Props {
notificationId: number | null
opened: boolean
onClose: () => void
}
const RECIPIENT_STATUS_LABELS: Record<string, { label: string; color: string }> = {
pending: { label: 'В очереди', color: 'gray' },
sent: { label: 'Доставлено', color: 'green' },
failed: { label: 'Ошибка', color: 'red' },
}
export default function NotificationDetailsModal({ notificationId, opened, onClose }: Props) {
const { data: notification, isLoading } = useNotification(notificationId)
return (
<Modal opened={opened} onClose={onClose} title="Детали уведомления" size="lg">
{isLoading || !notification ? (
<Center p={40}>
<Loader />
</Center>
) : (
<Stack gap="md">
<Stack gap={4}>
<Text fw={600}>{notification.title}</Text>
<div
style={{ fontSize: 14 }}
dangerouslySetInnerHTML={{ __html: notification.message_html }}
/>
</Stack>
<Divider label="Получатели" labelPosition="left" />
<ScrollArea h={300}>
<Table striped>
<Table.Thead>
<Table.Tr>
<Table.Th>Пользователь</Table.Th>
<Table.Th style={{ width: 120 }}>Статус</Table.Th>
<Table.Th>Ошибка</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{(notification.recipients || []).map((r) => {
const statusInfo = RECIPIENT_STATUS_LABELS[r.status || ''] || {
label: r.status || '—',
color: 'gray',
}
return (
<Table.Tr key={r.id}>
<Table.Td>{r.user?.full_name || `ID ${r.user_id}`}</Table.Td>
<Table.Td>
<Badge color={statusInfo.color} variant="light" size="sm">
{statusInfo.label}
</Badge>
</Table.Td>
<Table.Td>
<Text size="xs" c="red">
{r.error_message || ''}
</Text>
</Table.Td>
</Table.Tr>
)
})}
</Table.Tbody>
</Table>
</ScrollArea>
</Stack>
)}
</Modal>
)
}
-----END src/pages/notifications/components/NotificationDetailsModal.tsx-----
File: src/pages/notifications/components/NotificationsHistoryTable.tsx
Lines: 124
-----BEGIN src/pages/notifications/components/NotificationsHistoryTable.tsx-----
import { useState } from 'react'
import {
Paper, Table, Badge, Group, Text, Pagination, Loader, Center, Box, Stack,
} from '@mantine/core'
import NotificationDetailsModal from './NotificationDetailsModal'
import { useNotifications } from '@/features/notifications/hooks/useNotifications'
const LIMIT = 20
const STATUS_LABELS: Record<string, { label: string; color: string }> = {
pending: { label: 'В очереди', color: 'gray' },
sending: { label: 'Отправляется', color: 'blue' },
completed: { label: 'Завершено', color: 'green' },
failed: { label: 'Ошибка', color: 'red' },
}
export default function NotificationsHistoryTable() {
const [page, setPage] = useState(1)
const [selectedId, setSelectedId] = useState<number | null>(null)
const { data, isLoading } = useNotifications({
offset: (page - 1) * LIMIT,
limit: LIMIT,
})
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
return (
<Stack gap="md">
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Заголовок</Table.Th>
<Table.Th style={{ width: 120 }}>Статус</Table.Th>
<Table.Th style={{ width: 160 }}>Доставлено</Table.Th>
<Table.Th style={{ width: 160 }}>Дата отправки</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={5}>
<Center p={40}>
<Text c="dimmed">Уведомления не отправлялись</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).map((n) => {
const statusInfo = STATUS_LABELS[n.status || ''] || {
label: n.status || '—',
color: 'gray',
}
return (
<Table.Tr
key={n.id}
style={{ cursor: 'pointer' }}
onClick={() => setSelectedId(n.id!)}
>
<Table.Td>{n.id}</Table.Td>
<Table.Td>
<Text fw={500}>{n.title}</Text>
</Table.Td>
<Table.Td>
<Badge color={statusInfo.color} variant="light">
{statusInfo.label}
</Badge>
</Table.Td>
<Table.Td>
<Group gap={6}>
<Badge color="green" variant="light" size="sm">
{n.sent_count ?? 0}
</Badge>
{(n.failed_count ?? 0) > 0 && (
<Badge color="red" variant="light" size="sm">
{n.failed_count} ошибок
</Badge>
)}
<Text size="xs" c="dimmed">
из {n.total_count ?? 0}
</Text>
</Group>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">
{n.sent_at ? new Date(n.sent_at).toLocaleString('ru-RU') : '—'}
</Text>
</Table.Td>
</Table.Tr>
)
})
)}
</Table.Tbody>
</Table>
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination value={page} onChange={setPage} total={totalPages} withEdges />
</Group>
</Box>
)}
</>
)}
</Paper>
<NotificationDetailsModal
notificationId={selectedId}
opened={selectedId !== null}
onClose={() => setSelectedId(null)}
/>
</Stack>
)
}
-----END src/pages/notifications/components/NotificationsHistoryTable.tsx-----
File: src/pages/notifications/components/SendNotificationForm.tsx
Lines: 445
-----BEGIN src/pages/notifications/components/SendNotificationForm.tsx-----
import { useState, useMemo } from 'react'
import {
Paper, Stack, TextInput, Button, Group, MultiSelect, Checkbox,
Text, FileButton, Image, ActionIcon, Divider, Alert, Badge, Grid,
ThemeIcon,
} from '@mantine/core'
import {
IconPhoto, IconX, IconSend, IconAlertCircle, IconUsers,
IconUser, IconMask, IconBuilding, IconTag, IconEye, IconMessage,
} from '@tabler/icons-react'
import { RichTextEditor, Link } from '@mantine/tiptap'
import { useEditor } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import Underline from '@tiptap/extension-underline'
import { useDebouncedValue } from '@mantine/hooks'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useAllRoles } from '@/features/roles/hooks/useAllRoles'
import { useCreateNotification } from '@/features/notifications/hooks/useNotifications.ts'
import { convertHtmlToTelegram } from '@/features/notifications/utils/telegramHtml.ts'
import { notifications } from '@mantine/notifications'
import { Modal } from '@mantine/core'
import '@mantine/tiptap/styles.css'
const ROLE_TYPE_OPTIONS = [
{ value: 'director', label: 'Директора', icon: '👔' },
{ value: 'approver', label: 'Согласующие', icon: '✅' },
{ value: 'observer', label: 'Наблюдатели', icon: '👀' },
{ value: 'executor', label: 'Исполнители', icon: '⚙️' },
{ value: 'controller', label: 'Контролёры', icon: '🎯' },
]
export default function SendNotificationForm() {
const [title, setTitle] = useState('')
const [userSearch, setUserSearch] = useState('')
const [debouncedUserSearch] = useDebouncedValue(userSearch, 300)
const [selectedUserIds, setSelectedUserIds] = useState<string[]>([])
const [selectedRoleIds, setSelectedRoleIds] = useState<string[]>([])
const [selectedRoleFlags, setSelectedRoleFlags] = useState<string[]>([])
const [selectedDepartmentIds, setSelectedDepartmentIds] = useState<string[]>([])
const [photoBase64, setPhotoBase64] = useState<string | null>(null)
const [photoFileName, setPhotoFileName] = useState<string | null>(null)
const [photoPreviewUrl, setPhotoPreviewUrl] = useState<string | null>(null)
const [confirmOpen, setConfirmOpen] = useState(false)
const { data: usersData } = useUsers({
limit: 50,
...(debouncedUserSearch && { full_name: debouncedUserSearch }),
})
const { data: roles = [] } = useAllRoles()
const { data: departmentsResponse } = useDepartments({ limit: 1000 })
const departments = departmentsResponse?.data || []
const createNotification = useCreateNotification()
const editor = useEditor({
extensions: [StarterKit, Underline, Link],
content: '',
})
const userOptions = useMemo(
() => (usersData?.data || []).map((u) => ({
value: String(u.id),
label: u.full_name + (u.username ? ` (@${u.username})` : ''),
})),
[usersData],
)
const roleOptions = useMemo(
() => roles.map((r) => ({ value: String(r.id), label: r.name })),
[roles],
)
const departmentOptions = useMemo(
() => departments.map((d) => ({ value: String(d.id), label: d.name })),
[departments],
)
const MAX_ASPECT_RATIO = 20
const handlePhotoChange = (file: File | null) => {
if (!file) {
setPhotoBase64(null)
setPhotoFileName(null)
setPhotoPreviewUrl(null)
return
}
const reader = new FileReader()
reader.onload = () => {
const result = reader.result as string
const img = new window.Image()
img.onload = () => {
const ratio = Math.max(img.width, img.height) / Math.min(img.width, img.height)
const sumDimensions = img.width + img.height
if (ratio > MAX_ASPECT_RATIO || sumDimensions > 10000) {
notifications.show({
title: 'Некорректное изображение',
message: `Telegram не примет это фото: слишком вытянутые пропорции (${img.width}×${img.height}).`,
color: 'red',
})
return
}
setPhotoBase64(result.split(',')[1] || '')
setPhotoFileName(file.name)
setPhotoPreviewUrl(result)
}
img.src = result
}
reader.readAsDataURL(file)
}
const hasAnyTarget =
selectedUserIds.length > 0 ||
selectedRoleIds.length > 0 ||
selectedRoleFlags.length > 0 ||
selectedDepartmentIds.length > 0
const messageHtml = editor?.getHTML() ?? ''
const messageText = editor?.getText() ?? ''
const isMessageEmpty = editor?.isEmpty ?? true
const canSubmit = title.trim().length > 0 && !isMessageEmpty && hasAnyTarget
const totalCriteria =
(selectedUserIds.length > 0 ? 1 : 0) +
(selectedRoleIds.length > 0 ? 1 : 0) +
(selectedRoleFlags.length > 0 ? 1 : 0) +
(selectedDepartmentIds.length > 0 ? 1 : 0)
const doSubmit = () => {
setConfirmOpen(false)
createNotification.mutate(
{
title: title.trim(),
message_html: convertHtmlToTelegram(messageHtml),
photo_base64: photoBase64 || undefined,
photo_file_name: photoFileName || undefined,
targets: {
user_ids: selectedUserIds.map(Number),
role_ids: selectedRoleIds.map(Number),
role_type_flags: selectedRoleFlags,
department_ids: selectedDepartmentIds.map(Number),
},
},
{
onSuccess: () => {
setTitle('')
editor?.commands.clearContent()
setSelectedUserIds([])
setSelectedRoleIds([])
setSelectedRoleFlags([])
setSelectedDepartmentIds([])
handlePhotoChange(null)
notifications.show({
title: 'Успешно',
message: 'Уведомление отправлено',
color: 'green',
})
},
},
)
}
return (
<Paper withBorder p={{ base: 'md', md: 'xl' }} radius="md">
{/* ===== HEADER ===== */}
<Group justify="space-between" align="center" mb="lg">
<Group gap="sm">
<ThemeIcon size="lg" radius="md" variant="light" color="blue">
<IconMessage size={20} />
</ThemeIcon>
<div>
<Text size="xl" fw={700}>Новая рассылка</Text>
<Text size="xs" c="dimmed">Отправится через Telegram Bot</Text>
</div>
</Group>
{totalCriteria > 0 && (
<Badge size="lg" variant="light" color="blue" radius="sm">
{totalCriteria} {totalCriteria === 1 ? 'критерий' : 'критериев'}
</Badge>
)}
</Group>
<Grid gap="xl">
<Grid.Col span={{ base: 12, lg: 7 }}>
<Stack gap="lg">
<TextInput
label="Заголовок рассылки"
description="Только для админки, в Telegram не отправляется"
placeholder="Плановые работы 15 июля"
value={title}
onChange={(e) => setTitle(e.currentTarget.value)}
required
size="md"
/>
{/* Редактор */}
<Stack gap={6}>
<Group justify="space-between" align="center">
<Text size="sm" fw={500}>Текст сообщения</Text>
{!isMessageEmpty && (
<Badge size="xs" variant="light" color="green" leftSection={<IconEye size={10} />}>
Заполнено
</Badge>
)}
</Group>
<RichTextEditor editor={editor} style={{ minHeight: 320 }}>
<RichTextEditor.Toolbar sticky stickyOffset={0}>
<RichTextEditor.ControlsGroup>
<RichTextEditor.Bold />
<RichTextEditor.Italic />
<RichTextEditor.Underline />
<RichTextEditor.Strikethrough />
</RichTextEditor.ControlsGroup>
<RichTextEditor.ControlsGroup>
<RichTextEditor.Code />
<RichTextEditor.CodeBlock />
<RichTextEditor.ClearFormatting />
</RichTextEditor.ControlsGroup>
<RichTextEditor.ControlsGroup>
<RichTextEditor.Link />
<RichTextEditor.Unlink />
</RichTextEditor.ControlsGroup>
</RichTextEditor.Toolbar>
<RichTextEditor.Content style={{ minHeight: 220 }} />
</RichTextEditor>
<Text size="xs" c="dimmed">
<b>жирный</b> · <i>курсив</i> · <u>подчёркнутый</u> · <s>зачёркнутый</s> · <code>код</code> · ссылки — остальное Telegram не отобразит
</Text>
</Stack>
{/* Фото */}
<Stack gap={6}>
<Text size="sm" fw={500}>Фото (опционально)</Text>
{photoPreviewUrl ? (
<Group gap="sm">
<Paper withBorder p={4} radius="sm">
<Image src={photoPreviewUrl} h={90} w={90} radius="sm" fit="cover" />
</Paper>
<Stack gap={2} style={{ flex: 1 }}>
<Text size="sm" fw={500} lineClamp={1}>{photoFileName}</Text>
<Text size="xs" c="dimmed">Готово к отправке</Text>
</Stack>
<ActionIcon
color="red"
variant="light"
onClick={() => handlePhotoChange(null)}
>
<IconX size={16} />
</ActionIcon>
</Group>
) : (
<FileButton onChange={handlePhotoChange} accept="image/png,image/jpeg,image/webp">
{(props) => (
<Button {...props} variant="light" leftSection={<IconPhoto size={16} />}>
Прикрепить фото
</Button>
)}
</FileButton>
)}
</Stack>
</Stack>
</Grid.Col>
{/* ===== ПРАВАЯ КОЛОНКА: ПОЛУЧАТЕЛИ + ПРЕВЬЮ ===== */}
<Grid.Col span={{ base: 12, lg: 5 }}>
<Stack gap="lg">
{/* Получатели */}
<Paper withBorder p="md" radius="md">
<Group justify="space-between" mb="md">
<Group gap="xs">
<ThemeIcon size="sm" variant="light" color="violet">
<IconUsers size={14} />
</ThemeIcon>
<Text size="sm" fw={600}>Получатели</Text>
</Group>
{hasAnyTarget && (
<Badge size="xs" variant="light" color="violet">
Настроено
</Badge>
)}
</Group>
<Stack gap="md">
<MultiSelect
label={
<Group gap={4}>
<IconUser size={14} />
<Text size="sm" span>Конкретные пользователи</Text>
{selectedUserIds.length > 0 && (
<Badge size="xs" variant="filled" circle>{selectedUserIds.length}</Badge>
)}
</Group>
}
placeholder="Начните вводить имя..."
data={userOptions}
value={selectedUserIds}
onChange={setSelectedUserIds}
searchable
searchValue={userSearch}
onSearchChange={setUserSearch}
clearable
nothingFoundMessage="Никого не найдено"
size="xs"
/>
<MultiSelect
label={
<Group gap={4}>
<IconMask size={14} />
<Text size="sm" span>Роли</Text>
{selectedRoleIds.length > 0 && (
<Badge size="xs" variant="filled" circle>{selectedRoleIds.length}</Badge>
)}
</Group>
}
placeholder="Выберите роли"
data={roleOptions}
value={selectedRoleIds}
onChange={setSelectedRoleIds}
searchable
clearable
size="xs"
/>
<Stack gap={6}>
<Group gap={4}>
<IconTag size={14} />
<Text size="sm" span>Тип роли</Text>
{selectedRoleFlags.length > 0 && (
<Badge size="xs" variant="filled" circle>{selectedRoleFlags.length}</Badge>
)}
</Group>
<Checkbox.Group value={selectedRoleFlags} onChange={setSelectedRoleFlags}>
<Stack gap={6}>
{ROLE_TYPE_OPTIONS.map((opt) => (
<Checkbox
key={opt.value}
value={opt.value}
label={
<Group gap={6}>
<Text size="sm">{opt.icon}</Text>
<Text size="sm">{opt.label}</Text>
</Group>
}
/>
))}
</Stack>
</Checkbox.Group>
</Stack>
<MultiSelect
label={
<Group gap={4}>
<IconBuilding size={14} />
<Text size="sm" span>Отделы</Text>
{selectedDepartmentIds.length > 0 && (
<Badge size="xs" variant="filled" circle>{selectedDepartmentIds.length}</Badge>
)}
</Group>
}
placeholder="Выберите отделы"
data={departmentOptions}
value={selectedDepartmentIds}
onChange={setSelectedDepartmentIds}
searchable
clearable
size="xs"
/>
{!hasAnyTarget && (
<Alert color="blue" variant="light" icon={<IconAlertCircle size={16} />} p="xs">
<Text size="xs">Выберите хотя бы один способ определения получателей</Text>
</Alert>
)}
</Stack>
</Paper>
{/* Кнопка отправки */}
<Button
fullWidth
size="md"
leftSection={<IconSend size={18} />}
onClick={() => setConfirmOpen(true)}
loading={createNotification.isPending}
disabled={!canSubmit}
>
Отправить уведомление
</Button>
</Stack>
</Grid.Col>
</Grid>
{/* ===== МОДАЛКА ПОДТВЕРЖДЕНИЯ ===== */}
<Modal
opened={confirmOpen}
onClose={() => setConfirmOpen(false)}
title="Подтверждение отправки"
centered
>
<Stack gap="md">
<Text size="sm">
Отправить уведомление <b>«{title.trim()}»</b>?
</Text>
<Paper withBorder p="sm" radius="sm">
<Stack gap={4}>
{selectedUserIds.length > 0 && (
<Group justify="space-between">
<Text size="xs" c="dimmed">Пользователей</Text>
<Text size="sm" fw={500}>{selectedUserIds.length}</Text>
</Group>
)}
{selectedRoleIds.length > 0 && (
<Group justify="space-between">
<Text size="xs" c="dimmed">Ролей</Text>
<Text size="sm" fw={500}>{selectedRoleIds.length}</Text>
</Group>
)}
{selectedRoleFlags.length > 0 && (
<Group justify="space-between">
<Text size="xs" c="dimmed">Типов ролей</Text>
<Text size="sm" fw={500}>{selectedRoleFlags.length}</Text>
</Group>
)}
{selectedDepartmentIds.length > 0 && (
<Group justify="space-between">
<Text size="xs" c="dimmed">Отделов</Text>
<Text size="sm" fw={500}>{selectedDepartmentIds.length}</Text>
</Group>
)}
</Stack>
</Paper>
<Group justify="flex-end" gap="sm" mt="xs">
<Button variant="default" onClick={() => setConfirmOpen(false)}>
Отмена
</Button>
<Button color="blue" onClick={doSubmit} loading={createNotification.isPending}>
Отправить
</Button>
</Group>
</Stack>
</Modal>
</Paper>
)
}
-----END src/pages/notifications/components/SendNotificationForm.tsx-----
File: src/pages/permissions/PermissionsPage.tsx
Lines: 306
-----BEGIN src/pages/permissions/PermissionsPage.tsx-----
import { useState } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
Select,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Tabs,
UnstyledButton,
ThemeIcon,
} from '@mantine/core'
import {
IconPencil,
IconTrash,
IconPlus,
IconSearch,
IconShield,
IconCategory,
IconBriefcase,
IconWorld,
} from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { usePermissions, useDeletePermission } from '@/features/permissions/hooks/usePermissions'
import { useRoles } from '@/features/roles/hooks/useRoles'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { PERMISSION_ACTIONS, ACTION_COLORS, ACTION_LABELS } from '@/features/permissions/constants'
import PermissionEditModal from './components/PermissionEditModal'
const LIMIT = 50
export default function PermissionsPage() {
const [page, setPage] = useState(1)
const [roleFilter, setRoleFilter] = useState<string | null>(null)
const [actionFilter, setActionFilter] = useState<string | null>(null)
const [editPermissionId, setEditPermissionId] = useState<number | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const { data, isLoading, isFetching } = usePermissions({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(roleFilter && { role_id: Number(roleFilter) }),
...(actionFilter && { action: actionFilter }),
})
const { data: roles } = useRoles({ limit: 1000 })
const deletePermission = useDeletePermission()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const roleOptions = roles?.data?.map((r) => ({
value: String(r.id),
label: r.name || '',
})) || []
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить это право? Пользователи с этой ролью потеряют соответствующие возможности.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deletePermission.mutate(id),
})
}
// Определяем "уровень" права
const getPermissionLevel = (permission: any) => {
if (permission.topic_id && permission.topic) {
return {
level: 'topic',
label: 'Тема',
value: permission.topic.name,
icon: IconBriefcase,
color: 'orange',
}
}
if (permission.topic_category_id && permission.topic_category) {
return {
level: 'category',
label: 'Категория',
value: permission.topic_category.name,
icon: IconCategory,
color: 'blue',
}
}
return {
level: 'global',
label: 'Глобальное',
value: 'Все темы',
icon: IconWorld,
color: 'violet',
}
}
return (
<Stack gap="md">
<Group justify="space-between">
<Text size="xl" fw={700}>Права доступа</Text>
<Group>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
<Button
leftSection={<IconPlus size={16} />}
onClick={() => setCreateModalOpened(true)}
>
Добавить право
</Button>
</Group>
</Group>
{/* Подсказка */}
<Paper withBorder p="md" bg="blue.0">
<Group gap="xs">
<IconShield size={20} color="blue" />
<Text size="sm">
Права определяют, какие действия могут выполнять пользователи с определённой ролью.
Право может быть <b>глобальным</b> (на все темы),
на <b>категорию</b> (на все темы категории) или на <b>конкретную тему</b>.
</Text>
</Group>
</Paper>
{/* Фильтры */}
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<Select
label="Роль"
placeholder="Все роли"
data={roleOptions}
value={roleFilter}
onChange={(v) => {
setRoleFilter(v)
setPage(1)
}}
clearable
searchable
style={{ minWidth: 200 }}
/>
<Select
label="Действие"
placeholder="Все действия"
data={PERMISSION_ACTIONS.map((a) => ({
value: a.value,
label: a.label,
}))}
value={actionFilter}
onChange={(v) => {
setActionFilter(v)
setPage(1)
}}
clearable
style={{ minWidth: 200 }}
/>
</Group>
</Paper>
{/* Таблица */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Роль</Table.Th>
<Table.Th>Действие</Table.Th>
<Table.Th>Область действия</Table.Th>
<Table.Th>Объект</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={6}>
<Center p={40}>
<Text c="dimmed">Права не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).map((permission) => {
const level = getPermissionLevel(permission)
const LevelIcon = level.icon
return (
<Table.Tr key={permission.id}>
<Table.Td>{permission.id}</Table.Td>
<Table.Td>
<Group gap="xs">
<ThemeIcon size="sm" variant="light" color="blue">
<IconShield size={12} />
</ThemeIcon>
<Text size="sm" fw={500}>
{permission.role?.name || '—'}
</Text>
</Group>
<Text size="xs" c="dimmed">
{permission.role?.code}
</Text>
</Table.Td>
<Table.Td>
<Badge
color={ACTION_COLORS[permission.action || ''] || 'gray'}
variant="light"
>
{ACTION_LABELS[permission.action || ''] || permission.action}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs">
<LevelIcon size={14} color={`var(--mantine-color-${level.color}-6)`} />
<Text size="sm" c={level.color}>
{level.label}
</Text>
</Group>
</Table.Td>
<Table.Td>
<Text size="sm" lineClamp={2}>
{level.value}
</Text>
</Table.Td>
<Table.Td>
<Group gap="xs">
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditPermissionId(permission.id!)}
>
<IconPencil size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="light"
color="red"
onClick={() => handleDelete(permission.id!)}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Table.Td>
</Table.Tr>
)
})
)}
</Table.Tbody>
</Table>
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={setPage}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</>
)}
</Paper>
{isFetching && !isLoading && (
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
<Loader size="xs" />
</Box>
)}
<PermissionEditModal
permissionId={editPermissionId}
opened={editPermissionId !== null}
onClose={() => setEditPermissionId(null)}
/>
<PermissionEditModal
permissionId={null}
opened={createModalOpened}
onClose={() => setCreateModalOpened(false)}
/>
</Stack>
)
}
-----END src/pages/permissions/PermissionsPage.tsx-----
File: src/pages/permissions/components/PermissionEditModal.tsx
Lines: 303
-----BEGIN src/pages/permissions/components/PermissionEditModal.tsx-----
import { useEffect, useMemo } from 'react'
import {
Modal,
Stack,
Select,
Group,
Button,
Text,
Loader,
Center,
Badge,
Paper,
Alert,
Radio,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconInfoCircle } from '@tabler/icons-react'
import {
usePermission,
useCreatePermission,
useUpdatePermission
} from '@/features/permissions/hooks/usePermissions'
import { useRoles } from '@/features/roles/hooks/useRoles'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
import { PERMISSION_ACTIONS } from '@/features/permissions/constants'
interface PermissionEditModalProps {
permissionId: number | null
opened: boolean
onClose: () => void
}
type ScopeType = 'global' | 'category' | 'topic'
export default function PermissionEditModal({
permissionId,
opened,
onClose
}: PermissionEditModalProps) {
const { data: permission, isLoading: permissionLoading } = usePermission(permissionId)
const createPermission = useCreatePermission()
const updatePermission = useUpdatePermission()
const { data: roles } = useRoles({ limit: 1000 })
const { data: categories } = useCategories({ limit: 1000 })
const isEditMode = permissionId !== null
const form = useForm({
initialValues: {
role_id: null as number | null,
action: '',
scope_type: 'global' as ScopeType,
topic_category_id: null as number | null,
topic_id: null as number | null,
},
validate: {
role_id: (value) => (value === null ? 'Выберите роль' : null),
action: (value) => (value === '' ? 'Выберите действие' : null),
topic_id: (value, values) => {
if (values.scope_type === 'topic' && value === null) {
return 'Выберите тему'
}
return null
},
topic_category_id: (value, values) => {
if (values.scope_type === 'category' && value === null) {
return 'Выберите категорию'
}
return null
},
},
})
// Загружаем темы выбранной категории
const { data: categoryTopics } = useTopics({
limit: 1000,
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
})
// Заполняем форму данными
useEffect(() => {
if (permission) {
let scopeType: ScopeType = 'global'
if (permission.topic_id) scopeType = 'topic'
else if (permission.topic_category_id) scopeType = 'category'
form.setValues({
role_id: permission.role_id || null,
action: permission.action || '',
scope_type: scopeType,
topic_category_id: permission.topic_category_id || null,
topic_id: permission.topic_id || null,
})
} else if (!isEditMode) {
form.reset()
}
}, [permission, isEditMode])
// При смене scope_type сбрасываем связанные поля
const handleScopeTypeChange = (value: ScopeType) => {
form.setFieldValue('scope_type', value)
if (value === 'global') {
form.setFieldValue('topic_category_id', null)
form.setFieldValue('topic_id', null)
} else if (value === 'category') {
form.setFieldValue('topic_id', null)
}
}
// При смене категории сбрасываем тему
const handleCategoryChange = (value: string | null) => {
form.setFieldValue('topic_category_id', value ? Number(value) : null)
form.setFieldValue('topic_id', null)
}
// Опции
const roleOptions = roles?.data?.map((r) => ({
value: String(r.id),
label: r.name || '',
})) || []
const categoryOptions = categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions = categoryTopics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const actionOptions = PERMISSION_ACTIONS.map((a) => ({
value: a.value,
label: `${a.label} — ${a.description}`,
}))
// Получаем описание области действия
const scopeDescription = useMemo(() => {
switch (form.values.scope_type) {
case 'global':
return 'Право будет действовать на все темы согласований'
case 'category':
return 'Право будет действовать на все темы выбранной категории'
case 'topic':
return 'Право будет действовать только на выбранную тему'
}
}, [form.values.scope_type])
const handleSubmit = async (values: typeof form.values) => {
const payload = {
role_id: values.role_id!,
action: values.action,
topic_category_id: values.scope_type === 'global' ? null :
values.scope_type === 'category' ? values.topic_category_id : null,
topic_id: values.scope_type === 'topic' ? values.topic_id : null,
}
if (isEditMode && permissionId) {
await updatePermission.mutateAsync({
id: permissionId,
...payload,
})
} else {
await createPermission.mutateAsync(payload)
}
onClose()
}
const isLoading = permissionLoading
const isSubmitting = createPermission.isPending || updatePermission.isPending
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>
{isEditMode ? 'Редактирование права' : 'Добавление права'}
</Text>
{permission && <Badge variant="light">ID: {permission.id}</Badge>}
</Group>
}
size="lg"
>
{isLoading ? (
<Center p={40}>
<Loader />
</Center>
) : (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
{/* Роль */}
<Select
label="Роль"
placeholder="Выберите роль"
data={roleOptions}
value={form.values.role_id ? String(form.values.role_id) : null}
onChange={(v) => form.setFieldValue('role_id', v ? Number(v) : null)}
searchable
required
disabled={isEditMode}
description="Роль, которой назначается право"
/>
{/* Действие */}
<Select
label="Действие"
placeholder="Выберите действие"
data={actionOptions}
value={form.values.action}
onChange={(v) => form.setFieldValue('action', v || '')}
required
description="Какое действие будет доступно"
/>
{/* Область действия */}
<Paper withBorder p="md">
<Text size="sm" fw={500} mb="sm">
Область действия
</Text>
<Radio.Group
value={form.values.scope_type}
onChange={(v) => handleScopeTypeChange(v as ScopeType)}
>
<Stack gap="xs">
<Radio
value="global"
label="Глобальное право"
description="На все темы согласований"
/>
<Radio
value="category"
label="На категорию"
description="На все темы выбранной категории"
/>
<Radio
value="topic"
label="На конкретную тему"
description="Только на выбранную тему"
/>
</Stack>
</Radio.Group>
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light" mt="sm">
<Text size="sm">{scopeDescription}</Text>
</Alert>
</Paper>
{/* Категория (если выбрана) */}
{(form.values.scope_type === 'category' || form.values.scope_type === 'topic') && (
<Select
label="Категория"
placeholder="Выберите категорию"
data={categoryOptions}
value={form.values.topic_category_id ? String(form.values.topic_category_id) : null}
onChange={handleCategoryChange}
searchable
required={form.values.scope_type === 'category'}
description={
form.values.scope_type === 'topic'
? 'Категория, к которой принадлежит тема'
: 'Категория тем, на которые распространяется право'
}
/>
)}
{/* Тема (если выбрана) */}
{form.values.scope_type === 'topic' && (
<Select
label="Тема"
placeholder="Выберите тему"
data={topicOptions}
value={form.values.topic_id ? String(form.values.topic_id) : null}
onChange={(v) => form.setFieldValue('topic_id', v ? Number(v) : null)}
searchable
required
disabled={!form.values.topic_category_id}
description={
!form.values.topic_category_id
? 'Сначала выберите категорию'
: 'Тема, на которую распространяется право'
}
/>
)}
{/* Кнопки */}
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
{isEditMode ? 'Сохранить' : 'Создать'}
</Button>
</Group>
</Stack>
</form>
)}
</Modal>
)
}
-----END src/pages/permissions/components/PermissionEditModal.tsx-----
File: src/pages/roles/RolesPage.tsx
Lines: 318
-----BEGIN src/pages/roles/RolesPage.tsx-----
import { useState } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Switch,
} from '@mantine/core'
import { IconPencil, IconTrash, IconPlus, IconSearch } from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { useRoles, useDeleteRole } from '@/features/roles/hooks/useRoles'
import RoleEditModal from './components/RoleEditModal'
const LIMIT = 20
export default function RolesPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [roleTypeFilter, setRoleTypeFilter] = useState<string | null>(null)
const [editRoleId, setEditRoleId] = useState<number | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const { data, isLoading, isFetching } = useRoles({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(search && { name: search }),
...(roleTypeFilter === 'director' && { is_director: true }),
...(roleTypeFilter === 'approver' && { is_approver: true }),
...(roleTypeFilter === 'observer' && { is_observer: true }),
...(roleTypeFilter === 'executor' && { is_executor: true }),
...(roleTypeFilter === 'controller' && { is_controller: true }), // 🆕
})
const deleteRole = useDeleteRole()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить эту роль? Это действие нельзя отменить.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteRole.mutate(id),
})
}
return (
<Stack gap="md">
<Group justify="space-between">
<Text size="xl" fw={700}>Роли</Text>
<Group>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
<Button
leftSection={<IconPlus size={16} />}
onClick={() => setCreateModalOpened(true)}
>
Создать роль
</Button>
</Group>
</Group>
{/* Фильтры */}
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<TextInput
label="Поиск по названию"
placeholder="Администратор..."
leftSection={<IconSearch size={16} />}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
style={{ flex: 1 }}
/>
<Group gap="xs">
<Badge
variant={roleTypeFilter === null ? 'filled' : 'light'}
style={{ cursor: 'pointer' }}
onClick={() => {
setRoleTypeFilter(null)
setPage(1)
}}
>
Все
</Badge>
<Badge
variant={roleTypeFilter === 'director' ? 'filled' : 'light'}
color="violet"
style={{ cursor: 'pointer' }}
onClick={() => {
setRoleTypeFilter(roleTypeFilter === 'director' ? null : 'director')
setPage(1)
}}
>
Директора
</Badge>
<Badge
variant={roleTypeFilter === 'approver' ? 'filled' : 'light'}
color="blue"
style={{ cursor: 'pointer' }}
onClick={() => {
setRoleTypeFilter(roleTypeFilter === 'approver' ? null : 'approver')
setPage(1)
}}
>
Согласующие
</Badge>
<Badge
variant={roleTypeFilter === 'observer' ? 'filled' : 'light'}
color="green"
style={{ cursor: 'pointer' }}
onClick={() => {
setRoleTypeFilter(roleTypeFilter === 'observer' ? null : 'observer')
setPage(1)
}}
>
Наблюдатели
</Badge>
<Badge
variant={roleTypeFilter === 'controller' ? 'filled' : 'light'}
color="teal"
style={{ cursor: 'pointer' }}
onClick={() => {
setRoleTypeFilter(roleTypeFilter === 'controller' ? null : 'controller')
setPage(1)
}}
>
Контролёры
</Badge>
<Badge
variant={roleTypeFilter === 'executor' ? 'filled' : 'light'}
color="orange"
style={{ cursor: 'pointer' }}
onClick={() => {
setRoleTypeFilter(roleTypeFilter === 'executor' ? null : 'executor')
setPage(1)
}}
>
Исполнители
</Badge>
</Group>
</Group>
</Paper>
{/* Таблица */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Название</Table.Th>
<Table.Th>Код</Table.Th>
<Table.Th>Типы ролей</Table.Th>
<Table.Th>Описание</Table.Th>
<Table.Th style={{ width: 100 }}>Статус</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={7}>
<Center p={40}>
<Text c="dimmed">Роли не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).map((role) => (
<Table.Tr key={role.id}>
<Table.Td>{role.id}</Table.Td>
<Table.Td>
<Text fw={500}>{role.name}</Text>
</Table.Td>
<Table.Td>
<Text size="sm" ff="monospace" c="dimmed">
{role.code}
</Text>
</Table.Td>
<Table.Td>
<Group gap={4}>
{role.is_director && (
<Badge size="xs" color="violet" variant="light">Директор</Badge>
)}
{role.is_approver && (
<Badge size="xs" color="blue" variant="light">Согласующий</Badge>
)}
{role.is_observer && (
<Badge size="xs" color="green" variant="light">Наблюдатель</Badge>
)}
{role.is_executor && (
<Badge size="xs" color="orange" variant="light">Исполнитель</Badge>
)}
{role.is_controller && (
<Badge size="xs" color="teal" variant="light">Контролёр</Badge>
)}
{!role.is_director && !role.is_approver && !role.is_observer &&
!role.is_executor && !role.is_controller && (
<Text size="xs" c="dimmed">—</Text>
)}
</Group>
</Table.Td>
<Table.Td>
<Text size="sm" lineClamp={2}>
{role.description || '—'}
</Text>
</Table.Td>
<Table.Td>
<Badge
color={role.is_default ? 'blue' : 'gray'}
variant={role.is_default ? 'filled' : 'light'}
>
{role.is_default ? 'По умолчанию' : 'Пользовательская'}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs">
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditRoleId(role.id!)}
>
<IconPencil size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="light"
color="red"
onClick={() => handleDelete(role.id!)}
disabled={role.is_default}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Table.Td>
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
{/* Пагинация */}
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={setPage}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</>
)}
</Paper>
{/* Индикатор обновления */}
{isFetching && !isLoading && (
<Box
style={{
position: 'fixed',
top: 70,
right: 20,
zIndex: 1000
}}
>
<Loader size="xs" />
</Box>
)}
{/* Модальное окно редактирования */}
<RoleEditModal
roleId={editRoleId}
opened={editRoleId !== null}
onClose={() => setEditRoleId(null)}
/>
{/* Модальное окно создания */}
<RoleEditModal
roleId={null}
opened={createModalOpened}
onClose={() => setCreateModalOpened(false)}
/>
</Stack>
)
}
-----END src/pages/roles/RolesPage.tsx-----
File: src/pages/roles/components/RoleEditModal.tsx
Lines: 209
-----BEGIN src/pages/roles/components/RoleEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Textarea,
Switch,
Group,
Button,
Text,
Loader,
Center,
Badge,
Paper,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
useRole,
useCreateRole,
useUpdateRole
} from '@/features/roles/hooks/useRoles'
interface RoleEditModalProps {
roleId: number | null
opened: boolean
onClose: () => void
}
export default function RoleEditModal({
roleId,
opened,
onClose
}: RoleEditModalProps) {
const { data: role, isLoading: roleLoading } = useRole(roleId)
const createRole = useCreateRole()
const updateRole = useUpdateRole()
const isEditMode = roleId !== null
const form = useForm({
initialValues: {
name: '',
code: '',
description: '',
is_default: false,
is_director: false,
is_approver: false,
is_observer: false,
is_executor: false,
is_controller: false,
},
validate: {
name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
code: (value: string | any[]) => {
if (value.length < 2) return 'Код должен содержать минимум 2 символа'
if (!/^[a-z0-9_]+$/.test(value as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
return null
},
},
})
// Заполняем форму данными роли
useEffect(() => {
if (role) {
form.setValues({
name: role.name || '',
code: role.code || '',
description: role.description || '',
is_default: role.is_default ?? false,
is_director: role.is_director ?? false,
is_approver: role.is_approver ?? false,
is_observer: role.is_observer ?? false,
is_executor: role.is_executor ?? false,
is_controller: role.is_controller ?? false,
})
} else if (!isEditMode) {
form.reset()
}
}, [role, isEditMode])
const handleSubmit = async (values: typeof form.values) => {
if (isEditMode && roleId) {
// Режим редактирования
await updateRole.mutateAsync({
id: roleId,
...values,
})
} else {
// Режим создания
await createRole.mutateAsync(values)
}
onClose()
}
const isLoading = roleLoading
const isSubmitting = createRole.isPending || updateRole.isPending
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>
{isEditMode ? 'Редактирование роли' : 'Создание роли'}
</Text>
{role && <Badge variant="light">ID: {role.id}</Badge>}
</Group>
}
size="lg"
>
{isLoading ? (
<Center p={40}>
<Loader />
</Center>
) : (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<TextInput
label="Название"
placeholder="Администратор"
required
{...form.getInputProps('name')}
/>
<TextInput
label="Код"
placeholder="admin"
required
description="Уникальный идентификатор роли (lowercase, цифры, подчеркивания)"
disabled={isEditMode}
{...form.getInputProps('code')}
/>
<Textarea
label="Описание"
placeholder="Описание роли..."
minRows={2}
{...form.getInputProps('description')}
/>
<Paper withBorder p="md">
<Text size="sm" fw={500} mb="sm">Типы ролей</Text>
<Stack gap="sm">
<Switch
label="Директор"
description="Пользователь с этой ролью является директором"
checked={form.values.is_director}
onChange={(e) => form.setFieldValue('is_director', e.currentTarget.checked)}
color="violet"
/>
<Switch
label="Согласующий"
description="Пользователь с этой ролью может согласовывать заявки"
checked={form.values.is_approver}
onChange={(e) => form.setFieldValue('is_approver', e.currentTarget.checked)}
color="blue"
/>
<Switch
label="Наблюдатель"
description="Пользователь с этой ролью может наблюдать за заявками"
checked={form.values.is_observer}
onChange={(e) => form.setFieldValue('is_observer', e.currentTarget.checked)}
color="green"
/>
<Switch
label="Исполнитель"
description="Пользователь с этой ролью может выполнять задачи"
checked={form.values.is_executor}
onChange={(e) => form.setFieldValue('is_executor', e.currentTarget.checked)}
color="orange"
/>
<Switch
label="Контролёр"
description={
form.values.is_observer
? "Пользователь с этой ролью видит расширенный контроль по заявкам"
: "Доступно только вместе с ролью «Наблюдатель»"
}
checked={form.values.is_controller}
disabled={!form.values.is_observer}
onChange={(e) => form.setFieldValue('is_controller', e.currentTarget.checked)}
color="teal"
/>
</Stack>
</Paper>
<Switch
label="Роль по умолчанию"
description="Назначается новым пользователям автоматически"
checked={form.values.is_default}
onChange={(e) => form.setFieldValue('is_default', e.currentTarget.checked)}
color="blue"
/>
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
{isEditMode ? 'Сохранить' : 'Создать'}
</Button>
</Group>
</Stack>
</form>
)}
</Modal>
)
}
-----END src/pages/roles/components/RoleEditModal.tsx-----
File: src/pages/settings/SettingsPage.tsx
Lines: 179
-----BEGIN src/pages/settings/SettingsPage.tsx-----
import { useState } from 'react'
import {
Paper,
Stack,
Text,
PasswordInput,
Button,
Group,
Alert,
Box,
Title,
Divider,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import { modals } from '@mantine/modals'
import { IconShield, IconAlertCircle, IconKey } from '@tabler/icons-react'
import { authApi } from '@/api/auth'
import { useAuth } from '@/hooks/useAuth'
export default function SettingsPage() {
const [loading, setLoading] = useState(false)
const { user } = useAuth()
const form = useForm({
initialValues: {
current_password: '',
new_password: '',
confirm_password: '',
},
validate: {
current_password: (value) =>
value.length === 0 ? 'Введите текущий пароль' : null,
new_password: (value) => {
if (value.length === 0) return 'Введите новый пароль'
if (value.length < 6) return 'Пароль должен содержать минимум 6 символов'
return null
},
confirm_password: (value, values) =>
value !== values.new_password ? 'Пароли не совпадают' : null,
},
})
const handleSubmit = async (values: typeof form.values) => {
// Подтверждение через модальное окно
modals.openConfirmModal({
title: 'Подтвердите смену пароля',
children: (
<Text size="sm">
Вы уверены, что хотите изменить пароль? После смены пароля вам нужно будет
войти заново на всех устройствах.
</Text>
),
labels: { confirm: 'Изменить пароль', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: async () => {
setLoading(true)
try {
await authApi.updateProfile({ password: values.new_password })
notifications.show({
title: 'Успешно',
message: 'Пароль успешно изменен',
color: 'green',
})
form.reset()
// Разлогиниваем пользователя, чтобы он вошёл заново
setTimeout(() => {
localStorage.removeItem('token')
window.location.href = '/login'
}, 1500)
} catch (error: any) {
notifications.show({
title: 'Ошибка',
message: error.response?.data?.error_description || 'Не удалось изменить пароль',
color: 'red',
})
} finally {
setLoading(false)
}
},
})
}
return (
<Box maw={600}>
<Stack gap="lg">
<div>
<Title order={2}>Настройки</Title>
<Text c="dimmed" size="sm" mt={4}>
Управление вашим аккаунтом
</Text>
</div>
{/* Информация о профиле */}
<Paper withBorder p="md">
<Stack gap="xs">
<Group justify="space-between">
<Text size="sm" c="dimmed">Логин:</Text>
<Text fw={500}>{user?.login || '—'}</Text>
</Group>
{user?.last_login && (
<Group justify="space-between">
<Text size="sm" c="dimmed">Последний вход:</Text>
<Text size="sm">
{new Date(user.last_login).toLocaleString('ru-RU')}
</Text>
</Group>
)}
{user?.last_ip_login && (
<Group justify="space-between">
<Text size="sm" c="dimmed">Последний IP:</Text>
<Text size="sm" ff="monospace">{user.last_ip_login}</Text>
</Group>
)}
</Stack>
</Paper>
{/* Смена пароля */}
<Paper withBorder p="md">
<Group gap="xs" mb="md">
<IconKey size={20} color="var(--mantine-color-blue-6)" />
<Text fw={600} size="lg">Смена пароля</Text>
</Group>
<Alert
icon={<IconAlertCircle size={16} />}
color="yellow"
variant="light"
mb="md"
>
<Text size="sm">
После смены пароля вам нужно будет войти заново на всех устройствах.
</Text>
</Alert>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<PasswordInput
label="Текущий пароль"
placeholder="Введите текущий пароль"
required
{...form.getInputProps('current_password')}
/>
<Divider />
<PasswordInput
label="Новый пароль"
placeholder="Минимум 6 символов"
required
{...form.getInputProps('new_password')}
/>
<PasswordInput
label="Подтвердите новый пароль"
placeholder="Повторите новый пароль"
required
{...form.getInputProps('confirm_password')}
/>
<Group justify="flex-end" mt="md">
<Button
type="submit"
loading={loading}
leftSection={<IconShield size={16} />}
>
Изменить пароль
</Button>
</Group>
</Stack>
</form>
</Paper>
</Stack>
</Box>
)
}
-----END src/pages/settings/SettingsPage.tsx-----
File: src/pages/topicExecutors/TopicExecutorsPage.tsx
Lines: 397
-----BEGIN src/pages/topicExecutors/TopicExecutorsPage.tsx-----
import { useState, useMemo } from 'react'
import {
Paper,
Table,
Group,
ActionIcon,
Button,
Text,
Select,
Loader,
Center,
Tooltip,
Box,
Stack,
SegmentedControl,
Badge,
Alert,
ScrollArea,
} from '@mantine/core'
import {
IconPencil,
IconTrash,
IconPlus,
IconInfoCircle,
IconFile,
IconCheck,
IconX,
} from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import {
useTopicExecutors,
useDeleteTopicExecutor
} from '@/features/topicExecutors/hooks/useTopicExecutors'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useTopics } from '@/features/topics/hooks/useTopics'
import { useCategories } from '@/features/categories/hooks/useCategories'
import {
groupExecutorsByTopic,
TARGET_SYSTEMS,
TARGET_SYSTEM_LABELS,
TARGET_SYSTEM_COLORS,
type TopicExecutorsGroup,
} from '@/features/topicExecutors/utils'
import TopicExecutorsCard from './components/TopicExecutorsCard'
import TopicExecutorEditModal from './components/TopicExecutorEditModal'
import type { ApprovalTopicExecutor } from '@/types/api'
type ViewMode = 'cards' | 'table'
export default function TopicExecutorsPage() {
const [viewMode, setViewMode] = useState<ViewMode>('cards')
// ✅ Фильтры - адаптированы под дизайн Hierarchies
const [topicFilter, setTopicFilter] = useState<string | null>(null)
const [categoryFilter, setCategoryFilter] = useState<string | null>(null)
const [userFilter, setUserFilter] = useState<string | null>(null)
const [targetSystemFilter, setTargetSystemFilter] = useState<string | null>(null)
const [editExecutor, setEditExecutor] = useState<ApprovalTopicExecutor | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const [presetGroup, setPresetGroup] = useState<TopicExecutorsGroup | null>(null)
// ✅ Получаем категории
const { data: categories } = useCategories({ limit: 1000 })
// ✅ Получаем темы с учетом фильтра по категории
const { data: categoryTopics } = useTopics({
limit: 1000,
...(categoryFilter && { category_id: Number(categoryFilter) }),
})
const { data, isLoading, isFetching } = useTopicExecutors({
...(topicFilter && { topic_id: Number(topicFilter) }),
...(userFilter && { user_id: Number(userFilter) }),
...(categoryFilter && { category_id: Number(categoryFilter) }),
...(targetSystemFilter && { target_system: targetSystemFilter }),
})
const { data: users } = useUsers({ limit: 1000 })
const { data: topics } = useTopics({ limit: 1000 })
const deleteExecutor = useDeleteTopicExecutor()
// Группируем по темам
const groups = useMemo(() => {
if (!data?.data) return []
return groupExecutorsByTopic(data.data)
}, [data])
// ✅ Опции для фильтров
const userOptions = users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const categoryOptions = categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions = (categoryFilter ? categoryTopics?.data : topics?.data)?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const targetSystemOptions = TARGET_SYSTEMS.map((s) => ({
value: s.value,
label: s.label,
}))
// ✅ Обработчик изменения фильтров - сбрасывает страницу и выделение
const handleFilterChange =
(setter: (value: string | null) => void) => (value: string | null) => {
setter(value)
// Если меняется категория, сбрасываем тему
if (setter === setCategoryFilter) {
setTopicFilter(null)
}
}
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить этого исполнителя?
Задачи по этой теме не будут назначаться данному пользователю.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteExecutor.mutate(id),
})
}
const handleEditExecutor = (id: number) => {
const executor = data?.data?.find((e) => e.id === id)
if (executor) {
setEditExecutor(executor)
}
}
const handleAddExecutor = (group: TopicExecutorsGroup) => {
setPresetGroup(group)
setCreateModalOpened(true)
}
const handleCloseModal = () => {
setEditExecutor(null)
setCreateModalOpened(false)
setPresetGroup(null)
}
return (
<Stack gap="md">
{/* Заголовок - адаптирован под дизайн Hierarchies */}
<Group justify="space-between">
<Text size="xl" fw={700}>Исполнители тем</Text>
<Group>
<Text c="dimmed" size="sm">
Всего: {data?.data?.length || 0}
</Text>
<SegmentedControl
value={viewMode}
onChange={(v) => setViewMode(v as ViewMode)}
data={[
{ value: 'cards', label: 'Карточки' },
{ value: 'table', label: 'Таблица' },
]}
/>
<Button
leftSection={<IconPlus size={16} />}
onClick={() => {
setPresetGroup(null)
setCreateModalOpened(true)
}}
>
Добавить исполнителя
</Button>
</Group>
</Group>
{/* Подсказка */}
<Alert icon={<IconInfoCircle size={16} />} color="orange" variant="light">
<Text size="sm">
Исполнители — это пользователи, которые выполняют задачи после согласования заявки.
Каждая тема может иметь несколько исполнителей с разными шагами.
Поле "Текст задачи" содержит инструкцию для исполнителя.
</Text>
</Alert>
{/* ✅ Фильтры - адаптированы под дизайн Hierarchies */}
<Paper withBorder p="md">
<Stack gap="md">
<Group gap="md" align="flex-end">
<Select
label="Категория"
placeholder="Все категории"
data={categoryOptions}
value={categoryFilter}
onChange={handleFilterChange(setCategoryFilter)}
clearable
searchable
style={{ flex: 1, minWidth: 250 }}
/>
<Select
label="Тема"
placeholder="Все темы"
data={topicOptions}
value={topicFilter}
onChange={handleFilterChange(setTopicFilter)}
clearable
searchable
style={{ flex: 1, minWidth: 250 }}
/>
</Group>
<Group gap="md" align="flex-end">
<Select
label="Исполнитель"
placeholder="Все исполнители"
data={userOptions}
value={userFilter}
onChange={handleFilterChange(setUserFilter)}
clearable
searchable
style={{ flex: 1, minWidth: 250 }}
/>
<Select
label="Целевая система"
placeholder="Все системы"
data={targetSystemOptions}
value={targetSystemFilter}
onChange={handleFilterChange(setTargetSystemFilter)}
clearable
style={{ flex: 1, minWidth: 200 }}
/>
</Group>
</Stack>
</Paper>
{/* Контент */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : viewMode === 'cards' ? (
<ScrollArea p="md">
<Stack gap="md">
{groups.length === 0 ? (
<Center p={40}>
<Text c="dimmed">Исполнители не найдены</Text>
</Center>
) : (
groups.map((group) => (
<TopicExecutorsCard
key={group.topicId}
group={group}
onEditExecutor={handleEditExecutor}
onDeleteExecutor={handleDelete}
onAddExecutor={handleAddExecutor}
/>
))
)}
</Stack>
</ScrollArea>
) : (
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Тема</Table.Th>
<Table.Th>Исполнитель</Table.Th>
<Table.Th style={{ width: 80 }}>Шаг</Table.Th>
<Table.Th>Задача</Table.Th>
<Table.Th style={{ width: 120 }}>Система</Table.Th>
<Table.Th style={{ width: 80 }}>Файл</Table.Th>
<Table.Th style={{ width: 80 }}>Статус</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={9}>
<Center p={40}>
<Text c="dimmed">Исполнители не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
data?.data?.map((executor) => (
<Table.Tr key={executor.id}>
<Table.Td>{executor.id}</Table.Td>
<Table.Td>
<Text size="sm" fw={500}>
{executor.topic?.name || '—'}
</Text>
<Text size="xs" c="dimmed" ff="monospace">
{executor.topic?.code}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" fw={500}>
{executor.user?.full_name || '—'}
</Text>
<Text size="xs" c="dimmed">
{executor.user?.department?.name}
</Text>
</Table.Td>
<Table.Td>
<Badge variant="light" color="orange">
#{executor.step_order}
</Badge>
</Table.Td>
<Table.Td>
<Text size="xs" lineClamp={2}>
{executor.task_text || '—'}
</Text>
</Table.Td>
<Table.Td>
<Badge
size="xs"
variant="light"
color={TARGET_SYSTEM_COLORS[executor.target_system || ''] || 'gray'}
>
{TARGET_SYSTEM_LABELS[executor.target_system || ''] || executor.target_system}
</Badge>
</Table.Td>
<Table.Td>
{executor.require_file ? (
<IconFile size={16} color="var(--mantine-color-violet-6)" />
) : (
<Text size="xs" c="dimmed">—</Text>
)}
</Table.Td>
<Table.Td>
<Badge
size="xs"
variant="light"
color={executor.is_active ? 'green' : 'gray'}
leftSection={executor.is_active ? <IconCheck size={10} /> : <IconX size={10} />}
>
{executor.is_active ? 'Активен' : 'Неактивен'}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs">
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditExecutor(executor)}
>
<IconPencil size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="light"
color="red"
onClick={() => handleDelete(executor.id!)}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Table.Td>
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
)}
</Paper>
{isFetching && !isLoading && (
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
<Loader size="xs" />
</Box>
)}
{/* Модальные окна */}
<TopicExecutorEditModal
executor={editExecutor}
opened={editExecutor !== null}
onClose={handleCloseModal}
/>
<TopicExecutorEditModal
executor={null}
presetGroup={presetGroup}
opened={createModalOpened}
onClose={handleCloseModal}
/>
</Stack>
)
}
-----END src/pages/topicExecutors/TopicExecutorsPage.tsx-----
File: src/pages/topicExecutors/components/TopicExecutorEditModal.tsx
Lines: 233
-----BEGIN src/pages/topicExecutors/components/TopicExecutorEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
Select,
NumberInput,
Textarea,
Switch,
Group,
Button,
Text,
Loader,
Center,
Badge,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
useCreateTopicExecutor,
useUpdateTopicExecutor
} from '@/features/topicExecutors/hooks/useTopicExecutors'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useTopics } from '@/features/topics/hooks/useTopics'
import { TARGET_SYSTEMS } from '@/features/topicExecutors/utils'
import type { ApprovalTopicExecutor } from '@/types/api'
import type { TopicExecutorsGroup } from '@/features/topicExecutors/utils'
interface TopicExecutorEditModalProps {
executor: ApprovalTopicExecutor | null
presetGroup?: TopicExecutorsGroup | null
opened: boolean
onClose: () => void
}
export default function TopicExecutorEditModal({
executor,
presetGroup,
opened,
onClose
}: TopicExecutorEditModalProps) {
const createExecutor = useCreateTopicExecutor()
const updateExecutor = useUpdateTopicExecutor()
const { data: users } = useUsers({ limit: 1000 })
const { data: topics } = useTopics({ limit: 1000 })
const isEditMode = executor !== null
const form = useForm({
initialValues: {
topic_id: null as number | null,
user_id: null as number | null,
step_order: 0,
require_file: false,
task_text: '',
is_active: true,
target_system: 'all',
},
validate: {
topic_id: (v) => (v === null ? 'Выберите тему' : null),
user_id: (v) => (v === null ? 'Выберите исполнителя' : null),
},
})
// Заполняем форму данными
useEffect(() => {
if (executor) {
form.setValues({
topic_id: executor.topic_id || null,
user_id: executor.user_id || null,
step_order: executor.step_order ?? 0,
require_file: executor.require_file ?? false,
task_text: executor.task_text || '',
is_active: executor.is_active ?? true,
target_system: executor.target_system || 'all',
})
} else if (presetGroup) {
// Предзаполняем из группы
form.setValues({
topic_id: presetGroup.topicId,
user_id: null,
step_order: presetGroup.executors.length,
require_file: false,
task_text: '',
is_active: true,
target_system: 'all',
})
} else {
form.reset()
}
}, [executor, presetGroup, opened])
// Опции
const userOptions = users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
description: u.department?.name,
})) || []
const topicOptions = topics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
description: t.category?.name,
})) || []
const targetSystemOptions = TARGET_SYSTEMS.map((s) => ({
value: s.value,
label: s.label,
}))
const handleSubmit = async (values: typeof form.values) => {
const payload = {
topic_id: values.topic_id!,
user_id: values.user_id!,
step_order: values.step_order,
require_file: values.require_file,
task_text: values.task_text || null,
is_active: values.is_active,
target_system: values.target_system,
}
if (isEditMode && executor?.id) {
await updateExecutor.mutateAsync({
id: executor.id,
...payload,
})
} else {
await createExecutor.mutateAsync(payload)
}
onClose()
}
const isSubmitting = createExecutor.isPending || updateExecutor.isPending
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>
{isEditMode ? 'Редактирование исполнителя' : 'Добавление исполнителя'}
</Text>
{executor && <Badge variant="light">ID: {executor.id}</Badge>}
</Group>
}
size="lg"
>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
{/* Тема */}
<Select
label="Тема согласования"
placeholder="Выберите тему"
data={topicOptions}
value={form.values.topic_id ? String(form.values.topic_id) : null}
onChange={(v) => form.setFieldValue('topic_id', v ? Number(v) : null)}
searchable
required
disabled={isEditMode || !!presetGroup}
description="Тема, для которой назначается исполнитель"
/>
{/* Исполнитель */}
<Select
label="Исполнитель"
placeholder="Выберите пользователя"
data={userOptions}
value={form.values.user_id ? String(form.values.user_id) : null}
onChange={(v) => form.setFieldValue('user_id', v ? Number(v) : null)}
searchable
required
description="Пользователь, который будет выполнять задачу"
/>
{/* Порядок шага */}
<NumberInput
label="Порядок шага (step_order)"
description="0 = первый шаг, 1 = второй и т.д."
value={form.values.step_order}
onChange={(v) => form.setFieldValue('step_order', Number(v) || 0)}
min={0}
required
/>
{/* Целевая система */}
<Select
label="Целевая система"
placeholder="Выберите систему"
data={targetSystemOptions}
value={form.values.target_system}
onChange={(v) => form.setFieldValue('target_system', v || 'all')}
description="Система, в которой будет выполняться задача"
/>
{/* Текст задачи */}
<Textarea
label="Текст задачи"
placeholder="Опишите, что нужно сделать..."
value={form.values.task_text}
onChange={(e) => form.setFieldValue('task_text', e.currentTarget.value)}
minRows={3}
description="Инструкция для исполнителя"
/>
{/* Требует файл */}
<Switch
label="Требуется файл"
description="Исполнитель должен прикрепить файл при выполнении задачи"
checked={form.values.require_file}
onChange={(e) => form.setFieldValue('require_file', e.currentTarget.checked)}
/>
{/* Активен */}
<Switch
label="Активен"
description="Неактивные исполнители не будут получать задачи"
checked={form.values.is_active}
onChange={(e) => form.setFieldValue('is_active', e.currentTarget.checked)}
/>
{/* Кнопки */}
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
{isEditMode ? 'Сохранить' : 'Добавить'}
</Button>
</Group>
</Stack>
</form>
</Modal>
)
}
-----END src/pages/topicExecutors/components/TopicExecutorEditModal.tsx-----
File: src/pages/topicExecutors/components/TopicExecutorsCard.tsx
Lines: 218
-----BEGIN src/pages/topicExecutors/components/TopicExecutorsCard.tsx-----
import {
Paper,
Group,
Stack,
Text,
Badge,
ActionIcon,
Avatar,
Box,
Tooltip,
Switch,
} from '@mantine/core'
import {
IconPencil,
IconTrash,
IconUserPlus,
IconBriefcase,
IconCategory,
IconFile,
IconCheck,
IconX,
} from '@tabler/icons-react'
import type { TopicExecutorsGroup } from '@/features/topicExecutors/utils'
import { TARGET_SYSTEM_LABELS, TARGET_SYSTEM_COLORS } from '@/features/topicExecutors/utils'
interface TopicExecutorsCardProps {
group: TopicExecutorsGroup
onEditExecutor: (executorId: number) => void
onDeleteExecutor: (executorId: number) => void
onAddExecutor: (group: TopicExecutorsGroup) => void
}
export default function TopicExecutorsCard({
group,
onEditExecutor,
onDeleteExecutor,
onAddExecutor,
}: TopicExecutorsCardProps) {
return (
<Paper withBorder p="md" mb="md">
{/* Заголовок темы */}
<Group justify="space-between" mb="md">
<Group gap="md">
<Avatar size="sm" radius="xl" color="orange">
<IconBriefcase size={16} />
</Avatar>
<Stack gap={0}>
<Text fw={600} size="sm">{group.topicName}</Text>
<Text size="xs" c="dimmed" ff="monospace">{group.topicCode}</Text>
{group.categoryName && (
<Badge
size="xs"
variant="light"
color="blue"
leftSection={<IconCategory size={10} />}
mt={4}
>
{group.categoryName}
</Badge>
)}
</Stack>
</Group>
<Tooltip label="Добавить исполнителя">
<ActionIcon
variant="light"
color="green"
onClick={() => onAddExecutor(group)}
>
<IconUserPlus size={16} />
</ActionIcon>
</Tooltip>
</Group>
{/* Список исполнителей */}
<Box>
{group.executors.length === 0 ? (
<Text size="sm" c="dimmed" ta="center" py="md">
Исполнители не назначены
</Text>
) : (
<Stack gap="xs">
{group.executors.map((executor, index) => (
<Paper
key={executor.id}
withBorder
p="sm"
style={{
cursor: 'pointer',
transition: 'all 0.2s',
opacity: executor.is_active ? 1 : 0.6,
}}
onClick={() => onEditExecutor(executor.id!)}
className="hover-shadow"
>
<Stack gap="xs">
{/* Верхняя строка: исполнитель и метаданные */}
<Group justify="space-between">
<Group gap="sm">
<Badge
variant="light"
color="orange"
size="sm"
>
Шаг #{executor.step_order ?? index}
</Badge>
<Avatar size="sm" radius="xl" color="orange">
{executor.user?.full_name?.charAt(0) || '?'}
</Avatar>
<Stack gap={0}>
<Text size="sm" fw={500}>
{executor.user?.full_name || '—'}
</Text>
{executor.user?.department?.name && (
<Text size="xs" c="dimmed">
{executor.user.department.name}
</Text>
)}
</Stack>
</Group>
<Group gap={4}>
{/* Целевая система */}
{executor.target_system && (
<Badge
size="xs"
variant="light"
color={TARGET_SYSTEM_COLORS[executor.target_system] || 'gray'}
>
{TARGET_SYSTEM_LABELS[executor.target_system] || executor.target_system}
</Badge>
)}
{/* Требует файл */}
{executor.require_file && (
<Tooltip label="Требуется файл">
<Badge
size="xs"
variant="light"
color="violet"
leftSection={<IconFile size={10} />}
>
Файл
</Badge>
</Tooltip>
)}
{/* Активен/неактивен */}
<Badge
size="xs"
variant="light"
color={executor.is_active ? 'green' : 'gray'}
leftSection={executor.is_active ? <IconCheck size={10} /> : <IconX size={10} />}
>
{executor.is_active ? 'Активен' : 'Неактивен'}
</Badge>
{/* Кнопки действий */}
<Tooltip label="Редактировать">
<ActionIcon
variant="subtle"
color="blue"
size="sm"
onClick={(e) => {
e.stopPropagation()
onEditExecutor(executor.id!)
}}
>
<IconPencil size={14} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="subtle"
color="red"
size="sm"
onClick={(e) => {
e.stopPropagation()
onDeleteExecutor(executor.id!)
}}
>
<IconTrash size={14} />
</ActionIcon>
</Tooltip>
</Group>
</Group>
{/* Текст задачи */}
{executor.task_text && (
<Paper
withBorder
p="xs"
bg="gray.0"
style={{ borderRadius: 4 }}
>
<Text size="xs" c="dimmed" mb={4} fw={500}>
Задача:
</Text>
<Text size="xs" style={{ whiteSpace: 'pre-wrap' }}>
{executor.task_text}
</Text>
</Paper>
)}
</Stack>
</Paper>
))}
</Stack>
)}
</Box>
<style>{`
.hover-shadow:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border-color: var(--mantine-color-orange-4);
}
`}</style>
</Paper>
)
}
-----END src/pages/topicExecutors/components/TopicExecutorsCard.tsx-----
File: src/pages/topics/TopicsPage.tsx
Lines: 268
-----BEGIN src/pages/topics/TopicsPage.tsx-----
import { useState } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Select,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Switch,
} from '@mantine/core'
import { IconPencil, IconTrash, IconPlus, IconSearch } from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { useTopics, useDeleteTopic } from '@/features/topics/hooks/useTopics'
import { useCategories } from '@/features/categories/hooks/useCategories'
import TopicEditModal from './components/TopicEditModal'
const LIMIT = 20
export default function TopicsPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [categoryFilter, setCategoryFilter] = useState<string | null>(null)
const [activeFilter, setActiveFilter] = useState<boolean | null>(null)
const [editTopicId, setEditTopicId] = useState<number | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const { data, isLoading, isFetching } = useTopics({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(search && { name: search }),
...(categoryFilter && { category_id: Number(categoryFilter) }),
...(activeFilter !== null && { is_active: activeFilter }),
})
const { data: categories } = useCategories({ limit: 1000 })
const deleteTopic = useDeleteTopic()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const categoryOptions = categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить эту тему? Связанные данные (исполнители, иерархия) могут быть затронуты.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteTopic.mutate(id),
})
}
return (
<Stack gap="md">
<Group justify="space-between">
<Text size="xl" fw={700}>Темы согласований</Text>
<Group>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
<Button
leftSection={<IconPlus size={16} />}
onClick={() => setCreateModalOpened(true)}
>
Создать тему
</Button>
</Group>
</Group>
{/* Фильтры */}
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<TextInput
label="Поиск по названию"
placeholder="Отпуск, больничный..."
leftSection={<IconSearch size={16} />}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
style={{ flex: 1 }}
/>
<Select
label="Категория"
placeholder="Все категории"
data={categoryOptions}
value={categoryFilter}
onChange={(v) => {
setCategoryFilter(v)
setPage(1)
}}
clearable
searchable
style={{ minWidth: 200 }}
/>
<Switch
label="Только активные"
checked={activeFilter === true}
onChange={(e) => {
setActiveFilter(e.currentTarget.checked ? true : null)
setPage(1)
}}
/>
</Group>
</Paper>
{/* Таблица */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Название</Table.Th>
<Table.Th>Категория</Table.Th>
<Table.Th>Код</Table.Th>
<Table.Th>Параметры</Table.Th>
<Table.Th style={{ width: 100 }}>Статус</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={7}>
<Center p={40}>
<Text c="dimmed">Темы не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).map((topic) => (
<Table.Tr key={topic.id}>
<Table.Td>{topic.id}</Table.Td>
<Table.Td>
<Text fw={500} size="sm">{topic.name}</Text>
</Table.Td>
<Table.Td>
<Badge size="xs" variant="light" color="blue">
{topic.category?.name || '—'}
</Badge>
</Table.Td>
<Table.Td>
<Text size="xs" ff="monospace" c="dimmed">
{topic.code}
</Text>
</Table.Td>
<Table.Td>
<Group gap={4}>
{topic.duration_type && (
<Badge size="xs" variant="light" color="cyan">
{topic.duration_type}
</Badge>
)}
{topic.time_type && (
<Badge size="xs" variant="light" color="teal">
{topic.time_type}
</Badge>
)}
{topic.payment_type && (
<Badge size="xs" variant="light" color="violet">
{topic.payment_type}
</Badge>
)}
{topic.requires_file && (
<Badge size="xs" variant="light" color="orange">
Файл
</Badge>
)}
</Group>
</Table.Td>
<Table.Td>
<Badge
color={topic.is_active ? 'green' : 'gray'}
variant={topic.is_active ? 'light' : 'filled'}
>
{topic.is_active ? 'Активна' : 'Неактивна'}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs">
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditTopicId(topic.id!)}
>
<IconPencil size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="light"
color="red"
onClick={() => handleDelete(topic.id!)}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Table.Td>
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={setPage}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</>
)}
</Paper>
{isFetching && !isLoading && (
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
<Loader size="xs" />
</Box>
)}
<TopicEditModal
topicId={editTopicId}
opened={editTopicId !== null}
onClose={() => setEditTopicId(null)}
/>
<TopicEditModal
topicId={null}
opened={createModalOpened}
onClose={() => setCreateModalOpened(false)}
/>
</Stack>
)
}
-----END src/pages/topics/TopicsPage.tsx-----
File: src/pages/topics/components/TopicEditModal.tsx
Lines: 348
-----BEGIN src/pages/topics/components/TopicEditModal.tsx-----
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Textarea,
Select,
Switch,
Group,
Button,
Text,
Loader,
Center,
Badge,
Paper,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
useTopic,
useCreateTopic,
useUpdateTopic
} from '@/features/topics/hooks/useTopics'
import { useCategories } from '@/features/categories/hooks/useCategories'
import {
DURATION_TYPES,
TIME_TYPES,
PAYMENT_TYPES,
APPROVAL_MODES,
} from '@/features/topics/constants'
interface TopicEditModalProps {
topicId: number | null
opened: boolean
onClose: () => void
}
export default function TopicEditModal({
topicId,
opened,
onClose
}: TopicEditModalProps) {
const { data: topic, isLoading: topicLoading } = useTopic(topicId)
const { data: categories } = useCategories({ limit: 1000 })
const createTopic = useCreateTopic()
const updateTopic = useUpdateTopic()
const isEditMode = topicId !== null
const form = useForm({
initialValues: {
category_id: null as number | null,
name: '',
code: '',
duration_type: '',
time_type: '',
payment_type: '',
template: '',
allows_file: false,
is_active: true,
allow_approver_selection: false,
first_approver_role_code: '',
allow_observer_selection: false,
// 🆕 Делегирование обязанностей на время отсутствия — актуально
// для тем категорий "Отгул"/"Отпуск"/"Больничный".
allow_delegation_selection: false,
approval_mode: 'sequential',
require_approver_comment: false,
requires_file: false,
require_observer_selection: false,
instructions: '',
is_tree_root: false,
},
validate: {
category_id: (v) => (v === null ? 'Выберите категорию' : null),
name: (v: string | any[]) => (v.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
code: (v: string | any[]) => {
if (v.length < 2) return 'Код должен содержать минимум 2 символа'
if (!/^[a-z0-9_]+$/.test(v as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
return null
},
},
})
useEffect(() => {
if (topic) {
form.setValues({
category_id: topic.category_id || null,
name: topic.name || '',
code: topic.code || '',
duration_type: topic.duration_type || '',
time_type: topic.time_type || '',
payment_type: topic.payment_type || '',
template: topic.template || '',
allows_file: topic.allows_file ?? false,
is_active: topic.is_active ?? true,
allow_approver_selection: topic.allow_approver_selection ?? false,
first_approver_role_code: topic.first_approver_role_code || '',
allow_observer_selection: topic.allow_observer_selection ?? false,
allow_delegation_selection: topic.allow_delegation_selection ?? false,
approval_mode: topic.approval_mode || 'sequential',
require_approver_comment: topic.require_approver_comment ?? false,
requires_file: topic.requires_file ?? false,
require_observer_selection: topic.require_observer_selection ?? false,
instructions: topic.instructions || '',
})
} else if (!isEditMode) {
form.reset()
}
}, [topic, isEditMode])
const categoryOptions = categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const handleSubmit = async (values: typeof form.values) => {
const payload = {
category_id: values.category_id!,
name: values.name,
code: values.code,
duration_type: values.duration_type || undefined,
time_type: values.time_type || undefined,
payment_type: values.payment_type || undefined,
template: values.template || null,
allows_file: values.allows_file,
is_active: values.is_active,
allow_approver_selection: values.allow_approver_selection,
first_approver_role_code: values.first_approver_role_code || null,
allow_observer_selection: values.allow_observer_selection,
allow_delegation_selection: values.allow_delegation_selection,
approval_mode: values.approval_mode,
require_approver_comment: values.require_approver_comment,
requires_file: values.requires_file,
require_observer_selection: values.require_observer_selection,
instructions: values.instructions || null,
}
if (isEditMode && topicId) {
await updateTopic.mutateAsync({ id: topicId, ...payload })
} else {
await createTopic.mutateAsync(payload)
}
onClose()
}
const isLoading = topicLoading
const isSubmitting = createTopic.isPending || updateTopic.isPending
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group>
<Text fw={700}>
{isEditMode ? 'Редактирование темы' : 'Создание темы'}
</Text>
{topic && <Badge variant="light">ID: {topic.id}</Badge>}
</Group>
}
size="xl"
>
{isLoading ? (
<Center p={40}>
<Loader />
</Center>
) : (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
{/* Основные поля */}
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm">Основные параметры</Text>
<Stack gap="md">
<Select
label="Категория"
placeholder="Выберите категорию"
data={categoryOptions}
value={form.values.category_id ? String(form.values.category_id) : null}
onChange={(v) => form.setFieldValue('category_id', v ? Number(v) : null)}
searchable
required
/>
<TextInput
label="Название"
placeholder="Отпуск — несколько дней"
required
{...form.getInputProps('name')}
/>
<TextInput
label="Код"
placeholder="vacation_multi_day"
required
description="Уникальный идентификатор (lowercase, цифры, подчеркивания)"
disabled={isEditMode}
{...form.getInputProps('code')}
/>
<Textarea
label="Шаблон текста заявки"
placeholder="Пример заполнения..."
minRows={3}
{...form.getInputProps('template')}
/>
<Textarea
label="Инструкция для согласующего"
placeholder="Что нужно сделать для согласования заявки..."
minRows={2}
{...form.getInputProps('instructions')}
/>
</Stack>
</Paper>
{/* Типы */}
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm">Типы и параметры</Text>
<Stack gap="md">
<Select
label="Тип длительности"
placeholder="Не указан"
data={DURATION_TYPES}
value={form.values.duration_type || null}
onChange={(v) => form.setFieldValue('duration_type', v || '')}
clearable
/>
<Select
label="Тип времени"
placeholder="Не указан"
data={TIME_TYPES}
value={form.values.time_type || null}
onChange={(v) => form.setFieldValue('time_type', v || '')}
clearable
/>
<Select
label="Тип оплаты"
placeholder="Не указан"
data={PAYMENT_TYPES}
value={form.values.payment_type || null}
onChange={(v) => form.setFieldValue('payment_type', v || '')}
clearable
/>
<Select
label="Режим согласования"
data={APPROVAL_MODES}
value={form.values.approval_mode || 'sequential'}
onChange={(v) => form.setFieldValue('approval_mode', v || 'sequential')}
/>
</Stack>
</Paper>
{/* Настройки согласования */}
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm">Настройки согласования</Text>
<Stack gap="sm">
<Switch
label="Выбор согласующего из иерархии"
description="Пользователь может выбрать согласующего из списка людей, прописанных в иерархии (user_hierarchy) для этой темы"
checked={form.values.allow_approver_selection}
onChange={(e) => form.setFieldValue('allow_approver_selection', e.currentTarget.checked)}
/>
<TextInput
label="Код роли первого согласующего"
placeholder="supervisor, manager..."
description="Если указан — первый согласующий выбирается из пользователей с этой ролью. Работает независимо от выбора из иерархии."
value={form.values.first_approver_role_code}
onChange={(e) => form.setFieldValue('first_approver_role_code', e.currentTarget.value)}
/>
<Switch
label="Разрешить выбор наблюдателя"
description="Пользователь может добавить наблюдателей"
checked={form.values.allow_observer_selection}
onChange={(e) => form.setFieldValue('allow_observer_selection', e.currentTarget.checked)}
/>
<Switch
label="Требовать выбор наблюдателя"
description="Наблюдатель обязателен"
checked={form.values.require_observer_selection}
onChange={(e) => form.setFieldValue('require_observer_selection', e.currentTarget.checked)}
disabled={!form.values.allow_observer_selection}
/>
<Switch
label="Требовать комментарий согласующего"
description="Согласующий должен оставить комментарий"
checked={form.values.require_approver_comment}
onChange={(e) => form.setFieldValue('require_approver_comment', e.currentTarget.checked)}
/>
<Switch
label="Разрешить делегирование обязанностей"
description="В конце заявки сотруднику предложат делегировать все согласования на время отсутствия другому человеку (актуально для отгула/отпуска/больничного)"
checked={form.values.allow_delegation_selection}
onChange={(e) => form.setFieldValue('allow_delegation_selection', e.currentTarget.checked)}
/>
</Stack>
</Paper>
{/* Файлы */}
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm">Файлы</Text>
<Stack gap="sm">
<Switch
label="Разрешить прикрепление файлов"
description="Пользователь может прикрепить файлы"
checked={form.values.allows_file}
onChange={(e) => form.setFieldValue('allows_file', e.currentTarget.checked)}
/>
<Switch
label="Требовать файл"
description="Файл обязателен для подачи заявки"
checked={form.values.requires_file}
onChange={(e) => form.setFieldValue('requires_file', e.currentTarget.checked)}
disabled={!form.values.allows_file}
/>
</Stack>
</Paper>
{/* Статус */}
<Switch
label="Активна"
description="Неактивные темы не будут доступны для создания заявок"
checked={form.values.is_active}
onChange={(e) => form.setFieldValue('is_active', e.currentTarget.checked)}
/>
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
{isEditMode ? 'Сохранить' : 'Создать'}
</Button>
</Group>
</Stack>
</form>
)}
</Modal>
)
}
-----END src/pages/topics/components/TopicEditModal.tsx-----
File: src/pages/users/UsersPage.tsx
Lines: 330
-----BEGIN src/pages/users/UsersPage.tsx-----
import { useState, useMemo } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Text,
TextInput,
Select,
MultiSelect, // ✅ Добавлен
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Modal,
Button,
} from '@mantine/core'
import { IconPencil, IconSearch, IconTrash } from '@tabler/icons-react'
import { useUsers, useDeleteUser } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/users/hooks/useDepartments'
import { useRoles } from '@/features/users/hooks/useRoles' // ✅ Добавлен
import UserEditModal from "@/components/UserEditModal.tsx"
import { useAuth } from '@/hooks/useAuth'
const LIMIT = 20
export default function UsersPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [selectedRoleIds, setSelectedRoleIds] = useState<number[]>([]) // ✅ Массив ID ролей
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
const [statusFilter, setStatusFilter] = useState<string | null>(null)
const [editUserId, setEditUserId] = useState<number | null>(null)
const [deleteUserId, setDeleteUserId] = useState<number | null>(null)
const { user: currentUser } = useAuth()
const isRootAdmin = currentUser?.is_root === true
const { data, isLoading, isFetching } = useUsers({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(departmentFilter && { department_id: Number(departmentFilter) }),
...(statusFilter === 'blocked' && { is_blocked: true }),
...(statusFilter === 'fired' && { is_fired: true }),
...(statusFilter === 'active' && { is_blocked: false, is_fired: false }),
...(search && { full_name: search }),
...(selectedRoleIds.length > 0 && { role_ids: selectedRoleIds }), // ✅ Передаём массив
})
const { data: departments } = useDepartments()
const { data: allRoles } = useRoles({ limit: 1000 }) // ✅ Получаем все роли
const deleteUser = useDeleteUser()
const departmentOptions = useMemo(() => {
if (!departments || !Array.isArray(departments)) return []
return departments.map((d) => ({
value: String(d.id),
label: d.name || '',
}))
}, [departments])
const roleOptions = useMemo(() => {
if (!allRoles || !Array.isArray(allRoles)) return []
return allRoles.map((r) => ({
value: String(r.id),
label: r.name || '',
}))
}, [allRoles])
const users = Array.isArray(data?.data) ? data.data : []
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
const hasSelected = selectedRoleIds.length > 0;
const handleDelete = async () => {
if (!deleteUserId) return
await deleteUser.mutateAsync(deleteUserId)
setDeleteUserId(null)
}
return (
<Stack gap="md">
<Group justify="space-between">
<Text size="xl" fw={700}>Пользователи</Text>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
</Group>
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<TextInput
label="Поиск по имени"
placeholder="Иванов Иван..."
leftSection={<IconSearch size={16} />}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
style={{ flex: 1 }}
/>
<Box style={{ width: 250 }}>
<MultiSelect
label="Роли"
// ✅ Меняем placeholder в зависимости от количества выбранных
placeholder={hasSelected ? `Выбрано: ${selectedRoleIds.length}` : "Все роли"}
data={roleOptions}
value={selectedRoleIds.map(String)}
onChange={(v) => {
setSelectedRoleIds(v.map(Number))
setPage(1)
}}
searchable
clearable
maxDropdownHeight={400}
limit={15}
styles={{
input: {
minHeight: 36,
},
pill: {
display: 'none',
},
pillsList: {
display: 'none',
},
}}
/>
</Box>
<Select
label="Отдел"
placeholder="Все отделы"
data={departmentOptions}
value={departmentFilter}
onChange={(v) => {
setDepartmentFilter(v)
setPage(1)
}}
clearable
style={{ minWidth: 200 }}
/>
<Select
label="Статус"
placeholder="Все"
data={[
{ value: 'active', label: 'Активные' },
{ value: 'blocked', label: 'Заблокированные' },
{ value: 'fired', label: 'Уволенные' },
]}
value={statusFilter}
onChange={(v) => {
setStatusFilter(v)
setPage(1)
}}
clearable
style={{ minWidth: 180 }}
/>
</Group>
</Paper>
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Telegram ID</Table.Th>
<Table.Th>Имя</Table.Th>
<Table.Th>Username</Table.Th>
<Table.Th>Отдел</Table.Th>
<Table.Th>Роли</Table.Th>
<Table.Th>Статус</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{users.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={8}>
<Center p={40}>
<Text c="dimmed">Пользователи не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
users.map((user) => (
<Table.Tr key={user.id}>
<Table.Td>{user.id}</Table.Td>
<Table.Td>
<Text size="sm" ff="monospace">{user.telegram_id}</Text>
</Table.Td>
<Table.Td>
<Text fw={500}>{user.full_name}</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">@{user.username || '—'}</Text>
</Table.Td>
<Table.Td>
{user.department?.name || <Text c="dimmed">—</Text>}
</Table.Td>
<Table.Td>
<Group gap={4}>
{Array.isArray(user.user_roles) ? (
<>
{user.user_roles.slice(0, 3).map((ur) => (
<Badge key={ur.id} size="xs" variant="light">
{ur.role?.name || 'Роль'}
</Badge>
))}
{user.user_roles.length > 3 && (
<Badge size="xs" variant="outline">
+{user.user_roles.length - 3}
</Badge>
)}
</>
) : (
<Text size="xs" c="dimmed">—</Text>
)}
</Group>
</Table.Td>
<Table.Td>
<UserStatusBadge
isBlocked={user.is_blocked}
isFired={user.is_fired}
/>
</Table.Td>
<Table.Td>
<Group gap={4}>
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditUserId(user.id!)}
>
<IconPencil size={16} />
</ActionIcon>
</Tooltip>
{isRootAdmin && (
<Tooltip label="Удалить пользователя">
<ActionIcon
variant="light"
color="red"
onClick={() => setDeleteUserId(user.id!)}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
)}
</Group>
</Table.Td>
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={setPage}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</>
)}
</Paper>
{isFetching && !isLoading && (
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
<Loader size="xs" />
</Box>
)}
<UserEditModal
userId={editUserId}
opened={editUserId !== null}
onClose={() => setEditUserId(null)}
/>
<Modal
opened={deleteUserId !== null}
onClose={() => setDeleteUserId(null)}
title="Подтверждение удаления"
size="md"
>
<Stack gap="md">
<Text>
Вы уверены, что хотите удалить пользователя? Это действие нельзя отменить.
</Text>
<Group justify="flex-end">
<Button variant="default" onClick={() => setDeleteUserId(null)}>
Отмена
</Button>
<Button
color="red"
onClick={handleDelete}
loading={deleteUser.isPending}
>
Удалить
</Button>
</Group>
</Stack>
</Modal>
</Stack>
)
}
function UserStatusBadge({ isBlocked, isFired }: { isBlocked?: boolean; isFired?: boolean }) {
if (isFired) return <Badge color="gray" variant="filled">Уволен</Badge>
if (isBlocked) return <Badge color="red" variant="filled">Заблокирован</Badge>
return <Badge color="green" variant="light">Активен</Badge>
}
-----END src/pages/users/UsersPage.tsx-----
File: src/theme.ts
Lines: 17
-----BEGIN src/theme.ts-----
import { createTheme } from '@mantine/core'
export const theme = createTheme({
primaryColor: 'blue',
fontFamily: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif',
components: {
Button: {
defaultProps: {
size: 'sm',
},
},
Table: {
defaultProps: {
fontSize: 'sm',
},
},
},
})
-----END src/theme.ts-----
File: src/types/api.ts
Lines: 333
-----BEGIN src/types/api.ts-----
export interface User {
id?: number
telegram_id?: number
username?: string
full_name: string
language_code?: string
department_id?: number
is_blocked?: boolean
is_fired?: boolean
blocked_at?: string
last_login?: string
created_at?: string
updated_at?: string
department?: Department
user_roles?: UserRole[]
}
export interface Department {
id?: number
name: string
code: string
description?: string
is_active?: boolean
created_at?: string
updated_at?: string
}
export interface Role {
id?: number
name: string
code: string
is_default?: boolean
is_director?: boolean
is_approver?: boolean
is_controller?: boolean
is_observer?: boolean
is_executor?: boolean
description?: string
created_at?: string
updated_at?: string
}
export interface UserRole {
id?: number
user_id: number
role_id: number
created_at?: string
updated_at?: string
role?: Role
}
export interface Admin {
id?: number
login: string
name?: string
is_root?: boolean
is_observer?: boolean // 🆕
telegram_id?: number // 🆕
telegram_user?: User // 🆕
created_at?: string
last_login?: string
last_ip_login?: string
is_blocked?: boolean
password?: string
}
// 🆕 Типы для заявок
export interface ApprovalFile {
id?: number
approval_id?: number
file_base64?: string
file_name?: string
attached_by_id?: number
created_at?: string
}
export interface ApprovalStep {
id?: number
approval_id?: number
approver_id?: number
step_order?: number
status?: string
comment?: string
approver_name_snapshot?: string
approver_department_snapshot?: string
acted_at?: string
created_at?: string
updated_at?: string
returned_at?: string
approver?: User
}
export interface ApprovalTopicCategory {
id?: number
name: string
code: string
description?: string
is_active?: boolean
created_at?: string
updated_at?: string
topics?: ApprovalTopic[]
}
export interface ApprovalTopic {
id?: number
category_id?: number
name: string
code: string
approval_mode?: string
duration_type?: string
time_type?: string
payment_type?: string
template?: string
first_approver_role_code?: string
allows_file?: boolean
allow_approver_selection?: boolean
allow_observer_selection?: boolean
require_approver_comment?: boolean
requires_file?: boolean
require_observer_selection?: boolean
is_active?: boolean
created_at?: string
updated_at?: string
instructions?: string
category?: ApprovalTopicCategory
}
export interface Approval {
id?: number
initiator_id?: number
topic_id?: number
department_id?: number
content?: string
status?: string
revoked_by_id?: number
revoked_at?: string
created_at?: string
updated_at?: string
metadata?: string
revision_comment?: string
revision_by_id?: number
revision_at?: string
revision_count?: number
files?: ApprovalFile[]
initiator?: User
topic?: ApprovalTopic
department?: Department
revoked_by?: User
steps?: ApprovalStep[]
}
export interface ApiResponse<T> {
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-----
/// <reference types="vite/client" />
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-----