diff --git a/.env b/.env
new file mode 100644
index 0000000..66c28ec
--- /dev/null
+++ b/.env
@@ -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
\ No newline at end of file
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..0bf61e1
--- /dev/null
+++ b/.env.example
@@ -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
\ No newline at end of file
diff --git a/.gitea/workflows/deploy-frontend.yml b/.gitea/workflows/deploy-frontend.yml
new file mode 100644
index 0000000..a127f0f
--- /dev/null
+++ b/.gitea/workflows/deploy-frontend.yml
@@ -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
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index f3c0032..9907ca8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -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",
diff --git a/package.json b/package.json
index 068018c..c4e3fd2 100644
--- a/package.json
+++ b/package.json
@@ -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",
diff --git a/src/App.tsx b/src/App.tsx
index a66b5ef..73aab25 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -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 }) => (
+
+ {title}
+ Страница в разработке...
+
+)
- return (
- <>
-
-
-
-
Get started
-
- Edit src/App.tsx and save to test HMR
-
-
-
-
+function ProtectedRoute({ children }: { children: React.ReactNode }) {
+ const { isAuthenticated, loading } = useAuth()
-
+ if (loading) {
+ return (
+
+
+
+ )
+ }
-
-
-
-
Documentation
-
Your questions, answered
-
-
-
-
-
Connect with us
-
Join the Vite community
-
-
-
+ if (!isAuthenticated) {
+ return
+ }
-
-
- >
- )
+ return <>{children}>
}
-export default App
+function App() {
+ return (
+
+ } />
+
+ }>
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+
+
+ )
+}
+
+export default App
\ No newline at end of file
diff --git a/src/api/admins.ts b/src/api/admins.ts
new file mode 100644
index 0000000..b4a4e57
--- /dev/null
+++ b/src/api/admins.ts
@@ -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>('/admin', { params }),
+
+ create: (data: CreateAdminRequest) =>
+ apiClient.post('/admin', data),
+
+ update: (data: UpdateAdminRequest) =>
+ apiClient.put('/admin', data),
+
+ delete: (id: number) =>
+ apiClient.delete('/admin', { data: { id } }),
+}
\ No newline at end of file
diff --git a/src/api/approvalTasks.ts b/src/api/approvalTasks.ts
new file mode 100644
index 0000000..c4a28c7
--- /dev/null
+++ b/src/api/approvalTasks.ts
@@ -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>('/approval-tasks', { params }),
+
+ getById: (id: number) =>
+ apiClient.get(`/approval-tasks/${id}`),
+
+ update: (data: UpdateApprovalTaskRequest) =>
+ apiClient.put('/approval-tasks', data),
+
+ delete: (id: number) =>
+ apiClient.delete('/approval-tasks', { data: { id } }),
+}
\ No newline at end of file
diff --git a/src/api/approvals.ts b/src/api/approvals.ts
new file mode 100644
index 0000000..f5af568
--- /dev/null
+++ b/src/api/approvals.ts
@@ -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>('/approvals', { params }),
+
+ getById: (id: number) =>
+ apiClient.get(`/approvals/${id}`),
+
+ update: (data: UpdateApprovalRequest) =>
+ apiClient.put('/approvals', data),
+
+ delete: (id: number) =>
+ apiClient.delete('/approvals', { data: { id } }),
+
+ // 🆕 Получение заявок для отчёта (с фильтрами по датам)
+ getForReport: (params: ApprovalsReportParams = {}) =>
+ apiClient.get>('/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
+ })
+ },
+}
\ No newline at end of file
diff --git a/src/api/auth.ts b/src/api/auth.ts
new file mode 100644
index 0000000..0153908
--- /dev/null
+++ b/src/api/auth.ts
@@ -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('/auth/login', data),
+
+ getProfile: () =>
+ apiClient.get('/admin/profile'),
+
+ logout: () =>
+ apiClient.post('/auth/logout'),
+
+ // 🆕 Смена пароля через существующий endpoint
+ updateProfile: (data: UpdateProfileRequest) =>
+ apiClient.put('/admin/profile', data),
+}
\ No newline at end of file
diff --git a/src/api/categories.ts b/src/api/categories.ts
new file mode 100644
index 0000000..e8bb466
--- /dev/null
+++ b/src/api/categories.ts
@@ -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>('/categories', { params }),
+
+ getById: (id: number) =>
+ apiClient.get(`/categories/${id}`),
+
+ create: (data: CreateCategoryRequest) =>
+ apiClient.post('/categories', data),
+
+ update: (data: UpdateCategoryRequest) =>
+ apiClient.put('/categories', data),
+
+ delete: (id: number) =>
+ apiClient.delete('/categories', { data: { id } }),
+}
\ No newline at end of file
diff --git a/src/api/client.ts b/src/api/client.ts
index 3ec7e6d..eee9c40 100644
--- a/src/api/client.ts
+++ b/src/api/client.ts
@@ -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)
diff --git a/src/api/dashboard.ts b/src/api/dashboard.ts
new file mode 100644
index 0000000..0c783fe
--- /dev/null
+++ b/src/api/dashboard.ts
@@ -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('/dashboard/stats'),
+}
\ No newline at end of file
diff --git a/src/api/departments.ts b/src/api/departments.ts
new file mode 100644
index 0000000..dd03137
--- /dev/null
+++ b/src/api/departments.ts
@@ -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>('/departments', { params }),
+
+ // Получить отдел по ID
+ getById: (id: number) =>
+ apiClient.get(`/departments/${id}`),
+
+ // Создать отдел
+ create: (data: CreateDepartmentRequest) =>
+ apiClient.post('/departments', data),
+
+ // Обновить отдел
+ update: (data: UpdateDepartmentRequest) =>
+ apiClient.put('/departments', data),
+
+ // Удалить отдел
+ delete: (id: number) =>
+ apiClient.delete('/departments', { data: { id } }),
+}
\ No newline at end of file
diff --git a/src/api/hierarchies.ts b/src/api/hierarchies.ts
new file mode 100644
index 0000000..e02d343
--- /dev/null
+++ b/src/api/hierarchies.ts
@@ -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>('/hierarchies', { params }),
+
+ getById: (id: number) =>
+ apiClient.get(`/hierarchies/${id}`),
+
+ create: (data: CreateHierarchyRequest) =>
+ apiClient.post('/hierarchies', data),
+
+ update: (data: UpdateHierarchyRequest) =>
+ apiClient.put('/hierarchies', data),
+
+ delete: (id: number) =>
+ apiClient.delete('/hierarchies', { data: { id } }),
+}
\ No newline at end of file
diff --git a/src/api/permissions.ts b/src/api/permissions.ts
new file mode 100644
index 0000000..da9d130
--- /dev/null
+++ b/src/api/permissions.ts
@@ -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>('/permissions', { params }),
+
+ getById: (id: number) =>
+ apiClient.get(`/permissions/${id}`),
+
+ create: (data: CreatePermissionRequest) =>
+ apiClient.post('/permissions', data),
+
+ update: (data: UpdatePermissionRequest) =>
+ apiClient.put('/permissions', data),
+
+ delete: (id: number) =>
+ apiClient.delete('/permissions', { data: { id } }),
+}
\ No newline at end of file
diff --git a/src/api/roles.ts b/src/api/roles.ts
new file mode 100644
index 0000000..0399b02
--- /dev/null
+++ b/src/api/roles.ts
@@ -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>('/roles', { params }),
+
+ // Получить роль по ID
+ getById: (id: number) =>
+ apiClient.get(`/roles/${id}`),
+
+ // Создать роль
+ create: (data: CreateRoleRequest) =>
+ apiClient.post('/roles', data),
+
+ // Обновить роль
+ update: (data: UpdateRoleRequest) =>
+ apiClient.put('/roles', data),
+
+ // Удалить роль
+ delete: (id: number) =>
+ apiClient.delete('/roles', { data: { id } }),
+}
\ No newline at end of file
diff --git a/src/api/topicExecutors.ts b/src/api/topicExecutors.ts
new file mode 100644
index 0000000..425e3a1
--- /dev/null
+++ b/src/api/topicExecutors.ts
@@ -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>('/topic-executors', { params }),
+
+ getById: (id: number) =>
+ apiClient.get(`/topic-executors/${id}`),
+
+ create: (data: CreateTopicExecutorRequest) =>
+ apiClient.post('/topic-executors', data),
+
+ update: (data: UpdateTopicExecutorRequest) =>
+ apiClient.put('/topic-executors', data),
+
+ delete: (id: number) =>
+ apiClient.delete('/topic-executors', { data: { id } }),
+}
\ No newline at end of file
diff --git a/src/api/topics.ts b/src/api/topics.ts
new file mode 100644
index 0000000..333cb6c
--- /dev/null
+++ b/src/api/topics.ts
@@ -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>('/topics', { params }),
+
+ getById: (id: number) =>
+ apiClient.get(`/topics/${id}`),
+
+ create: (data: CreateTopicRequest) =>
+ apiClient.post('/topics', data),
+
+ update: (data: UpdateTopicRequest) =>
+ apiClient.put('/topics', data),
+
+ delete: (id: number) =>
+ apiClient.delete('/topics', { data: { id } }),
+}
\ No newline at end of file
diff --git a/src/api/userRoles.ts b/src/api/userRoles.ts
new file mode 100644
index 0000000..a687baa
--- /dev/null
+++ b/src/api/userRoles.ts
@@ -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>(`/users/${userId}/roles`),
+
+ // Массовое назначение ролей (полная замена)
+ bulkAssign: (data: BulkAssignRolesRequest) =>
+ apiClient.post>('/user-roles/bulk', data),
+}
\ No newline at end of file
diff --git a/src/api/users.ts b/src/api/users.ts
new file mode 100644
index 0000000..bda6280
--- /dev/null
+++ b/src/api/users.ts
@@ -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>('/users', { params }),
+
+ // Получить пользователя по ID
+ getById: (id: number) =>
+ apiClient.get(`/users/${id}`),
+
+ // Обновить пользователя
+ update: (data: UpdateUserRequest) =>
+ apiClient.put('/users', data),
+}
\ No newline at end of file
diff --git a/src/components/Layout/Header.tsx b/src/components/Layout/Header.tsx
new file mode 100644
index 0000000..78c9b31
--- /dev/null
+++ b/src/components/Layout/Header.tsx
@@ -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 (
+
+
+
+
+
+ Ruspet Admin Panel
+
+
+
+
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/components/Layout/MainLayout.tsx b/src/components/Layout/MainLayout.tsx
new file mode 100644
index 0000000..b458921
--- /dev/null
+++ b/src/components/Layout/MainLayout.tsx
@@ -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 (
+
+
+
+
+
+
+
+
+
+
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/components/Layout/Sidebar.tsx b/src/components/Layout/Sidebar.tsx
new file mode 100644
index 0000000..aa2b5b7
--- /dev/null
+++ b/src/components/Layout/Sidebar.tsx
@@ -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 (
+
+ : undefined}
+ rightSection={
+
+ }
+ active={hasActiveChild}
+ onClick={() => setOpened(!opened)}
+ styles={{
+ root: {
+ paddingLeft,
+ paddingRight: 12,
+ borderRadius: '8px',
+ marginBottom: 2,
+ '&:hover': {
+ backgroundColor: 'var(--mantine-color-gray-0)',
+ },
+ },
+ }}
+ />
+ {opened && (
+
+ {item.children!.map((child) => (
+
+ ))}
+
+ )}
+
+ )
+ }
+
+ return (
+ : undefined}
+ active={isActive}
+ onClick={() => {
+ if (item.path) navigate(item.path)
+ }}
+ styles={{
+ root: {
+ paddingLeft,
+ paddingRight: 12,
+ borderRadius: '8px',
+ marginBottom: 2,
+ '&:hover': {
+ backgroundColor: 'var(--mantine-color-gray-0)',
+ },
+ },
+ label: {
+ fontWeight: isActive ? 600 : 400,
+ },
+ }}
+ />
+ )
+}
+
+export default function Sidebar() {
+ return (
+
+
+ Главное меню
+
+
+
+ {menuItems.map((item) => (
+
+ ))}
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/components/UserEditModal.tsx b/src/components/UserEditModal.tsx
new file mode 100644
index 0000000..3c04b3f
--- /dev/null
+++ b/src/components/UserEditModal.tsx
@@ -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 (
+
+ Редактирование пользователя
+ {user && ID: {user.id}}
+
+ }
+ size="lg"
+ >
+ {isLoading ? (
+
+
+
+ ) : user ? (
+
+ ) : (
+
+ Пользователь не найден
+
+ )}
+
+ )
+}
\ No newline at end of file
diff --git a/src/features/admins/hooks/useAdmins.ts b/src/features/admins/hooks/useAdmins.ts
new file mode 100644
index 0000000..d4c4540
--- /dev/null
+++ b/src/features/admins/hooks/useAdmins.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/approvalTasks/const.ts b/src/features/approvalTasks/const.ts
new file mode 100644
index 0000000..edbe062
--- /dev/null
+++ b/src/features/approvalTasks/const.ts
@@ -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 = {
+ pending: 'blue',
+ waiting: 'orange',
+ completed: 'green',
+ cancelled: 'gray',
+}
+
+export const STATUS_LABELS: Record = {
+ pending: 'В ожидании',
+ waiting: 'Ожидает',
+ completed: 'Выполнена',
+ cancelled: 'Отменена',
+}
\ No newline at end of file
diff --git a/src/features/approvalTasks/hooks/useApprovalTasks.ts b/src/features/approvalTasks/hooks/useApprovalTasks.ts
new file mode 100644
index 0000000..d390b18
--- /dev/null
+++ b/src/features/approvalTasks/hooks/useApprovalTasks.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/approvals/hooks/useApprovals.ts b/src/features/approvals/hooks/useApprovals.ts
new file mode 100644
index 0000000..c97a0fe
--- /dev/null
+++ b/src/features/approvals/hooks/useApprovals.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/categories/hooks/useCategories.ts b/src/features/categories/hooks/useCategories.ts
new file mode 100644
index 0000000..6065e7c
--- /dev/null
+++ b/src/features/categories/hooks/useCategories.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/departments/components/DepartmentEditModal.tsx b/src/features/departments/components/DepartmentEditModal.tsx
new file mode 100644
index 0000000..705eb21
--- /dev/null
+++ b/src/features/departments/components/DepartmentEditModal.tsx
@@ -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 (
+
+
+ {isEditMode ? 'Редактирование отдела' : 'Создание отдела'}
+
+ {department && ID: {department.id}}
+
+ }
+ size="md"
+ >
+ {isLoading ? (
+
+
+
+ ) : (
+
+ )}
+
+ )
+}
\ No newline at end of file
diff --git a/src/features/departments/hooks/useDepartments.ts b/src/features/departments/hooks/useDepartments.ts
new file mode 100644
index 0000000..4752e3c
--- /dev/null
+++ b/src/features/departments/hooks/useDepartments.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/hierarchies/hooks/useHierarchies.ts b/src/features/hierarchies/hooks/useHierarchies.ts
new file mode 100644
index 0000000..15b2f47
--- /dev/null
+++ b/src/features/hierarchies/hooks/useHierarchies.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/hierarchies/utils.ts b/src/features/hierarchies/utils.ts
new file mode 100644
index 0000000..e72178e
--- /dev/null
+++ b/src/features/hierarchies/utils.ts
@@ -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()
+
+ 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, {
+ key,
+ subordinateId: h.subordinate_id,
+ subordinateName: h.subordinate?.full_name || `Пользователь #${h.subordinate_id}`,
+ departmentId: h.department_id,
+ departmentName: h.department?.name || `Отдел #${h.department_id}`,
+ scopeType,
+ scopeObjectId,
+ scopeObjectName,
+ steps: [],
+ })
+ }
+
+ groups.get(key)!.steps.push(h)
+ }
+
+ // Сортируем шаги по priority внутри каждой группы
+ for (const group of groups.values()) {
+ group.steps.sort((a, b) => (a.priority || 0) - (b.priority || 0))
+ }
+
+ return Array.from(groups.values())
+}
+
+// Цвета для scope types
+export const SCOPE_COLORS: Record = {
+ global: 'violet',
+ category: 'blue',
+ topic: 'orange',
+}
+
+export const SCOPE_LABELS: Record = {
+ global: 'Глобальное',
+ category: 'Категория',
+ topic: 'Тема',
+}
\ No newline at end of file
diff --git a/src/features/permissions/constants.ts b/src/features/permissions/constants.ts
new file mode 100644
index 0000000..6c7956f
--- /dev/null
+++ b/src/features/permissions/constants.ts
@@ -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 = {
+ create: 'blue',
+ read: 'gray',
+ update: 'cyan',
+ delete: 'red',
+ approve: 'green',
+ revoke: 'orange',
+ observe: 'violet',
+}
+
+export const ACTION_LABELS: Record = {
+ create: 'Создание',
+ read: 'Просмотр',
+ update: 'Редактирование',
+ delete: 'Удаление',
+ approve: 'Согласование',
+ revoke: 'Отзыв',
+ observe: 'Наблюдение',
+}
\ No newline at end of file
diff --git a/src/features/permissions/hooks/usePermissions.ts b/src/features/permissions/hooks/usePermissions.ts
new file mode 100644
index 0000000..2aaf37d
--- /dev/null
+++ b/src/features/permissions/hooks/usePermissions.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/roles/hooks/useRoles.ts b/src/features/roles/hooks/useRoles.ts
new file mode 100644
index 0000000..d65c98e
--- /dev/null
+++ b/src/features/roles/hooks/useRoles.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/topicExecutors/hooks/useTopicExecutors.ts b/src/features/topicExecutors/hooks/useTopicExecutors.ts
new file mode 100644
index 0000000..451dffc
--- /dev/null
+++ b/src/features/topicExecutors/hooks/useTopicExecutors.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/topicExecutors/utils.ts b/src/features/topicExecutors/utils.ts
new file mode 100644
index 0000000..4b48b70
--- /dev/null
+++ b/src/features/topicExecutors/utils.ts
@@ -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 = {
+ all: 'Все системы',
+ okb: 'ОКБ',
+ '1c': '1С',
+}
+
+export const TARGET_SYSTEM_COLORS: Record = {
+ all: 'blue',
+ okb: 'green',
+ '1c': 'orange',
+}
+
+// Группируем исполнителей по темам
+export function groupExecutorsByTopic(
+ executors: ApprovalTopicExecutor[]
+): TopicExecutorsGroup[] {
+ const groups = new Map()
+
+ for (const executor of executors) {
+ if (!executor.topic_id) continue
+
+ if (!groups.has(executor.topic_id)) {
+ groups.set(executor.topic_id, {
+ topicId: executor.topic_id,
+ topicName: executor.topic?.name || `Тема #${executor.topic_id}`,
+ topicCode: executor.topic?.code || '',
+ categoryName: executor.topic?.category?.name,
+ executors: [],
+ })
+ }
+
+ groups.get(executor.topic_id)!.executors.push(executor)
+ }
+
+ // Сортируем исполнителей по step_order внутри каждой группы
+ for (const group of groups.values()) {
+ group.executors.sort((a, b) => (a.step_order || 0) - (b.step_order || 0))
+ }
+
+ return Array.from(groups.values())
+}
\ No newline at end of file
diff --git a/src/features/topics/constants.ts b/src/features/topics/constants.ts
new file mode 100644
index 0000000..67b7c34
--- /dev/null
+++ b/src/features/topics/constants.ts
@@ -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 = {
+ single_day: 'Один день',
+ multi_day: 'Несколько дней',
+ date_range: 'Диапазон',
+}
+
+export const TIME_LABELS: Record = {
+ partial: 'Частично',
+ full_day: 'Весь день',
+}
+
+export const PAYMENT_LABELS: Record = {
+ own_expense: 'За свой счёт',
+ vacation_account: 'В счёт отпуска',
+ official: 'Официально',
+}
\ No newline at end of file
diff --git a/src/features/topics/hooks/useTopics.ts b/src/features/topics/hooks/useTopics.ts
new file mode 100644
index 0000000..437433a
--- /dev/null
+++ b/src/features/topics/hooks/useTopics.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/users/hooks/useDepartments.ts b/src/features/users/hooks/useDepartments.ts
new file mode 100644
index 0000000..dba871f
--- /dev/null
+++ b/src/features/users/hooks/useDepartments.ts
@@ -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 || []
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/users/hooks/useRoles.ts b/src/features/users/hooks/useRoles.ts
new file mode 100644
index 0000000..1315f82
--- /dev/null
+++ b/src/features/users/hooks/useRoles.ts
@@ -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 || []
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/users/hooks/useUserRoles.ts b/src/features/users/hooks/useUserRoles.ts
new file mode 100644
index 0000000..b59d191
--- /dev/null
+++ b/src/features/users/hooks/useUserRoles.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/features/users/hooks/useUsers.ts b/src/features/users/hooks/useUsers.ts
new file mode 100644
index 0000000..c8e97a1
--- /dev/null
+++ b/src/features/users/hooks/useUsers.ts
@@ -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',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts
new file mode 100644
index 0000000..ffd2dc3
--- /dev/null
+++ b/src/hooks/useAuth.ts
@@ -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(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 }
+}
\ No newline at end of file
diff --git a/src/main.tsx b/src/main.tsx
index 8e33d0b..d77471d 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -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: {
diff --git a/src/pages/Dashboard.tsx b/src/pages/Dashboard.tsx
new file mode 100644
index 0000000..a592c14
--- /dev/null
+++ b/src/pages/Dashboard.tsx
@@ -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 = {
+ draft: '#868e96',
+ pending: '#228be6',
+ approved: '#40c057',
+ rejected: '#fa5252',
+ revoked: '#fd7e14',
+ revision: '#7950f2',
+}
+
+const STATUS_LABELS: Record = {
+ draft: 'Черновики',
+ pending: 'На согласовании',
+ approved: 'Согласованы',
+ rejected: 'Отклонены',
+ revoked: 'Отозваны',
+ revision: 'На доработке',
+}
+
+export default function Dashboard() {
+ const [stats, setStats] = useState(null)
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState(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 (
+
+
+
+ )
+ }
+
+ if (error || !stats) {
+ return (
+ } color="red" title="Ошибка">
+ {error || 'Не удалось загрузить данные'}
+
+ )
+ }
+
+ // Фильтруем нулевые значения для pie chart
+ const chartData = stats.statusData.filter(s => s.count > 0)
+ const totalApprovals = chartData.reduce((sum, s) => sum + s.count, 0)
+
+ return (
+
+ {/* Заголовок */}
+
+
+ Dashboard
+ Обзор системы согласований
+
+
+ {dayjs().format('DD MMMM YYYY')}
+
+
+
+ {/* Alert: старые pending заявки */}
+ {stats.oldPendingCount > 0 && (
+ }
+ color="orange"
+ variant="light"
+ title={`⚠️ ${stats.oldPendingCount} заявок требуют внимания`}
+ >
+
+ Есть заявки, которые находятся на согласовании более 7 дней.
+
+
+ )}
+
+ {/* KPI карточки */}
+
+ 0 ? `${stats.users.blocked} заблокировано` : undefined}
+ />
+ 0 ? `${stats.approvals.pending} в работе` : undefined}
+ />
+
+
+
+
+ {/* Графики */}
+
+ {/* Pie chart */}
+
+
+ Распределение заявок по статусам
+ {totalApprovals} всего
+
+
+ {chartData.length === 0 ? (
+
+ Нет данных
+
+ ) : (
+
+
+ STATUS_LABELS[entry.payload?.status] || entry.payload?.status}
+ >
+ {chartData.map((entry, index) => (
+ |
+ ))}
+
+ [
+ value,
+ STATUS_LABELS[name] || name
+ ]}
+ />
+
+
+ )}
+
+
+ {/* Line chart */}
+
+
+ Динамика за 7 дней
+ Заявки
+
+
+
+
+
+ dayjs(d).format('DD.MM')}
+ />
+
+ dayjs(d).format('DD.MM.YYYY')}
+ formatter={(value: any, name: any) => [
+ value,
+ name === 'created' ? 'Создано' : 'Согласовано'
+ ]}
+ />
+
+
+
+
+
+ {/* Топ списки */}
+
+ {/* Топ тем */}
+
+
+
+
+
+ Топ-5 самых активных тем
+
+
+ {stats.topTopics.length === 0 ? (
+
+ Нет данных
+
+ ) : (
+
+ {stats.topTopics.map((topic, index) => {
+ const maxCount = Math.max(...stats.topTopics.map(t => t.total_count))
+ const percent = (topic.total_count / maxCount) * 100
+
+ return (
+
+
+
+
+ #{index + 1}
+
+
+ {topic.name}
+ {topic.category_name}
+
+
+
+ {topic.total_count}
+ {topic.pending_count > 0 && (
+
+ {topic.pending_count} в работе
+
+ )}
+
+
+
+
+ )
+ })}
+
+ )}
+
+
+ {/* Топ согласующих */}
+
+
+
+
+
+ Топ-5 согласующих
+
+
+ {stats.topApprovers.length === 0 ? (
+
+ Нет данных
+
+ ) : (
+
+ {stats.topApprovers.map((approver, index) => {
+ const maxSteps = Math.max(...stats.topApprovers.map(a => a.total_steps))
+ const percent = (approver.total_steps / maxSteps) * 100
+
+ return (
+
+
+
+
+ #{index + 1}
+
+
+ {approver.full_name}
+ {approver.department_name}
+
+
+
+ {approver.total_steps}
+ {approver.pending_steps > 0 && (
+
+ {approver.pending_steps} ожидают
+
+ )}
+
+
+
+
+ )
+ })}
+
+ )}
+
+
+
+ {/* Заявки на доработке */}
+ {stats.approvals.revision > 0 && (
+
+
+
+
+
+ Требуют внимания: {stats.approvals.revision} заявок на доработке
+
+
+ Эти заявки были возвращены согласующими на доработку и требуют действий от инициаторов.
+
+
+ )}
+
+ )
+}
+
+// Компонент карточки статистики
+interface StatCardProps {
+ title: string
+ value: number | string
+ subtitle?: string
+ icon: any
+ color: string
+ trend?: string
+}
+
+function StatCard({ title, value, subtitle, icon: Icon, color, trend }: StatCardProps) {
+ return (
+
+
+
+
+ {title}
+
+
+ {value}
+
+ {subtitle && (
+
+ {subtitle}
+
+ )}
+
+
+
+
+
+
+ {trend && (
+
+ {trend}
+
+ )}
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/DepartmentsPage.tsx b/src/pages/DepartmentsPage.tsx
new file mode 100644
index 0000000..8aed13a
--- /dev/null
+++ b/src/pages/DepartmentsPage.tsx
@@ -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(null)
+ const [editDepartmentId, setEditDepartmentId] = useState(null)
+ const [createModalOpened, setCreateModalOpened] = useState(false)
+
+ const { data, isLoading, isFetching } = useDepartments({
+ offset: (page - 1) * LIMIT,
+ limit: LIMIT,
+ ...(search && { name: search }),
+ ...(activeFilter !== null && { is_active: activeFilter }),
+ })
+
+ const deleteDepartment = useDeleteDepartment()
+
+ const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
+
+ const handleDelete = (id: number) => {
+ modals.openConfirmModal({
+ title: 'Подтвердите удаление',
+ children: (
+
+ Вы уверены, что хотите удалить этот отдел? Это действие нельзя отменить.
+
+ ),
+ labels: { confirm: 'Удалить', cancel: 'Отмена' },
+ confirmProps: { color: 'red' },
+ onConfirm: () => deleteDepartment.mutate(id),
+ })
+ }
+
+ return (
+
+
+ Отделы
+
+
+ Всего: {data?.total_count || 0}
+
+ }
+ onClick={() => setCreateModalOpened(true)}
+ >
+ Создать отдел
+
+
+
+
+ {/* Фильтры */}
+
+
+ }
+ value={search}
+ onChange={(e) => {
+ setSearch(e.currentTarget.value)
+ setPage(1)
+ }}
+ style={{ flex: 1 }}
+ />
+
+ {
+ setActiveFilter(e.currentTarget.checked ? true : null)
+ setPage(1)
+ }}
+ />
+
+
+
+ {/* Таблица */}
+
+ {isLoading ? (
+
+
+
+ ) : (
+ <>
+
+
+
+ ID
+ Название
+ Код
+ Описание
+ Статус
+ Действия
+
+
+
+ {data?.data?.length === 0 ? (
+
+
+
+ Отделы не найдены
+
+
+
+ ) : (
+ (data?.data || []).map((department) => (
+
+ {department.id}
+
+ {department.name}
+
+
+
+ {department.code}
+
+
+
+
+ {department.description || '—'}
+
+
+
+
+ {department.is_active ? 'Активен' : 'Неактивен'}
+
+
+
+
+
+ setEditDepartmentId(department.id!)}
+ >
+
+
+
+
+ handleDelete(department.id!)}
+ >
+
+
+
+
+
+
+ ))
+ )}
+
+
+
+ {/* Пагинация */}
+ {totalPages > 1 && (
+
+
+
+ Страница {page} из {totalPages}
+
+
+
+
+ )}
+ >
+ )}
+
+
+ {/* Индикатор обновления */}
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ {/* Модальное окно редактирования */}
+ setEditDepartmentId(null)}
+ />
+
+ {/* Модальное окно создания */}
+ setCreateModalOpened(false)}
+ />
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/Login.tsx b/src/pages/Login.tsx
new file mode 100644
index 0000000..b161000
--- /dev/null
+++ b/src/pages/Login.tsx
@@ -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 (
+
+
+ Корпоративная панель администратора
+
+
+ Введите свои данные для входа в систему
+
+
+
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/admins/AdminsPage.tsx b/src/pages/admins/AdminsPage.tsx
new file mode 100644
index 0000000..7920a73
--- /dev/null
+++ b/src/pages/admins/AdminsPage.tsx
@@ -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(null)
+ const [createModalOpened, setCreateModalOpened] = useState(false)
+ const [editAdmin, setEditAdmin] = useState(null)
+
+ const { user: currentUser } = useAuth()
+
+ const { data, isLoading, isFetching } = useAdmins({
+ offset: (page - 1) * LIMIT,
+ limit: LIMIT,
+ ...(search && { login: search }),
+ ...(blockedFilter !== null && { is_blocked: blockedFilter }),
+ })
+
+ const deleteAdmin = useDeleteAdmin()
+ const updateAdmin = useUpdateAdmin()
+
+ const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
+
+ // 🆕 Проверка, является ли текущий пользователь root
+ const isRoot = currentUser?.is_root === true
+
+ const handleDelete = (id: number, login: string, isAdminRoot: boolean) => {
+ // Нельзя удалить себя
+ if (currentUser?.id === id) {
+ notifications.show({
+ title: 'Ошибка',
+ message: 'Вы не можете удалить свой собственный аккаунт',
+ color: 'red',
+ })
+ return
+ }
+
+ // Нельзя удалить root-админа (если текущий не root)
+ if (isAdminRoot && !isRoot) {
+ notifications.show({
+ title: 'Ошибка',
+ message: 'Только root-администратор может удалять других root-администраторов',
+ color: 'red',
+ })
+ return
+ }
+
+ modals.openConfirmModal({
+ title: 'Подтвердите удаление',
+ children: (
+
+ Вы уверены, что хотите удалить администратора {login}?
+ Это действие нельзя отменить.
+
+ ),
+ labels: { confirm: 'Удалить', cancel: 'Отмена' },
+ confirmProps: { color: 'red' },
+ onConfirm: () => deleteAdmin.mutate(id),
+ })
+ }
+
+ const handleToggleBlock = (id: number, login: string, isBlocked: boolean, isAdminRoot: boolean) => {
+ // Нельзя заблокировать себя
+ if (currentUser?.id === id) {
+ notifications.show({
+ title: 'Ошибка',
+ message: 'Вы не можете заблокировать свой собственный аккаунт',
+ color: 'red',
+ })
+ return
+ }
+
+ // Нельзя заблокировать root-админа (если текущий не root)
+ if (isAdminRoot && !isRoot) {
+ notifications.show({
+ title: 'Ошибка',
+ message: 'Только root-администратор может блокировать других root-администраторов',
+ color: 'red',
+ })
+ return
+ }
+
+ const action = isBlocked ? 'разблокировать' : 'заблокировать'
+
+ modals.openConfirmModal({
+ title: 'Подтвердите действие',
+ children: (
+
+ Вы уверены, что хотите {action} администратора {login}?
+
+ ),
+ labels: { confirm: action.charAt(0).toUpperCase() + action.slice(1), cancel: 'Отмена' },
+ confirmProps: { color: isBlocked ? 'green' : 'red' },
+ onConfirm: () => updateAdmin.mutate({ id, is_blocked: !isBlocked }),
+ })
+ }
+
+ return (
+
+ {/* Заголовок */}
+
+ Администраторы
+
+
+ Всего: {data?.total_count || 0}
+
+ {isRoot && (
+ }
+ onClick={() => setCreateModalOpened(true)}
+ >
+ Создать администратора
+
+ )}
+
+
+
+ {/* Предупреждение для не-root пользователей */}
+ {!isRoot && (
+
+
+ ⚠️ Создание новых администраторов доступно только для root-администратора.
+
+
+ )}
+
+ {/* Фильтры */}
+
+
+ }
+ value={search}
+ onChange={(e) => {
+ setSearch(e.currentTarget.value)
+ setPage(1)
+ }}
+ style={{ flex: 1 }}
+ />
+
+ {
+ setBlockedFilter(e.currentTarget.checked ? true : null)
+ setPage(1)
+ }}
+ />
+
+
+
+ {/* Таблица */}
+
+ {isLoading ? (
+
+
+
+ ) : (
+ <>
+
+
+
+ ID
+ Логин
+ Имя
+ Создан
+ Последний вход
+ Последний IP
+ Статус
+ Действия
+
+
+
+ {data?.data?.length === 0 ? (
+
+
+
+ Администраторы не найдены
+
+
+
+ ) : (
+ (data?.data || []).map((admin) => {
+ const isCurrentUser = currentUser?.id === admin.id
+ const isAdminRoot = admin.is_root === true
+ return (
+
+ {admin.id}
+
+
+ {admin.login}
+ {isCurrentUser && (
+
+ Вы
+
+ )}
+ {isAdminRoot && (
+ }
+ >
+ ROOT
+
+ )}
+
+
+
+ {admin.name || '—'}
+
+
+
+ {admin.created_at
+ ? dayjs(admin.created_at).format('DD.MM.YYYY')
+ : '—'}
+
+
+
+
+ {admin.last_login
+ ? dayjs(admin.last_login).format('DD.MM.YYYY HH:mm')
+ : '—'}
+
+
+
+
+ {admin.last_ip_login || '—'}
+
+
+
+
+ {admin.is_blocked ? 'Заблокирован' : 'Активен'}
+
+
+
+
+
+ setEditAdmin(admin)}
+ >
+
+
+
+
+ handleToggleBlock(
+ admin.id!,
+ admin.login,
+ admin.is_blocked || false,
+ isAdminRoot
+ )}
+ disabled={isCurrentUser || (isAdminRoot && !isRoot)}
+ >
+ {admin.is_blocked ? : }
+
+
+
+ handleDelete(admin.id!, admin.login, isAdminRoot)}
+ disabled={isCurrentUser || (isAdminRoot && !isRoot)}
+ >
+
+
+
+
+
+
+ )
+ })
+ )}
+
+
+
+ {/* Пагинация */}
+ {totalPages > 1 && (
+
+
+
+ Страница {page} из {totalPages}
+
+
+
+
+ )}
+ >
+ )}
+
+
+ {/* Индикатор обновления */}
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ {/* Модальные окна */}
+ setCreateModalOpened(false)}
+ />
+
+ setEditAdmin(null)}
+ />
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/admins/components/CreateAdminModal.tsx b/src/pages/admins/components/CreateAdminModal.tsx
new file mode 100644
index 0000000..eaf2196
--- /dev/null
+++ b/src/pages/admins/components/CreateAdminModal.tsx
@@ -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(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 (
+
+ {createdAdmin ? (
+
+ }
+ title="Администратор создан"
+ color="green"
+ variant="light"
+ >
+
+ Администратор {createdAdmin.login} успешно создан.
+ {createdAdmin.is_root && (
+
+ Выданы root-права 👑
+
+ )}
+
+
+
+
+
+
+
+ Временный пароль
+
+
+
+ Сохраните этот пароль! После закрытия окна он больше не будет доступен.
+
+
+
+
+ {createdAdmin.password || '—'}
+
+
+ {({ copied, copy }) => (
+
+
+ {copied ? : }
+
+
+ )}
+
+
+
+
+
+
+
+ ) : (
+
+ )}
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/admins/components/EditAdminModal.tsx b/src/pages/admins/components/EditAdminModal.tsx
new file mode 100644
index 0000000..21f9296
--- /dev/null
+++ b/src/pages/admins/components/EditAdminModal.tsx
@@ -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 (
+
+ Редактирование администратора
+ {admin && {admin.login}}
+ {admin?.is_root && (
+ }>
+ ROOT
+
+ )}
+
+ }
+ size="md"
+ >
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/approvalTasks/ApprovalTasksPage.tsx b/src/pages/approvalTasks/ApprovalTasksPage.tsx
new file mode 100644
index 0000000..bc044ae
--- /dev/null
+++ b/src/pages/approvalTasks/ApprovalTasksPage.tsx
@@ -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(null)
+ const [executorFilter, setExecutorFilter] = useState(null)
+ const [requireFileFilter, setRequireFileFilter] = useState(null)
+ const [selectedTaskId, setSelectedTaskId] = useState(null)
+
+ const { data, isLoading, isFetching } = useApprovalTasks({
+ offset: (page - 1) * LIMIT,
+ limit: LIMIT,
+ ...(statusFilter && { status: statusFilter }),
+ ...(executorFilter && { executor_id: Number(executorFilter) }),
+ ...(requireFileFilter !== null && { require_file: requireFileFilter }),
+ })
+
+ const { data: users } = useUsers({ limit: 1000 })
+ const deleteTask = useDeleteApprovalTask()
+
+ const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
+
+ const executorOptions = users?.data?.map((u) => ({
+ value: String(u.id),
+ label: u.full_name || '',
+ })) || []
+
+ const handleDelete = (id: number) => {
+ modals.openConfirmModal({
+ title: 'Подтвердите удаление',
+ children: (
+
+ Вы уверены, что хотите удалить эту задачу? Это действие нельзя отменить.
+
+ ),
+ labels: { confirm: 'Удалить', cancel: 'Отмена' },
+ confirmProps: { color: 'red' },
+ onConfirm: () => deleteTask.mutate(id),
+ })
+ }
+
+ return (
+
+
+ Задачи по заявкам
+
+ Всего: {data?.total_count || 0}
+
+
+
+ {/* Фильтры */}
+
+
+
+
+
+ {/* Таблица */}
+
+ {isLoading ? (
+
+
+
+ ) : (
+ <>
+
+
+
+ ID
+ Заявка
+ Исполнитель
+ Текст задачи
+ Шаг
+ Статус
+ Файл
+ Создана
+ Выполнена
+ Действия
+
+
+
+ {data?.data?.length === 0 ? (
+
+
+
+ Задачи не найдены
+
+
+
+ ) : (
+ (data?.data || []).map((task) => (
+
+
+ #{task.id}
+
+
+
+
+ #{task.approval_id}
+
+
+ {task.approval?.topic?.name || '—'}
+
+
+
+
+
+ {task.executor?.full_name || '—'}
+
+
+ {task.executor?.department?.name}
+
+
+
+
+ {task.task_text || '—'}
+
+
+
+
+ #{task.step_order}
+
+
+
+
+ {STATUS_LABELS[task.status || ''] || task.status}
+
+
+
+ {task.require_file ? (
+
+ Да
+
+ ) : (
+ —
+ )}
+
+
+
+ {task.created_at
+ ? dayjs(task.created_at).format('DD.MM.YYYY HH:mm')
+ : '—'}
+
+
+
+
+ {task.completed_at
+ ? dayjs(task.completed_at).format('DD.MM.YYYY HH:mm')
+ : '—'}
+
+
+
+
+
+ setSelectedTaskId(task.id!)}
+ >
+
+
+
+
+ handleDelete(task.id!)}
+ >
+
+
+
+
+
+
+ ))
+ )}
+
+
+
+ {totalPages > 1 && (
+
+
+
+ Страница {page} из {totalPages}
+
+
+
+
+ )}
+ >
+ )}
+
+
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ setSelectedTaskId(null)}
+ />
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx b/src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx
new file mode 100644
index 0000000..086fccb
--- /dev/null
+++ b/src/pages/approvalTasks/components/ApprovalTaskDetailsModal.tsx
@@ -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 = {
+ 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'png': 'image/png',
+ 'gif': 'image/gif', 'webp': 'image/webp', 'svg': 'image/svg+xml',
+ 'pdf': 'application/pdf', 'txt': 'text/plain',
+ 'doc': 'application/msword',
+ 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'xls': 'application/vnd.ms-excel',
+ 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ }
+ return mimeTypes[ext] || 'application/octet-stream'
+}
+
+const PREVIEWABLE_TYPES = [
+ 'image/jpeg', 'image/png', 'image/gif', 'image/webp',
+ 'image/svg+xml', 'application/pdf', 'text/plain',
+]
+
+export default function ApprovalTaskDetailsModal({
+ taskId,
+ opened,
+ onClose
+ }: ApprovalTaskDetailsModalProps) {
+ const { data: task, isLoading } = useApprovalTask(taskId)
+ const updateTask = useUpdateApprovalTask()
+
+ // Состояние для предпросмотра файла
+ const [previewFileId, setPreviewFileId] = useState(null)
+ const [previewFileName, setPreviewFileName] = useState('')
+ const [previewFileType, setPreviewFileType] = useState('')
+
+ const form = useForm({
+ initialValues: {
+ status: '',
+ },
+ })
+
+ const handleFilePreview = (fileId: number, fileName: string) => {
+ setPreviewFileId(fileId)
+ setPreviewFileName(fileName)
+ setPreviewFileType(getMimeType(fileName))
+ }
+
+ const handleFileDownload = async (fileId: number, fileName: string) => {
+ try {
+ const token = localStorage.getItem('token')
+ const timestamp = Math.floor(Date.now() / 1000).toString()
+ const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
+ const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
+ const message = publicKey + ':' + timestamp
+ const CryptoJS = await import('crypto-js')
+ const signature = CryptoJS.HmacSHA256(message, privateKey).toString(CryptoJS.enc.Hex)
+ const deviceId = localStorage.getItem('device_id') || 'admin-panel'
+
+ // 🆕 Используем URL для задач
+ const url = `/api/approval-tasks/${taskId}/files/${fileId}/download`
+
+ const response = await fetch(url, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'ApiKey': signature,
+ 'X-Timestamp': timestamp,
+ 'x-device-id': deviceId,
+ },
+ })
+
+ if (!response.ok) throw new Error('Failed to download file')
+
+ const blob = await response.blob()
+ const blobUrl = window.URL.createObjectURL(blob)
+ const link = document.createElement('a')
+ link.href = blobUrl
+ link.download = fileName
+ document.body.appendChild(link)
+ link.click()
+ link.remove()
+ window.URL.revokeObjectURL(blobUrl)
+
+ notifications.show({
+ title: 'Успешно',
+ message: 'Файл скачан',
+ color: 'green',
+ })
+ } catch (error) {
+ notifications.show({
+ title: 'Ошибка',
+ message: 'Не удалось скачать файл',
+ color: 'red',
+ })
+ }
+ }
+
+ const handleSubmit = async (values: typeof form.values) => {
+ if (!task?.id) return
+ await updateTask.mutateAsync({
+ id: task.id,
+ status: values.status,
+ })
+ onClose()
+ }
+
+ return (
+ <>
+
+ Задача #{taskId}
+ {task && (
+
+ {STATUS_LABELS[task.status || ''] || task.status}
+
+ )}
+
+ }
+ size="xl"
+ styles={{
+ body: {
+ height: 'calc(80vh - 120px)',
+ padding: 0,
+ },
+ }}
+ >
+ {isLoading ? (
+
+
+
+ ) : task ? (
+
+
+
+ {/* Информация о задаче */}
+
+ Информация о задаче
+
+ Текст задачи:
+
+ {task.task_text || '—'}
+
+
+ Шаг:
+ #{task.step_order}
+
+
+ Требует файл:
+
+ {task.require_file ? 'Да' : 'Нет'}
+
+
+
+
+
+ {/* 🆕 Прикреплённые файлы */}
+ {task.files && task.files.length > 0 && (
+
+ Прикреплённые файлы
+
+ {task.files.map((file) => {
+ const mimeType = getMimeType(file.file_name || '')
+ const canPreview = PREVIEWABLE_TYPES.includes(mimeType)
+ const fileSizeKB = file.file_base64
+ ? Math.round((file.file_base64.length * 3 / 4) / 1024)
+ : 0
+
+ return (
+
+
+
+
+
+
+ {file.file_name || 'Без имени'}
+
+ {fileSizeKB > 0 && (
+
+ {fileSizeKB} KB
+
+ )}
+
+
+
+ {canPreview && (
+
+ handleFilePreview(file.id!, file.file_name || '')}
+ >
+
+
+
+ )}
+
+ handleFileDownload(file.id!, file.file_name || '')}
+ >
+
+
+
+
+
+
+ )
+ })}
+
+
+ )}
+
+ {/* Связанная заявка */}
+ {task.approval && (
+
+ Связанная заявка
+
+
+ ID заявки:
+ #{task.approval.id}
+
+
+ Тема:
+ {task.approval.topic?.name || '—'}
+
+
+ Инициатор:
+
+
+ {task.approval.initiator?.full_name || '—'}
+
+
+
+ Статус заявки:
+ {task.approval.status}
+
+
+
+ )}
+
+ {/* Исполнитель */}
+ {task.executor && (
+
+ Исполнитель
+
+
+ Имя:
+
+
+ {task.executor.full_name}
+
+
+ {task.executor.department && (
+
+ Отдел:
+
+
+ {task.executor.department.name}
+
+
+ )}
+
+
+ )}
+
+ {/* Даты */}
+
+ Временные метки
+
+
+ Создана:
+
+
+
+ {task.created_at
+ ? dayjs(task.created_at).format('DD.MM.YYYY HH:mm')
+ : '—'}
+
+
+
+
+ Обновлена:
+
+ {task.updated_at
+ ? dayjs(task.updated_at).format('DD.MM.YYYY HH:mm')
+ : '—'}
+
+
+ {task.completed_at && (
+
+ Выполнена:
+
+
+
+ {dayjs(task.completed_at).format('DD.MM.YYYY HH:mm')}
+
+
+
+ )}
+
+
+
+ {/* Форма обновления статуса */}
+
+ Изменить статус
+
+
+
+
+
+ ) : (
+
+ Задача не найдена
+
+ )}
+
+
+ {previewFileId && taskId && (
+ setPreviewFileId(null)}
+ />
+ )}
+ >
+ )
+}
\ No newline at end of file
diff --git a/src/pages/approvals/ApprovalsPage.tsx b/src/pages/approvals/ApprovalsPage.tsx
new file mode 100644
index 0000000..23d1b63
--- /dev/null
+++ b/src/pages/approvals/ApprovalsPage.tsx
@@ -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 = {
+ pending: 'blue',
+ approved: 'green',
+ rejected: 'red',
+ revoked: 'orange',
+ revision: 'violet',
+}
+
+const STATUS_LABELS: Record = {
+ pending: 'На согласовании',
+ approved: 'Согласована',
+ rejected: 'Отклонена',
+ revoked: 'Отозвана',
+ revision: 'На доработке',
+}
+
+export default function ApprovalsPage() {
+ // Фильтры списка
+ const [page, setPage] = useState(1)
+ const [search, setSearch] = useState('')
+ const [statusFilter, setStatusFilter] = useState(null)
+ const [categoryFilter, setCategoryFilter] = useState(null)
+ const [topicFilter, setTopicFilter] = useState(null)
+ const [departmentFilter, setDepartmentFilter] = useState(null)
+
+ const [reportDateFrom, setReportDateFrom] = useState(null)
+ const [reportDateTo, setReportDateTo] = useState(null)
+ const [reportLoading, setReportLoading] = useState(false)
+
+ const [selectedApprovalId, setSelectedApprovalId] = useState(null)
+
+ const [searchInput, setSearchInput] = useState('')
+ const [searchError, setSearchError] = useState(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 (
+
+ {/* Заголовок и кнопка отчёта */}
+
+ Заявки
+
+ Всего: {data?.total_count || 0}
+
+
+
+ {/* 🆕 Секция формирования отчёта */}
+
+
+
+
+
+ Формирование отчёта
+
+ }
+ color="green"
+ onClick={handleGenerateReport}
+ loading={reportLoading}
+ size="sm"
+ >
+ Скачать XLSX
+
+
+
+ } color="blue" variant="light" p="xs">
+
+ Выберите период для выгрузки отчёта. Если даты не указаны — будут выгружены все заявки.
+
+
+
+
+
+
+
+
+
+
+
+
+ {/* Фильтры списка */}
+
+ Фильтры списка
+
+
+ }
+ value={searchInput}
+ onChange={(e) => setSearchInput(e.currentTarget.value)}
+ error={searchError}
+ rightSection={
+ searchInput && (
+ setSearchInput('')}
+ >
+
+
+ )
+ }
+ style={{ flex: 1 }}
+ />
+
+ {
+ setStatusFilter(v)
+ setPage(1)
+ }}
+ clearable
+ style={{ minWidth: 180 }}
+ />
+
+
+
+ {
+ setTopicFilter(v)
+ setPage(1)
+ }}
+ clearable
+ searchable
+ style={{ minWidth: 200 }}
+ disabled={!!categoryFilter}
+ />
+
+ {
+ setDepartmentFilter(v)
+ setPage(1)
+ }}
+ clearable
+ style={{ minWidth: 180 }}
+ />
+
+
+
+
+ {/* Таблица */}
+
+ {isLoading ? (
+
+
+
+ ) : (
+ <>
+
+
+
+ ID
+ Категория / Тема
+ Инициатор
+ Отдел
+ Дата создания
+ Статус
+ Действия
+
+
+
+ {data?.data?.length === 0 ? (
+
+
+
+ Заявки не найдены
+
+
+
+ ) : (
+ (data?.data || []).map((approval) => (
+
+
+ #{approval.id}
+
+
+
+
+ {approval.topic?.category?.name || '—'}
+
+
+
+
+ {approval.topic?.name || 'Тема не указана'}
+
+
+
+
+
+
+ {approval.initiator?.full_name || '—'}
+
+
+
+
+ {approval.department?.name || '—'}
+
+
+
+
+ {approval.created_at
+ ? dayjs(approval.created_at).format('DD.MM.YYYY HH:mm')
+ : '—'}
+
+
+
+
+ {STATUS_LABELS[approval.status || ''] || approval.status}
+
+
+
+
+ setSelectedApprovalId(approval.id!)}
+ >
+
+
+
+
+
+ ))
+ )}
+
+
+
+ {totalPages > 1 && (
+
+
+
+ Страница {page} из {totalPages}
+
+
+
+
+ )}
+ >
+ )}
+
+
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ setSelectedApprovalId(null)}
+ />
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/approvals/components/ApprovalDetailsModal.tsx b/src/pages/approvals/components/ApprovalDetailsModal.tsx
new file mode 100644
index 0000000..d3542b5
--- /dev/null
+++ b/src/pages/approvals/components/ApprovalDetailsModal.tsx
@@ -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 = {
+ draft: 'gray',
+ pending: 'blue',
+ approved: 'green',
+ rejected: 'red',
+ revoked: 'orange',
+ revision: 'violet',
+}
+
+const STATUS_LABELS: Record = {
+ pending: 'На согласовании',
+ approved: 'Согласована',
+ rejected: 'Отклонена',
+ revoked: 'Отозвана',
+ revision: 'На доработке',
+}
+
+const STEP_STATUS_ICONS: Record = {
+ pending: IconClock,
+ approved: IconCheck,
+ rejected: IconX,
+ waiting: IconClock,
+ cancelled_any_of: IconAlertCircle,
+}
+
+const STEP_STATUS_COLORS: Record = {
+ pending: 'blue',
+ approved: 'green',
+ rejected: 'red',
+ waiting: 'gray',
+ cancelled_any_of: 'orange',
+}
+
+// 🆕 Типы файлов, для которых доступен предпросмотр
+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 = {
+ '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(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 (
+ <>
+
+ Заявка #{approvalId}
+ {approval && (
+
+ {STATUS_LABELS[approval.status || ''] || approval.status}
+
+ )}
+
+ }
+ size="xl"
+ styles={{
+ body: {
+ height: 'calc(80vh - 120px)',
+ padding: 0,
+ },
+ }}
+ >
+ {isLoading ? (
+
+
+
+ ) : approval ? (
+
+
+
+ {/* Основная информация */}
+
+ Основная информация
+
+
+ Категория:
+ {category?.name || '—'}
+
+
+ Тема:
+ {approval.topic?.name || '—'}
+
+
+ Инициатор:
+
+
+ {approval.initiator?.full_name || '—'}
+
+
+
+ Отдел:
+
+
+ {approval.department?.name || '—'}
+
+
+
+ Дата создания:
+
+
+
+ {approval.created_at
+ ? dayjs(approval.created_at).format('DD.MM.YYYY HH:mm')
+ : '—'}
+
+
+
+
+
+
+ {/* Текст заявки */}
+ {approval.content && (
+
+ Текст заявки
+ {approval.content}
+
+ )}
+
+ {/* Метаданные */}
+ {approval.metadata && (
+
+ Метаданные
+
+ {(() => {
+ try {
+ return JSON.stringify(JSON.parse(approval.metadata), null, 2)
+ } catch {
+ return approval.metadata
+ }
+ })()}
+
+
+ )}
+
+ {/* 🆕 Файлы */}
+ {approval.files && approval.files.length > 0 && (
+
+ Прикреплённые файлы
+
+ {approval.files.map((file) => {
+ const mimeType = getMimeType(file.file_name || '')
+ const canPreview = PREVIEWABLE_TYPES.includes(mimeType)
+ const fileSizeKB = file.file_base64
+ ? Math.round((file.file_base64.length * 3 / 4) / 1024)
+ : 0
+
+ return (
+
+
+
+
+
+
+ {file.file_name || 'Без имени'}
+
+ {fileSizeKB > 0 && (
+
+ {fileSizeKB} KB
+
+ )}
+
+
+
+ {canPreview && (
+
+ handleFilePreview(file.id!, file.file_name || '')}
+ >
+
+
+
+ )}
+
+ handleFileDownload(file.id!, file.file_name || '')}
+ >
+
+
+
+
+
+
+ )
+ })}
+
+
+ )}
+
+ {/* Шаги согласования */}
+ {approval.steps && approval.steps.length > 0 && (
+
+ Шаги согласования
+
+ {approval.steps
+ .sort((a, b) => (a.step_order || 0) - (b.step_order || 0))
+ .map((step, index) => {
+ const StatusIcon = STEP_STATUS_ICONS[step.status || ''] || IconClock
+ return (
+ }
+ title={
+
+
+ Шаг {index + 1}: {step.approver_name_snapshot || 'Согласующий'}
+
+
+ {step.status}
+
+
+ }
+ >
+
+ {step.approver?.full_name || '—'}
+ {step.acted_at && (
+ <>
+ {' • '}
+ {dayjs(step.acted_at).format('DD.MM.YYYY HH:mm')}
+ >
+ )}
+
+ {step.comment && (
+
+ Комментарий: {step.comment}
+
+ )}
+
+ )
+ })}
+
+
+ )}
+
+ {/* Информация об отзыве */}
+ {approval.status === 'revoked' && approval.revoked_by && (
+
+ Информация об отзыве
+
+
+
+ Отозвана: {approval.revoked_by.full_name}
+ {approval.revoked_at && (
+ <> {dayjs(approval.revoked_at).format('DD.MM.YYYY HH:mm')}>
+ )}
+
+
+
+ )}
+
+ {/* Информация о доработке */}
+ {approval.status === 'revision' && (
+
+ Информация о доработке
+
+ {approval.revision_comment && (
+
+ Комментарий: {approval.revision_comment}
+
+ )}
+ {approval.revision_count !== undefined && approval.revision_count > 0 && (
+
+ Количество доработок: {approval.revision_count}
+
+ )}
+
+
+ )}
+
+
+
+ ) : (
+
+ Заявка не найдена
+
+ )}
+
+
+ {/* 🆕 Модальное окно предпросмотра файла */}
+ {previewFileId && approvalId && (
+ setPreviewFileId(null)}
+ />
+ )}
+ >
+ )
+}
\ No newline at end of file
diff --git a/src/pages/approvals/components/FilePreviewModal.tsx b/src/pages/approvals/components/FilePreviewModal.tsx
new file mode 100644
index 0000000..fad8784
--- /dev/null
+++ b/src/pages/approvals/components/FilePreviewModal.tsx
@@ -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(null)
+ const [fileUrl, setFileUrl] = useState(null)
+
+ // 🆕 Определяем тип сущности
+ const entityType: EntityType = taskId ? 'task' : 'approval'
+ const entityId = taskId || approvalId
+
+ // 🆕 Формируем URL в зависимости от типа сущности
+ const getPreviewUrl = () => {
+ if (entityType === 'task') {
+ return `/api/approval-tasks/${taskId}/files/${fileId}`
+ }
+ return `/api/approvals/${approvalId}/files/${fileId}`
+ }
+
+ const getDownloadUrl = () => {
+ if (entityType === 'task') {
+ return `/api/approval-tasks/${taskId}/files/${fileId}/download`
+ }
+ return `/api/approvals/${approvalId}/files/${fileId}/download`
+ }
+
+ const canPreview = [
+ 'image/jpeg',
+ 'image/png',
+ 'image/gif',
+ 'image/webp',
+ 'image/svg+xml',
+ 'application/pdf',
+ 'text/plain',
+ ].includes(fileType)
+
+ useEffect(() => {
+ if (!opened || !canPreview || !entityId) return
+
+ let objectUrl: string | null = null
+
+ const loadFile = async () => {
+ setLoading(true)
+ setError(null)
+
+ try {
+ const headers = await getAuthHeaders()
+ const url = getPreviewUrl()
+
+ const response = await fetch(url, {
+ method: 'GET',
+ headers,
+ })
+
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`)
+ }
+
+ const blob = await response.blob()
+ objectUrl = window.URL.createObjectURL(blob)
+ setFileUrl(objectUrl)
+ } catch (err) {
+ console.error('File load error:', err)
+ setError('Не удалось загрузить файл')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ loadFile()
+
+ return () => {
+ if (objectUrl) {
+ window.URL.revokeObjectURL(objectUrl)
+ }
+ }
+ }, [opened, entityId, fileId, canPreview])
+
+ const handleDownload = async () => {
+ try {
+ const headers = await getAuthHeaders()
+ const url = getDownloadUrl()
+
+ const response = await fetch(url, {
+ method: 'GET',
+ headers,
+ })
+
+ if (!response.ok) {
+ throw new Error('Failed to download file')
+ }
+
+ const blob = await response.blob()
+ const blobUrl = window.URL.createObjectURL(blob)
+ const link = document.createElement('a')
+ link.href = blobUrl
+ link.download = fileName
+ document.body.appendChild(link)
+ link.click()
+ link.remove()
+ window.URL.revokeObjectURL(blobUrl)
+
+ notifications.show({
+ title: 'Успешно',
+ message: 'Файл скачан',
+ color: 'green',
+ })
+ } catch (err) {
+ console.error('Download error:', err)
+ notifications.show({
+ title: 'Ошибка',
+ message: 'Не удалось скачать файл',
+ color: 'red',
+ })
+ }
+ }
+
+ if (!canPreview) {
+ return (
+
+
+
+
+ Предпросмотр этого типа файла не поддерживается.
+
+ Вы можете скачать файл.
+
+
+
+
+
+
+
+
+
+ )
+ }
+
+ return (
+
+ {fileName}
+
+
+
+
+ }
+ size="xl"
+ styles={{
+ body: {
+ height: 'calc(80vh - 120px)',
+ padding: 0,
+ },
+ }}
+ >
+
+ {loading && (
+
+
+
+ Загрузка файла...
+
+
+ )}
+
+ {error && (
+
+ {error}
+
+ )}
+
+ {fileUrl && !error && (
+ <>
+ {fileType.startsWith('image/') ? (
+
+
+
+ ) : fileType === 'application/pdf' ? (
+
+ ) : fileType === 'text/plain' ? (
+
+ ) : null}
+ >
+ )}
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/categories/CategoriesPage.tsx b/src/pages/categories/CategoriesPage.tsx
new file mode 100644
index 0000000..41af889
--- /dev/null
+++ b/src/pages/categories/CategoriesPage.tsx
@@ -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(null)
+ const [editCategoryId, setEditCategoryId] = useState(null)
+ const [createModalOpened, setCreateModalOpened] = useState(false)
+
+ const { data, isLoading, isFetching } = useCategories({
+ offset: (page - 1) * LIMIT,
+ limit: LIMIT,
+ ...(search && { name: search }),
+ ...(activeFilter !== null && { is_active: activeFilter }),
+ })
+
+ const deleteCategory = useDeleteCategory()
+
+ const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
+
+ const handleDelete = (id: number) => {
+ modals.openConfirmModal({
+ title: 'Подтвердите удаление',
+ children: (
+
+ Вы уверены, что хотите удалить эту категорию? Все темы этой категории останутся без категории.
+
+ ),
+ labels: { confirm: 'Удалить', cancel: 'Отмена' },
+ confirmProps: { color: 'red' },
+ onConfirm: () => deleteCategory.mutate(id),
+ })
+ }
+
+ return (
+
+
+ Категории тем
+
+
+ Всего: {data?.total_count || 0}
+
+ }
+ onClick={() => setCreateModalOpened(true)}
+ >
+ Создать категорию
+
+
+
+
+ {/* Фильтры */}
+
+
+ }
+ value={search}
+ onChange={(e) => {
+ setSearch(e.currentTarget.value)
+ setPage(1)
+ }}
+ style={{ flex: 1 }}
+ />
+
+ {
+ setActiveFilter(e.currentTarget.checked ? true : null)
+ setPage(1)
+ }}
+ />
+
+
+
+ {/* Таблица */}
+
+ {isLoading ? (
+
+
+
+ ) : (
+ <>
+
+
+
+ ID
+ Название
+ Код
+ Описание
+ Статус
+ Действия
+
+
+
+ {data?.data?.length === 0 ? (
+
+
+
+ Категории не найдены
+
+
+
+ ) : (
+ (data?.data || []).map((category) => (
+
+ {category.id}
+
+ {category.name}
+
+
+
+ {category.code}
+
+
+
+
+ {category.description || '—'}
+
+
+
+
+ {category.is_active ? 'Активна' : 'Неактивна'}
+
+
+
+
+
+ setEditCategoryId(category.id!)}
+ >
+
+
+
+
+ handleDelete(category.id!)}
+ >
+
+
+
+
+
+
+ ))
+ )}
+
+
+
+ {/* Пагинация */}
+ {totalPages > 1 && (
+
+
+
+ Страница {page} из {totalPages}
+
+
+
+
+ )}
+ >
+ )}
+
+
+ {/* Индикатор обновления */}
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ {/* Модальное окно редактирования */}
+ setEditCategoryId(null)}
+ />
+
+ {/* Модальное окно создания */}
+ setCreateModalOpened(false)}
+ />
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/categories/components/CategoryEditModal.tsx b/src/pages/categories/components/CategoryEditModal.tsx
new file mode 100644
index 0000000..8290373
--- /dev/null
+++ b/src/pages/categories/components/CategoryEditModal.tsx
@@ -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 (
+
+
+ {isEditMode ? 'Редактирование категории' : 'Создание категории'}
+
+ {category && ID: {category.id}}
+
+ }
+ size="md"
+ >
+ {isLoading ? (
+
+
+
+ ) : (
+
+ )}
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/hierarchies/HierarchiesPage.tsx b/src/pages/hierarchies/HierarchiesPage.tsx
new file mode 100644
index 0000000..980f150
--- /dev/null
+++ b/src/pages/hierarchies/HierarchiesPage.tsx
@@ -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('chains')
+ const [subordinateFilter, setSubordinateFilter] = useState(null)
+ const [departmentFilter, setDepartmentFilter] = useState(null)
+ const [editHierarchy, setEditHierarchy] = useState(null)
+ const [createModalOpened, setCreateModalOpened] = useState(false)
+ const [presetGroup, setPresetGroup] = useState(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: (
+
+ Вы уверены, что хотите удалить эту связь? Это может повлиять на процесс согласования.
+
+ ),
+ 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 (
+
+ {/* Заголовок */}
+
+ Иерархия согласований
+
+ setViewMode(v as ViewMode)}
+ data={[
+ { value: 'chains', label: 'Цепочки' },
+ { value: 'table', label: 'Таблица'},
+ ]}
+ />
+ }
+ onClick={() => {
+ setPresetGroup(null)
+ setCreateModalOpened(true)
+ }}
+ >
+ Добавить связь
+
+
+
+
+ {/* Подсказка */}
+ } color="blue" variant="light">
+
+ Иерархия определяет порядок согласования заявок. Каждая цепочка показывает,
+ через каких согласующих проходит заявка от конкретного подчинённого.
+ Шаги выполняются последовательно в порядке возрастания priority.
+
+
+
+ {/* Фильтры */}
+
+
+
+
+
+
+
+ Всего связей: {data?.data?.length || 0}
+
+
+
+
+ {/* Контент */}
+ {isLoading ? (
+
+
+
+ ) : viewMode === 'chains' ? (
+ // Режим цепочек
+
+
+ {enrichedChains.length === 0 ? (
+
+
+ Связи не найдены
+
+
+ ) : (
+ enrichedChains.map((chain) => (
+
+ ))
+ )}
+
+
+ ) : (
+ // Режим таблицы
+
+
+
+
+ ID
+ Подчинённый
+ Согласующий
+ Отдел
+ Область
+ Объект
+ Порядок
+ Действия
+
+
+
+ {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 (
+
+ {h.id}
+
+
+ {h.subordinate?.full_name || '—'}
+
+
+
+
+ {h.approver?.full_name || '—'}
+
+
+
+ {h.department?.name || '—'}
+
+
+
+ {SCOPE_LABELS[scopeType as keyof typeof SCOPE_LABELS]}
+
+
+
+ {scopeObjectName}
+
+
+
+ #{h.priority}
+
+
+
+
+
+ setEditHierarchy(h)}
+ >
+
+
+
+
+ handleDelete(h.id!)}
+ >
+
+
+
+
+
+
+ )
+ })}
+
+
+
+ )}
+
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ {/* Модальные окна */}
+
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/hierarchies/components/ChainVisualization.tsx b/src/pages/hierarchies/components/ChainVisualization.tsx
new file mode 100644
index 0000000..fcebcc7
--- /dev/null
+++ b/src/pages/hierarchies/components/ChainVisualization.tsx
@@ -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
+ case 'category': return
+ case 'topic': return
+ default: return
+ }
+}
+
+export default function ChainVisualization({
+ group,
+ onEditStep,
+ onDeleteStep,
+ onAddStep,
+ }: ChainVisualizationProps) {
+ return (
+
+ {/* Заголовок группы */}
+
+
+
+ {group.subordinateName.charAt(0)}
+
+
+ {group.subordinateName}
+ {group.departmentName}
+
+
+ }
+ >
+ {SCOPE_LABELS[group.scopeType]}: {group.scopeObjectName}
+
+
+
+
+ onAddStep(group)}
+ >
+
+
+
+
+
+
+
+
+
+ ИНИЦИАТОР
+
+ {group.subordinateName.charAt(0)}
+
+
+ {group.subordinateName}
+
+
+
+
+ {/* Шаги согласования */}
+ {group.steps.map((step, index) => (
+
+ {/* Стрелка */}
+
+
+ {/* Карточка согласующего */}
+ onEditStep(step.id!)}
+ className="hover-shadow"
+ >
+
+
+
+ ШАГ {index + 1}
+
+
+ #{step.priority}
+
+
+
+ {step.approver?.full_name?.charAt(0) || '?'}
+
+
+ {step.approver?.full_name || '—'}
+
+
+ {/* Кнопки действий */}
+
+
+ {
+ e.stopPropagation()
+ onEditStep(step.id!)
+ }}
+ >
+
+
+
+
+ {
+ e.stopPropagation()
+ onDeleteStep(step.id!)
+ }}
+ >
+
+
+
+
+
+
+
+ ))}
+
+
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/hierarchies/components/HierarchyEditModal.tsx b/src/pages/hierarchies/components/HierarchyEditModal.tsx
new file mode 100644
index 0000000..7d8c22b
--- /dev/null
+++ b/src/pages/hierarchies/components/HierarchyEditModal.tsx
@@ -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 (
+
+
+ {isEditMode ? 'Редактирование связи' : 'Добавление связи'}
+
+ {hierarchy && ID: {hierarchy.id}}
+
+ }
+ size="lg"
+ >
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/permissions/PermissionsPage.tsx b/src/pages/permissions/PermissionsPage.tsx
new file mode 100644
index 0000000..552034b
--- /dev/null
+++ b/src/pages/permissions/PermissionsPage.tsx
@@ -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(null)
+ const [actionFilter, setActionFilter] = useState(null)
+ const [editPermissionId, setEditPermissionId] = useState(null)
+ const [createModalOpened, setCreateModalOpened] = useState(false)
+
+ const { data, isLoading, isFetching } = usePermissions({
+ offset: (page - 1) * LIMIT,
+ limit: LIMIT,
+ ...(roleFilter && { role_id: Number(roleFilter) }),
+ ...(actionFilter && { action: actionFilter }),
+ })
+
+ const { data: roles } = useRoles({ limit: 1000 })
+ const deletePermission = useDeletePermission()
+
+ const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
+
+ const roleOptions = roles?.data?.map((r) => ({
+ value: String(r.id),
+ label: r.name || '',
+ })) || []
+
+ const handleDelete = (id: number) => {
+ modals.openConfirmModal({
+ title: 'Подтвердите удаление',
+ children: (
+
+ Вы уверены, что хотите удалить это право? Пользователи с этой ролью потеряют соответствующие возможности.
+
+ ),
+ labels: { confirm: 'Удалить', cancel: 'Отмена' },
+ confirmProps: { color: 'red' },
+ onConfirm: () => deletePermission.mutate(id),
+ })
+ }
+
+ // Определяем "уровень" права
+ const getPermissionLevel = (permission: any) => {
+ if (permission.topic_id && permission.topic) {
+ return {
+ level: 'topic',
+ label: 'Тема',
+ value: permission.topic.name,
+ icon: IconBriefcase,
+ color: 'orange',
+ }
+ }
+ if (permission.topic_category_id && permission.topic_category) {
+ return {
+ level: 'category',
+ label: 'Категория',
+ value: permission.topic_category.name,
+ icon: IconCategory,
+ color: 'blue',
+ }
+ }
+ return {
+ level: 'global',
+ label: 'Глобальное',
+ value: 'Все темы',
+ icon: IconWorld,
+ color: 'violet',
+ }
+ }
+
+ return (
+
+
+ Права доступа
+
+
+ Всего: {data?.total_count || 0}
+
+ }
+ onClick={() => setCreateModalOpened(true)}
+ >
+ Добавить право
+
+
+
+
+ {/* Подсказка */}
+
+
+
+
+ Права определяют, какие действия могут выполнять пользователи с определённой ролью.
+ Право может быть глобальным (на все темы),
+ на категорию (на все темы категории) или на конкретную тему.
+
+
+
+
+ {/* Фильтры */}
+
+
+ {
+ setRoleFilter(v)
+ setPage(1)
+ }}
+ clearable
+ searchable
+ style={{ minWidth: 200 }}
+ />
+
+ ({
+ value: a.value,
+ label: a.label,
+ }))}
+ value={actionFilter}
+ onChange={(v) => {
+ setActionFilter(v)
+ setPage(1)
+ }}
+ clearable
+ style={{ minWidth: 200 }}
+ />
+
+
+
+ {/* Таблица */}
+
+ {isLoading ? (
+
+
+
+ ) : (
+ <>
+
+
+
+ ID
+ Роль
+ Действие
+ Область действия
+ Объект
+ Действия
+
+
+
+ {data?.data?.length === 0 ? (
+
+
+
+ Права не найдены
+
+
+
+ ) : (
+ (data?.data || []).map((permission) => {
+ const level = getPermissionLevel(permission)
+ const LevelIcon = level.icon
+ return (
+
+ {permission.id}
+
+
+
+
+
+
+ {permission.role?.name || '—'}
+
+
+
+ {permission.role?.code}
+
+
+
+
+ {ACTION_LABELS[permission.action || ''] || permission.action}
+
+
+
+
+
+
+ {level.label}
+
+
+
+
+
+ {level.value}
+
+
+
+
+
+ setEditPermissionId(permission.id!)}
+ >
+
+
+
+
+ handleDelete(permission.id!)}
+ >
+
+
+
+
+
+
+ )
+ })
+ )}
+
+
+
+ {totalPages > 1 && (
+
+
+
+ Страница {page} из {totalPages}
+
+
+
+
+ )}
+ >
+ )}
+
+
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ setEditPermissionId(null)}
+ />
+
+ setCreateModalOpened(false)}
+ />
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/permissions/components/PermissionEditModal.tsx b/src/pages/permissions/components/PermissionEditModal.tsx
new file mode 100644
index 0000000..0759d10
--- /dev/null
+++ b/src/pages/permissions/components/PermissionEditModal.tsx
@@ -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 (
+
+
+ {isEditMode ? 'Редактирование права' : 'Добавление права'}
+
+ {permission && ID: {permission.id}}
+
+ }
+ size="lg"
+ >
+ {isLoading ? (
+
+
+
+ ) : (
+
+ )}
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/roles/RolesPage.tsx b/src/pages/roles/RolesPage.tsx
new file mode 100644
index 0000000..3d3391c
--- /dev/null
+++ b/src/pages/roles/RolesPage.tsx
@@ -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(null)
+ const [editRoleId, setEditRoleId] = useState(null)
+ const [createModalOpened, setCreateModalOpened] = useState(false)
+
+ const { data, isLoading, isFetching } = useRoles({
+ offset: (page - 1) * LIMIT,
+ limit: LIMIT,
+ ...(search && { name: search }),
+ ...(roleTypeFilter === 'director' && { is_director: true }),
+ ...(roleTypeFilter === 'approver' && { is_approver: true }),
+ ...(roleTypeFilter === 'observer' && { is_observer: true }),
+ ...(roleTypeFilter === 'executor' && { is_executor: true }),
+ })
+
+ const deleteRole = useDeleteRole()
+
+ const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
+
+ const handleDelete = (id: number) => {
+ modals.openConfirmModal({
+ title: 'Подтвердите удаление',
+ children: (
+
+ Вы уверены, что хотите удалить эту роль? Это действие нельзя отменить.
+
+ ),
+ labels: { confirm: 'Удалить', cancel: 'Отмена' },
+ confirmProps: { color: 'red' },
+ onConfirm: () => deleteRole.mutate(id),
+ })
+ }
+
+ return (
+
+
+ Роли
+
+
+ Всего: {data?.total_count || 0}
+
+ }
+ onClick={() => setCreateModalOpened(true)}
+ >
+ Создать роль
+
+
+
+
+ {/* Фильтры */}
+
+
+ }
+ value={search}
+ onChange={(e) => {
+ setSearch(e.currentTarget.value)
+ setPage(1)
+ }}
+ style={{ flex: 1 }}
+ />
+
+
+ {
+ setRoleTypeFilter(null)
+ setPage(1)
+ }}
+ >
+ Все
+
+ {
+ setRoleTypeFilter(roleTypeFilter === 'director' ? null : 'director')
+ setPage(1)
+ }}
+ >
+ Директора
+
+ {
+ setRoleTypeFilter(roleTypeFilter === 'approver' ? null : 'approver')
+ setPage(1)
+ }}
+ >
+ Согласующие
+
+ {
+ setRoleTypeFilter(roleTypeFilter === 'observer' ? null : 'observer')
+ setPage(1)
+ }}
+ >
+ Наблюдатели
+
+ {
+ setRoleTypeFilter(roleTypeFilter === 'executor' ? null : 'executor')
+ setPage(1)
+ }}
+ >
+ Исполнители
+
+
+
+
+
+ {/* Таблица */}
+
+ {isLoading ? (
+
+
+
+ ) : (
+ <>
+
+
+
+ ID
+ Название
+ Код
+ Типы ролей
+ Описание
+ Статус
+ Действия
+
+
+
+ {data?.data?.length === 0 ? (
+
+
+
+ Роли не найдены
+
+
+
+ ) : (
+ (data?.data || []).map((role) => (
+
+ {role.id}
+
+ {role.name}
+
+
+
+ {role.code}
+
+
+
+
+ {role.is_director && (
+
+ Директор
+
+ )}
+ {role.is_approver && (
+
+ Согласующий
+
+ )}
+ {role.is_observer && (
+
+ Наблюдатель
+
+ )}
+ {role.is_executor && (
+
+ Исполнитель
+
+ )}
+ {!role.is_director && !role.is_approver && !role.is_observer && !role.is_executor && (
+ —
+ )}
+
+
+
+
+ {role.description || '—'}
+
+
+
+
+ {role.is_default ? 'По умолчанию' : 'Пользовательская'}
+
+
+
+
+
+ setEditRoleId(role.id!)}
+ >
+
+
+
+
+ handleDelete(role.id!)}
+ disabled={role.is_default}
+ >
+
+
+
+
+
+
+ ))
+ )}
+
+
+
+ {/* Пагинация */}
+ {totalPages > 1 && (
+
+
+
+ Страница {page} из {totalPages}
+
+
+
+
+ )}
+ >
+ )}
+
+
+ {/* Индикатор обновления */}
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ {/* Модальное окно редактирования */}
+ setEditRoleId(null)}
+ />
+
+ {/* Модальное окно создания */}
+ setCreateModalOpened(false)}
+ />
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/roles/components/RoleEditModal.tsx b/src/pages/roles/components/RoleEditModal.tsx
new file mode 100644
index 0000000..4ad9e61
--- /dev/null
+++ b/src/pages/roles/components/RoleEditModal.tsx
@@ -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 (
+
+
+ {isEditMode ? 'Редактирование роли' : 'Создание роли'}
+
+ {role && ID: {role.id}}
+
+ }
+ size="lg"
+ >
+ {isLoading ? (
+
+
+
+ ) : (
+
+ )}
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/settings/SettingsPage.tsx b/src/pages/settings/SettingsPage.tsx
new file mode 100644
index 0000000..c74150c
--- /dev/null
+++ b/src/pages/settings/SettingsPage.tsx
@@ -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: (
+
+ Вы уверены, что хотите изменить пароль? После смены пароля вам нужно будет
+ войти заново на всех устройствах.
+
+ ),
+ labels: { confirm: 'Изменить пароль', cancel: 'Отмена' },
+ confirmProps: { color: 'red' },
+ onConfirm: async () => {
+ setLoading(true)
+ try {
+ await authApi.updateProfile({ password: values.new_password })
+
+ notifications.show({
+ title: 'Успешно',
+ message: 'Пароль успешно изменен',
+ color: 'green',
+ })
+
+ form.reset()
+
+ // Разлогиниваем пользователя, чтобы он вошёл заново
+ setTimeout(() => {
+ localStorage.removeItem('token')
+ window.location.href = '/login'
+ }, 1500)
+
+ } catch (error: any) {
+ notifications.show({
+ title: 'Ошибка',
+ message: error.response?.data?.error_description || 'Не удалось изменить пароль',
+ color: 'red',
+ })
+ } finally {
+ setLoading(false)
+ }
+ },
+ })
+ }
+
+ return (
+
+
+
+
Настройки
+
+ Управление вашим аккаунтом
+
+
+
+ {/* Информация о профиле */}
+
+
+
+ Логин:
+ {user?.login || '—'}
+
+ {user?.last_login && (
+
+ Последний вход:
+
+ {new Date(user.last_login).toLocaleString('ru-RU')}
+
+
+ )}
+ {user?.last_ip_login && (
+
+ Последний IP:
+ {user.last_ip_login}
+
+ )}
+
+
+
+ {/* Смена пароля */}
+
+
+
+ Смена пароля
+
+
+ }
+ color="yellow"
+ variant="light"
+ mb="md"
+ >
+
+ После смены пароля вам нужно будет войти заново на всех устройствах.
+
+
+
+
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/topicExecutors/TopicExecutorsPage.tsx b/src/pages/topicExecutors/TopicExecutorsPage.tsx
new file mode 100644
index 0000000..59c5e1e
--- /dev/null
+++ b/src/pages/topicExecutors/TopicExecutorsPage.tsx
@@ -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('cards')
+ const [topicFilter, setTopicFilter] = useState(null)
+ const [targetSystemFilter, setTargetSystemFilter] = useState(null)
+ const [editExecutor, setEditExecutor] = useState(null)
+ const [createModalOpened, setCreateModalOpened] = useState(false)
+ const [presetGroup, setPresetGroup] = useState(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: (
+
+ Вы уверены, что хотите удалить этого исполнителя?
+ Задачи по этой теме не будут назначаться данному пользователю.
+
+ ),
+ 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 (
+
+ {/* Заголовок */}
+
+ Исполнители тем
+
+ setViewMode(v as ViewMode)}
+ data={[
+ { value: 'cards', label: 'Карточки' },
+ { value: 'table', label: 'Таблица'},
+ ]}
+ />
+ }
+ onClick={() => {
+ setPresetGroup(null)
+ setCreateModalOpened(true)
+ }}
+ >
+ Добавить исполнителя
+
+
+
+
+ {/* Подсказка */}
+ } color="orange" variant="light">
+
+ Исполнители — это пользователи, которые выполняют задачи после согласования заявки.
+ Каждая тема может иметь несколько исполнителей с разными шагами.
+ Поле "Текст задачи" содержит инструкцию для исполнителя.
+
+
+
+ {/* Фильтры */}
+
+
+
+
+
+
+
+ Всего исполнителей: {data?.data?.length || 0}
+
+
+
+
+ {/* Контент */}
+ {isLoading ? (
+
+
+
+ ) : viewMode === 'cards' ? (
+ // Режим карточек
+
+
+ {groups.length === 0 ? (
+
+
+ Исполнители не найдены
+
+
+ ) : (
+ groups.map((group) => (
+
+ ))
+ )}
+
+
+ ) : (
+ // Режим таблицы
+
+
+
+
+ ID
+ Тема
+ Исполнитель
+ Шаг
+ Задача
+ Система
+ Файл
+ Статус
+ Действия
+
+
+
+ {data?.data?.map((executor) => (
+
+ {executor.id}
+
+
+ {executor.topic?.name || '—'}
+
+
+ {executor.topic?.code}
+
+
+
+
+ {executor.user?.full_name || '—'}
+
+
+ {executor.user?.department?.name}
+
+
+
+
+ #{executor.step_order}
+
+
+
+
+ {executor.task_text || '—'}
+
+
+
+
+ {TARGET_SYSTEM_LABELS[executor.target_system || ''] || executor.target_system}
+
+
+
+ {executor.require_file ? (
+
+ ) : (
+ —
+ )}
+
+
+ : }
+ >
+ {executor.is_active ? 'Активен' : 'Неактивен'}
+
+
+
+
+
+ setEditExecutor(executor)}
+ >
+
+
+
+
+ handleDelete(executor.id!)}
+ >
+
+
+
+
+
+
+ ))}
+
+
+
+ )}
+
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ {/* Модальные окна */}
+
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/topicExecutors/components/TopicExecutorEditModal.tsx b/src/pages/topicExecutors/components/TopicExecutorEditModal.tsx
new file mode 100644
index 0000000..1269128
--- /dev/null
+++ b/src/pages/topicExecutors/components/TopicExecutorEditModal.tsx
@@ -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 (
+
+
+ {isEditMode ? 'Редактирование исполнителя' : 'Добавление исполнителя'}
+
+ {executor && ID: {executor.id}}
+
+ }
+ size="lg"
+ >
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/topicExecutors/components/TopicExecutorsCard.tsx b/src/pages/topicExecutors/components/TopicExecutorsCard.tsx
new file mode 100644
index 0000000..13bba54
--- /dev/null
+++ b/src/pages/topicExecutors/components/TopicExecutorsCard.tsx
@@ -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 (
+
+ {/* Заголовок темы */}
+
+
+
+
+
+
+ {group.topicName}
+ {group.topicCode}
+ {group.categoryName && (
+ }
+ mt={4}
+ >
+ {group.categoryName}
+
+ )}
+
+
+
+
+ onAddExecutor(group)}
+ >
+
+
+
+
+
+ {/* Список исполнителей */}
+
+ {group.executors.length === 0 ? (
+
+ Исполнители не назначены
+
+ ) : (
+
+ {group.executors.map((executor, index) => (
+ onEditExecutor(executor.id!)}
+ className="hover-shadow"
+ >
+
+ {/* Верхняя строка: исполнитель и метаданные */}
+
+
+
+ Шаг #{executor.step_order ?? index}
+
+
+ {executor.user?.full_name?.charAt(0) || '?'}
+
+
+
+ {executor.user?.full_name || '—'}
+
+ {executor.user?.department?.name && (
+
+ {executor.user.department.name}
+
+ )}
+
+
+
+
+ {/* Целевая система */}
+ {executor.target_system && (
+
+ {TARGET_SYSTEM_LABELS[executor.target_system] || executor.target_system}
+
+ )}
+
+ {/* Требует файл */}
+ {executor.require_file && (
+
+ }
+ >
+ Файл
+
+
+ )}
+
+ {/* Активен/неактивен */}
+ : }
+ >
+ {executor.is_active ? 'Активен' : 'Неактивен'}
+
+
+ {/* Кнопки действий */}
+
+ {
+ e.stopPropagation()
+ onEditExecutor(executor.id!)
+ }}
+ >
+
+
+
+
+ {
+ e.stopPropagation()
+ onDeleteExecutor(executor.id!)
+ }}
+ >
+
+
+
+
+
+
+ {/* Текст задачи */}
+ {executor.task_text && (
+
+
+ Задача:
+
+
+ {executor.task_text}
+
+
+ )}
+
+
+ ))}
+
+ )}
+
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/topics/TopicsPage.tsx b/src/pages/topics/TopicsPage.tsx
new file mode 100644
index 0000000..3558555
--- /dev/null
+++ b/src/pages/topics/TopicsPage.tsx
@@ -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(null)
+ const [activeFilter, setActiveFilter] = useState(null)
+ const [editTopicId, setEditTopicId] = useState(null)
+ const [createModalOpened, setCreateModalOpened] = useState(false)
+
+ const { data, isLoading, isFetching } = useTopics({
+ offset: (page - 1) * LIMIT,
+ limit: LIMIT,
+ ...(search && { name: search }),
+ ...(categoryFilter && { category_id: Number(categoryFilter) }),
+ ...(activeFilter !== null && { is_active: activeFilter }),
+ })
+
+ const { data: categories } = useCategories({ limit: 1000 })
+ const deleteTopic = useDeleteTopic()
+
+ const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
+
+ const categoryOptions = categories?.data?.map((c) => ({
+ value: String(c.id),
+ label: c.name || '',
+ })) || []
+
+ const handleDelete = (id: number) => {
+ modals.openConfirmModal({
+ title: 'Подтвердите удаление',
+ children: (
+
+ Вы уверены, что хотите удалить эту тему? Связанные данные (исполнители, иерархия) могут быть затронуты.
+
+ ),
+ labels: { confirm: 'Удалить', cancel: 'Отмена' },
+ confirmProps: { color: 'red' },
+ onConfirm: () => deleteTopic.mutate(id),
+ })
+ }
+
+ return (
+
+
+ Темы согласований
+
+
+ Всего: {data?.total_count || 0}
+
+ }
+ onClick={() => setCreateModalOpened(true)}
+ >
+ Создать тему
+
+
+
+
+ {/* Фильтры */}
+
+
+ }
+ value={search}
+ onChange={(e) => {
+ setSearch(e.currentTarget.value)
+ setPage(1)
+ }}
+ style={{ flex: 1 }}
+ />
+
+ {
+ setCategoryFilter(v)
+ setPage(1)
+ }}
+ clearable
+ searchable
+ style={{ minWidth: 200 }}
+ />
+
+ {
+ setActiveFilter(e.currentTarget.checked ? true : null)
+ setPage(1)
+ }}
+ />
+
+
+
+ {/* Таблица */}
+
+ {isLoading ? (
+
+
+
+ ) : (
+ <>
+
+
+
+ ID
+ Название
+ Категория
+ Код
+ Параметры
+ Статус
+ Действия
+
+
+
+ {data?.data?.length === 0 ? (
+
+
+
+ Темы не найдены
+
+
+
+ ) : (
+ (data?.data || []).map((topic) => (
+
+ {topic.id}
+
+ {topic.name}
+
+
+
+ {topic.category?.name || '—'}
+
+
+
+
+ {topic.code}
+
+
+
+
+ {topic.duration_type && (
+
+ {topic.duration_type}
+
+ )}
+ {topic.time_type && (
+
+ {topic.time_type}
+
+ )}
+ {topic.payment_type && (
+
+ {topic.payment_type}
+
+ )}
+ {topic.requires_file && (
+
+ Файл
+
+ )}
+
+
+
+
+ {topic.is_active ? 'Активна' : 'Неактивна'}
+
+
+
+
+
+ setEditTopicId(topic.id!)}
+ >
+
+
+
+
+ handleDelete(topic.id!)}
+ >
+
+
+
+
+
+
+ ))
+ )}
+
+
+
+ {totalPages > 1 && (
+
+
+
+ Страница {page} из {totalPages}
+
+
+
+
+ )}
+ >
+ )}
+
+
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ setEditTopicId(null)}
+ />
+
+ setCreateModalOpened(false)}
+ />
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/topics/components/TopicEditModal.tsx b/src/pages/topics/components/TopicEditModal.tsx
new file mode 100644
index 0000000..8858c83
--- /dev/null
+++ b/src/pages/topics/components/TopicEditModal.tsx
@@ -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 (
+
+
+ {isEditMode ? 'Редактирование темы' : 'Создание темы'}
+
+ {topic && ID: {topic.id}}
+
+ }
+ size="xl"
+ >
+ {isLoading ? (
+
+
+
+ ) : (
+
+ )}
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/users/UsersPage.tsx b/src/pages/users/UsersPage.tsx
new file mode 100644
index 0000000..5b108b6
--- /dev/null
+++ b/src/pages/users/UsersPage.tsx
@@ -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(null)
+ const [statusFilter, setStatusFilter] = useState(null)
+ const [editUserId, setEditUserId] = useState(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 (
+
+
+ Пользователи
+
+ Всего: {data?.total_count || 0}
+
+
+
+ {/* Фильтры */}
+
+
+ }
+ value={search}
+ onChange={(e) => {
+ setSearch(e.currentTarget.value)
+ setPage(1)
+ }}
+ style={{ flex: 1 }}
+ />
+
+ {
+ setDepartmentFilter(v)
+ setPage(1)
+ }}
+ clearable
+ style={{ minWidth: 200 }}
+ />
+
+ {
+ setStatusFilter(v)
+ setPage(1)
+ }}
+ clearable
+ style={{ minWidth: 180 }}
+ />
+
+
+
+ {/* Таблица */}
+
+ {isLoading ? (
+
+
+
+ ) : (
+ <>
+
+
+
+ ID
+ Telegram ID
+ Имя
+ Username
+ Отдел
+ Роли
+ Статус
+ Действия
+
+
+
+ {data?.data?.length === 0 ? (
+
+
+
+ Пользователи не найдены
+
+
+
+ ) : (
+ (data?.data || []).map((user) => (
+
+ {user.id}
+
+ {user.telegram_id}
+
+
+ {user.full_name}
+
+
+ @{user.username || '—'}
+
+
+ {user.department?.name || —}
+
+
+
+ {user.user_roles?.slice(0, 3).map((ur) => (
+
+ {ur.role?.name || 'Роль'}
+
+ ))}
+ {user.user_roles && user.user_roles.length > 3 && (
+
+ +{user.user_roles.length - 3}
+
+ )}
+ {(!user.user_roles || user.user_roles.length === 0) && (
+ —
+ )}
+
+
+
+
+
+
+
+ setEditUserId(user.id!)}
+ >
+
+
+
+
+
+ ))
+ )}
+
+
+
+ {/* Пагинация */}
+ {totalPages > 1 && (
+
+
+
+ Страница {page} из {totalPages}
+
+
+
+
+ )}
+ >
+ )}
+
+
+ {/* Индикатор обновления */}
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ {/* Модальное окно редактирования */}
+ setEditUserId(null)}
+ />
+
+ )
+}
+
+function UserStatusBadge({
+ isBlocked,
+ isFired
+ }: {
+ isBlocked?: boolean
+ isFired?: boolean
+}) {
+ if (isFired) {
+ return Уволен
+ }
+ if (isBlocked) {
+ return Заблокирован
+ }
+ return Активен
+}
\ No newline at end of file
diff --git a/src/types/api.ts b/src/types/api.ts
new file mode 100644
index 0000000..cb21588
--- /dev/null
+++ b/src/types/api.ts
@@ -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 {
+ 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[]
+}
\ No newline at end of file
diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts
new file mode 100644
index 0000000..afbc072
--- /dev/null
+++ b/src/vite-env.d.ts
@@ -0,0 +1,12 @@
+///
+
+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
+}
\ No newline at end of file
diff --git a/tsconfig.app.json b/tsconfig.app.json
index 7f42e5f..3e39e52 100644
--- a/tsconfig.app.json
+++ b/tsconfig.app.json
@@ -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"]
-}
+}
\ No newline at end of file
diff --git a/tsconfig.json b/tsconfig.json
index 1ffef60..6657b50 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -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" }]
+}
\ No newline at end of file
diff --git a/vite.config.ts b/vite.config.ts
index 1ebb97c..34e4f37 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -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'
+ }
+ },
},
},
},
Connect with us
-Join the Vite community
---
-
-
- GitHub
-
-
- -
-
-
- Discord
-
-
- -
-
-
- X.com
-
-
- -
-
-
- Bluesky
-
-
-
-