Compare commits
137 Commits
fix-permis
...
main
| Author | SHA1 | Date |
|---|---|---|
|
|
db587b3955 | |
|
|
19a02d2cd0 | |
|
|
925171adda | |
|
|
aff9812b43 | |
|
|
a24f00af1a | |
|
|
b858250756 | |
|
|
ba7dddbfb6 | |
|
|
efe6bff324 | |
|
|
53769e50c8 | |
|
|
13500e8b38 | |
|
|
965af735a9 | |
|
|
a2cec7e2a3 | |
|
|
f7ca74a7b5 | |
|
|
c3290d7c1d | |
|
|
f1e21f2112 | |
|
|
ca9736af21 | |
|
|
ae43fdae60 | |
|
|
498ed51022 | |
|
|
4d24ff36b4 | |
|
|
5d5e5e2ebb | |
|
|
33cd3d79c6 | |
|
|
86a456a296 | |
|
|
5ca93bd568 | |
|
|
386c505ce1 | |
|
|
a05a78f27e | |
|
|
208d0c8753 | |
|
|
baf0929044 | |
|
|
63d93d6792 | |
|
|
ca4e725bce | |
|
|
0a4a7829b0 | |
|
|
43fe957812 | |
|
|
e4f401f318 | |
|
|
fc64f3a51f | |
|
|
f10e69f964 | |
|
|
052d42faeb | |
|
|
6b5f3f9496 | |
|
|
0b25a1d932 | |
|
|
ea02e8b019 | |
|
|
f7272b6232 | |
|
|
cf0cd45744 | |
|
|
ac2d2e3ddb | |
|
|
f01687849b | |
|
|
22be4ccd0c | |
|
|
6f77b6af48 | |
|
|
d8a66bd665 | |
|
|
97b77a3ea5 | |
|
|
906c05b519 | |
|
|
cb38218c84 | |
|
|
061438d6c2 | |
|
|
6fa1b1742e | |
|
|
0262cdef48 | |
|
|
73d274e21c | |
|
|
7638d49fb6 | |
|
|
fee216fc19 | |
|
|
4af68d31af | |
|
|
8f5055b88a | |
|
|
3e0c5def80 | |
|
|
ac16ff1d4b | |
|
|
89c9ecd7b4 | |
|
|
4e8784c706 | |
|
|
0f97b7d8e4 | |
|
|
0ea62a1112 | |
|
|
baa156e643 | |
|
|
15d2bf137f | |
|
|
5eac7d32b2 | |
|
|
95e0ad3fcd | |
|
|
ecefa9a694 | |
|
|
6258345e95 | |
|
|
3f2db09bba | |
|
|
64ca5fd015 | |
|
|
69d1c11f7d | |
|
|
aa50168138 | |
|
|
9d61e80d92 | |
|
|
a7822e0351 | |
|
|
863f38cdb5 | |
|
|
9f201fe6fd | |
|
|
19f91269f5 | |
|
|
62fe738c8d | |
|
|
acbd65aa4f | |
|
|
2531e830b8 | |
|
|
54919969f4 | |
|
|
2c35c99f12 | |
|
|
d607b7ccb7 | |
|
|
ea547fb23a | |
|
|
7ed2889b78 | |
|
|
32aa17be41 | |
|
|
503354f3f9 | |
|
|
fe585f421c | |
|
|
31470f85cf | |
|
|
31e7c6e92e | |
|
|
8bbb6bcd89 | |
|
|
e2cc94b102 | |
|
|
4475cde45e | |
|
|
a44261e1ec | |
|
|
1cdc89b8ef | |
|
|
5f5e658de5 | |
|
|
97c71b9530 | |
|
|
d3d431383b | |
|
|
836f8a8bd0 | |
|
|
32fde7825c | |
|
|
fab63bbd2e | |
|
|
1cfffb6a5b | |
|
|
95478afec7 | |
|
|
9d24a0edc4 | |
|
|
47213f17d0 | |
|
|
f06ba023db | |
|
|
805bbdbd4a | |
|
|
98481e4f8a | |
|
|
404f324f5c | |
|
|
db6348babd | |
|
|
262c6d930f | |
|
|
8a95692122 | |
|
|
2f67990cae | |
|
|
dc0d52921a | |
|
|
6e480142b7 | |
|
|
b181d9a4be | |
|
|
30789b2642 | |
|
|
2eb37cc7ac | |
|
|
13bc512e66 | |
|
|
f70475b931 | |
|
|
0e9f59cf2a | |
|
|
740669c90b | |
|
|
c1cdb95557 | |
|
|
999c23c144 | |
|
|
fa28bffaf4 | |
|
|
13d7f4de67 | |
|
|
983b003abf | |
|
|
48cd2450ea | |
|
|
021a6fca85 | |
|
|
b4fdeb0efb | |
|
|
573ab61563 | |
|
|
74bf66554b | |
|
|
64bd6bd147 | |
|
|
50b64f87be | |
|
|
eacb0c2614 | |
|
|
3c3879a10e | |
|
|
7db584c101 |
2
.env
2
.env
|
|
@ -1,5 +1,5 @@
|
|||
# API Configuration
|
||||
VITE_API_BASE_URL=http://localhost:1726/api
|
||||
VITE_API_BASE_URL=https://api.ruspet-preforma.ru/api
|
||||
VITE_API_KEY=test
|
||||
VITE_API_PUBLIC_KEY=ruspet_public_key_2026
|
||||
VITE_API_PRIVATE_KEY=ruspet_private_key_SUPER_SECRET_2026
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@ on:
|
|||
|
||||
env:
|
||||
REPO_DIR: "/workspace/ruspet_admin_frontend"
|
||||
REPO_URL: "https://72.56.235.246.nip.io/gitea/romanskijdev/admin_ruspet.git"
|
||||
# Обновлен URL и добавлена авторизация
|
||||
REPO_URL: "https://${{ github.actor }}:${{ github.token }}@git.ruspet-preforma.ru/romanskijdev/admin_ruspet.git"
|
||||
BUILD_DIR: "/var/www/admin.ruspet.tw1.ru"
|
||||
|
||||
jobs:
|
||||
|
|
@ -33,6 +34,8 @@ jobs:
|
|||
if [ -d "$REPO_DIR/.git" ]; then
|
||||
echo "📦 Updating existing repo..."
|
||||
cd "$REPO_DIR"
|
||||
# Принудительно задаем новый URL на случай, если папка уже существует со старым
|
||||
git remote set-url origin "$REPO_URL"
|
||||
git fetch origin
|
||||
git reset --hard origin/main
|
||||
else
|
||||
|
|
@ -98,7 +101,7 @@ jobs:
|
|||
|
||||
if [ "${{ job.status }}" == "success" ]; then
|
||||
echo "✅ Frontend deployment completed!"
|
||||
echo "🌐 Available at: https://admin.ruspet.tw1.ru"
|
||||
echo "🌐 Available at: https://panel.ruspet-preforma.ru"
|
||||
else
|
||||
echo "❌ Frontend deployment failed!"
|
||||
fi
|
||||
|
|
@ -2,9 +2,9 @@
|
|||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/svg+xml" href="/logo.jpg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Административная панель РусПЭТ</title>
|
||||
<title>Портал сотрудника РусПЭТ</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
|
|
|||
|
|
@ -8,14 +8,24 @@
|
|||
"name": "ruspet_admin_frontend",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@mantine/core": "^9.3.1",
|
||||
"@mantine/dates": "^9.3.1",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@mantine/core": "^9.8.1",
|
||||
"@mantine/dates": "^9.8.1",
|
||||
"@mantine/form": "^9.3.1",
|
||||
"@mantine/hooks": "^9.3.1",
|
||||
"@mantine/modals": "^9.3.1",
|
||||
"@mantine/notifications": "^9.3.1",
|
||||
"@mantine/hooks": "^9.8.1",
|
||||
"@mantine/modals": "^9.8.1",
|
||||
"@mantine/notifications": "^9.8.1",
|
||||
"@mantine/spotlight": "^9.8.1",
|
||||
"@mantine/tiptap": "^9.8.1",
|
||||
"@tabler/icons-react": "^3.44.0",
|
||||
"@tanstack/react-query": "^5.101.0",
|
||||
"@tiptap/extension-link": "^3.27.3",
|
||||
"@tiptap/extension-underline": "^3.27.3",
|
||||
"@tiptap/pm": "^3.27.3",
|
||||
"@tiptap/react": "^3.27.3",
|
||||
"@tiptap/starter-kit": "^3.27.3",
|
||||
"axios": "^1.18.0",
|
||||
"crypto-js": "^4.2.0",
|
||||
"dayjs": "^1.11.21",
|
||||
|
|
@ -292,6 +302,59 @@
|
|||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/core": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/sortable": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
|
||||
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@dnd-kit/core": "^6.3.0",
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/utilities": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
||||
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
|
||||
|
|
@ -455,32 +518,32 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@floating-ui/core": {
|
||||
"version": "1.7.5",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz",
|
||||
"integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==",
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz",
|
||||
"integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/utils": "^0.2.11"
|
||||
"@floating-ui/utils": "^0.2.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/dom": {
|
||||
"version": "1.7.6",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz",
|
||||
"integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==",
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz",
|
||||
"integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/core": "^1.7.5",
|
||||
"@floating-ui/utils": "^0.2.11"
|
||||
"@floating-ui/core": "^1.8.0",
|
||||
"@floating-ui/utils": "^0.2.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/react": {
|
||||
"version": "0.27.19",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.27.19.tgz",
|
||||
"integrity": "sha512-31B8h5mm8YxotlE7/AU/PhNAl8eWxAmjL/v2QOxroDNkTFLk3Uu82u63N3b6TXa4EGJeeZLVcd/9AlNlVqzeog==",
|
||||
"version": "0.27.20",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.27.20.tgz",
|
||||
"integrity": "sha512-CMqMy7OaXl9W0eq1Uy7L7i2Y/anPvHmFmESd2CEw0t5YvZhcVCeo4MBevAmswRllX7Y2dEidA4ozGPunLSTQpw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/react-dom": "^2.1.8",
|
||||
"@floating-ui/utils": "^0.2.11",
|
||||
"@floating-ui/react-dom": "^2.1.9",
|
||||
"@floating-ui/utils": "^0.2.12",
|
||||
"tabbable": "^6.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
|
@ -489,12 +552,12 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@floating-ui/react-dom": {
|
||||
"version": "2.1.8",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.8.tgz",
|
||||
"integrity": "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==",
|
||||
"version": "2.1.9",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz",
|
||||
"integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/dom": "^1.7.6"
|
||||
"@floating-ui/dom": "^1.8.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0",
|
||||
|
|
@ -502,9 +565,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@floating-ui/utils": {
|
||||
"version": "0.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz",
|
||||
"integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==",
|
||||
"version": "0.2.12",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz",
|
||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@humanfs/core": {
|
||||
|
|
@ -624,34 +687,34 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@mantine/core": {
|
||||
"version": "9.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/core/-/core-9.3.1.tgz",
|
||||
"integrity": "sha512-4rBoHpggSohayE+Os7lKdbsHTw7m/uZRKYjk9DN6cKBhQIjdiULdcG+b4b5CMVZSqZDHPgT70uWGI7yqkn8Ufw==",
|
||||
"version": "9.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/core/-/core-9.8.1.tgz",
|
||||
"integrity": "sha512-+ayBTxun7MslJL6x4qaylVy6TyHu3o68+PH22gt70eJSHgy0CHYR/c2q+BYxS8WvORuc4f5mr0xFbi0vzlgHug==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/react": "^0.27.19",
|
||||
"@floating-ui/react": "^0.27.20",
|
||||
"clsx": "^2.1.1",
|
||||
"react-number-format": "^5.4.5",
|
||||
"react-remove-scroll": "^2.7.2",
|
||||
"type-fest": "^5.6.0"
|
||||
"type-fest": "^5.10.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@mantine/hooks": "9.3.1",
|
||||
"@mantine/hooks": "9.8.1",
|
||||
"react": "^19.2.0",
|
||||
"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==",
|
||||
"version": "9.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/dates/-/dates-9.8.1.tgz",
|
||||
"integrity": "sha512-BDYvM3hSvTkFNAqnRmL/nhf8NnoqwXOUe+jxq7xZZ1ME9NaVT5u3QuLY2zEilqF3Wm0iUtf3LP6deL9c4gunSQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"clsx": "^2.1.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@mantine/core": "9.3.1",
|
||||
"@mantine/hooks": "9.3.1",
|
||||
"@mantine/core": "9.8.1",
|
||||
"@mantine/hooks": "9.8.1",
|
||||
"dayjs": ">=1.0.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
|
|
@ -672,51 +735,80 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@mantine/hooks": {
|
||||
"version": "9.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-9.3.1.tgz",
|
||||
"integrity": "sha512-zAOlxV59j5CDgAnExN+ypaR6dVW1vwMKDvKUxIlUVd/e52qxYnPyYRD+shJmyOLaZRuQmVF0R/7mJAjt2jw9cA==",
|
||||
"version": "9.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-9.8.1.tgz",
|
||||
"integrity": "sha512-aAbY3zcqrS/n+wbMnKBXMiF5TJ7HZ06sH455Cf4ZkWRXko9Td2FYSe9aONCzXFaW62XqaWHBICyeIsAmUds3uA==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@mantine/modals": {
|
||||
"version": "9.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/modals/-/modals-9.3.1.tgz",
|
||||
"integrity": "sha512-JqP1o6hrfQJ5UCq97HJsI7uIPDy+WwvWwkkfctWqcYkFJA2DU8dVoPqvEhnhDQUIXNci3sx6XDoQZAq1Qg57mw==",
|
||||
"version": "9.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/modals/-/modals-9.8.1.tgz",
|
||||
"integrity": "sha512-QwlPGmwyWXIq5YM3xzbeVQ6dJXTm98YBcrI7YQ6lraHxEXHZAr6M2HDIF4Pqd158mP/Oc+HL+UPd0cvSeZfHLQ==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@mantine/core": "9.3.1",
|
||||
"@mantine/hooks": "9.3.1",
|
||||
"@mantine/core": "9.8.1",
|
||||
"@mantine/hooks": "9.8.1",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@mantine/notifications": {
|
||||
"version": "9.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/notifications/-/notifications-9.3.1.tgz",
|
||||
"integrity": "sha512-irkD9uszgVftthbCLd+4lS7M1jkhL4sVrZASv8+43aIkncW+oQkCFpBuaOAf6uRcMjmQ7XnKs2O8bXYzl/DqgQ==",
|
||||
"version": "9.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/notifications/-/notifications-9.8.1.tgz",
|
||||
"integrity": "sha512-lqi9+HfXMbMKzEsAIUkWRFw2rURzgVMv8//oCyq0rhy27X6NjSMMlzvwsjbSazT/+WugDIYLJ8khZ+JMW1gkMQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@mantine/store": "9.3.1",
|
||||
"@mantine/store": "9.8.1",
|
||||
"react-transition-group": "4.4.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@mantine/core": "9.3.1",
|
||||
"@mantine/hooks": "9.3.1",
|
||||
"@mantine/core": "9.8.1",
|
||||
"@mantine/hooks": "9.8.1",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@mantine/spotlight": {
|
||||
"version": "9.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/spotlight/-/spotlight-9.8.1.tgz",
|
||||
"integrity": "sha512-x5BL6D1Khp6GxhWWxhPgtoyPb40zFgwKx8XfjyoDMRANGhQ+vijyjyDHol7nYQq8DMiM2G4Hnue2vMyTDEkS1g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@mantine/store": "9.8.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@mantine/core": "9.8.1",
|
||||
"@mantine/hooks": "9.8.1",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@mantine/store": {
|
||||
"version": "9.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/store/-/store-9.3.1.tgz",
|
||||
"integrity": "sha512-UZ8wGKfF/NFMHCDl1Rd0M8XtHdt4W1w3V4ohNpFSaP3nSjJ+Cu1FT+iIWtXwC0Ogha8XnuVQ7vm/dw2BUfpw+g==",
|
||||
"version": "9.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/store/-/store-9.8.1.tgz",
|
||||
"integrity": "sha512-Wb5+6i6m3GdNgOjX1IbDPYrP76v9y4zThRoKDWH9Es+qY2c6gT2NpH7n10/zYgNPL8ipB6H6gGUPhLurs1o4kg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@mantine/tiptap": {
|
||||
"version": "9.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@mantine/tiptap/-/tiptap-9.8.1.tgz",
|
||||
"integrity": "sha512-jpeLjEL0z6QUoTMuZnwfTem3ITuNd1zKjHqElptEuhFCUWKtV4sIobiRk6bOkPcANeAXCzy4P3Xquxlnq/+erg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@mantine/core": "9.8.1",
|
||||
"@mantine/hooks": "9.8.1",
|
||||
"@tiptap/extension-link": ">=3.3.0",
|
||||
"@tiptap/react": ">=3.3.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/wasm-runtime": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz",
|
||||
|
|
@ -1111,6 +1203,435 @@
|
|||
"react": "^18 || ^19"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/core": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.27.3.tgz",
|
||||
"integrity": "sha512-TJj5929M96C1KlH796wS8MywfHDh49RhmakOyzyMMc9pFmRj9UXi1gj0TCXgsZtjEOG7B+m/DRvNOvnuvR9kmg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/pm": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-blockquote": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-blockquote/-/extension-blockquote-3.27.3.tgz",
|
||||
"integrity": "sha512-VGoVMcqcGkkoduzEqQ70ZK5OOHBDn5iYeHJSgkvNoSHzYHl0CaKoWxoDKJjSWC5DAM4mBU+tXTlsiUp3evRMfA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-bold": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-bold/-/extension-bold-3.27.3.tgz",
|
||||
"integrity": "sha512-pchbycFppBqBmvk+OxrQLIPZLNd3rNbcm7zOa+OTjluphpAcsJ6AmHBmiRhJUYWitV6/SA+0nujcaWxBp5hNcQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-bubble-menu": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.27.3.tgz",
|
||||
"integrity": "sha512-PKSM9g8BXzO0Lxm2gOin7FAFvxO6T0QvlXTXVke/GJn/sR1tEz7w5ybsvweytUPmSliUc601pfIUOHKEhIVC2Q==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@floating-ui/dom": "^1.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3",
|
||||
"@tiptap/pm": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-bullet-list": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-bullet-list/-/extension-bullet-list-3.27.3.tgz",
|
||||
"integrity": "sha512-owQW6mcgnYgQU1z5BqmslcjZFBUm1SGM/Ax++4R6XelIt/7ol6uSTjzjAzum+ASW7UlBbuJHuSgRjl8cA+RGkg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/extension-list": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-code": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-code/-/extension-code-3.27.3.tgz",
|
||||
"integrity": "sha512-T7JF10Y3k7fyVujXXLVubdUh7fctgBUoiuxbvjotpltg1U/mPbOcT0UW/uif9j3H8TFvAwNApVw3x8bwwFUakA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-code-block": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-code-block/-/extension-code-block-3.27.3.tgz",
|
||||
"integrity": "sha512-3CVnzkpGoqqI5KaXI9l9PMwLkx34SYY63tpeo0I0QjDk4LU+JTAQDTPJFSwB4zTsHZ7ZFMU0jjasFOZ1kZRVgw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3",
|
||||
"@tiptap/pm": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-document": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-3.27.3.tgz",
|
||||
"integrity": "sha512-PR25MRv56Nm4ETVLwA8nAh/0RrVdvD4D2nxnAC8kUkxz1WOYDaqTfPqqEeSWDoUUTUp1I1xzDkD4x0gEnAlmZA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-dropcursor": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-dropcursor/-/extension-dropcursor-3.27.3.tgz",
|
||||
"integrity": "sha512-XsL0Ziual+ynXyx5JgLb0KIOShlMN3MW7+GQvf9PGRb1vOB7IOTRFDxMPrxDWcFIZ6WWMWSrbkCLOKHStt1BWg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/extensions": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-floating-menu": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-floating-menu/-/extension-floating-menu-3.27.3.tgz",
|
||||
"integrity": "sha512-qL+g1Z6MqZvYG4mHTPwub9II2fWZY+2I5VFfV8fzqy1HchBOyY6Df0mRKDNb0bmjBdFabIXnswz3iqLx3mDTbw==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@floating-ui/dom": "^1.0.0",
|
||||
"@tiptap/core": "3.27.3",
|
||||
"@tiptap/pm": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-gapcursor": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-gapcursor/-/extension-gapcursor-3.27.3.tgz",
|
||||
"integrity": "sha512-MVBqzwYrDOttkn2GOrvvKTDCymfSS2VGSKpahcKKhge5mweSDiqko2X1vBDnMF8aVW3WxIFfDMmO4VMmh8HDZA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/extensions": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-hard-break": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-hard-break/-/extension-hard-break-3.27.3.tgz",
|
||||
"integrity": "sha512-cySObJITR2CRrWII87mI2LJ12wEETTnxt2p1vvC6ZtUmKnB50fOu+ux8ZEt6KYNocIOtrEZthNFzTOx7R7UtrQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-heading": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-heading/-/extension-heading-3.27.3.tgz",
|
||||
"integrity": "sha512-QHXnsNic6iId8pnsFZ8z4PkX5L+HCHa/D7rAi3nNWtPlSIAOxo4nKrALcB5/tHmY+XL8kEXKH3nsNLNEDLCYPg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-horizontal-rule": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-horizontal-rule/-/extension-horizontal-rule-3.27.3.tgz",
|
||||
"integrity": "sha512-sNCuo0+Q001B5XTVWY+ULpWXQqtBNRmAqXxAexZl44bx3rDqHG8OzjwT4EM0LIj2+BYVbdqwaJ1vfQbZVEEbig==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3",
|
||||
"@tiptap/pm": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-italic": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-3.27.3.tgz",
|
||||
"integrity": "sha512-7VpVi2vn8kGFAc/HLrt96J/E6+LXOGKn8xLhJS863t150yLIG3EPQLA1h+G5O6eo+/w+9YokvJAAJoeDihj1Jg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-link": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-link/-/extension-link-3.27.3.tgz",
|
||||
"integrity": "sha512-iXmu1tJ/3vP60c9d+zfO3+X64vod2EyBrM1qeufecAtWA6t0bT9tYeka0Zq6qDRGsZK5zViO9F2lsY7eHXiYuA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"linkifyjs": "^4.3.3"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3",
|
||||
"@tiptap/pm": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-list": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-list/-/extension-list-3.27.3.tgz",
|
||||
"integrity": "sha512-52rcaSzYjtVGUrNkdB8k1Bw/rId2lBirrWMvmnBLsieoeFd8zo8ow5zkwV057BYSgWXfnMAV7GOpDyq2IoSD9A==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3",
|
||||
"@tiptap/pm": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-list-item": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-list-item/-/extension-list-item-3.27.3.tgz",
|
||||
"integrity": "sha512-UddhVaQ7+V9IfQVVE8AJLNzSmyaaNpZPQsoPQxFNlJyOFxD6RwSTT8L4rb/TwbUctxSFWpyd1J7exzf33Ony/g==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/extension-list": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-list-keymap": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-list-keymap/-/extension-list-keymap-3.27.3.tgz",
|
||||
"integrity": "sha512-GZPVg4QCFm41yTMPEPeTlH2odNeQwRuWHY/pt3pI5LsfipQ4kDBv6h9we928vJQUnU2Gg9Y3cL5iRbmXIWWTUA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/extension-list": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-ordered-list": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-ordered-list/-/extension-ordered-list-3.27.3.tgz",
|
||||
"integrity": "sha512-oHYoE65WfRSM5tCcXi8MtQmzPxz83E2qw0pa2yHBKwr9xCCQUu8vJHJE+EJGduWdaNImv43+6/6kVMeYYbXRKg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/extension-list": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-paragraph": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-paragraph/-/extension-paragraph-3.27.3.tgz",
|
||||
"integrity": "sha512-G5XPCN7lm0nULYPelJC2eUbKbt1q97j67e/HSWxwMYEXhceec5eNAtVfpDCRyXNO9osyBi2kXqLv/IQtxbch9A==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-strike": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-strike/-/extension-strike-3.27.3.tgz",
|
||||
"integrity": "sha512-dp6Rs3I4zLVJPvAw2Q9yrNuYKcX5LTONH3/oyULvGsrqq5DKz7pqscfwhwnDSzrgm/3aCz6B9r1BVHlYI/DXlA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-text": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-text/-/extension-text-3.27.3.tgz",
|
||||
"integrity": "sha512-wSatZ/bop0pleeC18nF90zvWWEoRe/ewZncvm8LjcMrXwq41kTEs3j7nZflMYAh7X8fZvu00UIMeEyCNJl+5Yg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-underline": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-underline/-/extension-underline-3.27.3.tgz",
|
||||
"integrity": "sha512-YH7ka/Rp7ZwlzTuQCcs0OZ4CMSx/P/MzbseQKxKebEIZreWaKMZAaED97Fnu0dA66VlreD4/1C7xHJy84ovamg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extensions": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extensions/-/extensions-3.27.3.tgz",
|
||||
"integrity": "sha512-IA2QKUVJgzUPEhhkUfr6P5u5GFVfhiApiEaaHXBz07saL2c4HNoVs2RC18QlZDCtLNKrPR1mUScr72u7uYs+YQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3",
|
||||
"@tiptap/pm": "3.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/pm": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.27.3.tgz",
|
||||
"integrity": "sha512-ppiG57RxM3HSHHgcHT0hP6Ib4P56Sd5itxdV4w0hIGHKPGyLLKiAkYp+htIHa9T7IvjMdaqxIlsfyV3ZKsS1sw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-changeset": "^2.4.1",
|
||||
"prosemirror-commands": "^1.7.1",
|
||||
"prosemirror-dropcursor": "^1.8.2",
|
||||
"prosemirror-gapcursor": "^1.4.1",
|
||||
"prosemirror-history": "^1.5.0",
|
||||
"prosemirror-inputrules": "^1.5.1",
|
||||
"prosemirror-keymap": "^1.2.3",
|
||||
"prosemirror-model": "^1.25.9",
|
||||
"prosemirror-schema-list": "^1.5.1",
|
||||
"prosemirror-state": "^1.4.4",
|
||||
"prosemirror-tables": "^1.8.5",
|
||||
"prosemirror-transform": "^1.12.0",
|
||||
"prosemirror-view": "^1.41.9"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/react": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/react/-/react-3.27.3.tgz",
|
||||
"integrity": "sha512-lanXxMScw/LevbRFuFw5MoQJ1grmHUDszwph2VIk4l2U5e/EDIw3rr4CeDME6Z4isVReD6zccMFVShkHqsv+jg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/use-sync-external-store": "^0.0.6",
|
||||
"fast-equals": "^5.3.3",
|
||||
"use-sync-external-store": "^1.4.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@tiptap/extension-bubble-menu": "^3.27.3",
|
||||
"@tiptap/extension-floating-menu": "^3.27.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.27.3",
|
||||
"@tiptap/pm": "3.27.3",
|
||||
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"@types/react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/starter-kit": {
|
||||
"version": "3.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/starter-kit/-/starter-kit-3.27.3.tgz",
|
||||
"integrity": "sha512-xX3baFqiC30skntdhxUUvyJo755ON9c1pE83+2Wiq2g+Qnffg9knUuLCZStHoZZ318yB0aBsKAMvHWLtYDo8AA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@tiptap/core": "^3.27.3",
|
||||
"@tiptap/extension-blockquote": "^3.27.3",
|
||||
"@tiptap/extension-bold": "^3.27.3",
|
||||
"@tiptap/extension-bullet-list": "^3.27.3",
|
||||
"@tiptap/extension-code": "^3.27.3",
|
||||
"@tiptap/extension-code-block": "^3.27.3",
|
||||
"@tiptap/extension-document": "^3.27.3",
|
||||
"@tiptap/extension-dropcursor": "^3.27.3",
|
||||
"@tiptap/extension-gapcursor": "^3.27.3",
|
||||
"@tiptap/extension-hard-break": "^3.27.3",
|
||||
"@tiptap/extension-heading": "^3.27.3",
|
||||
"@tiptap/extension-horizontal-rule": "^3.27.3",
|
||||
"@tiptap/extension-italic": "^3.27.3",
|
||||
"@tiptap/extension-link": "^3.27.3",
|
||||
"@tiptap/extension-list": "^3.27.3",
|
||||
"@tiptap/extension-list-item": "^3.27.3",
|
||||
"@tiptap/extension-list-keymap": "^3.27.3",
|
||||
"@tiptap/extension-ordered-list": "^3.27.3",
|
||||
"@tiptap/extension-paragraph": "^3.27.3",
|
||||
"@tiptap/extension-strike": "^3.27.3",
|
||||
"@tiptap/extension-text": "^3.27.3",
|
||||
"@tiptap/extension-underline": "^3.27.3",
|
||||
"@tiptap/extensions": "^3.27.3",
|
||||
"@tiptap/pm": "^3.27.3"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
}
|
||||
},
|
||||
"node_modules/@tybys/wasm-util": {
|
||||
"version": "0.10.2",
|
||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz",
|
||||
|
|
@ -1244,7 +1765,6 @@
|
|||
"version": "19.2.17",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
|
||||
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"csstype": "^3.2.2"
|
||||
|
|
@ -1254,7 +1774,6 @@
|
|||
"version": "19.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
|
||||
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@types/react": "^19.2.0"
|
||||
|
|
@ -2308,6 +2827,15 @@
|
|||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-equals": {
|
||||
"version": "5.4.1",
|
||||
"resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.4.1.tgz",
|
||||
"integrity": "sha512-DjlFSM5Pk9cGcL0q5QXl66eGzx0N6szNgaswwc5ZphlBohjTVJSnGgI+rJVOgOi65qUoQnDZN4nDqi33udtydQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-json-stable-stringify": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
|
||||
|
|
@ -3051,6 +3579,12 @@
|
|||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/linkifyjs": {
|
||||
"version": "4.3.3",
|
||||
"resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.3.tgz",
|
||||
"integrity": "sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/locate-path": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
|
||||
|
|
@ -3210,6 +3744,12 @@
|
|||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/orderedmap": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz",
|
||||
"integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/p-limit": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
|
||||
|
|
@ -3332,6 +3872,145 @@
|
|||
"react-is": "^16.13.1"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-changeset": {
|
||||
"version": "2.4.1",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-changeset/-/prosemirror-changeset-2.4.1.tgz",
|
||||
"integrity": "sha512-96WBLhOaYhJ+kPhLg3uW359Tz6I/MfcrQfL4EGv4SrcqKEMC1gmoGrXHecPE8eOwTVCJ4IwgfzM8fFad25wNfw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-transform": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-commands": {
|
||||
"version": "1.7.1",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.1.tgz",
|
||||
"integrity": "sha512-rT7qZnQtx5c0/y/KlYaGvtG411S97UaL6gdp6RIZ23DLHanMYLyfGBV5DtSnZdthQql7W+lEVbpSfwtO8T+L2w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-model": "^1.0.0",
|
||||
"prosemirror-state": "^1.0.0",
|
||||
"prosemirror-transform": "^1.10.2"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-dropcursor": {
|
||||
"version": "1.8.3",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.3.tgz",
|
||||
"integrity": "sha512-FoYbsJR8gK+DGlqhNoE29Loa38eIZPzQRIb1VMaDNBoo4OLP6vVof/jR8qFY/6XvUd6Dhug8MDCHl2a/h8RTfQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-state": "^1.0.0",
|
||||
"prosemirror-transform": "^1.1.0",
|
||||
"prosemirror-view": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-gapcursor": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-gapcursor/-/prosemirror-gapcursor-1.4.1.tgz",
|
||||
"integrity": "sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-keymap": "^1.0.0",
|
||||
"prosemirror-model": "^1.0.0",
|
||||
"prosemirror-state": "^1.0.0",
|
||||
"prosemirror-view": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-history": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-history/-/prosemirror-history-1.5.0.tgz",
|
||||
"integrity": "sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-state": "^1.2.2",
|
||||
"prosemirror-transform": "^1.0.0",
|
||||
"prosemirror-view": "^1.31.0",
|
||||
"rope-sequence": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-inputrules": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-inputrules/-/prosemirror-inputrules-1.5.1.tgz",
|
||||
"integrity": "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-state": "^1.0.0",
|
||||
"prosemirror-transform": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-keymap": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz",
|
||||
"integrity": "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-state": "^1.0.0",
|
||||
"w3c-keyname": "^2.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-model": {
|
||||
"version": "1.25.11",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.11.tgz",
|
||||
"integrity": "sha512-QWg9RhnpLlogAmp3p96uEFrE5txQpFynd4vhBAELkwgOCWQs/X0yCzB3/hrHqiPwf91RG5KyWq6553zs9JqIOQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"orderedmap": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-schema-list": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz",
|
||||
"integrity": "sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-model": "^1.0.0",
|
||||
"prosemirror-state": "^1.0.0",
|
||||
"prosemirror-transform": "^1.7.3"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-state": {
|
||||
"version": "1.4.4",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz",
|
||||
"integrity": "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-model": "^1.0.0",
|
||||
"prosemirror-transform": "^1.0.0",
|
||||
"prosemirror-view": "^1.27.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-tables": {
|
||||
"version": "1.8.5",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-tables/-/prosemirror-tables-1.8.5.tgz",
|
||||
"integrity": "sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-keymap": "^1.2.3",
|
||||
"prosemirror-model": "^1.25.4",
|
||||
"prosemirror-state": "^1.4.4",
|
||||
"prosemirror-transform": "^1.10.5",
|
||||
"prosemirror-view": "^1.41.4"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-transform": {
|
||||
"version": "1.12.0",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.12.0.tgz",
|
||||
"integrity": "sha512-GxboyN4AMIsoHNtz5uf2r2Ru551i5hWeCMD6E2Ib4Eogqoub0NflniaBPVQ4MrGE5yZ8JV9tUHg9qcZTTrcN4w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-model": "^1.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-view": {
|
||||
"version": "1.42.1",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.42.1.tgz",
|
||||
"integrity": "sha512-rRqzZnRgkyh69XoOMrfFJHwauHscLBmHbq772kwbic1ymQAM8gXjzEbJse5j1ep2UO2HRIAQL0bY3kZ/RoqjVw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-model": "^1.25.8",
|
||||
"prosemirror-state": "^1.0.0",
|
||||
"prosemirror-transform": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-from-env": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
|
||||
|
|
@ -3619,6 +4298,12 @@
|
|||
"@rolldown/binding-win32-x64-msvc": "1.0.3"
|
||||
}
|
||||
},
|
||||
"node_modules/rope-sequence": {
|
||||
"version": "1.3.4",
|
||||
"resolved": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz",
|
||||
"integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/scheduler": {
|
||||
"version": "0.27.0",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
|
||||
|
|
@ -3687,9 +4372,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/tabbable": {
|
||||
"version": "6.4.0",
|
||||
"resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.4.0.tgz",
|
||||
"integrity": "sha512-05PUHKSNE8ou2dwIxTngl4EzcnsCDZGJ/iCLtDflR/SHB/ny14rXc+qU5P4mG9JkusiV7EivzY9Mhm55AzAvCg==",
|
||||
"version": "6.5.2",
|
||||
"resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.5.2.tgz",
|
||||
"integrity": "sha512-XgdnB1nGU6KU4VgMnZPaZCx7M1hBrLyEiZYau2G2gq9UT0d7d4FUBlNX7vvPlm/B1vk1PjrzJBx9Lbv4fsqS9g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tagged-tag": {
|
||||
|
|
@ -3760,9 +4445,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/type-fest": {
|
||||
"version": "5.7.0",
|
||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.7.0.tgz",
|
||||
"integrity": "sha512-1URUxUqfHFM1c+zfSPsa3gnkO7Aq21qyH75SIduNYz4SzY964rn1X2vCMQaHSHhktiw+0kPa2iyb6PUpXqB6Vg==",
|
||||
"version": "5.10.0",
|
||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.10.0.tgz",
|
||||
"integrity": "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA==",
|
||||
"license": "(MIT OR CC0-1.0)",
|
||||
"dependencies": {
|
||||
"tagged-tag": "^1.0.0"
|
||||
|
|
@ -4012,6 +4697,12 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"node_modules/w3c-keyname": {
|
||||
"version": "2.2.8",
|
||||
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
|
||||
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||
|
|
|
|||
20
package.json
20
package.json
|
|
@ -10,14 +10,24 @@
|
|||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mantine/core": "^9.3.1",
|
||||
"@mantine/dates": "^9.3.1",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@mantine/core": "^9.8.1",
|
||||
"@mantine/dates": "^9.8.1",
|
||||
"@mantine/form": "^9.3.1",
|
||||
"@mantine/hooks": "^9.3.1",
|
||||
"@mantine/modals": "^9.3.1",
|
||||
"@mantine/notifications": "^9.3.1",
|
||||
"@mantine/hooks": "^9.8.1",
|
||||
"@mantine/modals": "^9.8.1",
|
||||
"@mantine/notifications": "^9.8.1",
|
||||
"@mantine/spotlight": "^9.8.1",
|
||||
"@mantine/tiptap": "^9.8.1",
|
||||
"@tabler/icons-react": "^3.44.0",
|
||||
"@tanstack/react-query": "^5.101.0",
|
||||
"@tiptap/extension-link": "^3.27.3",
|
||||
"@tiptap/extension-underline": "^3.27.3",
|
||||
"@tiptap/pm": "^3.27.3",
|
||||
"@tiptap/react": "^3.27.3",
|
||||
"@tiptap/starter-kit": "^3.27.3",
|
||||
"axios": "^1.18.0",
|
||||
"crypto-js": "^4.2.0",
|
||||
"dayjs": "^1.11.21",
|
||||
|
|
|
|||
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
|
|
@ -0,0 +1,239 @@
|
|||
├── .DS_Store
|
||||
├── .env
|
||||
├── .env.example
|
||||
├── .gitea
|
||||
│ ├── workflows
|
||||
│ │ ├── deploy-frontend.yml
|
||||
├── .gitignore
|
||||
├── README.md
|
||||
├── eslint.config.js
|
||||
├── index.html
|
||||
├── package-lock.json
|
||||
├── package.json
|
||||
├── public
|
||||
│ ├── favicon.svg
|
||||
│ ├── icons.svg
|
||||
├── src
|
||||
│ ├── App.css
|
||||
│ ├── App.tsx
|
||||
│ ├── api
|
||||
│ │ ├── adminLogs.ts
|
||||
│ │ ├── admins.ts
|
||||
│ │ ├── approvalTasks.ts
|
||||
│ │ ├── approvals.ts
|
||||
│ │ ├── auth.ts
|
||||
│ │ ├── categories.ts
|
||||
│ │ ├── client.ts
|
||||
│ │ ├── dashboard.ts
|
||||
│ │ ├── departments.ts
|
||||
│ │ ├── flowNodes.ts
|
||||
│ │ ├── hierarchies.ts
|
||||
│ │ ├── monthlyOrders.ts
|
||||
│ │ ├── notifications.ts
|
||||
│ │ ├── permissions.ts
|
||||
│ │ ├── roles.ts
|
||||
│ │ ├── telegramManagers.ts
|
||||
│ │ ├── time.ts
|
||||
│ │ ├── topicExecutors.ts
|
||||
│ │ ├── topics.ts
|
||||
│ │ ├── userRoles.ts
|
||||
│ │ ├── users.ts
|
||||
│ │ ├── whatsappManagers.ts
|
||||
│ ├── assets
|
||||
│ │ ├── hero.png
|
||||
│ │ ├── react.svg
|
||||
│ │ ├── vite.svg
|
||||
│ ├── components
|
||||
│ │ ├── CopyRolesModal.tsx
|
||||
│ │ ├── DiagnosticErrorBoundary.tsx
|
||||
│ │ ├── Layout
|
||||
│ │ │ ├── Header.tsx
|
||||
│ │ │ ├── MainLayout.tsx
|
||||
│ │ │ ├── Sidebar.tsx
|
||||
│ │ ├── TopicGapsModal.tsx
|
||||
│ │ ├── UserEditModal.tsx
|
||||
│ ├── features
|
||||
│ │ ├── adminLogs
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useAdminLogs.ts
|
||||
│ │ ├── admins
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useAdmins.ts
|
||||
│ │ ├── approvalTasks
|
||||
│ │ │ ├── const.ts
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useApprovalTasks.ts
|
||||
│ │ ├── approvals
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useApprovals.ts
|
||||
│ │ ├── categories
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useCategories.ts
|
||||
│ │ ├── departments
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── DepartmentEditModal.tsx
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useDepartments.ts
|
||||
│ │ ├── flowNodes
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useFlowNodes.ts
|
||||
│ │ │ ├── utils
|
||||
│ │ │ │ ├── flattenTree.ts
|
||||
│ │ │ │ ├── treeWalk.ts
|
||||
│ │ ├── hierarchies
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useHierarchies.ts
|
||||
│ │ │ │ ├── useSystemOptions.ts
|
||||
│ │ │ ├── utils.ts
|
||||
│ │ ├── monthlyOrders
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useMonthlyOrderSettings.ts
|
||||
│ │ ├── notifications
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useNotifications.ts
|
||||
│ │ │ ├── utils
|
||||
│ │ │ │ ├── telegramHtml.ts
|
||||
│ │ ├── permissions
|
||||
│ │ │ ├── constants.ts
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── usePermissions.ts
|
||||
│ │ ├── roles
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useAllRoles.ts
|
||||
│ │ │ │ ├── useRoles.ts
|
||||
│ │ ├── telegramManagers
|
||||
│ │ │ ├── useTelegramManagers.ts
|
||||
│ │ ├── topicExecutors
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useTopicExecutors.ts
|
||||
│ │ │ ├── utils.ts
|
||||
│ │ ├── topics
|
||||
│ │ │ ├── constants.ts
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useTopics.ts
|
||||
│ │ ├── users
|
||||
│ │ │ ├── hooks
|
||||
│ │ │ │ ├── useDepartments.ts
|
||||
│ │ │ │ ├── useRoles.ts
|
||||
│ │ │ │ ├── useUserRoles.ts
|
||||
│ │ │ │ ├── useUsers.ts
|
||||
│ │ ├── whatsappManagers
|
||||
│ │ │ ├── useWhatsappManagers.ts
|
||||
│ ├── hooks
|
||||
│ │ ├── useAuth.ts
|
||||
│ ├── index.css
|
||||
│ ├── main.tsx
|
||||
│ ├── pages
|
||||
│ │ ├── Dashboard.tsx
|
||||
│ │ ├── DepartmentsPage.tsx
|
||||
│ │ ├── Login.tsx
|
||||
│ │ ├── adminLogs
|
||||
│ │ │ ├── AdminLogsPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── AdminLogDetailModal.tsx
|
||||
│ │ ├── admins
|
||||
│ │ │ ├── AdminsPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── CreateAdminModal.tsx
|
||||
│ │ │ │ ├── EditAdminModal.tsx
|
||||
│ │ ├── approvalTasks
|
||||
│ │ │ ├── ApprovalTasksPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── ApprovalTaskDetailsModal.tsx
|
||||
│ │ ├── approvals
|
||||
│ │ │ ├── ApprovalsPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── ApprovalDetailsModal.tsx
|
||||
│ │ │ │ ├── FilePreviewModal.tsx
|
||||
│ │ ├── categories
|
||||
│ │ │ ├── CategoriesPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── CategoryDrawer.tsx
|
||||
│ │ ├── flowNodes
|
||||
│ │ │ ├── FlowTreeGuidePage.tsx
|
||||
│ │ │ ├── FlowTreePage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── CategoryCreateModal.tsx
|
||||
│ │ │ │ ├── DataFlowExplainer.tsx
|
||||
│ │ │ │ ├── FlowNodeEditModal.tsx
|
||||
│ │ │ │ ├── SortableFlowTree.tsx
|
||||
│ │ │ │ ├── TreeHealthPanel.tsx
|
||||
│ │ ├── hierarchies
|
||||
│ │ │ ├── HierarchiesPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── ChainDuplicateDrawer.tsx
|
||||
│ │ │ │ ├── ChainCard.tsx
|
||||
│ │ │ │ ├── HierarchyEditDrawer.tsx
|
||||
│ │ │ │ ├── PersonDuplicateDrawer.tsx
|
||||
│ │ ├── monthlyOrders
|
||||
│ │ │ ├── MonthlyOrdersSettingsPage.tsx
|
||||
│ │ ├── notifications
|
||||
│ │ │ ├── NotificationsPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── NotificationDetailsDrawer.tsx
|
||||
│ │ │ │ ├── NotificationsHistoryTable.tsx
|
||||
│ │ │ │ ├── SendNotificationForm.tsx
|
||||
│ │ ├── permissions
|
||||
│ │ │ ├── PermissionsPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── PermissionEditModal.tsx
|
||||
│ │ ├── roles
|
||||
│ │ │ ├── RolesPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── RoleDrawer.tsx
|
||||
│ │ ├── settings
|
||||
│ │ │ ├── SettingsPage.tsx
|
||||
│ │ ├── telegramManagers
|
||||
│ │ │ ├── TelephonyPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── AddManagerModal.tsx
|
||||
│ │ │ │ ├── DeleteManagersModal.tsx
|
||||
│ │ ├── topicExecutors
|
||||
│ │ │ ├── TopicExecutorsPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── TopicExecutorEditModal.tsx
|
||||
│ │ │ │ ├── TopicExecutorsCard.tsx
|
||||
│ │ ├── topics
|
||||
│ │ │ ├── TopicsPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── TopicEditModal.tsx
|
||||
│ │ ├── users
|
||||
│ │ │ ├── UsersPage.tsx
|
||||
│ ├── theme.ts
|
||||
│ ├── types
|
||||
│ │ ├── api.ts
|
||||
│ ├── utils
|
||||
│ │ ├── date.ts
|
||||
│ ├── vite-env.d.ts
|
||||
├── tsconfig.app.json
|
||||
├── tsconfig.json
|
||||
├── tsconfig.node.json
|
||||
├── vite.config.ts
|
||||
File: eslint.config.js
|
||||
Lines: 22
|
||||
-----BEGIN eslint.config.js-----
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
-----END eslint.config.js-----
|
||||
|
||||
27
src/App.tsx
27
src/App.tsx
|
|
@ -7,18 +7,23 @@ 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 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 TopicExecutorsPage from "@/pages/topicExecutors/TopicExecutorsPage.tsx"
|
||||
import CategoriesPage from "@/pages/categories/CategoriesPage.tsx"
|
||||
import React from "react"
|
||||
import TopicsPage from "@/pages/topics/TopicsPage.tsx"
|
||||
import SettingsPage from './pages/settings/SettingsPage'
|
||||
import AdminsPage from './pages/admins/AdminsPage'
|
||||
import ApprovalTasksPage from './pages/approvalTasks/ApprovalTasksPage'
|
||||
import FlowTreePage from "@/pages/flowNodes/FlowTreePage.tsx";
|
||||
import FlowTreePage from "@/pages/flowNodes/FlowTreePage.tsx"
|
||||
import FlowTreeGuidePage from './pages/flowNodes/FlowTreeGuidePage'
|
||||
import NotificationsPage from "@/pages/notifications/NotificationsPage.tsx"
|
||||
import AdminLogsPage from './pages/adminLogs/AdminLogsPage'
|
||||
import MonthlyOrdersSettingsPage from "@/pages/monthlyOrders/MonthlyOrdersSettingsPage.tsx";
|
||||
import TelephonyPage from "@/pages/telephony/TelephonyPage.tsx";
|
||||
import ComingSoonPage from "@/components/Layout/ComingSoonPage.tsx";
|
||||
|
||||
const Placeholder = ({ title }: { title: string }) => (
|
||||
<div style={{ padding: 40 }}>
|
||||
|
|
@ -51,11 +56,15 @@ function App() {
|
|||
<Route path="/login" element={<Login />} />
|
||||
|
||||
<Route element={<ProtectedRoute><MainLayout /></ProtectedRoute>}>
|
||||
<Route path="/" element={<Placeholder title="Главная" /> } />
|
||||
<Route path="/notifications" element={<Placeholder title="Уведомления" /> } />
|
||||
<Route path="/" element={<ComingSoonPage title="Главная" description="Общий обзор системы" />} />
|
||||
<Route path="inbox" element={<ComingSoonPage title="Входящие" description="Заявки и задачи, которые ждут вашего действия: согласовать, выполнить, принять." />} />
|
||||
<Route path="my/approvals" element={<ComingSoonPage title="Мои заявки" description="Заявки, созданные вами, и создание новых." />} />
|
||||
<Route path="my/tasks" element={<ComingSoonPage title="Мои задачи" description="Задачи, назначенные вам." />} />
|
||||
<Route path="/notifications" element={<NotificationsPage />} />
|
||||
<Route path="/approval-dash" element={<Dashboard />} />
|
||||
<Route path="/nodes" element={<FlowTreePage />} />
|
||||
<Route path="/users" element={<UsersPage />} />
|
||||
<Route path="/monthly-orders-settings" element={<MonthlyOrdersSettingsPage />} />
|
||||
<Route path="/departments" element={<DepartmentsPage />} />
|
||||
<Route path="/roles" element={<RolesPage />} />
|
||||
<Route path="/approvals" element={<ApprovalsPage />} />
|
||||
|
|
@ -66,8 +75,10 @@ function App() {
|
|||
<Route path="/hierarchies" element={<HierarchiesPage />} />
|
||||
<Route path="/settings" element={<SettingsPage />} />
|
||||
<Route path="/admins" element={<AdminsPage />} />
|
||||
<Route path="/logs" element={<AdminLogsPage />} />
|
||||
<Route path="/approval-tasks" element={<ApprovalTasksPage />} />
|
||||
<Route path="/guide/flow-trees" element={<FlowTreeGuidePage />} />
|
||||
<Route path="/telegram-managers" element={<TelephonyPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,35 @@
|
|||
import apiClient from './client'
|
||||
import type { ApiResponse } from '@/types/api'
|
||||
|
||||
export interface AdminActionLog {
|
||||
id: number
|
||||
admin_id: number
|
||||
admin_login: string
|
||||
action: 'create' | 'update' | 'delete'
|
||||
entity_type: string
|
||||
entity_id?: number
|
||||
description: string
|
||||
metadata?: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface AdminLogsListParams {
|
||||
offset?: number
|
||||
limit?: number
|
||||
admin_id?: number
|
||||
admin_login?: string
|
||||
action?: string
|
||||
entity_type?: string
|
||||
entity_id?: number
|
||||
date_from?: string
|
||||
date_to?: string
|
||||
search?: string
|
||||
}
|
||||
|
||||
export const adminLogsApi = {
|
||||
getList: (params: AdminLogsListParams = {}) =>
|
||||
apiClient.get<ApiResponse<AdminActionLog[]>>('/admin-logs', { params }),
|
||||
|
||||
delete: (id: number) =>
|
||||
apiClient.delete<boolean>(`/admin-logs/${id}`),
|
||||
}
|
||||
|
|
@ -12,6 +12,9 @@ export interface CreateAdminRequest {
|
|||
login: string
|
||||
name?: string
|
||||
is_root?: boolean
|
||||
is_observer?: boolean // 🆕
|
||||
is_analyst?: boolean
|
||||
telegram_id?: number // 🆕
|
||||
}
|
||||
|
||||
export interface UpdateAdminRequest {
|
||||
|
|
@ -19,6 +22,9 @@ export interface UpdateAdminRequest {
|
|||
name?: string
|
||||
is_blocked?: boolean
|
||||
is_root?: boolean
|
||||
is_observer?: boolean // 🆕
|
||||
is_analyst?: boolean
|
||||
telegram_id?: number | null // 🆕
|
||||
}
|
||||
|
||||
export const adminsApi = {
|
||||
|
|
|
|||
|
|
@ -1,13 +1,39 @@
|
|||
import apiClient from './client'
|
||||
import type { Approval, ApiResponse } from '@/types/api'
|
||||
|
||||
export interface PlannedTask {
|
||||
id: number
|
||||
task_text: string
|
||||
executor_name?: string
|
||||
step_order: number
|
||||
}
|
||||
|
||||
export interface ApprovalTaskItem {
|
||||
id: number
|
||||
task_text: string
|
||||
executor_name: string
|
||||
status: 'pending' | 'waiting' | 'completed' | 'cancelled' | 'cancellation'
|
||||
completed_at?: string
|
||||
}
|
||||
|
||||
export interface ApprovalTasksResponse {
|
||||
topic_executors: PlannedTask[]
|
||||
tasks: ApprovalTaskItem[]
|
||||
has_task_error: boolean
|
||||
}
|
||||
|
||||
export interface ApprovalsListParams {
|
||||
offset?: number
|
||||
limit?: number
|
||||
id?: number
|
||||
status?: string
|
||||
initiator_id?: number
|
||||
topic_id?: number
|
||||
topic_id?: number // одиночный (для обратной совместимости)
|
||||
topic_ids?: number[] // 🆕 множественный выбор тем
|
||||
category_ids?: number[] // 🆕 множественный выбор категорий
|
||||
department_id?: number
|
||||
date_from?: string // 🆕 YYYY-MM-DD
|
||||
date_to?: string // 🆕 YYYY-MM-DD
|
||||
content?: string
|
||||
}
|
||||
|
||||
|
|
@ -25,8 +51,31 @@ export interface UpdateApprovalRequest {
|
|||
}
|
||||
|
||||
export const approvalsApi = {
|
||||
getList: (params: ApprovalsListParams = {}) =>
|
||||
apiClient.get<ApiResponse<Approval[]>>('/approvals', { params }),
|
||||
getList: (params: ApprovalsListParams = {}) => {
|
||||
// Формируем query-параметры, корректно сериализуя массивы
|
||||
const query: Record<string, any> = {}
|
||||
|
||||
if (params.offset !== undefined) query.offset = params.offset
|
||||
if (params.limit !== undefined) query.limit = params.limit
|
||||
if (params.status) query.status = params.status
|
||||
if (params.initiator_id) query.initiator_id = params.initiator_id
|
||||
if (params.topic_id) query.topic_id = params.topic_id
|
||||
if (params.id) query.id = params.id
|
||||
if (params.department_id) query.department_id = params.department_id
|
||||
if (params.content) query.content = params.content
|
||||
if (params.date_from) query.date_from = params.date_from
|
||||
if (params.date_to) query.date_to = params.date_to
|
||||
|
||||
// 🆕 Массивы передаём через запятую: "1,2,3"
|
||||
if (params.topic_ids && params.topic_ids.length > 0) {
|
||||
query.topic_ids = params.topic_ids.join(',')
|
||||
}
|
||||
if (params.category_ids && params.category_ids.length > 0) {
|
||||
query.category_ids = params.category_ids.join(',')
|
||||
}
|
||||
|
||||
return apiClient.get<ApiResponse<Approval[]>>('/approvals', { params: query })
|
||||
},
|
||||
|
||||
getById: (id: number) =>
|
||||
apiClient.get<Approval>(`/approvals/${id}`),
|
||||
|
|
@ -37,7 +86,9 @@ export const approvalsApi = {
|
|||
delete: (id: number) =>
|
||||
apiClient.delete<boolean>('/approvals', { data: { id } }),
|
||||
|
||||
// 🆕 Получение заявок для отчёта (с фильтрами по датам)
|
||||
getTasks: (approvalId: number) =>
|
||||
apiClient.get<ApiResponse<ApprovalTasksResponse>>(`/approvals/${approvalId}/tasks`),
|
||||
|
||||
getForReport: (params: ApprovalsReportParams = {}) =>
|
||||
apiClient.get<ApiResponse<Approval[]>>('/approvals/report', { params }),
|
||||
|
||||
|
|
@ -46,30 +97,41 @@ export const approvalsApi = {
|
|||
params,
|
||||
responseType: 'blob',
|
||||
}),
|
||||
|
||||
getAdditionalApprovers: (approvalId: number) =>
|
||||
apiClient.get<ApiResponse<AdditionalApprover[]>>(`/approvals/${approvalId}/additional-approvers`),
|
||||
|
||||
getComments: (approvalId: number) =>
|
||||
apiClient.get<ApiResponse<ApprovalComment[]>>(`/approvals/${approvalId}/comments`),
|
||||
|
||||
getObservers: (approvalId: number) =>
|
||||
apiClient.get<ApiResponse<ApprovalObserver[]>>(`/approvals/${approvalId}/observers`),
|
||||
|
||||
getRevocationRequest: (approvalId: number) =>
|
||||
apiClient.get<ApiResponse<RevocationRequest | null>>(`/approvals/${approvalId}/revocation-request`),
|
||||
|
||||
|
||||
getFile: (approvalId: number, fileId: number) =>
|
||||
apiClient.get(`/approvals/${approvalId}/files/${fileId}`, {
|
||||
responseType: 'blob',
|
||||
}),
|
||||
|
||||
downloadFile: (approvalId: number, fileId: number, fileName: string) => {
|
||||
const token = localStorage.getItem('token')
|
||||
const 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: {
|
||||
|
|
@ -94,3 +156,44 @@ export const approvalsApi = {
|
|||
})
|
||||
},
|
||||
}
|
||||
|
||||
// ДОБАВИТЬ в src/api/approvals.ts (по образцу остальных методов approvalsApi
|
||||
// в этом файле — замените apiClient.get на ваш реальный вызов, если он
|
||||
// называется иначе):
|
||||
|
||||
export interface AdditionalApprover {
|
||||
id: number
|
||||
approver_id: number
|
||||
approver_name: string
|
||||
status: 'pending' | 'approved' | 'rejected'
|
||||
comment?: string
|
||||
acted_at?: string
|
||||
}
|
||||
|
||||
export interface ApprovalComment {
|
||||
id: number
|
||||
user_id: number
|
||||
user_name: string
|
||||
comment: string
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export interface ApprovalObserver {
|
||||
id: number
|
||||
full_name: string
|
||||
}
|
||||
|
||||
export interface RevocationApprover {
|
||||
approver_id: number
|
||||
approver_name: string
|
||||
status: 'pending' | 'approved' | 'rejected'
|
||||
}
|
||||
|
||||
export interface RevocationRequest {
|
||||
id: number
|
||||
status: 'pending' | 'approved' | 'rejected'
|
||||
reason?: string
|
||||
requested_by_id: number
|
||||
requested_by_name: string
|
||||
approvers: RevocationApprover[]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
import axios from 'axios'
|
||||
import CryptoJS from 'crypto-js'
|
||||
import { timeApi } from './time'
|
||||
|
||||
// 🔄 Offset между клиентом и сервером (в секундах)
|
||||
let serverTimeOffset = 0
|
||||
let isSyncing = false
|
||||
let syncPromise: Promise<void> | null = null
|
||||
|
||||
// Функция генерации HMAC подписи
|
||||
function generateHmacSignature(publicKey: string, timestamp: string, privateKey: string): string {
|
||||
|
|
@ -12,36 +18,60 @@ function generateHmacSignature(publicKey: string, timestamp: string, privateKey:
|
|||
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
|
||||
}
|
||||
|
||||
// 🆕 Синхронизация времени с сервером
|
||||
async function syncTimeWithServer(): Promise<void> {
|
||||
if (isSyncing && syncPromise) {
|
||||
return syncPromise
|
||||
}
|
||||
|
||||
isSyncing = true
|
||||
syncPromise = (async () => {
|
||||
try {
|
||||
const serverTime = await timeApi.getServerTime()
|
||||
const clientTimestamp = Math.floor(Date.now() / 1000)
|
||||
serverTimeOffset = serverTime.timestamp - clientTimestamp
|
||||
|
||||
console.log('[Time] ✅ Synced with server', {
|
||||
serverTime: serverTime.iso,
|
||||
serverTimestamp: serverTime.timestamp,
|
||||
clientTimestamp,
|
||||
offset: serverTimeOffset,
|
||||
})
|
||||
} catch (error) {
|
||||
console.warn('[Time] ⚠️ Failed to sync with server:', error)
|
||||
// При ошибке сбрасываем offset
|
||||
serverTimeOffset = 0
|
||||
} finally {
|
||||
isSyncing = false
|
||||
syncPromise = null
|
||||
}
|
||||
})()
|
||||
|
||||
return syncPromise
|
||||
}
|
||||
|
||||
// 🆕 Получение timestamp с учётом offset
|
||||
function getCorrectedTimestamp(): string {
|
||||
return Math.floor(Date.now() / 1000 + serverTimeOffset).toString()
|
||||
}
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: '/api',
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
// Interceptor для добавления токена и HMAC подписи
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
apiClient.interceptors.request.use(async (config) => {
|
||||
console.log('[API] === Request interceptor started ===')
|
||||
|
||||
// Добавляем JWT токен, если есть
|
||||
|
|
@ -51,10 +81,10 @@ apiClient.interceptors.request.use((config) => {
|
|||
console.log('[API] ✅ Added JWT token')
|
||||
}
|
||||
|
||||
// Генерируем HMAC подпись
|
||||
// Генерируем HMAC подпись с скорректированным timestamp
|
||||
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()
|
||||
const timestamp = getCorrectedTimestamp()
|
||||
|
||||
if (!publicKey || !privateKey) {
|
||||
console.error('[API] ❌ Missing API keys in .env!')
|
||||
|
|
@ -66,11 +96,12 @@ apiClient.interceptors.request.use((config) => {
|
|||
|
||||
config.headers['X-Timestamp'] = timestamp
|
||||
|
||||
// 🆕 Получаем или создаём device_id
|
||||
// Получаем или создаём device_id
|
||||
const deviceId = getOrCreateDeviceId()
|
||||
config.headers['x-device-id'] = deviceId
|
||||
|
||||
console.log('[API] ✅ Added device_id:', deviceId)
|
||||
console.log('[API] 🕐 Using timestamp:', timestamp, 'offset:', serverTimeOffset)
|
||||
console.log('[API] === Request interceptor finished ===')
|
||||
|
||||
return config
|
||||
|
|
@ -82,7 +113,7 @@ apiClient.interceptors.response.use(
|
|||
console.log('[API] ✅ Response success:', response.config.url)
|
||||
return response
|
||||
},
|
||||
(error) => {
|
||||
async (error) => {
|
||||
console.error('[API] ❌ Response error:', {
|
||||
status: error.response?.status,
|
||||
statusText: error.response?.statusText,
|
||||
|
|
@ -90,14 +121,47 @@ apiClient.interceptors.response.use(
|
|||
url: error.config?.url,
|
||||
})
|
||||
|
||||
// 🆕 При ошибке "Timestamp expired" — синхронизируем время и повторяем запрос
|
||||
if (
|
||||
error.response?.status === 401 &&
|
||||
error.response?.data === 'Timestamp expired\n' &&
|
||||
!error.config._retry
|
||||
) {
|
||||
console.warn('[API] ⚠️ Timestamp expired, syncing with server...')
|
||||
error.config._retry = true
|
||||
|
||||
await syncTimeWithServer()
|
||||
|
||||
// Пересоздаём подпись с новым timestamp
|
||||
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
||||
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
|
||||
const newTimestamp = getCorrectedTimestamp()
|
||||
|
||||
error.config.headers['X-Timestamp'] = newTimestamp
|
||||
error.config.headers['ApiKey'] = generateHmacSignature(
|
||||
publicKey,
|
||||
newTimestamp,
|
||||
privateKey
|
||||
)
|
||||
|
||||
return apiClient(error.config)
|
||||
}
|
||||
|
||||
if (error.response?.status === 401) {
|
||||
console.warn('[API] ⚠️ Unauthorized, redirecting to login')
|
||||
localStorage.removeItem('token')
|
||||
// НЕ удаляем device_id!
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// 🆕 Синхронизируем время при загрузке модуля
|
||||
syncTimeWithServer()
|
||||
|
||||
// 🆕 Периодическая синхронизация каждые 5 минут
|
||||
setInterval(() => {
|
||||
syncTimeWithServer()
|
||||
}, 5 * 60 * 1000)
|
||||
|
||||
export default apiClient
|
||||
|
|
@ -10,21 +10,45 @@ export interface DashboardStats {
|
|||
executors: number
|
||||
statusData: Array<{ status: string; count: number }>
|
||||
dailyData: Array<{ date: string; created: number; approved: number }>
|
||||
topTopics: Array<{
|
||||
categoryBreakdown: Array<{
|
||||
id: number
|
||||
name: string
|
||||
category_name: string
|
||||
total_count: number
|
||||
pending_count: number
|
||||
}>
|
||||
topApprovers: Array<{
|
||||
bottleneckApprovers: Array<{
|
||||
user_id: number
|
||||
full_name: string
|
||||
department_name: string
|
||||
total_steps: number
|
||||
pending_steps: number
|
||||
pending_total: number
|
||||
overdue_count: number
|
||||
}>
|
||||
oldPendingCount: number
|
||||
// 🆕 Сколько дней считается "просрочкой" — приходит с бэкенда, чтобы
|
||||
// не дублировать магическое число 7 ещё и на фронте.
|
||||
oldPendingDays: number
|
||||
// 🆕 Задачи: тот же формат, что statusData/dailyData у заявок
|
||||
taskStatusData: Array<{ status: string; count: number }>
|
||||
taskDailyData: Array<{ date: string; created: number; completed: number }>
|
||||
// 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный)
|
||||
absentToday: Array<{ name: string; description: string }>
|
||||
// 🆕 Точечные пробелы: право создавать заявку по теме есть, но
|
||||
// порядок согласования для этого пользователя по ней не настроен.
|
||||
topicGaps: Array<{
|
||||
user_id: number
|
||||
full_name: string
|
||||
department_name: string
|
||||
topic_id: number
|
||||
topic_name: string
|
||||
category_name: string
|
||||
}>
|
||||
// 🆕 Более базовый случай: у пользователя вообще нет ни одной
|
||||
// строки иерархии для его отдела (даже глобального правила).
|
||||
usersWithoutHierarchy: Array<{
|
||||
user_id: number
|
||||
full_name: string
|
||||
department_name: string
|
||||
}>
|
||||
}
|
||||
|
||||
export const dashboardApi = {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import apiClient from './client'
|
|||
import type { ApprovalFlowNode, ApiResponse } from '@/types/api'
|
||||
|
||||
export interface CreateFlowNodeRequest {
|
||||
topic_id: number
|
||||
category_id: number
|
||||
parent_id?: number | null
|
||||
key: string
|
||||
label: string
|
||||
|
|
@ -15,12 +15,14 @@ export interface CreateFlowNodeRequest {
|
|||
multi_select_key?: string | null
|
||||
multi_select_value?: string | null
|
||||
topic_code?: string | null
|
||||
message_template?: string | null
|
||||
code_template?: string | null
|
||||
sort_order?: number
|
||||
}
|
||||
|
||||
export interface UpdateFlowNodeRequest {
|
||||
id: number
|
||||
topic_id?: number
|
||||
category_id?: number
|
||||
parent_id?: number | null
|
||||
key?: string
|
||||
label?: string
|
||||
|
|
@ -33,6 +35,8 @@ export interface UpdateFlowNodeRequest {
|
|||
multi_select_key?: string | null
|
||||
multi_select_value?: string | null
|
||||
topic_code?: string | null
|
||||
message_template?: string | null
|
||||
code_template?: string | null
|
||||
sort_order?: number
|
||||
}
|
||||
|
||||
|
|
@ -45,9 +49,26 @@ export interface SaveTreeRequest {
|
|||
nodes: ApprovalFlowNode[]
|
||||
}
|
||||
|
||||
// Живой предпросмотр: код темы + текст сообщения согласующему для
|
||||
// конкретного набора ответов (collected: data_key -> data_value),
|
||||
// посчитанные тем же движком, что использует боевой бот.
|
||||
export interface PreviewFlowRequest {
|
||||
collected: Record<string, string>
|
||||
initiator_name?: string
|
||||
}
|
||||
|
||||
export interface PreviewFlowResponse {
|
||||
code: string
|
||||
message: string
|
||||
incomplete: boolean
|
||||
topic_exists: boolean
|
||||
topic_id?: number
|
||||
topic_name?: string
|
||||
}
|
||||
|
||||
export const flowNodesApi = {
|
||||
getTree: (topicId: number) =>
|
||||
apiClient.get<ApiResponse<ApprovalFlowNode[]>>(`/flow-nodes/topic/${topicId}`),
|
||||
getTree: (categoryId: number) =>
|
||||
apiClient.get<ApiResponse<ApprovalFlowNode[]>>(`/flow-nodes/category/${categoryId}?limit=1000`),
|
||||
|
||||
getById: (id: number) =>
|
||||
apiClient.get<ApprovalFlowNode>(`/flow-nodes/${id}`),
|
||||
|
|
@ -61,12 +82,19 @@ export const flowNodesApi = {
|
|||
delete: (id: number) =>
|
||||
apiClient.delete<boolean>('/flow-nodes/', { data: { id } }),
|
||||
|
||||
saveTree: (topicId: number, data: SaveTreeRequest) =>
|
||||
apiClient.post<boolean>(`/flow-nodes/topic/${topicId}/tree`, data),
|
||||
saveTree: (categoryId: number, data: SaveTreeRequest) =>
|
||||
apiClient.post<boolean>(`/flow-nodes/category/${categoryId}/tree`, data),
|
||||
|
||||
move: (id: number, data: MoveFlowNodeRequest) =>
|
||||
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/move`, data),
|
||||
|
||||
duplicate: (id: number) =>
|
||||
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/duplicate`, {}),
|
||||
|
||||
// НОВОЕ
|
||||
preview: (categoryId: number, data: PreviewFlowRequest) =>
|
||||
apiClient.post<PreviewFlowResponse>(`/flow-nodes/category/${categoryId}/preview`, data),
|
||||
|
||||
// НОВОЕ: форсировать обновление Registry в процессе бота (без перезапуска)
|
||||
reloadBot: () => apiClient.post<boolean>('/flow-nodes/reload-bot', {}),
|
||||
}
|
||||
|
|
@ -9,8 +9,9 @@ export interface HierarchiesListParams {
|
|||
department_id?: number
|
||||
topic_category_id?: number
|
||||
topic_id?: number
|
||||
target_system?: string | null
|
||||
user_status?: 'active' | 'fired' | 'blocked'
|
||||
}
|
||||
|
||||
export interface CreateHierarchyRequest {
|
||||
subordinate_id: number
|
||||
approver_id: number
|
||||
|
|
@ -18,6 +19,7 @@ export interface CreateHierarchyRequest {
|
|||
topic_category_id?: number | null
|
||||
topic_id?: number | null
|
||||
priority?: number
|
||||
target_system?: string | null
|
||||
}
|
||||
|
||||
export interface UpdateHierarchyRequest {
|
||||
|
|
@ -28,6 +30,7 @@ export interface UpdateHierarchyRequest {
|
|||
topic_category_id?: number | null
|
||||
topic_id?: number | null
|
||||
priority?: number
|
||||
target_system?: string | null
|
||||
}
|
||||
|
||||
export const hierarchiesApi = {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,10 @@
|
|||
import apiClient from './client'
|
||||
import type { MonthlyOrderSetting } from '@/types/api'
|
||||
|
||||
export const monthlyOrdersApi = {
|
||||
getSettings: () =>
|
||||
apiClient.get<MonthlyOrderSetting>('/monthly-orders/settings'),
|
||||
|
||||
saveSettings: (data: MonthlyOrderSetting) =>
|
||||
apiClient.post<{status: string}>('/monthly-orders/settings', data),
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import apiClient from './client'
|
||||
import type { Notification, ApiResponse, TargetFilters } from '@/types/api'
|
||||
|
||||
export interface NotificationsListParams {
|
||||
offset?: number
|
||||
limit?: number
|
||||
status?: string
|
||||
}
|
||||
|
||||
export interface CreateNotificationRequest {
|
||||
title: string
|
||||
message_html: string
|
||||
photo_base64?: string
|
||||
photo_file_name?: string
|
||||
targets: TargetFilters
|
||||
}
|
||||
|
||||
export const notificationsApi = {
|
||||
getList: (params: NotificationsListParams = {}) =>
|
||||
apiClient.get<ApiResponse<Notification[]>>('/notifications', { params }),
|
||||
|
||||
getById: (id: number) =>
|
||||
apiClient.get<Notification>(`/notifications/${id}`),
|
||||
|
||||
create: (data: CreateNotificationRequest) =>
|
||||
apiClient.post<Notification>('/notifications', data),
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ export interface RolesListParams {
|
|||
is_approver?: boolean
|
||||
is_observer?: boolean
|
||||
is_executor?: boolean
|
||||
is_controller?: boolean
|
||||
name?: string
|
||||
code?: string
|
||||
}
|
||||
|
|
@ -22,6 +23,7 @@ export interface CreateRoleRequest {
|
|||
is_approver?: boolean
|
||||
is_observer?: boolean
|
||||
is_executor?: boolean
|
||||
is_controller?: boolean
|
||||
}
|
||||
|
||||
export interface UpdateRoleRequest {
|
||||
|
|
@ -34,6 +36,7 @@ export interface UpdateRoleRequest {
|
|||
is_approver?: boolean
|
||||
is_observer?: boolean
|
||||
is_executor?: boolean
|
||||
is_controller?: boolean
|
||||
}
|
||||
|
||||
export const rolesApi = {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,32 @@
|
|||
import axios from 'axios'
|
||||
|
||||
// Изолированный клиент ТОЛЬКО для сервера менеджеров
|
||||
const managerApiClient = axios.create({
|
||||
baseURL: 'https://38.180.230.177.nip.io/tg-api/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'supersecretkey',
|
||||
},
|
||||
})
|
||||
|
||||
export const telegramManagersApi = {
|
||||
getStatus: () =>
|
||||
managerApiClient.get('/managers/status'),
|
||||
|
||||
sendCode: (phone: string, name: string) =>
|
||||
managerApiClient.post('/managers/auth/send-code', { phone, name }),
|
||||
|
||||
verifyCode: (phone: string, code: string, password?: string) =>
|
||||
managerApiClient.post('/managers/auth/verify-code', { phone, code, password }),
|
||||
|
||||
delete: (managerId: number, wipeData: boolean) =>
|
||||
managerApiClient.delete(`/managers/${managerId}?wipe_data=${wipeData}`),
|
||||
|
||||
startQr: () =>
|
||||
managerApiClient.post('/managers/auth/qr/start'),
|
||||
|
||||
checkQrStatus: (token: string) =>
|
||||
managerApiClient.get(`/managers/auth/qr/status?token=${token}`),
|
||||
updateName: (managerId: number, name: string) =>
|
||||
managerApiClient.put(`/managers/${managerId}/name`, { name }),
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import axios from 'axios'
|
||||
|
||||
const publicApiClient = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
export interface ServerTimeResponse {
|
||||
timestamp: number
|
||||
iso: string
|
||||
}
|
||||
|
||||
export const timeApi = {
|
||||
getServerTime: async (): Promise<ServerTimeResponse> => {
|
||||
const response = await publicApiClient.get<ServerTimeResponse>('/time')
|
||||
return response.data
|
||||
},
|
||||
}
|
||||
|
|
@ -25,6 +25,7 @@ export interface CreateTopicRequest {
|
|||
allow_approver_selection?: boolean
|
||||
first_approver_role_code?: string | null
|
||||
allow_observer_selection?: boolean
|
||||
allow_delegation_selection?: boolean
|
||||
approval_mode?: string
|
||||
require_approver_comment?: boolean
|
||||
requires_file?: boolean
|
||||
|
|
@ -49,6 +50,8 @@ export interface UpdateTopicRequest {
|
|||
allow_approver_selection?: boolean
|
||||
first_approver_role_code?: string | null
|
||||
allow_observer_selection?: boolean
|
||||
// 🆕 см. CreateTopicRequest.allow_delegation_selection
|
||||
allow_delegation_selection?: boolean
|
||||
approval_mode?: string
|
||||
require_approver_comment?: boolean
|
||||
requires_file?: boolean
|
||||
|
|
|
|||
|
|
@ -8,25 +8,27 @@ export interface UsersListParams {
|
|||
is_fired?: boolean
|
||||
department_id?: number
|
||||
full_name?: string
|
||||
role_ids?: number[]
|
||||
}
|
||||
|
||||
export interface UpdateUserRequest {
|
||||
id: number
|
||||
full_name?: string
|
||||
department_id?: number | null
|
||||
is_blocked?: boolean
|
||||
is_fired?: boolean
|
||||
}
|
||||
|
||||
export const usersApi = {
|
||||
// Получить список пользователей с пагинацией и фильтрами
|
||||
getList: (params: UsersListParams = {}) =>
|
||||
apiClient.get<ApiResponse<User[]>>('/users', { params }),
|
||||
|
||||
// Получить пользователя по ID
|
||||
getById: (id: number) =>
|
||||
apiClient.get<User>(`/users/${id}`),
|
||||
|
||||
// Обновить пользователя
|
||||
update: (data: UpdateUserRequest) =>
|
||||
apiClient.put<User>('/users', data),
|
||||
|
||||
delete: (id: number) =>
|
||||
apiClient.delete(`/users/${id}`),
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import axios from 'axios'
|
||||
|
||||
const waApiClient = axios.create({
|
||||
baseURL: 'https://38.180.230.177.nip.io/wa-api/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'supersecretkey',
|
||||
},
|
||||
})
|
||||
|
||||
export const whatsappManagersApi = {
|
||||
getStatus: () => waApiClient.get('/managers/status'),
|
||||
startQr: () => waApiClient.post('/managers/auth/qr/start'),
|
||||
checkQrStatus: (token: string) => waApiClient.get(`/managers/auth/qr/status?token=${token}`),
|
||||
delete: (phone: string, wipeData: boolean) =>
|
||||
waApiClient.delete(`/managers/${phone}?wipe_data=${wipeData}`),
|
||||
updateName: (phone: string, name: string) =>
|
||||
waApiClient.put(`/managers/${phone}/name`, { name }),
|
||||
}
|
||||
|
|
@ -0,0 +1,147 @@
|
|||
import { useMemo, useState } from 'react'
|
||||
import {
|
||||
ActionIcon,
|
||||
Avatar,
|
||||
Box,
|
||||
Button,
|
||||
Drawer,
|
||||
Group,
|
||||
ScrollArea,
|
||||
SegmentedControl,
|
||||
Skeleton,
|
||||
Stack,
|
||||
Text,
|
||||
TextInput,
|
||||
UnstyledButton,
|
||||
} from '@mantine/core'
|
||||
import { useDebouncedValue } from '@mantine/hooks'
|
||||
import { IconArrowLeft, IconCheck, IconSearch } from '@tabler/icons-react'
|
||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||
import classes from './UserDrawer.module.css'
|
||||
|
||||
type Mode = 'replace' | 'merge'
|
||||
|
||||
interface Props {
|
||||
currentUserId: number | null
|
||||
onBack: () => void
|
||||
onApply: (roleIds: number[], mode: Mode) => void
|
||||
}
|
||||
|
||||
interface Picked {
|
||||
id: number
|
||||
roleIds: number[]
|
||||
}
|
||||
|
||||
export default function CopyRolesPanel({ currentUserId, onBack, onApply }: Props) {
|
||||
const [search, setSearch] = useState('')
|
||||
const [debounced] = useDebouncedValue(search.trim(), 300)
|
||||
const [picked, setPicked] = useState<Picked | null>(null)
|
||||
const [mode, setMode] = useState<Mode>('replace')
|
||||
|
||||
const { data, isLoading } = useUsers({
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
...(debounced && { full_name: debounced }),
|
||||
})
|
||||
|
||||
const users = useMemo(
|
||||
() => (Array.isArray(data?.data) ? data.data : []).filter((u) => u.id !== currentUserId),
|
||||
[data, currentUserId],
|
||||
)
|
||||
|
||||
const pick = (user: (typeof users)[number]) => {
|
||||
const roleIds = Array.isArray(user.user_roles)
|
||||
? user.user_roles.map((ur) => ur.role_id).filter((id): id is number => !!id)
|
||||
: []
|
||||
setPicked({ id: user.id!, roleIds })
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Drawer.Header>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<ActionIcon onClick={onBack} aria-label="Назад">
|
||||
<IconArrowLeft size={18} />
|
||||
</ActionIcon>
|
||||
<Text fw={600}>Скопировать роли</Text>
|
||||
</Group>
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body className={classes.body}>
|
||||
<Stack className={classes.section} gap="md">
|
||||
<TextInput
|
||||
placeholder="Поиск сотрудника по имени"
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<SegmentedControl
|
||||
fullWidth
|
||||
value={mode}
|
||||
onChange={(v) => setMode(v as Mode)}
|
||||
data={[
|
||||
{ value: 'replace', label: 'Заменить текущие' },
|
||||
{ value: 'merge', label: 'Добавить к текущим' },
|
||||
]}
|
||||
/>
|
||||
|
||||
{isLoading ? (
|
||||
<Stack gap="xs">
|
||||
{Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} h={52} />)}
|
||||
</Stack>
|
||||
) : users.length === 0 ? (
|
||||
<Text size="sm" c="dimmed" ta="center" py="lg">Никого не найдено</Text>
|
||||
) : (
|
||||
<ScrollArea.Autosize mah="calc(100dvh - 330px)" type="auto" mx={-6}>
|
||||
<Stack gap={2} px={6}>
|
||||
{users.map((u) => {
|
||||
const roles = (Array.isArray(u.user_roles) ? u.user_roles : [])
|
||||
.map((ur) => ur.role?.name)
|
||||
.filter(Boolean)
|
||||
const isPicked = picked?.id === u.id
|
||||
return (
|
||||
<UnstyledButton
|
||||
key={u.id}
|
||||
className={classes.pickRow}
|
||||
data-selected={isPicked || undefined}
|
||||
onClick={() => pick(u)}
|
||||
>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Avatar size={32} radius="xl" color="initials" name={u.full_name ?? ''} />
|
||||
<Box style={{ flex: 1, minWidth: 0 }}>
|
||||
<Group justify="space-between" wrap="nowrap" gap="xs">
|
||||
<Text size="sm" fw={500} truncate>{u.full_name}</Text>
|
||||
<Text size="xs" c="dimmed" style={{ flexShrink: 0 }}>
|
||||
{roles.length} ролей
|
||||
</Text>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{roles.length > 0 ? roles.join(', ') : 'Без ролей'}
|
||||
</Text>
|
||||
</Box>
|
||||
{isPicked && <IconCheck size={16} color="var(--mantine-primary-color-filled)" />}
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
)
|
||||
})}
|
||||
</Stack>
|
||||
</ScrollArea.Autosize>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
<Group className={classes.footer} justify="space-between" wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">Роли применятся после сохранения</Text>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Button variant="default" onClick={onBack}>Назад</Button>
|
||||
<Button disabled={!picked} onClick={() => picked && onApply(picked.roleIds, mode)}>
|
||||
Применить
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
</Drawer.Body>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
import { Component, type ErrorInfo, type ReactNode } from 'react'
|
||||
import { Center, Stack, Title, Text, Button, Code, Box } from '@mantine/core'
|
||||
import { IconAlertTriangle } from '@tabler/icons-react'
|
||||
|
||||
interface Props {
|
||||
children: ReactNode
|
||||
// Полноэкранный вариант — для самого верхнего "предохранителя" (main.tsx).
|
||||
// Без него — занимает высоту родителя (для page-level использования
|
||||
// внутри layout, где вокруг уже есть Header/Sidebar).
|
||||
fullPage?: boolean
|
||||
}
|
||||
|
||||
interface State {
|
||||
error: Error | null
|
||||
componentStack: string | null
|
||||
}
|
||||
|
||||
// Общий ErrorBoundary. Используется дважды:
|
||||
// 1) в main.tsx, оборачивая <App /> — последний рубеж на случай падения
|
||||
// чего угодно (в т.ч. самого layout/sidebar);
|
||||
// 2) в MainLayout.tsx, оборачивая <Outlet />, с key={location.pathname} —
|
||||
// тогда падение ОДНОЙ страницы не рушит весь интерфейс: Header и
|
||||
// Sidebar остаются рабочими, и переход на другую страницу сам
|
||||
// пересоздаёт boundary и сбрасывает ошибку — reload не нужен.
|
||||
export default class ErrorBoundary extends Component<Props, State> {
|
||||
state: State = { error: null, componentStack: null }
|
||||
|
||||
static getDerivedStateFromError(error: Error) {
|
||||
return { error }
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: ErrorInfo) {
|
||||
// 🆕 Логируем с максимумом контекста — пригодится и сейчас для
|
||||
// диагностики (например, бага "белый экран после правки
|
||||
// иерархии"), и впредь. Если подключите Sentry или аналог —
|
||||
// отправляйте error + info отсюда же.
|
||||
console.error('[ErrorBoundary] Необработанная ошибка рендера:', {
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
componentStack: info.componentStack,
|
||||
url: window.location.href,
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
this.setState({ componentStack: info.componentStack ?? null })
|
||||
}
|
||||
|
||||
handleReload = () => {
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
render() {
|
||||
const { error, componentStack } = this.state
|
||||
if (!error) {
|
||||
return this.props.children
|
||||
}
|
||||
|
||||
return (
|
||||
<Center h={this.props.fullPage ? '100vh' : '100%'} p="xl">
|
||||
<Stack gap="sm" maw={640} align="center">
|
||||
<IconAlertTriangle size={40} color="var(--mantine-color-red-6)" />
|
||||
<Title order={3} ta="center">
|
||||
Произошла ошибка при загрузке страницы
|
||||
</Title>
|
||||
<Text c="dimmed" ta="center" size="sm">
|
||||
Попробуйте перейти на другую страницу через меню слева или перезагрузить
|
||||
страницу. Если ошибка повторяется — сообщите в техническую поддержку.
|
||||
</Text>
|
||||
<Button onClick={this.handleReload} mt="sm">
|
||||
Перезагрузить страницу
|
||||
</Button>
|
||||
|
||||
{import.meta.env.DEV && (
|
||||
<Box mt="md" w="100%">
|
||||
<Text size="xs" fw={600} c="dimmed" mb={4}>
|
||||
Технические детали (видно только в dev-сборке):
|
||||
</Text>
|
||||
<Code
|
||||
block
|
||||
style={{ whiteSpace: 'pre-wrap', fontSize: 10, maxHeight: 240, overflow: 'auto' }}
|
||||
>
|
||||
{error.message}
|
||||
{'\n\n'}
|
||||
{componentStack}
|
||||
</Code>
|
||||
</Box>
|
||||
)}
|
||||
</Stack>
|
||||
</Center>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import { Center, Stack, Text, ThemeIcon } from '@mantine/core'
|
||||
import { IconTools } from '@tabler/icons-react'
|
||||
import { PageHeader } from '@/components/ui/PageHeader'
|
||||
|
||||
// Заглушка для разделов, которые ещё не сделаны. Если у «Обзора» уже есть своя заглушка — используйте её стиль.
|
||||
export default function ComingSoonPage({ title, description }: { title: string; description?: string }) {
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<PageHeader title={title} />
|
||||
<Center py={80}>
|
||||
<Stack align="center" gap={6}>
|
||||
<ThemeIcon variant="light" color="gray" size={48} radius="xl">
|
||||
<IconTools size={24} stroke={1.5} />
|
||||
</ThemeIcon>
|
||||
<Text fw={500}>Раздел в разработке</Text>
|
||||
{description && <Text size="sm" c="dimmed" ta="center" maw={420}>{description}</Text>}
|
||||
</Stack>
|
||||
</Center>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,13 +1,88 @@
|
|||
import {
|
||||
Group,
|
||||
Burger,
|
||||
Text,
|
||||
Avatar,
|
||||
Menu,
|
||||
ActionIcon,
|
||||
Group, Burger, Text, Avatar, Menu, ActionIcon, Button, Kbd, Breadcrumbs, Box, UnstyledButton,
|
||||
Popover, Indicator, ThemeIcon, Stack, ScrollArea,
|
||||
} from '@mantine/core'
|
||||
import { IconLogout, IconUser } from '@tabler/icons-react'
|
||||
import { spotlight } from '@mantine/spotlight'
|
||||
import {
|
||||
IconLogout, IconSearch, IconBell, IconBriefcase, IconCheck, IconX, type Icon
|
||||
} from '@tabler/icons-react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { findTrail } from './navigation'
|
||||
import { ColorSchemeToggle } from '@/components/ui/ColorSchemeToggle'
|
||||
|
||||
// Заглушки для Центра уведомлений
|
||||
const MOCK_NOTIFICATIONS = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Новая задача',
|
||||
text: 'Вам назначена задача по заявке #1024: «Подготовить договор»',
|
||||
time: '10 мин назад',
|
||||
icon: IconBriefcase,
|
||||
color: 'blue',
|
||||
unread: true,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'Заявка согласована',
|
||||
text: 'Заявка #980 успешно согласована всеми участниками',
|
||||
time: '1 час назад',
|
||||
icon: IconCheck,
|
||||
color: 'green',
|
||||
unread: true,
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'Заявка отклонена',
|
||||
text: 'Иван Иванов отклонил вашу заявку #975',
|
||||
time: 'Вчера, 15:30',
|
||||
icon: IconX,
|
||||
color: 'red',
|
||||
unread: false,
|
||||
},
|
||||
]
|
||||
|
||||
function NotificationItem({
|
||||
title, text, time, icon: IconCmp, color, unread
|
||||
}: {
|
||||
title: string; text: string; time: string; icon: Icon; color: string; unread: boolean
|
||||
}) {
|
||||
return (
|
||||
<UnstyledButton
|
||||
p="sm"
|
||||
style={(theme) => ({
|
||||
borderBottom: '1px solid var(--mantine-color-default-border)',
|
||||
width: '100%',
|
||||
backgroundColor: unread ? 'var(--mantine-color-default-hover)' : 'transparent',
|
||||
transition: 'background-color 150ms',
|
||||
'&:hover': { backgroundColor: 'var(--mantine-color-default-hover)' },
|
||||
})}
|
||||
>
|
||||
<Group wrap="nowrap" align="flex-start">
|
||||
<ThemeIcon variant="light" color={color} size={32} radius="xl">
|
||||
<IconCmp size={16} stroke={2} />
|
||||
</ThemeIcon>
|
||||
<Box style={{ flex: 1, minWidth: 0 }}>
|
||||
<Group justify="space-between" wrap="nowrap" align="flex-start">
|
||||
<Text size="sm" fw={600} truncate>{title}</Text>
|
||||
{unread && (
|
||||
<Box
|
||||
w={8} h={8} mt={6}
|
||||
style={{
|
||||
borderRadius: '50%',
|
||||
background: 'var(--mantine-primary-color-filled)',
|
||||
flexShrink: 0
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed" lineClamp={2} mt={2}>{text}</Text>
|
||||
<Text size="xs" c="dimmed" mt={4}>{time}</Text>
|
||||
</Box>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
)
|
||||
}
|
||||
|
||||
interface HeaderProps {
|
||||
toggleMobile: () => void
|
||||
|
|
@ -16,54 +91,118 @@ interface HeaderProps {
|
|||
desktopOpened: boolean
|
||||
}
|
||||
|
||||
export default function Header({
|
||||
toggleMobile,
|
||||
toggleDesktop,
|
||||
mobileOpened,
|
||||
desktopOpened
|
||||
}: HeaderProps) {
|
||||
export default function Header({ toggleMobile, toggleDesktop, mobileOpened, desktopOpened }: HeaderProps) {
|
||||
const { user, logout } = useAuth()
|
||||
const { pathname } = useLocation()
|
||||
const trail = findTrail(pathname)
|
||||
const role = user?.is_root ? 'Суперадмин' : user?.is_observer ? 'Наблюдатель' : 'Администратор'
|
||||
|
||||
const unreadCount = MOCK_NOTIFICATIONS.filter((n) => n.unread).length
|
||||
|
||||
return (
|
||||
<Group h="100%" px="md" justify="space-between">
|
||||
<Group h="100%" gap={0}>
|
||||
<Burger
|
||||
opened={mobileOpened}
|
||||
onClick={toggleMobile}
|
||||
hiddenFrom="sm"
|
||||
size="sm"
|
||||
/>
|
||||
<Burger
|
||||
opened={desktopOpened}
|
||||
onClick={toggleDesktop}
|
||||
visibleFrom="sm"
|
||||
size="sm"
|
||||
/>
|
||||
<Text ml="md" fw={700}>
|
||||
Ruspet Admin Panel
|
||||
</Text>
|
||||
<Group h="100%" px="md" justify="space-between" wrap="nowrap">
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Burger opened={mobileOpened} onClick={toggleMobile} hiddenFrom="sm" size="sm" />
|
||||
<Burger opened={desktopOpened} onClick={toggleDesktop} visibleFrom="sm" size="sm" />
|
||||
|
||||
<Group gap={8} wrap="nowrap">
|
||||
<Box
|
||||
w={28} h={28}
|
||||
style={{
|
||||
borderRadius: 8, display: 'grid', placeItems: 'center',
|
||||
background: 'var(--mantine-primary-color-filled)', color: '#fff',
|
||||
fontWeight: 700, fontSize: 14,
|
||||
}}
|
||||
>
|
||||
Р
|
||||
</Box>
|
||||
<Text fw={600} size="sm" visibleFrom="xs">Портал РусПЭТ</Text>
|
||||
</Group>
|
||||
|
||||
<Group>
|
||||
<Menu shadow="md" width={200}>
|
||||
{trail.length > 0 && (
|
||||
<Breadcrumbs separator="/" visibleFrom="md" ml="md">
|
||||
{trail.map((t, i) => (
|
||||
<Text key={i} size="sm" c={i === trail.length - 1 ? undefined : 'dimmed'} fw={i === trail.length - 1 ? 500 : 400}>
|
||||
{t}
|
||||
</Text>
|
||||
))}
|
||||
</Breadcrumbs>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Button
|
||||
variant="default"
|
||||
size="xs"
|
||||
visibleFrom="sm"
|
||||
leftSection={<IconSearch size={14} />}
|
||||
rightSection={<Kbd size="xs">Ctrl K</Kbd>}
|
||||
onClick={spotlight.open}
|
||||
c="dimmed"
|
||||
fw={400}
|
||||
w={220}
|
||||
justify="space-between"
|
||||
>
|
||||
Поиск
|
||||
</Button>
|
||||
<ActionIcon size="lg" hiddenFrom="sm" onClick={spotlight.open} aria-label="Поиск">
|
||||
<IconSearch size={18} stroke={1.6} />
|
||||
</ActionIcon>
|
||||
|
||||
{/* Центр уведомлений */}
|
||||
<Popover width={320} position="bottom-end" shadow="md">
|
||||
<Popover.Target>
|
||||
<Indicator
|
||||
color="brand"
|
||||
size={9}
|
||||
offset={5}
|
||||
disabled={unreadCount === 0}
|
||||
withBorder
|
||||
>
|
||||
<ActionIcon size="lg" aria-label="Уведомления" variant="subtle" color="gray">
|
||||
<IconBell size={20} stroke={1.6} />
|
||||
</ActionIcon>
|
||||
</Indicator>
|
||||
</Popover.Target>
|
||||
<Popover.Dropdown p={0}>
|
||||
<Group justify="space-between" px="md" py="xs" style={{ borderBottom: '1px solid var(--mantine-color-default-border)' }}>
|
||||
<Text size="sm" fw={600}>Уведомления</Text>
|
||||
{unreadCount > 0 && (
|
||||
<Button variant="subtle" size="compact-xs">Прочитать все</Button>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
<ScrollArea.Autosize mah={360} type="auto">
|
||||
{MOCK_NOTIFICATIONS.length > 0 ? (
|
||||
<Stack gap={0}>
|
||||
{MOCK_NOTIFICATIONS.map((notif) => (
|
||||
<NotificationItem key={notif.id} {...notif} />
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed" ta="center" py="xl">Нет новых уведомлений</Text>
|
||||
)}
|
||||
</ScrollArea.Autosize>
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
|
||||
<ColorSchemeToggle />
|
||||
|
||||
<Menu width={220} position="bottom-end">
|
||||
<Menu.Target>
|
||||
<ActionIcon variant="subtle" size="lg">
|
||||
<Avatar size="sm" radius="xl">
|
||||
<UnstyledButton aria-label="Профиль">
|
||||
<Avatar size="sm" radius="xl" color="brand">
|
||||
{user?.login?.charAt(0).toUpperCase() || 'A'}
|
||||
</Avatar>
|
||||
</ActionIcon>
|
||||
</UnstyledButton>
|
||||
</Menu.Target>
|
||||
|
||||
<Menu.Dropdown>
|
||||
<Menu.Item leftSection={<IconUser size={14} />}>
|
||||
{user?.login || 'Admin'}
|
||||
</Menu.Item>
|
||||
<Box px="sm" py={6}>
|
||||
<Text size="sm" fw={600}>{user?.login || 'Admin'}</Text>
|
||||
<Text size="xs" c="dimmed">{role}</Text>
|
||||
</Box>
|
||||
<Menu.Divider />
|
||||
<Menu.Item
|
||||
leftSection={<IconLogout size={14} />}
|
||||
onClick={logout}
|
||||
color="red"
|
||||
>
|
||||
<Menu.Item leftSection={<IconLogout size={14} />} color="red" onClick={logout}>
|
||||
Выйти
|
||||
</Menu.Item>
|
||||
</Menu.Dropdown>
|
||||
|
|
|
|||
|
|
@ -1,22 +1,44 @@
|
|||
import { AppShell } from '@mantine/core'
|
||||
import { useDisclosure } from '@mantine/hooks'
|
||||
import { Outlet } from 'react-router-dom'
|
||||
import { Spotlight } from '@mantine/spotlight'
|
||||
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useMemo } from 'react'
|
||||
import Sidebar from './Sidebar'
|
||||
import Header from './Header'
|
||||
import ErrorBoundary from '../DiagnosticErrorBoundary'
|
||||
import { navigation, flattenNav } from './navigation'
|
||||
import {useAccess} from "@/pages/admins/components/UseAccess.tsx";
|
||||
|
||||
export default function MainLayout() {
|
||||
const [mobileOpened, { toggle: toggleMobile }] = useDisclosure()
|
||||
const [mobileOpened, { toggle: toggleMobile, close: closeMobile }] = useDisclosure()
|
||||
const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true)
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const { can, access, isRoot } = useAccess()
|
||||
|
||||
// Поиск по разделам показывает только то, к чему у пользователя есть доступ
|
||||
const actions = useMemo(
|
||||
() =>
|
||||
flattenNav(navigation, (i) => !i.module || can(i.module)).map((i) => ({
|
||||
id: i.path,
|
||||
label: i.label,
|
||||
description: i.trail.slice(0, -1).join(' / '),
|
||||
leftSection: i.icon ? <i.icon size={20} stroke={1.5} /> : undefined,
|
||||
onClick: () => { navigate(i.path); closeMobile() },
|
||||
})),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[access, isRoot, navigate, closeMobile],
|
||||
)
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
header={{ height: 60 }}
|
||||
header={{ height: 56 }}
|
||||
navbar={{
|
||||
width: 280,
|
||||
width: 264,
|
||||
breakpoint: 'sm',
|
||||
collapsed: { mobile: !mobileOpened, desktop: !desktopOpened },
|
||||
}}
|
||||
padding="md"
|
||||
padding="lg"
|
||||
>
|
||||
<AppShell.Header>
|
||||
<Header
|
||||
|
|
@ -27,13 +49,22 @@ export default function MainLayout() {
|
|||
/>
|
||||
</AppShell.Header>
|
||||
|
||||
<AppShell.Navbar p={0}>
|
||||
<AppShell.Navbar>
|
||||
<Sidebar />
|
||||
</AppShell.Navbar>
|
||||
|
||||
<AppShell.Main bg="gray.0" miw={0}>
|
||||
<AppShell.Main miw={0} style={{ background: 'var(--app-bg)' }}>
|
||||
<ErrorBoundary key={location.pathname}>
|
||||
<Outlet />
|
||||
</ErrorBoundary>
|
||||
</AppShell.Main>
|
||||
|
||||
<Spotlight
|
||||
actions={actions}
|
||||
shortcut={['mod + K', '/']}
|
||||
nothingFound="Ничего не найдено"
|
||||
searchProps={{ placeholder: 'Перейти к разделу…' }}
|
||||
/>
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
.link {
|
||||
border-radius: var(--mantine-radius-md);
|
||||
padding: 8px 10px;
|
||||
font-size: var(--mantine-font-size-sm);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
padding: 0 10px;
|
||||
margin-bottom: 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mantine-color-dimmed);
|
||||
}
|
||||
|
|
@ -1,169 +1,65 @@
|
|||
import { useState } from 'react'
|
||||
import { NavLink, Box, Text, Stack } from '@mantine/core'
|
||||
import { Badge, Box, NavLink, ScrollArea, Stack, Text } from '@mantine/core'
|
||||
import { Link, useLocation } from 'react-router-dom'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import {useAccess} from "@/pages/admins/components/UseAccess.tsx";
|
||||
import {
|
||||
IconDashboard,
|
||||
IconFileCheck,
|
||||
IconSettings,
|
||||
IconChevronRight,
|
||||
IconList,
|
||||
IconUsers,
|
||||
IconBuilding,
|
||||
IconShield,
|
||||
IconKey,
|
||||
IconCategory,
|
||||
IconBriefcase,
|
||||
IconUserCheck,
|
||||
IconGitBranch,
|
||||
IconUserCog,
|
||||
IconCheck, IconBellRinging,
|
||||
} from '@tabler/icons-react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
navigation, filterNavigation, isPathActive, hasActiveDescendant, type NavItem,
|
||||
} from './navigation'
|
||||
import classes from './Sidebar.module.css'
|
||||
|
||||
interface MenuItem {
|
||||
label: string
|
||||
icon?: any
|
||||
path?: string
|
||||
children?: MenuItem[]
|
||||
}
|
||||
function NavNode({ item }: { item: NavItem }) {
|
||||
const { pathname } = useLocation()
|
||||
const Icon = item.icon
|
||||
const icon = Icon ? <Icon size={18} stroke={1.6} /> : undefined
|
||||
|
||||
const menuItems: MenuItem[] = [
|
||||
{ label: 'Обзор', icon: IconDashboard, path: '/' },
|
||||
{ label: 'Администраторы', icon: IconUserCog, path: '/admins' },
|
||||
{ label: 'Уведомления', icon: IconBellRinging, path: '/notifications' },
|
||||
{
|
||||
label: 'Система согласований',
|
||||
icon: IconFileCheck,
|
||||
children: [
|
||||
{ label: 'Панель управления', icon: IconDashboard, path: '/approval-dash' },
|
||||
{ label: 'Заявки', icon: IconList, path: '/approvals' },
|
||||
{ label: 'Задачи', icon: IconCheck, path: '/approval-tasks' },
|
||||
{ label: 'Пользователи', icon: IconUsers, path: '/users' },
|
||||
{ label: 'Отделы', icon: IconBuilding, path: '/departments' },
|
||||
{ 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) {
|
||||
if (item.children?.length) {
|
||||
return (
|
||||
<Box>
|
||||
<NavLink
|
||||
label={item.label}
|
||||
leftSection={item.icon ? <item.icon size={18} /> : undefined}
|
||||
rightSection={
|
||||
<IconChevronRight
|
||||
size={16}
|
||||
style={{
|
||||
transform: opened ? 'rotate(90deg)' : 'none',
|
||||
transition: 'transform 0.2s ease',
|
||||
}}
|
||||
/>
|
||||
}
|
||||
active={hasActiveChild}
|
||||
onClick={() => setOpened(!opened)}
|
||||
styles={{
|
||||
root: {
|
||||
paddingLeft,
|
||||
paddingRight: 12,
|
||||
borderRadius: '8px',
|
||||
marginBottom: 2,
|
||||
'&:hover': {
|
||||
backgroundColor: 'var(--mantine-color-gray-0)',
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
{opened && (
|
||||
leftSection={icon}
|
||||
defaultOpened={hasActiveDescendant(item, pathname)}
|
||||
childrenOffset={16}
|
||||
classNames={{ root: classes.link }}
|
||||
>
|
||||
<Stack gap={2} mt={2}>
|
||||
{item.children!.map((child) => (
|
||||
<MenuItemLink key={child.label} item={child} level={level + 1} />
|
||||
))}
|
||||
{item.children.map((c) => <NavNode key={c.label} item={c} />)}
|
||||
</Stack>
|
||||
)}
|
||||
</Box>
|
||||
</NavLink>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<NavLink
|
||||
component={Link}
|
||||
to={item.path!}
|
||||
label={item.label}
|
||||
leftSection={item.icon ? <item.icon size={18} /> : undefined}
|
||||
active={isActive}
|
||||
onClick={() => {
|
||||
if (item.path) navigate(item.path)
|
||||
}}
|
||||
styles={{
|
||||
root: {
|
||||
paddingLeft,
|
||||
paddingRight: 12,
|
||||
borderRadius: '8px',
|
||||
marginBottom: 2,
|
||||
'&:hover': {
|
||||
backgroundColor: 'var(--mantine-color-gray-0)',
|
||||
},
|
||||
},
|
||||
label: {
|
||||
fontWeight: isActive ? 600 : 400,
|
||||
},
|
||||
}}
|
||||
leftSection={icon}
|
||||
active={isPathActive(item.path!, pathname)}
|
||||
classNames={{ root: classes.link }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
return (
|
||||
<Box
|
||||
style={{
|
||||
padding: '12px 8px',
|
||||
height: '100%',
|
||||
overflowY: 'auto',
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
size="xs"
|
||||
c="dimmed"
|
||||
fw={700}
|
||||
mb="md"
|
||||
px="sm"
|
||||
style={{
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px',
|
||||
}}
|
||||
>
|
||||
Главное меню
|
||||
</Text>
|
||||
const { user } = useAuth()
|
||||
const { can } = useAccess()
|
||||
const isObserver = user?.is_observer === true
|
||||
// Пункт виден, если у него нет раздела или у пользователя есть доступ к этому разделу
|
||||
const sections = filterNavigation(navigation, (i) => !i.module || can(i.module))
|
||||
|
||||
<Stack gap={4}>
|
||||
{menuItems.map((item) => (
|
||||
<MenuItemLink key={item.label} item={item} level={0} />
|
||||
))}
|
||||
return (
|
||||
<ScrollArea h="100%" px="sm" py="md">
|
||||
{isObserver && <Badge color="blue" fullWidth mb="md">Режим наблюдателя</Badge>}
|
||||
<Stack gap="lg">
|
||||
{sections.map((section, i) => (
|
||||
<Box key={section.title ?? `section-${i}`}>
|
||||
{section.title && <Text className={classes.sectionTitle}>{section.title}</Text>}
|
||||
<Stack gap={2}>
|
||||
{section.items.map((item) => <NavNode key={item.label} item={item} />)}
|
||||
</Stack>
|
||||
</Box>
|
||||
))}
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,144 @@
|
|||
import {
|
||||
IconDashboard, IconFileCheck, IconSettings, IconList, IconUsers, IconBuilding,
|
||||
IconShield, IconKey, IconCategory, IconBriefcase, IconUserCheck, IconGitBranch,
|
||||
IconUserCog, IconCheck, IconBellRinging, IconBlocks, IconHistory, IconChartBar,
|
||||
IconPhone, IconInbox, IconFileDescription, IconChecklist, type Icon,
|
||||
} from '@tabler/icons-react'
|
||||
import { MODULES } from '@/lib/access'
|
||||
|
||||
export interface NavItem {
|
||||
label: string
|
||||
icon?: Icon
|
||||
path?: string
|
||||
children?: NavItem[]
|
||||
/** id раздела из lib/access (MODULES). Без него пункт виден всем. У группы не указывается: она видна, если виден хоть один вложенный пункт. */
|
||||
module?: string
|
||||
}
|
||||
|
||||
export interface NavSection {
|
||||
title?: string
|
||||
items: NavItem[]
|
||||
}
|
||||
|
||||
export const navigation: NavSection[] = [
|
||||
{
|
||||
items: [{ label: 'Обзор', icon: IconDashboard, path: '/' }],
|
||||
},
|
||||
{
|
||||
// Личная работа: видна всем, данные только свои
|
||||
title: 'Моё',
|
||||
items: [
|
||||
{ label: 'Входящие', icon: IconInbox, path: '/inbox' },
|
||||
{ label: 'Мои заявки', icon: IconFileDescription, path: '/my/approvals' },
|
||||
{ label: 'Мои задачи', icon: IconChecklist, path: '/my/tasks' },
|
||||
],
|
||||
},
|
||||
{
|
||||
// Просмотр и контроль по всей компании
|
||||
title: 'Контроль',
|
||||
items: [
|
||||
{ label: 'Все заявки', icon: IconList, path: '/approvals', module: 'approvals' },
|
||||
{ label: 'Все задачи', icon: IconCheck, path: '/approval-tasks', module: 'approval_tasks' },
|
||||
{ label: 'Заказы на месяц', icon: IconChartBar, path: '/monthly-orders-settings', module: 'monthly_orders' },
|
||||
{ label: 'Телефония', icon: IconPhone, path: '/telephony', module: 'telephony' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Согласования',
|
||||
items: [
|
||||
{ label: 'Панель управления', icon: IconFileCheck, path: '/approval-dash', module: 'approval_dash' },
|
||||
{
|
||||
label: 'Темы согласований',
|
||||
icon: IconBriefcase,
|
||||
children: [
|
||||
{ label: 'Категории', icon: IconCategory, path: '/categories', module: 'categories' },
|
||||
{ label: 'Темы', icon: IconBriefcase, path: '/topics', module: 'topics' },
|
||||
{ label: 'Исполнители', icon: IconUserCheck, path: '/executors', module: 'topic_executors' },
|
||||
],
|
||||
},
|
||||
{ label: 'Конструктор тем', icon: IconBlocks, path: '/nodes', module: 'nodes' },
|
||||
{ label: 'Иерархия', icon: IconGitBranch, path: '/hierarchies', module: 'hierarchies' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Организация',
|
||||
items: [
|
||||
{ label: 'Сотрудники', icon: IconUsers, path: '/users', module: 'users' },
|
||||
{ label: 'Отделы', icon: IconBuilding, path: '/departments', module: 'departments' },
|
||||
{ label: 'Роли', icon: IconShield, path: '/roles', module: 'roles' },
|
||||
{ label: 'Права', icon: IconKey, path: '/permissions', module: 'permissions' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Система',
|
||||
items: [
|
||||
{ label: 'Пользователи системы', icon: IconUserCog, path: '/admins', module: 'admins' },
|
||||
{ label: 'Уведомления', icon: IconBellRinging, path: '/notifications', module: 'notifications' },
|
||||
{ label: 'Журнал действий', icon: IconHistory, path: '/logs', module: 'logs' },
|
||||
{ label: 'Настройки', icon: IconSettings, path: '/settings' }, // личные настройки — доступны всем
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export type CanSee = (item: NavItem) => boolean
|
||||
const everything: CanSee = () => true
|
||||
|
||||
/** Подсказка при разработке: id раздела в меню должен существовать в lib/access, иначе пункт навсегда скрыт. */
|
||||
if (import.meta.env.DEV) {
|
||||
const known = new Set(MODULES.map((m) => m.id))
|
||||
const walk = (items: NavItem[]) =>
|
||||
items.forEach((i) => {
|
||||
if (i.module && !known.has(i.module)) console.warn(`[navigation] «${i.label}»: нет раздела «${i.module}» в MODULES`)
|
||||
if (i.children) walk(i.children)
|
||||
})
|
||||
navigation.forEach((s) => walk(s.items))
|
||||
}
|
||||
|
||||
export function isPathActive(path: string, pathname: string) {
|
||||
return path === '/' ? pathname === '/' : pathname === path || pathname.startsWith(path + '/')
|
||||
}
|
||||
|
||||
export function hasActiveDescendant(item: NavItem, pathname: string): boolean {
|
||||
if (item.path && isPathActive(item.path, pathname)) return true
|
||||
return item.children?.some((c) => hasActiveDescendant(c, pathname)) ?? false
|
||||
}
|
||||
|
||||
function filterItems(items: NavItem[], canSee: CanSee): NavItem[] {
|
||||
return items
|
||||
.filter(canSee)
|
||||
.map((i) => (i.children ? { ...i, children: filterItems(i.children, canSee) } : i))
|
||||
.filter((i) => !i.children || i.children.length > 0)
|
||||
}
|
||||
|
||||
export function filterNavigation(sections: NavSection[], canSee: CanSee = everything): NavSection[] {
|
||||
return sections
|
||||
.map((s) => ({ ...s, items: filterItems(s.items, canSee) }))
|
||||
.filter((s) => s.items.length > 0)
|
||||
}
|
||||
|
||||
export interface FlatNavItem {
|
||||
label: string
|
||||
path: string
|
||||
icon?: Icon
|
||||
trail: string[]
|
||||
}
|
||||
|
||||
export function flattenNav(sections: NavSection[], canSee: CanSee = everything): FlatNavItem[] {
|
||||
const out: FlatNavItem[] = []
|
||||
const walk = (items: NavItem[], trail: string[]) => {
|
||||
for (const i of items) {
|
||||
const t = [...trail, i.label]
|
||||
if (i.path) out.push({ label: i.label, path: i.path, icon: i.icon, trail: t })
|
||||
if (i.children) walk(i.children, t)
|
||||
}
|
||||
}
|
||||
filterNavigation(sections, canSee).forEach((s) => walk(s.items, s.title ? [s.title] : []))
|
||||
return out
|
||||
}
|
||||
|
||||
export function findTrail(pathname: string): string[] {
|
||||
const match = flattenNav(navigation)
|
||||
.filter((i) => isPathActive(i.path, pathname))
|
||||
.sort((a, b) => b.path.length - a.path.length)[0]
|
||||
return match?.trail ?? []
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
import { Modal, Table, Text, Badge, Group, ScrollArea, Stack, Center } from '@mantine/core'
|
||||
import { IconAlertTriangle } from '@tabler/icons-react'
|
||||
|
||||
interface TopicGap {
|
||||
user_id: number
|
||||
full_name: string
|
||||
department_name: string
|
||||
topic_id: number
|
||||
topic_name: string
|
||||
category_name: string
|
||||
}
|
||||
|
||||
interface TopicGapsModalProps {
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
gaps: TopicGap[]
|
||||
}
|
||||
|
||||
export default function TopicGapsModal({ opened, onClose, gaps }: TopicGapsModalProps) {
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={
|
||||
<Group gap="xs">
|
||||
<IconAlertTriangle size={18} color="var(--mantine-color-orange-6)" />
|
||||
<Text fw={700}>Темы без назначенного порядка согласования</Text>
|
||||
</Group>
|
||||
}
|
||||
size="xl"
|
||||
>
|
||||
<Stack gap="md">
|
||||
<Text size="sm" c="dimmed">
|
||||
У перечисленных сотрудников есть право создавать заявку по теме, но
|
||||
ни одно правило иерархии не назначает для них согласующего — при
|
||||
попытке отправить такую заявку в боте она не пройдёт.
|
||||
</Text>
|
||||
|
||||
{gaps.length === 0 ? (
|
||||
<Center p={40}>
|
||||
<Text c="dimmed">Пробелов не найдено — все настроено</Text>
|
||||
</Center>
|
||||
) : (
|
||||
<ScrollArea.Autosize mah={480}>
|
||||
<Table striped highlightOnHover>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>Сотрудник</Table.Th>
|
||||
<Table.Th>Отдел</Table.Th>
|
||||
<Table.Th>Категория</Table.Th>
|
||||
<Table.Th>Тема</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{gaps.map((g, i) => (
|
||||
<Table.Tr key={`${g.user_id}-${g.topic_id}-${i}`}>
|
||||
<Table.Td>
|
||||
<Text size="sm" fw={500}>{g.full_name || `ID: ${g.user_id}`}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" c="dimmed">{g.department_name || '—'}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge size="sm" variant="light" color="violet">
|
||||
{g.category_name || '—'}
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm">{g.topic_name || `ID: ${g.topic_id}`}</Text>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</ScrollArea.Autosize>
|
||||
)}
|
||||
</Stack>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: calc(100dvh - 68px);
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.section {
|
||||
padding: var(--mantine-spacing-md) var(--mantine-spacing-lg);
|
||||
}
|
||||
|
||||
.tabsList {
|
||||
padding: 0 var(--mantine-spacing-lg);
|
||||
}
|
||||
|
||||
.footer {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
margin-top: auto;
|
||||
padding: var(--mantine-spacing-sm) var(--mantine-spacing-lg);
|
||||
background: var(--mantine-color-body);
|
||||
border-top: 1px solid var(--mantine-color-default-border);
|
||||
}
|
||||
|
||||
.infoRow + .infoRow {
|
||||
border-top: 1px solid var(--mantine-color-default-border);
|
||||
}
|
||||
|
||||
.pickRow {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border-radius: var(--mantine-radius-md);
|
||||
transition: background-color 120ms ease;
|
||||
}
|
||||
|
||||
.pickRow:hover {
|
||||
background-color: var(--mantine-color-default-hover);
|
||||
}
|
||||
|
||||
.pickRow[data-selected] {
|
||||
background-color: var(--mantine-primary-color-light);
|
||||
}
|
||||
|
|
@ -0,0 +1,398 @@
|
|||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import {
|
||||
ActionIcon,
|
||||
Avatar,
|
||||
Box,
|
||||
Button,
|
||||
Checkbox,
|
||||
CopyButton,
|
||||
Drawer,
|
||||
Group,
|
||||
ScrollArea,
|
||||
Select,
|
||||
Skeleton,
|
||||
Stack,
|
||||
Switch,
|
||||
Tabs,
|
||||
Text,
|
||||
TextInput,
|
||||
Tooltip,
|
||||
UnstyledButton,
|
||||
} from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { IconCheck, IconCopy, IconSearch } from '@tabler/icons-react'
|
||||
import dayjs from 'dayjs'
|
||||
import { useUser, useUpdateUser } from '@/features/users/hooks/useUsers'
|
||||
import { useDepartments } from '@/features/users/hooks/useDepartments'
|
||||
import { useRoles } from '@/features/users/hooks/useRoles'
|
||||
import { useUserRoles, useBulkAssignRoles } from '@/features/users/hooks/useUserRoles'
|
||||
import { ConfirmModal } from '@/components/ui/ConfirmModal'
|
||||
import { StatusBadge, userStatusOf } from '@/components/ui/StatusBadge'
|
||||
import CopyRolesPanel from './CopyRolesPanel'
|
||||
import classes from './UserDrawer.module.css'
|
||||
|
||||
interface Props {
|
||||
userId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const EMPTY = {
|
||||
full_name: '',
|
||||
department_id: null as number | null,
|
||||
is_blocked: false,
|
||||
is_fired: false,
|
||||
role_ids: [] as number[],
|
||||
}
|
||||
|
||||
function InfoRow({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<Group justify="space-between" wrap="nowrap" py={8} className={classes.infoRow}>
|
||||
<Text size="sm" c="dimmed">{label}</Text>
|
||||
<Group gap={4} wrap="nowrap">{children}</Group>
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
|
||||
export default function UserEditDrawer({ userId, opened, onClose }: Props) {
|
||||
const { data: user, isLoading: userLoading } = useUser(userId)
|
||||
const { data: departments } = useDepartments()
|
||||
const { data: allRoles } = useRoles({ limit: 1000 })
|
||||
const { data: userRoles, isLoading: rolesLoading } = useUserRoles(userId)
|
||||
|
||||
const updateUser = useUpdateUser()
|
||||
const assignRoles = useBulkAssignRoles()
|
||||
|
||||
const [tab, setTab] = useState<string | null>('profile')
|
||||
const [view, setView] = useState<'edit' | 'copy'>('edit')
|
||||
const [roleQuery, setRoleQuery] = useState('')
|
||||
const [confirmClose, setConfirmClose] = useState(false)
|
||||
const initializedFor = useRef<number | null>(null)
|
||||
|
||||
const form = useForm({
|
||||
initialValues: EMPTY,
|
||||
validate: {
|
||||
full_name: (v) => (v.trim() ? null : 'Укажите ФИО'),
|
||||
},
|
||||
})
|
||||
|
||||
const isLoading = userLoading || rolesLoading
|
||||
const isSubmitting = updateUser.isPending || assignRoles.isPending
|
||||
|
||||
// Инициализация формы: один раз за открытие, чтобы фоновые обновления данных не затирали правки
|
||||
useEffect(() => {
|
||||
if (!opened || isLoading || !user || initializedFor.current === userId) return
|
||||
|
||||
const fromApi = Array.isArray(userRoles)
|
||||
? userRoles.map((ur) => ur.role?.id || ur.role_id).filter((id): id is number => !!id)
|
||||
: []
|
||||
const fromUser = Array.isArray(user.user_roles)
|
||||
? user.user_roles.map((ur) => ur.role_id).filter((id): id is number => !!id)
|
||||
: []
|
||||
|
||||
const values = {
|
||||
full_name: user.full_name || '',
|
||||
department_id: user.department_id || null,
|
||||
is_blocked: user.is_blocked || false,
|
||||
is_fired: user.is_fired || false,
|
||||
role_ids: fromApi.length > 0 ? fromApi : fromUser,
|
||||
}
|
||||
form.setValues(values)
|
||||
form.resetDirty(values)
|
||||
initializedFor.current = userId
|
||||
}, [opened, isLoading, user, userRoles, userId])
|
||||
|
||||
// Сброс локального состояния при закрытии
|
||||
useEffect(() => {
|
||||
if (!opened) {
|
||||
initializedFor.current = null
|
||||
setTab('profile')
|
||||
setView('edit')
|
||||
setRoleQuery('')
|
||||
setConfirmClose(false)
|
||||
}
|
||||
}, [opened])
|
||||
|
||||
const requestClose = () => (form.isDirty() ? setConfirmClose(true) : onClose())
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
if (!userId) return
|
||||
await updateUser.mutateAsync({
|
||||
id: userId,
|
||||
full_name: values.full_name.trim(),
|
||||
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 = useMemo(
|
||||
() => (Array.isArray(departments) ? departments.map((d) => ({ value: String(d.id), label: d.name || '' })) : []),
|
||||
[departments],
|
||||
)
|
||||
|
||||
const roleItems = useMemo(
|
||||
() =>
|
||||
Array.isArray(allRoles)
|
||||
? allRoles.map((r) => ({ id: r.id as number, name: r.name || '', description: r.description as string | undefined }))
|
||||
: [],
|
||||
[allRoles],
|
||||
)
|
||||
|
||||
const filteredRoles = useMemo(() => {
|
||||
const q = roleQuery.trim().toLowerCase()
|
||||
if (!q) return roleItems
|
||||
return roleItems.filter((r) => r.name.toLowerCase().includes(q) || (r.description ?? '').toLowerCase().includes(q))
|
||||
}, [roleItems, roleQuery])
|
||||
|
||||
const selected = useMemo(() => new Set(form.values.role_ids), [form.values.role_ids])
|
||||
|
||||
const toggleRole = (id: number) =>
|
||||
form.setFieldValue(
|
||||
'role_ids',
|
||||
selected.has(id) ? form.values.role_ids.filter((x) => x !== id) : [...form.values.role_ids, id],
|
||||
)
|
||||
|
||||
const applyCopiedRoles = (roleIds: number[], mode: 'replace' | 'merge') => {
|
||||
form.setFieldValue('role_ids', mode === 'merge' ? Array.from(new Set([...form.values.role_ids, ...roleIds])) : roleIds)
|
||||
setView('edit')
|
||||
setTab('roles')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Drawer.Root
|
||||
opened={opened}
|
||||
onClose={requestClose}
|
||||
position="right"
|
||||
size="min(560px, 100vw)"
|
||||
trapFocus
|
||||
>
|
||||
<Drawer.Overlay backgroundOpacity={0.25} />
|
||||
<Drawer.Content>
|
||||
{view === 'copy' ? (
|
||||
<CopyRolesPanel
|
||||
currentUserId={userId}
|
||||
onBack={() => setView('edit')}
|
||||
onApply={applyCopiedRoles}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Drawer.Header>
|
||||
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
<Avatar size={36} radius="xl" color="initials" name={user?.full_name ?? ''} />
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text fw={600} truncate>{user?.full_name || 'Пользователь'}</Text>
|
||||
<Group gap={8} wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">ID {userId}</Text>
|
||||
{user && <StatusBadge kind="user" status={userStatusOf(user)} />}
|
||||
</Group>
|
||||
</Box>
|
||||
</Group>
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body className={classes.body}>
|
||||
{isLoading ? (
|
||||
<Stack className={classes.section} gap="md">
|
||||
<Skeleton h={32} />
|
||||
<Skeleton h={96} />
|
||||
<Skeleton h={36} />
|
||||
<Skeleton h={36} />
|
||||
</Stack>
|
||||
) : !user ? (
|
||||
<Text className={classes.section} c="dimmed" size="sm">Пользователь не найден</Text>
|
||||
) : (
|
||||
<form
|
||||
style={{ display: 'contents' }}
|
||||
onSubmit={form.onSubmit(handleSubmit, () => setTab('profile'))}
|
||||
>
|
||||
<Tabs value={tab} onChange={setTab}>
|
||||
<Tabs.List className={classes.tabsList}>
|
||||
<Tabs.Tab value="profile">Профиль</Tabs.Tab>
|
||||
<Tabs.Tab
|
||||
value="roles"
|
||||
rightSection={
|
||||
<Text span size="xs" c="dimmed">{form.values.role_ids.length}</Text>
|
||||
}
|
||||
>
|
||||
Роли
|
||||
</Tabs.Tab>
|
||||
<Tabs.Tab value="access">Доступ</Tabs.Tab>
|
||||
</Tabs.List>
|
||||
|
||||
<Tabs.Panel value="profile" className={classes.section}>
|
||||
<Stack gap="lg">
|
||||
<Box>
|
||||
<InfoRow label="Telegram ID">
|
||||
<Text size="sm" ff="monospace">{user.telegram_id}</Text>
|
||||
<CopyButton value={String(user.telegram_id)} timeout={1500}>
|
||||
{({ copied, copy }) => (
|
||||
<Tooltip label={copied ? 'Скопировано' : 'Копировать'}>
|
||||
<ActionIcon size="sm" onClick={copy} aria-label="Копировать Telegram ID">
|
||||
{copied ? <IconCheck size={14} /> : <IconCopy size={14} />}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
</CopyButton>
|
||||
</InfoRow>
|
||||
{user.username && (
|
||||
<InfoRow label="Username">
|
||||
<Text size="sm">@{user.username}</Text>
|
||||
</InfoRow>
|
||||
)}
|
||||
{user.last_login && (
|
||||
<InfoRow label="Последний вход">
|
||||
<Text size="sm">{dayjs(user.last_login).format('D MMM YYYY, HH:mm')}</Text>
|
||||
</InfoRow>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<TextInput
|
||||
label="ФИО"
|
||||
placeholder="Иванов Иван Иванович"
|
||||
withAsterisk
|
||||
{...form.getInputProps('full_name')}
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Отдел"
|
||||
placeholder="Не назначен"
|
||||
data={departmentOptions}
|
||||
value={form.values.department_id ? String(form.values.department_id) : null}
|
||||
onChange={(v) => form.setFieldValue('department_id', v ? Number(v) : null)}
|
||||
searchable
|
||||
clearable
|
||||
/>
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
|
||||
<Tabs.Panel value="roles" className={classes.section}>
|
||||
<Stack gap="sm">
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Text size="sm" c="dimmed">
|
||||
Выбрано {form.values.role_ids.length} из {roleItems.length}
|
||||
</Text>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<Button
|
||||
size="compact-sm"
|
||||
variant="subtle"
|
||||
leftSection={<IconCopy size={14} />}
|
||||
onClick={() => setView('copy')}
|
||||
>
|
||||
Скопировать от…
|
||||
</Button>
|
||||
<Button
|
||||
size="compact-sm"
|
||||
variant="subtle"
|
||||
color="red"
|
||||
disabled={form.values.role_ids.length === 0}
|
||||
onClick={() => form.setFieldValue('role_ids', [])}
|
||||
>
|
||||
Снять все
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<TextInput
|
||||
placeholder="Поиск по ролям"
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={roleQuery}
|
||||
onChange={(e) => setRoleQuery(e.currentTarget.value)}
|
||||
/>
|
||||
|
||||
<ScrollArea.Autosize mah="calc(100dvh - 330px)" type="auto" mx={-6}>
|
||||
<Stack gap={2} px={6}>
|
||||
{filteredRoles.map((r) => (
|
||||
<UnstyledButton
|
||||
key={r.id}
|
||||
className={classes.pickRow}
|
||||
data-selected={selected.has(r.id) || undefined}
|
||||
role="checkbox"
|
||||
aria-checked={selected.has(r.id)}
|
||||
onClick={() => toggleRole(r.id)}
|
||||
>
|
||||
<Group gap="sm" wrap="nowrap" align="flex-start">
|
||||
<Checkbox
|
||||
checked={selected.has(r.id)}
|
||||
readOnly
|
||||
tabIndex={-1}
|
||||
aria-hidden
|
||||
mt={2}
|
||||
style={{ pointerEvents: 'none' }}
|
||||
/>
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text size="sm" fw={500}>{r.name}</Text>
|
||||
{r.description && (
|
||||
<Text size="xs" c="dimmed" lineClamp={2}>{r.description}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
))}
|
||||
{filteredRoles.length === 0 && (
|
||||
<Text size="sm" c="dimmed" ta="center" py="lg">Ничего не найдено</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</ScrollArea.Autosize>
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
|
||||
<Tabs.Panel value="access" className={classes.section}>
|
||||
<Stack gap="lg">
|
||||
<Switch
|
||||
label="Заблокирован"
|
||||
description="Пользователь не сможет пользоваться системой"
|
||||
color="red"
|
||||
checked={form.values.is_blocked}
|
||||
onChange={(e) => form.setFieldValue('is_blocked', e.currentTarget.checked)}
|
||||
/>
|
||||
<Switch
|
||||
label="Уволен"
|
||||
description="Пользователь больше не работает в компании"
|
||||
color="gray"
|
||||
checked={form.values.is_fired}
|
||||
onChange={(e) => form.setFieldValue('is_fired', e.currentTarget.checked)}
|
||||
/>
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
</Tabs>
|
||||
|
||||
<Group className={classes.footer} justify="space-between" wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">
|
||||
{form.isDirty() ? 'Есть несохранённые изменения' : ''}
|
||||
</Text>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Button variant="default" onClick={requestClose} disabled={isSubmitting}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting} disabled={!form.isDirty()}>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
</form>
|
||||
)}
|
||||
</Drawer.Body>
|
||||
</>
|
||||
)}
|
||||
</Drawer.Content>
|
||||
</Drawer.Root>
|
||||
|
||||
<ConfirmModal
|
||||
opened={confirmClose}
|
||||
onClose={() => setConfirmClose(false)}
|
||||
onConfirm={() => {
|
||||
setConfirmClose(false)
|
||||
onClose()
|
||||
}}
|
||||
title="Закрыть без сохранения?"
|
||||
message="Внесённые изменения будут потеряны."
|
||||
confirmLabel="Закрыть"
|
||||
danger
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,212 +0,0 @@
|
|||
import { useEffect } from 'react'
|
||||
import {
|
||||
Modal,
|
||||
Stack,
|
||||
TextInput,
|
||||
Select,
|
||||
MultiSelect,
|
||||
Switch,
|
||||
Group,
|
||||
Button,
|
||||
Text,
|
||||
Divider,
|
||||
Loader,
|
||||
Center,
|
||||
Badge,
|
||||
Paper,
|
||||
} from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { useUser, useUpdateUser } from '@/features/users/hooks/useUsers'
|
||||
import { useDepartments } from '@/features/users/hooks/useDepartments'
|
||||
import { useRoles } from '@/features/users/hooks/useRoles'
|
||||
import { useUserRoles, useBulkAssignRoles } from '@/features/users/hooks/useUserRoles'
|
||||
|
||||
interface UserEditModalProps {
|
||||
userId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function UserEditModal({ userId, opened, onClose }: UserEditModalProps) {
|
||||
const { data: user, isLoading: userLoading } = useUser(userId)
|
||||
const { data: departments } = useDepartments()
|
||||
const { data: allRoles } = useRoles()
|
||||
const { data: userRoles, isLoading: rolesLoading } = useUserRoles(userId)
|
||||
|
||||
const updateUser = useUpdateUser()
|
||||
const assignRoles = useBulkAssignRoles()
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
department_id: null as number | null,
|
||||
is_blocked: false,
|
||||
is_fired: false,
|
||||
role_ids: [] as number[],
|
||||
},
|
||||
})
|
||||
|
||||
// Заполняем форму данными пользователя
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
form.setValues({
|
||||
department_id: user.department_id || null,
|
||||
is_blocked: user.is_blocked || false,
|
||||
is_fired: user.is_fired || false,
|
||||
role_ids: user.user_roles?.map((ur) => ur.role_id!) || [],
|
||||
})
|
||||
}
|
||||
}, [user])
|
||||
|
||||
// Заполняем роли из отдельного запроса
|
||||
useEffect(() => {
|
||||
if (userRoles && userRoles.length > 0) {
|
||||
const roleIds = userRoles
|
||||
.map((ur) => ur.role?.id || ur.role_id)
|
||||
.filter((id): id is number => !!id)
|
||||
form.setFieldValue('role_ids', roleIds)
|
||||
}
|
||||
}, [userRoles])
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
if (!userId) return
|
||||
|
||||
// Обновляем пользователя
|
||||
await updateUser.mutateAsync({
|
||||
id: userId,
|
||||
department_id: values.department_id,
|
||||
is_blocked: values.is_blocked,
|
||||
is_fired: values.is_fired,
|
||||
})
|
||||
|
||||
// Обновляем роли
|
||||
await assignRoles.mutateAsync({
|
||||
user_id: userId,
|
||||
role_ids: values.role_ids,
|
||||
})
|
||||
|
||||
onClose()
|
||||
}
|
||||
|
||||
const departmentOptions = departments?.map((d) => ({
|
||||
value: String(d.id),
|
||||
label: d.name || '',
|
||||
})) || []
|
||||
|
||||
const roleOptions = allRoles?.map((r) => ({
|
||||
value: String(r.id),
|
||||
label: r.name || '',
|
||||
description: r.description,
|
||||
})) || []
|
||||
|
||||
const isLoading = userLoading || rolesLoading
|
||||
const isSubmitting = updateUser.isPending || assignRoles.isPending
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={
|
||||
<Group>
|
||||
<Text fw={700}>Редактирование пользователя</Text>
|
||||
{user && <Badge variant="light">ID: {user.id}</Badge>}
|
||||
</Group>
|
||||
}
|
||||
size="lg"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Center p={40}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : user ? (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="md">
|
||||
{/* Информация о пользователе (только для чтения) */}
|
||||
<Paper withBorder p="md" bg="gray.0">
|
||||
<Stack gap="xs">
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Имя:</Text>
|
||||
<Text fw={500}>{user.full_name}</Text>
|
||||
</Group>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Telegram ID:</Text>
|
||||
<Text ff="monospace">{user.telegram_id}</Text>
|
||||
</Group>
|
||||
{user.username && (
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Username:</Text>
|
||||
<Text>@{user.username}</Text>
|
||||
</Group>
|
||||
)}
|
||||
{user.last_login && (
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Последний вход:</Text>
|
||||
<Text size="sm">
|
||||
{new Date(user.last_login).toLocaleString('ru-RU')}
|
||||
</Text>
|
||||
</Group>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
<Divider label="Настройки" labelPosition="center" />
|
||||
|
||||
{/* Отдел */}
|
||||
<Select
|
||||
label="Отдел"
|
||||
placeholder="Не назначен"
|
||||
data={departmentOptions}
|
||||
value={form.values.department_id ? String(form.values.department_id) : null}
|
||||
onChange={(v) => form.setFieldValue('department_id', v ? Number(v) : null)}
|
||||
clearable
|
||||
/>
|
||||
|
||||
{/* Роли */}
|
||||
<MultiSelect
|
||||
label="Роли"
|
||||
placeholder="Выберите роли"
|
||||
data={roleOptions}
|
||||
value={form.values.role_ids.map(String)}
|
||||
onChange={(v) => form.setFieldValue('role_ids', v.map(Number))}
|
||||
searchable
|
||||
clearable
|
||||
description="Пользователь может иметь несколько ролей"
|
||||
/>
|
||||
|
||||
<Divider />
|
||||
|
||||
{/* Статусы */}
|
||||
<Switch
|
||||
label="Заблокирован"
|
||||
description="Пользователь не сможет пользоваться системой"
|
||||
checked={form.values.is_blocked}
|
||||
onChange={(e) => form.setFieldValue('is_blocked', e.currentTarget.checked)}
|
||||
color="red"
|
||||
/>
|
||||
|
||||
<Switch
|
||||
label="Уволен"
|
||||
description="Пользователь больше не работает в компании"
|
||||
checked={form.values.is_fired}
|
||||
onChange={(e) => form.setFieldValue('is_fired', e.currentTarget.checked)}
|
||||
color="gray"
|
||||
/>
|
||||
|
||||
{/* Кнопки */}
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting}>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
) : (
|
||||
<Center p={40}>
|
||||
<Text c="dimmed">Пользователь не найден</Text>
|
||||
</Center>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
import { ActionIcon, useComputedColorScheme, useMantineColorScheme } from '@mantine/core'
|
||||
import { IconMoon, IconSun } from '@tabler/icons-react'
|
||||
|
||||
export function ColorSchemeToggle() {
|
||||
const { setColorScheme } = useMantineColorScheme()
|
||||
const computed = useComputedColorScheme('light', { getInitialValueInEffect: true })
|
||||
|
||||
return (
|
||||
<ActionIcon
|
||||
size="lg"
|
||||
aria-label="Переключить тему"
|
||||
onClick={() => setColorScheme(computed === 'light' ? 'dark' : 'light')}
|
||||
>
|
||||
{computed === 'dark' ? <IconSun size={18} stroke={1.6} /> : <IconMoon size={18} stroke={1.6} />}
|
||||
</ActionIcon>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import { Button, Group, Modal, Text } from '@mantine/core'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
interface Props {
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
onConfirm: () => void
|
||||
title: string
|
||||
message: ReactNode
|
||||
confirmLabel?: string
|
||||
danger?: boolean
|
||||
loading?: boolean
|
||||
}
|
||||
|
||||
export function ConfirmModal({
|
||||
opened, onClose, onConfirm, title, message, confirmLabel = 'Подтвердить', danger, loading,
|
||||
}: Props) {
|
||||
return (
|
||||
<Modal opened={opened} onClose={onClose} title={title} size="sm">
|
||||
<Text size="sm" c="dimmed">{message}</Text>
|
||||
<Group justify="flex-end" gap="xs" mt="lg">
|
||||
<Button variant="default" onClick={onClose} disabled={loading}>Отмена</Button>
|
||||
<Button color={danger ? 'red' : undefined} onClick={onConfirm} loading={loading}>
|
||||
{confirmLabel}
|
||||
</Button>
|
||||
</Group>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
import { Group, Pagination, Paper, Skeleton, Table, Text } from '@mantine/core'
|
||||
import type { ReactNode } from 'react'
|
||||
import { EmptyState } from './EmptyState'
|
||||
|
||||
export interface Column<T> {
|
||||
key: string
|
||||
header: ReactNode
|
||||
cell: (row: T) => ReactNode
|
||||
width?: number | string
|
||||
align?: 'left' | 'right' | 'center'
|
||||
}
|
||||
|
||||
interface Props<T> {
|
||||
columns: Column<T>[]
|
||||
rows: T[]
|
||||
getRowId: (row: T) => string | number
|
||||
loading?: boolean // первая загрузка: показываем скелетоны
|
||||
refreshing?: boolean // перезапрос: приглушаем строки
|
||||
onRowClick?: (row: T) => void
|
||||
empty?: { title: string; description?: string }
|
||||
pagination?: { page: number; pageSize: number; total: number; onChange: (page: number) => void }
|
||||
minWidth?: number
|
||||
}
|
||||
|
||||
export function DataTable<T>({
|
||||
columns, rows, getRowId, loading, refreshing, onRowClick,
|
||||
empty = { title: 'Ничего не найдено' }, pagination, minWidth = 800,
|
||||
}: Props<T>) {
|
||||
const pages = pagination ? Math.max(1, Math.ceil(pagination.total / pagination.pageSize)) : 1
|
||||
const from = pagination ? (pagination.page - 1) * pagination.pageSize + 1 : 0
|
||||
const to = pagination ? Math.min(pagination.page * pagination.pageSize, pagination.total) : 0
|
||||
|
||||
return (
|
||||
<Paper style={{ overflow: 'hidden' }}>
|
||||
<Table.ScrollContainer minWidth={minWidth}>
|
||||
<Table highlightOnHover={!!onRowClick}>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
{columns.map((c) => (
|
||||
<Table.Th key={c.key} w={c.width} ta={c.align} fz="xs" fw={500} c="dimmed">
|
||||
{c.header}
|
||||
</Table.Th>
|
||||
))}
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
|
||||
<Table.Tbody style={{ opacity: refreshing && !loading ? 0.55 : 1, transition: 'opacity 120ms' }}>
|
||||
{loading
|
||||
? Array.from({ length: 8 }).map((_, r) => (
|
||||
<Table.Tr key={r}>
|
||||
{columns.map((c, i) => (
|
||||
<Table.Td key={c.key}>
|
||||
<Skeleton h={12} w={`${55 + ((r * 7 + i * 13) % 35)}%`} />
|
||||
</Table.Td>
|
||||
))}
|
||||
</Table.Tr>
|
||||
))
|
||||
: rows.map((row) => (
|
||||
<Table.Tr
|
||||
key={getRowId(row)}
|
||||
onClick={onRowClick ? () => onRowClick(row) : undefined}
|
||||
style={{ cursor: onRowClick ? 'pointer' : undefined }}
|
||||
>
|
||||
{columns.map((c) => (
|
||||
<Table.Td key={c.key} ta={c.align}>{c.cell(row)}</Table.Td>
|
||||
))}
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Table.ScrollContainer>
|
||||
|
||||
{!loading && rows.length === 0 && (
|
||||
<EmptyState title={empty.title} description={empty.description} />
|
||||
)}
|
||||
|
||||
{pagination && pagination.total > pagination.pageSize && (
|
||||
<Group
|
||||
justify="space-between"
|
||||
px="md"
|
||||
py="sm"
|
||||
style={{ borderTop: '1px solid var(--mantine-color-default-border)' }}
|
||||
>
|
||||
<Text size="xs" c="dimmed">{from}–{to} из {pagination.total}</Text>
|
||||
<Pagination size="sm" value={pagination.page} total={pages} onChange={pagination.onChange} />
|
||||
</Group>
|
||||
)}
|
||||
</Paper>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { Center, Stack, Text, ThemeIcon } from '@mantine/core'
|
||||
import { IconInbox, type Icon } from '@tabler/icons-react'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
description?: string
|
||||
icon?: Icon
|
||||
action?: ReactNode
|
||||
}
|
||||
|
||||
export function EmptyState({ title, description, icon: Icon = IconInbox, action }: Props) {
|
||||
return (
|
||||
<Center py={56}>
|
||||
<Stack align="center" gap="xs" maw={320} ta="center">
|
||||
<ThemeIcon variant="light" color="gray" size={44} radius="xl">
|
||||
<Icon size={22} stroke={1.5} />
|
||||
</ThemeIcon>
|
||||
<Text fw={600}>{title}</Text>
|
||||
{description && <Text size="sm" c="dimmed">{description}</Text>}
|
||||
{action}
|
||||
</Stack>
|
||||
</Center>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
import { ActionIcon, Box, Divider, Group, Stack, Text, ThemeIcon, Tooltip } from '@mantine/core'
|
||||
import { IconDownload, IconEye, IconFileText } from '@tabler/icons-react'
|
||||
import { formatFileSize, getMimeType, isPreviewable } from '@/lib/fileApi'
|
||||
|
||||
export interface FileItem {
|
||||
id?: number
|
||||
file_name?: string
|
||||
file_base64?: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
files: FileItem[]
|
||||
onPreview: (file: { id: number; name: string; type: string }) => void
|
||||
onDownload: (id: number, name: string) => void
|
||||
}
|
||||
|
||||
export function FileList({ files, onPreview, onDownload }: Props) {
|
||||
return (
|
||||
<Stack gap={0}>
|
||||
{files.map((file, i) => {
|
||||
const name = file.file_name || 'Без имени'
|
||||
const mime = getMimeType(name)
|
||||
const kb = file.file_base64 ? Math.round((file.file_base64.length * 3) / 4 / 1024) : 0
|
||||
return (
|
||||
<Box key={file.id ?? i}>
|
||||
{i > 0 && <Divider />}
|
||||
<Group justify="space-between" wrap="nowrap" py={8}>
|
||||
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
<ThemeIcon variant="light" color="gray" size={32} radius="md">
|
||||
<IconFileText size={16} stroke={1.6} />
|
||||
</ThemeIcon>
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text size="sm" fw={500} truncate>{name}</Text>
|
||||
{kb > 0 && <Text size="xs" c="dimmed">{formatFileSize(kb)}</Text>}
|
||||
</Box>
|
||||
</Group>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
{isPreviewable(mime) && (
|
||||
<Tooltip label="Предпросмотр">
|
||||
<ActionIcon
|
||||
aria-label="Предпросмотр"
|
||||
onClick={() => onPreview({ id: file.id!, name, type: mime })}
|
||||
>
|
||||
<IconEye size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip label="Скачать">
|
||||
<ActionIcon aria-label="Скачать" onClick={() => onDownload(file.id!, name)}>
|
||||
<IconDownload size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Group>
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import { Button, Group } from '@mantine/core'
|
||||
import { IconX } from '@tabler/icons-react'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
interface Props {
|
||||
children: ReactNode
|
||||
activeCount?: number
|
||||
onReset?: () => void
|
||||
}
|
||||
|
||||
export function FilterBar({ children, activeCount = 0, onReset }: Props) {
|
||||
return (
|
||||
<Group gap="sm" align="center">
|
||||
{children}
|
||||
{activeCount > 0 && onReset && (
|
||||
<Button
|
||||
variant="subtle"
|
||||
color="gray"
|
||||
size="sm"
|
||||
leftSection={<IconX size={14} />}
|
||||
onClick={onReset}
|
||||
>
|
||||
Сбросить · {activeCount}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { Children, type ReactNode } from 'react'
|
||||
import { Box, Divider, Group, Text } from '@mantine/core'
|
||||
|
||||
export function InfoList({ children }: { children: ReactNode }) {
|
||||
const items = Children.toArray(children).filter(Boolean)
|
||||
return (
|
||||
<Box>
|
||||
{items.map((item, i) => (
|
||||
<Box key={i}>
|
||||
{i > 0 && <Divider />}
|
||||
{item}
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export function InfoRow({ label, children }: { label: string; children: ReactNode }) {
|
||||
return (
|
||||
<Group justify="space-between" align="flex-start" wrap="nowrap" py={8} gap="md">
|
||||
<Text size="sm" c="dimmed" style={{ flexShrink: 0 }}>{label}</Text>
|
||||
<Group gap={4} wrap="nowrap" justify="flex-end" style={{ minWidth: 0 }}>{children}</Group>
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
import { useMemo, useState } from 'react'
|
||||
import { Badge, Button, Checkbox, Popover, ScrollArea, Stack, Text, TextInput } from '@mantine/core'
|
||||
import { IconChevronDown, IconSearch } from '@tabler/icons-react'
|
||||
|
||||
interface Props {
|
||||
label: string
|
||||
options: { value: string; label: string }[]
|
||||
value: string[]
|
||||
onChange: (value: string[]) => void
|
||||
width?: number
|
||||
}
|
||||
|
||||
export function MultiFilter({ label, options, value, onChange, width = 260 }: Props) {
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase()
|
||||
return q ? options.filter((o) => o.label.toLowerCase().includes(q)) : options
|
||||
}, [options, query])
|
||||
|
||||
return (
|
||||
<Popover position="bottom-start" shadow="md" width={width}>
|
||||
<Popover.Target>
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
fw={400}
|
||||
rightSection={<IconChevronDown size={14} />}
|
||||
>
|
||||
{label}
|
||||
{value.length > 0 && <Badge size="xs" circle variant="filled" ml={8}>{value.length}</Badge>}
|
||||
</Button>
|
||||
</Popover.Target>
|
||||
|
||||
<Popover.Dropdown p="xs">
|
||||
<TextInput
|
||||
size="xs"
|
||||
placeholder="Поиск"
|
||||
leftSection={<IconSearch size={14} />}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.currentTarget.value)}
|
||||
mb="xs"
|
||||
/>
|
||||
<ScrollArea.Autosize mah={260} type="auto">
|
||||
<Checkbox.Group value={value} onChange={onChange}>
|
||||
<Stack gap={8} p={4}>
|
||||
{filtered.map((o) => (
|
||||
<Checkbox key={o.value} value={o.value} label={o.label} size="sm" />
|
||||
))}
|
||||
</Stack>
|
||||
</Checkbox.Group>
|
||||
{filtered.length === 0 && (
|
||||
<Text size="xs" c="dimmed" ta="center" py="xs">Ничего не найдено</Text>
|
||||
)}
|
||||
</ScrollArea.Autosize>
|
||||
{value.length > 0 && (
|
||||
<Button variant="subtle" color="gray" size="compact-xs" mt="xs" onClick={() => onChange([])}>
|
||||
Очистить
|
||||
</Button>
|
||||
)}
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import { Group, Stack, Text, Title } from '@mantine/core'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
description?: string
|
||||
actions?: ReactNode
|
||||
}
|
||||
|
||||
export function PageHeader({ title, description, actions }: Props) {
|
||||
return (
|
||||
<Group justify="space-between" align="flex-start" wrap="nowrap">
|
||||
<Stack gap={2}>
|
||||
<Title order={3}>{title}</Title>
|
||||
{description && <Text size="sm" c="dimmed">{description}</Text>}
|
||||
</Stack>
|
||||
{actions && <Group gap="xs">{actions}</Group>}
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import { Group, Paper, Text } from '@mantine/core'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
interface Props {
|
||||
title: ReactNode
|
||||
extra?: ReactNode
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export function Panel({ title, extra, children }: Props) {
|
||||
return (
|
||||
<Paper p="md">
|
||||
<Group justify="space-between" wrap="nowrap" mb="md" mih={22}>
|
||||
<Text size="sm" fw={600}>{title}</Text>
|
||||
{extra}
|
||||
</Group>
|
||||
{children}
|
||||
</Paper>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
// Общая кнопка «Отчёт»: выбор периода и выгрузка в Excel.
|
||||
// Тот же паттерн, что в ApprovalsPage, — ReportButton там можно заменить на этот компонент.
|
||||
import { useState } from 'react'
|
||||
import { Button, Group, Popover, Stack, Text } from '@mantine/core'
|
||||
import { DatePicker } from '@mantine/dates'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import { IconDownload } from '@tabler/icons-react'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
export type DateRange = [Date | null, Date | null]
|
||||
|
||||
const PRESETS: { label: string; range: () => DateRange }[] = [
|
||||
{ label: 'Сегодня', range: () => [dayjs().startOf('day').toDate(), dayjs().endOf('day').toDate()] },
|
||||
{ label: 'Этот месяц', range: () => [dayjs().startOf('month').toDate(), dayjs().endOf('month').toDate()] },
|
||||
{
|
||||
label: 'Прошлый месяц',
|
||||
range: () => [
|
||||
dayjs().subtract(1, 'month').startOf('month').toDate(),
|
||||
dayjs().subtract(1, 'month').endOf('month').toDate(),
|
||||
],
|
||||
},
|
||||
{ label: 'Всё время', range: () => [null, null] },
|
||||
]
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
fileName: string // без расширения
|
||||
hint?: string
|
||||
onDownload: (range: DateRange) => Promise<BlobPart>
|
||||
}
|
||||
|
||||
export function ReportPopover({ title, fileName, hint, onDownload }: Props) {
|
||||
const [opened, setOpened] = useState(false)
|
||||
const [range, setRange] = useState<DateRange>([null, null])
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const download = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const blob = new Blob([await onDownload(range)], {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
})
|
||||
const url = window.URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `${fileName}_${dayjs().format('DD.MM.YYYY_HH-mm')}.xlsx`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
window.URL.revokeObjectURL(url)
|
||||
notifications.show({ title: 'Готово', message: 'Отчёт скачан', color: 'green' })
|
||||
setOpened(false)
|
||||
} catch {
|
||||
notifications.show({ title: 'Ошибка', message: 'Не удалось сформировать отчёт', color: 'red' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover opened={opened} onChange={setOpened} position="bottom-end" shadow="md" width={300}>
|
||||
<Popover.Target>
|
||||
<Button variant="default" leftSection={<IconDownload size={16} />} onClick={() => setOpened((o) => !o)}>
|
||||
Отчёт
|
||||
</Button>
|
||||
</Popover.Target>
|
||||
<Popover.Dropdown>
|
||||
<Stack gap="sm">
|
||||
<Stack gap={2}>
|
||||
<Text size="sm" fw={600}>{title}</Text>
|
||||
{hint && <Text size="xs" c="dimmed">{hint}</Text>}
|
||||
</Stack>
|
||||
<Group gap={6}>
|
||||
{PRESETS.map((p) => (
|
||||
<Button key={p.label} size="compact-xs" variant="default" onClick={() => setRange(p.range())}>
|
||||
{p.label}
|
||||
</Button>
|
||||
))}
|
||||
</Group>
|
||||
<DatePicker type="range" value={range} onChange={(v) => setRange(v as DateRange)} />
|
||||
<Button fullWidth leftSection={<IconDownload size={16} />} onClick={download} loading={loading}>
|
||||
Скачать XLSX
|
||||
</Button>
|
||||
</Stack>
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
import { Group, Paper, Text, ThemeIcon } from '@mantine/core'
|
||||
import type { Icon } from '@tabler/icons-react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import classes from './ui.module.css'
|
||||
|
||||
function Sparkline({ data, color }: { data: number[]; color: string }) {
|
||||
if (data.length < 2) return null
|
||||
const w = 72, h = 28
|
||||
const max = Math.max(...data, 1)
|
||||
const points = data
|
||||
.map((v, i) => `${(i / (data.length - 1)) * w},${h - 2 - (v / max) * (h - 4)}`)
|
||||
.join(' ')
|
||||
return (
|
||||
<svg width={w} height={h} aria-hidden>
|
||||
<polyline
|
||||
points={points}
|
||||
fill="none"
|
||||
stroke={`var(--mantine-color-${color}-filled)`}
|
||||
strokeWidth={1.6}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
interface Props {
|
||||
label: string
|
||||
value: ReactNode
|
||||
hint?: ReactNode
|
||||
icon: Icon
|
||||
color?: string
|
||||
to?: string
|
||||
spark?: number[]
|
||||
}
|
||||
|
||||
export function StatCard({ label, value, hint, icon: IconCmp, color = 'gray', to, spark }: Props) {
|
||||
const body = (
|
||||
<>
|
||||
<Group justify="space-between" align="flex-start" wrap="nowrap">
|
||||
<Text size="sm" c="dimmed" fw={500}>{label}</Text>
|
||||
<ThemeIcon variant="light" color={color} size={30} radius="md">
|
||||
<IconCmp size={16} stroke={1.7} />
|
||||
</ThemeIcon>
|
||||
</Group>
|
||||
<Group justify="space-between" align="flex-end" wrap="nowrap" mt={10}>
|
||||
<Text fz={28} fw={600} lh={1}>{value}</Text>
|
||||
{spark && <Sparkline data={spark} color={color} />}
|
||||
</Group>
|
||||
{hint && <Text size="xs" c="dimmed" mt={8}>{hint}</Text>}
|
||||
</>
|
||||
)
|
||||
|
||||
if (to) {
|
||||
return <Paper component={Link} to={to} p="md" className={classes.interactive}>{body}</Paper>
|
||||
}
|
||||
return <Paper p="md">{body}</Paper>
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import { Badge, type BadgeProps } from '@mantine/core'
|
||||
import { APPROVAL_STATUS, DECISION_STATUS, REVOCATION_STATUS, STEP_STATUS, TASK_STATUS, USER_STATUS } from './statuses'
|
||||
|
||||
const MAPS = {
|
||||
approval: APPROVAL_STATUS,
|
||||
task: TASK_STATUS,
|
||||
user: USER_STATUS,
|
||||
step: STEP_STATUS,
|
||||
decision: DECISION_STATUS,
|
||||
revocation: REVOCATION_STATUS,
|
||||
}
|
||||
|
||||
interface Props {
|
||||
kind: keyof typeof MAPS
|
||||
status: string
|
||||
size?: BadgeProps['size']
|
||||
}
|
||||
|
||||
// Заливка цветом + иконка: статус читается и по цвету, и по форме
|
||||
export function StatusBadge({ kind, status, size = 'md' }: Props) {
|
||||
const meta = MAPS[kind][status]
|
||||
const StatusIcon = meta?.icon
|
||||
return (
|
||||
<Badge
|
||||
variant="light"
|
||||
color={meta?.color ?? 'gray'}
|
||||
size={size}
|
||||
leftSection={StatusIcon ? <StatusIcon size={size === 'sm' ? 11 : 13} stroke={2.2} /> : undefined}
|
||||
>
|
||||
{meta?.label ?? status}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
export function userStatusOf(u: { is_blocked?: boolean; is_fired?: boolean }) {
|
||||
if (u.is_fired) return 'fired'
|
||||
if (u.is_blocked) return 'blocked'
|
||||
return 'active'
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
import { Box, Group, Progress, Stack, Text, UnstyledButton } from '@mantine/core'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { EmptyState } from './EmptyState'
|
||||
import type { StatusMeta } from './statuses'
|
||||
import classes from './ui.module.css'
|
||||
|
||||
interface Props {
|
||||
items: { status: string; count: number }[]
|
||||
meta: Record<string, StatusMeta>
|
||||
linkTo: (status: string) => string
|
||||
}
|
||||
|
||||
export function StatusBreakdown({ items, meta, linkTo }: Props) {
|
||||
const counts = new Map(items.map((i) => [i.status, i.count]))
|
||||
const rows = Object.entries(meta).map(([status, m]) => ({
|
||||
status,
|
||||
...m,
|
||||
count: counts.get(status) ?? 0,
|
||||
}))
|
||||
const total = rows.reduce((s, r) => s + r.count, 0)
|
||||
|
||||
if (total === 0) return <EmptyState title="Нет данных" />
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
<Progress.Root size={10} radius="xl">
|
||||
{rows
|
||||
.filter((r) => r.count > 0)
|
||||
.map((r) => (
|
||||
<Progress.Section key={r.status} value={(r.count / total) * 100} color={r.color} />
|
||||
))}
|
||||
</Progress.Root>
|
||||
|
||||
<Stack gap={2}>
|
||||
{rows.map((r) => (
|
||||
<UnstyledButton key={r.status} component={Link} to={linkTo(r.status)} className={classes.row}>
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Group gap={8} wrap="nowrap">
|
||||
<Box
|
||||
w={8}
|
||||
h={8}
|
||||
style={{ borderRadius: '50%', background: `var(--mantine-color-${r.color}-filled)` }}
|
||||
/>
|
||||
<Text size="sm" c={r.count === 0 ? 'dimmed' : undefined}>{r.plural}</Text>
|
||||
</Group>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Text size="sm" fw={500}>{r.count}</Text>
|
||||
<Text size="xs" c="dimmed" w={36} ta="right">
|
||||
{Math.round((r.count / total) * 100)}%
|
||||
</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
import { Box, Group, Text } from '@mantine/core'
|
||||
import dayjs from 'dayjs'
|
||||
import { CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'
|
||||
|
||||
export interface TrendSeries {
|
||||
key: string
|
||||
label: string
|
||||
color: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
data: Record<string, any>[]
|
||||
series: TrendSeries[]
|
||||
xKey?: string
|
||||
height?: number
|
||||
}
|
||||
|
||||
const tick = { fill: 'var(--mantine-color-dimmed)', fontSize: 12 }
|
||||
const colorOf = (c: string) => `var(--mantine-color-${c}-filled)`
|
||||
|
||||
export function TrendChart({ data, series, xKey = 'date', height = 220 }: Props) {
|
||||
const labels = Object.fromEntries(series.map((s) => [s.key, s.label]))
|
||||
|
||||
return (
|
||||
<>
|
||||
<Group gap="md" mb="xs">
|
||||
{series.map((s) => (
|
||||
<Group key={s.key} gap={6}>
|
||||
<Box w={8} h={8} style={{ borderRadius: '50%', background: colorOf(s.color) }} />
|
||||
<Text size="xs" c="dimmed">{s.label}</Text>
|
||||
</Group>
|
||||
))}
|
||||
</Group>
|
||||
|
||||
<ResponsiveContainer width="100%" height={height}>
|
||||
<LineChart data={data} margin={{ top: 8, right: 8, left: -20, bottom: 0 }}>
|
||||
<CartesianGrid vertical={false} stroke="var(--mantine-color-default-border)" />
|
||||
<XAxis
|
||||
dataKey={xKey}
|
||||
tickFormatter={(d) => dayjs(d).format('DD.MM')}
|
||||
tick={tick}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
/>
|
||||
<YAxis allowDecimals={false} tick={tick} tickLine={false} axisLine={false} />
|
||||
<Tooltip
|
||||
cursor={{ stroke: 'var(--mantine-color-default-border)' }}
|
||||
labelFormatter={(d) => dayjs(d).format('D MMMM')}
|
||||
formatter={(v: any, name: any) => [v, labels[name] ?? name]}
|
||||
contentStyle={{
|
||||
background: 'var(--mantine-color-body)',
|
||||
border: '1px solid var(--mantine-color-default-border)',
|
||||
borderRadius: 8,
|
||||
boxShadow: 'none',
|
||||
fontSize: 12,
|
||||
}}
|
||||
labelStyle={{ color: 'var(--mantine-color-dimmed)', marginBottom: 4 }}
|
||||
/>
|
||||
{series.map((s) => (
|
||||
<Line
|
||||
key={s.key}
|
||||
type="monotone"
|
||||
dataKey={s.key}
|
||||
stroke={colorOf(s.color)}
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
activeDot={{ r: 4 }}
|
||||
/>
|
||||
))}
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
import {
|
||||
IconArrowBackUp, IconBan, IconCheck, IconClock, IconHourglass, IconLock,
|
||||
IconMinus, IconPencil, IconRotate, IconUserOff, IconX, type Icon,
|
||||
} from '@tabler/icons-react'
|
||||
|
||||
export interface StatusMeta {
|
||||
label: string // для бейджа конкретной записи
|
||||
plural: string // для сводок и счётчиков
|
||||
color: string // цвет Mantine
|
||||
icon?: Icon // дублирует цвет формой, чтобы статусы различались и без него
|
||||
}
|
||||
|
||||
export const APPROVAL_STATUS: Record<string, StatusMeta> = {
|
||||
pending: { label: 'На согласовании', plural: 'На согласовании', color: 'blue', icon: IconClock },
|
||||
revision: { label: 'На доработке', plural: 'На доработке', color: 'violet', icon: IconArrowBackUp },
|
||||
approved: { label: 'Согласована', plural: 'Согласованы', color: 'green', icon: IconCheck },
|
||||
rejected: { label: 'Отклонена', plural: 'Отклонены', color: 'red', icon: IconX },
|
||||
revoked: { label: 'Отозвана', plural: 'Отозваны', color: 'orange', icon: IconRotate },
|
||||
draft: { label: 'Черновик', plural: 'Черновики', color: 'gray', icon: IconPencil },
|
||||
}
|
||||
|
||||
export const TASK_STATUS: Record<string, StatusMeta> = {
|
||||
pending: { label: 'В работе', plural: 'В работе', color: 'blue', icon: IconClock },
|
||||
waiting: { label: 'В очереди', plural: 'В очереди', color: 'gray', icon: IconHourglass },
|
||||
completed: { label: 'Выполнена', plural: 'Выполнены', color: 'green', icon: IconCheck },
|
||||
cancelled: { label: 'Отменена', plural: 'Отменены', color: 'red', icon: IconX },
|
||||
// ⚠️ В типе задачи есть 'cancellation' — уточните, что это за статус, и поправьте подпись
|
||||
cancellation: { label: 'Отменяется', plural: 'Отменяются', color: 'orange', icon: IconBan },
|
||||
}
|
||||
|
||||
export const USER_STATUS: Record<string, StatusMeta> = {
|
||||
active: { label: 'Активен', plural: 'Активные', color: 'green', icon: IconCheck },
|
||||
blocked: { label: 'Заблокирован', plural: 'Заблокированные', color: 'red', icon: IconLock },
|
||||
fired: { label: 'Уволен', plural: 'Уволенные', color: 'gray', icon: IconUserOff },
|
||||
}
|
||||
|
||||
// Шаг согласования (используется в ApprovalDetailsDrawer)
|
||||
export const STEP_STATUS: Record<string, StatusMeta> = {
|
||||
pending: { label: 'Ожидает', plural: 'Ожидают', color: 'blue', icon: IconClock },
|
||||
waiting: { label: 'В очереди', plural: 'В очереди', color: 'gray', icon: IconHourglass },
|
||||
approved: { label: 'Согласовал', plural: 'Согласовали', color: 'green', icon: IconCheck },
|
||||
rejected: { label: 'Отклонил', plural: 'Отклонили', color: 'red', icon: IconX },
|
||||
cancelled_any_of: { label: 'Закрыт другим согласующим', plural: 'Закрыты', color: 'gray', icon: IconMinus },
|
||||
}
|
||||
|
||||
// Решение дополнительного согласующего
|
||||
export const DECISION_STATUS: Record<string, StatusMeta> = {
|
||||
pending: { label: 'Ожидает', plural: 'Ожидают', color: 'blue', icon: IconClock },
|
||||
approved: { label: 'Согласовал', plural: 'Согласовали', color: 'green', icon: IconCheck },
|
||||
rejected: { label: 'Отклонил', plural: 'Отклонили', color: 'red', icon: IconX },
|
||||
}
|
||||
|
||||
// Ответ на запрос об отзыве заявки
|
||||
export const REVOCATION_STATUS: Record<string, StatusMeta> = {
|
||||
pending: { label: 'Ожидает ответа', plural: 'Ожидают', color: 'blue', icon: IconClock },
|
||||
approved: { label: 'Одобрил отзыв', plural: 'Одобрили', color: 'green', icon: IconCheck },
|
||||
rejected: { label: 'Против отзыва', plural: 'Против', color: 'red', icon: IconX },
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
.interactive,
|
||||
.row {
|
||||
display: block;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
transition: background-color 120ms ease;
|
||||
}
|
||||
|
||||
.interactive:hover,
|
||||
.row:hover {
|
||||
background-color: var(--mantine-color-default-hover);
|
||||
}
|
||||
|
||||
.row {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
border-radius: var(--mantine-radius-sm);
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { adminLogsApi, type AdminLogsListParams } from '@/api/adminLogs'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
|
||||
export const ADMIN_LOGS_QUERY_KEY = 'admin-logs'
|
||||
|
||||
export function useAdminLogs(params: AdminLogsListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: [ADMIN_LOGS_QUERY_KEY, params],
|
||||
queryFn: async () => {
|
||||
const response = await adminLogsApi.getList(params)
|
||||
return response.data
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeleteAdminLog() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => adminLogsApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [ADMIN_LOGS_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Запись журнала удалена',
|
||||
color: 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось удалить запись (доступно только root-администратору)',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -20,7 +20,7 @@ export function useCreateAdmin() {
|
|||
return useMutation({
|
||||
mutationFn: async (data: CreateAdminRequest) => {
|
||||
const response = await adminsApi.create(data)
|
||||
return response.data // ✅ Извлекаем Admin из AxiosResponse
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [ADMINS_QUERY_KEY] })
|
||||
|
|
@ -33,6 +33,10 @@ export function useCreateAdmin() {
|
|||
message = 'Администратор с таким логином уже существует'
|
||||
} else if (errorMsg === 'only_root_can_create_admins') {
|
||||
message = 'Только root-администратор может создавать новых администраторов'
|
||||
} else if (errorMsg === 'telegram_id_required_for_observer') {
|
||||
message = 'Для наблюдателя необходимо указать Telegram-аккаунт'
|
||||
} else if (errorMsg === 'telegram_user_not_found') {
|
||||
message = 'Пользователь с таким Telegram ID не найден в боте'
|
||||
}
|
||||
|
||||
notifications.show({
|
||||
|
|
@ -65,6 +69,10 @@ export function useUpdateAdmin() {
|
|||
message = 'Нельзя заблокировать root-администратора'
|
||||
} else if (errorMsg === 'cannot_block_self') {
|
||||
message = 'Нельзя заблокировать свой собственный аккаунт'
|
||||
} else if (errorMsg === 'telegram_id_required_for_observer') {
|
||||
message = 'Для наблюдателя необходимо указать Telegram-аккаунт'
|
||||
} else if (errorMsg === 'telegram_user_not_found') {
|
||||
message = 'Пользователь с таким Telegram ID не найден в боте'
|
||||
}
|
||||
|
||||
notifications.show({
|
||||
|
|
|
|||
|
|
@ -19,6 +19,18 @@ export function useApprovals(params: ApprovalsListParams = {}) {
|
|||
})
|
||||
}
|
||||
|
||||
export function useApprovalTasks(approvalId: number | null) {
|
||||
return useQuery({
|
||||
queryKey: ['approval-tasks', approvalId],
|
||||
queryFn: async () => {
|
||||
if (!approvalId) return null
|
||||
const response = await approvalsApi.getTasks(approvalId)
|
||||
return response.data
|
||||
},
|
||||
enabled: !!approvalId,
|
||||
})
|
||||
}
|
||||
|
||||
export function useApproval(id: number | null) {
|
||||
return useQuery({
|
||||
queryKey: ['approval', id],
|
||||
|
|
@ -88,3 +100,51 @@ export function useDeleteApproval() {
|
|||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useAdditionalApprovers(approvalId: number | null) {
|
||||
return useQuery({
|
||||
queryKey: ['approval-additional-approvers', approvalId],
|
||||
queryFn: async () => {
|
||||
if (!approvalId) return null
|
||||
const response = await approvalsApi.getAdditionalApprovers(approvalId)
|
||||
return response.data
|
||||
},
|
||||
enabled: !!approvalId,
|
||||
})
|
||||
}
|
||||
|
||||
export function useApprovalComments(approvalId: number | null) {
|
||||
return useQuery({
|
||||
queryKey: ['approval-comments', approvalId],
|
||||
queryFn: async () => {
|
||||
if (!approvalId) return null
|
||||
const response = await approvalsApi.getComments(approvalId)
|
||||
return response.data
|
||||
},
|
||||
enabled: !!approvalId,
|
||||
})
|
||||
}
|
||||
|
||||
export function useApprovalObservers(approvalId: number | null) {
|
||||
return useQuery({
|
||||
queryKey: ['approval-observers', approvalId],
|
||||
queryFn: async () => {
|
||||
if (!approvalId) return null
|
||||
const response = await approvalsApi.getObservers(approvalId)
|
||||
return response.data
|
||||
},
|
||||
enabled: !!approvalId,
|
||||
})
|
||||
}
|
||||
|
||||
export function useRevocationRequest(approvalId: number | null) {
|
||||
return useQuery({
|
||||
queryKey: ['approval-revocation-request', approvalId],
|
||||
queryFn: async () => {
|
||||
if (!approvalId) return null
|
||||
const response = await approvalsApi.getRevocationRequest(approvalId)
|
||||
return response.data
|
||||
},
|
||||
enabled: !!approvalId,
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,41 +4,36 @@ import {
|
|||
type CreateFlowNodeRequest,
|
||||
type UpdateFlowNodeRequest,
|
||||
type MoveFlowNodeRequest,
|
||||
type SaveTreeRequest,
|
||||
type PreviewFlowRequest,
|
||||
} from '@/api/flowNodes'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
|
||||
export const FLOW_NODES_QUERY_KEY = 'flowNodes'
|
||||
|
||||
export function useFlowNodesTree(topicId: number | null) {
|
||||
export function useFlowNodesTree(categoryId: number | null) {
|
||||
return useQuery({
|
||||
queryKey: [FLOW_NODES_QUERY_KEY, topicId],
|
||||
queryKey: [FLOW_NODES_QUERY_KEY, categoryId],
|
||||
queryFn: async () => {
|
||||
if (!topicId) return null
|
||||
const response = await flowNodesApi.getTree(topicId)
|
||||
if (!categoryId) return null
|
||||
const response = await flowNodesApi.getTree(categoryId)
|
||||
return response.data
|
||||
},
|
||||
enabled: !!topicId,
|
||||
enabled: !!categoryId,
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateFlowNode() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: CreateFlowNodeRequest) => flowNodesApi.create(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Узел создан',
|
||||
color: 'green',
|
||||
})
|
||||
notifications.show({ title: 'Готово', message: 'Кнопка/шаг добавлены', color: 'green' })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось создать узел',
|
||||
title: 'Не получилось',
|
||||
message: error.response?.data?.error_description || 'Не удалось сохранить',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
|
|
@ -47,21 +42,16 @@ export function useCreateFlowNode() {
|
|||
|
||||
export function useUpdateFlowNode() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: UpdateFlowNodeRequest) => flowNodesApi.update(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Узел обновлён',
|
||||
color: 'green',
|
||||
})
|
||||
notifications.show({ title: 'Готово', message: 'Изменения сохранены', color: 'green' })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось обновить узел',
|
||||
title: 'Не получилось',
|
||||
message: error.response?.data?.error_description || 'Не удалось сохранить изменения',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
|
|
@ -70,89 +60,121 @@ export function useUpdateFlowNode() {
|
|||
|
||||
export function useDeleteFlowNode() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => flowNodesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Узел удалён',
|
||||
color: 'green',
|
||||
})
|
||||
notifications.show({ title: 'Готово', message: 'Шаг удалён', color: 'green' })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось удалить узел',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useSaveFlowTree() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ topicId, data }: { topicId: number; data: SaveTreeRequest }) =>
|
||||
flowNodesApi.saveTree(topicId, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Дерево сохранено',
|
||||
color: 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось сохранить дерево',
|
||||
title: 'Не получилось',
|
||||
message: error.response?.data?.error_description || 'Не удалось удалить',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Перемещение узла — используется для ↑/↓ среди соседей и для
|
||||
// "поднять/опустить уровень" точечно (см. treeWalk.ts).
|
||||
export function useMoveFlowNode() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, data }: { id: number; data: MoveFlowNodeRequest }) =>
|
||||
flowNodesApi.move(id, data),
|
||||
mutationFn: ({ id, data }: { id: number; data: MoveFlowNodeRequest }) => flowNodesApi.move(id, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось переместить узел',
|
||||
title: 'Не получилось',
|
||||
message: error.response?.data?.error_description || 'Не удалось переместить',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// НОВОЕ: пакетное перемещение для drag&drop — план из buildReorderPlan
|
||||
// (см. treeFlatten.ts) может включать несколько узлов сразу (переиндексация
|
||||
// старой и новой групп соседей). Отправляем всё параллельно и обновляем
|
||||
// дерево ОДНИМ инвалидейтом в конце, а не на каждый отдельный вызов —
|
||||
// иначе список будет дёргаться на каждом промежуточном ответе.
|
||||
export function useReorderNodes() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async (ops: { id: number; new_parent_id: number | null; new_sort_order: number }[]) => {
|
||||
await Promise.all(
|
||||
ops.map((op) =>
|
||||
flowNodesApi.move(op.id, { new_parent_id: op.new_parent_id, new_sort_order: op.new_sort_order })
|
||||
)
|
||||
)
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Не получилось',
|
||||
message:
|
||||
error.response?.data?.error_description || 'Не удалось переместить шаг — дерево вернётся к прежнему виду',
|
||||
color: 'red',
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useDuplicateFlowNode() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => flowNodesApi.duplicate(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Узел дублирован',
|
||||
color: 'green',
|
||||
})
|
||||
notifications.show({ title: 'Готово', message: 'Шаг скопирован', color: 'green' })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось дублировать узел',
|
||||
title: 'Не получилось',
|
||||
message: error.response?.data?.error_description || 'Не удалось скопировать',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// НОВОЕ: живой предпросмотр — код темы + текст сообщения согласующему
|
||||
// для конкретного набора выборов. Не мутирует данные, поэтому это
|
||||
// useMutation, вызываемый вручную (а не useQuery), чтобы не дёргать
|
||||
// сервер на каждое нажатие клавиши, а только по явному запросу/дебаунсу.
|
||||
// НОВОЕ: кнопка "Обновить бота" — форсирует у бота перечитывание дерева тем
|
||||
// из БД, не дожидаясь фонового тика (см. reload_watcher.go в telegram_service).
|
||||
export function useReloadBot() {
|
||||
return useMutation({
|
||||
mutationFn: () => flowNodesApi.reloadBot(),
|
||||
onSuccess: () => {
|
||||
notifications.show({
|
||||
title: 'Готово',
|
||||
message: 'Бот обновит список тем в течение нескольких секунд',
|
||||
color: 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Не получилось',
|
||||
message: error.response?.data?.error_description || 'Не удалось обновить бота',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function usePreviewFlow(categoryId: number | null) {
|
||||
return useMutation({
|
||||
mutationFn: async (data: PreviewFlowRequest) => {
|
||||
if (!categoryId) throw new Error('categoryId is required')
|
||||
const response = await flowNodesApi.preview(categoryId, data)
|
||||
return response.data // разворачиваем AxiosResponse -> PreviewFlowResponse
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
import { arrayMove } from '@dnd-kit/sortable'
|
||||
import type { ApprovalFlowNode } from '@/types/api'
|
||||
|
||||
export interface FlatFlowNode extends ApprovalFlowNode {
|
||||
depth: number
|
||||
}
|
||||
|
||||
// Разворачивает дерево в плоский список для отображения в виде сортируемого
|
||||
// списка. parent_id уже есть на каждом узле (приходит с бэкенда) — отдельно
|
||||
// его не вычисляем.
|
||||
export function flattenTree(nodes: ApprovalFlowNode[], collapsed: Set<number>): FlatFlowNode[] {
|
||||
const result: FlatFlowNode[] = []
|
||||
const walk = (list: ApprovalFlowNode[], depth: number) => {
|
||||
for (const node of list) {
|
||||
result.push({ ...node, depth })
|
||||
if (node.children?.length && node.id != null && !collapsed.has(node.id)) {
|
||||
walk(node.children, depth + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(nodes, 0)
|
||||
return result
|
||||
}
|
||||
|
||||
export interface Projection {
|
||||
depth: number
|
||||
parentId: number | null
|
||||
}
|
||||
|
||||
// Классический алгоритм проекции для sortable-дерева (как в примере
|
||||
// "Sortable Tree" из документации dnd-kit): по горизонтальному смещению
|
||||
// курсора во время перетаскивания решаем, на какую глубину и к какому
|
||||
// родителю попадёт узел, если отпустить его над overId прямо сейчас.
|
||||
//
|
||||
// ВАЖНО: глубина никогда не может быть 0 — на верхнем уровне дерева
|
||||
// категории всегда должен быть ровно один узел (корень с ключом, равным
|
||||
// коду раздела), и он не участвует в перетаскивании.
|
||||
export function getProjection(
|
||||
items: FlatFlowNode[],
|
||||
activeId: number,
|
||||
overId: number,
|
||||
dragOffsetX: number,
|
||||
indentationWidth: number
|
||||
): Projection {
|
||||
const activeItemIndex = items.findIndex((n) => n.id === activeId)
|
||||
const overItemIndex = items.findIndex((n) => n.id === overId)
|
||||
if (activeItemIndex === -1 || overItemIndex === -1) {
|
||||
return { depth: 1, parentId: null }
|
||||
}
|
||||
|
||||
const activeItem = items[activeItemIndex]
|
||||
const newItems = arrayMove(items, activeItemIndex, overItemIndex)
|
||||
const previousItem = newItems[overItemIndex - 1]
|
||||
const nextItem = newItems[overItemIndex + 1]
|
||||
|
||||
const dragDepthDelta = Math.round(dragOffsetX / indentationWidth)
|
||||
const projectedDepth = activeItem.depth + dragDepthDelta
|
||||
|
||||
const maxDepth = Math.max(previousItem ? previousItem.depth + 1 : 1, 1)
|
||||
const minDepth = Math.max(nextItem ? nextItem.depth : 1, 1)
|
||||
|
||||
let depth = projectedDepth
|
||||
if (depth > maxDepth) depth = maxDepth
|
||||
if (depth < minDepth) depth = minDepth
|
||||
|
||||
let parentId: number | null = null
|
||||
if (previousItem) {
|
||||
if (depth === previousItem.depth) {
|
||||
parentId = previousItem.parent_id ?? null
|
||||
} else if (depth > previousItem.depth) {
|
||||
parentId = previousItem.id ?? null
|
||||
} else {
|
||||
const newParent = [...newItems]
|
||||
.slice(0, overItemIndex)
|
||||
.reverse()
|
||||
.find((n) => n.depth === depth)
|
||||
parentId = newParent?.parent_id ?? null
|
||||
}
|
||||
}
|
||||
|
||||
return { depth, parentId }
|
||||
}
|
||||
|
||||
export interface MoveOp {
|
||||
id: number
|
||||
new_parent_id: number | null
|
||||
new_sort_order: number
|
||||
}
|
||||
|
||||
// Строит план обновлений после drag&drop одного узла: полностью
|
||||
// переиндексирует группу соседей, откуда узел ушёл, и группу, куда он
|
||||
// попал (несколько лишних вызовов API по сравнению со строгим минимумом,
|
||||
// зато гарантированно нет дублей/дыр в sort_order).
|
||||
export function buildReorderPlan(
|
||||
tree: ApprovalFlowNode[],
|
||||
activeId: number,
|
||||
newParentId: number | null,
|
||||
overId: number
|
||||
): MoveOp[] {
|
||||
const flat = flattenTree(tree, new Set())
|
||||
const active = flat.find((n) => n.id === activeId)
|
||||
if (!active) return []
|
||||
|
||||
const oldParentId = active.parent_id ?? null
|
||||
|
||||
const oldSiblings = flat.filter((n) => (n.parent_id ?? null) === oldParentId && n.id !== activeId)
|
||||
const newSiblingsWithoutActive = flat.filter((n) => (n.parent_id ?? null) === newParentId && n.id !== activeId)
|
||||
|
||||
const overIdx = newSiblingsWithoutActive.findIndex((n) => n.id === overId)
|
||||
const insertAt = overIdx === -1 ? newSiblingsWithoutActive.length : overIdx
|
||||
|
||||
const newSiblings = [...newSiblingsWithoutActive]
|
||||
newSiblings.splice(insertAt, 0, active)
|
||||
|
||||
const ops: MoveOp[] = newSiblings.map((n, idx) => ({
|
||||
id: n.id!,
|
||||
new_parent_id: newParentId,
|
||||
new_sort_order: idx,
|
||||
}))
|
||||
|
||||
if (oldParentId !== newParentId) {
|
||||
oldSiblings.forEach((n, idx) => {
|
||||
ops.push({ id: n.id!, new_parent_id: oldParentId, new_sort_order: idx })
|
||||
})
|
||||
}
|
||||
|
||||
return ops
|
||||
}
|
||||
|
|
@ -0,0 +1,223 @@
|
|||
import type { ApprovalFlowNode } from '@/types/api'
|
||||
|
||||
// ============================================================
|
||||
// Базовый обход дерева
|
||||
// ============================================================
|
||||
|
||||
export function findParent(
|
||||
nodes: ApprovalFlowNode[],
|
||||
targetId: number,
|
||||
parent: ApprovalFlowNode | null = null
|
||||
): ApprovalFlowNode | null {
|
||||
for (const node of nodes) {
|
||||
if (node.id === targetId) return parent
|
||||
if (node.children) {
|
||||
const found = findParent(node.children, targetId, node)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function findNodeById(nodes: ApprovalFlowNode[], targetId: number): ApprovalFlowNode | null {
|
||||
for (const node of nodes) {
|
||||
if (node.id === targetId) return node
|
||||
if (node.children) {
|
||||
const found = findNodeById(node.children, targetId)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Путь от корня дерева категории до узла (включительно). Нужен, чтобы
|
||||
// посчитать, какие data_key/data_value уже "накопились" на этом пути —
|
||||
// именно так реальный бот собирает `collected` при прохождении сценария.
|
||||
export function getPathToNode(tree: ApprovalFlowNode[], targetId: number): ApprovalFlowNode[] {
|
||||
const path: ApprovalFlowNode[] = []
|
||||
const walk = (nodes: ApprovalFlowNode[]): boolean => {
|
||||
for (const n of nodes) {
|
||||
path.push(n)
|
||||
if (n.id === targetId) return true
|
||||
if (n.children && walk(n.children)) return true
|
||||
path.pop()
|
||||
}
|
||||
return false
|
||||
}
|
||||
walk(tree)
|
||||
return path
|
||||
}
|
||||
|
||||
// Собирает collected (data_key -> data_value) по цепочке узлов пути.
|
||||
// Мультиселект-узлы на одном пути объединяются через запятую — это
|
||||
// приближение (реальный пользователь может выбрать несколько узлов
|
||||
// мультиселекта одновременно), для целей предпросмотра/проверки этого
|
||||
// достаточно.
|
||||
export function collectFromPath(path: ApprovalFlowNode[]): Record<string, string> {
|
||||
const collected: Record<string, string> = {}
|
||||
for (const n of path) {
|
||||
if (n.data_key && n.data_value) {
|
||||
collected[n.data_key] = n.data_value
|
||||
}
|
||||
if (n.multi_select_key && n.multi_select_value) {
|
||||
collected[n.multi_select_key] = collected[n.multi_select_key]
|
||||
? `${collected[n.multi_select_key]},${n.multi_select_value}`
|
||||
: n.multi_select_value
|
||||
}
|
||||
}
|
||||
return collected
|
||||
}
|
||||
|
||||
// Все пути от корня до "концов" дерева (узел без детей ИЛИ узел
|
||||
// текстового ввода — именно на нём сценарий завершается и определяется
|
||||
// тема заявки).
|
||||
export function collectLeafPaths(tree: ApprovalFlowNode[]): ApprovalFlowNode[][] {
|
||||
const leaves: ApprovalFlowNode[][] = []
|
||||
const walk = (nodes: ApprovalFlowNode[], path: ApprovalFlowNode[]) => {
|
||||
for (const n of nodes) {
|
||||
const nextPath = [...path, n]
|
||||
if (n.is_input || !n.children || n.children.length === 0) {
|
||||
leaves.push(nextPath)
|
||||
} else {
|
||||
walk(n.children, nextPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(tree, [])
|
||||
return leaves
|
||||
}
|
||||
|
||||
export function pathLabel(path: ApprovalFlowNode[]): string {
|
||||
return path.map((n) => n.label).join(' → ')
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Перемещение по уровням ("поднять/опустить уровень")
|
||||
// ============================================================
|
||||
|
||||
export interface MoveTarget {
|
||||
new_parent_id: number | null
|
||||
new_sort_order: number
|
||||
}
|
||||
|
||||
// "Поднять уровень": узел становится соседом своего текущего родителя
|
||||
// (переходит на уровень выше), а не остаётся его ребёнком.
|
||||
export function getPromoteMove(tree: ApprovalFlowNode[], node: ApprovalFlowNode): MoveTarget | null {
|
||||
if (!node.id) return null
|
||||
const parent = findParent(tree, node.id)
|
||||
if (!parent || !parent.id) return null // узел уже на самом верхнем уровне
|
||||
|
||||
const grandParent = findParent(tree, parent.id)
|
||||
const grandSiblings = grandParent ? grandParent.children || [] : tree
|
||||
const parentIndex = grandSiblings.findIndex((n) => n.id === parent.id)
|
||||
|
||||
return {
|
||||
new_parent_id: grandParent?.id ?? null,
|
||||
new_sort_order: parentIndex + 1,
|
||||
}
|
||||
}
|
||||
|
||||
// "Опустить уровень": узел становится последним ребёнком своего
|
||||
// предыдущего соседа (вкладывается на уровень ниже).
|
||||
export function getDemoteMove(tree: ApprovalFlowNode[], node: ApprovalFlowNode): MoveTarget | null {
|
||||
if (!node.id) return null
|
||||
const parent = findParent(tree, node.id)
|
||||
const siblings = parent ? parent.children || [] : tree
|
||||
const index = siblings.findIndex((n) => n.id === node.id)
|
||||
if (index <= 0) return null // нет предыдущего соседа, чтобы вложиться в него
|
||||
|
||||
const newParent = siblings[index - 1]
|
||||
if (!newParent.id) return null
|
||||
|
||||
return {
|
||||
new_parent_id: newParent.id,
|
||||
new_sort_order: newParent.children?.length ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Черновик шаблона сообщения
|
||||
// ============================================================
|
||||
|
||||
// Бэкенд теперь умеет подставлять "{{.key_label}}" для ЛЮБОГО DataKey — не
|
||||
// только для зашитого в addLabelMappings списка (см. DYNAMIC_TOPIC_PATCH.txt:
|
||||
// addTreeLabelMappings берёт подпись прямо из Label узла дерева, с приоритетом
|
||||
// над старым хардкодом). Поэтому черновик сообщения теперь всегда предлагает
|
||||
// "_label"-версию — она либо подставится из названия соответствующей кнопки,
|
||||
// либо (для совсем старых зашитых значений) из старой карты addLabelMappings.
|
||||
function placeholderFor(key: string): string {
|
||||
return `{{.${key}_label}}`
|
||||
}
|
||||
|
||||
// Собирает ВСЕ DataKey/MultiSelectKey по всему дереву, а не только у
|
||||
// прямых детей корня — на любой глубине вложенности.
|
||||
export function collectAllDataKeys(node: ApprovalFlowNode): string[] {
|
||||
const acc: string[] = []
|
||||
const walk = (n: ApprovalFlowNode) => {
|
||||
for (const child of n.children || []) {
|
||||
if (child.data_key) acc.push(child.data_key)
|
||||
if (child.multi_select_key) acc.push(child.multi_select_key)
|
||||
if (child.children?.length) walk(child)
|
||||
}
|
||||
}
|
||||
walk(node)
|
||||
return Array.from(new Set(acc))
|
||||
}
|
||||
|
||||
// Ищет DataKey/MultiSelectKey, которые реально встречаются в дереве, но не
|
||||
// упомянуты в шаблоне кода темы. Эвристика: ищем подстроку ".ключ" —
|
||||
// покрывает и {{.branch}}, и {{if .branch}}, и {{if eq .branch "..."}}.
|
||||
// Пустой шаблон означает автосборку кода (см. TopicCodeFromCollected на
|
||||
// бэкенде) — она и так подхватывает любые ключи сама, предупреждать не о чем.
|
||||
export function findMissingKeysInCodeTemplate(root: ApprovalFlowNode, codeTemplate: string): string[] {
|
||||
if (!codeTemplate) return []
|
||||
return collectAllDataKeys(root).filter((k) => !codeTemplate.includes(`.${k}`))
|
||||
}
|
||||
|
||||
// Строит кусок шаблона для одного "потерянного" ключа — оборачиваем в
|
||||
// {{if}}, чтобы не сломать ветки, где этого ключа нет вообще (например,
|
||||
// более старые темы категории, у которых на один уровень вложенности
|
||||
// меньше).
|
||||
export function buildMissingKeySegment(key: string): string {
|
||||
return `{{if .${key}}}_{{.${key}}}{{end}}`
|
||||
}
|
||||
|
||||
// Генерирует ЧЕРНОВИК Go-шаблона сообщения согласующему. Это стартовая
|
||||
// точка, а не готовое решение — админ должен проверить результат через
|
||||
// живой предпросмотр и доработать формулировки при необходимости.
|
||||
//
|
||||
// Заголовок строится по первому уровню развилок (как раньше) — это
|
||||
// обычно самое важное различие между ветками, поэтому его выносим в
|
||||
// заголовок сообщения. А дальше — отдельной строкой на каждый DataKey,
|
||||
// который вообще встречается в дереве, НА ЛЮБОЙ глубине. Каждая такая
|
||||
// строка обёрнута в {{if .key}}...{{end}} и поэтому появляется в
|
||||
// сообщении, только если сотрудник реально прошёл через тот шаг, где
|
||||
// этот ключ собирается — остальные строки просто не покажутся, это
|
||||
// нормально для дерева с разными по длине ветками.
|
||||
export function generateDraftMessageTemplate(root: ApprovalFlowNode): string {
|
||||
const children = root.children || []
|
||||
const withDataKey = children.filter((c) => c.data_key && c.data_value)
|
||||
|
||||
let titleKey: string | undefined
|
||||
let title = root.label
|
||||
|
||||
if (withDataKey.length > 0) {
|
||||
const dataKey = withDataKey[0].data_key
|
||||
const uniform = withDataKey.every((c) => c.data_key === dataKey)
|
||||
if (uniform && dataKey) {
|
||||
titleKey = dataKey
|
||||
let chain = ''
|
||||
withDataKey.forEach((c, i) => {
|
||||
const cond = `eq .${dataKey} "${c.data_value}"`
|
||||
chain += i === 0 ? `{{if ${cond}}}${c.label}` : `{{else if ${cond}}}${c.label}`
|
||||
})
|
||||
chain += `{{else}}${root.label}{{end}}`
|
||||
title = chain
|
||||
}
|
||||
}
|
||||
|
||||
const bodyKeys = collectAllDataKeys(root).filter((k) => k !== titleKey)
|
||||
const bodyLines = bodyKeys.map((k) => `{{if .${k}}}${placeholderFor(k)} {{end}}`).join('')
|
||||
|
||||
return `📋 <b>${title}</b>\n${bodyLines}\n<b>{{.initiator_name}}</b>:\n{{.content}}`
|
||||
}
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
||||
import { useFlowNodesTree } from '@/features/flowNodes/hooks/useFlowNodes'
|
||||
import { flowNodesApi } from '@/api/flowNodes'
|
||||
import type { ApprovalFlowNode } from '@/types/api'
|
||||
|
||||
export interface SystemOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
function extractSystemOptions(nodes: ApprovalFlowNode[] | null | undefined): SystemOption[] {
|
||||
if (!nodes) return []
|
||||
const seen = new Map<string, string>()
|
||||
|
||||
// Рекурсивный обход всех вложенностей
|
||||
function traverse(nodeList: ApprovalFlowNode[]) {
|
||||
for (const n of nodeList) {
|
||||
// Ищем мультиселект с ключом systems
|
||||
if (n.is_multi_select && n.multi_select_key === 'systems' && n.multi_select_value) {
|
||||
if (!seen.has(n.multi_select_value)) {
|
||||
seen.set(n.multi_select_value, n.label || n.multi_select_value)
|
||||
}
|
||||
}
|
||||
// Погружаемся в дочерние узлы
|
||||
if (n.children && n.children.length > 0) {
|
||||
traverse(n.children)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traverse(nodes)
|
||||
return Array.from(seen.entries()).map(([value, label]) => ({ value, label }))
|
||||
}
|
||||
|
||||
export function useCategorySystemOptions(categoryId: number | null) {
|
||||
const { data, isLoading } = useFlowNodesTree(categoryId)
|
||||
const options = extractSystemOptions(data?.data)
|
||||
return { options, isLoading: categoryId ? isLoading : false }
|
||||
}
|
||||
|
||||
export function useAllSystemOptions(enabled: boolean = true) {
|
||||
const { data: categories } = useCategories({ limit: 1000 })
|
||||
const categoryIds = (categories?.data ?? [])
|
||||
.map((c) => c.id)
|
||||
.filter((id): id is number => !!id)
|
||||
|
||||
// Используем один запрос и последовательно опрашиваем категории, чтобы избежать 429 Too Many Requests
|
||||
const { data: options = [], isLoading } = useQuery({
|
||||
queryKey: ['all-systems-scan', categoryIds],
|
||||
queryFn: async () => {
|
||||
const seen = new Map<string, string>()
|
||||
|
||||
for (const id of categoryIds) {
|
||||
try {
|
||||
const response = await flowNodesApi.getTree(id)
|
||||
const opts = extractSystemOptions(response.data?.data)
|
||||
opts.forEach(o => {
|
||||
if (!seen.has(o.value)) seen.set(o.value, o.label)
|
||||
})
|
||||
} catch (e) {
|
||||
console.warn(`[useAllSystemOptions] Ошибка загрузки дерева для категории ${id}`, e)
|
||||
}
|
||||
}
|
||||
return Array.from(seen.entries()).map(([value, label]) => ({ value, label }))
|
||||
},
|
||||
enabled: enabled && categoryIds.length > 0,
|
||||
})
|
||||
|
||||
return { options, isLoading }
|
||||
}
|
||||
|
||||
export const ALL_SYSTEMS_VALUE = 'all'
|
||||
|
|
@ -36,14 +36,13 @@ export function groupHierarchiesIntoChains(
|
|||
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'}`
|
||||
// Формируем ключ группы (добавляем target_system)
|
||||
const targetSystemPart = h.target_system || 'all'
|
||||
const key = `${h.subordinate_id}-${h.department_id}-${scopeType}-${scopeObjectId || 'null'}-${targetSystemPart}`
|
||||
|
||||
if (!groups.has(key)) {
|
||||
// Определяем название объекта области действия
|
||||
let scopeObjectName = 'Все темы'
|
||||
if (scopeType === 'category' && h.subordinate) {
|
||||
// Будет заполнено позже из categories
|
||||
scopeObjectName = `Категория #${scopeObjectId}`
|
||||
} else if (scopeType === 'topic') {
|
||||
scopeObjectName = `Тема #${scopeObjectId}`
|
||||
|
|
|
|||
|
|
@ -0,0 +1,39 @@
|
|||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { monthlyOrdersApi } from '@/api/monthlyOrders'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import type { MonthlyOrderSetting } from '@/types/api'
|
||||
|
||||
export const MO_SETTINGS_QUERY_KEY = 'mo-settings'
|
||||
|
||||
export function useMonthlyOrderSettings() {
|
||||
return useQuery({
|
||||
queryKey: [MO_SETTINGS_QUERY_KEY],
|
||||
queryFn: async () => {
|
||||
const response = await monthlyOrdersApi.getSettings()
|
||||
return response.data
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useSaveMonthlyOrderSettings() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: MonthlyOrderSetting) => monthlyOrdersApi.saveSettings(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [MO_SETTINGS_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Настройки заказов на месяц сохранены',
|
||||
color: 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось сохранить настройки',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
notificationsApi,
|
||||
type NotificationsListParams,
|
||||
type CreateNotificationRequest,
|
||||
} from '@/api/notifications'
|
||||
import { notifications as mantineNotifications } from '@mantine/notifications'
|
||||
|
||||
export const NOTIFICATIONS_QUERY_KEY = 'notifications'
|
||||
|
||||
export function useNotifications(params: NotificationsListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: [NOTIFICATIONS_QUERY_KEY, params],
|
||||
queryFn: async () => {
|
||||
const response = await notificationsApi.getList(params)
|
||||
return response.data
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useNotification(id: number | null) {
|
||||
return useQuery({
|
||||
queryKey: ['notification', id],
|
||||
queryFn: async () => {
|
||||
if (!id) return null
|
||||
const response = await notificationsApi.getById(id)
|
||||
return response.data
|
||||
},
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateNotification() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: CreateNotificationRequest) => notificationsApi.create(data),
|
||||
onSuccess: (response) => {
|
||||
queryClient.invalidateQueries({ queryKey: [NOTIFICATIONS_QUERY_KEY] })
|
||||
const n = response.data
|
||||
const hasFailed = (n.failed_count ?? 0) > 0
|
||||
mantineNotifications.show({
|
||||
title: hasFailed ? 'Отправлено с ошибками' : 'Отправлено',
|
||||
message: `Доставлено: ${n.sent_count ?? 0} из ${n.total_count ?? 0}`,
|
||||
color: hasFailed ? 'yellow' : 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
mantineNotifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось отправить уведомление',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
// Приводит HTML из Tiptap-редактора к набору тегов, которые понимает Telegram ParseMode=HTML.
|
||||
// Разрешённые теги: b, i, u, s, a, code, pre, tg-spoiler
|
||||
const ALLOWED_TAGS = new Set(['b', 'i', 'u', 's', 'a', 'code', 'pre', 'tg-spoiler'])
|
||||
|
||||
export function convertHtmlToTelegram(html: string): string {
|
||||
let result = html
|
||||
|
||||
// Абзацы и переносы строк -> двойной/одинарный \n
|
||||
result = result.replace(/<\/p>\s*<p>/gi, '\n\n')
|
||||
result = result.replace(/<\/?p>/gi, '')
|
||||
result = result.replace(/<br\s*\/?>/gi, '\n')
|
||||
|
||||
// Синонимы тегов из Tiptap -> Telegram-теги
|
||||
result = result
|
||||
.replace(/<strong>/gi, '<b>').replace(/<\/strong>/gi, '</b>')
|
||||
.replace(/<em>/gi, '<i>').replace(/<\/em>/gi, '</i>')
|
||||
.replace(/<strike>/gi, '<s>').replace(/<\/strike>/gi, '</s>')
|
||||
|
||||
// Ссылки: сохраняем только href, убираем target/rel/class и т.п.
|
||||
result = result.replace(/<a\s+[^>]*href="([^"]*)"[^>]*>/gi, '<a href="$1">')
|
||||
|
||||
// Убираем все теги, не входящие в белый список Telegram
|
||||
result = result.replace(/<(\/?)([a-zA-Z0-9-]+)([^>]*)>/g, (match, closing, rawTag) => {
|
||||
const tag = rawTag.toLowerCase()
|
||||
if (!ALLOWED_TAGS.has(tag)) return ''
|
||||
if (tag === 'a' && !closing) return match // href уже нормализован выше
|
||||
return closing ? `</${tag}>` : `<${tag}>`
|
||||
})
|
||||
|
||||
return result.trim()
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { useQuery } from '@tanstack/react-query'
|
||||
import { rolesApi } from '@/api/roles.ts'
|
||||
import type { Role } from '@/types/api'
|
||||
|
||||
export const ALL_ROLES_QUERY_KEY = 'roles-all'
|
||||
|
||||
export function useAllRoles() {
|
||||
return useQuery({
|
||||
queryKey: [ALL_ROLES_QUERY_KEY],
|
||||
queryFn: async (): Promise<Role[]> => {
|
||||
const response = await rolesApi.getList({ limit: 1000 })
|
||||
return response.data.data || []
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
// Единый справочник типов ролей: из него строятся фильтр, бейджи в таблице и переключатели в форме.
|
||||
export type RoleTypeKey = 'is_director' | 'is_approver' | 'is_observer' | 'is_controller' | 'is_executor'
|
||||
|
||||
export interface RoleTypeMeta {
|
||||
key: RoleTypeKey
|
||||
label: string
|
||||
color: string
|
||||
description: string
|
||||
requires?: RoleTypeKey // тип доступен только вместе с другим
|
||||
}
|
||||
|
||||
export const ROLE_TYPES: RoleTypeMeta[] = [
|
||||
{ key: 'is_director', label: 'Директор', color: 'violet', description: 'Является директором' },
|
||||
{ key: 'is_approver', label: 'Согласующий', color: 'blue', description: 'Может согласовывать заявки' },
|
||||
{ key: 'is_observer', label: 'Наблюдатель', color: 'green', description: 'Может наблюдать за заявками' },
|
||||
{
|
||||
key: 'is_controller',
|
||||
label: 'Контролёр',
|
||||
color: 'teal',
|
||||
description: 'Видит расширенный контроль по заявкам',
|
||||
requires: 'is_observer',
|
||||
},
|
||||
{ key: 'is_executor', label: 'Исполнитель', color: 'orange', description: 'Может выполнять задачи' },
|
||||
]
|
||||
|
||||
export interface RoleFormValues {
|
||||
name: string
|
||||
code: string
|
||||
description: string
|
||||
is_default: boolean
|
||||
is_director: boolean
|
||||
is_approver: boolean
|
||||
is_observer: boolean
|
||||
is_controller: boolean
|
||||
is_executor: boolean
|
||||
}
|
||||
|
||||
export const EMPTY_ROLE: RoleFormValues = {
|
||||
name: '',
|
||||
code: '',
|
||||
description: '',
|
||||
is_default: false,
|
||||
is_director: false,
|
||||
is_approver: false,
|
||||
is_observer: false,
|
||||
is_controller: false,
|
||||
is_executor: false,
|
||||
}
|
||||
|
||||
const TRANSLIT: Record<string, string> = {
|
||||
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z', и: 'i', й: 'y', к: 'k', л: 'l',
|
||||
м: 'm', н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f', х: 'h', ц: 'ts', ч: 'ch',
|
||||
ш: 'sh', щ: 'sch', ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
|
||||
}
|
||||
|
||||
// «Старший менеджер» → «starshiy_menedzher»
|
||||
export function slugifyRoleCode(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.split('')
|
||||
.map((c) => TRANSLIT[c] ?? c)
|
||||
.join('')
|
||||
.replace(/[^a-z0-9]+/g, '_')
|
||||
.replace(/^_+|_+$/g, '')
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import { telegramManagersApi } from '@/api/telegramManagers'
|
||||
|
||||
export function useTelegramManagers() {
|
||||
return useQuery({
|
||||
queryKey: ['telegram-managers-status'],
|
||||
queryFn: async () => {
|
||||
const response = await telegramManagersApi.getStatus()
|
||||
return response.data
|
||||
},
|
||||
refetchInterval: 10000, // Автоматическое обновление статуса каждые 10 секунд
|
||||
})
|
||||
}
|
||||
|
||||
interface DeleteTelegramParams {
|
||||
managerId: number;
|
||||
wipeData: boolean;
|
||||
}
|
||||
|
||||
export function useDeleteTelegramManager() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
// Передаем объект с двумя полями
|
||||
mutationFn: ({ managerId, wipeData }: DeleteTelegramParams) =>
|
||||
telegramManagersApi.delete(managerId, wipeData),
|
||||
onSuccess: (_, variables) => {
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
// Можно сделать динамическое сообщение в зависимости от галочки
|
||||
message: variables.wipeData
|
||||
? 'Сессия и история переписки удалены'
|
||||
: 'Сессия менеджера отключена',
|
||||
color: 'green',
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.detail || 'Не удалось удалить сессию',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -3,11 +3,11 @@ import { rolesApi } from '@/api/roles.ts'
|
|||
|
||||
export const ROLES_QUERY_KEY = 'roles'
|
||||
|
||||
export function useRoles() {
|
||||
export function useRoles(params: import('@/api/roles').RolesListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: [ROLES_QUERY_KEY],
|
||||
queryKey: [ROLES_QUERY_KEY, params],
|
||||
queryFn: async () => {
|
||||
const response = await rolesApi.getList()
|
||||
const response = await rolesApi.getList(params)
|
||||
return response.data.data || []
|
||||
},
|
||||
})
|
||||
|
|
|
|||
|
|
@ -48,3 +48,27 @@ export function useUpdateUser() {
|
|||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ✅ Новый хук для удаления пользователя
|
||||
export function useDeleteUser() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => usersApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [USERS_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Пользователь удален',
|
||||
color: 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось удалить пользователя',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import {whatsappManagersApi} from "@/api/whatsappManagers.ts";
|
||||
|
||||
export function useWhatsAppManagers() {
|
||||
return useQuery({
|
||||
queryKey: ['WhatsApp-managers-status'],
|
||||
queryFn: async () => {
|
||||
const response = await whatsappManagersApi.getStatus()
|
||||
return response.data
|
||||
},
|
||||
refetchInterval: 10000, // Автоматическое обновление статуса каждые 10 секунд
|
||||
})
|
||||
}
|
||||
|
||||
interface DeleteWhatsappParams {
|
||||
phone: string;
|
||||
wipeData: boolean;
|
||||
}
|
||||
|
||||
export function useDeleteWhatsAppManager() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
// Передаем объект с двумя полями
|
||||
mutationFn: ({ phone, wipeData }: DeleteWhatsappParams) =>
|
||||
whatsappManagersApi.delete(phone, wipeData),
|
||||
onSuccess: (_, variables) => {
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: variables.wipeData
|
||||
? 'Сессия и история переписки удалены'
|
||||
: 'Сессия менеджера отключена',
|
||||
color: 'green',
|
||||
})
|
||||
// Внимание: проверьте регистр ключа. Обычно используют ['whatsapp-managers-status'] (строчными)
|
||||
queryClient.invalidateQueries({ queryKey: ['whatsapp-managers-status'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.detail || 'Не удалось удалить сессию',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,255 @@
|
|||
import {
|
||||
IconAdjustments, IconBriefcase, IconChartBar, IconEye, IconShield, IconUserCog, type Icon,
|
||||
} from '@tabler/icons-react'
|
||||
|
||||
/* ——— Модель ———
|
||||
* Доступ = набор разделов; у каждого раздела список разрешённых действий.
|
||||
* Действие 'view' означает, что раздел виден; без него остальные действия не имеют смысла.
|
||||
* Для разделов с данными сотрудников (заявки, задачи) дополнительно задаётся охват (scope).
|
||||
*/
|
||||
|
||||
export type Scope = 'own' | 'department' | 'all'
|
||||
|
||||
export interface ModuleAccess {
|
||||
actions: string[]
|
||||
scope?: Scope
|
||||
}
|
||||
|
||||
export type AccessConfig = Record<string, ModuleAccess>
|
||||
|
||||
export interface AccessAction {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface AccessModule {
|
||||
id: string
|
||||
label: string
|
||||
group: string
|
||||
paths: string[] // маршруты, которые открывает раздел (для скрытия меню и защиты роутов)
|
||||
actions: AccessAction[] // без 'view' — он есть у каждого раздела
|
||||
scoped?: boolean // можно ограничить «чьи данные»
|
||||
note?: string
|
||||
}
|
||||
|
||||
export const SCOPES: { value: Scope; label: string }[] = [
|
||||
{ value: 'own', label: 'Только свои' },
|
||||
{ value: 'department', label: 'Своего отдела' },
|
||||
{ value: 'all', label: 'Все' },
|
||||
]
|
||||
|
||||
const CRUD: AccessAction[] = [
|
||||
{ id: 'create', label: 'Создавать' },
|
||||
{ id: 'edit', label: 'Редактировать' },
|
||||
{ id: 'delete', label: 'Удалять' },
|
||||
]
|
||||
const EDIT: AccessAction[] = [{ id: 'edit', label: 'Редактировать' }]
|
||||
|
||||
export const MODULES: AccessModule[] = [
|
||||
// Работа
|
||||
{ id: 'overview', group: 'Работа', label: 'Обзор', paths: ['/'], actions: [] },
|
||||
{
|
||||
id: 'approvals', group: 'Работа', label: 'Заявки', paths: ['/approvals'], scoped: true,
|
||||
actions: [
|
||||
{ id: 'export', label: 'Выгружать отчёты' },
|
||||
{ id: 'edit', label: 'Менять статус' },
|
||||
{ id: 'delete', label: 'Удалять' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'tasks', group: 'Работа', label: 'Задачи', paths: ['/approval-tasks'], scoped: true,
|
||||
actions: [{ id: 'status', label: 'Менять статус' }, { id: 'delete', label: 'Удалять' }],
|
||||
},
|
||||
{ id: 'monthly-orders', group: 'Работа', label: 'Заказы на месяц', paths: ['/monthly-orders-settings'], actions: EDIT },
|
||||
{ id: 'telephony', group: 'Работа', label: 'Телефония', paths: ['/telegram-managers'], actions: EDIT },
|
||||
|
||||
// Согласования
|
||||
{ id: 'approval-dash', group: 'Согласования', label: 'Панель управления', paths: ['/approval-dash'], actions: [] },
|
||||
{
|
||||
id: 'topics', group: 'Согласования', label: 'Темы согласований',
|
||||
paths: ['/categories', '/topics', '/executors'], actions: CRUD,
|
||||
},
|
||||
{ id: 'nodes', group: 'Согласования', label: 'Конструктор тем', paths: ['/nodes'], actions: EDIT },
|
||||
{ id: 'hierarchies', group: 'Согласования', label: 'Иерархия', paths: ['/hierarchies'], actions: EDIT },
|
||||
|
||||
// Организация
|
||||
{
|
||||
id: 'users', group: 'Организация', label: 'Пользователи', paths: ['/users'],
|
||||
actions: [{ id: 'edit', label: 'Редактировать' }, { id: 'delete', label: 'Удалять' }],
|
||||
},
|
||||
{ id: 'departments', group: 'Организация', label: 'Отделы', paths: ['/departments'], actions: CRUD },
|
||||
{ id: 'roles', group: 'Организация', label: 'Роли', paths: ['/roles'], actions: CRUD },
|
||||
{ id: 'permissions', group: 'Организация', label: 'Права', paths: ['/permissions'], actions: EDIT },
|
||||
|
||||
// Система
|
||||
{
|
||||
id: 'admins', group: 'Система', label: 'Пользователи системы', paths: ['/admins'],
|
||||
note: 'Создавать пользователей может только суперадминистратор',
|
||||
actions: [
|
||||
{ id: 'edit', label: 'Менять доступы' },
|
||||
{ id: 'block', label: 'Блокировать' },
|
||||
{ id: 'delete', label: 'Удалять' },
|
||||
],
|
||||
},
|
||||
{ id: 'notifications', group: 'Система', label: 'Уведомления', paths: ['/notifications'], actions: EDIT },
|
||||
{ id: 'logs', group: 'Система', label: 'Журнал действий', paths: ['/logs'], actions: [] },
|
||||
{ id: 'settings', group: 'Система', label: 'Настройки', paths: ['/settings'], actions: EDIT },
|
||||
]
|
||||
|
||||
export const MODULE_BY_ID: Record<string, AccessModule> = Object.fromEntries(MODULES.map((m) => [m.id, m]))
|
||||
export const GROUPS: string[] = Array.from(new Set(MODULES.map((m) => m.group)))
|
||||
|
||||
/* ——— Роли-шаблоны ——— */
|
||||
|
||||
export type PresetId = 'superadmin' | 'admin' | 'analyst' | 'observer' | 'manager'
|
||||
|
||||
export interface PresetMeta {
|
||||
id: PresetId | 'custom'
|
||||
label: string
|
||||
description: string
|
||||
color: string
|
||||
icon: Icon
|
||||
}
|
||||
|
||||
function full(exclude: string[] = []): AccessConfig {
|
||||
const out: AccessConfig = {}
|
||||
for (const m of MODULES) {
|
||||
if (exclude.includes(m.id)) continue
|
||||
out[m.id] = { actions: ['view', ...m.actions.map((a) => a.id)], ...(m.scoped && { scope: 'all' as Scope }) }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const view = (scope?: Scope, ...extra: string[]): ModuleAccess => ({
|
||||
actions: ['view', ...extra],
|
||||
...(scope && { scope }),
|
||||
})
|
||||
|
||||
export const PRESETS: (PresetMeta & { build: () => AccessConfig })[] = [
|
||||
{
|
||||
id: 'superadmin', label: 'Суперадминистратор', color: 'red', icon: IconShield,
|
||||
description: 'Полный доступ, управление пользователями системы',
|
||||
build: () => full(),
|
||||
},
|
||||
{
|
||||
id: 'admin', label: 'Администратор', color: 'brand', icon: IconUserCog,
|
||||
description: 'Вся работа и настройка, без управления пользователями системы',
|
||||
build: () => full(['admins']),
|
||||
},
|
||||
{
|
||||
id: 'analyst', label: 'Аналитик', color: 'grape', icon: IconChartBar,
|
||||
description: 'Заказы на месяц, отчёты по заявкам',
|
||||
build: () => ({
|
||||
overview: view(),
|
||||
approvals: view('all', 'export'),
|
||||
tasks: view('all'),
|
||||
'monthly-orders': view(undefined, 'edit'),
|
||||
'approval-dash': view(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'observer', label: 'Наблюдатель', color: 'blue', icon: IconEye,
|
||||
description: 'Только просмотр пользователей, заявок и задач. Нужен Telegram',
|
||||
build: () => ({ users: view(), approvals: view('all'), tasks: view('all') }),
|
||||
},
|
||||
{
|
||||
id: 'manager', label: 'Менеджер', color: 'teal', icon: IconBriefcase,
|
||||
description: 'Только веб-приложение заказов, без доступа к панели. Нужен Telegram',
|
||||
build: () => ({}),
|
||||
},
|
||||
]
|
||||
|
||||
export const PRESET_BY_ID = Object.fromEntries(PRESETS.map((p) => [p.id, p])) as Record<
|
||||
PresetId,
|
||||
(typeof PRESETS)[number]
|
||||
>
|
||||
|
||||
export const CUSTOM_META: PresetMeta = {
|
||||
id: 'custom', label: 'Особая настройка', color: 'gray', icon: IconAdjustments,
|
||||
description: 'Доступ настроен вручную',
|
||||
}
|
||||
|
||||
/* ——— Сравнение и определение роли ——— */
|
||||
|
||||
function normalize(access: AccessConfig): string {
|
||||
const entries = Object.entries(access)
|
||||
.filter(([id, a]) => MODULE_BY_ID[id] && a.actions.includes('view'))
|
||||
.map(([id, a]) => [
|
||||
id,
|
||||
[...new Set(a.actions)].sort(),
|
||||
MODULE_BY_ID[id].scoped ? a.scope ?? 'own' : null,
|
||||
])
|
||||
.sort((a, b) => String(a[0]).localeCompare(String(b[0])))
|
||||
return JSON.stringify(entries)
|
||||
}
|
||||
|
||||
export function detectPreset(access: AccessConfig): PresetId | 'custom' {
|
||||
const key = normalize(access)
|
||||
return PRESETS.find((p) => normalize(p.build()) === key)?.id ?? 'custom'
|
||||
}
|
||||
|
||||
export function presetMetaOf(access: AccessConfig): PresetMeta {
|
||||
const id = detectPreset(access)
|
||||
return id === 'custom' ? CUSTOM_META : PRESET_BY_ID[id]
|
||||
}
|
||||
|
||||
export const needsTelegram = (id: PresetId | 'custom') => id === 'observer' || id === 'manager'
|
||||
|
||||
/* ——— Редактирование ——— */
|
||||
|
||||
export function setModule(access: AccessConfig, id: string, next: ModuleAccess | null): AccessConfig {
|
||||
const copy = { ...access }
|
||||
if (next) copy[id] = next
|
||||
else delete copy[id]
|
||||
return copy
|
||||
}
|
||||
|
||||
// Включение раздела по умолчанию даёт минимум: просмотр и только свои данные
|
||||
export const enableModule = (id: string): ModuleAccess => ({
|
||||
actions: ['view'],
|
||||
...(MODULE_BY_ID[id].scoped && { scope: 'own' as Scope }),
|
||||
})
|
||||
|
||||
/* ——— Проверки ——— */
|
||||
|
||||
export function can(access: AccessConfig | undefined, moduleId: string, action = 'view'): boolean {
|
||||
return !!access?.[moduleId]?.actions.includes(action)
|
||||
}
|
||||
|
||||
export function scopeOf(access: AccessConfig | undefined, moduleId: string): Scope | null {
|
||||
const m = access?.[moduleId]
|
||||
if (!m || !MODULE_BY_ID[moduleId]?.scoped) return null
|
||||
return m.scope ?? 'own'
|
||||
}
|
||||
|
||||
// Можно ли открыть маршрут (для меню и защиты роутов)
|
||||
export function canOpenPath(access: AccessConfig | undefined, pathname: string): boolean {
|
||||
const m = MODULES.find((x) =>
|
||||
x.paths.some((p) => (p === '/' ? pathname === '/' : pathname === p || pathname.startsWith(p + '/'))),
|
||||
)
|
||||
return m ? can(access, m.id) : true // маршруты вне каталога (логин, 404) не ограничиваем
|
||||
}
|
||||
|
||||
export function accessSummary(access: AccessConfig) {
|
||||
const enabled = MODULES.filter((m) => can(access, m.id)).length
|
||||
return { enabled, total: MODULES.length }
|
||||
}
|
||||
|
||||
|
||||
interface LegacyFlags {
|
||||
is_root?: boolean
|
||||
is_analyst?: boolean
|
||||
is_observer?: boolean
|
||||
}
|
||||
|
||||
export function accessFromLegacy(a: LegacyFlags | null | undefined): AccessConfig {
|
||||
if (a?.is_root) return PRESET_BY_ID.superadmin.build()
|
||||
if (a?.is_analyst) return PRESET_BY_ID.analyst.build()
|
||||
if (a?.is_observer) return PRESET_BY_ID.observer.build()
|
||||
return PRESET_BY_ID.manager.build()
|
||||
}
|
||||
|
||||
export function legacyFlags(access: AccessConfig) {
|
||||
const p = detectPreset(access)
|
||||
return { is_root: p === 'superadmin', is_analyst: p === 'analyst', is_observer: p === 'observer' }
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
import type { ChainGroup } from '@/features/hierarchies/utils'
|
||||
|
||||
export type UserState = 'active' | 'blocked' | 'fired'
|
||||
|
||||
export const USER_STATE_LABEL: Record<Exclude<UserState, 'active'>, string> = {
|
||||
blocked: 'Заблокирован',
|
||||
fired: 'Уволен',
|
||||
}
|
||||
|
||||
export interface ChainIssue {
|
||||
kind: 'inactive' | 'self' | 'duplicate'
|
||||
message: string
|
||||
stepId?: number
|
||||
}
|
||||
|
||||
type UserLike = { id?: number; is_blocked?: boolean; is_fired?: boolean }
|
||||
|
||||
// Статусы берём из уже загруженного списка сотрудников — отдельных запросов не нужно
|
||||
export function userStateMap(users: UserLike[] | undefined): Map<number, UserState> {
|
||||
const map = new Map<number, UserState>()
|
||||
for (const u of users ?? []) {
|
||||
if (u.id == null) continue
|
||||
map.set(u.id, u.is_fired ? 'fired' : u.is_blocked ? 'blocked' : 'active')
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
// Проблемы, из-за которых заявка по цепочке может застрять или согласоваться формально
|
||||
export function chainIssues(group: ChainGroup, states: Map<number, UserState>): ChainIssue[] {
|
||||
const issues: ChainIssue[] = []
|
||||
const seen = new Set<number>()
|
||||
|
||||
for (const step of group.steps) {
|
||||
const id = step.approver_id
|
||||
if (id == null) continue
|
||||
const name = step.approver?.full_name || `ID ${id}`
|
||||
|
||||
const state = states.get(id) ?? 'active'
|
||||
if (state !== 'active') {
|
||||
issues.push({ kind: 'inactive', stepId: step.id, message: `${name}: ${USER_STATE_LABEL[state].toLowerCase()}, заявки на этом шаге не будут рассмотрены` })
|
||||
}
|
||||
if (id === group.subordinateId) {
|
||||
issues.push({ kind: 'self', stepId: step.id, message: `${name} согласует собственную заявку` })
|
||||
}
|
||||
if (seen.has(id)) {
|
||||
issues.push({ kind: 'duplicate', stepId: step.id, message: `${name} указан в цепочке несколько раз` })
|
||||
}
|
||||
seen.add(id)
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
import apiClient from '@/api/client'
|
||||
|
||||
export const approvalFileUrl = (approvalId: number, fileId: number, download = false) =>
|
||||
`/approvals/${approvalId}/files/${fileId}${download ? '/download' : ''}`
|
||||
|
||||
export const taskFileUrl = (taskId: number, fileId: number, download = false) =>
|
||||
`/approval-tasks/${taskId}/files/${fileId}${download ? '/download' : ''}`
|
||||
|
||||
export async function fetchFileBlob(url: string): Promise<Blob> {
|
||||
const response = await apiClient.get<Blob>(url, { responseType: 'blob' })
|
||||
return response.data
|
||||
}
|
||||
|
||||
export async function saveFile(url: string, fileName: string): Promise<void> {
|
||||
const blob = await fetchFileBlob(url)
|
||||
const objectUrl = window.URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = objectUrl
|
||||
link.setAttribute('download', fileName)
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
window.URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
|
||||
const MIME_BY_EXT: Record<string, string> = {
|
||||
pdf: 'application/pdf',
|
||||
png: 'image/png',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
gif: 'image/gif',
|
||||
webp: 'image/webp',
|
||||
svg: 'image/svg+xml',
|
||||
txt: 'text/plain',
|
||||
csv: 'text/csv',
|
||||
doc: 'application/msword',
|
||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
xls: 'application/vnd.ms-excel',
|
||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
zip: 'application/zip',
|
||||
}
|
||||
|
||||
export function getMimeType(fileName: string): string {
|
||||
const ext = fileName.split('.').pop()?.toLowerCase() ?? ''
|
||||
return MIME_BY_EXT[ext] ?? 'application/octet-stream'
|
||||
}
|
||||
|
||||
export function isPreviewable(mime: string): boolean {
|
||||
return mime.startsWith('image/') || mime === 'application/pdf' || mime === 'text/plain'
|
||||
}
|
||||
|
||||
export function formatFileSize(kb: number): string {
|
||||
if (kb < 1024) return `${kb} КБ`
|
||||
return `${(kb / 1024).toFixed(1).replace('.', ',')} МБ`
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
export function plural(n: number, forms: [string, string, string]) {
|
||||
const m10 = n % 10
|
||||
const m100 = n % 100
|
||||
if (m10 === 1 && m100 !== 11) return forms[0]
|
||||
if (m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14)) return forms[1]
|
||||
return forms[2]
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
// ВАЖНО: пути и поля — предположение. Подставьте реальные эндпоинты бэкенда.
|
||||
import api from '@/api/client'
|
||||
|
||||
export type ReportType = 'call' | 'sms' | 'chat'
|
||||
export type Channel = 'telegram' | 'whatsapp' | 'max'
|
||||
|
||||
export interface ReportRow {
|
||||
id: string
|
||||
type: ReportType
|
||||
channel?: Channel | null // только для type = 'chat'
|
||||
started_at: string // ISO; дата и время из таблицы одним полем
|
||||
direction: 'in' | 'out'
|
||||
phone: string
|
||||
contact_name?: string | null
|
||||
company?: string | null
|
||||
value: number // звонок — секунды, SMS/чат — число сообщений
|
||||
answered: boolean
|
||||
recording_url?: string | null // звонок
|
||||
last_message?: string | null // SMS / чат
|
||||
manager: string
|
||||
manager_id?: number | null
|
||||
notes_count?: number // число заметок, для индикатора в таблице
|
||||
status: string // «Отвечен», «Пропущен, перезвон не совершен», …
|
||||
}
|
||||
|
||||
export interface ReportParams {
|
||||
offset?: number; limit?: number
|
||||
type?: ReportType; manager?: string; direction?: 'in' | 'out'
|
||||
status?: string; content?: string; date_from?: string; date_to?: string
|
||||
}
|
||||
|
||||
export interface ChatSummary {
|
||||
id: string
|
||||
contact_name?: string | null
|
||||
phone: string
|
||||
last_message?: string | null
|
||||
last_at?: string | null
|
||||
messages_count: number
|
||||
}
|
||||
|
||||
export interface Note {
|
||||
id: number
|
||||
text: string
|
||||
author: string
|
||||
created_at: string
|
||||
can_delete: boolean // права решает сервер: автор или суперадмин
|
||||
}
|
||||
|
||||
export interface ChatMessage { id: string; direction: 'in' | 'out'; text: string; at: string; author?: string }
|
||||
|
||||
export const telephonyApi = {
|
||||
list: (params: ReportParams) =>
|
||||
api.get<{ data: ReportRow[]; total_count: number }>('/telephony/report', { params }).then((r) => r.data),
|
||||
// Заметки общие: видны всем, у кого есть доступ к разделу. id — id строки отчёта
|
||||
notes: (id: string) =>
|
||||
api.get<{ data: Note[] }>(`/telephony/report/${id}/notes`).then((r) => r.data.data),
|
||||
addNote: (id: string, text: string) => api.post(`/telephony/report/${id}/notes`, { text }),
|
||||
deleteNote: (id: string, noteId: number) => api.delete(`/telephony/report/${id}/notes/${noteId}`),
|
||||
// Диалоги менеджера в одном канале
|
||||
chats: (p: { channel: Channel; manager_id: string | number; search?: string; limit?: number }) =>
|
||||
api.get<{ data: ChatSummary[]; total_count: number }>('/telephony/chats', { params: p }).then((r) => r.data),
|
||||
// Переписка постранично: before — id самого раннего из уже загруженных сообщений
|
||||
thread: (chatId: string, p: { before?: string; limit?: number }) =>
|
||||
api.get<{ data: ChatMessage[]; has_more: boolean }>(`/telephony/chats/${chatId}/messages`, { params: p }).then((r) => r.data),
|
||||
download: (params: ReportParams) =>
|
||||
api.get('/telephony/report/xlsx', { params, responseType: 'blob' }).then((r) => r.data as BlobPart),
|
||||
}
|
||||
|
|
@ -6,10 +6,11 @@ import { ModalsProvider } from '@mantine/modals'
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import { theme } from './theme'
|
||||
import { theme } from './theme/theme'
|
||||
import '@mantine/core/styles.css'
|
||||
import '@mantine/notifications/styles.css'
|
||||
import '@mantine/dates/styles.css'
|
||||
import ErrorBoundary from './components/DiagnosticErrorBoundary'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
|
|
@ -24,10 +25,12 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
|
|||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MantineProvider theme={theme}>
|
||||
<MantineProvider theme={theme} defaultColorScheme="auto">
|
||||
<ModalsProvider>
|
||||
<Notifications position="top-right" />
|
||||
<ErrorBoundary fullPage>
|
||||
<App />
|
||||
</ErrorBoundary>
|
||||
</ModalsProvider>
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>
|
||||
|
|
|
|||
|
|
@ -1,426 +1,346 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
SimpleGrid,
|
||||
Paper,
|
||||
Text,
|
||||
Group,
|
||||
Stack,
|
||||
Loader,
|
||||
Center,
|
||||
Badge,
|
||||
Progress,
|
||||
Alert,
|
||||
Box,
|
||||
ThemeIcon,
|
||||
ActionIcon, Alert, Avatar, Badge, Box, Button, Group, Progress, ScrollArea,
|
||||
SimpleGrid, Skeleton, Stack, Text, ThemeIcon, Tooltip, UnstyledButton,
|
||||
} from '@mantine/core'
|
||||
import {
|
||||
IconUsers,
|
||||
IconFileCheck,
|
||||
IconBuilding,
|
||||
IconShield,
|
||||
IconCategory,
|
||||
IconUserCheck,
|
||||
IconAlertTriangle,
|
||||
IconClock,
|
||||
IconTrendingUp,
|
||||
IconAlertCircle,
|
||||
IconAlertCircle, IconAlertTriangle, IconArrowBackUp, IconCategory, IconChecklist,
|
||||
IconChevronRight, IconFileCheck, IconRefresh, IconTrendingUp, IconUserExclamation,
|
||||
type Icon,
|
||||
} 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 { useQuery } from '@tanstack/react-query'
|
||||
import { Link } from 'react-router-dom'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/ru'
|
||||
import { dashboardApi } from '@/api/dashboard'
|
||||
import type { DashboardStats } from '@/api/dashboard'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import TopicGapsModal from '@/components/TopicGapsModal.tsx'
|
||||
import { PageHeader } from '@/components/ui/PageHeader'
|
||||
import { Panel } from '@/components/ui/Panel'
|
||||
import { StatCard } from '@/components/ui/StatCard'
|
||||
import { StatusBreakdown } from '@/components/ui/StatusBreakdown'
|
||||
import { TrendChart } from '@/components/ui/TrendChart'
|
||||
import { APPROVAL_STATUS, TASK_STATUS } from '@/components/ui/statuses'
|
||||
import { plural } from '@/lib/plural'
|
||||
import classes from '@/components/ui/ui.module.css'
|
||||
|
||||
dayjs.locale('ru')
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
draft: '#868e96',
|
||||
pending: '#228be6',
|
||||
approved: '#40c057',
|
||||
rejected: '#fa5252',
|
||||
revoked: '#fd7e14',
|
||||
revision: '#7950f2',
|
||||
interface AttentionItem {
|
||||
id: string
|
||||
color: string
|
||||
icon: Icon
|
||||
title: string
|
||||
description: string
|
||||
to?: string
|
||||
onClick?: () => void
|
||||
}
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
draft: 'Черновики',
|
||||
pending: 'На согласовании',
|
||||
approved: 'Согласованы',
|
||||
rejected: 'Отклонены',
|
||||
revoked: 'Отозваны',
|
||||
revision: 'На доработке',
|
||||
function AttentionRow({ item }: { item: AttentionItem }) {
|
||||
const content = (
|
||||
<Group wrap="nowrap" gap="sm">
|
||||
<ThemeIcon variant="light" color={item.color} size={32} radius="md">
|
||||
<item.icon size={16} stroke={1.7} />
|
||||
</ThemeIcon>
|
||||
<Box style={{ flex: 1, minWidth: 0 }}>
|
||||
<Text size="sm" fw={500}>{item.title}</Text>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>{item.description}</Text>
|
||||
</Box>
|
||||
<IconChevronRight size={16} color="var(--mantine-color-dimmed)" />
|
||||
</Group>
|
||||
)
|
||||
|
||||
if (item.to) {
|
||||
return <UnstyledButton component={Link} to={item.to} className={classes.row}>{content}</UnstyledButton>
|
||||
}
|
||||
return <UnstyledButton onClick={item.onClick} className={classes.row}>{content}</UnstyledButton>
|
||||
}
|
||||
|
||||
export default function Dashboard() {
|
||||
const [stats, setStats] = useState<DashboardStats | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const loadData = async () => {
|
||||
try {
|
||||
const response = await dashboardApi.getStats()
|
||||
setStats(response.data)
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.error_description || 'Ошибка загрузки')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
loadData()
|
||||
}, [])
|
||||
|
||||
if (loading) {
|
||||
function DashboardSkeleton() {
|
||||
return (
|
||||
<Center h={400}>
|
||||
<Loader size="xl" />
|
||||
</Center>
|
||||
<Stack gap="lg">
|
||||
<PageHeader title="Обзор" />
|
||||
<SimpleGrid cols={{ base: 1, xs: 2, lg: 4 }}>
|
||||
{[0, 1, 2, 3].map((i) => <Skeleton key={i} h={112} radius="md" />)}
|
||||
</SimpleGrid>
|
||||
<SimpleGrid cols={{ base: 1, lg: 2 }}>
|
||||
<Skeleton h={300} radius="md" />
|
||||
<Skeleton h={300} radius="md" />
|
||||
</SimpleGrid>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
const countOf = (items: { status: string; count: number }[], status: string) =>
|
||||
items.find((i) => i.status === status)?.count ?? 0
|
||||
|
||||
export default function Dashboard() {
|
||||
const { user } = useAuth()
|
||||
const isObserver = user?.is_observer === true
|
||||
const [gapsOpened, setGapsOpened] = useState(false)
|
||||
|
||||
const { data: stats, isLoading, isFetching, error, refetch } = useQuery({
|
||||
queryKey: ['dashboard-stats'],
|
||||
queryFn: async () => (await dashboardApi.getStats()).data as DashboardStats,
|
||||
refetchInterval: 60_000,
|
||||
})
|
||||
|
||||
if (isLoading) return <DashboardSkeleton />
|
||||
|
||||
if (error || !stats) {
|
||||
const message = (error as any)?.response?.data?.error_description || 'Не удалось загрузить данные'
|
||||
return (
|
||||
<Alert icon={<IconAlertCircle size={16} />} color="red" title="Ошибка">
|
||||
{error || 'Не удалось загрузить данные'}
|
||||
<Stack gap="xs" align="flex-start">
|
||||
<Text size="sm">{message}</Text>
|
||||
<Button size="xs" variant="default" onClick={() => refetch()}>Повторить</Button>
|
||||
</Stack>
|
||||
</Alert>
|
||||
)
|
||||
}
|
||||
|
||||
// Фильтруем нулевые значения для pie chart
|
||||
const chartData = stats.statusData.filter(s => s.count > 0)
|
||||
const totalApprovals = chartData.reduce((sum, s) => sum + s.count, 0)
|
||||
// --- производные метрики ---
|
||||
const tasksInWork = countOf(stats.taskStatusData, 'pending')
|
||||
const tasksQueued = countOf(stats.taskStatusData, 'waiting')
|
||||
const createdSeries = stats.dailyData.map((d) => d.created)
|
||||
const created7 = createdSeries.reduce((s, v) => s + v, 0)
|
||||
const approved7 = stats.dailyData.reduce((s, d) => s + d.approved, 0)
|
||||
const cutoff = dayjs().subtract(stats.oldPendingDays, 'day').format('YYYY-MM-DD')
|
||||
|
||||
// --- «Требует внимания» ---
|
||||
const attention: AttentionItem[] = []
|
||||
|
||||
if (stats.oldPendingCount > 0) {
|
||||
const n = stats.oldPendingCount
|
||||
const d = stats.oldPendingDays
|
||||
attention.push({
|
||||
id: 'old',
|
||||
color: 'orange',
|
||||
icon: IconAlertTriangle,
|
||||
title: `${n} ${plural(n, ['заявка', 'заявки', 'заявок'])} на согласовании дольше ${d} ${plural(d, ['дня', 'дней', 'дней'])}`,
|
||||
description: 'Стоит напомнить согласующим',
|
||||
to: `/approvals?status=pending&date_to=${cutoff}`,
|
||||
})
|
||||
}
|
||||
|
||||
if (stats.approvals.revision > 0) {
|
||||
const n = stats.approvals.revision
|
||||
attention.push({
|
||||
id: 'revision',
|
||||
color: 'violet',
|
||||
icon: IconArrowBackUp,
|
||||
title: `${n} ${plural(n, ['заявка', 'заявки', 'заявок'])} на доработке`,
|
||||
description: 'Возвращены согласующими, ждут действий инициатора',
|
||||
to: '/approvals?status=revision',
|
||||
})
|
||||
}
|
||||
|
||||
if (!isObserver && stats.topicGaps.length > 0) {
|
||||
const n = stats.topicGaps.length
|
||||
attention.push({
|
||||
id: 'gaps',
|
||||
color: 'orange',
|
||||
icon: IconCategory,
|
||||
title: `${n} ${plural(n, ['тема', 'темы', 'тем'])} без порядка согласования`,
|
||||
description: 'Сотрудник сможет создать заявку, но согласовать её будет некому',
|
||||
onClick: () => setGapsOpened(true),
|
||||
})
|
||||
}
|
||||
|
||||
if (!isObserver && stats.usersWithoutHierarchy.length > 0) {
|
||||
const list = stats.usersWithoutHierarchy
|
||||
const names = list.slice(0, 3).map((u) => u.full_name || `ID ${u.user_id}`).join(', ')
|
||||
const rest = list.length - 3
|
||||
attention.push({
|
||||
id: 'hierarchy',
|
||||
color: 'red',
|
||||
icon: IconUserExclamation,
|
||||
title: `${list.length} ${plural(list.length, ['сотрудник', 'сотрудника', 'сотрудников'])} без иерархии согласования`,
|
||||
description: rest > 0 ? `${names} и ещё ${rest}` : names,
|
||||
to: '/hierarchies',
|
||||
})
|
||||
}
|
||||
|
||||
const maxCategory = Math.max(1, ...stats.categoryBreakdown.map((c) => c.total_count))
|
||||
|
||||
const catalog = [
|
||||
{ label: 'Пользователи', value: stats.users.total, to: '/users',
|
||||
hint: stats.users.blocked > 0 ? `${stats.users.blocked} заблокировано` : `${stats.users.active} активных` },
|
||||
{ label: 'Темы', value: stats.topics.total, to: '/topics', hint: `${stats.topics.active} активных` },
|
||||
{ label: 'Категории', value: stats.categories, to: '/categories' },
|
||||
{ label: 'Отделы', value: stats.departments, to: '/departments' },
|
||||
{ label: 'Роли', value: stats.roles, to: '/roles' },
|
||||
{ label: 'Исполнители', value: stats.executors, to: '/executors' },
|
||||
]
|
||||
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
{/* Заголовок */}
|
||||
<Group justify="space-between">
|
||||
<div>
|
||||
<Text size="xl" fw={700}>Dashboard</Text>
|
||||
<Text size="sm" c="dimmed">Обзор системы согласований</Text>
|
||||
</div>
|
||||
<Badge size="lg" variant="light" color="blue">
|
||||
{dayjs().format('DD MMMM YYYY')}
|
||||
</Badge>
|
||||
</Group>
|
||||
<PageHeader
|
||||
title="Обзор"
|
||||
description={dayjs().format('dddd, D MMMM')}
|
||||
actions={
|
||||
<Tooltip label="Обновить">
|
||||
<ActionIcon size="lg" loading={isFetching} onClick={() => refetch()} aria-label="Обновить">
|
||||
<IconRefresh size={18} stroke={1.6} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Alert: старые pending заявки */}
|
||||
{stats.oldPendingCount > 0 && (
|
||||
<Alert
|
||||
icon={<IconAlertTriangle size={16} />}
|
||||
color="orange"
|
||||
variant="light"
|
||||
title={`⚠️ ${stats.oldPendingCount} заявок требуют внимания`}
|
||||
>
|
||||
<Text size="sm">
|
||||
Есть заявки, которые находятся на согласовании более 7 дней.
|
||||
</Text>
|
||||
</Alert>
|
||||
{attention.length > 0 && (
|
||||
<Panel title="Требует внимания" extra={<Badge color="orange">{attention.length}</Badge>}>
|
||||
<Stack gap={2} mx={-8} mb={-8}>
|
||||
{attention.map((item) => <AttentionRow key={item.id} item={item} />)}
|
||||
</Stack>
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
{/* KPI карточки */}
|
||||
<SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }} spacing="md">
|
||||
<SimpleGrid cols={{ base: 1, xs: 2, lg: 4 }}>
|
||||
<StatCard
|
||||
title="Пользователи"
|
||||
value={stats.users.total}
|
||||
subtitle={`${stats.users.active} активных`}
|
||||
icon={IconUsers}
|
||||
color="blue"
|
||||
trend={stats.users.blocked > 0 ? `${stats.users.blocked} заблокировано` : undefined}
|
||||
/>
|
||||
<StatCard
|
||||
title="Заявки"
|
||||
value={stats.approvals.total}
|
||||
subtitle={`${stats.approvals.today} за сегодня`}
|
||||
label="На согласовании"
|
||||
value={stats.approvals.pending}
|
||||
hint={stats.oldPendingCount > 0 ? `${stats.oldPendingCount} просрочено` : 'Просрочек нет'}
|
||||
icon={IconFileCheck}
|
||||
color="green"
|
||||
trend={stats.approvals.pending > 0 ? `${stats.approvals.pending} в работе` : undefined}
|
||||
color={stats.oldPendingCount > 0 ? 'orange' : 'brand'}
|
||||
to="/approvals?status=pending"
|
||||
/>
|
||||
<StatCard
|
||||
title="Темы"
|
||||
value={stats.topics.total}
|
||||
subtitle={`${stats.topics.active} активных`}
|
||||
icon={IconCategory}
|
||||
label="На доработке"
|
||||
value={stats.approvals.revision}
|
||||
hint="Ждут действий инициатора"
|
||||
icon={IconArrowBackUp}
|
||||
color="violet"
|
||||
trend={`${stats.categories} категорий`}
|
||||
to="/approvals?status=revision"
|
||||
/>
|
||||
<StatCard
|
||||
title="Отделы / Роли"
|
||||
value={stats.departments}
|
||||
subtitle={`${stats.roles} ролей`}
|
||||
icon={IconBuilding}
|
||||
color="orange"
|
||||
trend={`${stats.executors} исполнителей`}
|
||||
label="Задачи в работе"
|
||||
value={tasksInWork}
|
||||
hint={`${tasksQueued} в очереди`}
|
||||
icon={IconChecklist}
|
||||
color="teal"
|
||||
to="/approval-tasks?status=pending"
|
||||
/>
|
||||
<StatCard
|
||||
label="Создано за 7 дней"
|
||||
value={created7}
|
||||
hint={`Сегодня ${stats.approvals.today} · согласовано за неделю ${approved7}`}
|
||||
icon={IconTrendingUp}
|
||||
color="gray"
|
||||
spark={createdSeries}
|
||||
/>
|
||||
</SimpleGrid>
|
||||
|
||||
{/* Графики */}
|
||||
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
|
||||
{/* Pie chart */}
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Group justify="space-between" mb="md">
|
||||
<Text fw={600}>Распределение заявок по статусам</Text>
|
||||
<Badge variant="light">{totalApprovals} всего</Badge>
|
||||
</Group>
|
||||
|
||||
{chartData.length === 0 ? (
|
||||
<Center h={250}>
|
||||
<Text c="dimmed">Нет данных</Text>
|
||||
</Center>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={chartData}
|
||||
dataKey="count"
|
||||
nameKey="status"
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
innerRadius={60}
|
||||
outerRadius={90}
|
||||
paddingAngle={2}
|
||||
label={(entry: any) => STATUS_LABELS[entry.payload?.status] || entry.payload?.status}
|
||||
<Panel
|
||||
title="Отсутствуют сегодня"
|
||||
extra={stats.absentToday.length > 0 && <Badge color="gray">{stats.absentToday.length}</Badge>}
|
||||
>
|
||||
{chartData.map((entry, index) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={STATUS_COLORS[entry.status] || '#868e96'}
|
||||
/>
|
||||
{stats.absentToday.length === 0 ? (
|
||||
<Text size="sm" c="dimmed">Сегодня все на месте</Text>
|
||||
) : (
|
||||
<ScrollArea.Autosize mah={280} type="auto">
|
||||
<Stack gap="sm">
|
||||
{stats.absentToday.map((p, i) => (
|
||||
<Group key={i} gap="sm" wrap="nowrap">
|
||||
<Avatar size={28} radius="xl" color="initials" name={p.name} />
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text size="sm" fw={500} truncate>{p.name}</Text>
|
||||
<Text size="xs" c="dimmed" truncate>{p.description}</Text>
|
||||
</Box>
|
||||
</Group>
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip
|
||||
formatter={(value: any, name: any) => [
|
||||
value,
|
||||
STATUS_LABELS[name] || name
|
||||
</Stack>
|
||||
</ScrollArea.Autosize>
|
||||
)}
|
||||
</Panel>
|
||||
|
||||
<SimpleGrid cols={{ base: 1, lg: 2 }}>
|
||||
<Panel
|
||||
title="Заявки по статусам"
|
||||
extra={<Text size="xs" c="dimmed">Всего {stats.approvals.total}</Text>}
|
||||
>
|
||||
<StatusBreakdown
|
||||
items={stats.statusData}
|
||||
meta={APPROVAL_STATUS}
|
||||
linkTo={(s) => `/approvals?status=${s}`}
|
||||
/>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Заявки за 7 дней">
|
||||
<TrendChart
|
||||
data={stats.dailyData}
|
||||
series={[
|
||||
{ key: 'created', label: 'Создано', color: 'brand' },
|
||||
{ key: 'approved', label: 'Согласовано', color: 'green' },
|
||||
]}
|
||||
/>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</Paper>
|
||||
</Panel>
|
||||
</SimpleGrid>
|
||||
|
||||
{/* Line chart */}
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Group justify="space-between" mb="md">
|
||||
<Text fw={600}>Динамика за 7 дней</Text>
|
||||
<Badge variant="light" color="blue">Заявки</Badge>
|
||||
</Group>
|
||||
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<LineChart data={stats.dailyData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tickFormatter={(d) => dayjs(d).format('DD.MM')}
|
||||
<SimpleGrid cols={{ base: 1, lg: 2 }}>
|
||||
<Panel title="Задачи по статусам">
|
||||
<StatusBreakdown
|
||||
items={stats.taskStatusData}
|
||||
meta={TASK_STATUS}
|
||||
linkTo={(s) => `/approval-tasks?status=${s}`}
|
||||
/>
|
||||
<YAxis />
|
||||
<Tooltip
|
||||
labelFormatter={(d) => dayjs(d).format('DD.MM.YYYY')}
|
||||
formatter={(value: any, name: any) => [
|
||||
value,
|
||||
name === 'created' ? 'Создано' : 'Согласовано'
|
||||
</Panel>
|
||||
|
||||
<Panel title="Задачи за 7 дней">
|
||||
<TrendChart
|
||||
data={stats.taskDailyData}
|
||||
series={[
|
||||
{ key: 'created', label: 'Создано', color: 'brand' },
|
||||
{ key: 'completed', label: 'Выполнено', color: 'teal' },
|
||||
]}
|
||||
/>
|
||||
<Legend
|
||||
formatter={(value) =>
|
||||
value === 'created' ? 'Создано' : 'Согласовано'
|
||||
}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="created"
|
||||
stroke="#228be6"
|
||||
strokeWidth={2}
|
||||
dot={{ r: 4 }}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="approved"
|
||||
stroke="#40c057"
|
||||
strokeWidth={2}
|
||||
dot={{ r: 4 }}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</Paper>
|
||||
</Panel>
|
||||
</SimpleGrid>
|
||||
|
||||
{/* Топ списки */}
|
||||
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
|
||||
{/* Топ тем */}
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Group mb="md">
|
||||
<ThemeIcon variant="light" color="violet" size="lg">
|
||||
<IconTrendingUp size={18} />
|
||||
</ThemeIcon>
|
||||
<Text fw={600}>Топ-5 самых активных тем</Text>
|
||||
</Group>
|
||||
|
||||
{stats.topTopics.length === 0 ? (
|
||||
<Center h={200}>
|
||||
<Text c="dimmed">Нет данных</Text>
|
||||
</Center>
|
||||
<SimpleGrid cols={{ base: 1, lg: 2 }}>
|
||||
<Panel title="Заявки по категориям">
|
||||
{stats.categoryBreakdown.length === 0 ? (
|
||||
<Text size="sm" c="dimmed">Нет данных</Text>
|
||||
) : (
|
||||
<Stack gap="sm">
|
||||
{stats.topTopics.map((topic, index) => {
|
||||
const maxCount = Math.max(...stats.topTopics.map(t => t.total_count))
|
||||
const percent = (topic.total_count / maxCount) * 100
|
||||
|
||||
return (
|
||||
<Box key={topic.id}>
|
||||
<Group justify="space-between" mb={4}>
|
||||
<Group gap="xs">
|
||||
<Badge size="sm" variant="light" color="gray">
|
||||
#{index + 1}
|
||||
</Badge>
|
||||
<div>
|
||||
<Text size="sm" fw={500} lineClamp={1}>{topic.name}</Text>
|
||||
<Text size="xs" c="dimmed">{topic.category_name}</Text>
|
||||
</div>
|
||||
</Group>
|
||||
<Group gap="xs">
|
||||
<Text size="sm" fw={600}>{topic.total_count}</Text>
|
||||
{topic.pending_count > 0 && (
|
||||
<Badge size="xs" color="blue" variant="light">
|
||||
{topic.pending_count} в работе
|
||||
</Badge>
|
||||
<Stack gap="md">
|
||||
{stats.categoryBreakdown.map((cat) => (
|
||||
<Box key={cat.id}>
|
||||
<Group justify="space-between" mb={6} wrap="nowrap">
|
||||
<Text size="sm" truncate>{cat.name}</Text>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
{cat.pending_count > 0 && (
|
||||
<Text size="xs" c="dimmed">{cat.pending_count} в работе</Text>
|
||||
)}
|
||||
<Text size="sm" fw={500}>{cat.total_count}</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
<Progress value={percent} size="sm" color="violet" />
|
||||
<Progress value={(cat.total_count / maxCategory) * 100} size="xs" color="gray" />
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
{/* Топ согласующих */}
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Group mb="md">
|
||||
<ThemeIcon variant="light" color="blue" size="lg">
|
||||
<IconUsers size={18} />
|
||||
</ThemeIcon>
|
||||
<Text fw={600}>Топ-5 согласующих</Text>
|
||||
</Group>
|
||||
|
||||
{stats.topApprovers.length === 0 ? (
|
||||
<Center h={200}>
|
||||
<Text c="dimmed">Нет данных</Text>
|
||||
</Center>
|
||||
) : (
|
||||
<Stack gap="sm">
|
||||
{stats.topApprovers.map((approver, index) => {
|
||||
const maxSteps = Math.max(...stats.topApprovers.map(a => a.total_steps))
|
||||
const percent = (approver.total_steps / maxSteps) * 100
|
||||
|
||||
return (
|
||||
<Box key={approver.user_id}>
|
||||
<Group justify="space-between" mb={4}>
|
||||
<Group gap="xs">
|
||||
<Badge size="sm" variant="light" color="gray">
|
||||
#{index + 1}
|
||||
</Badge>
|
||||
<div>
|
||||
<Text size="sm" fw={500}>{approver.full_name}</Text>
|
||||
<Text size="xs" c="dimmed">{approver.department_name}</Text>
|
||||
</div>
|
||||
</Group>
|
||||
<Group gap="xs">
|
||||
<Text size="sm" fw={600}>{approver.total_steps}</Text>
|
||||
{approver.pending_steps > 0 && (
|
||||
<Badge size="xs" color="orange" variant="light">
|
||||
{approver.pending_steps} ожидают
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
</Group>
|
||||
<Progress value={percent} size="sm" color="blue" />
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
</Stack>
|
||||
)}
|
||||
</Paper>
|
||||
</Panel>
|
||||
</SimpleGrid>
|
||||
|
||||
{/* Заявки на доработке */}
|
||||
{stats.approvals.revision > 0 && (
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Group mb="md">
|
||||
<ThemeIcon variant="light" color="orange" size="lg">
|
||||
<IconClock size={18} />
|
||||
</ThemeIcon>
|
||||
<Text fw={600}>Требуют внимания: {stats.approvals.revision} заявок на доработке</Text>
|
||||
</Group>
|
||||
<Text size="sm" c="dimmed">
|
||||
Эти заявки были возвращены согласующими на доработку и требуют действий от инициаторов.
|
||||
</Text>
|
||||
</Paper>
|
||||
{!isObserver && (
|
||||
<Panel title="Справочники">
|
||||
<SimpleGrid cols={{ base: 2, sm: 3, lg: 6 }} spacing="xs" mx={-8} mb={-8}>
|
||||
{catalog.map((c) => (
|
||||
<UnstyledButton key={c.label} component={Link} to={c.to} className={classes.row}>
|
||||
<Text size="xs" c="dimmed">{c.label}</Text>
|
||||
<Text fz={20} fw={600} lh={1.3}>{c.value}</Text>
|
||||
{c.hint && <Text size="xs" c="dimmed">{c.hint}</Text>}
|
||||
</UnstyledButton>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
<TopicGapsModal
|
||||
opened={gapsOpened}
|
||||
onClose={() => setGapsOpened(false)}
|
||||
gaps={stats.topicGaps}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
// Компонент карточки статистики
|
||||
interface StatCardProps {
|
||||
title: string
|
||||
value: number | string
|
||||
subtitle?: string
|
||||
icon: any
|
||||
color: string
|
||||
trend?: string
|
||||
}
|
||||
|
||||
function StatCard({ title, value, subtitle, icon: Icon, color, trend }: StatCardProps) {
|
||||
return (
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Group justify="space-between" align="flex-start">
|
||||
<Stack gap={4}>
|
||||
<Text c="dimmed" size="xs" tt="uppercase" fw={700}>
|
||||
{title}
|
||||
</Text>
|
||||
<Text size="xl" fw={700} c={color}>
|
||||
{value}
|
||||
</Text>
|
||||
{subtitle && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{subtitle}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
<ThemeIcon
|
||||
variant="light"
|
||||
color={color}
|
||||
size="xl"
|
||||
radius="md"
|
||||
>
|
||||
<Icon size={24} />
|
||||
</ThemeIcon>
|
||||
</Group>
|
||||
|
||||
{trend && (
|
||||
<Box
|
||||
mt="md"
|
||||
pt="md"
|
||||
style={{
|
||||
borderTop: '1px solid var(--mantine-color-gray-3)',
|
||||
}}
|
||||
>
|
||||
<Text size="xs" c="dimmed">{trend}</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,86 +1,102 @@
|
|||
import { useState } from 'react'
|
||||
import {
|
||||
Container,
|
||||
Paper,
|
||||
Title,
|
||||
Text,
|
||||
TextInput,
|
||||
PasswordInput,
|
||||
Button,
|
||||
Group,
|
||||
} from '@mantine/core'
|
||||
import { Alert, Box, Button, Paper, PasswordInput, Stack, Text, TextInput, Title } from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import { IconAlertCircle } from '@tabler/icons-react'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { ColorSchemeToggle } from '@/components/ui/ColorSchemeToggle'
|
||||
|
||||
export default function Login() {
|
||||
const { login } = useAuth()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [capsLock, setCapsLock] = useState(false)
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
login: '',
|
||||
password: '',
|
||||
},
|
||||
initialValues: { login: '', password: '' },
|
||||
validate: {
|
||||
login: (value: string | any[]) => (value.length < 3 ? 'Логин должен содержать минимум 3 символа' : null),
|
||||
password: (value: string | any[]) => (value.length < 4 ? 'Пароль должен содержать минимум 4 символа' : null),
|
||||
login: (v) => (v.trim().length < 3 ? 'Минимум 3 символа' : null),
|
||||
password: (v) => (v.length < 4 ? 'Минимум 4 символа' : null),
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
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',
|
||||
})
|
||||
await login(values.login.trim(), values.password)
|
||||
} catch (e: any) {
|
||||
setError(e.response?.data?.error_description || 'Неверный логин или пароль')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Container size={420} my={40}>
|
||||
<Title ta="center" mb="md">
|
||||
Корпоративная панель администратора
|
||||
</Title>
|
||||
<Text c="dimmed" size="sm" ta="center" mb="xl">
|
||||
Введите свои данные для входа в систему
|
||||
</Text>
|
||||
<Box
|
||||
mih="100dvh"
|
||||
p="md"
|
||||
style={{ background: 'var(--app-bg)', display: 'grid', placeItems: 'center', position: 'relative' }}
|
||||
>
|
||||
<Box style={{ position: 'absolute', top: 16, right: 16 }}>
|
||||
<ColorSchemeToggle />
|
||||
</Box>
|
||||
|
||||
<Paper withBorder shadow="md" p={30} mt={30} radius="md">
|
||||
<Stack w="100%" maw={400} gap="xl">
|
||||
<Stack align="center" gap={4}>
|
||||
<Box
|
||||
w={44}
|
||||
h={44}
|
||||
mb="xs"
|
||||
style={{
|
||||
borderRadius: 12,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
background: 'var(--mantine-primary-color-filled)',
|
||||
color: '#fff',
|
||||
fontWeight: 700,
|
||||
fontSize: 20,
|
||||
}}
|
||||
>
|
||||
Р
|
||||
</Box>
|
||||
<Title order={3}>Вход в систему</Title>
|
||||
<Text size="sm" c="dimmed">Портал РусПЭТ</Text>
|
||||
</Stack>
|
||||
|
||||
<Paper p="xl">
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="md">
|
||||
{error && (
|
||||
<Alert color="red" icon={<IconAlertCircle size={16} />} p="sm">
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<TextInput
|
||||
label="Логин"
|
||||
placeholder="admin"
|
||||
required
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
{...form.getInputProps('login')}
|
||||
/>
|
||||
|
||||
<PasswordInput
|
||||
label="Пароль"
|
||||
placeholder="your password"
|
||||
required
|
||||
mt="md"
|
||||
placeholder="Введите пароль"
|
||||
autoComplete="current-password"
|
||||
description={capsLock ? 'Включён Caps Lock' : undefined}
|
||||
onKeyDown={(e) => setCapsLock(e.getModifierState('CapsLock'))}
|
||||
onKeyUp={(e) => setCapsLock(e.getModifierState('CapsLock'))}
|
||||
{...form.getInputProps('password')}
|
||||
/>
|
||||
|
||||
<Group justify="space-between" mt="xl">
|
||||
<Button type="submit" fullWidth loading={loading}>
|
||||
<Button type="submit" fullWidth loading={loading} mt="xs">
|
||||
Войти
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
</Paper>
|
||||
</Container>
|
||||
</Stack>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,277 @@
|
|||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { ActionIcon, Badge, Select, Stack, Text, TextInput, Tooltip } from '@mantine/core'
|
||||
import { DatePickerInput } from '@mantine/dates'
|
||||
import { useDebouncedValue } from '@mantine/hooks'
|
||||
import { IconCalendar, IconSearch, IconTrash } from '@tabler/icons-react'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/ru'
|
||||
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useAdminLogs, useDeleteAdminLog } from '@/features/adminLogs/hooks/useAdminLogs'
|
||||
import type { AdminActionLog } from '@/api/adminLogs'
|
||||
import { formatMsk } from '@/utils/date'
|
||||
|
||||
import { PageHeader } from '@/components/ui/PageHeader'
|
||||
import { FilterBar } from '@/components/ui/FilterBar'
|
||||
import { DataTable, type Column } from '@/components/ui/DataTable'
|
||||
import { ConfirmModal } from '@/components/ui/ConfirmModal'
|
||||
import AdminLogDrawer from './components/AdminLogDrawer'
|
||||
|
||||
dayjs.locale('ru')
|
||||
|
||||
const LIMIT = 50
|
||||
|
||||
const ACTION_META: Record<string, { label: string; color: string }> = {
|
||||
create: { label: 'Создание', color: 'green' },
|
||||
update: { label: 'Изменение', color: 'blue' },
|
||||
delete: { label: 'Удаление', color: 'red' },
|
||||
}
|
||||
|
||||
const ENTITY_OPTIONS = [
|
||||
{ value: 'user', label: 'Пользователь' },
|
||||
{ value: 'admin', label: 'Администратор' },
|
||||
{ value: 'department', label: 'Отдел' },
|
||||
{ value: 'role', label: 'Роль' },
|
||||
{ value: 'permission', label: 'Право' },
|
||||
{ value: 'category', label: 'Категория' },
|
||||
{ value: 'topic', label: 'Тема' },
|
||||
{ value: 'hierarchy', label: 'Иерархия' },
|
||||
{ value: 'flow_node', label: 'Узел дерева' },
|
||||
{ value: 'approval_task', label: 'Задача' },
|
||||
{ value: 'notification', label: 'Рассылка' },
|
||||
]
|
||||
|
||||
interface Filters {
|
||||
adminLogin: string
|
||||
action: string | null
|
||||
entityType: string | null
|
||||
entityId: string
|
||||
range: [Date | null, Date | null]
|
||||
}
|
||||
|
||||
const EMPTY_FILTERS: Filters = {
|
||||
adminLogin: '',
|
||||
action: null,
|
||||
entityType: null,
|
||||
entityId: '',
|
||||
range: [null, null],
|
||||
}
|
||||
|
||||
const fmtDate = (d: Date) => dayjs(d).format('YYYY-MM-DD')
|
||||
|
||||
export default function AdminLogsPage() {
|
||||
const { user: currentUser } = useAuth()
|
||||
const isRoot = currentUser?.is_root === true
|
||||
|
||||
const [page, setPage] = useState(1)
|
||||
const [filters, setFilters] = useState<Filters>(EMPTY_FILTERS)
|
||||
const [searchInput, setSearchInput] = useState('')
|
||||
const [debouncedSearch] = useDebouncedValue(searchInput.trim(), 400)
|
||||
|
||||
const [selectedLog, setSelectedLog] = useState<AdminActionLog | null>(null)
|
||||
const [deleteTarget, setDeleteTarget] = useState<AdminActionLog | null>(null)
|
||||
|
||||
// При изменении текстового поиска сбрасываем страницу на первую
|
||||
useEffect(() => setPage(1), [debouncedSearch])
|
||||
|
||||
const updateFilter = (patch: Partial<Filters>) => {
|
||||
setFilters((prev) => ({ ...prev, ...patch }))
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
const requestParams = useMemo(() => {
|
||||
const params: Record<string, any> = { offset: (page - 1) * LIMIT, limit: LIMIT }
|
||||
if (filters.adminLogin) params.admin_login = filters.adminLogin
|
||||
if (filters.action) params.action = filters.action
|
||||
if (filters.entityType) params.entity_type = filters.entityType
|
||||
if (filters.entityId) params.entity_id = Number(filters.entityId)
|
||||
if (debouncedSearch.length >= 2) params.search = debouncedSearch
|
||||
if (filters.range[0]) params.date_from = fmtDate(filters.range[0])
|
||||
if (filters.range[1]) params.date_to = fmtDate(filters.range[1])
|
||||
return params
|
||||
}, [page, filters, debouncedSearch])
|
||||
|
||||
const { data, isLoading, isFetching } = useAdminLogs(requestParams)
|
||||
const deleteLog = useDeleteAdminLog()
|
||||
|
||||
const total = data?.total_count ?? 0
|
||||
|
||||
const activeCount = [
|
||||
filters.adminLogin,
|
||||
filters.action,
|
||||
filters.entityType,
|
||||
filters.entityId,
|
||||
debouncedSearch.length >= 2,
|
||||
filters.range[0] || filters.range[1],
|
||||
].filter(Boolean).length
|
||||
|
||||
const handleReset = () => {
|
||||
setSearchInput('')
|
||||
setFilters(EMPTY_FILTERS)
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteTarget) return
|
||||
await deleteLog.mutateAsync(deleteTarget.id)
|
||||
setDeleteTarget(null)
|
||||
}
|
||||
|
||||
const columns: Column<AdminActionLog>[] = [
|
||||
{
|
||||
key: 'created',
|
||||
header: 'Когда',
|
||||
width: 150,
|
||||
cell: (r) => <Text size="sm" c="dimmed">{formatMsk(r.created_at)}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'admin',
|
||||
header: 'Администратор',
|
||||
cell: (r) => <Text size="sm" fw={500}>{r.admin_login}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'action',
|
||||
header: 'Действие',
|
||||
width: 140,
|
||||
cell: (r) => {
|
||||
const meta = ACTION_META[r.action]
|
||||
return (
|
||||
<Badge variant="light" color={meta?.color || 'gray'} size="sm">
|
||||
{meta?.label || r.action}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'entity',
|
||||
header: 'Сущность',
|
||||
width: 180,
|
||||
cell: (r) => (
|
||||
<Badge variant="outline" color="gray" size="sm" tt="none">
|
||||
{r.entity_type}{r.entity_id ? ` #${r.entity_id}` : ''}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'description',
|
||||
header: 'Описание',
|
||||
cell: (r) => <Text size="sm" lineClamp={2}>{r.description}</Text>,
|
||||
},
|
||||
]
|
||||
|
||||
if (isRoot) {
|
||||
columns.push({
|
||||
key: 'actions',
|
||||
header: '',
|
||||
width: 60,
|
||||
align: 'right',
|
||||
cell: (r) => (
|
||||
<Tooltip label="Удалить (только root)">
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
color="red"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation() // Чтобы не открывался Drawer просмотра
|
||||
setDeleteTarget(r)
|
||||
}}
|
||||
>
|
||||
<IconTrash size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<PageHeader
|
||||
title="Журнал действий администраторов"
|
||||
description={isLoading ? undefined : `Всего записей: ${total}`}
|
||||
/>
|
||||
|
||||
<FilterBar activeCount={activeCount} onReset={handleReset}>
|
||||
<TextInput
|
||||
placeholder="Поиск по описанию"
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.currentTarget.value)}
|
||||
w={220}
|
||||
/>
|
||||
<TextInput
|
||||
placeholder="Администратор"
|
||||
value={filters.adminLogin}
|
||||
onChange={(e) => updateFilter({ adminLogin: e.currentTarget.value })}
|
||||
w={150}
|
||||
/>
|
||||
<Select
|
||||
placeholder="Действие"
|
||||
data={[
|
||||
{ value: 'create', label: 'Создание' },
|
||||
{ value: 'update', label: 'Изменение' },
|
||||
{ value: 'delete', label: 'Удаление' },
|
||||
]}
|
||||
value={filters.action}
|
||||
onChange={(action) => updateFilter({ action })}
|
||||
clearable
|
||||
w={140}
|
||||
/>
|
||||
<Select
|
||||
placeholder="Тип сущности"
|
||||
data={ENTITY_OPTIONS}
|
||||
value={filters.entityType}
|
||||
onChange={(entityType) => updateFilter({ entityType })}
|
||||
searchable
|
||||
clearable
|
||||
w={180}
|
||||
/>
|
||||
<TextInput
|
||||
placeholder="ID сущности"
|
||||
value={filters.entityId}
|
||||
onChange={(e) => updateFilter({ entityId: e.currentTarget.value.replace(/\D/g, '') })}
|
||||
w={110}
|
||||
/>
|
||||
<DatePickerInput
|
||||
type="range"
|
||||
placeholder="Период"
|
||||
valueFormat="D MMM YYYY"
|
||||
leftSection={<IconCalendar size={16} />}
|
||||
value={filters.range}
|
||||
onChange={(range) => updateFilter({ range: range as [Date | null, Date | null] })}
|
||||
clearable
|
||||
w={240}
|
||||
/>
|
||||
</FilterBar>
|
||||
|
||||
<DataTable<AdminActionLog>
|
||||
columns={columns}
|
||||
rows={data?.data ?? []}
|
||||
getRowId={(r) => r.id}
|
||||
loading={isLoading}
|
||||
refreshing={isFetching}
|
||||
onRowClick={setSelectedLog}
|
||||
empty={{
|
||||
title: 'Записей не найдено',
|
||||
description: activeCount > 0 ? 'Попробуйте смягчить фильтры' : undefined,
|
||||
}}
|
||||
pagination={{ page, pageSize: LIMIT, total, onChange: setPage }}
|
||||
/>
|
||||
|
||||
<AdminLogDrawer
|
||||
log={selectedLog}
|
||||
opened={selectedLog !== null}
|
||||
onClose={() => setSelectedLog(null)}
|
||||
/>
|
||||
|
||||
<ConfirmModal
|
||||
opened={deleteTarget !== null}
|
||||
onClose={() => setDeleteTarget(null)}
|
||||
onConfirm={handleDelete}
|
||||
title="Удалить запись журнала?"
|
||||
message="Это действие необратимо. Обычно записи журнала не удаляют — используйте это только если лог содержит чувствительные данные."
|
||||
confirmLabel="Удалить безвозвратно"
|
||||
danger
|
||||
loading={deleteLog.isPending}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
import { useMemo } from 'react'
|
||||
import { Badge, Box, Code, Drawer, Group, Stack, Text } from '@mantine/core'
|
||||
import { IconArrowRight } from '@tabler/icons-react'
|
||||
import type { AdminActionLog } from '@/api/adminLogs'
|
||||
import { InfoList, InfoRow } from '@/components/ui/InfoRow'
|
||||
import { formatMsk } from '@/utils/date'
|
||||
|
||||
interface FieldChange {
|
||||
field: string
|
||||
old: unknown
|
||||
new: unknown
|
||||
}
|
||||
|
||||
interface Props {
|
||||
log: AdminActionLog | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
function formatValue(v: unknown): string {
|
||||
if (v === null || v === undefined || v === '') return '—'
|
||||
if (typeof v === 'boolean') return v ? 'Да' : 'Нет'
|
||||
if (Array.isArray(v)) return v.length ? v.join(', ') : '—'
|
||||
if (typeof v === 'object') return JSON.stringify(v)
|
||||
return String(v)
|
||||
}
|
||||
|
||||
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<Box>
|
||||
<Text size="sm" fw={600} mb="xs">{title}</Text>
|
||||
{children}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default function AdminLogDrawer({ log, opened, onClose }: Props) {
|
||||
const parsed = useMemo(() => {
|
||||
if (!log?.metadata) return null
|
||||
try {
|
||||
return JSON.parse(log.metadata) as {
|
||||
changes?: FieldChange[]
|
||||
snapshot?: Record<string, unknown>
|
||||
[key: string]: unknown
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}, [log])
|
||||
|
||||
return (
|
||||
<Drawer.Root opened={opened} onClose={onClose} position="right" size="min(600px, 100vw)">
|
||||
<Drawer.Overlay backgroundOpacity={0.25} />
|
||||
<Drawer.Content>
|
||||
<Drawer.Header>
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Text fw={600}>Журнал: {log?.entity_type}</Text>
|
||||
{log?.entity_id && <Badge variant="outline" color="gray" tt="none">#{log.entity_id}</Badge>}
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed" mt={2}>
|
||||
{log?.created_at ? formatMsk(log.created_at) : ''}
|
||||
</Text>
|
||||
</Box>
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body pb="xl">
|
||||
{!log ? null : (
|
||||
<Stack gap="xl" mt="sm">
|
||||
<InfoList>
|
||||
<InfoRow label="Администратор">
|
||||
<Text size="sm" fw={500}>{log.admin_login}</Text>
|
||||
</InfoRow>
|
||||
<InfoRow label="Тип действия">
|
||||
<Text size="sm">{log.action}</Text>
|
||||
</InfoRow>
|
||||
<InfoRow label="Описание">
|
||||
<Text size="sm" style={{ textAlign: 'right' }}>{log.description}</Text>
|
||||
</InfoRow>
|
||||
</InfoList>
|
||||
|
||||
{parsed?.changes && parsed.changes.length > 0 && (
|
||||
<Section title="Измененные поля">
|
||||
<Stack gap={0}>
|
||||
{parsed.changes.map((c, i) => (
|
||||
<Box key={i} py={8} style={{ borderBottom: '1px solid var(--mantine-color-default-border)' }}>
|
||||
<Text size="sm" ff="monospace" mb={4}>{c.field}</Text>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Text size="sm" c="red" style={{ flex: 1, wordBreak: 'break-word' }}>
|
||||
{formatValue(c.old)}
|
||||
</Text>
|
||||
<IconArrowRight size={14} color="var(--mantine-color-dimmed)" />
|
||||
<Text size="sm" c="green" style={{ flex: 1, wordBreak: 'break-word' }}>
|
||||
{formatValue(c.new)}
|
||||
</Text>
|
||||
</Group>
|
||||
</Box>
|
||||
))}
|
||||
</Stack>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{parsed?.snapshot && (
|
||||
<Section title="Снапшот объекта">
|
||||
<InfoList>
|
||||
{Object.entries(parsed.snapshot).map(([key, value]) => (
|
||||
<InfoRow key={key} label={key}>
|
||||
<Text size="sm" style={{ textAlign: 'right', wordBreak: 'break-word', maxWidth: 280 }}>
|
||||
{formatValue(value)}
|
||||
</Text>
|
||||
</InfoRow>
|
||||
))}
|
||||
</InfoList>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{!parsed?.changes && !parsed?.snapshot && parsed && (
|
||||
<Section title="Сырые метаданные (JSON)">
|
||||
<Code block style={{ whiteSpace: 'pre-wrap' }}>
|
||||
{JSON.stringify(parsed, null, 2)}
|
||||
</Code>
|
||||
</Section>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
</Drawer.Body>
|
||||
</Drawer.Content>
|
||||
</Drawer.Root>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,367 +1,282 @@
|
|||
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 { useEffect, useState, type ReactNode } from 'react'
|
||||
import { ActionIcon, Avatar, Badge, Box, Button, Group, Menu, SegmentedControl, Stack, Text, TextInput } from '@mantine/core'
|
||||
import { useDebouncedValue } from '@mantine/hooks'
|
||||
import { IconDots, IconLock, IconLockOpen, IconPencil, IconPlus, IconSearch, IconShieldCheck, IconTrash } from '@tabler/icons-react'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/ru'
|
||||
|
||||
import { useAdmins, useDeleteAdmin, useUpdateAdmin } from '@/features/admins/hooks/useAdmins'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { formatMsk } from '@/utils/date'
|
||||
import type { Admin } from '@/types/api'
|
||||
|
||||
import { PageHeader } from '@/components/ui/PageHeader'
|
||||
import { FilterBar } from '@/components/ui/FilterBar'
|
||||
import { DataTable, type Column } from '@/components/ui/DataTable'
|
||||
import { StatusBadge } from '@/components/ui/StatusBadge'
|
||||
import { ConfirmModal } from '@/components/ui/ConfirmModal'
|
||||
import { MODULES, accessFromLegacy, accessSummary, can, type AccessConfig } from '@/lib/access'
|
||||
import AdminDrawer from './components/AdminDrawer'
|
||||
|
||||
dayjs.locale('ru')
|
||||
|
||||
const LIMIT = 20
|
||||
|
||||
type StatusFilter = 'all' | 'active' | 'blocked'
|
||||
type WithAccess = Admin & { access?: AccessConfig }
|
||||
|
||||
const accessOf = (a: Admin): AccessConfig => (a as WithAccess).access ?? accessFromLegacy(a)
|
||||
|
||||
function AccessCell({ admin }: { admin: Admin }) {
|
||||
if (admin.is_root === true) {
|
||||
return (
|
||||
<Stack gap={2} align="flex-start">
|
||||
<Badge color="violet" leftSection={<IconShieldCheck size={12} stroke={2.2} />}>Суперадмин</Badge>
|
||||
<Text size="xs" c="dimmed">Все права</Text>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
const access = accessOf(admin)
|
||||
const { enabled, total } = accessSummary(access)
|
||||
if (enabled === 0) return <Text size="sm" c="dimmed">Нет доступа</Text>
|
||||
|
||||
const names = MODULES.filter((m) => can(access, m.id)).map((m) => m.label)
|
||||
return (
|
||||
<Stack gap={0} miw={0}>
|
||||
<Text size="sm">{enabled} из {total} разделов</Text>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{names.slice(0, 2).join(', ')}{names.length > 2 ? ` +${names.length - 2}` : ''}
|
||||
</Text>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
type Confirm = { kind: 'delete' | 'block'; admin: Admin } | null
|
||||
|
||||
export default function AdminsPage() {
|
||||
const { user: currentUser } = useAuth()
|
||||
const isRoot = currentUser?.is_root === true
|
||||
|
||||
const [page, setPage] = useState(1)
|
||||
const [search, setSearch] = useState('')
|
||||
const [blockedFilter, setBlockedFilter] = useState<boolean | null>(null)
|
||||
const [createModalOpened, setCreateModalOpened] = useState(false)
|
||||
const [editAdmin, setEditAdmin] = useState<Admin | null>(null)
|
||||
const [debouncedSearch] = useDebouncedValue(search.trim(), 400)
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all')
|
||||
|
||||
const { user: currentUser } = useAuth()
|
||||
// Drawer: admin === null при opened значит «создание»
|
||||
const [drawer, setDrawer] = useState<{ admin: Admin | null; opened: boolean }>({ admin: null, opened: false })
|
||||
const [confirm, setConfirm] = useState<Confirm>(null)
|
||||
|
||||
useEffect(() => setPage(1), [debouncedSearch])
|
||||
|
||||
const { data, isLoading, isFetching } = useAdmins({
|
||||
offset: (page - 1) * LIMIT,
|
||||
limit: LIMIT,
|
||||
...(search && { login: search }),
|
||||
...(blockedFilter !== null && { is_blocked: blockedFilter }),
|
||||
...(debouncedSearch && { login: debouncedSearch }),
|
||||
...(statusFilter !== 'all' && { is_blocked: statusFilter === 'blocked' }),
|
||||
})
|
||||
const total = data?.total_count ?? 0
|
||||
|
||||
const deleteAdmin = useDeleteAdmin()
|
||||
const updateAdmin = useUpdateAdmin()
|
||||
|
||||
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
||||
const openDrawer = (admin: Admin | null) => setDrawer({ admin, opened: true })
|
||||
const closeDrawer = () => setDrawer((d) => ({ ...d, opened: false }))
|
||||
|
||||
// 🆕 Проверка, является ли текущий пользователь 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
|
||||
const activeCount = (debouncedSearch ? 1 : 0) + (statusFilter !== 'all' ? 1 : 0)
|
||||
const resetFilters = () => {
|
||||
setSearch('')
|
||||
setStatusFilter('all')
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
// Нельзя удалить root-админа (если текущий не root)
|
||||
if (isAdminRoot && !isRoot) {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: 'Только root-администратор может удалять других root-администраторов',
|
||||
color: 'red',
|
||||
})
|
||||
return
|
||||
const runConfirmed = () => {
|
||||
if (!confirm) return
|
||||
const { kind, admin } = confirm
|
||||
const done = { onSettled: () => setConfirm(null) }
|
||||
if (kind === 'delete') deleteAdmin.mutate(admin.id!, done)
|
||||
else updateAdmin.mutate({ id: admin.id!, is_blocked: !admin.is_blocked }, done)
|
||||
}
|
||||
|
||||
modals.openConfirmModal({
|
||||
title: 'Подтвердите удаление',
|
||||
children: (
|
||||
<Text size="sm">
|
||||
Вы уверены, что хотите удалить администратора <b>{login}</b>?
|
||||
Это действие нельзя отменить.
|
||||
</Text>
|
||||
const confirmContent = (): { title: string; message: ReactNode; label: string; danger: boolean } | null => {
|
||||
if (!confirm) return null
|
||||
const { kind, admin } = confirm
|
||||
if (kind === 'delete') {
|
||||
return {
|
||||
title: 'Удалить пользователя?',
|
||||
message: <>Пользователь <b>{admin.login}</b> будет удалён без возможности восстановления.</>,
|
||||
label: 'Удалить',
|
||||
danger: true,
|
||||
}
|
||||
}
|
||||
return admin.is_blocked
|
||||
? { title: 'Разблокировать пользователя?', message: <><b>{admin.login}</b> снова сможет входить в систему.</>, label: 'Разблокировать', danger: false }
|
||||
: { title: 'Заблокировать пользователя?', message: <><b>{admin.login}</b> больше не сможет входить в систему.</>, label: 'Заблокировать', danger: true }
|
||||
}
|
||||
const confirmInfo = confirmContent()
|
||||
|
||||
const columns: Column<Admin>[] = [
|
||||
{
|
||||
key: 'user',
|
||||
header: 'Пользователь',
|
||||
cell: (a) => {
|
||||
const name = a.name || a.login
|
||||
return (
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Avatar size={32} radius="xl" color="initials" name={name} />
|
||||
<Box miw={0}>
|
||||
<Group gap={6} wrap="nowrap">
|
||||
<Text size="sm" fw={500} truncate>{name}</Text>
|
||||
{currentUser?.id === a.id && <Badge size="xs">Вы</Badge>}
|
||||
</Group>
|
||||
{a.name && <Text size="xs" c="dimmed" truncate>{a.login}</Text>}
|
||||
</Box>
|
||||
</Group>
|
||||
)
|
||||
},
|
||||
},
|
||||
{ key: 'access', header: 'Доступ', width: 220, cell: (a) => <AccessCell admin={a} /> },
|
||||
{
|
||||
key: 'telegram',
|
||||
header: 'Telegram',
|
||||
cell: (a) =>
|
||||
a.telegram_user ? (
|
||||
<Text size="sm">{a.telegram_user.full_name || a.telegram_user.username || '—'}</Text>
|
||||
) : a.telegram_id ? (
|
||||
<Text size="sm" c="dimmed">ID {a.telegram_id}</Text>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed">—</Text>
|
||||
),
|
||||
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
||||
confirmProps: { color: 'red' },
|
||||
onConfirm: () => deleteAdmin.mutate(id),
|
||||
})
|
||||
}
|
||||
|
||||
const handleToggleBlock = (id: number, login: string, isBlocked: boolean, isAdminRoot: boolean) => {
|
||||
// Нельзя заблокировать себя
|
||||
if (currentUser?.id === id) {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: 'Вы не можете заблокировать свой собственный аккаунт',
|
||||
color: 'red',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Нельзя заблокировать root-админа (если текущий не root)
|
||||
if (isAdminRoot && !isRoot) {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: 'Только root-администратор может блокировать других root-администраторов',
|
||||
color: 'red',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const action = isBlocked ? 'разблокировать' : 'заблокировать'
|
||||
|
||||
modals.openConfirmModal({
|
||||
title: 'Подтвердите действие',
|
||||
children: (
|
||||
<Text size="sm">
|
||||
Вы уверены, что хотите {action} администратора <b>{login}</b>?
|
||||
</Text>
|
||||
},
|
||||
{
|
||||
key: 'last_login',
|
||||
header: 'Последний вход',
|
||||
width: 170,
|
||||
cell: (a) => (
|
||||
<Stack gap={0}>
|
||||
<Text size="sm" c="dimmed">{a.last_login ? formatMsk(a.last_login) : '—'}</Text>
|
||||
{a.last_ip_login && <Text size="xs" ff="monospace" c="dimmed">{a.last_ip_login}</Text>}
|
||||
</Stack>
|
||||
),
|
||||
labels: { confirm: action.charAt(0).toUpperCase() + action.slice(1), cancel: 'Отмена' },
|
||||
confirmProps: { color: isBlocked ? 'green' : 'red' },
|
||||
onConfirm: () => updateAdmin.mutate({ id, is_blocked: !isBlocked }),
|
||||
})
|
||||
}
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Статус',
|
||||
width: 150,
|
||||
cell: (a) => <StatusBadge kind="user" status={a.is_blocked ? 'blocked' : 'active'} />,
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: '',
|
||||
width: 56,
|
||||
align: 'right',
|
||||
cell: (a) => {
|
||||
// Себя блокировать и удалять нельзя; root-пользователей трогает только root
|
||||
const locked = currentUser?.id === a.id || (a.is_root === true && !isRoot)
|
||||
return (
|
||||
// Клики из меню (оно в портале) не должны открывать drawer строки
|
||||
<Box onClick={(e) => e.stopPropagation()}>
|
||||
<Menu position="bottom-end">
|
||||
<Menu.Target>
|
||||
<ActionIcon aria-label="Действия">
|
||||
<IconDots size={16} />
|
||||
</ActionIcon>
|
||||
</Menu.Target>
|
||||
<Menu.Dropdown>
|
||||
<Menu.Item leftSection={<IconPencil size={14} />} onClick={() => openDrawer(a)}>
|
||||
Редактировать
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
leftSection={a.is_blocked ? <IconLockOpen size={14} /> : <IconLock size={14} />}
|
||||
disabled={locked}
|
||||
onClick={() => setConfirm({ kind: 'block', admin: a })}
|
||||
>
|
||||
{a.is_blocked ? 'Разблокировать' : 'Заблокировать'}
|
||||
</Menu.Item>
|
||||
<Menu.Divider />
|
||||
<Menu.Item
|
||||
color="red"
|
||||
leftSection={<IconTrash size={14} />}
|
||||
disabled={locked}
|
||||
onClick={() => setConfirm({ kind: 'delete', admin: a })}
|
||||
>
|
||||
Удалить
|
||||
</Menu.Item>
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
</Box>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
{/* Заголовок */}
|
||||
<Group justify="space-between">
|
||||
<Text size="xl" fw={700}>Администраторы</Text>
|
||||
<Group>
|
||||
<Text c="dimmed" size="sm">
|
||||
Всего: {data?.total_count || 0}
|
||||
</Text>
|
||||
{isRoot && (
|
||||
<Button
|
||||
leftSection={<IconPlus size={16} />}
|
||||
onClick={() => setCreateModalOpened(true)}
|
||||
>
|
||||
Создать администратора
|
||||
<Stack gap="lg">
|
||||
<PageHeader
|
||||
title="Пользователи системы"
|
||||
description={
|
||||
isLoading
|
||||
? undefined
|
||||
: isRoot
|
||||
? `Всего: ${total}`
|
||||
: `Всего: ${total}. Новых пользователей создаёт суперадминистратор`
|
||||
}
|
||||
actions={
|
||||
isRoot && (
|
||||
<Button leftSection={<IconPlus size={16} />} onClick={() => openDrawer(null)}>
|
||||
Создать
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Предупреждение для не-root пользователей */}
|
||||
{!isRoot && (
|
||||
<Paper withBorder p="md" bg="yellow.0">
|
||||
<Text size="sm">
|
||||
⚠️ Создание новых администраторов доступно только для root-администратора.
|
||||
</Text>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Фильтры */}
|
||||
<Paper withBorder p="md">
|
||||
<Group gap="md" align="flex-end">
|
||||
<FilterBar activeCount={activeCount} onReset={resetFilters}>
|
||||
<TextInput
|
||||
label="Поиск по логину"
|
||||
placeholder="admin_user..."
|
||||
placeholder="Поиск по логину"
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.currentTarget.value)
|
||||
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||
w={260}
|
||||
/>
|
||||
<SegmentedControl
|
||||
value={statusFilter}
|
||||
onChange={(v) => {
|
||||
setStatusFilter(v as StatusFilter)
|
||||
setPage(1)
|
||||
}}
|
||||
style={{ flex: 1 }}
|
||||
data={[
|
||||
{ value: 'all', label: 'Все' },
|
||||
{ value: 'active', label: 'Активные' },
|
||||
{ value: 'blocked', label: 'Заблокированные' },
|
||||
]}
|
||||
/>
|
||||
</FilterBar>
|
||||
|
||||
<Switch
|
||||
label="Только заблокированные"
|
||||
checked={blockedFilter === true}
|
||||
onChange={(e) => {
|
||||
setBlockedFilter(e.currentTarget.checked ? true : null)
|
||||
setPage(1)
|
||||
<DataTable<Admin>
|
||||
columns={columns}
|
||||
rows={data?.data ?? []}
|
||||
getRowId={(a) => a.id!}
|
||||
loading={isLoading}
|
||||
refreshing={isFetching}
|
||||
minWidth={900}
|
||||
onRowClick={openDrawer}
|
||||
empty={{
|
||||
title: 'Пользователи не найдены',
|
||||
description: activeCount > 0 ? 'Измените или сбросьте фильтры' : undefined,
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
</Paper>
|
||||
|
||||
{/* Таблица */}
|
||||
<Paper withBorder>
|
||||
{isLoading ? (
|
||||
<Center p={60}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : (
|
||||
<>
|
||||
<Table striped highlightOnHover>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
||||
<Table.Th>Логин</Table.Th>
|
||||
<Table.Th>Имя</Table.Th>
|
||||
<Table.Th>Создан</Table.Th>
|
||||
<Table.Th>Последний вход</Table.Th>
|
||||
<Table.Th>Последний IP</Table.Th>
|
||||
<Table.Th style={{ width: 100 }}>Статус</Table.Th>
|
||||
<Table.Th style={{ width: 140 }}>Действия</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{data?.data?.length === 0 ? (
|
||||
<Table.Tr>
|
||||
<Table.Td colSpan={8}>
|
||||
<Center p={40}>
|
||||
<Text c="dimmed">Администраторы не найдены</Text>
|
||||
</Center>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
) : (
|
||||
(data?.data || []).map((admin) => {
|
||||
const isCurrentUser = currentUser?.id === admin.id
|
||||
const isAdminRoot = admin.is_root === true
|
||||
return (
|
||||
<Table.Tr key={admin.id}>
|
||||
<Table.Td>{admin.id}</Table.Td>
|
||||
<Table.Td>
|
||||
<Group gap="xs">
|
||||
<Text fw={500}>{admin.login}</Text>
|
||||
{isCurrentUser && (
|
||||
<Badge size="xs" color="blue" variant="light">
|
||||
Вы
|
||||
</Badge>
|
||||
)}
|
||||
{isAdminRoot && (
|
||||
<Badge
|
||||
size="xs"
|
||||
color="red"
|
||||
variant="filled"
|
||||
leftSection={<IconShield size={10} />}
|
||||
>
|
||||
ROOT
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm">{admin.name || '—'}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" c="dimmed">
|
||||
{admin.created_at
|
||||
? dayjs(admin.created_at).format('DD.MM.YYYY')
|
||||
: '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" c="dimmed">
|
||||
{admin.last_login
|
||||
? dayjs(admin.last_login).format('DD.MM.YYYY HH:mm')
|
||||
: '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" ff="monospace" c="dimmed">
|
||||
{admin.last_ip_login || '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge
|
||||
color={admin.is_blocked ? 'red' : 'green'}
|
||||
variant={admin.is_blocked ? 'filled' : 'light'}
|
||||
>
|
||||
{admin.is_blocked ? 'Заблокирован' : 'Активен'}
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Group gap="xs">
|
||||
<Tooltip label="Редактировать">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="blue"
|
||||
onClick={() => setEditAdmin(admin)}
|
||||
>
|
||||
<IconPencil size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label={admin.is_blocked ? 'Разблокировать' : 'Заблокировать'}>
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color={admin.is_blocked ? 'green' : 'orange'}
|
||||
onClick={() => handleToggleBlock(
|
||||
admin.id!,
|
||||
admin.login,
|
||||
admin.is_blocked || false,
|
||||
isAdminRoot
|
||||
)}
|
||||
disabled={isCurrentUser || (isAdminRoot && !isRoot)}
|
||||
>
|
||||
{admin.is_blocked ? <IconLockOpen size={16} /> : <IconLock size={16} />}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Удалить">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="red"
|
||||
onClick={() => handleDelete(admin.id!, admin.login, isAdminRoot)}
|
||||
disabled={isCurrentUser || (isAdminRoot && !isRoot)}
|
||||
>
|
||||
<IconTrash size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
|
||||
{/* Пагинация */}
|
||||
{totalPages > 1 && (
|
||||
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">
|
||||
Страница {page} из {totalPages}
|
||||
</Text>
|
||||
<Pagination
|
||||
value={page}
|
||||
onChange={setPage}
|
||||
total={totalPages}
|
||||
withEdges
|
||||
/>
|
||||
</Group>
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
{/* Индикатор обновления */}
|
||||
{isFetching && !isLoading && (
|
||||
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
|
||||
<Loader size="xs" />
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Модальные окна */}
|
||||
<CreateAdminModal
|
||||
opened={createModalOpened}
|
||||
onClose={() => setCreateModalOpened(false)}
|
||||
pagination={{ page, pageSize: LIMIT, total, onChange: setPage }}
|
||||
/>
|
||||
|
||||
<EditAdminModal
|
||||
admin={editAdmin}
|
||||
opened={editAdmin !== null}
|
||||
onClose={() => setEditAdmin(null)}
|
||||
<AdminDrawer admin={drawer.admin} opened={drawer.opened} onClose={closeDrawer} />
|
||||
|
||||
<ConfirmModal
|
||||
opened={!!confirm}
|
||||
onClose={() => setConfirm(null)}
|
||||
onConfirm={runConfirmed}
|
||||
title={confirmInfo?.title ?? ''}
|
||||
message={confirmInfo?.message}
|
||||
confirmLabel={confirmInfo?.label}
|
||||
danger={confirmInfo?.danger}
|
||||
loading={deleteAdmin.isPending || updateAdmin.isPending}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,134 @@
|
|||
import { Box, Button, Checkbox, Divider, Group, Select, Stack, Switch, Text } from '@mantine/core'
|
||||
import {
|
||||
GROUPS, MODULES, SCOPES, accessSummary, can, enableModule, setModule,
|
||||
type AccessConfig, type Scope,
|
||||
} from '@/lib/access'
|
||||
|
||||
interface Props {
|
||||
value: AccessConfig
|
||||
onChange: (next: AccessConfig) => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function AccessMatrix({ value, onChange, disabled }: Props) {
|
||||
const { enabled, total } = accessSummary(value)
|
||||
|
||||
// Массовые операции: всё выключить / только просмотр / все действия
|
||||
const setAll = (mode: 'none' | 'view' | 'full') => {
|
||||
let next = value
|
||||
for (const m of MODULES) {
|
||||
if (mode === 'none') {
|
||||
next = setModule(next, m.id, null)
|
||||
continue
|
||||
}
|
||||
const base = enableModule(m.id)
|
||||
next = setModule(
|
||||
next,
|
||||
m.id,
|
||||
mode === 'view'
|
||||
? base
|
||||
: { ...base, actions: ['view', ...m.actions.map((a) => a.id)], ...(m.scoped && { scope: 'all' as Scope }) },
|
||||
)
|
||||
}
|
||||
onChange(next)
|
||||
}
|
||||
|
||||
const toggleGroup = (group: string, on: boolean) => {
|
||||
let next = value
|
||||
for (const m of MODULES.filter((x) => x.group === group)) {
|
||||
next = setModule(next, m.id, on ? (can(next, m.id) ? next[m.id] : enableModule(m.id)) : null)
|
||||
}
|
||||
onChange(next)
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<Group justify="space-between" wrap="wrap" gap="xs">
|
||||
<Text size="xs" c="dimmed">Доступно разделов: {enabled} из {total}</Text>
|
||||
<Group gap={4}>
|
||||
<Button size="compact-xs" variant="subtle" disabled={disabled} onClick={() => setAll('view')}>Только просмотр</Button>
|
||||
<Button size="compact-xs" variant="subtle" disabled={disabled} onClick={() => setAll('full')}>Все действия</Button>
|
||||
<Button size="compact-xs" variant="subtle" color="gray" disabled={disabled || enabled === 0} onClick={() => setAll('none')}>Снять всё</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
{GROUPS.map((group) => {
|
||||
const mods = MODULES.filter((m) => m.group === group)
|
||||
const onCount = mods.filter((m) => can(value, m.id)).length
|
||||
const allOn = onCount === mods.length
|
||||
|
||||
return (
|
||||
<Box key={group}>
|
||||
<Group justify="space-between" mb={4}>
|
||||
<Text size="sm" fw={600}>{group}</Text>
|
||||
<Button size="compact-xs" variant="subtle" color="gray" disabled={disabled} onClick={() => toggleGroup(group, !allOn)}>
|
||||
{allOn ? 'Отключить все' : 'Включить все'}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
{mods.map((m, i) => {
|
||||
const on = can(value, m.id)
|
||||
const current = value[m.id]
|
||||
const extra = m.actions
|
||||
|
||||
return (
|
||||
<Box key={m.id}>
|
||||
{i > 0 && <Divider />}
|
||||
<Box py={10}>
|
||||
<Group justify="space-between" wrap="nowrap" mih={30}>
|
||||
<Switch
|
||||
size="sm"
|
||||
label={m.label}
|
||||
checked={on}
|
||||
disabled={disabled}
|
||||
onChange={(e) =>
|
||||
onChange(setModule(value, m.id, e.currentTarget.checked ? enableModule(m.id) : null))
|
||||
}
|
||||
/>
|
||||
{m.scoped && on && (
|
||||
<Select
|
||||
size="xs"
|
||||
w={160}
|
||||
aria-label={`Чьи данные доступны: ${m.label}`}
|
||||
data={SCOPES}
|
||||
value={current?.scope ?? 'own'}
|
||||
allowDeselect={false}
|
||||
disabled={disabled}
|
||||
onChange={(scope) =>
|
||||
scope && onChange(setModule(value, m.id, { ...current, scope: scope as Scope }))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
{on && extra.length > 0 && (
|
||||
<Checkbox.Group
|
||||
value={current.actions}
|
||||
onChange={(vals) =>
|
||||
onChange(
|
||||
setModule(value, m.id, {
|
||||
...current,
|
||||
actions: ['view', ...vals.filter((v) => v !== 'view')],
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Group gap="lg" mt={8} ml={44}>
|
||||
{extra.map((a) => (
|
||||
<Checkbox key={a.id} size="xs" value={a.id} label={a.label} disabled={disabled} />
|
||||
))}
|
||||
</Group>
|
||||
</Checkbox.Group>
|
||||
)}
|
||||
|
||||
{on && m.note && <Text size="xs" c="dimmed" mt={6} ml={44}>{m.note}</Text>}
|
||||
</Box>
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,335 @@
|
|||
import { useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
ActionIcon, Alert, Avatar, Badge, Box, Button, Code, CopyButton, Drawer, Group, Paper, Select,
|
||||
Stack, Switch, Tabs, Text, TextInput, Tooltip,
|
||||
} from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { IconAlertCircle, IconCheck, IconCopy, IconShieldCheck } from '@tabler/icons-react'
|
||||
|
||||
import { useAdmins, useCreateAdmin, useUpdateAdmin } from '@/features/admins/hooks/useAdmins'
|
||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { ConfirmModal } from '@/components/ui/ConfirmModal'
|
||||
import { StatusBadge } from '@/components/ui/StatusBadge'
|
||||
import { accessFromLegacy, legacyFlags, type AccessConfig } from '@/lib/access'
|
||||
import type { Admin } from '@/types/api'
|
||||
import { AccessMatrix } from './AccessMatrix'
|
||||
import classes from '@/components/UserDrawer.module.css'
|
||||
|
||||
interface Props {
|
||||
admin: Admin | null // null — создание нового пользователя
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// Поле access пока не описано в типе Admin — бэкенд должен его хранить
|
||||
type WithAccess = Admin & { access?: AccessConfig }
|
||||
|
||||
const EMPTY_ACCESS = {} as AccessConfig
|
||||
const accessOf = (a: Admin | null): AccessConfig =>
|
||||
a ? (a as WithAccess).access ?? accessFromLegacy(a) : EMPTY_ACCESS
|
||||
|
||||
export default function AdminDrawer({ admin, opened, onClose }: Props) {
|
||||
const creating = admin === null
|
||||
const { user: currentUser } = useAuth()
|
||||
const isRoot = currentUser?.is_root === true
|
||||
const isSelf = !creating && currentUser?.id === admin?.id
|
||||
// Права меняет только суперадмин, и не себе
|
||||
const canEditAccess = isRoot && !isSelf
|
||||
|
||||
const createAdmin = useCreateAdmin()
|
||||
const updateAdmin = useUpdateAdmin()
|
||||
const { data: usersData } = useUsers({ limit: 1000 })
|
||||
const { data: adminsData } = useAdmins({ limit: 1000 })
|
||||
|
||||
const [tab, setTab] = useState<string | null>('main')
|
||||
const [created, setCreated] = useState<Admin | null>(null)
|
||||
const [confirmClose, setConfirmClose] = useState(false)
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
login: '',
|
||||
name: '',
|
||||
telegram_id: null as number | null,
|
||||
is_root: false,
|
||||
access: EMPTY_ACCESS,
|
||||
},
|
||||
validate: {
|
||||
login: (v) => {
|
||||
if (!creating) return null
|
||||
if (v.length < 3) return 'Минимум 3 символа'
|
||||
if (!/^[a-zA-Z0-9_]+$/.test(v)) return 'Только буквы, цифры и подчёркивание'
|
||||
return null
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Подготовка формы при каждом открытии
|
||||
useEffect(() => {
|
||||
if (!opened) return
|
||||
const values = {
|
||||
login: admin?.login ?? '',
|
||||
name: admin?.name ?? '',
|
||||
telegram_id: admin?.telegram_id ?? null,
|
||||
is_root: admin?.is_root === true,
|
||||
access: accessOf(admin),
|
||||
}
|
||||
form.setValues(values)
|
||||
form.resetDirty(values)
|
||||
form.clearErrors()
|
||||
setTab('main')
|
||||
setCreated(null)
|
||||
setConfirmClose(false)
|
||||
}, [opened, admin?.id]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const isSubmitting = createAdmin.isPending || updateAdmin.isPending
|
||||
|
||||
const userOptions = useMemo(
|
||||
() =>
|
||||
(usersData?.data ?? [])
|
||||
.filter((u) => u.telegram_id && u.telegram_id > 0)
|
||||
.map((u) => ({
|
||||
value: String(u.telegram_id),
|
||||
label: u.full_name || u.username || `ID: ${u.telegram_id}`,
|
||||
})),
|
||||
[usersData],
|
||||
)
|
||||
|
||||
// Источники для «Скопировать доступ у…»: другие пользователи без полных прав
|
||||
const copyOptions = useMemo(
|
||||
() =>
|
||||
(adminsData?.data ?? [])
|
||||
.filter((a) => a.id !== admin?.id && a.is_root !== true)
|
||||
.map((a) => ({ value: String(a.id), label: a.name ? `${a.name} (${a.login})` : a.login })),
|
||||
[adminsData, admin?.id],
|
||||
)
|
||||
|
||||
const copyAccessFrom = (id: string | null) => {
|
||||
const source = (adminsData?.data ?? []).find((a) => String(a.id) === id)
|
||||
if (source) form.setFieldValue('access', accessOf(source))
|
||||
}
|
||||
|
||||
const requestClose = () => (form.isDirty() && !created ? setConfirmClose(true) : onClose())
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
// Пока бэкенд не перешёл на access, старые флаги выводятся из матрицы; «все права» — это is_root
|
||||
const flags = { ...legacyFlags(values.access), is_root: values.is_root }
|
||||
try {
|
||||
if (creating) {
|
||||
setCreated(
|
||||
await createAdmin.mutateAsync({
|
||||
login: values.login,
|
||||
name: values.name || undefined,
|
||||
...flags,
|
||||
telegram_id: values.telegram_id ?? undefined,
|
||||
// TODO: раскомментировать после того как сделаю это на бэкенде
|
||||
// access: values.access,
|
||||
}),
|
||||
)
|
||||
} else if (admin?.id) {
|
||||
// Не суперадмин меняет только имя и привязку Telegram
|
||||
const payload = canEditAccess
|
||||
? { id: admin.id, name: values.name || undefined, ...flags, telegram_id: values.telegram_id, access: values.access }
|
||||
: { id: admin.id, name: values.name || undefined, telegram_id: values.telegram_id }
|
||||
await updateAdmin.mutateAsync(payload)
|
||||
onClose()
|
||||
}
|
||||
} catch {
|
||||
// Ошибка уже показана в хуке
|
||||
}
|
||||
}
|
||||
|
||||
const displayName = admin?.name || admin?.login
|
||||
|
||||
return (
|
||||
<>
|
||||
<Drawer.Root opened={opened} onClose={requestClose} position="right" size="min(640px, 100vw)" trapFocus>
|
||||
<Drawer.Overlay backgroundOpacity={0.25} />
|
||||
<Drawer.Content>
|
||||
<Drawer.Header>
|
||||
{creating ? (
|
||||
<Text fw={600}>Новый пользователь</Text>
|
||||
) : (
|
||||
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
<Avatar size={36} radius="xl" color="initials" name={displayName ?? ''} />
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text fw={600} truncate>{displayName}</Text>
|
||||
<Group gap={8} wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">{admin?.login}</Text>
|
||||
<StatusBadge kind="user" status={admin?.is_blocked ? 'blocked' : 'active'} size="sm" />
|
||||
{admin?.is_root && (
|
||||
<Badge size="sm" color="violet" variant="light">Суперадмин</Badge>
|
||||
)}
|
||||
</Group>
|
||||
</Box>
|
||||
</Group>
|
||||
)}
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body className={classes.body}>
|
||||
{created ? (
|
||||
<>
|
||||
<Stack className={classes.section} gap="md">
|
||||
<Alert color="green" title="Пользователь создан">
|
||||
<Text size="sm">Логин: <Code>{created.login}</Code></Text>
|
||||
</Alert>
|
||||
|
||||
<Box>
|
||||
<Group gap={6} mb={4}>
|
||||
<IconAlertCircle size={16} />
|
||||
<Text size="sm" fw={600}>Временный пароль</Text>
|
||||
</Group>
|
||||
<Text size="sm" c="dimmed" mb="xs">
|
||||
Сохраните его сейчас: после закрытия окна пароль больше не показывается.
|
||||
</Text>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Code block style={{ flex: 1, fontSize: 16, fontWeight: 600, padding: 12 }}>
|
||||
{created.password || '—'}
|
||||
</Code>
|
||||
<CopyButton value={created.password || ''} timeout={1800}>
|
||||
{({ copied, copy }) => (
|
||||
<Tooltip label={copied ? 'Скопировано' : 'Копировать'}>
|
||||
<ActionIcon onClick={copy} aria-label="Копировать пароль">
|
||||
{copied ? <IconCheck size={16} /> : <IconCopy size={16} />}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
</CopyButton>
|
||||
</Group>
|
||||
</Box>
|
||||
</Stack>
|
||||
<Group className={classes.footer} justify="flex-end">
|
||||
<Button onClick={onClose}>Готово</Button>
|
||||
</Group>
|
||||
</>
|
||||
) : (
|
||||
<form style={{ display: 'contents' }} onSubmit={form.onSubmit(handleSubmit, () => setTab('main'))}>
|
||||
<Tabs value={tab} onChange={setTab}>
|
||||
<Tabs.List className={classes.tabsList}>
|
||||
<Tabs.Tab value="main">Основное</Tabs.Tab>
|
||||
<Tabs.Tab value="access">Доступ</Tabs.Tab>
|
||||
</Tabs.List>
|
||||
|
||||
<Tabs.Panel value="main" className={classes.section}>
|
||||
<Stack gap="lg">
|
||||
<TextInput
|
||||
label="Логин"
|
||||
placeholder="user_login"
|
||||
description={creating ? 'Буквы, цифры и подчёркивание. Потом не меняется' : undefined}
|
||||
withAsterisk={creating}
|
||||
disabled={!creating}
|
||||
{...form.getInputProps('login')}
|
||||
/>
|
||||
<TextInput
|
||||
label="Имя"
|
||||
placeholder="Иванов Иван"
|
||||
description="Так пользователь отображается в системе"
|
||||
{...form.getInputProps('name')}
|
||||
/>
|
||||
<Select
|
||||
label="Telegram-аккаунт сотрудника"
|
||||
placeholder="Не привязан"
|
||||
description="Связывает вход в панель с сотрудником: нужен для личных заявок, задач и уведомлений в боте"
|
||||
data={userOptions}
|
||||
value={form.values.telegram_id ? String(form.values.telegram_id) : null}
|
||||
onChange={(v) => form.setFieldValue('telegram_id', v ? Number(v) : null)}
|
||||
searchable
|
||||
clearable
|
||||
nothingFoundMessage="Никого не найдено"
|
||||
/>
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
|
||||
<Tabs.Panel value="access" className={classes.section}>
|
||||
<Stack gap="lg">
|
||||
{!canEditAccess && (
|
||||
<Alert color="gray" icon={<IconAlertCircle size={16} />}>
|
||||
<Text size="sm">
|
||||
{isSelf ? 'Свои права изменить нельзя.' : 'Права меняет только суперадминистратор.'}
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Paper withBorder p="md">
|
||||
<Group justify="space-between" wrap="nowrap" align="flex-start">
|
||||
<Group gap="sm" wrap="nowrap" align="flex-start">
|
||||
<IconShieldCheck size={20} stroke={1.7} style={{ marginTop: 2 }} />
|
||||
<Box>
|
||||
<Text size="sm" fw={600}>Все права</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
Полный доступ ко всем разделам и действиям, включая управление пользователями и правами
|
||||
</Text>
|
||||
</Box>
|
||||
</Group>
|
||||
<Switch
|
||||
aria-label="Все права"
|
||||
checked={form.values.is_root}
|
||||
disabled={!canEditAccess}
|
||||
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
||||
/>
|
||||
</Group>
|
||||
</Paper>
|
||||
|
||||
{form.values.is_root ? (
|
||||
<Text size="sm" c="dimmed">
|
||||
Отдельные разделы настраивать не нужно. Выключите «Все права», чтобы выдать доступ точечно.
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
{canEditAccess && copyOptions.length > 0 && (
|
||||
<Select
|
||||
label="Скопировать доступ у другого пользователя"
|
||||
description="Заменит текущие настройки ниже, потом их можно поправить"
|
||||
placeholder="Выберите пользователя"
|
||||
data={copyOptions}
|
||||
value={null}
|
||||
onChange={copyAccessFrom}
|
||||
searchable
|
||||
nothingFoundMessage="Никого не найдено"
|
||||
/>
|
||||
)}
|
||||
<Box>
|
||||
<Text size="sm" fw={600} mb="xs">Разделы и действия</Text>
|
||||
<AccessMatrix
|
||||
value={form.values.access}
|
||||
onChange={(next) => form.setFieldValue('access', next)}
|
||||
disabled={!canEditAccess}
|
||||
/>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
</Tabs>
|
||||
|
||||
<Group className={classes.footer} justify="space-between" wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">{form.isDirty() ? 'Есть несохранённые изменения' : ''}</Text>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Button variant="default" onClick={requestClose} disabled={isSubmitting}>Отмена</Button>
|
||||
<Button type="submit" loading={isSubmitting} disabled={!creating && !form.isDirty()}>
|
||||
{creating ? 'Создать' : 'Сохранить'}
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
</form>
|
||||
)}
|
||||
</Drawer.Body>
|
||||
</Drawer.Content>
|
||||
</Drawer.Root>
|
||||
|
||||
<ConfirmModal
|
||||
opened={confirmClose}
|
||||
onClose={() => setConfirmClose(false)}
|
||||
onConfirm={() => {
|
||||
setConfirmClose(false)
|
||||
onClose()
|
||||
}}
|
||||
title="Закрыть без сохранения?"
|
||||
message="Внесённые изменения будут потеряны."
|
||||
confirmLabel="Закрыть"
|
||||
danger
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,185 +0,0 @@
|
|||
import { useState } from 'react'
|
||||
import {
|
||||
Modal,
|
||||
Stack,
|
||||
TextInput,
|
||||
Button,
|
||||
Text,
|
||||
Alert,
|
||||
CopyButton,
|
||||
ActionIcon,
|
||||
Tooltip,
|
||||
Group,
|
||||
Paper,
|
||||
Code,
|
||||
Switch,
|
||||
} from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { IconCheck, IconCopy, IconKey, IconAlertCircle, IconShield } from '@tabler/icons-react'
|
||||
import { useCreateAdmin } from '@/features/admins/hooks/useAdmins'
|
||||
import type { Admin } from '@/types/api'
|
||||
|
||||
interface CreateAdminModalProps {
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function CreateAdminModal({ opened, onClose }: CreateAdminModalProps) {
|
||||
const [createdAdmin, setCreatedAdmin] = useState<Admin | null>(null)
|
||||
const createAdmin = useCreateAdmin()
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
login: '',
|
||||
name: '',
|
||||
is_root: false,
|
||||
},
|
||||
validate: {
|
||||
login: (value) => {
|
||||
if (value.length < 3) return 'Логин должен содержать минимум 3 символа'
|
||||
if (!/^[a-zA-Z0-9_]+$/.test(value)) return 'Логин может содержать только буквы, цифры и подчеркивания'
|
||||
return null
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
try {
|
||||
const admin = await createAdmin.mutateAsync({
|
||||
login: values.login,
|
||||
name: values.name || undefined,
|
||||
is_root: values.is_root,
|
||||
})
|
||||
setCreatedAdmin(admin)
|
||||
form.reset()
|
||||
} catch (error) {
|
||||
// Ошибка уже обработана в хуке
|
||||
}
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
setCreatedAdmin(null)
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={handleClose}
|
||||
title="Создание администратора"
|
||||
size="md"
|
||||
>
|
||||
{createdAdmin ? (
|
||||
<Stack gap="md">
|
||||
<Alert
|
||||
icon={<IconKey size={16} />}
|
||||
title="Администратор создан"
|
||||
color="green"
|
||||
variant="light"
|
||||
>
|
||||
<Text size="sm">
|
||||
Администратор <Code>{createdAdmin.login}</Code> успешно создан.
|
||||
{createdAdmin.is_root && (
|
||||
<Text size="sm" fw={600} mt={4}>
|
||||
Выданы root-права 👑
|
||||
</Text>
|
||||
)}
|
||||
</Text>
|
||||
</Alert>
|
||||
|
||||
<Paper withBorder p="md" bg="yellow.0">
|
||||
<Stack gap="xs">
|
||||
<Group gap="xs">
|
||||
<IconAlertCircle size={20} color="orange" />
|
||||
<Text fw={600} size="sm">Временный пароль</Text>
|
||||
</Group>
|
||||
|
||||
<Text size="sm" c="dimmed">
|
||||
Сохраните этот пароль! После закрытия окна он больше не будет доступен.
|
||||
</Text>
|
||||
|
||||
<Group gap="xs">
|
||||
<Code
|
||||
block
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '12px',
|
||||
fontSize: '16px',
|
||||
fontWeight: 600,
|
||||
letterSpacing: '1px',
|
||||
}}
|
||||
>
|
||||
{createdAdmin.password || '—'}
|
||||
</Code>
|
||||
<CopyButton value={createdAdmin.password || ''} timeout={2000}>
|
||||
{({ copied, copy }) => (
|
||||
<Tooltip label={copied ? 'Скопировано' : 'Копировать'} withArrow position="right">
|
||||
<ActionIcon color={copied ? 'teal' : 'gray'} variant="subtle" onClick={copy}>
|
||||
{copied ? <IconCheck size={16} /> : <IconCopy size={16} />}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
</CopyButton>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
<Button onClick={handleClose} fullWidth>
|
||||
Закрыть
|
||||
</Button>
|
||||
</Stack>
|
||||
) : (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="md">
|
||||
<TextInput
|
||||
label="Логин"
|
||||
placeholder="admin_user"
|
||||
required
|
||||
description="Уникальный идентификатор (буквы, цифры, подчеркивания)"
|
||||
{...form.getInputProps('login')}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
label="Имя (опционально)"
|
||||
placeholder="Иванов Иван"
|
||||
description="Отображаемое имя администратора"
|
||||
{...form.getInputProps('name')}
|
||||
/>
|
||||
|
||||
<Paper withBorder p="md" bg={form.values.is_root ? 'red.0' : 'gray.0'}>
|
||||
<Switch
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<IconShield size={16} color="red" />
|
||||
<Text fw={600}>Выдать root-права</Text>
|
||||
</Group>
|
||||
}
|
||||
description="Администратор сможет создавать других администраторов и управлять root-правами"
|
||||
checked={form.values.is_root}
|
||||
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
||||
color="red"
|
||||
/>
|
||||
</Paper>
|
||||
|
||||
{form.values.is_root && (
|
||||
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
|
||||
<Text size="sm">
|
||||
<b>Внимание!</b> Root-права дают полный доступ к системе, включая создание и удаление других администраторов.
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={handleClose} disabled={createAdmin.isPending}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={createAdmin.isPending}>
|
||||
Создать
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,137 +0,0 @@
|
|||
import { useEffect } from 'react'
|
||||
import {
|
||||
Modal,
|
||||
Stack,
|
||||
TextInput,
|
||||
Button,
|
||||
Text,
|
||||
Group,
|
||||
Badge,
|
||||
Switch,
|
||||
Paper,
|
||||
Alert,
|
||||
} from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { IconShield, IconAlertCircle } from '@tabler/icons-react'
|
||||
import { useUpdateAdmin } from '@/features/admins/hooks/useAdmins'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import type { Admin } from '@/types/api'
|
||||
|
||||
interface EditAdminModalProps {
|
||||
admin: Admin | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function EditAdminModal({ admin, opened, onClose }: EditAdminModalProps) {
|
||||
const updateAdmin = useUpdateAdmin()
|
||||
const { user: currentUser } = useAuth()
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
name: '',
|
||||
is_root: false,
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (admin) {
|
||||
form.setValues({
|
||||
name: admin.name || '',
|
||||
is_root: admin.is_root ?? false,
|
||||
})
|
||||
}
|
||||
}, [admin])
|
||||
|
||||
const isCurrentUser = currentUser?.id === admin?.id
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
if (!admin?.id) return
|
||||
await updateAdmin.mutateAsync({
|
||||
id: admin.id,
|
||||
name: values.name || undefined,
|
||||
is_root: values.is_root,
|
||||
})
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={
|
||||
<Group>
|
||||
<Text fw={700}>Редактирование администратора</Text>
|
||||
{admin && <Badge variant="light">{admin.login}</Badge>}
|
||||
{admin?.is_root && (
|
||||
<Badge color="red" variant="filled" leftSection={<IconShield size={12} />}>
|
||||
ROOT
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
}
|
||||
size="md"
|
||||
>
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="md">
|
||||
<TextInput
|
||||
label="Логин"
|
||||
value={admin?.login || ''}
|
||||
disabled
|
||||
description="Логин нельзя изменить"
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
label="Имя"
|
||||
placeholder="Иванов Иван"
|
||||
description="Отображаемое имя администратора"
|
||||
{...form.getInputProps('name')}
|
||||
/>
|
||||
|
||||
<Paper withBorder p="md" bg={form.values.is_root ? 'red.0' : 'gray.0'}>
|
||||
<Switch
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<IconShield size={16} color="red" />
|
||||
<Text fw={600}>Root-права</Text>
|
||||
</Group>
|
||||
}
|
||||
description="Может создавать администраторов и управлять root-правами"
|
||||
checked={form.values.is_root}
|
||||
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
||||
color="red"
|
||||
disabled={isCurrentUser}
|
||||
/>
|
||||
</Paper>
|
||||
|
||||
{isCurrentUser && (
|
||||
<Alert icon={<IconAlertCircle size={16} />} color="yellow" variant="light">
|
||||
<Text size="sm">
|
||||
Вы не можете изменить свои собственные root-права.
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{form.values.is_root !== (admin?.is_root ?? false) && !isCurrentUser && (
|
||||
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
|
||||
<Text size="sm">
|
||||
<b>Внимание!</b> Вы изменяете root-права. {form.values.is_root
|
||||
? 'Этот администратор получит полный доступ к системе.'
|
||||
: 'Этот администратор потеряет возможность создавать других администраторов.'}
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={onClose} disabled={updateAdmin.isPending}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={updateAdmin.isPending}>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
import { useMemo, type ReactNode } from 'react'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { accessFromLegacy, can as canDo, scopeOf, type AccessConfig, type Scope } from '@/lib/access'
|
||||
|
||||
// Пока бэкенд не отдаёт user.access, доступ выводится из старых флагов
|
||||
type AuthUser = { is_root?: boolean; is_analyst?: boolean; is_observer?: boolean; access?: AccessConfig } | null | undefined
|
||||
|
||||
export function useAccess() {
|
||||
const { user } = useAuth() as { user: AuthUser }
|
||||
|
||||
const access = useMemo<AccessConfig>(() => user?.access ?? accessFromLegacy(user), [user])
|
||||
const isRoot = user?.is_root === true
|
||||
|
||||
return {
|
||||
access,
|
||||
isRoot,
|
||||
can: (moduleId: string, action = 'view') => isRoot || canDo(access, moduleId, action),
|
||||
scope: (moduleId: string): Scope | null => (isRoot ? 'all' : scopeOf(access, moduleId)),
|
||||
}
|
||||
}
|
||||
|
||||
interface CanProps {
|
||||
module: string
|
||||
action?: string
|
||||
fallback?: ReactNode
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
// <Can module="approvals" action="export"><Button>Отчёт</Button></Can>
|
||||
export function Can({ module, action = 'view', fallback = null, children }: CanProps) {
|
||||
const { can } = useAccess()
|
||||
return <>{can(module, action) ? children : fallback}</>
|
||||
}
|
||||
|
|
@ -1,277 +1,236 @@
|
|||
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 { useMemo, useState } from 'react'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import { ActionIcon, Avatar, Group, Select, Stack, Switch, Text, Tooltip } from '@mantine/core'
|
||||
import { IconPaperclip, IconTrash } from '@tabler/icons-react'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/ru'
|
||||
|
||||
import { useApprovalTasks, useDeleteApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
|
||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||
import { formatMsk } from '@/utils/date'
|
||||
|
||||
import { PageHeader } from '@/components/ui/PageHeader'
|
||||
import { FilterBar } from '@/components/ui/FilterBar'
|
||||
import { DataTable, type Column } from '@/components/ui/DataTable'
|
||||
import { StatusBadge } from '@/components/ui/StatusBadge'
|
||||
import { ConfirmModal } from '@/components/ui/ConfirmModal'
|
||||
import { TASK_STATUS } from '@/components/ui/statuses'
|
||||
import ApprovalTaskDetailsDrawer from './components/ApprovalTaskDetailsDrawer'
|
||||
|
||||
dayjs.locale('ru')
|
||||
|
||||
const LIMIT = 20
|
||||
|
||||
type Row = NonNullable<NonNullable<ReturnType<typeof useApprovalTasks>['data']>['data']>[number]
|
||||
|
||||
interface Filters {
|
||||
status: string | null
|
||||
executor: string | null
|
||||
requireFile: boolean
|
||||
}
|
||||
|
||||
const STATUS_OPTIONS = Object.entries(TASK_STATUS).map(([value, m]) => ({ value, label: m.label }))
|
||||
const VALID_STATUSES = new Set(STATUS_OPTIONS.map((o) => o.value))
|
||||
|
||||
export default function ApprovalTasksPage() {
|
||||
// Начальный статус берём из URL (например, с дашборда: /approval-tasks?status=completed).
|
||||
// Читаем один раз при монтировании.
|
||||
const [searchParams] = useSearchParams()
|
||||
|
||||
const [page, setPage] = useState(1)
|
||||
const [statusFilter, setStatusFilter] = useState<string | null>(null)
|
||||
const [executorFilter, setExecutorFilter] = useState<string | null>(null)
|
||||
const [requireFileFilter, setRequireFileFilter] = useState<boolean | null>(null)
|
||||
const [selectedTaskId, setSelectedTaskId] = useState<number | null>(null)
|
||||
const [filters, setFilters] = useState<Filters>(() => {
|
||||
const status = searchParams.get('status')
|
||||
return { status: status && VALID_STATUSES.has(status) ? status : null, executor: null, requireFile: false }
|
||||
})
|
||||
|
||||
// Drawer: id храним отдельно от opened, чтобы содержимое не мигало при закрытии
|
||||
const [drawerId, setDrawerId] = useState<number | null>(null)
|
||||
const [drawerOpened, setDrawerOpened] = useState(false)
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null)
|
||||
|
||||
const update = (patch: Partial<Filters>) => {
|
||||
setFilters((prev) => ({ ...prev, ...patch }))
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
const { data, isLoading, isFetching } = useApprovalTasks({
|
||||
offset: (page - 1) * LIMIT,
|
||||
limit: LIMIT,
|
||||
...(statusFilter && { status: statusFilter }),
|
||||
...(executorFilter && { executor_id: Number(executorFilter) }),
|
||||
...(requireFileFilter !== null && { require_file: requireFileFilter }),
|
||||
...(filters.status && { status: filters.status }),
|
||||
...(filters.executor && { executor_id: Number(filters.executor) }),
|
||||
...(filters.requireFile && { require_file: true }),
|
||||
})
|
||||
const total = data?.total_count ?? 0
|
||||
|
||||
const { data: users } = useUsers({ limit: 1000 })
|
||||
const deleteTask = useDeleteApprovalTask()
|
||||
|
||||
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
||||
const executorOptions = useMemo(
|
||||
() => (users?.data ?? []).map((u) => ({ value: String(u.id), label: u.full_name || '' })),
|
||||
[users],
|
||||
)
|
||||
|
||||
const executorOptions = users?.data?.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.full_name || '',
|
||||
})) || []
|
||||
|
||||
const handleDelete = (id: number) => {
|
||||
modals.openConfirmModal({
|
||||
title: 'Подтвердите удаление',
|
||||
children: (
|
||||
<Text size="sm">
|
||||
Вы уверены, что хотите удалить эту задачу? Это действие нельзя отменить.
|
||||
</Text>
|
||||
),
|
||||
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
||||
confirmProps: { color: 'red' },
|
||||
onConfirm: () => deleteTask.mutate(id),
|
||||
})
|
||||
const activeCount = [filters.status, filters.executor, filters.requireFile].filter(Boolean).length
|
||||
const resetFilters = () => {
|
||||
setFilters({ status: null, executor: null, requireFile: false })
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between">
|
||||
<Text size="xl" fw={700}>Задачи по заявкам</Text>
|
||||
<Text c="dimmed" size="sm">
|
||||
Всего: {data?.total_count || 0}
|
||||
</Text>
|
||||
</Group>
|
||||
|
||||
{/* Фильтры */}
|
||||
<Paper withBorder p="md">
|
||||
<Group gap="md" align="flex-end">
|
||||
<Select
|
||||
label="Статус"
|
||||
placeholder="Все статусы"
|
||||
data={TASK_STATUSES.map((s) => ({ value: s.value, label: s.label }))}
|
||||
value={statusFilter}
|
||||
onChange={(v) => {
|
||||
setStatusFilter(v)
|
||||
setPage(1)
|
||||
}}
|
||||
clearable
|
||||
style={{ minWidth: 180 }}
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Исполнитель"
|
||||
placeholder="Все исполнители"
|
||||
data={executorOptions}
|
||||
value={executorFilter}
|
||||
onChange={(v) => {
|
||||
setExecutorFilter(v)
|
||||
setPage(1)
|
||||
}}
|
||||
clearable
|
||||
searchable
|
||||
style={{ minWidth: 200 }}
|
||||
/>
|
||||
|
||||
<Switch
|
||||
label="Требуют файл"
|
||||
checked={requireFileFilter === true}
|
||||
onChange={(e) => {
|
||||
setRequireFileFilter(e.currentTarget.checked ? true : null)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
</Paper>
|
||||
|
||||
{/* Таблица */}
|
||||
<Paper withBorder>
|
||||
{isLoading ? (
|
||||
<Center p={60}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : (
|
||||
<>
|
||||
<Table striped highlightOnHover>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
||||
<Table.Th>Заявка</Table.Th>
|
||||
<Table.Th>Исполнитель</Table.Th>
|
||||
<Table.Th>Текст задачи</Table.Th>
|
||||
<Table.Th style={{ width: 80 }}>Шаг</Table.Th>
|
||||
<Table.Th style={{ width: 120 }}>Статус</Table.Th>
|
||||
<Table.Th style={{ width: 80 }}>Файл</Table.Th>
|
||||
<Table.Th>Создана</Table.Th>
|
||||
<Table.Th>Выполнена</Table.Th>
|
||||
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{data?.data?.length === 0 ? (
|
||||
<Table.Tr>
|
||||
<Table.Td colSpan={10}>
|
||||
<Center p={40}>
|
||||
<Text c="dimmed">Задачи не найдены</Text>
|
||||
</Center>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
) : (
|
||||
(data?.data || []).map((task) => (
|
||||
<Table.Tr key={task.id}>
|
||||
<Table.Td>
|
||||
<Text fw={500}>#{task.id}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Stack gap={0}>
|
||||
<Text size="xs" c="dimmed">
|
||||
#{task.approval_id}
|
||||
</Text>
|
||||
<Text size="sm" lineClamp={1}>
|
||||
{task.approval?.topic?.name || '—'}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm">
|
||||
{task.executor?.full_name || '—'}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{task.executor?.department?.name}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" lineClamp={2}>
|
||||
{task.task_text || '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge variant="light" color="gray">
|
||||
#{task.step_order}
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge
|
||||
color={STATUS_COLORS[task.status || ''] || 'gray'}
|
||||
variant={task.status === 'completed' ? 'filled' : 'light'}
|
||||
>
|
||||
{STATUS_LABELS[task.status || ''] || task.status}
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
{task.require_file ? (
|
||||
<Badge size="xs" color="violet" variant="light">
|
||||
Да
|
||||
</Badge>
|
||||
) : (
|
||||
<Text size="xs" c="dimmed">—</Text>
|
||||
)}
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="xs" c="dimmed">
|
||||
{task.created_at
|
||||
? dayjs(task.created_at).format('DD.MM.YYYY HH:mm')
|
||||
: '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="xs" c="dimmed">
|
||||
{task.completed_at
|
||||
? dayjs(task.completed_at).format('DD.MM.YYYY HH:mm')
|
||||
: '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Group gap="xs">
|
||||
<Tooltip label="Просмотреть">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="blue"
|
||||
onClick={() => setSelectedTaskId(task.id!)}
|
||||
>
|
||||
<IconEye size={16} />
|
||||
</ActionIcon>
|
||||
const columns: Column<Row>[] = [
|
||||
{
|
||||
key: 'id',
|
||||
header: 'ID',
|
||||
width: 80,
|
||||
cell: (r) => <Text size="sm" fw={500}>#{r.id}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'task',
|
||||
header: 'Задача',
|
||||
cell: (r) => (
|
||||
<Group gap={6} wrap="nowrap" align="flex-start">
|
||||
<Text size="sm" lineClamp={2} style={{ flex: 1, minWidth: 0 }}>{r.task_text || '—'}</Text>
|
||||
{r.require_file && (
|
||||
<Tooltip label="Нужен файл">
|
||||
<IconPaperclip size={14} style={{ flexShrink: 0, marginTop: 3, opacity: 0.55 }} />
|
||||
</Tooltip>
|
||||
)}
|
||||
</Group>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'approval',
|
||||
header: 'Заявка',
|
||||
width: 220,
|
||||
cell: (r) => (
|
||||
<Stack gap={0} miw={0}>
|
||||
<Text size="sm" lineClamp={1}>{r.approval?.topic?.name || '—'}</Text>
|
||||
<Text size="xs" c="dimmed">#{r.approval_id} · шаг {r.step_order}</Text>
|
||||
</Stack>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'executor',
|
||||
header: 'Исполнитель',
|
||||
width: 220,
|
||||
cell: (r) =>
|
||||
r.executor?.full_name ? (
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Avatar size={24} radius="xl" color="initials" name={r.executor.full_name} />
|
||||
<Stack gap={0} miw={0}>
|
||||
<Text size="sm" truncate>{r.executor.full_name}</Text>
|
||||
{r.executor.department?.name && (
|
||||
<Text size="xs" c="dimmed" truncate>{r.executor.department.name}</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</Group>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed">—</Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Статус',
|
||||
width: 150,
|
||||
cell: (r) => <StatusBadge kind="task" status={r.status || ''} />,
|
||||
},
|
||||
{
|
||||
key: 'created',
|
||||
header: 'Создана',
|
||||
width: 150,
|
||||
cell: (r) => <Text size="sm" c="dimmed">{r.created_at ? formatMsk(r.created_at) : '—'}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'completed',
|
||||
header: 'Выполнена',
|
||||
width: 150,
|
||||
cell: (r) => <Text size="sm" c="dimmed">{r.completed_at ? formatMsk(r.completed_at) : '—'}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: '',
|
||||
width: 56,
|
||||
align: 'right',
|
||||
cell: (r) => (
|
||||
<Tooltip label="Удалить">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="red"
|
||||
onClick={() => handleDelete(task.id!)}
|
||||
aria-label="Удалить задачу"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation() // не открывать drawer
|
||||
setDeleteId(r.id!)
|
||||
}}
|
||||
>
|
||||
<IconTrash size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))
|
||||
)}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
{totalPages > 1 && (
|
||||
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">
|
||||
Страница {page} из {totalPages}
|
||||
</Text>
|
||||
<Pagination
|
||||
value={page}
|
||||
onChange={setPage}
|
||||
total={totalPages}
|
||||
withEdges
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<PageHeader title="Задачи" description={isLoading ? undefined : `Всего: ${total}`} />
|
||||
|
||||
<FilterBar activeCount={activeCount} onReset={resetFilters}>
|
||||
<Select
|
||||
placeholder="Статус"
|
||||
data={STATUS_OPTIONS}
|
||||
value={filters.status}
|
||||
onChange={(status) => update({ status })}
|
||||
clearable
|
||||
w={180}
|
||||
/>
|
||||
</Group>
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Paper>
|
||||
<Select
|
||||
placeholder="Исполнитель"
|
||||
data={executorOptions}
|
||||
value={filters.executor}
|
||||
onChange={(executor) => update({ executor })}
|
||||
searchable
|
||||
clearable
|
||||
w={220}
|
||||
/>
|
||||
<Switch
|
||||
label="Нужен файл"
|
||||
checked={filters.requireFile}
|
||||
onChange={(e) => update({ requireFile: e.currentTarget.checked })}
|
||||
/>
|
||||
</FilterBar>
|
||||
|
||||
{isFetching && !isLoading && (
|
||||
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
|
||||
<Loader size="xs" />
|
||||
</Box>
|
||||
)}
|
||||
<DataTable<Row>
|
||||
columns={columns}
|
||||
rows={data?.data ?? []}
|
||||
getRowId={(r) => r.id!}
|
||||
loading={isLoading}
|
||||
refreshing={isFetching}
|
||||
minWidth={1000}
|
||||
onRowClick={(r) => {
|
||||
setDrawerId(r.id!)
|
||||
setDrawerOpened(true)
|
||||
}}
|
||||
empty={{
|
||||
title: 'Задачи не найдены',
|
||||
description: activeCount > 0 ? 'Измените или сбросьте фильтры' : undefined,
|
||||
}}
|
||||
pagination={{ page, pageSize: LIMIT, total, onChange: setPage }}
|
||||
/>
|
||||
|
||||
<ApprovalTaskDetailsModal
|
||||
taskId={selectedTaskId}
|
||||
opened={selectedTaskId !== null}
|
||||
onClose={() => setSelectedTaskId(null)}
|
||||
<ApprovalTaskDetailsDrawer
|
||||
taskId={drawerId}
|
||||
opened={drawerOpened}
|
||||
onClose={() => setDrawerOpened(false)}
|
||||
/>
|
||||
|
||||
<ConfirmModal
|
||||
opened={deleteId !== null}
|
||||
onClose={() => setDeleteId(null)}
|
||||
onConfirm={() => {
|
||||
if (deleteId !== null) deleteTask.mutate(deleteId, { onSettled: () => setDeleteId(null) })
|
||||
}}
|
||||
title="Удалить задачу?"
|
||||
message={`Задача #${deleteId} будет удалена без возможности восстановления.`}
|
||||
confirmLabel="Удалить"
|
||||
danger
|
||||
loading={deleteTask.isPending}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,211 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import { Avatar, Box, Button, Drawer, Group, Select, Skeleton, Stack, Text } from '@mantine/core'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import { IconPaperclip } from '@tabler/icons-react'
|
||||
|
||||
import { useApprovalTask, useUpdateApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
|
||||
import { TASK_STATUSES } from '@/features/approvalTasks/const'
|
||||
import { StatusBadge } from '@/components/ui/StatusBadge'
|
||||
import { InfoList, InfoRow } from '@/components/ui/InfoRow'
|
||||
import { FileList } from '@/components/ui/FileList'
|
||||
import { saveFile, taskFileUrl } from '@/lib/fileApi'
|
||||
import { formatMsk } from '@/utils/date'
|
||||
import FilePreviewModal from '@/pages/approvals/components/FilePreviewModal'
|
||||
import classes from '@/components/UserDrawer.module.css'
|
||||
|
||||
interface Props {
|
||||
taskId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
function Section({ title, count, children }: { title: string; count?: number; children: React.ReactNode }) {
|
||||
return (
|
||||
<Box>
|
||||
<Group gap={6} mb="xs">
|
||||
<Text size="sm" fw={600}>{title}</Text>
|
||||
{count !== undefined && <Text size="xs" c="dimmed">{count}</Text>}
|
||||
</Group>
|
||||
{children}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ApprovalTaskDetailsDrawer({ taskId, opened, onClose }: Props) {
|
||||
const { data: task, isLoading } = useApprovalTask(taskId)
|
||||
const updateTask = useUpdateApprovalTask()
|
||||
|
||||
const [status, setStatus] = useState<string | null>(null)
|
||||
const [preview, setPreview] = useState<{ id: number; name: string; type: string } | null>(null)
|
||||
|
||||
// Выбранный статус синхронизируем с данными задачи
|
||||
useEffect(() => {
|
||||
setStatus(task?.status ?? null)
|
||||
}, [task?.id, task?.status])
|
||||
|
||||
useEffect(() => {
|
||||
if (!opened) setPreview(null)
|
||||
}, [opened])
|
||||
|
||||
const dirty = !!task && !!status && status !== task.status
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!task?.id || !status) return
|
||||
await updateTask.mutateAsync({ id: task.id, status })
|
||||
onClose()
|
||||
}
|
||||
|
||||
const handleDownload = async (fileId: number, fileName: string) => {
|
||||
if (!taskId) return
|
||||
try {
|
||||
await saveFile(taskFileUrl(taskId, fileId, true), fileName)
|
||||
notifications.show({ title: 'Готово', message: 'Файл скачан', color: 'green' })
|
||||
} catch (error) {
|
||||
console.error('Download error:', error)
|
||||
notifications.show({ title: 'Ошибка', message: 'Не удалось скачать файл', color: 'red' })
|
||||
}
|
||||
}
|
||||
|
||||
const files = task?.files ?? []
|
||||
|
||||
return (
|
||||
<>
|
||||
<Drawer.Root opened={opened} onClose={onClose} position="right" size="min(560px, 100vw)">
|
||||
<Drawer.Overlay backgroundOpacity={0.25} />
|
||||
<Drawer.Content>
|
||||
<Drawer.Header>
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Text fw={600}>Задача #{taskId}</Text>
|
||||
{task && <StatusBadge kind="task" status={task.status || ''} />}
|
||||
</Group>
|
||||
{task && (
|
||||
<Text size="xs" c="dimmed" truncate>
|
||||
Заявка #{task.approval_id}
|
||||
{task.approval?.topic?.name && ` · ${task.approval.topic.name}`}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body className={classes.body}>
|
||||
{isLoading ? (
|
||||
<Stack className={classes.section} gap="md">
|
||||
<Skeleton h={160} />
|
||||
<Skeleton h={80} />
|
||||
<Skeleton h={120} />
|
||||
</Stack>
|
||||
) : !task ? (
|
||||
<Text className={classes.section} size="sm" c="dimmed">Задача не найдена</Text>
|
||||
) : (
|
||||
<>
|
||||
<Stack className={classes.section} gap="xl">
|
||||
<Section title="Текст задачи">
|
||||
<Text size="sm" style={{ whiteSpace: 'pre-wrap' }}>{task.task_text || '—'}</Text>
|
||||
{task.require_file && (
|
||||
<Group gap={6} mt="xs" c="dimmed">
|
||||
<IconPaperclip size={14} />
|
||||
<Text size="xs" c="dimmed">Для выполнения нужен файл</Text>
|
||||
</Group>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<InfoList>
|
||||
<InfoRow label="Исполнитель">
|
||||
{task.executor?.full_name ? (
|
||||
<>
|
||||
<Avatar size={22} radius="xl" color="initials" name={task.executor.full_name} />
|
||||
<Text size="sm">{task.executor.full_name}</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text size="sm">—</Text>
|
||||
)}
|
||||
</InfoRow>
|
||||
{task.executor?.department?.name && (
|
||||
<InfoRow label="Отдел">
|
||||
<Text size="sm">{task.executor.department.name}</Text>
|
||||
</InfoRow>
|
||||
)}
|
||||
<InfoRow label="Шаг">
|
||||
<Text size="sm">{task.step_order}</Text>
|
||||
</InfoRow>
|
||||
<InfoRow label="Создана (МСК)">
|
||||
<Text size="sm">{task.created_at ? formatMsk(task.created_at) : '—'}</Text>
|
||||
</InfoRow>
|
||||
{task.updated_at && (
|
||||
<InfoRow label="Обновлена (МСК)">
|
||||
<Text size="sm">{formatMsk(task.updated_at)}</Text>
|
||||
</InfoRow>
|
||||
)}
|
||||
{task.completed_at && (
|
||||
<InfoRow label="Выполнена (МСК)">
|
||||
<Text size="sm">{formatMsk(task.completed_at)}</Text>
|
||||
</InfoRow>
|
||||
)}
|
||||
</InfoList>
|
||||
|
||||
{files.length > 0 && (
|
||||
<Section title="Файлы" count={files.length}>
|
||||
<FileList files={files} onPreview={setPreview} onDownload={handleDownload} />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{task.approval && (
|
||||
<Section title="Связанная заявка">
|
||||
<InfoList>
|
||||
<InfoRow label="Заявка">
|
||||
<Text size="sm" fw={500}>#{task.approval.id}</Text>
|
||||
</InfoRow>
|
||||
<InfoRow label="Тема">
|
||||
<Text size="sm">{task.approval.topic?.name || '—'}</Text>
|
||||
</InfoRow>
|
||||
<InfoRow label="Инициатор">
|
||||
<Text size="sm">{task.approval.initiator?.full_name || '—'}</Text>
|
||||
</InfoRow>
|
||||
<InfoRow label="Статус">
|
||||
<StatusBadge kind="approval" status={task.approval.status || ''} size="sm" />
|
||||
</InfoRow>
|
||||
</InfoList>
|
||||
</Section>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
<Group className={classes.footer} justify="space-between" wrap="nowrap">
|
||||
<Select
|
||||
aria-label="Статус задачи"
|
||||
placeholder="Статус"
|
||||
data={TASK_STATUSES.map((s) => ({ value: s.value, label: s.label }))}
|
||||
value={status}
|
||||
onChange={setStatus}
|
||||
allowDeselect={false}
|
||||
w={200}
|
||||
/>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Button variant="default" onClick={onClose} disabled={updateTask.isPending}>
|
||||
Закрыть
|
||||
</Button>
|
||||
<Button onClick={handleSave} loading={updateTask.isPending} disabled={!dirty}>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
</>
|
||||
)}
|
||||
</Drawer.Body>
|
||||
</Drawer.Content>
|
||||
</Drawer.Root>
|
||||
|
||||
{preview && taskId && (
|
||||
<FilePreviewModal
|
||||
taskId={taskId}
|
||||
fileId={preview.id}
|
||||
fileName={preview.name}
|
||||
fileType={preview.type}
|
||||
opened
|
||||
onClose={() => setPreview(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,397 +0,0 @@
|
|||
import { useState } from 'react'
|
||||
import {
|
||||
Modal,
|
||||
Stack,
|
||||
Text,
|
||||
Group,
|
||||
Badge,
|
||||
Paper,
|
||||
Loader,
|
||||
Center,
|
||||
ScrollArea,
|
||||
Select,
|
||||
Button,
|
||||
Box,
|
||||
ActionIcon,
|
||||
Tooltip,
|
||||
} from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import {
|
||||
IconUser,
|
||||
IconBuilding,
|
||||
IconCalendar,
|
||||
IconFileText,
|
||||
IconCheck,
|
||||
IconEye,
|
||||
IconDownload,
|
||||
} from '@tabler/icons-react'
|
||||
import { useApprovalTask, useUpdateApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
|
||||
import { TASK_STATUSES, STATUS_COLORS, STATUS_LABELS } from '@/features/approvalTasks/const'
|
||||
import FilePreviewModal from '@/pages/approvals/components/FilePreviewModal'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/ru'
|
||||
|
||||
dayjs.locale('ru')
|
||||
|
||||
interface ApprovalTaskDetailsModalProps {
|
||||
taskId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// Определение MIME типа по расширению
|
||||
const getMimeType = (fileName: string): string => {
|
||||
const ext = fileName.split('.').pop()?.toLowerCase() || ''
|
||||
const mimeTypes: Record<string, string> = {
|
||||
'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'png': 'image/png',
|
||||
'gif': 'image/gif', 'webp': 'image/webp', 'svg': 'image/svg+xml',
|
||||
'pdf': 'application/pdf', 'txt': 'text/plain',
|
||||
'doc': 'application/msword',
|
||||
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'xls': 'application/vnd.ms-excel',
|
||||
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
}
|
||||
return mimeTypes[ext] || 'application/octet-stream'
|
||||
}
|
||||
|
||||
const PREVIEWABLE_TYPES = [
|
||||
'image/jpeg', 'image/png', 'image/gif', 'image/webp',
|
||||
'image/svg+xml', 'application/pdf', 'text/plain',
|
||||
]
|
||||
|
||||
export default function ApprovalTaskDetailsModal({
|
||||
taskId,
|
||||
opened,
|
||||
onClose
|
||||
}: ApprovalTaskDetailsModalProps) {
|
||||
const { data: task, isLoading } = useApprovalTask(taskId)
|
||||
const updateTask = useUpdateApprovalTask()
|
||||
|
||||
// Состояние для предпросмотра файла
|
||||
const [previewFileId, setPreviewFileId] = useState<number | null>(null)
|
||||
const [previewFileName, setPreviewFileName] = useState('')
|
||||
const [previewFileType, setPreviewFileType] = useState('')
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
status: '',
|
||||
},
|
||||
})
|
||||
|
||||
const handleFilePreview = (fileId: number, fileName: string) => {
|
||||
setPreviewFileId(fileId)
|
||||
setPreviewFileName(fileName)
|
||||
setPreviewFileType(getMimeType(fileName))
|
||||
}
|
||||
|
||||
const handleFileDownload = async (fileId: number, fileName: string) => {
|
||||
try {
|
||||
const token = localStorage.getItem('token')
|
||||
const timestamp = Math.floor(Date.now() / 1000).toString()
|
||||
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
||||
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
|
||||
const message = publicKey + ':' + timestamp
|
||||
const CryptoJS = await import('crypto-js')
|
||||
const signature = CryptoJS.HmacSHA256(message, privateKey).toString(CryptoJS.enc.Hex)
|
||||
const deviceId = localStorage.getItem('device_id') || 'admin-panel'
|
||||
|
||||
// 🆕 Используем URL для задач
|
||||
const url = `/api/approval-tasks/${taskId}/files/${fileId}/download`
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'ApiKey': signature,
|
||||
'X-Timestamp': timestamp,
|
||||
'x-device-id': deviceId,
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) throw new Error('Failed to download file')
|
||||
|
||||
const blob = await response.blob()
|
||||
const blobUrl = window.URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = blobUrl
|
||||
link.download = fileName
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
window.URL.revokeObjectURL(blobUrl)
|
||||
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Файл скачан',
|
||||
color: 'green',
|
||||
})
|
||||
} catch (error) {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: 'Не удалось скачать файл',
|
||||
color: 'red',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
if (!task?.id) return
|
||||
await updateTask.mutateAsync({
|
||||
id: task.id,
|
||||
status: values.status,
|
||||
})
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={
|
||||
<Group>
|
||||
<Text fw={700}>Задача #{taskId}</Text>
|
||||
{task && (
|
||||
<Badge color={STATUS_COLORS[task.status || ''] || 'gray'}>
|
||||
{STATUS_LABELS[task.status || ''] || task.status}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
}
|
||||
size="xl"
|
||||
styles={{
|
||||
body: {
|
||||
height: 'calc(80vh - 120px)',
|
||||
padding: 0,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Center p={40}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : task ? (
|
||||
<ScrollArea
|
||||
style={{ height: 'calc(80vh - 120px)' }}
|
||||
offsetScrollbars
|
||||
>
|
||||
<Box p="md">
|
||||
<Stack gap="md">
|
||||
{/* Информация о задаче */}
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" c="dimmed" mb="xs">Информация о задаче</Text>
|
||||
<Stack gap="sm">
|
||||
<Text size="sm" c="dimmed">Текст задачи:</Text>
|
||||
<Text size="sm" style={{ whiteSpace: 'pre-wrap' }}>
|
||||
{task.task_text || '—'}
|
||||
</Text>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Шаг:</Text>
|
||||
<Badge variant="light">#{task.step_order}</Badge>
|
||||
</Group>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Требует файл:</Text>
|
||||
<Badge color={task.require_file ? 'violet' : 'gray'} variant="light">
|
||||
{task.require_file ? 'Да' : 'Нет'}
|
||||
</Badge>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* 🆕 Прикреплённые файлы */}
|
||||
{task.files && task.files.length > 0 && (
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" c="dimmed" mb="xs">Прикреплённые файлы</Text>
|
||||
<Stack gap="xs">
|
||||
{task.files.map((file) => {
|
||||
const mimeType = getMimeType(file.file_name || '')
|
||||
const canPreview = PREVIEWABLE_TYPES.includes(mimeType)
|
||||
const fileSizeKB = file.file_base64
|
||||
? Math.round((file.file_base64.length * 3 / 4) / 1024)
|
||||
: 0
|
||||
|
||||
return (
|
||||
<Paper key={file.id} withBorder p="sm">
|
||||
<Group justify="space-between">
|
||||
<Group gap="sm">
|
||||
<IconFileText size={20} color="blue" />
|
||||
<Stack gap={0}>
|
||||
<Text size="sm" fw={500}>
|
||||
{file.file_name || 'Без имени'}
|
||||
</Text>
|
||||
{fileSizeKB > 0 && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{fileSizeKB} KB
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</Group>
|
||||
<Group gap="xs">
|
||||
{canPreview && (
|
||||
<Tooltip label="Предпросмотр">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="blue"
|
||||
onClick={() => handleFilePreview(file.id!, file.file_name || '')}
|
||||
>
|
||||
<IconEye size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip label="Скачать">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="green"
|
||||
onClick={() => handleFileDownload(file.id!, file.file_name || '')}
|
||||
>
|
||||
<IconDownload size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Group>
|
||||
</Paper>
|
||||
)
|
||||
})}
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Связанная заявка */}
|
||||
{task.approval && (
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" c="dimmed" mb="xs">Связанная заявка</Text>
|
||||
<Stack gap="sm">
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">ID заявки:</Text>
|
||||
<Text fw={500}>#{task.approval.id}</Text>
|
||||
</Group>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Тема:</Text>
|
||||
<Text>{task.approval.topic?.name || '—'}</Text>
|
||||
</Group>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Инициатор:</Text>
|
||||
<Group gap="xs">
|
||||
<IconUser size={16} />
|
||||
<Text>{task.approval.initiator?.full_name || '—'}</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Статус заявки:</Text>
|
||||
<Badge>{task.approval.status}</Badge>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Исполнитель */}
|
||||
{task.executor && (
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" c="dimmed" mb="xs">Исполнитель</Text>
|
||||
<Stack gap="sm">
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Имя:</Text>
|
||||
<Group gap="xs">
|
||||
<IconUser size={16} />
|
||||
<Text fw={500}>{task.executor.full_name}</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
{task.executor.department && (
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Отдел:</Text>
|
||||
<Group gap="xs">
|
||||
<IconBuilding size={16} />
|
||||
<Text>{task.executor.department.name}</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Даты */}
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" c="dimmed" mb="xs">Временные метки</Text>
|
||||
<Stack gap="sm">
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Создана:</Text>
|
||||
<Group gap="xs">
|
||||
<IconCalendar size={16} />
|
||||
<Text>
|
||||
{task.created_at
|
||||
? dayjs(task.created_at).format('DD.MM.YYYY HH:mm')
|
||||
: '—'}
|
||||
</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Обновлена:</Text>
|
||||
<Text>
|
||||
{task.updated_at
|
||||
? dayjs(task.updated_at).format('DD.MM.YYYY HH:mm')
|
||||
: '—'}
|
||||
</Text>
|
||||
</Group>
|
||||
{task.completed_at && (
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Выполнена:</Text>
|
||||
<Group gap="xs">
|
||||
<IconCheck size={16} color="green" />
|
||||
<Text c="green">
|
||||
{dayjs(task.completed_at).format('DD.MM.YYYY HH:mm')}
|
||||
</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* Форма обновления статуса */}
|
||||
<Paper withBorder p="md" bg="blue.0">
|
||||
<Text size="sm" fw={600} mb="sm">Изменить статус</Text>
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="md">
|
||||
<Select
|
||||
label="Новый статус"
|
||||
placeholder="Выберите статус"
|
||||
data={TASK_STATUSES.map((s) => ({ value: s.value, label: s.label }))}
|
||||
value={form.values.status || task.status}
|
||||
onChange={(v) => form.setFieldValue('status', v || '')}
|
||||
required
|
||||
/>
|
||||
<Group justify="flex-end">
|
||||
<Button
|
||||
type="submit"
|
||||
loading={updateTask.isPending}
|
||||
leftSection={<IconCheck size={16} />}
|
||||
>
|
||||
Обновить статус
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
</Paper>
|
||||
</Stack>
|
||||
</Box>
|
||||
</ScrollArea>
|
||||
) : (
|
||||
<Center p={40}>
|
||||
<Text c="dimmed">Задача не найдена</Text>
|
||||
</Center>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{previewFileId && taskId && (
|
||||
<FilePreviewModal
|
||||
taskId={taskId}
|
||||
fileId={previewFileId}
|
||||
fileName={previewFileName}
|
||||
fileType={previewFileType}
|
||||
opened={!!previewFileId}
|
||||
onClose={() => setPreviewFileId(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,457 +1,430 @@
|
|||
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 { useEffect, useMemo, useState } from 'react'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import { Avatar, Button, Group, Popover, Select, Stack, Text, TextInput } from '@mantine/core'
|
||||
import { DatePicker, DatePickerInput } from '@mantine/dates'
|
||||
import { useDebouncedValue } from '@mantine/hooks'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import { IconCalendar, IconDownload, IconSearch } from '@tabler/icons-react'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/ru'
|
||||
|
||||
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";
|
||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||
import { approvalsApi, type ApprovalsListParams, type ApprovalsReportParams } from '@/api/approvals'
|
||||
import { formatMsk } from '@/utils/date'
|
||||
|
||||
import { PageHeader } from '@/components/ui/PageHeader'
|
||||
import { FilterBar } from '@/components/ui/FilterBar'
|
||||
import { MultiFilter } from '@/components/ui/MultiFilter'
|
||||
import { DataTable, type Column } from '@/components/ui/DataTable'
|
||||
import { StatusBadge } from '@/components/ui/StatusBadge'
|
||||
import { APPROVAL_STATUS } from '@/components/ui/statuses'
|
||||
import ApprovalDetailsDrawer from './components/ApprovalDetailsDrawer'
|
||||
|
||||
dayjs.locale('ru')
|
||||
|
||||
const LIMIT = 20
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
pending: 'blue',
|
||||
approved: 'green',
|
||||
rejected: 'red',
|
||||
revoked: 'orange',
|
||||
revision: 'violet',
|
||||
type DateRange = [Date | null, Date | null]
|
||||
type Row = NonNullable<NonNullable<ReturnType<typeof useApprovals>['data']>['data']>[number]
|
||||
|
||||
interface Filters {
|
||||
id: string
|
||||
status: string | null
|
||||
categories: string[]
|
||||
topics: string[]
|
||||
department: string | null
|
||||
initiator: string | null
|
||||
range: DateRange
|
||||
}
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
pending: 'На согласовании',
|
||||
approved: 'Согласована',
|
||||
rejected: 'Отклонена',
|
||||
revoked: 'Отозвана',
|
||||
revision: 'На доработке',
|
||||
const EMPTY_FILTERS: Filters = {
|
||||
id: '',
|
||||
status: null,
|
||||
categories: [],
|
||||
topics: [],
|
||||
department: null,
|
||||
initiator: null,
|
||||
range: [null, null],
|
||||
}
|
||||
|
||||
export default function ApprovalsPage() {
|
||||
// Фильтры списка
|
||||
const [page, setPage] = useState(1)
|
||||
const [search, setSearch] = useState('')
|
||||
const [statusFilter, setStatusFilter] = useState<string | null>(null)
|
||||
const [categoryFilter, setCategoryFilter] = useState<string | null>(null)
|
||||
const [topicFilter, setTopicFilter] = useState<string | null>(null)
|
||||
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
|
||||
// Черновики в общем списке заявок не показываем
|
||||
const STATUS_OPTIONS = Object.entries(APPROVAL_STATUS)
|
||||
.filter(([value]) => value !== 'draft')
|
||||
.map(([value, m]) => ({ value, label: m.label }))
|
||||
const VALID_STATUSES = new Set(STATUS_OPTIONS.map((o) => o.value))
|
||||
|
||||
const [reportDateFrom, setReportDateFrom] = useState<Date | null>(null)
|
||||
const [reportDateTo, setReportDateTo] = useState<Date | null>(null)
|
||||
const [reportLoading, setReportLoading] = useState(false)
|
||||
|
||||
const [selectedApprovalId, setSelectedApprovalId] = useState<number | null>(null)
|
||||
|
||||
const [searchInput, setSearchInput] = useState('')
|
||||
const [searchError, setSearchError] = useState<string | null>(null)
|
||||
const [debouncedSearch] = useDebouncedValue(searchInput, 400)
|
||||
|
||||
useEffect(() => {
|
||||
if (debouncedSearch === '') {
|
||||
setSearch('')
|
||||
setSearchError(null)
|
||||
setPage(1)
|
||||
return
|
||||
// Начальные фильтры из ссылки (например, с дашборда: /approvals?status=pending&date_to=2026-07-20).
|
||||
// Читаем один раз при монтировании, дальше URL не синхронизируем.
|
||||
function initialFilters(params: URLSearchParams): Filters {
|
||||
const status = params.get('status')
|
||||
const from = params.get('date_from')
|
||||
const to = params.get('date_to')
|
||||
return {
|
||||
...EMPTY_FILTERS,
|
||||
status: status && VALID_STATUSES.has(status) ? status : null,
|
||||
range: [from ? dayjs(from).toDate() : null, to ? dayjs(to).toDate() : null],
|
||||
}
|
||||
}
|
||||
|
||||
if (debouncedSearch.length < 2) {
|
||||
setSearchError('Введите минимум 2 символа')
|
||||
return
|
||||
}
|
||||
const fmtDate = (d: Date) => dayjs(d).format('YYYY-MM-DD')
|
||||
|
||||
setSearchError(null)
|
||||
setSearch(debouncedSearch)
|
||||
setPage(1)
|
||||
}, [debouncedSearch])
|
||||
/* ——— Выгрузка отчёта ——— */
|
||||
|
||||
const { data: categoryTopics } = useTopics({
|
||||
limit: 1000,
|
||||
...(categoryFilter && { category_id: Number(categoryFilter) }),
|
||||
})
|
||||
const REPORT_PRESETS: { label: string; range: () => DateRange }[] = [
|
||||
{ label: 'Этот месяц', range: () => [dayjs().startOf('month').toDate(), dayjs().endOf('month').toDate()] },
|
||||
{
|
||||
label: 'Прошлый месяц',
|
||||
range: () => [
|
||||
dayjs().subtract(1, 'month').startOf('month').toDate(),
|
||||
dayjs().subtract(1, 'month').endOf('month').toDate(),
|
||||
],
|
||||
},
|
||||
{ label: 'Всё время', range: () => [null, null] },
|
||||
]
|
||||
|
||||
const effectiveTopicFilter = categoryFilter && categoryTopics?.data?.length === 1
|
||||
? String(categoryTopics.data[0].id)
|
||||
: topicFilter
|
||||
function ReportButton() {
|
||||
const [opened, setOpened] = useState(false)
|
||||
const [range, setRange] = useState<DateRange>([null, null])
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
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)
|
||||
const handleDownload = async () => {
|
||||
setLoading(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 params: ApprovalsReportParams = { all_access: true }
|
||||
if (range[0]) params.date_from = fmtDate(range[0])
|
||||
if (range[1]) params.date_to = fmtDate(range[1])
|
||||
|
||||
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)
|
||||
link.setAttribute('download', `Согласования_${dayjs().format('DD.MM.YYYY_HH-mm')}.xlsx`)
|
||||
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: 'Отчёт скачан', color: 'green' })
|
||||
setOpened(false)
|
||||
} catch (error) {
|
||||
const description = (error as { response?: { data?: { error_description?: string } } }).response?.data
|
||||
?.error_description
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: text || 'Не удалось сформировать отчёт',
|
||||
message: description || 'Не удалось сформировать отчёт',
|
||||
color: 'red',
|
||||
})
|
||||
} else {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось сформировать отчёт',
|
||||
color: 'red',
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
setReportLoading(false)
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
{/* Заголовок и кнопка отчёта */}
|
||||
<Group justify="space-between">
|
||||
<Text size="xl" fw={700}>Заявки</Text>
|
||||
<Text c="dimmed" size="sm">
|
||||
Всего: {data?.total_count || 0}
|
||||
</Text>
|
||||
<Popover opened={opened} onChange={setOpened} position="bottom-end" shadow="md" width={300}>
|
||||
<Popover.Target>
|
||||
<Button
|
||||
variant="default"
|
||||
leftSection={<IconDownload size={16} />}
|
||||
onClick={() => setOpened((o) => !o)}
|
||||
>
|
||||
Отчёт
|
||||
</Button>
|
||||
</Popover.Target>
|
||||
|
||||
<Popover.Dropdown>
|
||||
<Stack gap="sm">
|
||||
<Stack gap={2}>
|
||||
<Text size="sm" fw={600}>Выгрузка в Excel</Text>
|
||||
<Text size="xs" c="dimmed">Без дат выгрузятся все заявки</Text>
|
||||
</Stack>
|
||||
|
||||
<Group gap={6}>
|
||||
{REPORT_PRESETS.map((p) => (
|
||||
<Button
|
||||
key={p.label}
|
||||
size="compact-xs"
|
||||
variant="default"
|
||||
onClick={() => setRange(p.range())}
|
||||
>
|
||||
{p.label}
|
||||
</Button>
|
||||
))}
|
||||
</Group>
|
||||
|
||||
{/* 🆕 Секция формирования отчёта */}
|
||||
<Paper withBorder p="md" bg="blue.0">
|
||||
<Stack gap="sm">
|
||||
<Group justify="space-between">
|
||||
<Group gap="xs">
|
||||
<IconFileExcel size={20} color="blue" />
|
||||
<Text fw={600} size="lg">Формирование отчёта</Text>
|
||||
</Group>
|
||||
<DatePicker type="range" value={range} onChange={(v) => setRange(v as DateRange)} />
|
||||
|
||||
<Button
|
||||
leftSection={<IconFileExcel size={16} />}
|
||||
color="green"
|
||||
onClick={handleGenerateReport}
|
||||
loading={reportLoading}
|
||||
size="sm"
|
||||
fullWidth
|
||||
leftSection={<IconDownload size={16} />}
|
||||
onClick={handleDownload}
|
||||
loading={loading}
|
||||
>
|
||||
Скачать XLSX
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light" p="xs">
|
||||
<Text size="sm">
|
||||
Выберите период для выгрузки отчёта. Если даты не указаны — будут выгружены все заявки.
|
||||
</Text>
|
||||
</Alert>
|
||||
|
||||
<Group gap="md" align="flex-end">
|
||||
<DatePickerInput
|
||||
label="Дата начала периода"
|
||||
placeholder="Выберите дату"
|
||||
value={reportDateFrom}
|
||||
onChange={(val) => setReportDateFrom(val as Date | null)}
|
||||
clearable
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
<DatePickerInput
|
||||
label="Дата окончания периода"
|
||||
placeholder="Выберите дату"
|
||||
value={reportDateTo}
|
||||
onChange={(val) => setReportDateTo(val as Date | null)}
|
||||
clearable
|
||||
minDate={reportDateFrom || undefined}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
<Divider />
|
||||
/* ——— Страница ——— */
|
||||
|
||||
{/* Фильтры списка */}
|
||||
<Paper withBorder p="md">
|
||||
<Text fw={600} size="lg" mb="sm">Фильтры списка</Text>
|
||||
<Stack gap="md">
|
||||
<Group gap="md" align="flex-end">
|
||||
export default function ApprovalsPage() {
|
||||
const [searchParams] = useSearchParams()
|
||||
|
||||
const [page, setPage] = useState(1)
|
||||
const [filters, setFilters] = useState<Filters>(() => initialFilters(searchParams))
|
||||
const [searchInput, setSearchInput] = useState('')
|
||||
const [debouncedSearch] = useDebouncedValue(searchInput.trim(), 400)
|
||||
// Короткие запросы (1 символ) на сервер не отправляем
|
||||
const search = debouncedSearch.length >= 2 ? debouncedSearch : ''
|
||||
|
||||
// Drawer: id храним отдельно от opened, чтобы содержимое не мигало при анимации закрытия
|
||||
const [drawerId, setDrawerId] = useState<number | null>(null)
|
||||
const [drawerOpened, setDrawerOpened] = useState(false)
|
||||
|
||||
useEffect(() => setPage(1), [search])
|
||||
|
||||
const update = (patch: Partial<Filters>) => {
|
||||
setFilters((prev) => ({ ...prev, ...patch }))
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
// === Справочники ===
|
||||
const { data: categories } = useCategories({ limit: 1000 })
|
||||
const { data: allTopics } = useTopics({ limit: 1000 })
|
||||
const { data: departments } = useDepartments()
|
||||
const { data: users } = useUsers({ limit: 1000 })
|
||||
|
||||
const topicById = useMemo(() => new Map((allTopics?.data ?? []).map((t) => [t.id, t])), [allTopics])
|
||||
|
||||
const categoryOptions = useMemo(
|
||||
() => (categories?.data ?? []).map((c) => ({ value: String(c.id), label: c.name || '' })),
|
||||
[categories],
|
||||
)
|
||||
|
||||
const topicOptions = useMemo(() => {
|
||||
const ids = filters.categories.map(Number)
|
||||
return (allTopics?.data ?? [])
|
||||
.filter((t) => ids.length === 0 || (t.category_id != null && ids.includes(t.category_id)))
|
||||
.map((t) => ({ value: String(t.id), label: `${t.category?.name || '—'} / ${t.name || ''}` }))
|
||||
}, [allTopics, filters.categories])
|
||||
|
||||
const departmentOptions = useMemo(
|
||||
() => (departments?.data ?? []).map((d) => ({ value: String(d.id), label: d.name || '' })),
|
||||
[departments],
|
||||
)
|
||||
|
||||
const userOptions = useMemo(
|
||||
() =>
|
||||
(users?.data ?? []).map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.full_name || u.username || `ID: ${u.id}`,
|
||||
})),
|
||||
[users],
|
||||
)
|
||||
|
||||
// При смене категорий убираем темы, которые в них не входят
|
||||
const handleCategories = (categoryIds: string[]) => {
|
||||
const ids = categoryIds.map(Number)
|
||||
const topics =
|
||||
ids.length === 0
|
||||
? filters.topics
|
||||
: filters.topics.filter((id) => {
|
||||
const cat = topicById.get(Number(id))?.category_id
|
||||
return cat != null && ids.includes(cat)
|
||||
})
|
||||
update({ categories: categoryIds, topics })
|
||||
}
|
||||
|
||||
// === Запрос ===
|
||||
const requestParams = useMemo(() => {
|
||||
const params: ApprovalsListParams = { offset: (page - 1) * LIMIT, limit: LIMIT }
|
||||
if (filters.id) params.id = Number(filters.id)
|
||||
if (search) params.content = search
|
||||
if (filters.status) params.status = filters.status
|
||||
if (filters.department) params.department_id = Number(filters.department)
|
||||
if (filters.initiator) params.initiator_id = Number(filters.initiator)
|
||||
if (filters.categories.length > 0) params.category_ids = filters.categories.map(Number)
|
||||
if (filters.topics.length > 0) params.topic_ids = filters.topics.map(Number)
|
||||
if (filters.range[0]) params.date_from = fmtDate(filters.range[0])
|
||||
if (filters.range[1]) params.date_to = fmtDate(filters.range[1])
|
||||
return params
|
||||
}, [page, search, filters])
|
||||
|
||||
const { data, isLoading, isFetching } = useApprovals(requestParams)
|
||||
const total = data?.total_count ?? 0
|
||||
|
||||
// === Фильтры ===
|
||||
const activeCount = [
|
||||
search,
|
||||
filters.id,
|
||||
filters.status,
|
||||
filters.department,
|
||||
filters.initiator,
|
||||
filters.categories.length > 0,
|
||||
filters.topics.length > 0,
|
||||
filters.range[0] || filters.range[1],
|
||||
].filter(Boolean).length
|
||||
|
||||
const resetFilters = () => {
|
||||
setSearchInput('')
|
||||
setFilters(EMPTY_FILTERS)
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
// === Таблица ===
|
||||
const columns: Column<Row>[] = [
|
||||
{
|
||||
key: 'id',
|
||||
header: 'ID',
|
||||
width: 80,
|
||||
cell: (r) => <Text size="sm" fw={500}>#{r.id}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'topic',
|
||||
header: 'Тема',
|
||||
cell: (r) => (
|
||||
<Stack gap={0} miw={0}>
|
||||
<Text size="sm" lineClamp={1}>{r.topic?.name || 'Тема не указана'}</Text>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>{r.topic?.category?.name || '—'}</Text>
|
||||
</Stack>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'initiator',
|
||||
header: 'Инициатор',
|
||||
cell: (r) =>
|
||||
r.initiator?.full_name ? (
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Avatar size={24} radius="xl" color="initials" name={r.initiator.full_name} />
|
||||
<Text size="sm" truncate>{r.initiator.full_name}</Text>
|
||||
</Group>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed">—</Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'department',
|
||||
header: 'Отдел',
|
||||
cell: (r) => <Text size="sm" c="dimmed">{r.department?.name || '—'}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'created',
|
||||
header: 'Создана',
|
||||
width: 160,
|
||||
cell: (r) => <Text size="sm" c="dimmed">{r.created_at ? formatMsk(r.created_at) : '—'}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Статус',
|
||||
width: 170,
|
||||
cell: (r) => <StatusBadge kind="approval" status={r.status || ''} />,
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<PageHeader
|
||||
title="Заявки"
|
||||
description={isLoading ? undefined : `Всего: ${total}`}
|
||||
actions={<ReportButton />}
|
||||
/>
|
||||
|
||||
<FilterBar activeCount={activeCount} onReset={resetFilters}>
|
||||
<TextInput
|
||||
label="Поиск по тексту заявки"
|
||||
placeholder="Введите 2+ символа..."
|
||||
placeholder="Поиск по тексту"
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.currentTarget.value)}
|
||||
error={searchError}
|
||||
rightSection={
|
||||
searchInput && (
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
onClick={() => setSearchInput('')}
|
||||
>
|
||||
<IconX size={14} />
|
||||
</ActionIcon>
|
||||
)
|
||||
}
|
||||
style={{ flex: 1 }}
|
||||
w={240}
|
||||
/>
|
||||
<TextInput
|
||||
placeholder="ID"
|
||||
value={filters.id}
|
||||
onChange={(e) => update({ id: e.currentTarget.value.replace(/\D/g, '') })}
|
||||
w={90}
|
||||
inputMode="numeric"
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Статус"
|
||||
placeholder="Все статусы"
|
||||
data={[
|
||||
{ value: 'pending', label: 'На согласовании' },
|
||||
{ value: 'approved', label: 'Согласована' },
|
||||
{ value: 'rejected', label: 'Отклонена' },
|
||||
{ value: 'revoked', label: 'Отозвана' },
|
||||
{ value: 'revision', label: 'На доработке' },
|
||||
]}
|
||||
value={statusFilter}
|
||||
onChange={(v) => {
|
||||
setStatusFilter(v)
|
||||
setPage(1)
|
||||
}}
|
||||
placeholder="Статус"
|
||||
data={STATUS_OPTIONS}
|
||||
value={filters.status}
|
||||
onChange={(status) => update({ status })}
|
||||
clearable
|
||||
style={{ minWidth: 180 }}
|
||||
w={170}
|
||||
/>
|
||||
</Group>
|
||||
|
||||
<Group gap="md" align="flex-end">
|
||||
<Select
|
||||
label="Тема"
|
||||
placeholder="Все темы"
|
||||
data={topicOptions}
|
||||
value={topicFilter}
|
||||
onChange={(v) => {
|
||||
setTopicFilter(v)
|
||||
setPage(1)
|
||||
}}
|
||||
clearable
|
||||
searchable
|
||||
style={{ minWidth: 200 }}
|
||||
disabled={!!categoryFilter}
|
||||
<MultiFilter
|
||||
label="Категории"
|
||||
options={categoryOptions}
|
||||
value={filters.categories}
|
||||
onChange={handleCategories}
|
||||
/>
|
||||
<MultiFilter
|
||||
label="Темы"
|
||||
options={topicOptions}
|
||||
value={filters.topics}
|
||||
onChange={(topics) => update({ topics })}
|
||||
width={340}
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Отдел"
|
||||
placeholder="Все отделы"
|
||||
placeholder="Отдел"
|
||||
data={departmentOptions}
|
||||
value={departmentFilter}
|
||||
onChange={(v) => {
|
||||
setDepartmentFilter(v)
|
||||
setPage(1)
|
||||
}}
|
||||
value={filters.department}
|
||||
onChange={(department) => update({ department })}
|
||||
searchable
|
||||
clearable
|
||||
style={{ minWidth: 180 }}
|
||||
w={170}
|
||||
/>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* Таблица */}
|
||||
<Paper withBorder>
|
||||
{isLoading ? (
|
||||
<Center p={60}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : (
|
||||
<>
|
||||
<Table striped highlightOnHover>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
||||
<Table.Th>Категория / Тема</Table.Th>
|
||||
<Table.Th>Инициатор</Table.Th>
|
||||
<Table.Th>Отдел</Table.Th>
|
||||
<Table.Th>Дата создания</Table.Th>
|
||||
<Table.Th style={{ width: 150 }}>Статус</Table.Th>
|
||||
<Table.Th style={{ width: 80 }}>Действия</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{data?.data?.length === 0 ? (
|
||||
<Table.Tr>
|
||||
<Table.Td colSpan={7}>
|
||||
<Center p={40}>
|
||||
<Text c="dimmed">Заявки не найдены</Text>
|
||||
</Center>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
) : (
|
||||
(data?.data || []).map((approval) => (
|
||||
<Table.Tr key={approval.id}>
|
||||
<Table.Td>
|
||||
<Text fw={500}>#{approval.id}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Stack gap={0}>
|
||||
<Text size="xs" c="dimmed">
|
||||
{approval.topic?.category?.name || '—'}
|
||||
</Text>
|
||||
<Group gap="xs">
|
||||
<IconFileText size={14} color="gray" />
|
||||
<Text size="sm" lineClamp={1}>
|
||||
{approval.topic?.name || 'Тема не указана'}
|
||||
</Text>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm">
|
||||
{approval.initiator?.full_name || '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" c="dimmed">
|
||||
{approval.department?.name || '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" c="dimmed">
|
||||
{approval.created_at
|
||||
? dayjs(approval.created_at).format('DD.MM.YYYY HH:mm')
|
||||
: '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge
|
||||
color={STATUS_COLORS[approval.status || ''] || 'gray'}
|
||||
variant={approval.status === 'pending' ? 'light' : 'filled'}
|
||||
>
|
||||
{STATUS_LABELS[approval.status || ''] || approval.status}
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Tooltip label="Просмотреть детали">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="blue"
|
||||
onClick={() => setSelectedApprovalId(approval.id!)}
|
||||
>
|
||||
<IconEye size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))
|
||||
)}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
|
||||
{totalPages > 1 && (
|
||||
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">
|
||||
Страница {page} из {totalPages}
|
||||
</Text>
|
||||
<Pagination
|
||||
value={page}
|
||||
onChange={setPage}
|
||||
total={totalPages}
|
||||
withEdges
|
||||
<Select
|
||||
placeholder="Инициатор"
|
||||
data={userOptions}
|
||||
value={filters.initiator}
|
||||
onChange={(initiator) => update({ initiator })}
|
||||
searchable
|
||||
clearable
|
||||
w={190}
|
||||
/>
|
||||
</Group>
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Paper>
|
||||
<DatePickerInput
|
||||
type="range"
|
||||
placeholder="Период создания"
|
||||
valueFormat="D MMM YYYY"
|
||||
leftSection={<IconCalendar size={16} />}
|
||||
value={filters.range}
|
||||
onChange={(range) => update({ range: range as DateRange })}
|
||||
clearable
|
||||
w={250}
|
||||
/>
|
||||
</FilterBar>
|
||||
|
||||
{isFetching && !isLoading && (
|
||||
<Box
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 70,
|
||||
right: 20,
|
||||
zIndex: 1000
|
||||
<DataTable<Row>
|
||||
columns={columns}
|
||||
rows={data?.data ?? []}
|
||||
getRowId={(r) => r.id!}
|
||||
loading={isLoading}
|
||||
refreshing={isFetching}
|
||||
onRowClick={(r) => {
|
||||
setDrawerId(r.id!)
|
||||
setDrawerOpened(true)
|
||||
}}
|
||||
>
|
||||
<Loader size="xs" />
|
||||
</Box>
|
||||
)}
|
||||
empty={{
|
||||
title: 'Заявки не найдены',
|
||||
description: activeCount > 0 ? 'Измените или сбросьте фильтры' : undefined,
|
||||
}}
|
||||
pagination={{ page, pageSize: LIMIT, total, onChange: setPage }}
|
||||
/>
|
||||
|
||||
<ApprovalDetailsModal
|
||||
approvalId={selectedApprovalId}
|
||||
opened={selectedApprovalId !== null}
|
||||
onClose={() => setSelectedApprovalId(null)}
|
||||
<ApprovalDetailsDrawer
|
||||
approvalId={drawerId}
|
||||
opened={drawerOpened}
|
||||
onClose={() => setDrawerOpened(false)}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,523 @@
|
|||
import { useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
ActionIcon,
|
||||
Alert,
|
||||
Avatar,
|
||||
Box,
|
||||
Code,
|
||||
Divider,
|
||||
Drawer,
|
||||
Group,
|
||||
Skeleton,
|
||||
Spoiler,
|
||||
Stack,
|
||||
Tabs,
|
||||
Text,
|
||||
ThemeIcon,
|
||||
Timeline,
|
||||
Tooltip,
|
||||
} from '@mantine/core'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import {
|
||||
IconAlertCircle,
|
||||
IconAlertTriangle,
|
||||
IconArrowBackUp,
|
||||
IconCheck,
|
||||
IconClock,
|
||||
IconDownload,
|
||||
IconEye,
|
||||
IconFileText,
|
||||
IconRotate,
|
||||
IconX,
|
||||
type Icon,
|
||||
} from '@tabler/icons-react'
|
||||
import {
|
||||
useAdditionalApprovers,
|
||||
useApproval,
|
||||
useApprovalComments,
|
||||
useApprovalObservers,
|
||||
useApprovalTasks,
|
||||
useRevocationRequest,
|
||||
} from '@/features/approvals/hooks/useApprovals'
|
||||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
||||
import { StatusBadge } from '@/components/ui/StatusBadge'
|
||||
import { STEP_STATUS } from '@/components/ui/statuses'
|
||||
import { InfoList, InfoRow } from '@/components/ui/InfoRow'
|
||||
import {
|
||||
approvalFileUrl,
|
||||
formatFileSize,
|
||||
getMimeType,
|
||||
isPreviewable,
|
||||
saveFile,
|
||||
} from '@/lib/fileApi'
|
||||
import { formatMsk } from '@/utils/date'
|
||||
import FilePreviewModal from './FilePreviewModal'
|
||||
import classes from '@/components/UserDrawer.module.css'
|
||||
|
||||
interface Props {
|
||||
approvalId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const MODE_LABELS: Record<string, string> = {
|
||||
sequential: 'Последовательно',
|
||||
any_of: 'Любой из согласующих',
|
||||
}
|
||||
|
||||
const STEP_ICONS: Record<string, Icon> = {
|
||||
pending: IconClock,
|
||||
approved: IconCheck,
|
||||
rejected: IconX,
|
||||
waiting: IconClock,
|
||||
cancelled_any_of: IconAlertCircle,
|
||||
}
|
||||
|
||||
function Section({ title, count, children }: { title: string; count?: number; children: React.ReactNode }) {
|
||||
return (
|
||||
<Box>
|
||||
<Group gap={6} mb="xs">
|
||||
<Text size="sm" fw={600}>{title}</Text>
|
||||
{count !== undefined && <Text size="xs" c="dimmed">{count}</Text>}
|
||||
</Group>
|
||||
{children}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ApprovalDetailsDrawer({ approvalId, opened, onClose }: Props) {
|
||||
const { data: approval, isLoading } = useApproval(approvalId)
|
||||
const { data: categories } = useCategories({ limit: 1000 })
|
||||
|
||||
// Хуки отдают ApiResponse<T> целиком — разворачиваем здесь
|
||||
const { data: additionalApproversResponse } = useAdditionalApprovers(approvalId)
|
||||
const { data: commentsResponse } = useApprovalComments(approvalId)
|
||||
const { data: observersResponse } = useApprovalObservers(approvalId)
|
||||
const { data: revocationRequestResponse } = useRevocationRequest(approvalId)
|
||||
const { data: tasksResponse } = useApprovalTasks(approvalId)
|
||||
|
||||
const additionalApprovers = additionalApproversResponse?.data ?? []
|
||||
const comments = commentsResponse?.data ?? []
|
||||
const observers = observersResponse?.data ?? []
|
||||
const revocationRequest = revocationRequestResponse?.data
|
||||
const tasksData = tasksResponse?.data
|
||||
|
||||
const [tab, setTab] = useState<string | null>('overview')
|
||||
const [preview, setPreview] = useState<{ id: number; name: string; type: string } | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!opened) {
|
||||
setTab('overview')
|
||||
setPreview(null)
|
||||
}
|
||||
}, [opened])
|
||||
|
||||
const category =
|
||||
approval?.topic?.category_id && categories?.data
|
||||
? categories.data.find((c) => c.id === approval.topic?.category_id)
|
||||
: null
|
||||
|
||||
// Копия, чтобы не мутировать данные из кэша react-query
|
||||
const steps = useMemo(
|
||||
() => [...(approval?.steps ?? [])].sort((a, b) => (a.step_order || 0) - (b.step_order || 0)),
|
||||
[approval],
|
||||
)
|
||||
|
||||
const tasks = tasksData?.tasks ?? []
|
||||
const plannedTasks = tasksData?.topic_executors ?? []
|
||||
// План показываем, пока заявка не согласована и реальных задач ещё нет
|
||||
const showPlannedTasks = approval?.status === 'pending' && plannedTasks.length > 0 && tasks.length === 0
|
||||
|
||||
const prettyMetadata = useMemo(() => {
|
||||
if (!approval?.metadata) return null
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(approval.metadata), null, 2)
|
||||
} catch {
|
||||
return approval.metadata
|
||||
}
|
||||
}, [approval?.metadata])
|
||||
|
||||
const handleDownload = async (fileId: number, fileName: string) => {
|
||||
if (!approvalId) return
|
||||
try {
|
||||
await saveFile(approvalFileUrl(approvalId, fileId, true), fileName)
|
||||
notifications.show({ title: 'Готово', message: 'Файл скачан', color: 'green' })
|
||||
} catch (error) {
|
||||
console.error('Download error:', error)
|
||||
notifications.show({ title: 'Ошибка', message: 'Не удалось скачать файл', color: 'red' })
|
||||
}
|
||||
}
|
||||
|
||||
const files = approval?.files ?? []
|
||||
const hasAlerts =
|
||||
!!tasksData?.has_task_error ||
|
||||
!!revocationRequest ||
|
||||
(approval?.status === 'revoked' && !!approval.revoked_by) ||
|
||||
approval?.status === 'revision'
|
||||
|
||||
return (
|
||||
<>
|
||||
<Drawer.Root opened={opened} onClose={onClose} position="right" size="min(720px, 100vw)">
|
||||
<Drawer.Overlay backgroundOpacity={0.25} />
|
||||
<Drawer.Content>
|
||||
<Drawer.Header>
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Text fw={600}>Заявка #{approvalId}</Text>
|
||||
{approval && <StatusBadge kind="approval" status={approval.status || ''} />}
|
||||
</Group>
|
||||
{approval?.topic?.name && (
|
||||
<Text size="xs" c="dimmed" truncate>{approval.topic.name}</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body className={classes.body}>
|
||||
{isLoading ? (
|
||||
<Stack className={classes.section} gap="md">
|
||||
<Skeleton h={64} />
|
||||
<Skeleton h={180} />
|
||||
<Skeleton h={120} />
|
||||
</Stack>
|
||||
) : !approval ? (
|
||||
<Text className={classes.section} size="sm" c="dimmed">Заявка не найдена</Text>
|
||||
) : (
|
||||
<>
|
||||
{hasAlerts && (
|
||||
<Stack className={classes.section} gap="sm" pb={0}>
|
||||
{tasksData?.has_task_error && (
|
||||
<Alert
|
||||
color="red"
|
||||
icon={<IconAlertTriangle size={16} />}
|
||||
title="Ошибка при создании задачи"
|
||||
>
|
||||
<Text size="sm">
|
||||
Для темы настроены исполнители и заявка согласована, но ни одной
|
||||
задачи не создано. Стоит проверить вручную.
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{revocationRequest && (
|
||||
<Alert
|
||||
color="orange"
|
||||
icon={<IconRotate size={16} />}
|
||||
title="Идёт запрос на отзыв заявки"
|
||||
>
|
||||
<Stack gap={6}>
|
||||
<Text size="sm">
|
||||
Запросил: {revocationRequest.requested_by_name}
|
||||
{revocationRequest.reason && ` · ${revocationRequest.reason}`}
|
||||
</Text>
|
||||
{revocationRequest.approvers.map((a) => (
|
||||
<Group key={a.approver_id} justify="space-between" wrap="nowrap">
|
||||
<Text size="sm">{a.approver_name}</Text>
|
||||
<StatusBadge kind="revocation" status={a.status} size="sm" />
|
||||
</Group>
|
||||
))}
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{approval.status === 'revoked' && approval.revoked_by && (
|
||||
<Alert color="orange" icon={<IconAlertCircle size={16} />} title="Заявка отозвана">
|
||||
<Text size="sm">
|
||||
{approval.revoked_by.full_name}
|
||||
{approval.revoked_at && ` · ${formatMsk(approval.revoked_at)}`}
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{approval.status === 'revision' && (
|
||||
<Alert color="violet" icon={<IconArrowBackUp size={16} />} title="Заявка на доработке">
|
||||
<Stack gap={4}>
|
||||
{approval.revision_comment && (
|
||||
<Text size="sm">{approval.revision_comment}</Text>
|
||||
)}
|
||||
{!!approval.revision_count && (
|
||||
<Text size="xs" c="dimmed">
|
||||
Количество доработок: {approval.revision_count}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
<Tabs value={tab} onChange={setTab} mt={hasAlerts ? 'sm' : 0}>
|
||||
<Tabs.List className={classes.tabsList}>
|
||||
<Tabs.Tab value="overview">Обзор</Tabs.Tab>
|
||||
<Tabs.Tab
|
||||
value="flow"
|
||||
rightSection={steps.length > 0 ? <Text span size="xs" c="dimmed">{steps.length}</Text> : null}
|
||||
>
|
||||
Согласование
|
||||
</Tabs.Tab>
|
||||
<Tabs.Tab
|
||||
value="tasks"
|
||||
rightSection={tasks.length > 0 ? <Text span size="xs" c="dimmed">{tasks.length}</Text> : null}
|
||||
>
|
||||
Задачи
|
||||
</Tabs.Tab>
|
||||
<Tabs.Tab
|
||||
value="comments"
|
||||
rightSection={comments.length > 0 ? <Text span size="xs" c="dimmed">{comments.length}</Text> : null}
|
||||
>
|
||||
Комментарии
|
||||
</Tabs.Tab>
|
||||
</Tabs.List>
|
||||
|
||||
{/* ——— Обзор ——— */}
|
||||
<Tabs.Panel value="overview" className={classes.section}>
|
||||
<Stack gap="xl">
|
||||
<InfoList>
|
||||
<InfoRow label="Категория">
|
||||
<Text size="sm">{category?.name || '—'}</Text>
|
||||
</InfoRow>
|
||||
<InfoRow label="Тема">
|
||||
<Text size="sm">{approval.topic?.name || '—'}</Text>
|
||||
</InfoRow>
|
||||
{approval.topic?.approval_mode && (
|
||||
<InfoRow label="Режим согласования">
|
||||
<Text size="sm">
|
||||
{MODE_LABELS[approval.topic.approval_mode] || approval.topic.approval_mode}
|
||||
</Text>
|
||||
</InfoRow>
|
||||
)}
|
||||
<InfoRow label="Инициатор">
|
||||
<Text size="sm">{approval.initiator?.full_name || '—'}</Text>
|
||||
</InfoRow>
|
||||
<InfoRow label="Отдел">
|
||||
<Text size="sm">{approval.department?.name || '—'}</Text>
|
||||
</InfoRow>
|
||||
<InfoRow label="Создана (МСК)">
|
||||
<Text size="sm">{formatMsk(approval.created_at)}</Text>
|
||||
</InfoRow>
|
||||
</InfoList>
|
||||
|
||||
{approval.content && (
|
||||
<Section title="Текст заявки">
|
||||
<Text size="sm" style={{ whiteSpace: 'pre-wrap' }}>{approval.content}</Text>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{files.length > 0 && (
|
||||
<Section title="Файлы" count={files.length}>
|
||||
<Stack gap={0}>
|
||||
{files.map((file, i) => {
|
||||
const name = file.file_name || 'Без имени'
|
||||
const mime = getMimeType(name)
|
||||
const kb = file.file_base64
|
||||
? Math.round((file.file_base64.length * 3) / 4 / 1024)
|
||||
: 0
|
||||
return (
|
||||
<Box key={file.id}>
|
||||
{i > 0 && <Divider />}
|
||||
<Group justify="space-between" wrap="nowrap" py={8}>
|
||||
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
<ThemeIcon variant="light" color="gray" size={32} radius="md">
|
||||
<IconFileText size={16} stroke={1.6} />
|
||||
</ThemeIcon>
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text size="sm" fw={500} truncate>{name}</Text>
|
||||
{kb > 0 && <Text size="xs" c="dimmed">{formatFileSize(kb)}</Text>}
|
||||
</Box>
|
||||
</Group>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
{isPreviewable(mime) && (
|
||||
<Tooltip label="Предпросмотр">
|
||||
<ActionIcon
|
||||
aria-label="Предпросмотр"
|
||||
onClick={() => setPreview({ id: file.id!, name, type: mime })}
|
||||
>
|
||||
<IconEye size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip label="Скачать">
|
||||
<ActionIcon
|
||||
aria-label="Скачать"
|
||||
onClick={() => handleDownload(file.id!, name)}
|
||||
>
|
||||
<IconDownload size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Group>
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
</Stack>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{prettyMetadata && (
|
||||
<Section title="Метаданные">
|
||||
<Spoiler maxHeight={96} showLabel="Показать полностью" hideLabel="Свернуть">
|
||||
<Code block>{prettyMetadata}</Code>
|
||||
</Spoiler>
|
||||
</Section>
|
||||
)}
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
|
||||
{/* ——— Согласование ——— */}
|
||||
<Tabs.Panel value="flow" className={classes.section}>
|
||||
<Stack gap="xl">
|
||||
{steps.length === 0 ? (
|
||||
<Text size="sm" c="dimmed">Шаги согласования не заданы</Text>
|
||||
) : (
|
||||
<Section title="Шаги">
|
||||
<Timeline active={steps.length} bulletSize={24} lineWidth={2}>
|
||||
{steps.map((step, index) => {
|
||||
const StepIcon = STEP_ICONS[step.status || ''] || IconClock
|
||||
const color = STEP_STATUS[step.status || '']?.color ?? 'gray'
|
||||
return (
|
||||
<Timeline.Item
|
||||
key={step.id}
|
||||
color={color}
|
||||
bullet={<StepIcon size={13} />}
|
||||
title={
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Text size="sm" fw={500}>
|
||||
{step.approver_name_snapshot || 'Согласующий'}
|
||||
</Text>
|
||||
<StatusBadge kind="step" status={step.status || ''} size="sm" />
|
||||
</Group>
|
||||
}
|
||||
>
|
||||
<Text size="xs" c="dimmed">
|
||||
Шаг {index + 1}
|
||||
{step.approver?.full_name && ` · ${step.approver.full_name}`}
|
||||
{step.acted_at && ` · ${formatMsk(step.acted_at)}`}
|
||||
</Text>
|
||||
{step.comment && (
|
||||
<Text size="sm" mt={4}>{step.comment}</Text>
|
||||
)}
|
||||
</Timeline.Item>
|
||||
)
|
||||
})}
|
||||
</Timeline>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{additionalApprovers.length > 0 && (
|
||||
<Section title="Дополнительные согласующие" count={additionalApprovers.length}>
|
||||
<Stack gap={8}>
|
||||
{additionalApprovers.map((aa) => (
|
||||
<Group key={aa.id} justify="space-between" wrap="nowrap">
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text size="sm" truncate>{aa.approver_name}</Text>
|
||||
{aa.acted_at && (
|
||||
<Text size="xs" c="dimmed">{formatMsk(aa.acted_at)}</Text>
|
||||
)}
|
||||
</Box>
|
||||
<StatusBadge kind="decision" status={aa.status} size="sm" />
|
||||
</Group>
|
||||
))}
|
||||
</Stack>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{observers.length > 0 && (
|
||||
<Section title="Наблюдатели" count={observers.length}>
|
||||
<Group gap={6}>
|
||||
{observers.map((o) => (
|
||||
<Group key={o.id} gap={6} wrap="nowrap">
|
||||
<Avatar size={22} radius="xl" color="initials" name={o.full_name} />
|
||||
<Text size="sm">{o.full_name}</Text>
|
||||
</Group>
|
||||
))}
|
||||
</Group>
|
||||
</Section>
|
||||
)}
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
|
||||
{/* ——— Задачи ——— */}
|
||||
<Tabs.Panel value="tasks" className={classes.section}>
|
||||
{showPlannedTasks ? (
|
||||
<Section title="Будут поставлены после согласования">
|
||||
<Stack gap="sm">
|
||||
{[...plannedTasks]
|
||||
.sort((a, b) => a.step_order - b.step_order)
|
||||
.map((te) => (
|
||||
<Group key={te.id} justify="space-between" wrap="nowrap" align="flex-start">
|
||||
<Text size="sm" style={{ flex: 1 }}>{te.task_text || '—'}</Text>
|
||||
<Text size="xs" c="dimmed" ta="right">
|
||||
{te.executor_name || 'Исполнитель не назначен'}
|
||||
</Text>
|
||||
</Group>
|
||||
))}
|
||||
<Text size="xs" c="dimmed">
|
||||
Появятся автоматически, когда заявку согласуют полностью.
|
||||
</Text>
|
||||
</Stack>
|
||||
</Section>
|
||||
) : tasks.length === 0 ? (
|
||||
<Text size="sm" c="dimmed">Задач по заявке нет</Text>
|
||||
) : (
|
||||
<Stack gap="md">
|
||||
{tasks.map((task, i) => (
|
||||
<Box key={task.id}>
|
||||
{i > 0 && <Divider mb="md" />}
|
||||
<Group justify="space-between" wrap="nowrap" mb={4}>
|
||||
<Text size="sm" fw={500}>Задача №{i + 1}</Text>
|
||||
<StatusBadge kind="task" status={task.status} size="sm" />
|
||||
</Group>
|
||||
<Text size="sm">{task.task_text || '—'}</Text>
|
||||
<Text size="xs" c="dimmed" mt={4}>
|
||||
{task.executor_name || 'Исполнитель не назначен'}
|
||||
{task.completed_at && ` · выполнена ${formatMsk(task.completed_at)}`}
|
||||
</Text>
|
||||
</Box>
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
</Tabs.Panel>
|
||||
|
||||
{/* ——— Комментарии ——— */}
|
||||
<Tabs.Panel value="comments" className={classes.section}>
|
||||
{comments.length === 0 ? (
|
||||
<Text size="sm" c="dimmed">Комментариев нет</Text>
|
||||
) : (
|
||||
<Stack gap="lg">
|
||||
{comments.map((c) => (
|
||||
<Group key={c.id} gap="sm" align="flex-start" wrap="nowrap">
|
||||
<Avatar size={28} radius="xl" color="initials" name={c.user_name} />
|
||||
<Box style={{ minWidth: 0, flex: 1 }}>
|
||||
<Group gap={8}>
|
||||
<Text size="sm" fw={500}>{c.user_name}</Text>
|
||||
{c.created_at && (
|
||||
<Text size="xs" c="dimmed">{formatMsk(c.created_at)}</Text>
|
||||
)}
|
||||
</Group>
|
||||
<Text size="sm" style={{ whiteSpace: 'pre-wrap' }}>{c.comment}</Text>
|
||||
</Box>
|
||||
</Group>
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
</Tabs.Panel>
|
||||
</Tabs>
|
||||
</>
|
||||
)}
|
||||
</Drawer.Body>
|
||||
</Drawer.Content>
|
||||
</Drawer.Root>
|
||||
|
||||
{preview && approvalId && (
|
||||
<FilePreviewModal
|
||||
approvalId={approvalId}
|
||||
fileId={preview.id}
|
||||
fileName={preview.name}
|
||||
fileType={preview.type}
|
||||
opened
|
||||
onClose={() => setPreview(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,456 +0,0 @@
|
|||
import { useState } from 'react'
|
||||
import {
|
||||
Modal,
|
||||
Stack,
|
||||
Text,
|
||||
Group,
|
||||
Badge,
|
||||
Paper,
|
||||
Loader,
|
||||
Center,
|
||||
Timeline,
|
||||
ScrollArea,
|
||||
Box,
|
||||
ActionIcon, Tooltip,
|
||||
} from '@mantine/core'
|
||||
import {
|
||||
IconUser,
|
||||
IconBuilding,
|
||||
IconCalendar,
|
||||
IconFileText,
|
||||
IconCheck,
|
||||
IconX,
|
||||
IconClock,
|
||||
IconAlertCircle,
|
||||
IconEye,
|
||||
IconDownload,
|
||||
} from '@tabler/icons-react'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import { useApproval } from '@/features/approvals/hooks/useApprovals'
|
||||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
||||
import FilePreviewModal from './FilePreviewModal'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/ru'
|
||||
|
||||
dayjs.locale('ru')
|
||||
|
||||
interface ApprovalDetailsModalProps {
|
||||
approvalId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
draft: 'gray',
|
||||
pending: 'blue',
|
||||
approved: 'green',
|
||||
rejected: 'red',
|
||||
revoked: 'orange',
|
||||
revision: 'violet',
|
||||
}
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
pending: 'На согласовании',
|
||||
approved: 'Согласована',
|
||||
rejected: 'Отклонена',
|
||||
revoked: 'Отозвана',
|
||||
revision: 'На доработке',
|
||||
}
|
||||
|
||||
const STEP_STATUS_ICONS: Record<string, any> = {
|
||||
pending: IconClock,
|
||||
approved: IconCheck,
|
||||
rejected: IconX,
|
||||
waiting: IconClock,
|
||||
cancelled_any_of: IconAlertCircle,
|
||||
}
|
||||
|
||||
const STEP_STATUS_COLORS: Record<string, string> = {
|
||||
pending: 'blue',
|
||||
approved: 'green',
|
||||
rejected: 'red',
|
||||
waiting: 'gray',
|
||||
cancelled_any_of: 'orange',
|
||||
}
|
||||
|
||||
// 🆕 Типы файлов, для которых доступен предпросмотр
|
||||
const PREVIEWABLE_TYPES = [
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/gif',
|
||||
'image/webp',
|
||||
'image/svg+xml',
|
||||
'application/pdf',
|
||||
'text/plain',
|
||||
]
|
||||
|
||||
// 🆕 Определение MIME типа по расширению
|
||||
const getMimeType = (fileName: string): string => {
|
||||
const ext = fileName.split('.').pop()?.toLowerCase() || ''
|
||||
const mimeTypes: Record<string, string> = {
|
||||
'jpg': 'image/jpeg',
|
||||
'jpeg': 'image/jpeg',
|
||||
'png': 'image/png',
|
||||
'gif': 'image/gif',
|
||||
'webp': 'image/webp',
|
||||
'svg': 'image/svg+xml',
|
||||
'pdf': 'application/pdf',
|
||||
'txt': 'text/plain',
|
||||
'doc': 'application/msword',
|
||||
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'xls': 'application/vnd.ms-excel',
|
||||
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
}
|
||||
return mimeTypes[ext] || 'application/octet-stream'
|
||||
}
|
||||
|
||||
// 🆕 Генерация HMAC подписи (вынесена в отдельную функцию)
|
||||
const generateSignature = async (): Promise<{ signature: string; timestamp: string; deviceId: string }> => {
|
||||
const timestamp = Math.floor(Date.now() / 1000).toString()
|
||||
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
||||
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
|
||||
const message = publicKey + ':' + timestamp
|
||||
const CryptoJS = await import('crypto-js')
|
||||
const signature = CryptoJS.HmacSHA256(message, privateKey).toString(CryptoJS.enc.Hex)
|
||||
const deviceId = localStorage.getItem('device_id') || 'admin-panel'
|
||||
return { signature, timestamp, deviceId }
|
||||
}
|
||||
|
||||
// 🆕 Получение заголовков авторизации
|
||||
const getAuthHeaders = async () => {
|
||||
const token = localStorage.getItem('token')
|
||||
const { signature, timestamp, deviceId } = await generateSignature()
|
||||
return {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'ApiKey': signature,
|
||||
'X-Timestamp': timestamp,
|
||||
'x-device-id': deviceId,
|
||||
}
|
||||
}
|
||||
|
||||
export default function ApprovalDetailsModal({
|
||||
approvalId,
|
||||
opened,
|
||||
onClose,
|
||||
}: ApprovalDetailsModalProps) {
|
||||
const { data: approval, isLoading } = useApproval(approvalId)
|
||||
const { data: categories } = useCategories({ limit: 1000 })
|
||||
|
||||
// 🆕 Состояние для предпросмотра файла
|
||||
const [previewFileId, setPreviewFileId] = useState<number | null>(null)
|
||||
const [previewFileName, setPreviewFileName] = useState('')
|
||||
const [previewFileType, setPreviewFileType] = useState('')
|
||||
|
||||
const category = approval?.topic?.category_id && categories?.data
|
||||
? categories.data.find((c) => c.id === approval.topic?.category_id)
|
||||
: null
|
||||
|
||||
// 🆕 Открытие предпросмотра
|
||||
const handleFilePreview = (fileId: number, fileName: string) => {
|
||||
setPreviewFileId(fileId)
|
||||
setPreviewFileName(fileName)
|
||||
setPreviewFileType(getMimeType(fileName))
|
||||
}
|
||||
|
||||
// 🆕 Скачивание файла
|
||||
const handleFileDownload = async (fileId: number, fileName: string) => {
|
||||
try {
|
||||
const headers = await getAuthHeaders()
|
||||
const url = `/api/approvals/${approvalId}/files/${fileId}/download`
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to download file')
|
||||
}
|
||||
|
||||
const blob = await response.blob()
|
||||
const blobUrl = window.URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = blobUrl
|
||||
link.download = fileName
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
window.URL.revokeObjectURL(blobUrl)
|
||||
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Файл скачан',
|
||||
color: 'green',
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Download error:', error)
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: 'Не удалось скачать файл',
|
||||
color: 'red',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={
|
||||
<Group>
|
||||
<Text fw={700}>Заявка #{approvalId}</Text>
|
||||
{approval && (
|
||||
<Badge color={STATUS_COLORS[approval.status || ''] || 'gray'}>
|
||||
{STATUS_LABELS[approval.status || ''] || approval.status}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
}
|
||||
size="xl"
|
||||
styles={{
|
||||
body: {
|
||||
height: 'calc(80vh - 120px)',
|
||||
padding: 0,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Center p={40}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : approval ? (
|
||||
<ScrollArea
|
||||
style={{ height: 'calc(80vh - 120px)' }}
|
||||
offsetScrollbars
|
||||
>
|
||||
<Box p="md">
|
||||
<Stack gap="md">
|
||||
{/* Основная информация */}
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" c="dimmed" mb="xs">Основная информация</Text>
|
||||
<Stack gap="sm">
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Категория:</Text>
|
||||
<Text fw={500}>{category?.name || '—'}</Text>
|
||||
</Group>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Тема:</Text>
|
||||
<Text>{approval.topic?.name || '—'}</Text>
|
||||
</Group>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Инициатор:</Text>
|
||||
<Group gap="xs">
|
||||
<IconUser size={16} />
|
||||
<Text>{approval.initiator?.full_name || '—'}</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Отдел:</Text>
|
||||
<Group gap="xs">
|
||||
<IconBuilding size={16} />
|
||||
<Text>{approval.department?.name || '—'}</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">Дата создания:</Text>
|
||||
<Group gap="xs">
|
||||
<IconCalendar size={16} />
|
||||
<Text>
|
||||
{approval.created_at
|
||||
? dayjs(approval.created_at).format('DD.MM.YYYY HH:mm')
|
||||
: '—'}
|
||||
</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* Текст заявки */}
|
||||
{approval.content && (
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" c="dimmed" mb="xs">Текст заявки</Text>
|
||||
<Text>{approval.content}</Text>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Метаданные */}
|
||||
{approval.metadata && (
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" c="dimmed" mb="xs">Метаданные</Text>
|
||||
<Text size="sm" style={{ fontFamily: 'monospace', whiteSpace: 'pre-wrap' }}>
|
||||
{(() => {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(approval.metadata), null, 2)
|
||||
} catch {
|
||||
return approval.metadata
|
||||
}
|
||||
})()}
|
||||
</Text>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* 🆕 Файлы */}
|
||||
{approval.files && approval.files.length > 0 && (
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" c="dimmed" mb="xs">Прикреплённые файлы</Text>
|
||||
<Stack gap="xs">
|
||||
{approval.files.map((file) => {
|
||||
const mimeType = getMimeType(file.file_name || '')
|
||||
const canPreview = PREVIEWABLE_TYPES.includes(mimeType)
|
||||
const fileSizeKB = file.file_base64
|
||||
? Math.round((file.file_base64.length * 3 / 4) / 1024)
|
||||
: 0
|
||||
|
||||
return (
|
||||
<Paper key={file.id} withBorder p="sm">
|
||||
<Group justify="space-between">
|
||||
<Group gap="sm">
|
||||
<IconFileText size={20} color="blue" />
|
||||
<Stack gap={0}>
|
||||
<Text size="sm" fw={500}>
|
||||
{file.file_name || 'Без имени'}
|
||||
</Text>
|
||||
{fileSizeKB > 0 && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{fileSizeKB} KB
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</Group>
|
||||
<Group gap="xs">
|
||||
{canPreview && (
|
||||
<Tooltip label="Предпросмотр">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="blue"
|
||||
onClick={() => handleFilePreview(file.id!, file.file_name || '')}
|
||||
>
|
||||
<IconEye size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip label="Скачать">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="green"
|
||||
onClick={() => handleFileDownload(file.id!, file.file_name || '')}
|
||||
>
|
||||
<IconDownload size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Group>
|
||||
</Paper>
|
||||
)
|
||||
})}
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Шаги согласования */}
|
||||
{approval.steps && approval.steps.length > 0 && (
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" c="dimmed" mb="xs">Шаги согласования</Text>
|
||||
<Timeline active={-1} bulletSize={24} lineWidth={2}>
|
||||
{approval.steps
|
||||
.sort((a, b) => (a.step_order || 0) - (b.step_order || 0))
|
||||
.map((step, index) => {
|
||||
const StatusIcon = STEP_STATUS_ICONS[step.status || ''] || IconClock
|
||||
return (
|
||||
<Timeline.Item
|
||||
key={step.id}
|
||||
bullet={<StatusIcon size={14} />}
|
||||
title={
|
||||
<Group gap="xs">
|
||||
<Text size="sm" fw={500}>
|
||||
Шаг {index + 1}: {step.approver_name_snapshot || 'Согласующий'}
|
||||
</Text>
|
||||
<Badge
|
||||
size="xs"
|
||||
color={STEP_STATUS_COLORS[step.status || ''] || 'gray'}
|
||||
>
|
||||
{step.status}
|
||||
</Badge>
|
||||
</Group>
|
||||
}
|
||||
>
|
||||
<Text size="xs" c="dimmed">
|
||||
{step.approver?.full_name || '—'}
|
||||
{step.acted_at && (
|
||||
<>
|
||||
{' • '}
|
||||
{dayjs(step.acted_at).format('DD.MM.YYYY HH:mm')}
|
||||
</>
|
||||
)}
|
||||
</Text>
|
||||
{step.comment && (
|
||||
<Text size="xs" mt={4}>
|
||||
Комментарий: {step.comment}
|
||||
</Text>
|
||||
)}
|
||||
</Timeline.Item>
|
||||
)
|
||||
})}
|
||||
</Timeline>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Информация об отзыве */}
|
||||
{approval.status === 'revoked' && approval.revoked_by && (
|
||||
<Paper withBorder p="md" bg="orange.0">
|
||||
<Text size="sm" c="dimmed" mb="xs">Информация об отзыве</Text>
|
||||
<Group gap="sm">
|
||||
<IconAlertCircle size={16} />
|
||||
<Text size="sm">
|
||||
Отозвана: {approval.revoked_by.full_name}
|
||||
{approval.revoked_at && (
|
||||
<> {dayjs(approval.revoked_at).format('DD.MM.YYYY HH:mm')}</>
|
||||
)}
|
||||
</Text>
|
||||
</Group>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Информация о доработке */}
|
||||
{approval.status === 'revision' && (
|
||||
<Paper withBorder p="md" bg="violet.0">
|
||||
<Text size="sm" c="dimmed" mb="xs">Информация о доработке</Text>
|
||||
<Stack gap="xs">
|
||||
{approval.revision_comment && (
|
||||
<Text size="sm">
|
||||
<Text fw={500} component="span">Комментарий:</Text> {approval.revision_comment}
|
||||
</Text>
|
||||
)}
|
||||
{approval.revision_count !== undefined && approval.revision_count > 0 && (
|
||||
<Text size="sm">
|
||||
<Text fw={500} component="span">Количество доработок:</Text> {approval.revision_count}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
</Stack>
|
||||
</Box>
|
||||
</ScrollArea>
|
||||
) : (
|
||||
<Center p={40}>
|
||||
<Text c="dimmed">Заявка не найдена</Text>
|
||||
</Center>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{/* 🆕 Модальное окно предпросмотра файла */}
|
||||
{previewFileId && approvalId && (
|
||||
<FilePreviewModal
|
||||
approvalId={approvalId}
|
||||
fileId={previewFileId}
|
||||
fileName={previewFileName}
|
||||
fileType={previewFileType}
|
||||
opened={!!previewFileId}
|
||||
onClose={() => setPreviewFileId(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,184 +1,103 @@
|
|||
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 { useEffect, useState } from 'react'
|
||||
import { Box, Button, Center, Group, Loader, Modal, Stack, Text } from '@mantine/core'
|
||||
import { useMediaQuery } from '@mantine/hooks'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import { IconDownload } from '@tabler/icons-react'
|
||||
import {
|
||||
approvalFileUrl,
|
||||
fetchFileBlob,
|
||||
isPreviewable,
|
||||
saveFile,
|
||||
taskFileUrl,
|
||||
} from '@/lib/fileApi'
|
||||
|
||||
interface FilePreviewModalProps {
|
||||
approvalId?: number // Теперь опционально
|
||||
interface Props {
|
||||
fileId: number
|
||||
fileName: string
|
||||
fileType: string
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
taskId?: number // 🆕 Для файлов задач
|
||||
approvalId?: number
|
||||
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,
|
||||
}
|
||||
}
|
||||
type LoadState = { status: 'loading' } | { status: 'error' } | { status: 'ready'; url: string }
|
||||
|
||||
export default function FilePreviewModal({
|
||||
approvalId,
|
||||
taskId,
|
||||
fileId,
|
||||
fileName,
|
||||
fileType,
|
||||
opened,
|
||||
onClose,
|
||||
taskId, // 🆕
|
||||
}: FilePreviewModalProps) {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [fileUrl, setFileUrl] = useState<string | null>(null)
|
||||
}: Props) {
|
||||
const isMobile = useMediaQuery('(max-width: 48em)')
|
||||
const [state, setState] = useState<LoadState>({ status: 'loading' })
|
||||
|
||||
// 🆕 Определяем тип сущности
|
||||
const entityType: EntityType = taskId ? 'task' : 'approval'
|
||||
const entityId = taskId || approvalId
|
||||
const previewUrl = taskId
|
||||
? taskFileUrl(taskId, fileId)
|
||||
: approvalId
|
||||
? approvalFileUrl(approvalId, fileId)
|
||||
: null
|
||||
const downloadUrl = taskId
|
||||
? taskFileUrl(taskId, fileId, true)
|
||||
: approvalId
|
||||
? approvalFileUrl(approvalId, fileId, true)
|
||||
: null
|
||||
|
||||
// 🆕 Формируем 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)
|
||||
const canPreview = isPreviewable(fileType)
|
||||
|
||||
useEffect(() => {
|
||||
if (!opened || !canPreview || !entityId) return
|
||||
if (!opened || !canPreview || !previewUrl) return
|
||||
|
||||
let cancelled = false
|
||||
let objectUrl: string | null = null
|
||||
// Сбрасываем состояние, чтобы при открытии другого файла не мелькал предыдущий
|
||||
setState({ status: 'loading' })
|
||||
|
||||
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()
|
||||
fetchFileBlob(previewUrl)
|
||||
.then((blob) => {
|
||||
if (cancelled) return
|
||||
objectUrl = window.URL.createObjectURL(blob)
|
||||
setFileUrl(objectUrl)
|
||||
} catch (err) {
|
||||
setState({ status: 'ready', url: objectUrl })
|
||||
})
|
||||
.catch((err) => {
|
||||
if (cancelled) return
|
||||
console.error('File load error:', err)
|
||||
setError('Не удалось загрузить файл')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
loadFile()
|
||||
setState({ status: 'error' })
|
||||
})
|
||||
|
||||
return () => {
|
||||
if (objectUrl) {
|
||||
window.URL.revokeObjectURL(objectUrl)
|
||||
cancelled = true
|
||||
if (objectUrl) window.URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
}
|
||||
}, [opened, entityId, fileId, canPreview])
|
||||
}, [opened, previewUrl, canPreview])
|
||||
|
||||
const handleDownload = async () => {
|
||||
if (!downloadUrl) return
|
||||
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',
|
||||
})
|
||||
await saveFile(downloadUrl, fileName)
|
||||
notifications.show({ title: 'Готово', message: 'Файл скачан', color: 'green' })
|
||||
} catch (err) {
|
||||
console.error('Download error:', err)
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: 'Не удалось скачать файл',
|
||||
color: 'red',
|
||||
})
|
||||
notifications.show({ title: 'Ошибка', message: 'Не удалось скачать файл', color: 'red' })
|
||||
}
|
||||
}
|
||||
|
||||
if (!canPreview) {
|
||||
return (
|
||||
<Modal opened={opened} onClose={onClose} title="Предпросмотр недоступен" size="md">
|
||||
<Paper p="md" withBorder>
|
||||
<Modal opened={opened} onClose={onClose} title="Предпросмотр недоступен" size="sm" zIndex={400}>
|
||||
<Stack gap="md">
|
||||
<Text>
|
||||
Предпросмотр этого типа файла не поддерживается.
|
||||
<br />
|
||||
Вы можете скачать файл.
|
||||
<Text size="sm" c="dimmed">
|
||||
Этот тип файла нельзя открыть в браузере. Его можно скачать.
|
||||
</Text>
|
||||
<Group justify="flex-end">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="blue"
|
||||
size="lg"
|
||||
onClick={handleDownload}
|
||||
>
|
||||
<IconDownload size={20} />
|
||||
</ActionIcon>
|
||||
<Button leftSection={<IconDownload size={16} />} onClick={handleDownload}>
|
||||
Скачать
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
|
@ -187,80 +106,59 @@ export default function FilePreviewModal({
|
|||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
size="xl"
|
||||
zIndex={400}
|
||||
fullScreen={isMobile}
|
||||
title={
|
||||
<Group justify="space-between" style={{ flex: 1 }}>
|
||||
<Group justify="space-between" wrap="nowrap" gap="md" style={{ flex: 1 }}>
|
||||
<Text fw={600} lineClamp={1}>{fileName}</Text>
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="blue"
|
||||
<Button
|
||||
size="compact-sm"
|
||||
variant="default"
|
||||
leftSection={<IconDownload size={14} />}
|
||||
onClick={handleDownload}
|
||||
>
|
||||
<IconDownload size={20} />
|
||||
</ActionIcon>
|
||||
Скачать
|
||||
</Button>
|
||||
</Group>
|
||||
}
|
||||
size="xl"
|
||||
styles={{
|
||||
body: {
|
||||
height: 'calc(80vh - 120px)',
|
||||
padding: 0,
|
||||
},
|
||||
title: { flex: 1, minWidth: 0 },
|
||||
body: { padding: 0, height: isMobile ? 'calc(100dvh - 70px)' : '75dvh' },
|
||||
}}
|
||||
>
|
||||
<Box style={{ height: '100%', width: '100%', position: 'relative' }}>
|
||||
{loading && (
|
||||
<Center style={{ position: 'absolute', inset: 0, zIndex: 1 }}>
|
||||
<Box style={{ height: '100%', position: 'relative' }}>
|
||||
{state.status === 'loading' && (
|
||||
<Center h="100%">
|
||||
<Stack align="center" gap="xs">
|
||||
<Loader size="lg" />
|
||||
<Text size="sm" c="dimmed">Загрузка файла...</Text>
|
||||
<Loader size="sm" />
|
||||
<Text size="sm" c="dimmed">Загрузка файла…</Text>
|
||||
</Stack>
|
||||
</Center>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
{state.status === 'error' && (
|
||||
<Center h="100%">
|
||||
<Text c="red">{error}</Text>
|
||||
<Text size="sm" c="red">Не удалось загрузить файл</Text>
|
||||
</Center>
|
||||
)}
|
||||
|
||||
{fileUrl && !error && (
|
||||
<>
|
||||
{fileType.startsWith('image/') ? (
|
||||
<Center style={{ height: '100%', background: '#f5f5f5' }}>
|
||||
{state.status === 'ready' &&
|
||||
(fileType.startsWith('image/') ? (
|
||||
<Center h="100%" style={{ background: 'var(--mantine-color-default-hover)' }}>
|
||||
<img
|
||||
src={fileUrl}
|
||||
src={state.url}
|
||||
alt={fileName}
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: '100%',
|
||||
objectFit: 'contain',
|
||||
}}
|
||||
style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }}
|
||||
/>
|
||||
</Center>
|
||||
) : fileType === 'application/pdf' ? (
|
||||
) : (
|
||||
<iframe
|
||||
src={fileUrl}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
border: 'none',
|
||||
}}
|
||||
src={state.url}
|
||||
title={fileName}
|
||||
style={{ width: '100%', height: '100%', border: 'none', background: '#fff' }}
|
||||
/>
|
||||
) : fileType === 'text/plain' ? (
|
||||
<iframe
|
||||
src={fileUrl}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
border: 'none',
|
||||
background: 'white',
|
||||
}}
|
||||
title={fileName}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
))}
|
||||
</Box>
|
||||
</Modal>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,230 +1,204 @@
|
|||
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 { useEffect, useMemo, useState } from 'react'
|
||||
import { ActionIcon, Badge, Button, Group, Select, Stack, Text, TextInput, Tooltip } from '@mantine/core'
|
||||
import { useDebouncedValue } from '@mantine/hooks'
|
||||
import { IconPencil, IconPlus, IconSearch, IconTrash } from '@tabler/icons-react'
|
||||
|
||||
import { useCategories, useDeleteCategory } from '@/features/categories/hooks/useCategories'
|
||||
import CategoryEditModal from './components/CategoryEditModal'
|
||||
|
||||
import { ApprovalTopicCategory } from '@/types/api'
|
||||
import { PageHeader } from '@/components/ui/PageHeader'
|
||||
import { FilterBar } from '@/components/ui/FilterBar'
|
||||
import { DataTable, type Column } from '@/components/ui/DataTable'
|
||||
import { ConfirmModal } from '@/components/ui/ConfirmModal'
|
||||
import CategoryDrawer from './components/CategoryDrawer'
|
||||
|
||||
const LIMIT = 20
|
||||
|
||||
interface Filters {
|
||||
search: string
|
||||
isActive: string | null
|
||||
}
|
||||
|
||||
const EMPTY_FILTERS: Filters = {
|
||||
search: '',
|
||||
isActive: null,
|
||||
}
|
||||
|
||||
export default function CategoriesPage() {
|
||||
const [page, setPage] = useState(1)
|
||||
const [search, setSearch] = useState('')
|
||||
const [activeFilter, setActiveFilter] = useState<boolean | null>(null)
|
||||
const [editCategoryId, setEditCategoryId] = useState<number | null>(null)
|
||||
const [createModalOpened, setCreateModalOpened] = useState(false)
|
||||
const [filters, setFilters] = useState<Filters>(EMPTY_FILTERS)
|
||||
const [searchInput, setSearchInput] = useState('')
|
||||
const [debouncedSearch] = useDebouncedValue(searchInput.trim(), 400)
|
||||
|
||||
const { data, isLoading, isFetching } = useCategories({
|
||||
offset: (page - 1) * LIMIT,
|
||||
limit: LIMIT,
|
||||
...(search && { name: search }),
|
||||
...(activeFilter !== null && { is_active: activeFilter }),
|
||||
})
|
||||
const [drawerId, setDrawerId] = useState<number | 'new' | null>(null)
|
||||
const [deleteTarget, setDeleteTarget] = useState<ApprovalTopicCategory | null>(null)
|
||||
|
||||
const deleteCategory = useDeleteCategory()
|
||||
|
||||
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
||||
// Сброс страницы при поиске
|
||||
useEffect(() => setPage(1), [debouncedSearch])
|
||||
|
||||
const handleDelete = (id: number) => {
|
||||
modals.openConfirmModal({
|
||||
title: 'Подтвердите удаление',
|
||||
children: (
|
||||
<Text size="sm">
|
||||
Вы уверены, что хотите удалить эту категорию? Все темы этой категории останутся без категории.
|
||||
</Text>
|
||||
),
|
||||
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
||||
confirmProps: { color: 'red' },
|
||||
onConfirm: () => deleteCategory.mutate(id),
|
||||
})
|
||||
const updateFilter = (patch: Partial<Filters>) => {
|
||||
setFilters((prev) => ({ ...prev, ...patch }))
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between">
|
||||
<Text size="xl" fw={700}>Категории тем</Text>
|
||||
<Group>
|
||||
<Text c="dimmed" size="sm">
|
||||
Всего: {data?.total_count || 0}
|
||||
</Text>
|
||||
<Button
|
||||
leftSection={<IconPlus size={16} />}
|
||||
onClick={() => setCreateModalOpened(true)}
|
||||
>
|
||||
Создать категорию
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
const requestParams = useMemo(() => {
|
||||
const params: Record<string, any> = { offset: (page - 1) * LIMIT, limit: LIMIT }
|
||||
if (debouncedSearch.length >= 2) params.name = debouncedSearch
|
||||
if (filters.isActive !== null) params.is_active = filters.isActive === 'true'
|
||||
return params
|
||||
}, [page, filters, debouncedSearch])
|
||||
|
||||
{/* Фильтры */}
|
||||
<Paper withBorder p="md">
|
||||
<Group gap="md" align="flex-end">
|
||||
<TextInput
|
||||
label="Поиск по названию"
|
||||
placeholder="Отпуска, больничные..."
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.currentTarget.value)
|
||||
const { data, isLoading, isFetching } = useCategories(requestParams)
|
||||
const total = data?.total_count ?? 0
|
||||
|
||||
const activeCount = [
|
||||
debouncedSearch.length >= 2,
|
||||
filters.isActive !== null,
|
||||
].filter(Boolean).length
|
||||
|
||||
const handleReset = () => {
|
||||
setSearchInput('')
|
||||
setFilters(EMPTY_FILTERS)
|
||||
setPage(1)
|
||||
}}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
}
|
||||
|
||||
<Switch
|
||||
label="Только активные"
|
||||
checked={activeFilter === true}
|
||||
onChange={(e) => {
|
||||
setActiveFilter(e.currentTarget.checked ? true : null)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
</Paper>
|
||||
const handleDelete = async () => {
|
||||
if (!deleteTarget?.id) return
|
||||
await deleteCategory.mutateAsync(deleteTarget.id)
|
||||
setDeleteTarget(null)
|
||||
}
|
||||
|
||||
{/* Таблица */}
|
||||
<Paper withBorder>
|
||||
{isLoading ? (
|
||||
<Center p={60}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : (
|
||||
<>
|
||||
<Table striped highlightOnHover>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
||||
<Table.Th>Название</Table.Th>
|
||||
<Table.Th>Код</Table.Th>
|
||||
<Table.Th>Описание</Table.Th>
|
||||
<Table.Th style={{ width: 100 }}>Статус</Table.Th>
|
||||
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{data?.data?.length === 0 ? (
|
||||
<Table.Tr>
|
||||
<Table.Td colSpan={6}>
|
||||
<Center p={40}>
|
||||
<Text c="dimmed">Категории не найдены</Text>
|
||||
</Center>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
) : (
|
||||
(data?.data || []).map((category) => (
|
||||
<Table.Tr key={category.id}>
|
||||
<Table.Td>{category.id}</Table.Td>
|
||||
<Table.Td>
|
||||
<Text fw={500}>{category.name}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" ff="monospace" c="dimmed">
|
||||
{category.code}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" lineClamp={2}>
|
||||
{category.description || '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
const columns: Column<ApprovalTopicCategory>[] = [
|
||||
{
|
||||
key: 'id',
|
||||
header: 'ID',
|
||||
width: 80,
|
||||
cell: (r) => <Text size="sm" fw={500}>#{r.id}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'name',
|
||||
header: 'Название',
|
||||
cell: (r) => <Text size="sm" fw={500}>{r.name}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'code',
|
||||
header: 'Код',
|
||||
width: 200,
|
||||
cell: (r) => <Text size="sm" ff="monospace" c="dimmed">{r.code}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'description',
|
||||
header: 'Описание',
|
||||
cell: (r) => <Text size="sm" lineClamp={2} c="dimmed">{r.description || '—'}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Статус',
|
||||
width: 120,
|
||||
cell: (r) => (
|
||||
<Badge
|
||||
color={category.is_active ? 'green' : 'gray'}
|
||||
variant={category.is_active ? 'light' : 'filled'}
|
||||
color={r.is_active ? 'green' : 'gray'}
|
||||
variant={r.is_active ? 'light' : 'filled'}
|
||||
size="sm"
|
||||
>
|
||||
{category.is_active ? 'Активна' : 'Неактивна'}
|
||||
{r.is_active ? 'Активна' : 'Неактивна'}
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Group gap="xs">
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: '',
|
||||
width: 100,
|
||||
align: 'right',
|
||||
cell: (r) => (
|
||||
<Group gap="xs" justify="flex-end" wrap="nowrap">
|
||||
<Tooltip label="Редактировать">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
variant="subtle"
|
||||
color="blue"
|
||||
onClick={() => setEditCategoryId(category.id!)}
|
||||
onClick={(e) => { e.stopPropagation(); setDrawerId(r.id!); }}
|
||||
>
|
||||
<IconPencil size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Удалить">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
variant="subtle"
|
||||
color="red"
|
||||
onClick={() => handleDelete(category.id!)}
|
||||
onClick={(e) => { e.stopPropagation(); setDeleteTarget(r); }}
|
||||
>
|
||||
<IconTrash size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))
|
||||
)}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
{/* Пагинация */}
|
||||
{totalPages > 1 && (
|
||||
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">
|
||||
Страница {page} из {totalPages}
|
||||
</Text>
|
||||
<Pagination
|
||||
value={page}
|
||||
onChange={setPage}
|
||||
total={totalPages}
|
||||
withEdges
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<PageHeader
|
||||
title="Категории тем"
|
||||
description={isLoading ? undefined : `Всего: ${total}`}
|
||||
actions={
|
||||
<Button leftSection={<IconPlus size={16} />} onClick={() => setDrawerId('new')}>
|
||||
Создать категорию
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</Group>
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
{/* Индикатор обновления */}
|
||||
{isFetching && !isLoading && (
|
||||
<Box
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 70,
|
||||
right: 20,
|
||||
zIndex: 1000
|
||||
<FilterBar activeCount={activeCount} onReset={handleReset}>
|
||||
<TextInput
|
||||
placeholder="Поиск по названию"
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.currentTarget.value)}
|
||||
w={280}
|
||||
/>
|
||||
<Select
|
||||
placeholder="Статус"
|
||||
data={[
|
||||
{ value: 'true', label: 'Только активные' },
|
||||
{ value: 'false', label: 'Неактивные' },
|
||||
]}
|
||||
value={filters.isActive}
|
||||
onChange={(isActive) => updateFilter({ isActive })}
|
||||
clearable
|
||||
w={180}
|
||||
/>
|
||||
</FilterBar>
|
||||
|
||||
<DataTable<ApprovalTopicCategory>
|
||||
columns={columns}
|
||||
rows={data?.data ?? []}
|
||||
getRowId={(r) => r.id!}
|
||||
loading={isLoading}
|
||||
refreshing={isFetching}
|
||||
onRowClick={(r) => setDrawerId(r.id!)}
|
||||
empty={{
|
||||
title: 'Категории не найдены',
|
||||
description: activeCount > 0 ? 'Измените параметры фильтрации' : undefined,
|
||||
}}
|
||||
>
|
||||
<Loader size="xs" />
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Модальное окно редактирования */}
|
||||
<CategoryEditModal
|
||||
categoryId={editCategoryId}
|
||||
opened={editCategoryId !== null}
|
||||
onClose={() => setEditCategoryId(null)}
|
||||
pagination={{ page, pageSize: LIMIT, total, onChange: setPage }}
|
||||
/>
|
||||
|
||||
{/* Модальное окно создания */}
|
||||
<CategoryEditModal
|
||||
categoryId={null}
|
||||
opened={createModalOpened}
|
||||
onClose={() => setCreateModalOpened(false)}
|
||||
<CategoryDrawer
|
||||
categoryId={drawerId === 'new' ? null : drawerId}
|
||||
opened={drawerId !== null}
|
||||
onClose={() => setDrawerId(null)}
|
||||
/>
|
||||
|
||||
<ConfirmModal
|
||||
opened={deleteTarget !== null}
|
||||
onClose={() => setDeleteTarget(null)}
|
||||
onConfirm={handleDelete}
|
||||
title="Подтвердите удаление"
|
||||
message="Вы уверены, что хотите удалить эту категорию? Все темы, привязанные к ней, останутся без категории."
|
||||
confirmLabel="Удалить"
|
||||
danger
|
||||
loading={deleteCategory.isPending}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,180 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import { Badge, Box, Button, Drawer, Group, Stack, Switch, Text, Textarea, TextInput, Skeleton } from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
|
||||
import { useCategory, useCreateCategory, useUpdateCategory } from '@/features/categories/hooks/useCategories'
|
||||
import classes from '@/components/UserDrawer.module.css'
|
||||
|
||||
interface Props {
|
||||
categoryId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
function generateSlug(text: string): string {
|
||||
const ru: Record<string, string> = {
|
||||
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh',
|
||||
з: 'z', и: 'i', й: 'y', к: 'k', л: 'l', м: 'm', н: 'n', о: 'o',
|
||||
п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f', х: 'h', ц: 'c',
|
||||
ч: 'ch', ш: 'sh', щ: 'sch', ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
|
||||
}
|
||||
return text
|
||||
.toLowerCase()
|
||||
.split('')
|
||||
.map((char) => ru[char] || char)
|
||||
.join('')
|
||||
.replace(/[^a-z0-9\s_-]/g, '') // оставляем только латиницу, цифры, пробелы и дефисы
|
||||
.trim()
|
||||
.replace(/[\s-]+/g, '_') // заменяем пробелы и дефисы на нижнее подчеркивание
|
||||
}
|
||||
|
||||
export default function CategoryDrawer({ categoryId, opened, onClose }: Props) {
|
||||
const { data: category, isLoading: categoryLoading } = useCategory(categoryId)
|
||||
|
||||
const createCategory = useCreateCategory()
|
||||
const updateCategory = useUpdateCategory()
|
||||
|
||||
const isEditMode = categoryId !== null
|
||||
const [isCodeAutoGenerated, setIsCodeAutoGenerated] = useState(true)
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
name: '',
|
||||
code: '',
|
||||
description: '',
|
||||
is_active: true,
|
||||
},
|
||||
validate: {
|
||||
name: (v) => (v.trim().length < 2 ? 'Минимум 2 символа' : null),
|
||||
code: (v) => {
|
||||
if (v.trim().length < 2) return 'Минимум 2 символа'
|
||||
if (!/^[a-z0-9_]+$/.test(v)) return 'Только lowercase буквы, цифры и подчеркивания'
|
||||
return null
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (category && opened) {
|
||||
form.setValues({
|
||||
name: category.name || '',
|
||||
code: category.code || '',
|
||||
description: category.description || '',
|
||||
is_active: category.is_active ?? true,
|
||||
})
|
||||
form.resetDirty()
|
||||
setIsCodeAutoGenerated(false)
|
||||
} else if (!isEditMode && opened) {
|
||||
form.reset()
|
||||
setIsCodeAutoGenerated(true)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [category, isEditMode, opened])
|
||||
|
||||
// Автогенерация кода при изменении названия (только если пользователь не начал вводить код вручную)
|
||||
useEffect(() => {
|
||||
if (!isEditMode && isCodeAutoGenerated) {
|
||||
form.setFieldValue('code', generateSlug(form.values.name))
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [form.values.name, isEditMode, isCodeAutoGenerated])
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
if (isEditMode && categoryId) {
|
||||
await updateCategory.mutateAsync({ id: categoryId, ...values })
|
||||
} else {
|
||||
await createCategory.mutateAsync(values)
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
const isLoading = isEditMode && categoryLoading
|
||||
const isSubmitting = createCategory.isPending || updateCategory.isPending
|
||||
|
||||
const codeProps = form.getInputProps('code')
|
||||
|
||||
return (
|
||||
<Drawer.Root opened={opened} onClose={onClose} position="right" size="min(480px, 100vw)">
|
||||
<Drawer.Overlay backgroundOpacity={0.25} />
|
||||
<Drawer.Content>
|
||||
<Drawer.Header>
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Text fw={600}>{isEditMode ? 'Редактирование' : 'Новая категория'}</Text>
|
||||
{isEditMode && category && (
|
||||
<Badge variant="light" color={category.is_active ? 'green' : 'gray'}>
|
||||
ID {category.id}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
</Box>
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body className={classes.body}>
|
||||
{isLoading ? (
|
||||
<Stack className={classes.section} gap="md">
|
||||
<Skeleton h={40} />
|
||||
<Skeleton h={40} />
|
||||
<Skeleton h={90} />
|
||||
</Stack>
|
||||
) : (
|
||||
<form style={{ display: 'contents' }} onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="lg" className={classes.section}>
|
||||
<TextInput
|
||||
label="Название"
|
||||
placeholder="Например: Отпуска и отгулы"
|
||||
withAsterisk
|
||||
{...form.getInputProps('name')}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
label="Код"
|
||||
placeholder="vacation"
|
||||
description="Уникальный системный идентификатор (только lowercase)"
|
||||
withAsterisk
|
||||
disabled={isEditMode}
|
||||
{...codeProps}
|
||||
onChange={(e) => {
|
||||
codeProps.onChange(e)
|
||||
setIsCodeAutoGenerated(false)
|
||||
}}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Описание"
|
||||
placeholder="Для чего нужна эта категория..."
|
||||
minRows={3}
|
||||
autosize
|
||||
{...form.getInputProps('description')}
|
||||
/>
|
||||
|
||||
<Switch
|
||||
label="Активна"
|
||||
description="Скрытые категории не будут доступны при создании новых заявок"
|
||||
color="green"
|
||||
checked={form.values.is_active}
|
||||
onChange={(e) => form.setFieldValue('is_active', e.currentTarget.checked)}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Group className={classes.footer} justify="space-between" wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">
|
||||
{form.isDirty() ? 'Есть несохраненные изменения' : ''}
|
||||
</Text>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting} disabled={isEditMode && !form.isDirty()}>
|
||||
{isEditMode ? 'Сохранить' : 'Создать'}
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
</form>
|
||||
)}
|
||||
</Drawer.Body>
|
||||
</Drawer.Content>
|
||||
</Drawer.Root>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,152 +0,0 @@
|
|||
import { useEffect } from 'react'
|
||||
import {
|
||||
Modal,
|
||||
Stack,
|
||||
TextInput,
|
||||
Textarea,
|
||||
Switch,
|
||||
Group,
|
||||
Button,
|
||||
Text,
|
||||
Loader,
|
||||
Center,
|
||||
Badge,
|
||||
} from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import {
|
||||
useCategory,
|
||||
useCreateCategory,
|
||||
useUpdateCategory
|
||||
} from '@/features/categories/hooks/useCategories'
|
||||
|
||||
interface CategoryEditModalProps {
|
||||
categoryId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function CategoryEditModal({
|
||||
categoryId,
|
||||
opened,
|
||||
onClose
|
||||
}: CategoryEditModalProps) {
|
||||
const { data: category, isLoading: categoryLoading } = useCategory(categoryId)
|
||||
|
||||
const createCategory = useCreateCategory()
|
||||
const updateCategory = useUpdateCategory()
|
||||
|
||||
const isEditMode = categoryId !== null
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
name: '',
|
||||
code: '',
|
||||
description: '',
|
||||
is_active: true,
|
||||
},
|
||||
validate: {
|
||||
name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
|
||||
code: (value: string | any[]) => {
|
||||
if (value.length < 2) return 'Код должен содержать минимум 2 символа'
|
||||
if (!/^[a-z0-9_]+$/.test(value as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
|
||||
return null
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Заполняем форму данными категории
|
||||
useEffect(() => {
|
||||
if (category) {
|
||||
form.setValues({
|
||||
name: category.name || '',
|
||||
code: category.code || '',
|
||||
description: category.description || '',
|
||||
is_active: category.is_active ?? true,
|
||||
})
|
||||
} else if (!isEditMode) {
|
||||
form.reset()
|
||||
}
|
||||
}, [category, isEditMode])
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
if (isEditMode && categoryId) {
|
||||
// Режим редактирования
|
||||
await updateCategory.mutateAsync({
|
||||
id: categoryId,
|
||||
...values,
|
||||
})
|
||||
} else {
|
||||
// Режим создания
|
||||
await createCategory.mutateAsync(values)
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
const isLoading = categoryLoading
|
||||
const isSubmitting = createCategory.isPending || updateCategory.isPending
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={
|
||||
<Group>
|
||||
<Text fw={700}>
|
||||
{isEditMode ? 'Редактирование категории' : 'Создание категории'}
|
||||
</Text>
|
||||
{category && <Badge variant="light">ID: {category.id}</Badge>}
|
||||
</Group>
|
||||
}
|
||||
size="md"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Center p={40}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="md">
|
||||
<TextInput
|
||||
label="Название"
|
||||
placeholder="Отпуска и отгулы"
|
||||
required
|
||||
{...form.getInputProps('name')}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
label="Код"
|
||||
placeholder="vacation"
|
||||
required
|
||||
description="Уникальный идентификатор категории (lowercase, цифры, подчеркивания)"
|
||||
disabled={isEditMode}
|
||||
{...form.getInputProps('code')}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Описание"
|
||||
placeholder="Описание категории..."
|
||||
minRows={3}
|
||||
{...form.getInputProps('description')}
|
||||
/>
|
||||
|
||||
<Switch
|
||||
label="Активна"
|
||||
description="Неактивные категории не будут доступны для выбора при создании тем"
|
||||
checked={form.values.is_active}
|
||||
onChange={(e) => form.setFieldValue('is_active', e.currentTarget.checked)}
|
||||
/>
|
||||
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting}>
|
||||
{isEditMode ? 'Сохранить' : 'Создать'}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,4 +1,4 @@
|
|||
import { useState, useMemo } from 'react'
|
||||
import {useState, useMemo, useEffect} from 'react'
|
||||
import {
|
||||
Paper,
|
||||
Group,
|
||||
|
|
@ -8,126 +8,116 @@ import {
|
|||
Loader,
|
||||
Center,
|
||||
Stack,
|
||||
Box,
|
||||
Badge,
|
||||
Textarea,
|
||||
Code,
|
||||
Divider,
|
||||
Alert,
|
||||
Collapse,
|
||||
ActionIcon,
|
||||
Tooltip,
|
||||
} from '@mantine/core'
|
||||
import {
|
||||
IconPlus,
|
||||
IconDeviceFloppy,
|
||||
IconRefresh,
|
||||
IconChevronDown,
|
||||
IconChevronRight,
|
||||
IconInfoCircle, IconBook,
|
||||
} from '@tabler/icons-react'
|
||||
import { IconPlus, IconInfoCircle, IconBook, IconFolderPlus, IconRefresh, IconAlertTriangle } from '@tabler/icons-react'
|
||||
import { modals } from '@mantine/modals'
|
||||
import { useTopics } from '@/features/topics/hooks/useTopics'
|
||||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
||||
import {
|
||||
useFlowNodesTree,
|
||||
useDeleteFlowNode,
|
||||
useSaveFlowTree,
|
||||
useMoveFlowNode,
|
||||
useDuplicateFlowNode,
|
||||
useReloadBot,
|
||||
useUpdateFlowNode,
|
||||
} from '@/features/flowNodes/hooks/useFlowNodes'
|
||||
import { useUpdateTopic } from '@/features/topics/hooks/useTopics'
|
||||
import FlowTreeNode from './components/FlowTreeNode'
|
||||
import FlowNodeEditModal from './components/FlowNodeEditModal'
|
||||
import type { ApprovalFlowNode, ApprovalTopic } from '@/types/api'
|
||||
import { findParent } from '@/features/flowNodes/utils/treeWalk'
|
||||
import type { ApprovalFlowNode, ApprovalTopicCategory } from '@/types/api'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import CategoryCreateModal from "@/pages/flowNodes/components/CategoryCreateModal.tsx";
|
||||
import FlowNodeEditModal from "@/pages/flowNodes/components/FlowNodeEditModal.tsx";
|
||||
import SortableFlowTree from "@/pages/flowNodes/components/SortableFlowTree.tsx";
|
||||
import TreeHealthPanel from "@/pages/flowNodes/components/TreeHealthPanel.tsx";
|
||||
import {notifications} from "@mantine/notifications";
|
||||
import apiClient from "@/api/client.ts";
|
||||
import {flowNodesApi} from "@/api/flowNodes.ts";
|
||||
import {topicsApi} from "@/api/topics.ts";
|
||||
|
||||
export default function FlowTreePage() {
|
||||
const [selectedTopicId, setSelectedTopicId] = useState<number | null>(null)
|
||||
const [showTemplates, setShowTemplates] = useState(false)
|
||||
const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null)
|
||||
const [categoryModalOpened, setCategoryModalOpened] = useState(false)
|
||||
|
||||
// Модалка редактирования узла
|
||||
const [editModal, setEditModal] = useState<{
|
||||
opened: boolean
|
||||
parentNode: ApprovalFlowNode | null
|
||||
editNode: ApprovalFlowNode | null
|
||||
}>({
|
||||
opened: false,
|
||||
parentNode: null,
|
||||
editNode: null,
|
||||
})
|
||||
}>({ opened: false, parentNode: null, editNode: null })
|
||||
|
||||
// Загружаем все темы
|
||||
const { data: topicsData } = useTopics({
|
||||
limit: 1000,
|
||||
is_tree_root: true
|
||||
})
|
||||
const topics = topicsData?.data || []
|
||||
const { data: categoriesData } = useCategories({ limit: 1000, is_active: true })
|
||||
const categories = categoriesData?.data || []
|
||||
|
||||
// Загружаем дерево для выбранной темы
|
||||
const { data: treeData, isLoading: treeLoading } = useFlowNodesTree(selectedTopicId)
|
||||
const { data: treeData, isLoading: treeLoading } = useFlowNodesTree(selectedCategoryId)
|
||||
const tree = treeData?.data || []
|
||||
|
||||
const deleteFlowNode = useDeleteFlowNode()
|
||||
const saveTree = useSaveFlowTree()
|
||||
const moveFlowNode = useMoveFlowNode()
|
||||
const duplicateFlowNode = useDuplicateFlowNode()
|
||||
const updateTopic = useUpdateTopic()
|
||||
const reloadBot = useReloadBot()
|
||||
|
||||
// Вычисляем недостающие ключи в шаблоне сообщения
|
||||
const missingMessageKeys = useMemo(() => {
|
||||
if (!tree || tree.length === 0) return []
|
||||
|
||||
const rootNode = tree.find(n => !n.parent_id) || tree[0]
|
||||
if (!rootNode) return []
|
||||
|
||||
const template = rootNode.message_template || ''
|
||||
|
||||
const allKeys = new Set<string>()
|
||||
const walk = (nodes: ApprovalFlowNode[]) => {
|
||||
for (const n of nodes) {
|
||||
if (n.data_key) allKeys.add(n.data_key)
|
||||
if (n.multi_select_key) allKeys.add(n.multi_select_key)
|
||||
if (n.children) walk(n.children)
|
||||
}
|
||||
}
|
||||
walk(tree)
|
||||
|
||||
const missing: string[] = []
|
||||
allKeys.forEach(key => {
|
||||
if (!template.includes(`.${key}`)) {
|
||||
missing.push(key)
|
||||
}
|
||||
})
|
||||
|
||||
return missing
|
||||
}, [tree])
|
||||
|
||||
const navigate = useNavigate()
|
||||
|
||||
// Выбранная тема
|
||||
const selectedTopic = useMemo(() => {
|
||||
return topics.find((t) => t.id === selectedTopicId) || null
|
||||
}, [topics, selectedTopicId])
|
||||
const selectedCategory = useMemo<ApprovalTopicCategory | null>(
|
||||
() => categories.find((c) => c.id === selectedCategoryId) || null,
|
||||
[selectedCategoryId]
|
||||
)
|
||||
|
||||
const topicOptions = topics.map((t) => ({
|
||||
value: String(t.id),
|
||||
label: `${t.name} (${t.code})`,
|
||||
}))
|
||||
const categoryOptions = categories.map((c) => ({ value: String(c.id), label: `${c.name} (${c.code})` }))
|
||||
|
||||
// Подсчёт узлов
|
||||
const countNodes = (nodes: ApprovalFlowNode[]): number => {
|
||||
let count = nodes.length
|
||||
for (const n of nodes) {
|
||||
if (n.children) count += countNodes(n.children)
|
||||
}
|
||||
for (const n of nodes) if (n.children) count += countNodes(n.children)
|
||||
return count
|
||||
}
|
||||
const totalNodes = countNodes(tree)
|
||||
|
||||
// Обработчики
|
||||
const handleEdit = (node: ApprovalFlowNode) => {
|
||||
// Находим родителя
|
||||
const parent = findParent(tree, node.id!)
|
||||
setEditModal({
|
||||
opened: true,
|
||||
parentNode: parent,
|
||||
editNode: node,
|
||||
})
|
||||
setEditModal({ opened: true, parentNode: parent, editNode: node })
|
||||
}
|
||||
|
||||
const handleAddChild = (parent: ApprovalFlowNode) => {
|
||||
setEditModal({
|
||||
opened: true,
|
||||
parentNode: parent,
|
||||
editNode: null,
|
||||
})
|
||||
setEditModal({ opened: true, parentNode: parent, editNode: null })
|
||||
}
|
||||
|
||||
const handleAddRoot = () => {
|
||||
setEditModal({
|
||||
opened: true,
|
||||
parentNode: null,
|
||||
editNode: null,
|
||||
})
|
||||
setEditModal({ opened: true, parentNode: null, editNode: null })
|
||||
}
|
||||
|
||||
const handleDelete = (node: ApprovalFlowNode) => {
|
||||
modals.openConfirmModal({
|
||||
title: 'Удалить узел?',
|
||||
title: 'Удалить этот шаг?',
|
||||
children: (
|
||||
<Text size="sm">
|
||||
Удалить узел <b>{node.label}</b>? Все дочерние узлы также будут удалены.
|
||||
Удалить шаг <b>{node.label}</b>? Все шаги, которые идут после него, тоже удалятся.
|
||||
</Text>
|
||||
),
|
||||
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
||||
|
|
@ -136,199 +126,173 @@ export default function FlowTreePage() {
|
|||
})
|
||||
}
|
||||
|
||||
const handleDuplicate = (node: ApprovalFlowNode) => {
|
||||
duplicateFlowNode.mutate(node.id!)
|
||||
const handleConfigureTopic = async (node: ApprovalFlowNode) => {
|
||||
if (!selectedCategoryId || !node.id) return
|
||||
|
||||
const collected: Record<string, string> = {}
|
||||
const nodeMap = new Map<number, ApprovalFlowNode>()
|
||||
|
||||
const walk = (nodes: ApprovalFlowNode[]) => {
|
||||
for (const n of nodes) {
|
||||
if (n.id) nodeMap.set(n.id, n)
|
||||
if (n.children) walk(n.children)
|
||||
}
|
||||
}
|
||||
walk(tree)
|
||||
|
||||
let current = nodeMap.get(node.id)
|
||||
while (current) {
|
||||
if (current.data_key && current.data_value) {
|
||||
collected[current.data_key] = current.data_value
|
||||
}
|
||||
if (current.multi_select_key && current.multi_select_value) {
|
||||
collected[current.multi_select_key] = current.multi_select_value
|
||||
}
|
||||
current = current.parent_id ? nodeMap.get(current.parent_id) : undefined
|
||||
}
|
||||
|
||||
const handleMoveUp = (node: ApprovalFlowNode) => {
|
||||
const parent = findParent(tree, node.id!)
|
||||
const siblings = parent ? parent.children! : tree
|
||||
const index = siblings.findIndex((n) => n.id === node.id)
|
||||
if (index > 0) {
|
||||
moveFlowNode.mutate({
|
||||
id: node.id!,
|
||||
data: { new_sort_order: index - 1 },
|
||||
try {
|
||||
const response = await flowNodesApi.preview(selectedCategoryId, { collected })
|
||||
const previewData = response.data
|
||||
|
||||
if (previewData.incomplete) {
|
||||
notifications.show({
|
||||
title: 'Недостаточно данных',
|
||||
message: 'Невозможно настроить маршрут: на этом уровне не хватает данных для формирования кода темы.',
|
||||
color: 'orange'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Если темы с таким кодом еще нет, создаем её
|
||||
if (!previewData.topic_exists) {
|
||||
await topicsApi.create({
|
||||
category_id: selectedCategoryId,
|
||||
code: previewData.code,
|
||||
name: `${selectedCategory?.name}: ${node.label} (Узел)`,
|
||||
is_active: true,
|
||||
allow_approver_selection: false,
|
||||
allow_observer_selection: false,
|
||||
allow_delegation_selection: false
|
||||
})
|
||||
|
||||
notifications.show({
|
||||
title: 'Успех',
|
||||
message: 'Тема для этого узла успешно создана в базе.',
|
||||
color: 'green'
|
||||
})
|
||||
}
|
||||
|
||||
modals.openConfirmModal({
|
||||
title: 'Настройка иерархии',
|
||||
children: (
|
||||
<Text size="sm">
|
||||
Тема для каскадного согласования готова. Хотите перейти на страницу настройки иерархии прямо сейчас?
|
||||
</Text>
|
||||
),
|
||||
labels: { confirm: 'Перейти', cancel: 'Настроить позже' },
|
||||
onConfirm: () => {
|
||||
navigate('/hierarchies')
|
||||
},
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Ошибка при настройке маршрута:', error)
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: 'Не удалось подготовить маршрут. Проверьте консоль.',
|
||||
color: 'red'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleMoveDown = (node: ApprovalFlowNode) => {
|
||||
const parent = findParent(tree, node.id!)
|
||||
const siblings = parent ? parent.children! : tree
|
||||
const index = siblings.findIndex((n) => n.id === node.id)
|
||||
if (index < siblings.length - 1) {
|
||||
moveFlowNode.mutate({
|
||||
id: node.id!,
|
||||
data: { new_sort_order: index + 1 },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Сохранение шаблонов темы
|
||||
const handleSaveTemplates = () => {
|
||||
if (!selectedTopic) return
|
||||
updateTopic.mutate({
|
||||
id: selectedTopic.id!,
|
||||
message_template: selectedTopic.message_template,
|
||||
code_template: selectedTopic.code_template,
|
||||
})
|
||||
}
|
||||
const handleDuplicate = (node: ApprovalFlowNode) => duplicateFlowNode.mutate(node.id!)
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between">
|
||||
<Text size="xl" fw={700}>Конструктор деревьев</Text>
|
||||
<Text size="xl" fw={700}>
|
||||
Конструктор тем
|
||||
</Text>
|
||||
<Group>
|
||||
{selectedTopic && (
|
||||
<Badge size="lg" variant="light">{totalNodes} узлов</Badge>
|
||||
)}
|
||||
{selectedCategory && <Badge size="lg" variant="light">{totalNodes} шагов</Badge>}
|
||||
<Tooltip label="Заставить бота немедленно перечитать разделы/деревья/темы из базы, не дожидаясь автоматической проверки">
|
||||
<Button
|
||||
variant="light"
|
||||
leftSection={<IconBook size={16} />}
|
||||
onClick={() => navigate('/guide/flow-trees')}
|
||||
color="orange"
|
||||
leftSection={<IconRefresh size={16} />}
|
||||
onClick={() => reloadBot.mutate()}
|
||||
loading={reloadBot.isPending}
|
||||
>
|
||||
Обновить бота
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Button variant="light" leftSection={<IconBook size={16} />} onClick={() => navigate('/guide/flow-trees')}>
|
||||
Руководство
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
{/* Выбор темы */}
|
||||
<Paper withBorder p="md">
|
||||
<Stack gap="md">
|
||||
<Group align="end" gap="sm">
|
||||
<Select
|
||||
label="Тема"
|
||||
placeholder="Выберите тему для редактирования дерева"
|
||||
data={topicOptions}
|
||||
value={selectedTopicId ? String(selectedTopicId) : null}
|
||||
onChange={(v) => setSelectedTopicId(v ? Number(v) : null)}
|
||||
label="Раздел заявок"
|
||||
placeholder="Выберите раздел, дерево которого будете настраивать"
|
||||
data={categoryOptions}
|
||||
value={selectedCategoryId ? String(selectedCategoryId) : null}
|
||||
onChange={(v) => setSelectedCategoryId(v ? Number(v) : null)}
|
||||
searchable
|
||||
required
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
|
||||
{/* Шаблоны темы */}
|
||||
{selectedTopic && (
|
||||
<>
|
||||
<Divider label="Шаблоны темы" labelPosition="center" />
|
||||
|
||||
<Box>
|
||||
<Group
|
||||
justify="space-between"
|
||||
mb="xs"
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={() => setShowTemplates(!showTemplates)}
|
||||
>
|
||||
<Group gap="xs">
|
||||
{showTemplates ? (
|
||||
<IconChevronDown size={16} />
|
||||
) : (
|
||||
<IconChevronRight size={16} />
|
||||
)}
|
||||
<Text size="sm" fw={500}>
|
||||
Шаблоны сообщений и кодов
|
||||
</Text>
|
||||
</Group>
|
||||
<Tooltip label="Завести новый раздел заявок, не выходя отсюда">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="light"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleSaveTemplates()
|
||||
}}
|
||||
loading={updateTopic.isPending}
|
||||
leftSection={<IconDeviceFloppy size={14} />}
|
||||
variant="default"
|
||||
leftSection={<IconFolderPlus size={16} />}
|
||||
onClick={() => setCategoryModalOpened(true)}
|
||||
>
|
||||
Сохранить шаблоны
|
||||
Новый раздел
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
|
||||
<Collapse expanded={showTemplates}>
|
||||
<Stack gap="sm">
|
||||
<Textarea
|
||||
label="Шаблон сообщения для согласующего (Go template)"
|
||||
description={
|
||||
<Text size="xs">
|
||||
Доступные переменные:{' '}
|
||||
<Code>{'{{.initiator_name}}'}</Code>,{' '}
|
||||
<Code>{'{{.topic_name}}'}</Code>,{' '}
|
||||
<Code>{'{{.content}}'}</Code>,{' '}
|
||||
<Code>{'{{.region_label}}'}</Code>,{' '}
|
||||
<Code>{'{{.branch_label}}'}</Code>, и любые ключи из{' '}
|
||||
<Code>collected</Code> + суффикс <Code>_label</Code>
|
||||
</Text>
|
||||
}
|
||||
minRows={6}
|
||||
value={selectedTopic.message_template || ''}
|
||||
onChange={(e) => {
|
||||
if (selectedTopic) {
|
||||
selectedTopic.message_template = e.currentTarget.value
|
||||
}
|
||||
}}
|
||||
styles={{ input: { fontFamily: 'monospace', fontSize: 12 } }}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Шаблон кода темы (Go template)"
|
||||
description={
|
||||
<Text size="xs">
|
||||
Формирует финальный код темы. Если не задан — код формируется
|
||||
автоматически из всех значений <Code>collected</Code>. Функции:{' '}
|
||||
<Code>trimPrefix</Code>, <Code>eq</Code>, <Code>contains</Code>
|
||||
</Text>
|
||||
}
|
||||
minRows={2}
|
||||
value={selectedTopic.code_template || ''}
|
||||
onChange={(e) => {
|
||||
if (selectedTopic) {
|
||||
selectedTopic.code_template = e.currentTarget.value
|
||||
}
|
||||
}}
|
||||
styles={{ input: { fontFamily: 'monospace', fontSize: 12 } }}
|
||||
/>
|
||||
</Stack>
|
||||
</Collapse>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* Дерево */}
|
||||
{selectedTopicId && (
|
||||
{selectedCategoryId && (
|
||||
<Paper withBorder p="md">
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between">
|
||||
<Group gap="xs">
|
||||
<Text fw={600}>Дерево навигации</Text>
|
||||
{treeLoading && <Loader size="xs" />}
|
||||
</Group>
|
||||
<Group>
|
||||
<Tooltip label="Обновить">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
onClick={() => {
|
||||
if (selectedTopicId) {
|
||||
// Инвалидация кэша
|
||||
window.location.reload()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<IconRefresh size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Button
|
||||
leftSection={<IconPlus size={16} />}
|
||||
onClick={handleAddRoot}
|
||||
>
|
||||
Добавить корневой узел
|
||||
<Button leftSection={<IconPlus size={16} />} onClick={handleAddRoot} disabled={tree.length > 0}>
|
||||
Добавить первый вопрос
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
{missingMessageKeys.length > 0 && (
|
||||
<Alert icon={<IconAlertTriangle size={16} />} color="orange" variant="light">
|
||||
<Text size="sm" fw={600}>
|
||||
В шаблоне сообщения учтены не все ветки
|
||||
</Text>
|
||||
<Text size="sm" mt={4}>
|
||||
Вы добавили новые варианты ответов, но не обновили шаблон сообщения.
|
||||
Без этого согласующий не увидит, что именно выбрал сотрудник на этих шагах:
|
||||
</Text>
|
||||
<Group gap={6} mt="xs" mb="xs">
|
||||
{missingMessageKeys.map(key => (
|
||||
<Badge key={key} color="orange" variant="light">{key}</Badge>
|
||||
))}
|
||||
</Group>
|
||||
<Text size="sm">
|
||||
Откройте первый шаг дерева (корневой узел) на редактирование и добавьте их в блок «Сообщение согласующему и код темы» (или нажмите там кнопку «Сформировать черновик»).
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
||||
<Text size="sm">
|
||||
<b>Совет:</b> Используйте кнопки ↑ ↓ для изменения порядка,{' '}
|
||||
<b>+</b> для добавления дочернего узла, <b>📋</b> для дублирования.
|
||||
Все изменения сохраняются автоматически.
|
||||
Перетаскивайте шаги за значок ⠿ слева, чтобы менять порядок и вложенность — тяните
|
||||
влево/вправо во время перетаскивания, чтобы изменить уровень. Первый шаг дерева
|
||||
(с пометкой «начало дерева») не перетаскивается.
|
||||
</Text>
|
||||
</Alert>
|
||||
|
||||
|
|
@ -339,64 +303,44 @@ export default function FlowTreePage() {
|
|||
) : tree.length === 0 ? (
|
||||
<Center p={40}>
|
||||
<Stack gap="sm" align="center">
|
||||
<Text c="dimmed">Дерево пустое</Text>
|
||||
<Button
|
||||
leftSection={<IconPlus size={16} />}
|
||||
onClick={handleAddRoot}
|
||||
>
|
||||
Добавить первый узел
|
||||
<Text c="dimmed">В этом разделе пока нет вопросов</Text>
|
||||
<Button leftSection={<IconPlus size={16} />} onClick={handleAddRoot}>
|
||||
Добавить первый вопрос
|
||||
</Button>
|
||||
</Stack>
|
||||
</Center>
|
||||
) : (
|
||||
<Stack gap={4}>
|
||||
{tree.map((node, idx) => (
|
||||
<FlowTreeNode
|
||||
key={node.id}
|
||||
node={node}
|
||||
depth={0}
|
||||
siblings={tree}
|
||||
<SortableFlowTree
|
||||
tree={tree}
|
||||
onEdit={handleEdit}
|
||||
onAddChild={handleAddChild}
|
||||
onDelete={handleDelete}
|
||||
onDuplicate={handleDuplicate}
|
||||
onMoveUp={handleMoveUp}
|
||||
onMoveDown={handleMoveDown}
|
||||
index={idx}
|
||||
onConfigureTopic={handleConfigureTopic}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Модалка редактирования узла */}
|
||||
{selectedTopicId && (
|
||||
{selectedCategoryId && tree.length > 0 && <TreeHealthPanel categoryId={selectedCategoryId} tree={tree} />}
|
||||
|
||||
{selectedCategoryId && (
|
||||
<FlowNodeEditModal
|
||||
topicId={selectedTopicId}
|
||||
categoryId={selectedCategoryId}
|
||||
tree={tree}
|
||||
parentNode={editModal.parentNode}
|
||||
editNode={editModal.editNode}
|
||||
opened={editModal.opened}
|
||||
onClose={() => setEditModal({ opened: false, parentNode: null, editNode: null })}
|
||||
/>
|
||||
)}
|
||||
|
||||
<CategoryCreateModal
|
||||
opened={categoryModalOpened}
|
||||
onClose={() => setCategoryModalOpened(false)}
|
||||
onCreated={(newId) => setSelectedCategoryId(newId)}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
// Вспомогательная функция: найти родителя узла по ID
|
||||
function findParent(
|
||||
nodes: ApprovalFlowNode[],
|
||||
targetId: number,
|
||||
parent: ApprovalFlowNode | null = null
|
||||
): ApprovalFlowNode | null {
|
||||
for (const node of nodes) {
|
||||
if (node.id === targetId) return parent
|
||||
if (node.children) {
|
||||
const found = findParent(node.children, targetId, node)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
|
@ -0,0 +1,121 @@
|
|||
import { useEffect } from 'react'
|
||||
import { Modal, Stack, TextInput, Textarea, Group, Button, Text, Alert } from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { IconInfoCircle } from '@tabler/icons-react'
|
||||
import { useCreateCategory } from '@/features/categories/hooks/useCategories'
|
||||
import type { CreateCategoryRequest } from '@/api/categories'
|
||||
|
||||
interface CategoryCreateModalProps {
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
onCreated: (categoryId: number) => void
|
||||
}
|
||||
|
||||
const translitMap: Record<string, string> = {
|
||||
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'yo', ж: 'zh', з: 'z', и: 'i', й: 'y',
|
||||
к: 'k', л: 'l', м: 'm', н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f',
|
||||
х: 'h', ц: 'ts', ч: 'ch', ш: 'sh', щ: 'sch', ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
|
||||
}
|
||||
|
||||
function slugify(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.split('')
|
||||
.map((ch) => translitMap[ch] ?? ch)
|
||||
.join('')
|
||||
.replace(/[\s-]+/g, '_')
|
||||
.replace(/[^a-z0-9_]/g, '')
|
||||
.replace(/_+/g, '_')
|
||||
.replace(/^_+|_+$/g, '')
|
||||
// Код раздела попадает в Telegram callback_data КАЖДОЙ кнопки внутри
|
||||
// этой категории (формат "appr:{код_раздела}:{ключ_шага}", лимит
|
||||
// Telegram — 64 байта на всю строку) — держим его коротким, иначе
|
||||
// он съедает бюджет, который нужен для ключей узлов вглубь дерева.
|
||||
.substring(0, 20)
|
||||
}
|
||||
|
||||
// Создание новой категории (раздела заявок) прямо из конструктора дерева —
|
||||
// требование "полной автономности": админ не должен переходить в другой
|
||||
// раздел, чтобы завести новый вид заявки.
|
||||
export default function CategoryCreateModal({ opened, onClose, onCreated }: CategoryCreateModalProps) {
|
||||
const createCategory = useCreateCategory()
|
||||
|
||||
const form = useForm({
|
||||
initialValues: { name: '', code: '', description: '' },
|
||||
validate: {
|
||||
name: (v) => (!v || v.length < 2 ? 'Введите название раздела' : null),
|
||||
code: (v) => (!v || v.length < 2 ? 'Технический код должен быть заполнен' : null),
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (opened) form.reset()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [opened])
|
||||
|
||||
useEffect(() => {
|
||||
form.setFieldValue('code', slugify(form.values.name))
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [form.values.name])
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
const payload: CreateCategoryRequest = {
|
||||
name: values.name,
|
||||
code: values.code,
|
||||
description: values.description || undefined,
|
||||
is_active: true,
|
||||
}
|
||||
const result = await createCategory.mutateAsync(payload)
|
||||
// categoriesApi.create возвращает ApprovalTopicCategory без обёртки
|
||||
// (apiClient.post<ApprovalTopicCategory>), axios кладёт его в response.data.
|
||||
const newId = result?.data?.id
|
||||
if (newId) onCreated(newId)
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal opened={opened} onClose={onClose} title={<Text fw={700}>Новый раздел заявок</Text>}>
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="md">
|
||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
||||
<Text size="xs">
|
||||
Раздел — это то, что сотрудник увидит в главном меню бота (например, «Отпуска» или
|
||||
«Возвраты»). Внутри одного раздела вы потом соберёте дерево вопросов.
|
||||
</Text>
|
||||
</Alert>
|
||||
|
||||
<TextInput
|
||||
label="Название раздела"
|
||||
placeholder="Например: Возвраты товара"
|
||||
description="То, что увидит сотрудник в списке заявок"
|
||||
required
|
||||
{...form.getInputProps('name')}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
label="Технический код"
|
||||
description="Заполняется само из названия. Трогать не нужно."
|
||||
disabled
|
||||
{...form.getInputProps('code')}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Описание (необязательно)"
|
||||
placeholder="Короткая заметка для себя, сотрудники её не видят"
|
||||
minRows={2}
|
||||
{...form.getInputProps('description')}
|
||||
/>
|
||||
|
||||
<Group justify="flex-end" mt="sm">
|
||||
<Button variant="default" onClick={onClose}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={createCategory.isPending}>
|
||||
Создать раздел
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,227 +0,0 @@
|
|||
import {
|
||||
Group,
|
||||
Text,
|
||||
ActionIcon,
|
||||
Badge,
|
||||
Paper,
|
||||
Stack,
|
||||
Tooltip,
|
||||
Box,
|
||||
Code,
|
||||
Collapse,
|
||||
} from '@mantine/core'
|
||||
import {
|
||||
IconPencil,
|
||||
IconTrash,
|
||||
IconCopy,
|
||||
IconPlus,
|
||||
IconChevronRight,
|
||||
IconChevronDown,
|
||||
IconArrowUp,
|
||||
IconArrowDown,
|
||||
IconKeyboard,
|
||||
IconCheckbox,
|
||||
IconHierarchy,
|
||||
} from '@tabler/icons-react'
|
||||
import { useState } from 'react'
|
||||
import type { ApprovalFlowNode } from '@/types/api'
|
||||
|
||||
interface FlowTreeNodeProps {
|
||||
node: ApprovalFlowNode
|
||||
depth: number
|
||||
siblings: ApprovalFlowNode[]
|
||||
onEdit: (node: ApprovalFlowNode) => void
|
||||
onAddChild: (parent: ApprovalFlowNode) => void
|
||||
onDelete: (node: ApprovalFlowNode) => void
|
||||
onDuplicate: (node: ApprovalFlowNode) => void
|
||||
onMoveUp: (node: ApprovalFlowNode) => void
|
||||
onMoveDown: (node: ApprovalFlowNode) => void
|
||||
index: number
|
||||
}
|
||||
|
||||
export default function FlowTreeNode({
|
||||
node,
|
||||
depth,
|
||||
siblings,
|
||||
onEdit,
|
||||
onAddChild,
|
||||
onDelete,
|
||||
onDuplicate,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
index,
|
||||
}: FlowTreeNodeProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(true)
|
||||
const hasChildren = node.children && node.children.length > 0
|
||||
|
||||
// Определяем тип узла для иконки
|
||||
let typeIcon = <IconHierarchy size={14} />
|
||||
let typeColor = 'blue'
|
||||
let typeLabel = 'Кнопка'
|
||||
|
||||
if (node.is_input) {
|
||||
typeIcon = <IconKeyboard size={14} />
|
||||
typeColor = 'orange'
|
||||
typeLabel = 'Ввод'
|
||||
} else if (node.is_multi_select) {
|
||||
typeIcon = <IconCheckbox size={14} />
|
||||
typeColor = 'violet'
|
||||
typeLabel = 'Мульти'
|
||||
}
|
||||
|
||||
return (
|
||||
<Box style={{ marginLeft: depth * 24 }}>
|
||||
<Paper
|
||||
withBorder
|
||||
p="xs"
|
||||
style={{
|
||||
backgroundColor: depth === 0 ? 'var(--mantine-color-blue-0)' : undefined,
|
||||
}}
|
||||
>
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Group gap="xs" wrap="nowrap" style={{ flex: 1, minWidth: 0 }}>
|
||||
{/* Раскрывалка */}
|
||||
{hasChildren ? (
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
>
|
||||
{isExpanded ? <IconChevronDown size={16} /> : <IconChevronRight size={16} />}
|
||||
</ActionIcon>
|
||||
) : (
|
||||
<Box w={24} />
|
||||
)}
|
||||
|
||||
{/* Иконка типа */}
|
||||
<Tooltip label={typeLabel}>
|
||||
<Badge size="xs" variant="light" color={typeColor} leftSection={typeIcon}>
|
||||
{typeLabel}
|
||||
</Badge>
|
||||
</Tooltip>
|
||||
|
||||
{/* Название */}
|
||||
<Text fw={500} size="sm" lineClamp={1} title={node.label}>
|
||||
{node.label}
|
||||
</Text>
|
||||
|
||||
{/* Техническая информация */}
|
||||
<Code style={{ fontSize: 11 }}>{node.key}</Code>
|
||||
|
||||
{/* DataKey/DataValue */}
|
||||
{node.data_key && node.data_value && (
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{node.data_key}={node.data_value}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{/* Topic code */}
|
||||
{node.topic_code && (
|
||||
<Badge size="xs" variant="dot" color="red">
|
||||
🔒 {node.topic_code}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
{/* Действия */}
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<Tooltip label="Переместить вверх">
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
color="gray"
|
||||
onClick={() => onMoveUp(node)}
|
||||
disabled={index === 0}
|
||||
>
|
||||
<IconArrowUp size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Переместить вниз">
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
color="gray"
|
||||
onClick={() => onMoveDown(node)}
|
||||
disabled={index === siblings.length - 1}
|
||||
>
|
||||
<IconArrowDown size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Добавить дочерний">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="green"
|
||||
size="sm"
|
||||
onClick={() => onAddChild(node)}
|
||||
>
|
||||
<IconPlus size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Редактировать">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="blue"
|
||||
size="sm"
|
||||
onClick={() => onEdit(node)}
|
||||
>
|
||||
<IconPencil size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Дублировать">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="violet"
|
||||
size="sm"
|
||||
onClick={() => onDuplicate(node)}
|
||||
>
|
||||
<IconCopy size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Удалить (с детьми)">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="red"
|
||||
size="sm"
|
||||
onClick={() => onDelete(node)}
|
||||
>
|
||||
<IconTrash size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
{/* Input hint preview */}
|
||||
{node.is_input && node.input_hint && (
|
||||
<Box ml={32} mt={4}>
|
||||
<Text size="xs" c="dimmed" lineClamp={2}>
|
||||
💬 {node.input_hint}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
{/* Дети */}
|
||||
{hasChildren && (
|
||||
<Collapse expanded={isExpanded}>
|
||||
<Stack gap={4} mt={4}>
|
||||
{node.children!.map((child, idx) => (
|
||||
<FlowTreeNode
|
||||
key={child.id}
|
||||
node={child}
|
||||
depth={depth + 1}
|
||||
siblings={node.children!}
|
||||
onEdit={onEdit}
|
||||
onAddChild={onAddChild}
|
||||
onDelete={onDelete}
|
||||
onDuplicate={onDuplicate}
|
||||
onMoveUp={onMoveUp}
|
||||
onMoveDown={onMoveDown}
|
||||
index={idx}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</Collapse>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue