Updated admin panel project to 1.0v

This commit is contained in:
romanskijdev 2026-06-16 12:37:49 +03:00
parent 22e53e3561
commit f82821589f
79 changed files with 11221 additions and 144 deletions

9
.env Normal file
View File

@ -0,0 +1,9 @@
# API Configuration
#VITE_API_BASE_URL=http://localhost:1726/api
VITE_API_KEY=test
VITE_API_PUBLIC_KEY=ruspet_public_key_2026
VITE_API_PRIVATE_KEY=ruspet_private_key_SUPER_SECRET_2026
# App Configuration
VITE_APP_NAME=Ruspet Admin
VITE_APP_VERSION=1.0.0

7
.env.example Normal file
View File

@ -0,0 +1,7 @@
# API Configuration
VITE_API_BASE_URL=http://localhost:8081/api
VITE_API_KEY=your_api_key_here
# App Configuration
VITE_APP_NAME=Ruspet Admin
VITE_APP_VERSION=1.0.0

View File

@ -0,0 +1,96 @@
name: Deploy Frontend
on:
push:
branches: [main]
env:
REPO_DIR: "/workspace/ruspet_admin_frontend"
REPO_URL: "https://72.56.235.246.nip.io/gitea/romanskijdev/admin_ruspet.git"
BUILD_DIR: "/var/www/admin.ruspet.local"
jobs:
build-and-deploy:
runs-on: self-hosted
timeout-minutes: 15
steps:
- name: 📋 Deployment Info
run: |
echo "════════════════════════════════════════"
echo "🚀 Starting frontend deployment"
echo "════════════════════════════════════════"
echo "Branch: ${{ github.ref }}"
echo "Commit: ${{ github.sha }}"
echo "Author: ${{ github.actor }}"
echo "Time: $(date '+%Y-%m-%d %H:%M:%S')"
echo "════════════════════════════════════════"
- name: 📦 Checkout
run: |
if [ -d "$REPO_DIR/.git" ]; then
echo "📦 Updating existing repo..."
cd "$REPO_DIR"
git fetch origin
git reset --hard origin/main
else
echo "📦 Cloning repo..."
git clone "$REPO_URL" "$REPO_DIR"
fi
- name: 📥 Install dependencies
run: |
cd "$REPO_DIR"
npm ci
- name: 🔨 Build
run: |
cd "$REPO_DIR"
npm run build
echo "✅ Build completed"
ls -la dist/
- name: 📤 Deploy to web server
run: |
echo "📤 Deploying to $BUILD_DIR..."
# Создаем директорию если не существует
sudo mkdir -p "$BUILD_DIR"
# Очищаем старую версию
sudo rm -rf "$BUILD_DIR"/*
# Копируем новую сборку
sudo cp -r "$REPO_DIR/dist/"* "$BUILD_DIR/"
# Устанавливаем правильные права
sudo chown -R www-data:www-data "$BUILD_DIR"
sudo chmod -R 755 "$BUILD_DIR"
echo "✅ Frontend deployed successfully"
- name: ✅ Verify deployment
run: |
echo "🔍 Verifying deployment..."
if [ -f "$BUILD_DIR/index.html" ]; then
echo "✅ index.html exists"
echo "✅ Deployment verified successfully"
else
echo "❌ index.html not found"
exit 1
fi
- name: 📊 Deployment Summary
if: always()
run: |
echo "════════════════════════════════════════"
echo "📊 DEPLOYMENT SUMMARY"
echo "════════════════════════════════════════"
echo "Status: ${{ job.status }}"
echo "════════════════════════════════════════"
if [ "${{ job.status }}" == "success" ]; then
echo "✅ Frontend deployment completed!"
else
echo "❌ Frontend deployment failed!"
fi

523
package-lock.json generated
View File

@ -9,6 +9,7 @@
"version": "0.0.0",
"dependencies": {
"@mantine/core": "^9.3.1",
"@mantine/dates": "^9.3.1",
"@mantine/form": "^9.3.1",
"@mantine/hooks": "^9.3.1",
"@mantine/modals": "^9.3.1",
@ -16,14 +17,18 @@
"@tabler/icons-react": "^3.44.0",
"@tanstack/react-query": "^5.101.0",
"axios": "^1.18.0",
"crypto-js": "^4.2.0",
"dayjs": "^1.11.21",
"lodash-es": "^4.18.1",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"react-router-dom": "^7.17.0"
"react-router-dom": "^7.17.0",
"recharts": "^3.8.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/crypto-js": "^4.2.2",
"@types/lodash-es": "^4.17.12",
"@types/node": "^24.12.3",
"@types/react": "^19.2.14",
@ -636,6 +641,22 @@
"react-dom": "^19.2.0"
}
},
"node_modules/@mantine/dates": {
"version": "9.3.1",
"resolved": "https://registry.npmjs.org/@mantine/dates/-/dates-9.3.1.tgz",
"integrity": "sha512-Nh4XQyyV1AM0XRnUJugb1kNfCm++nkticsO8aroKmFPZ7cpGV7cjdL+4MJNPu1atS1EUePXl2VLLpKnrclpqOQ==",
"license": "MIT",
"dependencies": {
"clsx": "^2.1.1"
},
"peerDependencies": {
"@mantine/core": "9.3.1",
"@mantine/hooks": "9.3.1",
"dayjs": ">=1.0.0",
"react": "^19.2.0",
"react-dom": "^19.2.0"
}
},
"node_modules/@mantine/form": {
"version": "9.3.1",
"resolved": "https://registry.npmjs.org/@mantine/form/-/form-9.3.1.tgz",
@ -725,6 +746,42 @@
"url": "https://github.com/sponsors/Boshen"
}
},
"node_modules/@reduxjs/toolkit": {
"version": "2.12.0",
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.12.0.tgz",
"integrity": "sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw==",
"license": "MIT",
"dependencies": {
"@standard-schema/spec": "^1.0.0",
"@standard-schema/utils": "^0.3.0",
"immer": "^11.0.0",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
"reselect": "^5.1.0"
},
"peerDependencies": {
"react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
},
"react-redux": {
"optional": true
}
}
},
"node_modules/@reduxjs/toolkit/node_modules/immer": {
"version": "11.1.8",
"resolved": "https://registry.npmjs.org/immer/-/immer-11.1.8.tgz",
"integrity": "sha512-/tbkHMW7y10Lx6i1crLjD4/OhNkRG+Fo7byZHtah0547nIeXYcpIXaUh0IAQY6gO5459qpGGYapcEOHtFXkIuA==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/immer"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz",
@ -996,6 +1053,12 @@
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT"
},
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
"node_modules/@tabler/icons": {
"version": "3.44.0",
"resolved": "https://registry.npmjs.org/@tabler/icons/-/icons-3.44.0.tgz",
@ -1059,6 +1122,76 @@
"tslib": "^2.4.0"
}
},
"node_modules/@types/crypto-js": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.2.2.tgz",
"integrity": "sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/d3-array": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
"integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
"license": "MIT"
},
"node_modules/@types/d3-color": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
"license": "MIT"
},
"node_modules/@types/d3-ease": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
"license": "MIT"
},
"node_modules/@types/d3-interpolate": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
"integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
"license": "MIT",
"dependencies": {
"@types/d3-color": "*"
}
},
"node_modules/@types/d3-path": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
"license": "MIT"
},
"node_modules/@types/d3-scale": {
"version": "4.0.9",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
"integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
"license": "MIT",
"dependencies": {
"@types/d3-time": "*"
}
},
"node_modules/@types/d3-shape": {
"version": "3.1.8",
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",
"integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "*"
}
},
"node_modules/@types/d3-time": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
"license": "MIT"
},
"node_modules/@types/d3-timer": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
"license": "MIT"
},
"node_modules/@types/esrecurse": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
@ -1127,6 +1260,12 @@
"@types/react": "^19.2.0"
}
},
"node_modules/@types/use-sync-external-store": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
"license": "MIT"
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.61.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.61.0.tgz",
@ -1419,6 +1558,15 @@
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/adler-32": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz",
"integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
@ -1570,6 +1718,19 @@
],
"license": "CC-BY-4.0"
},
"node_modules/cfb": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz",
"integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"crc-32": "~1.2.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@ -1579,6 +1740,15 @@
"node": ">=6"
}
},
"node_modules/codepage": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz",
"integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@ -1611,6 +1781,18 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
"license": "Apache-2.0",
"bin": {
"crc32": "bin/crc32.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@ -1626,12 +1808,139 @@
"node": ">= 8"
}
},
"node_modules/crypto-js": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
"license": "MIT"
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"license": "MIT"
},
"node_modules/d3-array": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
"integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
"license": "ISC",
"dependencies": {
"internmap": "1 - 2"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-color": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
"integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-ease": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
"integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-format": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",
"integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
"integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-path": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
"integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
"integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
"license": "ISC",
"dependencies": {
"d3-array": "2.10.0 - 3",
"d3-format": "1 - 3",
"d3-interpolate": "1.2.0 - 3",
"d3-time": "2.1.1 - 3",
"d3-time-format": "2 - 4"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-shape": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
"integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
"license": "ISC",
"dependencies": {
"d3-path": "^3.1.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
"integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
"license": "ISC",
"dependencies": {
"d3-array": "2 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time-format": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
"integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
"license": "ISC",
"dependencies": {
"d3-time": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-timer": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
"integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/dayjs": {
"version": "1.11.21",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.21.tgz",
@ -1655,6 +1964,12 @@
}
}
},
"node_modules/decimal.js-light": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",
"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
"license": "MIT"
},
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@ -1763,6 +2078,16 @@
"node": ">= 0.4"
}
},
"node_modules/es-toolkit": {
"version": "1.47.1",
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.47.1.tgz",
"integrity": "sha512-5RAqEwf4P4E17p+W75KLOWw/nOvKZzSQpxM32IpI2KZLaVonjTrZ0Ai5ghMaVI9eKC2p8eoQgcBdkEDgzFk6+Q==",
"license": "MIT",
"workspaces": [
"docs",
"benchmarks"
]
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
@ -1971,6 +2296,12 @@
"node": ">=0.10.0"
}
},
"node_modules/eventemitter3": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
"license": "MIT"
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@ -2096,6 +2427,15 @@
"node": ">= 6"
}
},
"node_modules/frac": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz",
"integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@ -2293,6 +2633,16 @@
"node": ">= 4"
}
},
"node_modules/immer": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz",
"integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/immer"
}
},
"node_modules/imurmurhash": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
@ -2303,6 +2653,15 @@
"node": ">=0.8.19"
}
},
"node_modules/internmap": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@ -3029,6 +3388,29 @@
"react-dom": "^0.14 || ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/react-redux": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.0.tgz",
"integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==",
"license": "MIT",
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0"
},
"peerDependencies": {
"@types/react": "^18.2.25 || ^19",
"react": "^18.0 || ^19",
"redux": "^5.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"redux": {
"optional": true
}
}
},
"node_modules/react-remove-scroll": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",
@ -3152,6 +3534,57 @@
"react-dom": ">=16.6.0"
}
},
"node_modules/recharts": {
"version": "3.8.1",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.8.1.tgz",
"integrity": "sha512-mwzmO1s9sFL0TduUpwndxCUNoXsBw3u3E/0+A+cLcrSfQitSG62L32N69GhqUrrT5qKcAE3pCGVINC6pqkBBQg==",
"license": "MIT",
"workspaces": [
"www"
],
"dependencies": {
"@reduxjs/toolkit": "^1.9.0 || 2.x.x",
"clsx": "^2.1.1",
"decimal.js-light": "^2.5.1",
"es-toolkit": "^1.39.3",
"eventemitter3": "^5.0.1",
"immer": "^10.1.1",
"react-redux": "8.x.x || 9.x.x",
"reselect": "5.1.1",
"tiny-invariant": "^1.3.3",
"use-sync-external-store": "^1.2.2",
"victory-vendor": "^37.0.2"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/redux": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT"
},
"node_modules/redux-thunk": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
"integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
"license": "MIT",
"peerDependencies": {
"redux": "^5.0.0"
}
},
"node_modules/reselect": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",
"integrity": "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==",
"license": "MIT"
},
"node_modules/rolldown": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.3.tgz",
@ -3241,6 +3674,18 @@
"node": ">=0.10.0"
}
},
"node_modules/ssf": {
"version": "0.11.2",
"resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz",
"integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
"license": "Apache-2.0",
"dependencies": {
"frac": "~1.1.2"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/tabbable": {
"version": "6.4.0",
"resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.4.0.tgz",
@ -3259,6 +3704,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/tiny-invariant": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
"license": "MIT"
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@ -3452,6 +3903,37 @@
}
}
},
"node_modules/use-sync-external-store": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/victory-vendor": {
"version": "37.3.6",
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",
"integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==",
"license": "MIT AND ISC",
"dependencies": {
"@types/d3-array": "^3.0.3",
"@types/d3-ease": "^3.0.0",
"@types/d3-interpolate": "^3.0.1",
"@types/d3-scale": "^4.0.2",
"@types/d3-shape": "^3.1.0",
"@types/d3-time": "^3.0.0",
"@types/d3-timer": "^3.0.0",
"d3-array": "^3.1.6",
"d3-ease": "^3.0.1",
"d3-interpolate": "^3.0.1",
"d3-scale": "^4.0.2",
"d3-shape": "^3.1.0",
"d3-time": "^3.0.0",
"d3-timer": "^3.0.1"
}
},
"node_modules/vite": {
"version": "8.0.16",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.0.16.tgz",
@ -3546,6 +4028,24 @@
"node": ">= 8"
}
},
"node_modules/wmf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz",
"integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz",
"integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
@ -3556,6 +4056,27 @@
"node": ">=0.10.0"
}
},
"node_modules/xlsx": {
"version": "0.18.5",
"resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz",
"integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"cfb": "~1.2.1",
"codepage": "~1.15.0",
"crc-32": "~1.2.1",
"ssf": "~0.11.2",
"wmf": "~1.0.1",
"word": "~0.3.0"
},
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",

View File

@ -11,6 +11,7 @@
},
"dependencies": {
"@mantine/core": "^9.3.1",
"@mantine/dates": "^9.3.1",
"@mantine/form": "^9.3.1",
"@mantine/hooks": "^9.3.1",
"@mantine/modals": "^9.3.1",
@ -18,14 +19,18 @@
"@tabler/icons-react": "^3.44.0",
"@tanstack/react-query": "^5.101.0",
"axios": "^1.18.0",
"crypto-js": "^4.2.0",
"dayjs": "^1.11.21",
"lodash-es": "^4.18.1",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"react-router-dom": "^7.17.0"
"react-router-dom": "^7.17.0",
"recharts": "^3.8.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/crypto-js": "^4.2.2",
"@types/lodash-es": "^4.17.12",
"@types/node": "^24.12.3",
"@types/react": "^19.2.14",

View File

@ -1,122 +1,70 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from './assets/vite.svg'
import heroImg from './assets/hero.png'
import './App.css'
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'
function App() {
const [count, setCount] = useState(0)
const Placeholder = ({ title }: { title: string }) => (
<div style={{ padding: 40 }}>
<Text size="xl" fw={700} mb="md">{title}</Text>
<Text c="dimmed">Страница в разработке...</Text>
</div>
)
return (
<>
<section id="center">
<div className="hero">
<img src={heroImg} className="base" width="170" height="179" alt="" />
<img src={reactLogo} className="framework" alt="React logo" />
<img src={viteLogo} className="vite" alt="Vite logo" />
</div>
<div>
<h1>Get started</h1>
<p>
Edit <code>src/App.tsx</code> and save to test <code>HMR</code>
</p>
</div>
<button
type="button"
className="counter"
onClick={() => setCount((count) => count + 1)}
>
Count is {count}
</button>
</section>
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated, loading } = useAuth()
<div className="ticks"></div>
if (loading) {
return (
<Center h="100vh">
<Loader />
</Center>
)
}
<section id="next-steps">
<div id="docs">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#documentation-icon"></use>
</svg>
<h2>Documentation</h2>
<p>Your questions, answered</p>
<ul>
<li>
<a href="https://vite.dev/" target="_blank">
<img className="logo" src={viteLogo} alt="" />
Explore Vite
</a>
</li>
<li>
<a href="https://react.dev/" target="_blank">
<img className="button-icon" src={reactLogo} alt="" />
Learn more
</a>
</li>
</ul>
</div>
<div id="social">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#social-icon"></use>
</svg>
<h2>Connect with us</h2>
<p>Join the Vite community</p>
<ul>
<li>
<a href="https://github.com/vitejs/vite" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#github-icon"></use>
</svg>
GitHub
</a>
</li>
<li>
<a href="https://chat.vite.dev/" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#discord-icon"></use>
</svg>
Discord
</a>
</li>
<li>
<a href="https://x.com/vite_js" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#x-icon"></use>
</svg>
X.com
</a>
</li>
<li>
<a href="https://bsky.app/profile/vite.dev" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#bluesky-icon"></use>
</svg>
Bluesky
</a>
</li>
</ul>
</div>
</section>
if (!isAuthenticated) {
return <Navigate to="/login" replace />
}
<div className="ticks"></div>
<section id="spacer"></section>
</>
)
return <>{children}</>
}
export default App
function App() {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route element={<ProtectedRoute><MainLayout /></ProtectedRoute>}>
<Route path="/" element={<Dashboard />} />
<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="/approval-tasks" element={<ApprovalTasksPage />} />
</Route>
</Routes>
)
}
export default App

36
src/api/admins.ts Normal file
View File

@ -0,0 +1,36 @@
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
}
export interface UpdateAdminRequest {
id: number
name?: string
is_blocked?: boolean
is_root?: boolean
}
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 } }),
}

32
src/api/approvalTasks.ts Normal file
View File

@ -0,0 +1,32 @@
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 } }),
}

96
src/api/approvals.ts Normal file
View File

@ -0,0 +1,96 @@
import apiClient from './client'
import type { Approval, ApiResponse } from '@/types/api'
export interface ApprovalsListParams {
offset?: number
limit?: number
status?: string
initiator_id?: number
topic_id?: number
department_id?: number
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 = {}) =>
apiClient.get<ApiResponse<Approval[]>>('/approvals', { params }),
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 } }),
// 🆕 Получение заявок для отчёта (с фильтрами по датам)
getForReport: (params: ApprovalsReportParams = {}) =>
apiClient.get<ApiResponse<Approval[]>>('/approvals/report', { params }),
downloadReport: (params: ApprovalsReportParams = {}) =>
apiClient.get('/approvals/report/download', {
params,
responseType: 'blob',
}),
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 apiKey = import.meta.env.VITE_API_KEY
const timestamp = Math.floor(Date.now() / 1000).toString()
const deviceId = localStorage.getItem('device_id') || 'admin-panel'
// Генерируем HMAC подпись (как в client.ts)
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)
// Создаём URL с query параметрами
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
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
})
},
}

22
src/api/auth.ts Normal file
View File

@ -0,0 +1,22 @@
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),
}

42
src/api/categories.ts Normal file
View File

@ -0,0 +1,42 @@
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 } }),
}

View File

@ -1,4 +1,37 @@
import axios from 'axios'
import CryptoJS from 'crypto-js'
// Функция генерации 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')
console.log('[DeviceID] Checking localStorage:', {
exists: !!deviceId,
value: deviceId || 'null'
})
if (!deviceId) {
deviceId = crypto.randomUUID()
localStorage.setItem('device_id', deviceId)
console.log('[DeviceID] 🆕 Created and saved new device_id:', deviceId)
// Проверяем, что действительно сохранилось
const saved = localStorage.getItem('device_id')
console.log('[DeviceID] ✅ Verification - saved value:', saved)
} else {
console.log('[DeviceID] ✅ Using existing device_id:', deviceId)
}
return deviceId
}
const apiClient = axios.create({
baseURL: '/api',
@ -7,27 +40,60 @@ const apiClient = axios.create({
},
})
// Interceptor для добавления токена
// Interceptor для добавления токена и HMAC подписи
apiClient.interceptors.request.use((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')
}
// Добавляем API ключ и timestamp (как в backend)
config.headers.ApiKey = import.meta.env.VITE_API_KEY || ''
config.headers['X-Timestamp'] = Date.now().toString()
config.headers['x-device-id'] = localStorage.getItem('device_id') || 'admin-panel'
// Генерируем HMAC подпись
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
const timestamp = Math.floor(Date.now() / 1000).toString()
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] === Request interceptor finished ===')
return config
})
// Interceptor для обработки ошибок
apiClient.interceptors.response.use(
(response) => response,
(response) => {
console.log('[API] ✅ Response success:', response.config.url)
return response
},
(error) => {
console.error('[API] ❌ Response error:', {
status: error.response?.status,
statusText: error.response?.statusText,
data: error.response?.data,
url: error.config?.url,
})
if (error.response?.status === 401) {
console.warn('[API] ⚠️ Unauthorized, redirecting to login')
localStorage.removeItem('token')
// НЕ удаляем device_id!
window.location.href = '/login'
}
return Promise.reject(error)

33
src/api/dashboard.ts Normal file
View File

@ -0,0 +1,33 @@
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 }>
topTopics: Array<{
id: number
name: string
category_name: string
total_count: number
pending_count: number
}>
topApprovers: Array<{
user_id: number
full_name: string
department_name: string
total_steps: number
pending_steps: number
}>
oldPendingCount: number
}
export const dashboardApi = {
// 🆕 Один endpoint — все данные сразу
getStats: () => apiClient.get<DashboardStats>('/dashboard/stats'),
}

47
src/api/departments.ts Normal file
View File

@ -0,0 +1,47 @@
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 } }),
}

48
src/api/hierarchies.ts Normal file
View File

@ -0,0 +1,48 @@
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
}
export interface CreateHierarchyRequest {
subordinate_id: number
approver_id: number
department_id: number
topic_category_id?: number | null
topic_id?: number | null
priority?: number
}
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
}
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 } }),
}

43
src/api/permissions.ts Normal file
View File

@ -0,0 +1,43 @@
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 } }),
}

59
src/api/roles.ts Normal file
View File

@ -0,0 +1,59 @@
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
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
}
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
}
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 } }),
}

49
src/api/topicExecutors.ts Normal file
View File

@ -0,0 +1,49 @@
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 } }),
}

69
src/api/topics.ts Normal file
View File

@ -0,0 +1,69 @@
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
}
export interface CreateTopicRequest {
category_id: number
name: string
code: string
duration_type?: string
time_type?: string
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
approval_mode?: string
require_approver_comment?: boolean
requires_file?: boolean
require_observer_selection?: boolean
instructions?: string | null
}
export interface UpdateTopicRequest {
id: number
category_id?: number
name?: string
code?: string
duration_type?: string
time_type?: string
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
approval_mode?: string
require_approver_comment?: boolean
requires_file?: boolean
require_observer_selection?: boolean
instructions?: 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 } }),
}

17
src/api/userRoles.ts Normal file
View File

@ -0,0 +1,17 @@
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),
}

32
src/api/users.ts Normal file
View File

@ -0,0 +1,32 @@
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
}
export interface UpdateUserRequest {
id: number
department_id?: number | null
is_blocked?: boolean
is_fired?: boolean
}
export const usersApi = {
// Получить список пользователей с пагинацией и фильтрами
getList: (params: UsersListParams = {}) =>
apiClient.get<ApiResponse<User[]>>('/users', { params }),
// Получить пользователя по ID
getById: (id: number) =>
apiClient.get<User>(`/users/${id}`),
// Обновить пользователя
update: (data: UpdateUserRequest) =>
apiClient.put<User>('/users', data),
}

View File

@ -0,0 +1,74 @@
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}>
Ruspet Admin Panel
</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>
)
}

View File

@ -0,0 +1,39 @@
import { AppShell } from '@mantine/core'
import { useDisclosure } from '@mantine/hooks'
import { Outlet } from 'react-router-dom'
import Sidebar from './Sidebar'
import Header from './Header'
export default function MainLayout() {
const [mobileOpened, { toggle: toggleMobile }] = useDisclosure()
const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true)
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}>
<Outlet />
</AppShell.Main>
</AppShell>
)
}

View File

@ -0,0 +1,167 @@
import { useState } from 'react'
import { NavLink, Box, Text, Stack } from '@mantine/core'
import {
IconDashboard,
IconFileCheck,
IconSettings,
IconChevronRight,
IconList,
IconUsers,
IconBuilding,
IconShield,
IconKey,
IconCategory,
IconBriefcase,
IconUserCheck,
IconGitBranch,
IconUserCog,
IconCheck,
} from '@tabler/icons-react'
import { useLocation, useNavigate } from 'react-router-dom'
interface MenuItem {
label: string
icon?: any
path?: string
children?: MenuItem[]
}
const menuItems: MenuItem[] = [
{ label: 'Dashboard', icon: IconDashboard, path: '/' },
{ label: 'Администраторы', icon: IconUserCog, path: '/admins' },
{
label: 'Система согласований',
icon: IconFileCheck,
children: [
{ label: 'Заявки', icon: IconList, path: '/approvals' },
{ label: 'Задачи', icon: IconCheck, path: '/approval-tasks' },
{ label: 'Пользователи', icon: IconUsers, path: '/users' },
{ label: 'Отделы', icon: IconBuilding, path: '/departments' },
{ label: 'Роли', icon: IconShield, path: '/roles' },
{ label: 'Права', icon: IconKey, path: '/permissions' },
{
label: 'Темы согласований',
icon: IconBriefcase,
children: [
{ label: 'Категории', icon: IconCategory, path: '/categories' },
{ label: 'Темы', icon: IconBriefcase, path: '/topics' },
{ label: 'Исполнители', icon: IconUserCheck, path: '/executors' },
]
},
{ label: 'Иерархия', icon: IconGitBranch, path: '/hierarchies' },
]
},
{ label: 'Настройки', icon: IconSettings, path: '/settings' },
]
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
// ✅ Используем padding вместо marginLeft для правильного выравнивания
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() {
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>
<Stack gap={4}>
{menuItems.map((item) => (
<MenuItemLink key={item.label} item={item} level={0} />
))}
</Stack>
</Box>
)
}

View File

@ -0,0 +1,212 @@
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Select,
MultiSelect,
Switch,
Group,
Button,
Text,
Divider,
Loader,
Center,
Badge,
Paper,
} from '@mantine/core'
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'
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()
const { data: userRoles, isLoading: rolesLoading } = useUserRoles(userId)
const updateUser = useUpdateUser()
const assignRoles = useBulkAssignRoles()
const form = useForm({
initialValues: {
department_id: null as number | null,
is_blocked: false,
is_fired: false,
role_ids: [] as number[],
},
})
// Заполняем форму данными пользователя
useEffect(() => {
if (user) {
form.setValues({
department_id: user.department_id || null,
is_blocked: user.is_blocked || false,
is_fired: user.is_fired || false,
role_ids: user.user_roles?.map((ur) => ur.role_id!) || [],
})
}
}, [user])
// Заполняем роли из отдельного запроса
useEffect(() => {
if (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,
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 departmentOptions = departments?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || []
const roleOptions = 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="lg"
>
{isLoading ? (
<Center p={40}>
<Loader />
</Center>
) : user ? (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
{/* Информация о пользователе (только для чтения) */}
<Paper withBorder p="md" bg="gray.0">
<Stack gap="xs">
<Group justify="space-between">
<Text size="sm" c="dimmed">Имя:</Text>
<Text fw={500}>{user.full_name}</Text>
</Group>
<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>
<Divider label="Настройки" labelPosition="center" />
{/* Отдел */}
<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
/>
{/* Роли */}
<MultiSelect
label="Роли"
placeholder="Выберите роли"
data={roleOptions}
value={form.values.role_ids.map(String)}
onChange={(v) => form.setFieldValue('role_ids', v.map(Number))}
searchable
clearable
description="Пользователь может иметь несколько ролей"
/>
<Divider />
{/* Статусы */}
<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"
/>
{/* Кнопки */}
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
Сохранить
</Button>
</Group>
</Stack>
</form>
) : (
<Center p={40}>
<Text c="dimmed">Пользователь не найден</Text>
</Center>
)}
</Modal>
)
}

View File

@ -0,0 +1,109 @@
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 // ✅ Извлекаем Admin из AxiosResponse
},
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-администратор может создавать новых администраторов'
}
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 = 'Нельзя заблокировать свой собственный аккаунт'
}
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',
})
},
})
}

View File

@ -0,0 +1,20 @@
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: 'Отменена',
}

View File

@ -0,0 +1,77 @@
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',
})
},
})
}

View File

@ -0,0 +1,90 @@
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 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',
})
},
})
}

View File

@ -0,0 +1,101 @@
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',
})
},
})
}

View File

@ -0,0 +1,152 @@
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>
)
}

View File

@ -0,0 +1,101 @@
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',
})
},
})
}

View File

@ -0,0 +1,89 @@
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',
})
},
})
}

View File

@ -0,0 +1,87 @@
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
// Формируем ключ группы
const key = `${h.subordinate_id}-${h.department_id}-${scopeType}-${scopeObjectId || 'null'}`
if (!groups.has(key)) {
// Определяем название объекта области действия
let scopeObjectName = 'Все темы'
if (scopeType === 'category' && h.subordinate) {
// Будет заполнено позже из categories
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: 'Тема',
}

View File

@ -0,0 +1,29 @@
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: 'Наблюдение',
}

View File

@ -0,0 +1,101 @@
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',
})
},
})
}

View File

@ -0,0 +1,103 @@
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',
})
},
})
}

View File

@ -0,0 +1,89 @@
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',
})
},
})
}

View File

@ -0,0 +1,59 @@
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())
}

View File

@ -0,0 +1,38 @@
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: 'Официально',
}

View File

@ -0,0 +1,101 @@
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',
})
},
})
}

View File

@ -0,0 +1,14 @@
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 || []
},
})
}

View File

@ -0,0 +1,14 @@
import { useQuery } from '@tanstack/react-query'
import { rolesApi } from '@/api/roles.ts'
export const ROLES_QUERY_KEY = 'roles'
export function useRoles() {
return useQuery({
queryKey: [ROLES_QUERY_KEY],
queryFn: async () => {
const response = await rolesApi.getList()
return response.data.data || []
},
})
}

View File

@ -0,0 +1,40 @@
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',
})
},
})
}

View File

@ -0,0 +1,50 @@
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',
})
},
})
}

58
src/hooks/useAuth.ts Normal file
View File

@ -0,0 +1,58 @@
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 }
}

View File

@ -9,6 +9,7 @@ import App from './App'
import { theme } from './theme'
import '@mantine/core/styles.css'
import '@mantine/notifications/styles.css'
import '@mantine/dates/styles.css'
const queryClient = new QueryClient({
defaultOptions: {

426
src/pages/Dashboard.tsx Normal file
View File

@ -0,0 +1,426 @@
import { useEffect, useState } from 'react'
import {
SimpleGrid,
Paper,
Text,
Group,
Stack,
Loader,
Center,
Badge,
Progress,
Alert,
Box,
ThemeIcon,
} from '@mantine/core'
import {
IconUsers,
IconFileCheck,
IconBuilding,
IconShield,
IconCategory,
IconUserCheck,
IconAlertTriangle,
IconClock,
IconTrendingUp,
IconAlertCircle,
} from '@tabler/icons-react'
import {
PieChart,
Pie,
Cell,
ResponsiveContainer,
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from 'recharts'
import { dashboardApi } from '@/api/dashboard'
import type { DashboardStats } from '@/api/dashboard'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
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: 'На доработке',
}
export default function Dashboard() {
const [stats, setStats] = useState<DashboardStats | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
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)
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: старые pending заявки */}
{stats.oldPendingCount > 0 && (
<Alert
icon={<IconAlertTriangle size={16} />}
color="orange"
variant="light"
title={`⚠️ ${stats.oldPendingCount} заявок требуют внимания`}
>
<Text size="sm">
Есть заявки, которые находятся на согласовании более 7 дней.
</Text>
</Alert>
)}
{/* 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}
>
{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 mb="md">
<ThemeIcon variant="light" color="violet" size="lg">
<IconTrendingUp size={18} />
</ThemeIcon>
<Text fw={600}>Топ-5 самых активных тем</Text>
</Group>
{stats.topTopics.length === 0 ? (
<Center h={200}>
<Text c="dimmed">Нет данных</Text>
</Center>
) : (
<Stack gap="sm">
{stats.topTopics.map((topic, index) => {
const maxCount = Math.max(...stats.topTopics.map(t => t.total_count))
const percent = (topic.total_count / maxCount) * 100
return (
<Box key={topic.id}>
<Group justify="space-between" mb={4}>
<Group gap="xs">
<Badge size="sm" variant="light" color="gray">
#{index + 1}
</Badge>
<div>
<Text size="sm" fw={500} lineClamp={1}>{topic.name}</Text>
<Text size="xs" c="dimmed">{topic.category_name}</Text>
</div>
</Group>
<Group gap="xs">
<Text size="sm" fw={600}>{topic.total_count}</Text>
{topic.pending_count > 0 && (
<Badge size="xs" color="blue" variant="light">
{topic.pending_count} в работе
</Badge>
)}
</Group>
</Group>
<Progress value={percent} size="sm" color="violet" />
</Box>
)
})}
</Stack>
)}
</Paper>
{/* Топ согласующих */}
<Paper withBorder p="md" radius="md">
<Group mb="md">
<ThemeIcon variant="light" color="blue" size="lg">
<IconUsers size={18} />
</ThemeIcon>
<Text fw={600}>Топ-5 согласующих</Text>
</Group>
{stats.topApprovers.length === 0 ? (
<Center h={200}>
<Text c="dimmed">Нет данных</Text>
</Center>
) : (
<Stack gap="sm">
{stats.topApprovers.map((approver, index) => {
const maxSteps = Math.max(...stats.topApprovers.map(a => a.total_steps))
const percent = (approver.total_steps / maxSteps) * 100
return (
<Box key={approver.user_id}>
<Group justify="space-between" mb={4}>
<Group gap="xs">
<Badge size="sm" variant="light" color="gray">
#{index + 1}
</Badge>
<div>
<Text size="sm" fw={500}>{approver.full_name}</Text>
<Text size="xs" c="dimmed">{approver.department_name}</Text>
</div>
</Group>
<Group gap="xs">
<Text size="sm" fw={600}>{approver.total_steps}</Text>
{approver.pending_steps > 0 && (
<Badge size="xs" color="orange" variant="light">
{approver.pending_steps} ожидают
</Badge>
)}
</Group>
</Group>
<Progress value={percent} size="sm" color="blue" />
</Box>
)
})}
</Stack>
)}
</Paper>
</SimpleGrid>
{/* Заявки на доработке */}
{stats.approvals.revision > 0 && (
<Paper withBorder p="md" radius="md">
<Group mb="md">
<ThemeIcon variant="light" color="orange" size="lg">
<IconClock size={18} />
</ThemeIcon>
<Text fw={600}>Требуют внимания: {stats.approvals.revision} заявок на доработке</Text>
</Group>
<Text size="sm" c="dimmed">
Эти заявки были возвращены согласующими на доработку и требуют действий от инициаторов.
</Text>
</Paper>
)}
</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>
)
}

View File

@ -0,0 +1,231 @@
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>
)
}

86
src/pages/Login.tsx Normal file
View File

@ -0,0 +1,86 @@
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>
)
}

View File

@ -0,0 +1,368 @@
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,
} 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>Последний вход</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={8}>
<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>
<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>
)
}

View File

@ -0,0 +1,185 @@
import { useState } from 'react'
import {
Modal,
Stack,
TextInput,
Button,
Text,
Alert,
CopyButton,
ActionIcon,
Tooltip,
Group,
Paper,
Code,
Switch,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconCheck, IconCopy, IconKey, IconAlertCircle, IconShield } from '@tabler/icons-react'
import { useCreateAdmin } from '@/features/admins/hooks/useAdmins'
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 form = useForm({
initialValues: {
login: '',
name: '',
is_root: false,
},
validate: {
login: (value) => {
if (value.length < 3) return 'Логин должен содержать минимум 3 символа'
if (!/^[a-zA-Z0-9_]+$/.test(value)) return 'Логин может содержать только буквы, цифры и подчеркивания'
return null
},
},
})
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,
})
setCreatedAdmin(admin)
form.reset()
} catch (error) {
// Ошибка уже обработана в хуке
}
}
const handleClose = () => {
setCreatedAdmin(null)
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>
)}
</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"
/>
</Paper>
{form.values.is_root && (
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
<Text size="sm">
<b>Внимание!</b> Root-права дают полный доступ к системе, включая создание и удаление других администраторов.
</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>
)
}

View File

@ -0,0 +1,137 @@
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Button,
Text,
Group,
Badge,
Switch,
Paper,
Alert,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconShield, IconAlertCircle } from '@tabler/icons-react'
import { useUpdateAdmin } from '@/features/admins/hooks/useAdmins'
import { useAuth } from '@/hooks/useAuth'
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 form = useForm({
initialValues: {
name: '',
is_root: false,
},
})
useEffect(() => {
if (admin) {
form.setValues({
name: admin.name || '',
is_root: admin.is_root ?? false,
})
}
}, [admin])
const isCurrentUser = currentUser?.id === admin?.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,
})
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>
)}
</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}
/>
</Paper>
{isCurrentUser && (
<Alert icon={<IconAlertCircle size={16} />} color="yellow" variant="light">
<Text size="sm">
Вы не можете изменить свои собственные root-права.
</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>
)
}

View File

@ -0,0 +1,278 @@
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 { 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() {
const [page, setPage] = useState(1)
const [statusFilter, setStatusFilter] = useState<string | null>(null)
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>
)
}

View File

@ -0,0 +1,397 @@
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)}
/>
)}
</>
)
}

View File

@ -0,0 +1,458 @@
import {useEffect, useState} from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Select,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Divider,
Alert,
} from '@mantine/core'
import { DatePickerInput } from '@mantine/dates'
import {IconEye, IconSearch, IconFileText, IconFileExcel, IconInfoCircle, IconX} from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
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 { 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() {
// Фильтры списка
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [statusFilter, setStatusFilter] = useState<string | null>(null)
const [categoryFilter, setCategoryFilter] = useState<string | null>(null)
const [topicFilter, setTopicFilter] = useState<string | null>(null)
const [departmentFilter, setDepartmentFilter] = useState<string | null>(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)
const [searchInput, setSearchInput] = useState('')
const [searchError, setSearchError] = useState<string | null>(null)
const [debouncedSearch] = useDebouncedValue(searchInput, 400)
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: categoryTopics } = useTopics({
limit: 1000,
...(categoryFilter && { category_id: Number(categoryFilter) }),
})
const effectiveTopicFilter = categoryFilter && categoryTopics?.data?.length === 1
? String(categoryTopics.data[0].id)
: topicFilter
const { data, isLoading, isFetching } = useApprovals({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(search && { content: search }),
...(statusFilter && { status: statusFilter }),
...(effectiveTopicFilter && { topic_id: Number(effectiveTopicFilter) }),
...(departmentFilter && { department_id: Number(departmentFilter) }),
})
const { data: categories } = useCategories({ limit: 1000 })
const { data: topics } = useTopics({ limit: 1000 })
const { data: departments } = useDepartments()
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 topicOptions = topics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const departmentOptions = departments?.data?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || []
const handleCategoryChange = (value: string | null) => {
setCategoryFilter(value)
setTopicFilter(null)
setPage(1)
}
// 🆕 Генерация отчёта
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()
let fileName = `Согласования_${now.format('DD.MM.YYYY')}_${now.format('HH-mm')}.xlsx`
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(url)
notifications.show({
title: 'Успешно',
message: 'Отчёт сформирован и скачан',
color: 'green',
})
} catch (error: any) {
if (error.response?.data instanceof Blob) {
const text = await error.response.data.text()
notifications.show({
title: 'Ошибка',
message: text || 'Не удалось сформировать отчёт',
color: 'red',
})
} else {
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={setReportDateFrom}
clearable
style={{ flex: 1 }}
/>
<DatePickerInput
label="Дата окончания периода"
placeholder="Выберите дату"
value={reportDateTo}
onChange={setReportDateTo}
clearable
minDate={reportDateFrom || undefined}
style={{ flex: 1 }}
/>
</Group>
</Stack>
</Paper>
<Divider />
{/* Фильтры списка */}
<Paper withBorder p="md">
<Text fw={600} size="lg" mb="sm">Фильтры списка</Text>
<Stack gap="md">
<Group gap="md" align="flex-end">
<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>
)
}
style={{ flex: 1 }}
/>
<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
style={{ minWidth: 180 }}
/>
</Group>
<Group gap="md" align="flex-end">
<Select
label="Тема"
placeholder="Все темы"
data={topicOptions}
value={topicFilter}
onChange={(v) => {
setTopicFilter(v)
setPage(1)
}}
clearable
searchable
style={{ minWidth: 200 }}
disabled={!!categoryFilter}
/>
<Select
label="Отдел"
placeholder="Все отделы"
data={departmentOptions}
value={departmentFilter}
onChange={(v) => {
setDepartmentFilter(v)
setPage(1)
}}
clearable
style={{ minWidth: 180 }}
/>
</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>
)
}

View File

@ -0,0 +1,456 @@
import { useState } from 'react'
import {
Modal,
Stack,
Text,
Group,
Badge,
Paper,
Loader,
Center,
Timeline,
ScrollArea,
Box,
ActionIcon, Tooltip,
} from '@mantine/core'
import {
IconUser,
IconBuilding,
IconCalendar,
IconFileText,
IconCheck,
IconX,
IconClock,
IconAlertCircle,
IconEye,
IconDownload,
} from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import { useApproval } from '@/features/approvals/hooks/useApprovals'
import { useCategories } from '@/features/categories/hooks/useCategories'
import FilePreviewModal from './FilePreviewModal'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
dayjs.locale('ru')
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',
}
// 🆕 Типы файлов, для которых доступен предпросмотр
const PREVIEWABLE_TYPES = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/svg+xml',
'application/pdf',
'text/plain',
]
// 🆕 Определение 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'
}
// 🆕 Генерация HMAC подписи (вынесена в отдельную функцию)
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 })
// 🆕 Состояние для предпросмотра файла
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',
})
}
}
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">
{/* Основная информация */}
<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>
<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>
{approval.created_at
? dayjs(approval.created_at).format('DD.MM.YYYY HH:mm')
: '—'}
</Text>
</Group>
</Group>
</Stack>
</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 && (
<>
{' • '}
{dayjs(step.acted_at).format('DD.MM.YYYY HH:mm')}
</>
)}
</Text>
{step.comment && (
<Text size="xs" mt={4}>
Комментарий: {step.comment}
</Text>
)}
</Timeline.Item>
)
})}
</Timeline>
</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 && (
<> {dayjs(approval.revoked_at).format('DD.MM.YYYY HH:mm')}</>
)}
</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)}
/>
)}
</>
)
}

View File

@ -0,0 +1,267 @@
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>
)
}

View File

@ -0,0 +1,231 @@
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>
)
}

View File

@ -0,0 +1,152 @@
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) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
code: (value) => {
if (value.length < 2) return 'Код должен содержать минимум 2 символа'
if (!/^[a-z0-9_]+$/.test(value)) 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>
)
}

View File

@ -0,0 +1,339 @@
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,
IconList,
IconRoute,
IconInfoCircle,
} from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { notifications } from '@mantine/notifications'
import {
useHierarchies,
useDeleteHierarchy
} 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 HierarchyEditModal from './components/HierarchyEditModal'
import type { UserHierarchy } from '@/types/api'
type ViewMode = 'chains' | 'table'
export default function HierarchiesPage() {
const [viewMode, setViewMode] = useState<ViewMode>('chains')
const [subordinateFilter, setSubordinateFilter] = useState<string | null>(null)
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
const [editHierarchy, setEditHierarchy] = useState<UserHierarchy | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const [presetGroup, setPresetGroup] = useState<ChainGroup | null>(null)
const { data, isLoading, isFetching } = useHierarchies({
...(subordinateFilter && { subordinate_id: Number(subordinateFilter) }),
...(departmentFilter && { department_id: Number(departmentFilter) }),
})
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 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 handleDelete = (id: number) => {
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить эту связь? Это может повлиять на процесс согласования.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteHierarchy.mutate(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 handleCloseModal = () => {
setEditHierarchy(null)
setCreateModalOpened(false)
setPresetGroup(null)
}
return (
<Stack gap="md">
{/* Заголовок */}
<Group justify="space-between">
<Text size="xl" fw={700}>Иерархия согласований</Text>
<Group>
<SegmentedControl
value={viewMode}
onChange={(v) => setViewMode(v as ViewMode)}
data={[
{ value: 'chains', label: 'Цепочки' },
{ value: 'table', label: 'Таблица'},
]}
/>
<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">
Иерархия определяет порядок согласования заявок. Каждая цепочка показывает,
через каких согласующих проходит заявка от конкретного подчинённого.
Шаги выполняются последовательно в порядке возрастания priority.
</Text>
</Alert>
{/* Фильтры */}
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<Select
label="Подчинённый"
placeholder="Все пользователи"
data={userOptions}
value={subordinateFilter}
onChange={setSubordinateFilter}
clearable
searchable
style={{ minWidth: 250 }}
/>
<Select
label="Отдел"
placeholder="Все отделы"
data={departmentOptions}
value={departmentFilter}
onChange={setDepartmentFilter}
clearable
style={{ minWidth: 200 }}
/>
<Text c="dimmed" size="sm">
Всего связей: {data?.data?.length || 0}
</Text>
</Group>
</Paper>
{/* Контент */}
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : viewMode === 'chains' ? (
// Режим цепочек
<ScrollArea>
<Stack gap="md">
{enrichedChains.length === 0 ? (
<Paper withBorder p={40}>
<Center>
<Text c="dimmed">Связи не найдены</Text>
</Center>
</Paper>
) : (
enrichedChains.map((chain) => (
<ChainVisualization
key={chain.key}
group={chain}
onEditStep={handleEditStep}
onDeleteStep={handleDelete}
onAddStep={handleAddStep}
/>
))
)}
</Stack>
</ScrollArea>
) : (
// Режим таблицы
<Paper withBorder>
<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>Объект</Table.Th>
<Table.Th style={{ width: 80 }}>Порядок</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{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}>
<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>
</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}
/>
</Stack>
)
}

View File

@ -0,0 +1,180 @@
import {
Paper,
Group,
Stack,
Text,
Badge,
ActionIcon,
Avatar,
Box,
ThemeIcon,
Tooltip,
} from '@mantine/core'
import {
IconArrowRight,
IconPencil,
IconTrash,
IconUser,
IconWorld,
IconCategory,
IconFileText,
} from '@tabler/icons-react'
import type { ChainGroup } from '@/features/hierarchies/utils'
import { SCOPE_COLORS, SCOPE_LABELS } from '@/features/hierarchies/utils'
interface ChainVisualizationProps {
group: ChainGroup
onEditStep: (hierarchyId: number) => void
onDeleteStep: (hierarchyId: number) => void
onAddStep: (group: ChainGroup) => void
}
const ScopeIcon = ({ type }: { type: string }) => {
switch (type) {
case 'global': return <IconWorld size={14} />
case 'category': return <IconCategory size={14} />
case 'topic': return <IconFileText size={14} />
default: return <IconWorld size={14} />
}
}
export default function ChainVisualization({
group,
onEditStep,
onDeleteStep,
onAddStep,
}: ChainVisualizationProps) {
return (
<Paper withBorder p="md" mb="md">
{/* Заголовок группы */}
<Group justify="space-between" mb="md">
<Group gap="md">
<Avatar size="sm" radius="xl" color="blue">
{group.subordinateName.charAt(0)}
</Avatar>
<Stack gap={0}>
<Text fw={600} size="sm">{group.subordinateName}</Text>
<Text size="xs" c="dimmed">{group.departmentName}</Text>
</Stack>
<Badge
variant="light"
color={SCOPE_COLORS[group.scopeType]}
leftSection={<ScopeIcon type={group.scopeType} />}
>
{SCOPE_LABELS[group.scopeType]}: {group.scopeObjectName}
</Badge>
</Group>
<Tooltip label="Добавить шаг">
<ActionIcon
variant="light"
color="green"
onClick={() => onAddStep(group)}
>
<IconUser size={16} />
</ActionIcon>
</Tooltip>
</Group>
<Box style={{ overflowX: 'auto' }}>
<Group gap="xs" wrap="nowrap" align="center">
<Paper
withBorder
p="sm"
style={{
minWidth: 140,
backgroundColor: 'var(--mantine-color-gray-0)',
}}
>
<Stack gap={4} align="center">
<Text size="xs" c="dimmed" fw={600}>ИНИЦИАТОР</Text>
<Avatar size="md" radius="xl" color="gray">
{group.subordinateName.charAt(0)}
</Avatar>
<Text size="xs" fw={500} ta="center" lineClamp={2}>
{group.subordinateName}
</Text>
</Stack>
</Paper>
{/* Шаги согласования */}
{group.steps.map((step, index) => (
<Group key={step.id} gap="xs" wrap="nowrap" align="center">
{/* Стрелка */}
<IconArrowRight size={20} color="var(--mantine-color-gray-5)" />
{/* Карточка согласующего */}
<Paper
withBorder
p="sm"
style={{
minWidth: 140,
cursor: 'pointer',
transition: 'all 0.2s',
borderColor: 'var(--mantine-color-blue-4)',
}}
onClick={() => onEditStep(step.id!)}
className="hover-shadow"
>
<Stack gap={4} align="center">
<Group gap={4}>
<Text size="xs" c="dimmed" fw={600}>
ШАГ {index + 1}
</Text>
<Badge size="xs" variant="light" color="blue">
#{step.priority}
</Badge>
</Group>
<Avatar size="md" radius="xl" color="blue">
{step.approver?.full_name?.charAt(0) || '?'}
</Avatar>
<Text size="xs" fw={500} ta="center" lineClamp={2}>
{step.approver?.full_name || '—'}
</Text>
{/* Кнопки действий */}
<Group gap={4} mt={4}>
<Tooltip label="Редактировать">
<ActionIcon
variant="subtle"
color="blue"
size="xs"
onClick={(e) => {
e.stopPropagation()
onEditStep(step.id!)
}}
>
<IconPencil size={12} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="subtle"
color="red"
size="xs"
onClick={(e) => {
e.stopPropagation()
onDeleteStep(step.id!)
}}
>
<IconTrash size={12} />
</ActionIcon>
</Tooltip>
</Group>
</Stack>
</Paper>
</Group>
))}
</Group>
</Box>
<style>{`
.hover-shadow:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
transform: translateY(-2px);
}
`}</style>
</Paper>
)
}

View File

@ -0,0 +1,320 @@
import { useEffect } from 'react'
import {
Modal,
Stack,
Select,
NumberInput,
Group,
Button,
Text,
Loader,
Center,
Badge,
Paper,
Alert,
Radio,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconInfoCircle } from '@tabler/icons-react'
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'
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 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,
},
validate: {
subordinate_id: (v) => (v === null ? 'Выберите подчинённого' : null),
approver_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
},
},
})
// Загружаем темы выбранной категории
const { data: categoryTopics } = useTopics({
limit: 1000,
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
})
// Заполняем форму данными
useEffect(() => {
if (hierarchy) {
let scopeType: ScopeType = 'global'
if (hierarchy.topic_id) scopeType = 'topic'
else if (hierarchy.topic_category_id) scopeType = 'category'
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: hierarchy.topic_category_id || null,
topic_id: hierarchy.topic_id || null,
priority: hierarchy.priority ?? 0,
})
} else if (presetGroup) {
// Предзаполняем из группы (для добавления шага)
form.setValues({
subordinate_id: presetGroup.subordinateId,
department_id: presetGroup.departmentId,
scope_type: presetGroup.scopeType,
topic_category_id: presetGroup.scopeType === 'category' ? presetGroup.scopeObjectId : null,
topic_id: presetGroup.scopeType === 'topic' ? presetGroup.scopeObjectId : null,
priority: presetGroup.steps.length, // Следующий priority
approver_id: null,
})
} else {
form.reset()
}
}, [hierarchy, presetGroup, opened])
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 handleSubmit = async (values: typeof form.values) => {
const payload = {
subordinate_id: values.subordinate_id!,
approver_id: values.approver_id!,
department_id: values.department_id!,
priority: values.priority,
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 && hierarchy?.id) {
await updateHierarchy.mutateAsync({
id: hierarchy.id,
...payload,
})
} else {
await createHierarchy.mutateAsync(payload)
}
onClose()
}
const isSubmitting = createHierarchy.isPending || updateHierarchy.isPending
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">
{/* Подчинённый */}
<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={isEditMode || !!presetGroup}
description="Пользователь, для которого настраивается согласование"
/>
{/* Отдел */}
<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
disabled={isEditMode || !!presetGroup}
/>
{/* Согласующий */}
<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="Пользователь, который будет согласовывать заявки"
/>
{/* Область действия */}
<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>
</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
disabled={isEditMode || !!presetGroup}
/>
)}
{/* Тема */}
{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 || isEditMode || !!presetGroup}
description={!form.values.topic_category_id ? 'Сначала выберите категорию' : undefined}
/>
)}
{/* 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.
Заявка переходит к следующему согласующему только после одобрения предыдущим.
</Text>
</Alert>
{/* Кнопки */}
<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>
)
}

View File

@ -0,0 +1,307 @@
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>
)
}

View File

@ -0,0 +1,304 @@
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>
)
}

View File

@ -0,0 +1,311 @@
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 }),
})
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 === '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_director && !role.is_approver && !role.is_observer && !role.is_executor && (
<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>
)
}

View File

@ -0,0 +1,196 @@
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,
},
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,
})
} 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"
/>
</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>
)
}

View File

@ -0,0 +1,180 @@
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>
)
}

View File

@ -0,0 +1,334 @@
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,
IconList,
IconUsers,
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 {
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')
const [topicFilter, setTopicFilter] = 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, isLoading, isFetching } = useTopicExecutors({
...(topicFilter && { topic_id: Number(topicFilter) }),
...(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 topicOptions = topics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const targetSystemOptions = TARGET_SYSTEMS.map((s) => ({
value: s.value,
label: s.label,
}))
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">
{/* Заголовок */}
<Group justify="space-between">
<Text size="xl" fw={700}>Исполнители тем</Text>
<Group>
<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>
{/* Фильтры */}
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<Select
label="Тема"
placeholder="Все темы"
data={topicOptions}
value={topicFilter}
onChange={setTopicFilter}
clearable
searchable
style={{ minWidth: 300 }}
/>
<Select
label="Целевая система"
placeholder="Все системы"
data={targetSystemOptions}
value={targetSystemFilter}
onChange={setTargetSystemFilter}
clearable
style={{ minWidth: 200 }}
/>
<Text c="dimmed" size="sm">
Всего исполнителей: {data?.data?.length || 0}
</Text>
</Group>
</Paper>
{/* Контент */}
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : viewMode === 'cards' ? (
// Режим карточек
<ScrollArea>
<Stack gap="md">
{groups.length === 0 ? (
<Paper withBorder p={40}>
<Center>
<Text c="dimmed">Исполнители не найдены</Text>
</Center>
</Paper>
) : (
groups.map((group) => (
<TopicExecutorsCard
key={group.topicId}
group={group}
onEditExecutor={handleEditExecutor}
onDeleteExecutor={handleDelete}
onAddExecutor={handleAddExecutor}
/>
))
)}
</Stack>
</ScrollArea>
) : (
// Режим таблицы
<Paper withBorder>
<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: 100 }}>Статус</Table.Th>
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{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>
)
}

View File

@ -0,0 +1,234 @@
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>
)
}

View File

@ -0,0 +1,219 @@
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>
)
}

View File

@ -0,0 +1,269 @@
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>
)
}

View File

@ -0,0 +1,338 @@
import { useEffect } from 'react'
import {
Modal,
Stack,
TextInput,
Textarea,
Select,
Switch,
Group,
Button,
Text,
Loader,
Center,
Badge,
Paper,
Divider,
} 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,
approval_mode: 'sequential',
require_approver_comment: false,
requires_file: false,
require_observer_selection: false,
instructions: '',
},
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,
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,
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="Пользователь может сам выбрать согласующего"
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)}
disabled={!form.values.allow_approver_selection}
/>
<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)}
/>
</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>
)
}

View File

@ -0,0 +1,255 @@
import { useState, useMemo } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Select,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
} from '@mantine/core'
import { IconPencil, IconSearch, IconRefresh } from '@tabler/icons-react'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/users/hooks/useDepartments'
import UserEditModal from "@/components/UserEditModal.tsx";
const LIMIT = 20
export default function UsersPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
const [statusFilter, setStatusFilter] = useState<string | null>(null)
const [editUserId, setEditUserId] = useState<number | null>(null)
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 }),
})
const { data: departments } = useDepartments()
const departmentOptions = useMemo(() => {
if (!departments) return []
return departments.map((d) => ({
value: String(d.id),
label: d.name || '',
}))
}, [departments])
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
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 }}
/>
<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: 60 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={8}>
<Center p={40}>
<Text c="dimmed">Пользователи не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).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}>
{user.user_roles?.slice(0, 3).map((ur) => (
<Badge key={ur.id} size="xs" variant="light">
{ur.role?.name || 'Роль'}
</Badge>
))}
{user.user_roles && user.user_roles.length > 3 && (
<Badge size="xs" variant="outline">
+{user.user_roles.length - 3}
</Badge>
)}
{(!user.user_roles || user.user_roles.length === 0) && (
<Text size="xs" c="dimmed">—</Text>
)}
</Group>
</Table.Td>
<Table.Td>
<UserStatusBadge
isBlocked={user.is_blocked}
isFired={user.is_fired}
/>
</Table.Td>
<Table.Td>
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditUserId(user.id!)}
>
<IconPencil 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>
)}
{/* Модальное окно редактирования */}
<UserEditModal
userId={editUserId}
opened={editUserId !== null}
onClose={() => setEditUserId(null)}
/>
</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>
}

265
src/types/api.ts Normal file
View File

@ -0,0 +1,265 @@
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_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
password_hash?: string
is_blocked?: boolean
last_login?: string
last_ip_login?: string
created_at?: string
updated_at?: 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
}
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
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[]
}

12
src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
/// <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
}

View File

@ -1,25 +1,27 @@
{
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"]
}
}

View File

@ -1,7 +1,25 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View File

@ -11,10 +11,40 @@ export default defineConfig({
},
server: {
port: 3000,
allowedHosts: ['.trycloudflare.com'], // 👈 ДОБАВЬ ЭТУ СТРОКУ
proxy: {
'/api': {
target: 'http://localhost:8081', // Порт админки
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'
}
},
},
},
},