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 ( - <> -
-
- - React logo - Vite logo -
-
-

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 + + + + + + + + + {user?.login?.charAt(0).toUpperCase() || 'A'} + + + + + + }> + {user?.login || 'Admin'} + + + } + onClick={logout} + color="red" + > + Выйти + + + + + + ) +} \ 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 ? ( +
+ + {/* Информация о пользователе (только для чтения) */} + + + + Имя: + {user.full_name} + + + Telegram ID: + {user.telegram_id} + + {user.username && ( + + Username: + @{user.username} + + )} + {user.last_login && ( + + Последний вход: + + {new Date(user.last_login).toLocaleString('ru-RU')} + + + )} + + + + + + {/* Отдел */} +