Compare commits
No commits in common. "main" and "fix-permissions" have entirely different histories.
main
...
fix-permis
2
.env
2
.env
|
|
@ -1,5 +1,5 @@
|
||||||
# API Configuration
|
# API Configuration
|
||||||
VITE_API_BASE_URL=https://api.ruspet-preforma.ru:45373/api
|
VITE_API_BASE_URL=http://localhost:1726/api
|
||||||
VITE_API_KEY=test
|
VITE_API_KEY=test
|
||||||
VITE_API_PUBLIC_KEY=ruspet_public_key_2026
|
VITE_API_PUBLIC_KEY=ruspet_public_key_2026
|
||||||
VITE_API_PRIVATE_KEY=ruspet_private_key_SUPER_SECRET_2026
|
VITE_API_PRIVATE_KEY=ruspet_private_key_SUPER_SECRET_2026
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,7 @@ on:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REPO_DIR: "/workspace/ruspet_admin_frontend"
|
REPO_DIR: "/workspace/ruspet_admin_frontend"
|
||||||
# Обновлен URL и добавлена авторизация
|
REPO_URL: "https://72.56.235.246.nip.io/gitea/romanskijdev/admin_ruspet.git"
|
||||||
REPO_URL: "https://${{ github.actor }}:${{ github.token }}@git.ruspet-preforma.ru/romanskijdev/admin_ruspet.git"
|
|
||||||
BUILD_DIR: "/var/www/admin.ruspet.tw1.ru"
|
BUILD_DIR: "/var/www/admin.ruspet.tw1.ru"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
|
@ -34,8 +33,6 @@ jobs:
|
||||||
if [ -d "$REPO_DIR/.git" ]; then
|
if [ -d "$REPO_DIR/.git" ]; then
|
||||||
echo "📦 Updating existing repo..."
|
echo "📦 Updating existing repo..."
|
||||||
cd "$REPO_DIR"
|
cd "$REPO_DIR"
|
||||||
# Принудительно задаем новый URL на случай, если папка уже существует со старым
|
|
||||||
git remote set-url origin "$REPO_URL"
|
|
||||||
git fetch origin
|
git fetch origin
|
||||||
git reset --hard origin/main
|
git reset --hard origin/main
|
||||||
else
|
else
|
||||||
|
|
@ -101,7 +98,7 @@ jobs:
|
||||||
|
|
||||||
if [ "${{ job.status }}" == "success" ]; then
|
if [ "${{ job.status }}" == "success" ]; then
|
||||||
echo "✅ Frontend deployment completed!"
|
echo "✅ Frontend deployment completed!"
|
||||||
echo "🌐 Available at: https://panel.ruspet-preforma.ru"
|
echo "🌐 Available at: https://admin.ruspet.tw1.ru"
|
||||||
else
|
else
|
||||||
echo "❌ Frontend deployment failed!"
|
echo "❌ Frontend deployment failed!"
|
||||||
fi
|
fi
|
||||||
|
|
@ -1,146 +0,0 @@
|
||||||
const BALANCER_URL = 'https://72.56.235.246.nip.io/balancer/api/balancer/send';
|
|
||||||
const BALANCER_PUBLIC = '68929830b9a07e7c6fa1d4bdfbcafe798a50de4da2969e743fee690dfaec3fb4';
|
|
||||||
const BALANCER_PRIVATE = '89bab1c15544e7bb667b773df786e65f9aed0bf173a84e66e2a88aec3f0014d89a289807c34f71c876b79f67997c9ac281ffd19d00fe8582ebcda97660bddaa3';
|
|
||||||
const BITRIX_WEBHOOK = 'https://thebest.bitrix24.ru/rest/{USER}/{METHOD_ID}/';
|
|
||||||
|
|
||||||
function generateBalancerSignature_(timestampStr) {
|
|
||||||
const message = `${BALANCER_PUBLIC}:${timestampStr}`;
|
|
||||||
const signature = Utilities.computeHmacSha256Signature(message, BALANCER_PRIVATE);
|
|
||||||
return signature.map(b => ('0' + (b & 0xFF).toString(16)).slice(-2)).join('');
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Балансировщик: одиночный запрос
|
|
||||||
// Используется для get, update, add, delete и любых методов
|
|
||||||
// которые не возвращают next (не список).
|
|
||||||
function balancerPost_(method, body) {
|
|
||||||
const timestamp = Math.floor(Date.now() / 1000).toString();
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
url: BITRIX_WEBHOOK + method + '.json',
|
|
||||||
method: 'POST',
|
|
||||||
body: body || {},
|
|
||||||
};
|
|
||||||
|
|
||||||
const options = {
|
|
||||||
method: 'post',
|
|
||||||
contentType: 'application/json',
|
|
||||||
headers: {
|
|
||||||
'X-Timestamp': timestamp,
|
|
||||||
'X-Signature': generateBalancerSignature_(timestamp),
|
|
||||||
},
|
|
||||||
payload: JSON.stringify(payload),
|
|
||||||
muteHttpExceptions: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
let attempt = 0;
|
|
||||||
const maxRetries = 5;
|
|
||||||
const baseRetryMs = 1000;
|
|
||||||
const limitWaitMs = 5000;
|
|
||||||
|
|
||||||
while (attempt <= maxRetries) {
|
|
||||||
let res, data;
|
|
||||||
try {
|
|
||||||
res = UrlFetchApp.fetch(BALANCER_URL, options);
|
|
||||||
const httpCode = res.getResponseCode();
|
|
||||||
const rawText = res.getContentText();
|
|
||||||
|
|
||||||
if (httpCode === 401) throw new Error(`Балансировщик: ошибка авторизации — ${rawText}. Проверьте BALANCER_PUBLIC / BALANCER_PRIVATE`);
|
|
||||||
if (httpCode === 500) throw new Error(`Балансировщик: внутренняя ошибка — ${rawText}`);
|
|
||||||
if (httpCode !== 200) throw new Error(`Балансировщик: HTTP ${httpCode} — ${rawText}`);
|
|
||||||
|
|
||||||
data = JSON.parse(rawText);
|
|
||||||
} catch (e) {
|
|
||||||
attempt++;
|
|
||||||
const wait = baseRetryMs * attempt;
|
|
||||||
Logger.log(`⚠️ balancerPost_ сетевая ошибка (попытка ${attempt}): ${e} — ждём ${wait}ms`);
|
|
||||||
if (attempt > maxRetries) throw new Error(`Сетевая ошибка после ${maxRetries} попыток: ${e}`);
|
|
||||||
Utilities.sleep(wait);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (res.getResponseCode() !== 200) {
|
|
||||||
attempt++;
|
|
||||||
const wait = baseRetryMs * attempt;
|
|
||||||
Logger.log(`🔴 balancerPost_ HTTP ${res.getResponseCode()} (попытка ${attempt}) — ждём ${wait}ms`);
|
|
||||||
if (attempt > maxRetries) throw new Error(`balancer HTTP ${res.getResponseCode()}`);
|
|
||||||
Utilities.sleep(wait);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const bitrixBody = data?.body;
|
|
||||||
const errCode = bitrixBody?.error;
|
|
||||||
|
|
||||||
if (errCode === 'QUERY_LIMIT_EXCEEDED') {
|
|
||||||
attempt++;
|
|
||||||
const wait = limitWaitMs * attempt;
|
|
||||||
Logger.log(`🚦 QUERY_LIMIT_EXCEEDED (попытка ${attempt}) — ждём ${wait}ms`);
|
|
||||||
if (attempt > maxRetries) throw new Error('QUERY_LIMIT_EXCEEDED: превышен лимит');
|
|
||||||
Utilities.sleep(wait);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (errCode === 'INTERNAL_SERVER_ERROR') {
|
|
||||||
attempt++;
|
|
||||||
const wait = baseRetryMs * attempt;
|
|
||||||
Logger.log(`🔴 INTERNAL_SERVER_ERROR (попытка ${attempt}) — ждём ${wait}ms`);
|
|
||||||
if (attempt > maxRetries) throw new Error('INTERNAL_SERVER_ERROR после нескольких попыток');
|
|
||||||
Utilities.sleep(wait);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (errCode) {
|
|
||||||
throw new Error(`Битрикс API [${method}]: ${errCode} — ${bitrixBody?.error_description || ''}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
Logger.log(`🟢 balancerPost_ [${method}] OK`);
|
|
||||||
|
|
||||||
return bitrixBody;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error('balancerPost_: исчерпаны все попытки');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Выполняет рекуррентный запрос через балансировщик.
|
|
||||||
// Балансировщик сам крутит пагинацию и возвращает все записи одним массивом.
|
|
||||||
function balancerRecurrentPost_(method, body, resultKey) {
|
|
||||||
const timestamp = Math.floor(Date.now() / 1000).toString();
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
url: BITRIX_WEBHOOK + method + '.json',
|
|
||||||
method: 'POST',
|
|
||||||
is_recurrent: true,
|
|
||||||
result_key: resultKey || null,
|
|
||||||
body: body,
|
|
||||||
};
|
|
||||||
|
|
||||||
const options = {
|
|
||||||
method: 'post',
|
|
||||||
contentType: 'application/json',
|
|
||||||
headers: {
|
|
||||||
'X-Timestamp': timestamp,
|
|
||||||
'X-Signature': generateBalancerSignature_(timestamp),
|
|
||||||
},
|
|
||||||
payload: JSON.stringify(payload),
|
|
||||||
muteHttpExceptions: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
const sig = generateBalancerSignature_(timestamp);
|
|
||||||
Logger.log('Timestamp: ' + timestamp);
|
|
||||||
Logger.log('Signature: ' + sig);
|
|
||||||
Logger.log('Message: ' + BALANCER_PUBLIC + ':' + timestamp);
|
|
||||||
|
|
||||||
res = UrlFetchApp.fetch(BALANCER_URL, options);
|
|
||||||
const httpCode = res.getResponseCode();
|
|
||||||
const rawText = res.getContentText();
|
|
||||||
|
|
||||||
if (httpCode === 401) throw new Error(`Балансировщик: ошибка авторизации — ${rawText}. Проверьте BALANCER_PUBLIC / BALANCER_PRIVATE`);
|
|
||||||
if (httpCode === 500) throw new Error(`Балансировщик: внутренняя ошибка — ${rawText}`);
|
|
||||||
if (httpCode !== 200) throw new Error(`Балансировщик: HTTP ${httpCode} — ${rawText}`);
|
|
||||||
|
|
||||||
data = JSON.parse(rawText);
|
|
||||||
|
|
||||||
if (data.error) throw new Error(`balancer error [${method}]: ${JSON.stringify(data.error)}`);
|
|
||||||
|
|
||||||
// Возвращает { body: [...], total_fetched: N, quota_left: N }
|
|
||||||
return data.body || [];
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -8,23 +8,14 @@
|
||||||
"name": "ruspet_admin_frontend",
|
"name": "ruspet_admin_frontend",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@mantine/core": "^9.3.1",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@mantine/dates": "^9.3.1",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
|
||||||
"@mantine/core": "^9.4.1",
|
|
||||||
"@mantine/dates": "^9.4.1",
|
|
||||||
"@mantine/form": "^9.3.1",
|
"@mantine/form": "^9.3.1",
|
||||||
"@mantine/hooks": "^9.4.1",
|
"@mantine/hooks": "^9.3.1",
|
||||||
"@mantine/modals": "^9.4.1",
|
"@mantine/modals": "^9.3.1",
|
||||||
"@mantine/notifications": "^9.4.1",
|
"@mantine/notifications": "^9.3.1",
|
||||||
"@mantine/tiptap": "^9.4.1",
|
|
||||||
"@tabler/icons-react": "^3.44.0",
|
"@tabler/icons-react": "^3.44.0",
|
||||||
"@tanstack/react-query": "^5.101.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",
|
"axios": "^1.18.0",
|
||||||
"crypto-js": "^4.2.0",
|
"crypto-js": "^4.2.0",
|
||||||
"dayjs": "^1.11.21",
|
"dayjs": "^1.11.21",
|
||||||
|
|
@ -301,59 +292,6 @@
|
||||||
"node": ">=6.9.0"
|
"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": {
|
"node_modules/@emnapi/core": {
|
||||||
"version": "1.10.0",
|
"version": "1.10.0",
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
|
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
|
||||||
|
|
@ -686,34 +624,34 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@mantine/core": {
|
"node_modules/@mantine/core": {
|
||||||
"version": "9.4.1",
|
"version": "9.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/@mantine/core/-/core-9.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/@mantine/core/-/core-9.3.1.tgz",
|
||||||
"integrity": "sha512-lZWEICrum4+vwKxzh/mk4RB1N6BqZ0Cshdl6lhm7OYLiQzmOaxKtOgyaWz+vr65G8mqTXjalZalB+wmMVBYK2Q==",
|
"integrity": "sha512-4rBoHpggSohayE+Os7lKdbsHTw7m/uZRKYjk9DN6cKBhQIjdiULdcG+b4b5CMVZSqZDHPgT70uWGI7yqkn8Ufw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@floating-ui/react": "^0.27.19",
|
"@floating-ui/react": "^0.27.19",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"react-number-format": "^5.4.5",
|
"react-number-format": "^5.4.5",
|
||||||
"react-remove-scroll": "^2.7.2",
|
"react-remove-scroll": "^2.7.2",
|
||||||
"type-fest": "^5.7.0"
|
"type-fest": "^5.6.0"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@mantine/hooks": "9.4.1",
|
"@mantine/hooks": "9.3.1",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
"react-dom": "^19.2.0"
|
"react-dom": "^19.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@mantine/dates": {
|
"node_modules/@mantine/dates": {
|
||||||
"version": "9.4.1",
|
"version": "9.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/@mantine/dates/-/dates-9.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/@mantine/dates/-/dates-9.3.1.tgz",
|
||||||
"integrity": "sha512-DoQDvQMAlIw6ohwhUwYuTYQevG9y5AQmYWkhOHUuavABFEZmtBglkwziBoATvxT09I/6I56UMPhproXcS6XUfg==",
|
"integrity": "sha512-Nh4XQyyV1AM0XRnUJugb1kNfCm++nkticsO8aroKmFPZ7cpGV7cjdL+4MJNPu1atS1EUePXl2VLLpKnrclpqOQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"clsx": "^2.1.1"
|
"clsx": "^2.1.1"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@mantine/core": "9.4.1",
|
"@mantine/core": "9.3.1",
|
||||||
"@mantine/hooks": "9.4.1",
|
"@mantine/hooks": "9.3.1",
|
||||||
"dayjs": ">=1.0.0",
|
"dayjs": ">=1.0.0",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
"react-dom": "^19.2.0"
|
"react-dom": "^19.2.0"
|
||||||
|
|
@ -734,65 +672,51 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@mantine/hooks": {
|
"node_modules/@mantine/hooks": {
|
||||||
"version": "9.4.1",
|
"version": "9.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-9.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-9.3.1.tgz",
|
||||||
"integrity": "sha512-eTI8wmzPx3r98zgKIEuvukmoGTHBhmtI6+9E6o2DbTmEU2eM1bCdjE2vFdf0op2AlRO0KEYEcZhNQi4T/SJk0A==",
|
"integrity": "sha512-zAOlxV59j5CDgAnExN+ypaR6dVW1vwMKDvKUxIlUVd/e52qxYnPyYRD+shJmyOLaZRuQmVF0R/7mJAjt2jw9cA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react": "^19.2.0"
|
"react": "^19.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@mantine/modals": {
|
"node_modules/@mantine/modals": {
|
||||||
"version": "9.4.1",
|
"version": "9.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/@mantine/modals/-/modals-9.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/@mantine/modals/-/modals-9.3.1.tgz",
|
||||||
"integrity": "sha512-z5G3Biz7/5Ybz5Z8u5Xyvo9UBmFhAX/YXMf6U96ejvtAB11xVnCo8m37R5DJyzeFEqB4D1tvUgWiVVPBb+yadw==",
|
"integrity": "sha512-JqP1o6hrfQJ5UCq97HJsI7uIPDy+WwvWwkkfctWqcYkFJA2DU8dVoPqvEhnhDQUIXNci3sx6XDoQZAq1Qg57mw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@mantine/core": "9.4.1",
|
"@mantine/core": "9.3.1",
|
||||||
"@mantine/hooks": "9.4.1",
|
"@mantine/hooks": "9.3.1",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
"react-dom": "^19.2.0"
|
"react-dom": "^19.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@mantine/notifications": {
|
"node_modules/@mantine/notifications": {
|
||||||
"version": "9.4.1",
|
"version": "9.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/@mantine/notifications/-/notifications-9.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/@mantine/notifications/-/notifications-9.3.1.tgz",
|
||||||
"integrity": "sha512-Sm1g8E8RkFmesxpNz9zFvOjkTVxOa7dJJjMGoHNIXH+9/wO0s9kInny4mVnxTbLJJsD6nTqIQlk1v8tq2C4Ftw==",
|
"integrity": "sha512-irkD9uszgVftthbCLd+4lS7M1jkhL4sVrZASv8+43aIkncW+oQkCFpBuaOAf6uRcMjmQ7XnKs2O8bXYzl/DqgQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@mantine/store": "9.4.1",
|
"@mantine/store": "9.3.1",
|
||||||
"react-transition-group": "4.4.5"
|
"react-transition-group": "4.4.5"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@mantine/core": "9.4.1",
|
"@mantine/core": "9.3.1",
|
||||||
"@mantine/hooks": "9.4.1",
|
"@mantine/hooks": "9.3.1",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
"react-dom": "^19.2.0"
|
"react-dom": "^19.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@mantine/store": {
|
"node_modules/@mantine/store": {
|
||||||
"version": "9.4.1",
|
"version": "9.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/@mantine/store/-/store-9.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/@mantine/store/-/store-9.3.1.tgz",
|
||||||
"integrity": "sha512-/DCZq0aqqIdm03J0RJ7pbzoau2cwY8ndSOjskHOKHhTeWMnOBdCKXA3oMO5aIDldDqJ9T7Io4Boh4Pt461zNQw==",
|
"integrity": "sha512-UZ8wGKfF/NFMHCDl1Rd0M8XtHdt4W1w3V4ohNpFSaP3nSjJ+Cu1FT+iIWtXwC0Ogha8XnuVQ7vm/dw2BUfpw+g==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react": "^19.2.0"
|
"react": "^19.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@mantine/tiptap": {
|
|
||||||
"version": "9.4.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@mantine/tiptap/-/tiptap-9.4.1.tgz",
|
|
||||||
"integrity": "sha512-0qN6SFh9BuwXNOHUf4ygx8LPvWcgU1zUULY7IJ9zKiVHfa1K6b0BRa8LpLVKtVv7K5NLyj2uHJwv+mXB+ypOJw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"peerDependencies": {
|
|
||||||
"@mantine/core": "9.4.1",
|
|
||||||
"@mantine/hooks": "9.4.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": {
|
"node_modules/@napi-rs/wasm-runtime": {
|
||||||
"version": "1.1.5",
|
"version": "1.1.5",
|
||||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz",
|
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz",
|
||||||
|
|
@ -1187,435 +1111,6 @@
|
||||||
"react": "^18 || ^19"
|
"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": {
|
"node_modules/@tybys/wasm-util": {
|
||||||
"version": "0.10.2",
|
"version": "0.10.2",
|
||||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz",
|
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz",
|
||||||
|
|
@ -1749,6 +1244,7 @@
|
||||||
"version": "19.2.17",
|
"version": "19.2.17",
|
||||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
|
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
|
||||||
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
|
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
|
||||||
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"csstype": "^3.2.2"
|
"csstype": "^3.2.2"
|
||||||
|
|
@ -1758,6 +1254,7 @@
|
||||||
"version": "19.2.3",
|
"version": "19.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
|
||||||
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
|
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@types/react": "^19.2.0"
|
"@types/react": "^19.2.0"
|
||||||
|
|
@ -2811,15 +2308,6 @@
|
||||||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||||
"license": "MIT"
|
"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": {
|
"node_modules/fast-json-stable-stringify": {
|
||||||
"version": "2.1.0",
|
"version": "2.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
|
||||||
|
|
@ -3563,12 +3051,6 @@
|
||||||
"url": "https://opencollective.com/parcel"
|
"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": {
|
"node_modules/locate-path": {
|
||||||
"version": "6.0.0",
|
"version": "6.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
|
||||||
|
|
@ -3728,12 +3210,6 @@
|
||||||
"node": ">= 0.8.0"
|
"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": {
|
"node_modules/p-limit": {
|
||||||
"version": "3.1.0",
|
"version": "3.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
|
||||||
|
|
@ -3856,145 +3332,6 @@
|
||||||
"react-is": "^16.13.1"
|
"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": {
|
"node_modules/proxy-from-env": {
|
||||||
"version": "2.1.0",
|
"version": "2.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
|
||||||
|
|
@ -4282,12 +3619,6 @@
|
||||||
"@rolldown/binding-win32-x64-msvc": "1.0.3"
|
"@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": {
|
"node_modules/scheduler": {
|
||||||
"version": "0.27.0",
|
"version": "0.27.0",
|
||||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
|
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
|
||||||
|
|
@ -4681,12 +4012,6 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"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": {
|
"node_modules/which": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||||
|
|
|
||||||
19
package.json
19
package.json
|
|
@ -10,23 +10,14 @@
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@mantine/core": "^9.3.1",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@mantine/dates": "^9.3.1",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
|
||||||
"@mantine/core": "^9.4.1",
|
|
||||||
"@mantine/dates": "^9.4.1",
|
|
||||||
"@mantine/form": "^9.3.1",
|
"@mantine/form": "^9.3.1",
|
||||||
"@mantine/hooks": "^9.4.1",
|
"@mantine/hooks": "^9.3.1",
|
||||||
"@mantine/modals": "^9.4.1",
|
"@mantine/modals": "^9.3.1",
|
||||||
"@mantine/notifications": "^9.4.1",
|
"@mantine/notifications": "^9.3.1",
|
||||||
"@mantine/tiptap": "^9.4.1",
|
|
||||||
"@tabler/icons-react": "^3.44.0",
|
"@tabler/icons-react": "^3.44.0",
|
||||||
"@tanstack/react-query": "^5.101.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",
|
"axios": "^1.18.0",
|
||||||
"crypto-js": "^4.2.0",
|
"crypto-js": "^4.2.0",
|
||||||
"dayjs": "^1.11.21",
|
"dayjs": "^1.11.21",
|
||||||
|
|
|
||||||
19591
react_code.txt
19591
react_code.txt
File diff suppressed because it is too large
Load Diff
25
src/App.tsx
25
src/App.tsx
|
|
@ -7,22 +7,18 @@ import RolesPage from './pages/roles/RolesPage'
|
||||||
import ApprovalsPage from './pages/approvals/ApprovalsPage'
|
import ApprovalsPage from './pages/approvals/ApprovalsPage'
|
||||||
import { useAuth } from './hooks/useAuth'
|
import { useAuth } from './hooks/useAuth'
|
||||||
import { Loader, Center, Text } from '@mantine/core'
|
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 PermissionsPage from './pages/permissions/PermissionsPage'
|
||||||
import HierarchiesPage from './pages/hierarchies/HierarchiesPage'
|
import HierarchiesPage from './pages/hierarchies/HierarchiesPage'
|
||||||
import TopicExecutorsPage from "@/pages/topicExecutors/TopicExecutorsPage.tsx"
|
import TopicExecutorsPage from "@/pages/topicExecutors/TopicExecutorsPage.tsx";
|
||||||
import CategoriesPage from "@/pages/categories/CategoriesPage.tsx"
|
import CategoriesPage from "@/pages/categories/CategoriesPage.tsx";
|
||||||
import React from "react"
|
import React from "react";
|
||||||
import TopicsPage from "@/pages/topics/TopicsPage.tsx"
|
import TopicsPage from "@/pages/topics/TopicsPage.tsx";
|
||||||
import SettingsPage from './pages/settings/SettingsPage'
|
import SettingsPage from './pages/settings/SettingsPage'
|
||||||
import AdminsPage from './pages/admins/AdminsPage'
|
import AdminsPage from './pages/admins/AdminsPage'
|
||||||
import ApprovalTasksPage from './pages/approvalTasks/ApprovalTasksPage'
|
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 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 TelegramManagersPage from "@/pages/telegramManagers/TelegramManagersPage.tsx";
|
|
||||||
|
|
||||||
const Placeholder = ({ title }: { title: string }) => (
|
const Placeholder = ({ title }: { title: string }) => (
|
||||||
<div style={{ padding: 40 }}>
|
<div style={{ padding: 40 }}>
|
||||||
|
|
@ -55,12 +51,11 @@ function App() {
|
||||||
<Route path="/login" element={<Login />} />
|
<Route path="/login" element={<Login />} />
|
||||||
|
|
||||||
<Route element={<ProtectedRoute><MainLayout /></ProtectedRoute>}>
|
<Route element={<ProtectedRoute><MainLayout /></ProtectedRoute>}>
|
||||||
<Route path="/" element={<Placeholder title="Главная" />} />
|
<Route path="/" element={<Placeholder title="Главная" /> } />
|
||||||
<Route path="/notifications" element={<NotificationsPage />} />
|
<Route path="/notifications" element={<Placeholder title="Уведомления" /> } />
|
||||||
<Route path="/approval-dash" element={<Dashboard />} />
|
<Route path="/approval-dash" element={<Dashboard />} />
|
||||||
<Route path="/nodes" element={<FlowTreePage />} />
|
<Route path="/nodes" element={<FlowTreePage/>} />
|
||||||
<Route path="/users" element={<UsersPage />} />
|
<Route path="/users" element={<UsersPage />} />
|
||||||
<Route path="/monthly-orders-settings" element={<MonthlyOrdersSettingsPage />} />
|
|
||||||
<Route path="/departments" element={<DepartmentsPage />} />
|
<Route path="/departments" element={<DepartmentsPage />} />
|
||||||
<Route path="/roles" element={<RolesPage />} />
|
<Route path="/roles" element={<RolesPage />} />
|
||||||
<Route path="/approvals" element={<ApprovalsPage />} />
|
<Route path="/approvals" element={<ApprovalsPage />} />
|
||||||
|
|
@ -71,10 +66,8 @@ function App() {
|
||||||
<Route path="/hierarchies" element={<HierarchiesPage />} />
|
<Route path="/hierarchies" element={<HierarchiesPage />} />
|
||||||
<Route path="/settings" element={<SettingsPage />} />
|
<Route path="/settings" element={<SettingsPage />} />
|
||||||
<Route path="/admins" element={<AdminsPage />} />
|
<Route path="/admins" element={<AdminsPage />} />
|
||||||
<Route path="/logs" element={<AdminLogsPage />} />
|
|
||||||
<Route path="/approval-tasks" element={<ApprovalTasksPage />} />
|
<Route path="/approval-tasks" element={<ApprovalTasksPage />} />
|
||||||
<Route path="/guide/flow-trees" element={<FlowTreeGuidePage />} />
|
<Route path="/guide/flow-trees" element={<FlowTreeGuidePage />} />
|
||||||
<Route path="/telegram-managers" element={<TelegramManagersPage />} />
|
|
||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
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,9 +12,6 @@ export interface CreateAdminRequest {
|
||||||
login: string
|
login: string
|
||||||
name?: string
|
name?: string
|
||||||
is_root?: boolean
|
is_root?: boolean
|
||||||
is_observer?: boolean // 🆕
|
|
||||||
is_analyst?: boolean
|
|
||||||
telegram_id?: number // 🆕
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateAdminRequest {
|
export interface UpdateAdminRequest {
|
||||||
|
|
@ -22,9 +19,6 @@ export interface UpdateAdminRequest {
|
||||||
name?: string
|
name?: string
|
||||||
is_blocked?: boolean
|
is_blocked?: boolean
|
||||||
is_root?: boolean
|
is_root?: boolean
|
||||||
is_observer?: boolean // 🆕
|
|
||||||
is_analyst?: boolean
|
|
||||||
telegram_id?: number | null // 🆕
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const adminsApi = {
|
export const adminsApi = {
|
||||||
|
|
|
||||||
|
|
@ -1,39 +1,13 @@
|
||||||
import apiClient from './client'
|
import apiClient from './client'
|
||||||
import type { Approval, ApiResponse } from '@/types/api'
|
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 {
|
export interface ApprovalsListParams {
|
||||||
offset?: number
|
offset?: number
|
||||||
limit?: number
|
limit?: number
|
||||||
id?: number
|
|
||||||
status?: string
|
status?: string
|
||||||
initiator_id?: number
|
initiator_id?: number
|
||||||
topic_id?: number // одиночный (для обратной совместимости)
|
topic_id?: number
|
||||||
topic_ids?: number[] // 🆕 множественный выбор тем
|
|
||||||
category_ids?: number[] // 🆕 множественный выбор категорий
|
|
||||||
department_id?: number
|
department_id?: number
|
||||||
date_from?: string // 🆕 YYYY-MM-DD
|
|
||||||
date_to?: string // 🆕 YYYY-MM-DD
|
|
||||||
content?: string
|
content?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -51,31 +25,8 @@ export interface UpdateApprovalRequest {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const approvalsApi = {
|
export const approvalsApi = {
|
||||||
getList: (params: ApprovalsListParams = {}) => {
|
getList: (params: ApprovalsListParams = {}) =>
|
||||||
// Формируем query-параметры, корректно сериализуя массивы
|
apiClient.get<ApiResponse<Approval[]>>('/approvals', { params }),
|
||||||
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) =>
|
getById: (id: number) =>
|
||||||
apiClient.get<Approval>(`/approvals/${id}`),
|
apiClient.get<Approval>(`/approvals/${id}`),
|
||||||
|
|
@ -86,9 +37,7 @@ export const approvalsApi = {
|
||||||
delete: (id: number) =>
|
delete: (id: number) =>
|
||||||
apiClient.delete<boolean>('/approvals', { data: { id } }),
|
apiClient.delete<boolean>('/approvals', { data: { id } }),
|
||||||
|
|
||||||
getTasks: (approvalId: number) =>
|
// 🆕 Получение заявок для отчёта (с фильтрами по датам)
|
||||||
apiClient.get<ApiResponse<ApprovalTasksResponse>>(`/approvals/${approvalId}/tasks`),
|
|
||||||
|
|
||||||
getForReport: (params: ApprovalsReportParams = {}) =>
|
getForReport: (params: ApprovalsReportParams = {}) =>
|
||||||
apiClient.get<ApiResponse<Approval[]>>('/approvals/report', { params }),
|
apiClient.get<ApiResponse<Approval[]>>('/approvals/report', { params }),
|
||||||
|
|
||||||
|
|
@ -97,41 +46,30 @@ export const approvalsApi = {
|
||||||
params,
|
params,
|
||||||
responseType: 'blob',
|
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) =>
|
getFile: (approvalId: number, fileId: number) =>
|
||||||
apiClient.get(`/approvals/${approvalId}/files/${fileId}`, {
|
apiClient.get(`/approvals/${approvalId}/files/${fileId}`, {
|
||||||
responseType: 'blob',
|
responseType: 'blob',
|
||||||
}),
|
}),
|
||||||
|
|
||||||
downloadFile: (approvalId: number, fileId: number, fileName: string) => {
|
downloadFile: (approvalId: number, fileId: number, fileName: string) => {
|
||||||
const token = localStorage.getItem('token')
|
const token = localStorage.getItem('token')
|
||||||
|
const apiKey = import.meta.env.VITE_API_KEY
|
||||||
const timestamp = Math.floor(Date.now() / 1000).toString()
|
const timestamp = Math.floor(Date.now() / 1000).toString()
|
||||||
const deviceId = localStorage.getItem('device_id') || 'admin-panel'
|
const deviceId = localStorage.getItem('device_id') || 'admin-panel'
|
||||||
|
|
||||||
|
// Генерируем HMAC подпись (как в client.ts)
|
||||||
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
||||||
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
|
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
|
||||||
const message = publicKey + ":" + timestamp
|
const message = publicKey + ":" + timestamp
|
||||||
const signature = CryptoJS.HmacSHA256(message, privateKey).toString(CryptoJS.enc.Hex)
|
const signature = CryptoJS.HmacSHA256(message, privateKey).toString(CryptoJS.enc.Hex)
|
||||||
|
|
||||||
|
// Создаём URL с query параметрами
|
||||||
const url = `${apiClient.defaults.baseURL}/approvals/${approvalId}/files/${fileId}/download`
|
const url = `${apiClient.defaults.baseURL}/approvals/${approvalId}/files/${fileId}/download`
|
||||||
|
|
||||||
const link = document.createElement('a')
|
const link = document.createElement('a')
|
||||||
link.href = `${url}?_t=${timestamp}`
|
link.href = `${url}?_t=${timestamp}`
|
||||||
link.setAttribute('download', fileName)
|
link.setAttribute('download', fileName)
|
||||||
|
|
||||||
|
// Добавляем заголовки через fetch
|
||||||
fetch(url, {
|
fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: {
|
headers: {
|
||||||
|
|
@ -156,44 +94,3 @@ 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,11 +1,5 @@
|
||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
import CryptoJS from 'crypto-js'
|
import CryptoJS from 'crypto-js'
|
||||||
import { timeApi } from './time'
|
|
||||||
|
|
||||||
// 🔄 Offset между клиентом и сервером (в секундах)
|
|
||||||
let serverTimeOffset = 0
|
|
||||||
let isSyncing = false
|
|
||||||
let syncPromise: Promise<void> | null = null
|
|
||||||
|
|
||||||
// Функция генерации HMAC подписи
|
// Функция генерации HMAC подписи
|
||||||
function generateHmacSignature(publicKey: string, timestamp: string, privateKey: string): string {
|
function generateHmacSignature(publicKey: string, timestamp: string, privateKey: string): string {
|
||||||
|
|
@ -18,60 +12,36 @@ function generateHmacSignature(publicKey: string, timestamp: string, privateKey:
|
||||||
function getOrCreateDeviceId(): string {
|
function getOrCreateDeviceId(): string {
|
||||||
let deviceId = localStorage.getItem('device_id')
|
let deviceId = localStorage.getItem('device_id')
|
||||||
|
|
||||||
|
console.log('[DeviceID] Checking localStorage:', {
|
||||||
|
exists: !!deviceId,
|
||||||
|
value: deviceId || 'null'
|
||||||
|
})
|
||||||
|
|
||||||
if (!deviceId) {
|
if (!deviceId) {
|
||||||
deviceId = crypto.randomUUID()
|
deviceId = crypto.randomUUID()
|
||||||
localStorage.setItem('device_id', deviceId)
|
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
|
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({
|
const apiClient = axios.create({
|
||||||
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
baseURL: '/api',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
// Interceptor для добавления токена и HMAC подписи
|
// Interceptor для добавления токена и HMAC подписи
|
||||||
apiClient.interceptors.request.use(async (config) => {
|
apiClient.interceptors.request.use((config) => {
|
||||||
console.log('[API] === Request interceptor started ===')
|
console.log('[API] === Request interceptor started ===')
|
||||||
|
|
||||||
// Добавляем JWT токен, если есть
|
// Добавляем JWT токен, если есть
|
||||||
|
|
@ -81,10 +51,10 @@ apiClient.interceptors.request.use(async (config) => {
|
||||||
console.log('[API] ✅ Added JWT token')
|
console.log('[API] ✅ Added JWT token')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Генерируем HMAC подпись с скорректированным timestamp
|
// Генерируем HMAC подпись
|
||||||
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
||||||
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
|
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
|
||||||
const timestamp = getCorrectedTimestamp()
|
const timestamp = Math.floor(Date.now() / 1000).toString()
|
||||||
|
|
||||||
if (!publicKey || !privateKey) {
|
if (!publicKey || !privateKey) {
|
||||||
console.error('[API] ❌ Missing API keys in .env!')
|
console.error('[API] ❌ Missing API keys in .env!')
|
||||||
|
|
@ -96,12 +66,11 @@ apiClient.interceptors.request.use(async (config) => {
|
||||||
|
|
||||||
config.headers['X-Timestamp'] = timestamp
|
config.headers['X-Timestamp'] = timestamp
|
||||||
|
|
||||||
// Получаем или создаём device_id
|
// 🆕 Получаем или создаём device_id
|
||||||
const deviceId = getOrCreateDeviceId()
|
const deviceId = getOrCreateDeviceId()
|
||||||
config.headers['x-device-id'] = deviceId
|
config.headers['x-device-id'] = deviceId
|
||||||
|
|
||||||
console.log('[API] ✅ Added device_id:', deviceId)
|
console.log('[API] ✅ Added device_id:', deviceId)
|
||||||
console.log('[API] 🕐 Using timestamp:', timestamp, 'offset:', serverTimeOffset)
|
|
||||||
console.log('[API] === Request interceptor finished ===')
|
console.log('[API] === Request interceptor finished ===')
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
@ -113,7 +82,7 @@ apiClient.interceptors.response.use(
|
||||||
console.log('[API] ✅ Response success:', response.config.url)
|
console.log('[API] ✅ Response success:', response.config.url)
|
||||||
return response
|
return response
|
||||||
},
|
},
|
||||||
async (error) => {
|
(error) => {
|
||||||
console.error('[API] ❌ Response error:', {
|
console.error('[API] ❌ Response error:', {
|
||||||
status: error.response?.status,
|
status: error.response?.status,
|
||||||
statusText: error.response?.statusText,
|
statusText: error.response?.statusText,
|
||||||
|
|
@ -121,47 +90,14 @@ apiClient.interceptors.response.use(
|
||||||
url: error.config?.url,
|
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) {
|
if (error.response?.status === 401) {
|
||||||
console.warn('[API] ⚠️ Unauthorized, redirecting to login')
|
console.warn('[API] ⚠️ Unauthorized, redirecting to login')
|
||||||
localStorage.removeItem('token')
|
localStorage.removeItem('token')
|
||||||
|
// НЕ удаляем device_id!
|
||||||
window.location.href = '/login'
|
window.location.href = '/login'
|
||||||
}
|
}
|
||||||
return Promise.reject(error)
|
return Promise.reject(error)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
// 🆕 Синхронизируем время при загрузке модуля
|
|
||||||
syncTimeWithServer()
|
|
||||||
|
|
||||||
// 🆕 Периодическая синхронизация каждые 5 минут
|
|
||||||
setInterval(() => {
|
|
||||||
syncTimeWithServer()
|
|
||||||
}, 5 * 60 * 1000)
|
|
||||||
|
|
||||||
export default apiClient
|
export default apiClient
|
||||||
|
|
@ -10,45 +10,21 @@ export interface DashboardStats {
|
||||||
executors: number
|
executors: number
|
||||||
statusData: Array<{ status: string; count: number }>
|
statusData: Array<{ status: string; count: number }>
|
||||||
dailyData: Array<{ date: string; created: number; approved: number }>
|
dailyData: Array<{ date: string; created: number; approved: number }>
|
||||||
categoryBreakdown: Array<{
|
topTopics: Array<{
|
||||||
id: number
|
id: number
|
||||||
name: string
|
name: string
|
||||||
|
category_name: string
|
||||||
total_count: number
|
total_count: number
|
||||||
pending_count: number
|
pending_count: number
|
||||||
}>
|
}>
|
||||||
bottleneckApprovers: Array<{
|
topApprovers: Array<{
|
||||||
user_id: number
|
user_id: number
|
||||||
full_name: string
|
full_name: string
|
||||||
department_name: string
|
department_name: string
|
||||||
pending_total: number
|
total_steps: number
|
||||||
overdue_count: number
|
pending_steps: number
|
||||||
}>
|
}>
|
||||||
oldPendingCount: 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 = {
|
export const dashboardApi = {
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import apiClient from './client'
|
||||||
import type { ApprovalFlowNode, ApiResponse } from '@/types/api'
|
import type { ApprovalFlowNode, ApiResponse } from '@/types/api'
|
||||||
|
|
||||||
export interface CreateFlowNodeRequest {
|
export interface CreateFlowNodeRequest {
|
||||||
category_id: number
|
topic_id: number
|
||||||
parent_id?: number | null
|
parent_id?: number | null
|
||||||
key: string
|
key: string
|
||||||
label: string
|
label: string
|
||||||
|
|
@ -15,14 +15,12 @@ export interface CreateFlowNodeRequest {
|
||||||
multi_select_key?: string | null
|
multi_select_key?: string | null
|
||||||
multi_select_value?: string | null
|
multi_select_value?: string | null
|
||||||
topic_code?: string | null
|
topic_code?: string | null
|
||||||
message_template?: string | null
|
|
||||||
code_template?: string | null
|
|
||||||
sort_order?: number
|
sort_order?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateFlowNodeRequest {
|
export interface UpdateFlowNodeRequest {
|
||||||
id: number
|
id: number
|
||||||
category_id?: number
|
topic_id?: number
|
||||||
parent_id?: number | null
|
parent_id?: number | null
|
||||||
key?: string
|
key?: string
|
||||||
label?: string
|
label?: string
|
||||||
|
|
@ -35,8 +33,6 @@ export interface UpdateFlowNodeRequest {
|
||||||
multi_select_key?: string | null
|
multi_select_key?: string | null
|
||||||
multi_select_value?: string | null
|
multi_select_value?: string | null
|
||||||
topic_code?: string | null
|
topic_code?: string | null
|
||||||
message_template?: string | null
|
|
||||||
code_template?: string | null
|
|
||||||
sort_order?: number
|
sort_order?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -49,26 +45,9 @@ export interface SaveTreeRequest {
|
||||||
nodes: ApprovalFlowNode[]
|
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 = {
|
export const flowNodesApi = {
|
||||||
getTree: (categoryId: number) =>
|
getTree: (topicId: number) =>
|
||||||
apiClient.get<ApiResponse<ApprovalFlowNode[]>>(`/flow-nodes/category/${categoryId}?limit=1000`),
|
apiClient.get<ApiResponse<ApprovalFlowNode[]>>(`/flow-nodes/topic/${topicId}`),
|
||||||
|
|
||||||
getById: (id: number) =>
|
getById: (id: number) =>
|
||||||
apiClient.get<ApprovalFlowNode>(`/flow-nodes/${id}`),
|
apiClient.get<ApprovalFlowNode>(`/flow-nodes/${id}`),
|
||||||
|
|
@ -82,19 +61,12 @@ export const flowNodesApi = {
|
||||||
delete: (id: number) =>
|
delete: (id: number) =>
|
||||||
apiClient.delete<boolean>('/flow-nodes/', { data: { id } }),
|
apiClient.delete<boolean>('/flow-nodes/', { data: { id } }),
|
||||||
|
|
||||||
saveTree: (categoryId: number, data: SaveTreeRequest) =>
|
saveTree: (topicId: number, data: SaveTreeRequest) =>
|
||||||
apiClient.post<boolean>(`/flow-nodes/category/${categoryId}/tree`, data),
|
apiClient.post<boolean>(`/flow-nodes/topic/${topicId}/tree`, data),
|
||||||
|
|
||||||
move: (id: number, data: MoveFlowNodeRequest) =>
|
move: (id: number, data: MoveFlowNodeRequest) =>
|
||||||
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/move`, data),
|
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/move`, data),
|
||||||
|
|
||||||
duplicate: (id: number) =>
|
duplicate: (id: number) =>
|
||||||
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/duplicate`, {}),
|
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,9 +9,8 @@ export interface HierarchiesListParams {
|
||||||
department_id?: number
|
department_id?: number
|
||||||
topic_category_id?: number
|
topic_category_id?: number
|
||||||
topic_id?: number
|
topic_id?: number
|
||||||
target_system?: string | null
|
|
||||||
user_status?: 'active' | 'fired' | 'blocked'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateHierarchyRequest {
|
export interface CreateHierarchyRequest {
|
||||||
subordinate_id: number
|
subordinate_id: number
|
||||||
approver_id: number
|
approver_id: number
|
||||||
|
|
@ -19,7 +18,6 @@ export interface CreateHierarchyRequest {
|
||||||
topic_category_id?: number | null
|
topic_category_id?: number | null
|
||||||
topic_id?: number | null
|
topic_id?: number | null
|
||||||
priority?: number
|
priority?: number
|
||||||
target_system?: string | null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateHierarchyRequest {
|
export interface UpdateHierarchyRequest {
|
||||||
|
|
@ -30,7 +28,6 @@ export interface UpdateHierarchyRequest {
|
||||||
topic_category_id?: number | null
|
topic_category_id?: number | null
|
||||||
topic_id?: number | null
|
topic_id?: number | null
|
||||||
priority?: number
|
priority?: number
|
||||||
target_system?: string | null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const hierarchiesApi = {
|
export const hierarchiesApi = {
|
||||||
|
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
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),
|
|
||||||
}
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
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,7 +9,6 @@ export interface RolesListParams {
|
||||||
is_approver?: boolean
|
is_approver?: boolean
|
||||||
is_observer?: boolean
|
is_observer?: boolean
|
||||||
is_executor?: boolean
|
is_executor?: boolean
|
||||||
is_controller?: boolean
|
|
||||||
name?: string
|
name?: string
|
||||||
code?: string
|
code?: string
|
||||||
}
|
}
|
||||||
|
|
@ -23,7 +22,6 @@ export interface CreateRoleRequest {
|
||||||
is_approver?: boolean
|
is_approver?: boolean
|
||||||
is_observer?: boolean
|
is_observer?: boolean
|
||||||
is_executor?: boolean
|
is_executor?: boolean
|
||||||
is_controller?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateRoleRequest {
|
export interface UpdateRoleRequest {
|
||||||
|
|
@ -36,7 +34,6 @@ export interface UpdateRoleRequest {
|
||||||
is_approver?: boolean
|
is_approver?: boolean
|
||||||
is_observer?: boolean
|
is_observer?: boolean
|
||||||
is_executor?: boolean
|
is_executor?: boolean
|
||||||
is_controller?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const rolesApi = {
|
export const rolesApi = {
|
||||||
|
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
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 }),
|
|
||||||
}
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
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,7 +25,6 @@ export interface CreateTopicRequest {
|
||||||
allow_approver_selection?: boolean
|
allow_approver_selection?: boolean
|
||||||
first_approver_role_code?: string | null
|
first_approver_role_code?: string | null
|
||||||
allow_observer_selection?: boolean
|
allow_observer_selection?: boolean
|
||||||
allow_delegation_selection?: boolean
|
|
||||||
approval_mode?: string
|
approval_mode?: string
|
||||||
require_approver_comment?: boolean
|
require_approver_comment?: boolean
|
||||||
requires_file?: boolean
|
requires_file?: boolean
|
||||||
|
|
@ -50,8 +49,6 @@ export interface UpdateTopicRequest {
|
||||||
allow_approver_selection?: boolean
|
allow_approver_selection?: boolean
|
||||||
first_approver_role_code?: string | null
|
first_approver_role_code?: string | null
|
||||||
allow_observer_selection?: boolean
|
allow_observer_selection?: boolean
|
||||||
// 🆕 см. CreateTopicRequest.allow_delegation_selection
|
|
||||||
allow_delegation_selection?: boolean
|
|
||||||
approval_mode?: string
|
approval_mode?: string
|
||||||
require_approver_comment?: boolean
|
require_approver_comment?: boolean
|
||||||
requires_file?: boolean
|
requires_file?: boolean
|
||||||
|
|
|
||||||
|
|
@ -8,27 +8,25 @@ export interface UsersListParams {
|
||||||
is_fired?: boolean
|
is_fired?: boolean
|
||||||
department_id?: number
|
department_id?: number
|
||||||
full_name?: string
|
full_name?: string
|
||||||
role_ids?: number[]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateUserRequest {
|
export interface UpdateUserRequest {
|
||||||
id: number
|
id: number
|
||||||
full_name?: string
|
|
||||||
department_id?: number | null
|
department_id?: number | null
|
||||||
is_blocked?: boolean
|
is_blocked?: boolean
|
||||||
is_fired?: boolean
|
is_fired?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export const usersApi = {
|
export const usersApi = {
|
||||||
|
// Получить список пользователей с пагинацией и фильтрами
|
||||||
getList: (params: UsersListParams = {}) =>
|
getList: (params: UsersListParams = {}) =>
|
||||||
apiClient.get<ApiResponse<User[]>>('/users', { params }),
|
apiClient.get<ApiResponse<User[]>>('/users', { params }),
|
||||||
|
|
||||||
|
// Получить пользователя по ID
|
||||||
getById: (id: number) =>
|
getById: (id: number) =>
|
||||||
apiClient.get<User>(`/users/${id}`),
|
apiClient.get<User>(`/users/${id}`),
|
||||||
|
|
||||||
|
// Обновить пользователя
|
||||||
update: (data: UpdateUserRequest) =>
|
update: (data: UpdateUserRequest) =>
|
||||||
apiClient.put<User>('/users', data),
|
apiClient.put<User>('/users', data),
|
||||||
|
|
||||||
delete: (id: number) =>
|
|
||||||
apiClient.delete(`/users/${id}`),
|
|
||||||
}
|
}
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
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 }),
|
|
||||||
}
|
|
||||||
|
|
@ -1,123 +0,0 @@
|
||||||
import { useState } from 'react'
|
|
||||||
import {
|
|
||||||
Modal,
|
|
||||||
Stack,
|
|
||||||
TextInput,
|
|
||||||
Text,
|
|
||||||
Button,
|
|
||||||
Group,
|
|
||||||
Loader,
|
|
||||||
Center,
|
|
||||||
Paper,
|
|
||||||
Badge,
|
|
||||||
ScrollArea,
|
|
||||||
Box,
|
|
||||||
} from '@mantine/core'
|
|
||||||
import { IconSearch, IconCopy } from '@tabler/icons-react'
|
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
|
||||||
|
|
||||||
interface CopyRolesModalProps {
|
|
||||||
opened: boolean
|
|
||||||
onClose: () => void
|
|
||||||
onCopy: (roleIds: number[]) => void
|
|
||||||
currentUserId: number | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function CopyRolesModal({ opened, onClose, onCopy, currentUserId }: CopyRolesModalProps) {
|
|
||||||
const [search, setSearch] = useState('')
|
|
||||||
const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
|
|
||||||
|
|
||||||
const { data, isLoading } = useUsers({
|
|
||||||
offset: 0,
|
|
||||||
limit: 100,
|
|
||||||
...(search && { full_name: search }),
|
|
||||||
})
|
|
||||||
|
|
||||||
const users = Array.isArray(data?.data) ? data.data : []
|
|
||||||
|
|
||||||
const handleSelectUser = (userId: number) => {
|
|
||||||
setSelectedUserId(userId)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleCopy = () => {
|
|
||||||
if (!selectedUserId) return
|
|
||||||
|
|
||||||
const selectedUser = users.find(u => u.id === selectedUserId)
|
|
||||||
if (selectedUser && Array.isArray(selectedUser.user_roles)) {
|
|
||||||
const roleIds = selectedUser.user_roles
|
|
||||||
.map(ur => ur.role_id)
|
|
||||||
.filter((id): id is number => !!id)
|
|
||||||
onCopy(roleIds)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal
|
|
||||||
opened={opened}
|
|
||||||
onClose={onClose}
|
|
||||||
title="Скопировать роли от пользователя"
|
|
||||||
size="md"
|
|
||||||
>
|
|
||||||
<Stack gap="md">
|
|
||||||
<TextInput
|
|
||||||
placeholder="Поиск по имени..."
|
|
||||||
leftSection={<IconSearch size={16} />}
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.currentTarget.value)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<Center p={40}>
|
|
||||||
<Loader />
|
|
||||||
</Center>
|
|
||||||
) : (
|
|
||||||
<ScrollArea.Autosize mah={400}>
|
|
||||||
<Stack gap="xs">
|
|
||||||
{users
|
|
||||||
.filter(u => u.id !== currentUserId)
|
|
||||||
.map((user) => (
|
|
||||||
<Paper
|
|
||||||
key={user.id}
|
|
||||||
withBorder
|
|
||||||
p="sm"
|
|
||||||
style={{
|
|
||||||
cursor: 'pointer',
|
|
||||||
backgroundColor: selectedUserId === user.id
|
|
||||||
? 'var(--mantine-color-blue-0)'
|
|
||||||
: undefined,
|
|
||||||
}}
|
|
||||||
onClick={() => handleSelectUser(user.id!)}
|
|
||||||
>
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Box>
|
|
||||||
<Text fw={500} size="sm">{user.full_name}</Text>
|
|
||||||
<Text size="xs" c="dimmed">
|
|
||||||
{user.username ? `@${user.username}` : user.telegram_id}
|
|
||||||
</Text>
|
|
||||||
</Box>
|
|
||||||
<Badge variant="light" size="sm">
|
|
||||||
{Array.isArray(user.user_roles) ? user.user_roles.length : 0} ролей
|
|
||||||
</Badge>
|
|
||||||
</Group>
|
|
||||||
</Paper>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</ScrollArea.Autosize>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Group justify="flex-end">
|
|
||||||
<Button variant="default" onClick={onClose}>
|
|
||||||
Отмена
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={handleCopy}
|
|
||||||
disabled={!selectedUserId}
|
|
||||||
leftSection={<IconCopy size={16} />}
|
|
||||||
>
|
|
||||||
Скопировать роли
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,91 +0,0 @@
|
||||||
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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -40,7 +40,7 @@ export default function Header({
|
||||||
size="sm"
|
size="sm"
|
||||||
/>
|
/>
|
||||||
<Text ml="md" fw={700}>
|
<Text ml="md" fw={700}>
|
||||||
РусПЭТ CRM
|
Ruspet Admin Panel
|
||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,12 @@
|
||||||
import { AppShell } from '@mantine/core'
|
import { AppShell } from '@mantine/core'
|
||||||
import { useDisclosure } from '@mantine/hooks'
|
import { useDisclosure } from '@mantine/hooks'
|
||||||
import { Outlet, useLocation } from 'react-router-dom'
|
import { Outlet } from 'react-router-dom'
|
||||||
import Sidebar from './Sidebar'
|
import Sidebar from './Sidebar'
|
||||||
import Header from './Header'
|
import Header from './Header'
|
||||||
import ErrorBoundary from '../DiagnosticErrorBoundary'
|
|
||||||
|
|
||||||
export default function MainLayout() {
|
export default function MainLayout() {
|
||||||
const [mobileOpened, { toggle: toggleMobile }] = useDisclosure()
|
const [mobileOpened, { toggle: toggleMobile }] = useDisclosure()
|
||||||
const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true)
|
const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true)
|
||||||
const location = useLocation()
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AppShell
|
<AppShell
|
||||||
|
|
@ -34,9 +32,7 @@ export default function MainLayout() {
|
||||||
</AppShell.Navbar>
|
</AppShell.Navbar>
|
||||||
|
|
||||||
<AppShell.Main bg="gray.0" miw={0}>
|
<AppShell.Main bg="gray.0" miw={0}>
|
||||||
<ErrorBoundary key={location.pathname}>
|
<Outlet />
|
||||||
<Outlet />
|
|
||||||
</ErrorBoundary>
|
|
||||||
</AppShell.Main>
|
</AppShell.Main>
|
||||||
</AppShell>
|
</AppShell>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { useState, useMemo } from 'react'
|
import { useState } from 'react'
|
||||||
import { NavLink, Box, Text, Stack, Badge } from '@mantine/core'
|
import { NavLink, Box, Text, Stack } from '@mantine/core'
|
||||||
import {
|
import {
|
||||||
IconDashboard,
|
IconDashboard,
|
||||||
IconFileCheck,
|
IconFileCheck,
|
||||||
|
|
@ -15,81 +15,47 @@ import {
|
||||||
IconUserCheck,
|
IconUserCheck,
|
||||||
IconGitBranch,
|
IconGitBranch,
|
||||||
IconUserCog,
|
IconUserCog,
|
||||||
IconCheck,
|
IconCheck, IconBellRinging,
|
||||||
IconBellRinging,
|
|
||||||
IconBlocks,
|
|
||||||
IconHistory, IconChartBar, IconBrandTelegram,
|
|
||||||
} from '@tabler/icons-react'
|
} from '@tabler/icons-react'
|
||||||
import { useLocation, useNavigate } from 'react-router-dom'
|
import { useLocation, useNavigate } from 'react-router-dom'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
|
||||||
|
|
||||||
interface MenuItem {
|
interface MenuItem {
|
||||||
label: string
|
label: string
|
||||||
icon?: any
|
icon?: any
|
||||||
path?: string
|
path?: string
|
||||||
children?: MenuItem[]
|
children?: MenuItem[]
|
||||||
adminOnly?: boolean // скрывать от наблюдателей
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const menuItems: MenuItem[] = [
|
const menuItems: MenuItem[] = [
|
||||||
{ label: 'Обзор', icon: IconDashboard, path: '/' },
|
{ label: 'Обзор', icon: IconDashboard, path: '/' },
|
||||||
{ label: 'Администраторы', icon: IconUserCog, path: '/admins', adminOnly: true },
|
{ label: 'Администраторы', icon: IconUserCog, path: '/admins' },
|
||||||
{ label: 'Уведомления', icon: IconBellRinging, path: '/notifications', adminOnly: true },
|
{ label: 'Уведомления', icon: IconBellRinging, path: '/notifications' },
|
||||||
{ label: 'Журнал действий', icon: IconHistory, path: '/logs', adminOnly: true },
|
|
||||||
{
|
|
||||||
label: 'Заказы на месяц',
|
|
||||||
icon: IconChartBar,
|
|
||||||
path: '/monthly-orders-settings',
|
|
||||||
adminOnly: true, // Скрываем от наблюдателей
|
|
||||||
// Если нужно скрыть от менеджеров, можно добавить флаг analystOnly: true и фильтровать
|
|
||||||
},
|
|
||||||
{ label: 'Телефония', icon: IconBrandTelegram, path: '/telegram-managers', adminOnly: true },
|
|
||||||
{
|
{
|
||||||
label: 'Система согласований',
|
label: 'Система согласований',
|
||||||
icon: IconFileCheck,
|
icon: IconFileCheck,
|
||||||
children: [
|
children: [
|
||||||
{ label: 'Панель управления', icon: IconDashboard, path: '/approval-dash', adminOnly: true },
|
{ label: 'Панель управления', icon: IconDashboard, path: '/approval-dash' },
|
||||||
{ label: 'Заявки', icon: IconList, path: '/approvals' },
|
{ label: 'Заявки', icon: IconList, path: '/approvals' },
|
||||||
{ label: 'Задачи', icon: IconCheck, path: '/approval-tasks' },
|
{ label: 'Задачи', icon: IconCheck, path: '/approval-tasks' },
|
||||||
{ label: 'Пользователи', icon: IconUsers, path: '/users', adminOnly: true },
|
{ label: 'Пользователи', icon: IconUsers, path: '/users' },
|
||||||
{ label: 'Отделы', icon: IconBuilding, path: '/departments', adminOnly: true },
|
{ label: 'Отделы', icon: IconBuilding, path: '/departments' },
|
||||||
{ label: 'Роли', icon: IconShield, path: '/roles', adminOnly: true },
|
{ label: 'Роли', icon: IconShield, path: '/roles' },
|
||||||
{ label: 'Права', icon: IconKey, path: '/permissions', adminOnly: true },
|
{ label: 'Права', icon: IconKey, path: '/permissions' },
|
||||||
{
|
{
|
||||||
label: 'Темы согласований',
|
label: 'Темы согласований',
|
||||||
icon: IconBriefcase,
|
icon: IconBriefcase,
|
||||||
adminOnly: true,
|
|
||||||
children: [
|
children: [
|
||||||
{ label: 'Настройки категорий', icon: IconCategory, path: '/categories' },
|
{ label: 'Категории', icon: IconCategory, path: '/categories' },
|
||||||
{ label: 'Настройки тем', icon: IconBriefcase, path: '/topics', adminOnly: true },
|
{ label: 'Темы', icon: IconBriefcase, path: '/topics' },
|
||||||
{ label: 'Исполнители', icon: IconUserCheck, path: '/executors', adminOnly: true },
|
{ label: 'Исполнители', icon: IconUserCheck, path: '/executors' },
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{ label: 'Конструктор тем', icon: IconBlocks, path: '/nodes', adminOnly: true },
|
{ label: 'Иерархия', icon: IconGitBranch, path: '/hierarchies' },
|
||||||
{ label: 'Иерархия', icon: IconGitBranch, path: '/hierarchies', adminOnly: true },
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{ label: 'Настройки', icon: IconSettings, path: '/settings'},
|
{ label: 'Настройки', icon: IconSettings, path: '/settings' },
|
||||||
]
|
]
|
||||||
|
|
||||||
function filterMenuByRole(items: MenuItem[], isObserver: boolean): MenuItem[] {
|
|
||||||
return items
|
|
||||||
.filter((item) => {
|
|
||||||
if (isObserver && item.adminOnly) return false
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
.map((item) => {
|
|
||||||
if (item.children) {
|
|
||||||
const filteredChildren = filterMenuByRole(item.children, isObserver)
|
|
||||||
// Если после фильтрации детей не осталось — скрываем родителя
|
|
||||||
if (filteredChildren.length === 0) return null
|
|
||||||
return { ...item, children: filteredChildren }
|
|
||||||
}
|
|
||||||
return item
|
|
||||||
})
|
|
||||||
.filter((item): item is MenuItem => item !== null)
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuItemLink({ item, level }: { item: MenuItem; level: number }) {
|
function MenuItemLink({ item, level }: { item: MenuItem; level: number }) {
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
@ -101,6 +67,7 @@ function MenuItemLink({ item, level }: { item: MenuItem; level: number }) {
|
||||||
child.path ? location.pathname === child.path : false
|
child.path ? location.pathname === child.path : false
|
||||||
) || false
|
) || false
|
||||||
|
|
||||||
|
// ✅ Используем padding вместо marginLeft для правильного выравнивания
|
||||||
const paddingLeft = 16 + level * 20
|
const paddingLeft = 16 + level * 20
|
||||||
|
|
||||||
if (hasChildren) {
|
if (hasChildren) {
|
||||||
|
|
@ -170,16 +137,6 @@ function MenuItemLink({ item, level }: { item: MenuItem; level: number }) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Sidebar() {
|
export default function Sidebar() {
|
||||||
const { user } = useAuth()
|
|
||||||
const isObserver = user?.is_observer === true
|
|
||||||
const isAnalyst = user?.is_analyst === true || user?.is_root === true
|
|
||||||
|
|
||||||
// 🆕 Фильтруем меню в зависимости от роли
|
|
||||||
const filteredMenuItems = useMemo(
|
|
||||||
() => filterMenuByRole(menuItems, isObserver),
|
|
||||||
[isObserver]
|
|
||||||
)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
style={{
|
style={{
|
||||||
|
|
@ -202,17 +159,8 @@ export default function Sidebar() {
|
||||||
Главное меню
|
Главное меню
|
||||||
</Text>
|
</Text>
|
||||||
|
|
||||||
{/* 🆕 Индикатор режима наблюдателя */}
|
|
||||||
{isObserver && (
|
|
||||||
<Box px="sm" mb="md">
|
|
||||||
<Badge color="blue" variant="light" size="sm" fullWidth>
|
|
||||||
Режим наблюдателя
|
|
||||||
</Badge>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Stack gap={4}>
|
<Stack gap={4}>
|
||||||
{filteredMenuItems.map((item) => (
|
{menuItems.map((item) => (
|
||||||
<MenuItemLink key={item.label} item={item} level={0} />
|
<MenuItemLink key={item.label} item={item} level={0} />
|
||||||
))}
|
))}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
|
||||||
|
|
@ -1,80 +0,0 @@
|
||||||
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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect } from 'react'
|
||||||
import {
|
import {
|
||||||
Modal,
|
Modal,
|
||||||
Stack,
|
Stack,
|
||||||
|
|
@ -14,18 +14,12 @@ import {
|
||||||
Center,
|
Center,
|
||||||
Badge,
|
Badge,
|
||||||
Paper,
|
Paper,
|
||||||
Tabs,
|
|
||||||
ActionIcon,
|
|
||||||
Tooltip,
|
|
||||||
Box,
|
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { IconTrash, IconCopy, IconUser, IconSettings, IconShield } from '@tabler/icons-react'
|
|
||||||
import { useForm } from '@mantine/form'
|
import { useForm } from '@mantine/form'
|
||||||
import { useUser, useUpdateUser } from '@/features/users/hooks/useUsers'
|
import { useUser, useUpdateUser } from '@/features/users/hooks/useUsers'
|
||||||
import { useDepartments } from '@/features/users/hooks/useDepartments'
|
import { useDepartments } from '@/features/users/hooks/useDepartments'
|
||||||
import { useRoles } from '@/features/users/hooks/useRoles'
|
import { useRoles } from '@/features/users/hooks/useRoles'
|
||||||
import { useUserRoles, useBulkAssignRoles } from '@/features/users/hooks/useUserRoles'
|
import { useUserRoles, useBulkAssignRoles } from '@/features/users/hooks/useUserRoles'
|
||||||
import CopyRolesModal from './CopyRolesModal'
|
|
||||||
|
|
||||||
interface UserEditModalProps {
|
interface UserEditModalProps {
|
||||||
userId: number | null
|
userId: number | null
|
||||||
|
|
@ -36,17 +30,14 @@ interface UserEditModalProps {
|
||||||
export default function UserEditModal({ userId, opened, onClose }: UserEditModalProps) {
|
export default function UserEditModal({ userId, opened, onClose }: UserEditModalProps) {
|
||||||
const { data: user, isLoading: userLoading } = useUser(userId)
|
const { data: user, isLoading: userLoading } = useUser(userId)
|
||||||
const { data: departments } = useDepartments()
|
const { data: departments } = useDepartments()
|
||||||
const { data: allRoles } = useRoles({ limit: 1000 })
|
const { data: allRoles } = useRoles()
|
||||||
const { data: userRoles, isLoading: rolesLoading } = useUserRoles(userId)
|
const { data: userRoles, isLoading: rolesLoading } = useUserRoles(userId)
|
||||||
|
|
||||||
const updateUser = useUpdateUser()
|
const updateUser = useUpdateUser()
|
||||||
const assignRoles = useBulkAssignRoles()
|
const assignRoles = useBulkAssignRoles()
|
||||||
|
|
||||||
const [copyRolesOpened, setCopyRolesOpened] = useState(false)
|
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
initialValues: {
|
initialValues: {
|
||||||
full_name: '',
|
|
||||||
department_id: null as number | null,
|
department_id: null as number | null,
|
||||||
is_blocked: false,
|
is_blocked: false,
|
||||||
is_fired: false,
|
is_fired: false,
|
||||||
|
|
@ -54,22 +45,21 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Заполняем форму данными пользователя
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user) {
|
if (user) {
|
||||||
form.setValues({
|
form.setValues({
|
||||||
full_name: user.full_name || '',
|
|
||||||
department_id: user.department_id || null,
|
department_id: user.department_id || null,
|
||||||
is_blocked: user.is_blocked || false,
|
is_blocked: user.is_blocked || false,
|
||||||
is_fired: user.is_fired || false,
|
is_fired: user.is_fired || false,
|
||||||
role_ids: Array.isArray(user.user_roles)
|
role_ids: user.user_roles?.map((ur) => ur.role_id!) || [],
|
||||||
? user.user_roles.map((ur) => ur.role_id!)
|
|
||||||
: [],
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}, [user])
|
}, [user])
|
||||||
|
|
||||||
|
// Заполняем роли из отдельного запроса
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (Array.isArray(userRoles) && userRoles.length > 0) {
|
if (userRoles && userRoles.length > 0) {
|
||||||
const roleIds = userRoles
|
const roleIds = userRoles
|
||||||
.map((ur) => ur.role?.id || ur.role_id)
|
.map((ur) => ur.role?.id || ur.role_id)
|
||||||
.filter((id): id is number => !!id)
|
.filter((id): id is number => !!id)
|
||||||
|
|
@ -80,14 +70,15 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
const handleSubmit = async (values: typeof form.values) => {
|
const handleSubmit = async (values: typeof form.values) => {
|
||||||
if (!userId) return
|
if (!userId) return
|
||||||
|
|
||||||
|
// Обновляем пользователя
|
||||||
await updateUser.mutateAsync({
|
await updateUser.mutateAsync({
|
||||||
id: userId,
|
id: userId,
|
||||||
full_name: values.full_name,
|
|
||||||
department_id: values.department_id,
|
department_id: values.department_id,
|
||||||
is_blocked: values.is_blocked,
|
is_blocked: values.is_blocked,
|
||||||
is_fired: values.is_fired,
|
is_fired: values.is_fired,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Обновляем роли
|
||||||
await assignRoles.mutateAsync({
|
await assignRoles.mutateAsync({
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
role_ids: values.role_ids,
|
role_ids: values.role_ids,
|
||||||
|
|
@ -96,179 +87,112 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleClearAllRoles = () => {
|
const departmentOptions = departments?.map((d) => ({
|
||||||
form.setFieldValue('role_ids', [])
|
value: String(d.id),
|
||||||
}
|
label: d.name || '',
|
||||||
|
})) || []
|
||||||
|
|
||||||
const handleCopyRoles = (roleIds: number[]) => {
|
const roleOptions = allRoles?.map((r) => ({
|
||||||
form.setFieldValue('role_ids', roleIds)
|
value: String(r.id),
|
||||||
setCopyRolesOpened(false)
|
label: r.name || '',
|
||||||
}
|
description: r.description,
|
||||||
|
})) || []
|
||||||
const departmentOptions = Array.isArray(departments)
|
|
||||||
? departments.map((d) => ({
|
|
||||||
value: String(d.id),
|
|
||||||
label: d.name || '',
|
|
||||||
}))
|
|
||||||
: []
|
|
||||||
|
|
||||||
const roleOptions = Array.isArray(allRoles)
|
|
||||||
? allRoles.map((r) => ({
|
|
||||||
value: String(r.id),
|
|
||||||
label: r.name || '',
|
|
||||||
description: r.description,
|
|
||||||
}))
|
|
||||||
: []
|
|
||||||
|
|
||||||
const isLoading = userLoading || rolesLoading
|
const isLoading = userLoading || rolesLoading
|
||||||
const isSubmitting = updateUser.isPending || assignRoles.isPending
|
const isSubmitting = updateUser.isPending || assignRoles.isPending
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<Modal
|
||||||
<Modal
|
opened={opened}
|
||||||
opened={opened}
|
onClose={onClose}
|
||||||
onClose={onClose}
|
title={
|
||||||
title={
|
<Group>
|
||||||
<Group>
|
<Text fw={700}>Редактирование пользователя</Text>
|
||||||
<Text fw={700}>Редактирование пользователя</Text>
|
{user && <Badge variant="light">ID: {user.id}</Badge>}
|
||||||
{user && <Badge variant="light">ID: {user.id}</Badge>}
|
</Group>
|
||||||
</Group>
|
}
|
||||||
}
|
size="lg"
|
||||||
size="xl"
|
>
|
||||||
>
|
{isLoading ? (
|
||||||
{isLoading ? (
|
<Center p={40}>
|
||||||
<Center p={40}>
|
<Loader />
|
||||||
<Loader />
|
</Center>
|
||||||
</Center>
|
) : user ? (
|
||||||
) : user ? (
|
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
<Stack gap="md">
|
||||||
<Tabs defaultValue="info" variant="outline">
|
{/* Информация о пользователе (только для чтения) */}
|
||||||
<Tabs.List mb="md">
|
<Paper withBorder p="md" bg="gray.0">
|
||||||
<Tabs.Tab value="info" leftSection={<IconUser size={14} />}>
|
<Stack gap="xs">
|
||||||
Информация
|
<Group justify="space-between">
|
||||||
</Tabs.Tab>
|
<Text size="sm" c="dimmed">Имя:</Text>
|
||||||
<Tabs.Tab value="roles" leftSection={<IconShield size={14} />}>
|
<Text fw={500}>{user.full_name}</Text>
|
||||||
Роли ({form.values.role_ids.length})
|
</Group>
|
||||||
</Tabs.Tab>
|
<Group justify="space-between">
|
||||||
<Tabs.Tab value="settings" leftSection={<IconSettings size={14} />}>
|
<Text size="sm" c="dimmed">Telegram ID:</Text>
|
||||||
Настройки
|
<Text ff="monospace">{user.telegram_id}</Text>
|
||||||
</Tabs.Tab>
|
</Group>
|
||||||
</Tabs.List>
|
{user.username && (
|
||||||
|
|
||||||
{/* Вкладка: Информация */}
|
|
||||||
<Tabs.Panel value="info">
|
|
||||||
<Stack gap="md">
|
|
||||||
<Paper withBorder p="md" bg="gray.0">
|
|
||||||
<Stack gap="xs">
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">Telegram ID:</Text>
|
|
||||||
<Text ff="monospace">{user.telegram_id}</Text>
|
|
||||||
</Group>
|
|
||||||
{user.username && (
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">Username:</Text>
|
|
||||||
<Text>@{user.username}</Text>
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
{user.last_login && (
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">Последний вход:</Text>
|
|
||||||
<Text size="sm">
|
|
||||||
{new Date(user.last_login).toLocaleString('ru-RU')}
|
|
||||||
</Text>
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<TextInput
|
|
||||||
label="ФИО"
|
|
||||||
placeholder="Иванов Иван Иванович"
|
|
||||||
value={form.values.full_name}
|
|
||||||
onChange={(e) => form.setFieldValue('full_name', e.currentTarget.value)}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Отдел"
|
|
||||||
placeholder="Не назначен"
|
|
||||||
data={departmentOptions}
|
|
||||||
value={form.values.department_id ? String(form.values.department_id) : null}
|
|
||||||
onChange={(v) => form.setFieldValue('department_id', v ? Number(v) : null)}
|
|
||||||
clearable
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
</Tabs.Panel>
|
|
||||||
|
|
||||||
{/* Вкладка: Роли */}
|
|
||||||
<Tabs.Panel value="roles">
|
|
||||||
<Stack gap="md">
|
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Text size="sm" fw={500}>
|
<Text size="sm" c="dimmed">Username:</Text>
|
||||||
Выбрано ролей: {form.values.role_ids.length}
|
<Text>@{user.username}</Text>
|
||||||
</Text>
|
|
||||||
<Group gap="xs">
|
|
||||||
<Tooltip label="Снять все роли">
|
|
||||||
<ActionIcon
|
|
||||||
variant="light"
|
|
||||||
color="red"
|
|
||||||
onClick={handleClearAllRoles}
|
|
||||||
disabled={form.values.role_ids.length === 0}
|
|
||||||
>
|
|
||||||
<IconTrash size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip label="Скопировать роли от другого пользователя">
|
|
||||||
<ActionIcon
|
|
||||||
variant="light"
|
|
||||||
color="blue"
|
|
||||||
onClick={() => setCopyRolesOpened(true)}
|
|
||||||
>
|
|
||||||
<IconCopy size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
</Group>
|
|
||||||
</Group>
|
</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>
|
||||||
|
|
||||||
<MultiSelect
|
<Divider label="Настройки" labelPosition="center" />
|
||||||
label="Роли"
|
|
||||||
placeholder="Выберите роли"
|
|
||||||
data={roleOptions}
|
|
||||||
value={form.values.role_ids.map(String)}
|
|
||||||
onChange={(v) => form.setFieldValue('role_ids', v.map(Number))}
|
|
||||||
searchable
|
|
||||||
clearable
|
|
||||||
description="Пользователь может иметь несколько ролей"
|
|
||||||
maxDropdownHeight={300}
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
</Tabs.Panel>
|
|
||||||
|
|
||||||
{/* Вкладка: Настройки */}
|
{/* Отдел */}
|
||||||
<Tabs.Panel value="settings">
|
<Select
|
||||||
<Stack gap="md">
|
label="Отдел"
|
||||||
<Switch
|
placeholder="Не назначен"
|
||||||
label="Заблокирован"
|
data={departmentOptions}
|
||||||
description="Пользователь не сможет пользоваться системой"
|
value={form.values.department_id ? String(form.values.department_id) : null}
|
||||||
checked={form.values.is_blocked}
|
onChange={(v) => form.setFieldValue('department_id', v ? Number(v) : null)}
|
||||||
onChange={(e) => form.setFieldValue('is_blocked', e.currentTarget.checked)}
|
clearable
|
||||||
color="red"
|
/>
|
||||||
/>
|
|
||||||
|
|
||||||
<Switch
|
{/* Роли */}
|
||||||
label="Уволен"
|
<MultiSelect
|
||||||
description="Пользователь больше не работает в компании"
|
label="Роли"
|
||||||
checked={form.values.is_fired}
|
placeholder="Выберите роли"
|
||||||
onChange={(e) => form.setFieldValue('is_fired', e.currentTarget.checked)}
|
data={roleOptions}
|
||||||
color="gray"
|
value={form.values.role_ids.map(String)}
|
||||||
/>
|
onChange={(v) => form.setFieldValue('role_ids', v.map(Number))}
|
||||||
</Stack>
|
searchable
|
||||||
</Tabs.Panel>
|
clearable
|
||||||
</Tabs>
|
description="Пользователь может иметь несколько ролей"
|
||||||
|
/>
|
||||||
|
|
||||||
<Divider my="md" />
|
<Divider />
|
||||||
|
|
||||||
<Group justify="flex-end">
|
{/* Статусы */}
|
||||||
|
<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 variant="default" onClick={onClose} disabled={isSubmitting}>
|
||||||
Отмена
|
Отмена
|
||||||
</Button>
|
</Button>
|
||||||
|
|
@ -276,20 +200,13 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
Сохранить
|
Сохранить
|
||||||
</Button>
|
</Button>
|
||||||
</Group>
|
</Group>
|
||||||
</form>
|
</Stack>
|
||||||
) : (
|
</form>
|
||||||
<Center p={40}>
|
) : (
|
||||||
<Text c="dimmed">Пользователь не найден</Text>
|
<Center p={40}>
|
||||||
</Center>
|
<Text c="dimmed">Пользователь не найден</Text>
|
||||||
)}
|
</Center>
|
||||||
</Modal>
|
)}
|
||||||
|
</Modal>
|
||||||
<CopyRolesModal
|
|
||||||
opened={copyRolesOpened}
|
|
||||||
onClose={() => setCopyRolesOpened(false)}
|
|
||||||
onCopy={handleCopyRoles}
|
|
||||||
currentUserId={userId}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
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({
|
return useMutation({
|
||||||
mutationFn: async (data: CreateAdminRequest) => {
|
mutationFn: async (data: CreateAdminRequest) => {
|
||||||
const response = await adminsApi.create(data)
|
const response = await adminsApi.create(data)
|
||||||
return response.data
|
return response.data // ✅ Извлекаем Admin из AxiosResponse
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [ADMINS_QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [ADMINS_QUERY_KEY] })
|
||||||
|
|
@ -33,10 +33,6 @@ export function useCreateAdmin() {
|
||||||
message = 'Администратор с таким логином уже существует'
|
message = 'Администратор с таким логином уже существует'
|
||||||
} else if (errorMsg === 'only_root_can_create_admins') {
|
} else if (errorMsg === 'only_root_can_create_admins') {
|
||||||
message = 'Только root-администратор может создавать новых администраторов'
|
message = 'Только root-администратор может создавать новых администраторов'
|
||||||
} else if (errorMsg === 'telegram_id_required_for_observer') {
|
|
||||||
message = 'Для наблюдателя необходимо указать Telegram-аккаунт'
|
|
||||||
} else if (errorMsg === 'telegram_user_not_found') {
|
|
||||||
message = 'Пользователь с таким Telegram ID не найден в боте'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
notifications.show({
|
notifications.show({
|
||||||
|
|
@ -69,10 +65,6 @@ export function useUpdateAdmin() {
|
||||||
message = 'Нельзя заблокировать root-администратора'
|
message = 'Нельзя заблокировать root-администратора'
|
||||||
} else if (errorMsg === 'cannot_block_self') {
|
} else if (errorMsg === 'cannot_block_self') {
|
||||||
message = 'Нельзя заблокировать свой собственный аккаунт'
|
message = 'Нельзя заблокировать свой собственный аккаунт'
|
||||||
} else if (errorMsg === 'telegram_id_required_for_observer') {
|
|
||||||
message = 'Для наблюдателя необходимо указать Telegram-аккаунт'
|
|
||||||
} else if (errorMsg === 'telegram_user_not_found') {
|
|
||||||
message = 'Пользователь с таким Telegram ID не найден в боте'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
notifications.show({
|
notifications.show({
|
||||||
|
|
|
||||||
|
|
@ -19,18 +19,6 @@ 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) {
|
export function useApproval(id: number | null) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['approval', id],
|
queryKey: ['approval', id],
|
||||||
|
|
@ -100,51 +88,3 @@ 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,36 +4,41 @@ import {
|
||||||
type CreateFlowNodeRequest,
|
type CreateFlowNodeRequest,
|
||||||
type UpdateFlowNodeRequest,
|
type UpdateFlowNodeRequest,
|
||||||
type MoveFlowNodeRequest,
|
type MoveFlowNodeRequest,
|
||||||
type PreviewFlowRequest,
|
type SaveTreeRequest,
|
||||||
} from '@/api/flowNodes'
|
} from '@/api/flowNodes'
|
||||||
import { notifications } from '@mantine/notifications'
|
import { notifications } from '@mantine/notifications'
|
||||||
|
|
||||||
export const FLOW_NODES_QUERY_KEY = 'flowNodes'
|
export const FLOW_NODES_QUERY_KEY = 'flowNodes'
|
||||||
|
|
||||||
export function useFlowNodesTree(categoryId: number | null) {
|
export function useFlowNodesTree(topicId: number | null) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: [FLOW_NODES_QUERY_KEY, categoryId],
|
queryKey: [FLOW_NODES_QUERY_KEY, topicId],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
if (!categoryId) return null
|
if (!topicId) return null
|
||||||
const response = await flowNodesApi.getTree(categoryId)
|
const response = await flowNodesApi.getTree(topicId)
|
||||||
return response.data
|
return response.data
|
||||||
},
|
},
|
||||||
enabled: !!categoryId,
|
enabled: !!topicId,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCreateFlowNode() {
|
export function useCreateFlowNode() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (data: CreateFlowNodeRequest) => flowNodesApi.create(data),
|
mutationFn: (data: CreateFlowNodeRequest) => flowNodesApi.create(data),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||||
notifications.show({ title: 'Готово', message: 'Кнопка/шаг добавлены', color: 'green' })
|
notifications.show({
|
||||||
|
title: 'Успешно',
|
||||||
|
message: 'Узел создан',
|
||||||
|
color: 'green',
|
||||||
|
})
|
||||||
},
|
},
|
||||||
onError: (error: any) => {
|
onError: (error: any) => {
|
||||||
notifications.show({
|
notifications.show({
|
||||||
title: 'Не получилось',
|
title: 'Ошибка',
|
||||||
message: error.response?.data?.error_description || 'Не удалось сохранить',
|
message: error.response?.data?.error_description || 'Не удалось создать узел',
|
||||||
color: 'red',
|
color: 'red',
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
@ -42,16 +47,21 @@ export function useCreateFlowNode() {
|
||||||
|
|
||||||
export function useUpdateFlowNode() {
|
export function useUpdateFlowNode() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (data: UpdateFlowNodeRequest) => flowNodesApi.update(data),
|
mutationFn: (data: UpdateFlowNodeRequest) => flowNodesApi.update(data),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||||
notifications.show({ title: 'Готово', message: 'Изменения сохранены', color: 'green' })
|
notifications.show({
|
||||||
|
title: 'Успешно',
|
||||||
|
message: 'Узел обновлён',
|
||||||
|
color: 'green',
|
||||||
|
})
|
||||||
},
|
},
|
||||||
onError: (error: any) => {
|
onError: (error: any) => {
|
||||||
notifications.show({
|
notifications.show({
|
||||||
title: 'Не получилось',
|
title: 'Ошибка',
|
||||||
message: error.response?.data?.error_description || 'Не удалось сохранить изменения',
|
message: error.response?.data?.error_description || 'Не удалось обновить узел',
|
||||||
color: 'red',
|
color: 'red',
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
@ -60,121 +70,89 @@ export function useUpdateFlowNode() {
|
||||||
|
|
||||||
export function useDeleteFlowNode() {
|
export function useDeleteFlowNode() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => flowNodesApi.delete(id),
|
mutationFn: (id: number) => flowNodesApi.delete(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||||
notifications.show({ title: 'Готово', message: 'Шаг удалён', color: 'green' })
|
notifications.show({
|
||||||
|
title: 'Успешно',
|
||||||
|
message: 'Узел удалён',
|
||||||
|
color: 'green',
|
||||||
|
})
|
||||||
},
|
},
|
||||||
onError: (error: any) => {
|
onError: (error: any) => {
|
||||||
notifications.show({
|
notifications.show({
|
||||||
title: 'Не получилось',
|
title: 'Ошибка',
|
||||||
message: error.response?.data?.error_description || 'Не удалось удалить',
|
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 || 'Не удалось сохранить дерево',
|
||||||
color: 'red',
|
color: 'red',
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Перемещение узла — используется для ↑/↓ среди соседей и для
|
|
||||||
// "поднять/опустить уровень" точечно (см. treeWalk.ts).
|
|
||||||
export function useMoveFlowNode() {
|
export function useMoveFlowNode() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
return useMutation({
|
|
||||||
mutationFn: ({ id, data }: { id: number; data: MoveFlowNodeRequest }) => flowNodesApi.move(id, data),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
|
||||||
},
|
|
||||||
onError: (error: any) => {
|
|
||||||
notifications.show({
|
|
||||||
title: 'Не получилось',
|
|
||||||
message: error.response?.data?.error_description || 'Не удалось переместить',
|
|
||||||
color: 'red',
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// НОВОЕ: пакетное перемещение для drag&drop — план из buildReorderPlan
|
|
||||||
// (см. treeFlatten.ts) может включать несколько узлов сразу (переиндексация
|
|
||||||
// старой и новой групп соседей). Отправляем всё параллельно и обновляем
|
|
||||||
// дерево ОДНИМ инвалидейтом в конце, а не на каждый отдельный вызов —
|
|
||||||
// иначе список будет дёргаться на каждом промежуточном ответе.
|
|
||||||
export function useReorderNodes() {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (ops: { id: number; new_parent_id: number | null; new_sort_order: number }[]) => {
|
mutationFn: ({ id, data }: { id: number; data: MoveFlowNodeRequest }) =>
|
||||||
await Promise.all(
|
flowNodesApi.move(id, data),
|
||||||
ops.map((op) =>
|
|
||||||
flowNodesApi.move(op.id, { new_parent_id: op.new_parent_id, new_sort_order: op.new_sort_order })
|
|
||||||
)
|
|
||||||
)
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||||
},
|
},
|
||||||
onError: (error: any) => {
|
onError: (error: any) => {
|
||||||
notifications.show({
|
notifications.show({
|
||||||
title: 'Не получилось',
|
title: 'Ошибка',
|
||||||
message:
|
message: error.response?.data?.error_description || 'Не удалось переместить узел',
|
||||||
error.response?.data?.error_description || 'Не удалось переместить шаг — дерево вернётся к прежнему виду',
|
|
||||||
color: 'red',
|
color: 'red',
|
||||||
})
|
})
|
||||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDuplicateFlowNode() {
|
export function useDuplicateFlowNode() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => flowNodesApi.duplicate(id),
|
mutationFn: (id: number) => flowNodesApi.duplicate(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||||
notifications.show({ title: 'Готово', message: 'Шаг скопирован', color: 'green' })
|
|
||||||
},
|
|
||||||
onError: (error: any) => {
|
|
||||||
notifications.show({
|
notifications.show({
|
||||||
title: 'Не получилось',
|
title: 'Успешно',
|
||||||
message: error.response?.data?.error_description || 'Не удалось скопировать',
|
message: 'Узел дублирован',
|
||||||
color: 'red',
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// НОВОЕ: живой предпросмотр — код темы + текст сообщения согласующему
|
|
||||||
// для конкретного набора выборов. Не мутирует данные, поэтому это
|
|
||||||
// useMutation, вызываемый вручную (а не useQuery), чтобы не дёргать
|
|
||||||
// сервер на каждое нажатие клавиши, а только по явному запросу/дебаунсу.
|
|
||||||
// НОВОЕ: кнопка "Обновить бота" — форсирует у бота перечитывание дерева тем
|
|
||||||
// из БД, не дожидаясь фонового тика (см. reload_watcher.go в telegram_service).
|
|
||||||
export function useReloadBot() {
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: () => flowNodesApi.reloadBot(),
|
|
||||||
onSuccess: () => {
|
|
||||||
notifications.show({
|
|
||||||
title: 'Готово',
|
|
||||||
message: 'Бот обновит список тем в течение нескольких секунд',
|
|
||||||
color: 'green',
|
color: 'green',
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
onError: (error: any) => {
|
onError: (error: any) => {
|
||||||
notifications.show({
|
notifications.show({
|
||||||
title: 'Не получилось',
|
title: 'Ошибка',
|
||||||
message: error.response?.data?.error_description || 'Не удалось обновить бота',
|
message: error.response?.data?.error_description || 'Не удалось дублировать узел',
|
||||||
color: 'red',
|
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
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
@ -1,128 +0,0 @@
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
@ -1,223 +0,0 @@
|
||||||
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}}`
|
|
||||||
}
|
|
||||||
|
|
@ -1,73 +0,0 @@
|
||||||
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,13 +36,14 @@ export function groupHierarchiesIntoChains(
|
||||||
const scopeObjectId = scopeType === 'topic' ? h.topic_id :
|
const scopeObjectId = scopeType === 'topic' ? h.topic_id :
|
||||||
scopeType === 'category' ? h.topic_category_id : null
|
scopeType === 'category' ? h.topic_category_id : null
|
||||||
|
|
||||||
// Формируем ключ группы (добавляем target_system)
|
// Формируем ключ группы
|
||||||
const targetSystemPart = h.target_system || 'all'
|
const key = `${h.subordinate_id}-${h.department_id}-${scopeType}-${scopeObjectId || 'null'}`
|
||||||
const key = `${h.subordinate_id}-${h.department_id}-${scopeType}-${scopeObjectId || 'null'}-${targetSystemPart}`
|
|
||||||
|
|
||||||
if (!groups.has(key)) {
|
if (!groups.has(key)) {
|
||||||
|
// Определяем название объекта области действия
|
||||||
let scopeObjectName = 'Все темы'
|
let scopeObjectName = 'Все темы'
|
||||||
if (scopeType === 'category' && h.subordinate) {
|
if (scopeType === 'category' && h.subordinate) {
|
||||||
|
// Будет заполнено позже из categories
|
||||||
scopeObjectName = `Категория #${scopeObjectId}`
|
scopeObjectName = `Категория #${scopeObjectId}`
|
||||||
} else if (scopeType === 'topic') {
|
} else if (scopeType === 'topic') {
|
||||||
scopeObjectName = `Тема #${scopeObjectId}`
|
scopeObjectName = `Тема #${scopeObjectId}`
|
||||||
|
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
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',
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
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',
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
// Приводит 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()
|
|
||||||
}
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
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 || []
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
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 const ROLES_QUERY_KEY = 'roles'
|
||||||
|
|
||||||
export function useRoles(params: import('@/api/roles').RolesListParams = {}) {
|
export function useRoles() {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: [ROLES_QUERY_KEY, params],
|
queryKey: [ROLES_QUERY_KEY],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await rolesApi.getList(params)
|
const response = await rolesApi.getList()
|
||||||
return response.data.data || []
|
return response.data.data || []
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -48,27 +48,3 @@ 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',
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
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',
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
@ -10,7 +10,6 @@ import { theme } from './theme'
|
||||||
import '@mantine/core/styles.css'
|
import '@mantine/core/styles.css'
|
||||||
import '@mantine/notifications/styles.css'
|
import '@mantine/notifications/styles.css'
|
||||||
import '@mantine/dates/styles.css'
|
import '@mantine/dates/styles.css'
|
||||||
import ErrorBoundary from './components/DiagnosticErrorBoundary'
|
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
|
|
@ -28,9 +27,7 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||||
<MantineProvider theme={theme}>
|
<MantineProvider theme={theme}>
|
||||||
<ModalsProvider>
|
<ModalsProvider>
|
||||||
<Notifications position="top-right" />
|
<Notifications position="top-right" />
|
||||||
<ErrorBoundary fullPage>
|
<App />
|
||||||
<App />
|
|
||||||
</ErrorBoundary>
|
|
||||||
</ModalsProvider>
|
</ModalsProvider>
|
||||||
</MantineProvider>
|
</MantineProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
|
|
|
||||||
|
|
@ -12,22 +12,18 @@ import {
|
||||||
Alert,
|
Alert,
|
||||||
Box,
|
Box,
|
||||||
ThemeIcon,
|
ThemeIcon,
|
||||||
UnstyledButton,
|
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import {
|
import {
|
||||||
IconUsers,
|
IconUsers,
|
||||||
IconFileCheck,
|
IconFileCheck,
|
||||||
IconBuilding,
|
IconBuilding,
|
||||||
|
IconShield,
|
||||||
IconCategory,
|
IconCategory,
|
||||||
|
IconUserCheck,
|
||||||
IconAlertTriangle,
|
IconAlertTriangle,
|
||||||
IconAlertOctagon,
|
|
||||||
IconClock,
|
IconClock,
|
||||||
|
IconTrendingUp,
|
||||||
IconAlertCircle,
|
IconAlertCircle,
|
||||||
IconCircleCheck,
|
|
||||||
IconChecklist,
|
|
||||||
IconCalendarOff,
|
|
||||||
IconChevronRight,
|
|
||||||
IconUserExclamation,
|
|
||||||
} from '@tabler/icons-react'
|
} from '@tabler/icons-react'
|
||||||
import {
|
import {
|
||||||
PieChart,
|
PieChart,
|
||||||
|
|
@ -42,12 +38,10 @@ import {
|
||||||
Tooltip,
|
Tooltip,
|
||||||
Legend,
|
Legend,
|
||||||
} from 'recharts'
|
} from 'recharts'
|
||||||
import { useNavigate } from 'react-router-dom'
|
|
||||||
import { dashboardApi } from '@/api/dashboard'
|
import { dashboardApi } from '@/api/dashboard'
|
||||||
import type { DashboardStats } from '@/api/dashboard'
|
import type { DashboardStats } from '@/api/dashboard'
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
import 'dayjs/locale/ru'
|
import 'dayjs/locale/ru'
|
||||||
import TopicGapsModal from "@/components/TopicGapsModal.tsx";
|
|
||||||
|
|
||||||
dayjs.locale('ru')
|
dayjs.locale('ru')
|
||||||
|
|
||||||
|
|
@ -69,26 +63,10 @@ const STATUS_LABELS: Record<string, string> = {
|
||||||
revision: 'На доработке',
|
revision: 'На доработке',
|
||||||
}
|
}
|
||||||
|
|
||||||
const TASK_STATUS_COLORS: Record<string, string> = {
|
|
||||||
pending: '#228be6',
|
|
||||||
waiting: '#868e96',
|
|
||||||
completed: '#40c057',
|
|
||||||
cancelled: '#fa5252',
|
|
||||||
}
|
|
||||||
|
|
||||||
const TASK_STATUS_LABELS: Record<string, string> = {
|
|
||||||
pending: 'В работе',
|
|
||||||
waiting: 'В очереди',
|
|
||||||
completed: 'Выполнены',
|
|
||||||
cancelled: 'Отменены',
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Dashboard() {
|
export default function Dashboard() {
|
||||||
const navigate = useNavigate()
|
|
||||||
const [stats, setStats] = useState<DashboardStats | null>(null)
|
const [stats, setStats] = useState<DashboardStats | null>(null)
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
const [topicGapsOpened, setTopicGapsOpened] = useState(false)
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const loadData = async () => {
|
const loadData = async () => {
|
||||||
|
|
@ -124,25 +102,6 @@ export default function Dashboard() {
|
||||||
const chartData = stats.statusData.filter(s => s.count > 0)
|
const chartData = stats.statusData.filter(s => s.count > 0)
|
||||||
const totalApprovals = chartData.reduce((sum, s) => sum + s.count, 0)
|
const totalApprovals = chartData.reduce((sum, s) => sum + s.count, 0)
|
||||||
|
|
||||||
const taskChartData = stats.taskStatusData.filter(s => s.count > 0)
|
|
||||||
const totalTasks = taskChartData.reduce((sum, s) => sum + s.count, 0)
|
|
||||||
|
|
||||||
// 🆕 Клик по алерту "просрочены" — ведёт на заявки со status=pending
|
|
||||||
// и date_to = сегодня минус oldPendingDays (те же самые заявки, что
|
|
||||||
// посчитаны в oldPendingCount на бэкенде — общее определение "просрочки").
|
|
||||||
const goToOldPending = () => {
|
|
||||||
const cutoff = dayjs().subtract(stats.oldPendingDays, 'day').format('YYYY-MM-DD')
|
|
||||||
navigate(`/approvals?status=pending&date_to=${cutoff}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
const goToRevision = () => {
|
|
||||||
navigate('/approvals?status=revision')
|
|
||||||
}
|
|
||||||
|
|
||||||
const goToTasksByStatus = (status: string) => {
|
|
||||||
navigate(`/approval-tasks?status=${status}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="lg">
|
<Stack gap="lg">
|
||||||
{/* Заголовок */}
|
{/* Заголовок */}
|
||||||
|
|
@ -156,128 +115,20 @@ export default function Dashboard() {
|
||||||
</Badge>
|
</Badge>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
{/* 🆕 Alert теперь кликабельный — ведёт на отфильтрованный список заявок */}
|
{/* Alert: старые pending заявки */}
|
||||||
{stats.oldPendingCount > 0 && (
|
{stats.oldPendingCount > 0 && (
|
||||||
<UnstyledButton onClick={goToOldPending} style={{ width: '100%' }}>
|
|
||||||
<Alert
|
|
||||||
icon={<IconAlertTriangle size={16} />}
|
|
||||||
color="orange"
|
|
||||||
variant="light"
|
|
||||||
title={`⚠️ ${stats.oldPendingCount} заявок требуют внимания`}
|
|
||||||
style={{ cursor: 'pointer' }}
|
|
||||||
>
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm">
|
|
||||||
Есть заявки, которые находятся на согласовании более {stats.oldPendingDays} дней.
|
|
||||||
</Text>
|
|
||||||
<Group gap={4} c="orange">
|
|
||||||
<Text size="xs" fw={600}>Посмотреть список</Text>
|
|
||||||
<IconChevronRight size={14} />
|
|
||||||
</Group>
|
|
||||||
</Group>
|
|
||||||
</Alert>
|
|
||||||
</UnstyledButton>
|
|
||||||
)}
|
|
||||||
|
|
||||||
|
|
||||||
{/* 🆕 Проблемы конфигурации инициаторов */}
|
|
||||||
{stats.topicGaps.length > 0 && (
|
|
||||||
<UnstyledButton onClick={() => setTopicGapsOpened(true)} style={{ width: '100%' }}>
|
|
||||||
<Paper withBorder p="md" radius="md" style={{ cursor: 'pointer' }}>
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Group>
|
|
||||||
<ThemeIcon variant="light" color="orange" size="lg">
|
|
||||||
<IconAlertTriangle size={18} />
|
|
||||||
</ThemeIcon>
|
|
||||||
<div>
|
|
||||||
<Text fw={600}>
|
|
||||||
{stats.topicGaps.length} {stats.topicGaps.length === 1 ? 'тема без' : 'тем без'} назначенного порядка согласования
|
|
||||||
</Text>
|
|
||||||
<Text size="sm" c="dimmed">
|
|
||||||
Есть право создать заявку, но некому её согласовать — сотрудник наткнётся на ошибку в боте.
|
|
||||||
</Text>
|
|
||||||
</div>
|
|
||||||
</Group>
|
|
||||||
<Group gap={4} c="orange">
|
|
||||||
<Text size="xs" fw={600}>Показать список</Text>
|
|
||||||
<IconChevronRight size={14} />
|
|
||||||
</Group>
|
|
||||||
</Group>
|
|
||||||
</Paper>
|
|
||||||
</UnstyledButton>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{stats.usersWithoutHierarchy.length > 0 && (
|
|
||||||
<Alert
|
<Alert
|
||||||
icon={<IconUserExclamation size={16} />}
|
icon={<IconAlertTriangle size={16} />}
|
||||||
color="red"
|
color="orange"
|
||||||
variant="light"
|
variant="light"
|
||||||
title={`${stats.usersWithoutHierarchy.length} сотрудник(ов) без настроенной иерархии`}
|
title={`⚠️ ${stats.oldPendingCount} заявок требуют внимания`}
|
||||||
>
|
>
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
У перечисленных ниже есть право создавать заявки, но для их отдела не
|
Есть заявки, которые находятся на согласовании более 7 дней.
|
||||||
настроено вообще ни одного правила согласования:{' '}
|
|
||||||
<Text span fw={600}>
|
|
||||||
{stats.usersWithoutHierarchy.map(u => u.full_name || `ID ${u.user_id}`).join(', ')}
|
|
||||||
</Text>
|
|
||||||
</Text>
|
</Text>
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
||||||
<TopicGapsModal
|
|
||||||
opened={topicGapsOpened}
|
|
||||||
onClose={() => setTopicGapsOpened(false)}
|
|
||||||
gaps={stats.topicGaps}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* 🆕 Alert теперь кликабельный — ведёт на заявки на доработке */}
|
|
||||||
{stats.approvals.revision > 0 && (
|
|
||||||
<UnstyledButton onClick={goToRevision} style={{ width: '100%' }}>
|
|
||||||
<Paper withBorder p="md" radius="md" style={{ cursor: 'pointer' }}>
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Group>
|
|
||||||
<ThemeIcon variant="light" color="orange" size="lg">
|
|
||||||
<IconClock size={18} />
|
|
||||||
</ThemeIcon>
|
|
||||||
<div>
|
|
||||||
<Text fw={600}>Требуют внимания: {stats.approvals.revision} заявок на доработке</Text>
|
|
||||||
<Text size="sm" c="dimmed">
|
|
||||||
Эти заявки были возвращены согласующими на доработку и требуют действий от инициаторов.
|
|
||||||
</Text>
|
|
||||||
</div>
|
|
||||||
</Group>
|
|
||||||
<IconChevronRight size={18} color="var(--mantine-color-gray-5)" />
|
|
||||||
</Group>
|
|
||||||
</Paper>
|
|
||||||
</UnstyledButton>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 🆕 Кто отсутствует сегодня */}
|
|
||||||
<Paper withBorder p="md" radius="md">
|
|
||||||
<Group mb="md">
|
|
||||||
<ThemeIcon variant="light" color="gray" size="lg">
|
|
||||||
<IconCalendarOff size={18} />
|
|
||||||
</ThemeIcon>
|
|
||||||
<Text fw={600}>
|
|
||||||
Отсутствуют сегодня{stats.absentToday.length > 0 ? ` (${stats.absentToday.length})` : ''}
|
|
||||||
</Text>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
{stats.absentToday.length === 0 ? (
|
|
||||||
<Text c="dimmed" size="sm">Сегодня все на месте</Text>
|
|
||||||
) : (
|
|
||||||
<SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="xs">
|
|
||||||
{stats.absentToday.map((person, i) => (
|
|
||||||
<Group key={i} gap="xs" wrap="nowrap">
|
|
||||||
<Text size="sm" fw={500} truncate>{person.name}</Text>
|
|
||||||
<Text size="xs" c="dimmed" truncate>— {person.description}</Text>
|
|
||||||
</Group>
|
|
||||||
))}
|
|
||||||
</SimpleGrid>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{/* KPI карточки */}
|
{/* KPI карточки */}
|
||||||
<SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }} spacing="md">
|
<SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }} spacing="md">
|
||||||
<StatCard
|
<StatCard
|
||||||
|
|
@ -314,7 +165,7 @@ export default function Dashboard() {
|
||||||
/>
|
/>
|
||||||
</SimpleGrid>
|
</SimpleGrid>
|
||||||
|
|
||||||
{/* Графики по заявкам */}
|
{/* Графики */}
|
||||||
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
|
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
|
||||||
{/* Pie chart */}
|
{/* Pie chart */}
|
||||||
<Paper withBorder p="md" radius="md">
|
<Paper withBorder p="md" radius="md">
|
||||||
|
|
@ -340,8 +191,6 @@ export default function Dashboard() {
|
||||||
outerRadius={90}
|
outerRadius={90}
|
||||||
paddingAngle={2}
|
paddingAngle={2}
|
||||||
label={(entry: any) => STATUS_LABELS[entry.payload?.status] || entry.payload?.status}
|
label={(entry: any) => STATUS_LABELS[entry.payload?.status] || entry.payload?.status}
|
||||||
onClick={(entry: any) => navigate(`/approvals?status=${entry.status}`)}
|
|
||||||
style={{ cursor: 'pointer' }}
|
|
||||||
>
|
>
|
||||||
{chartData.map((entry, index) => (
|
{chartData.map((entry, index) => (
|
||||||
<Cell
|
<Cell
|
||||||
|
|
@ -407,132 +256,44 @@ export default function Dashboard() {
|
||||||
</Paper>
|
</Paper>
|
||||||
</SimpleGrid>
|
</SimpleGrid>
|
||||||
|
|
||||||
{/* 🆕 Задачи — те же два графика, что у заявок выше */}
|
{/* Топ списки */}
|
||||||
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
|
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
|
||||||
<Paper withBorder p="md" radius="md">
|
{/* Топ тем */}
|
||||||
<Group justify="space-between" mb="md">
|
|
||||||
<Group gap="xs">
|
|
||||||
<ThemeIcon variant="light" color="teal" size="lg">
|
|
||||||
<IconChecklist size={18} />
|
|
||||||
</ThemeIcon>
|
|
||||||
<Text fw={600}>Задачи по статусам</Text>
|
|
||||||
</Group>
|
|
||||||
<Badge variant="light">{totalTasks} всего</Badge>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
{taskChartData.length === 0 ? (
|
|
||||||
<Center h={250}>
|
|
||||||
<Text c="dimmed">Нет данных</Text>
|
|
||||||
</Center>
|
|
||||||
) : (
|
|
||||||
<ResponsiveContainer width="100%" height={250}>
|
|
||||||
<PieChart>
|
|
||||||
<Pie
|
|
||||||
data={taskChartData}
|
|
||||||
dataKey="count"
|
|
||||||
nameKey="status"
|
|
||||||
cx="50%"
|
|
||||||
cy="50%"
|
|
||||||
innerRadius={60}
|
|
||||||
outerRadius={90}
|
|
||||||
paddingAngle={2}
|
|
||||||
label={(entry: any) => TASK_STATUS_LABELS[entry.payload?.status] || entry.payload?.status}
|
|
||||||
onClick={(entry: any) => goToTasksByStatus(entry.status)}
|
|
||||||
style={{ cursor: 'pointer' }}
|
|
||||||
>
|
|
||||||
{taskChartData.map((entry, index) => (
|
|
||||||
<Cell
|
|
||||||
key={`task-cell-${index}`}
|
|
||||||
fill={TASK_STATUS_COLORS[entry.status] || '#868e96'}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Pie>
|
|
||||||
<Tooltip
|
|
||||||
formatter={(value: any, name: any) => [
|
|
||||||
value,
|
|
||||||
TASK_STATUS_LABELS[name] || name
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
</PieChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<Paper withBorder p="md" radius="md">
|
|
||||||
<Group justify="space-between" mb="md">
|
|
||||||
<Text fw={600}>Динамика задач за 7 дней</Text>
|
|
||||||
<Badge variant="light" color="teal">Задачи</Badge>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<ResponsiveContainer width="100%" height={250}>
|
|
||||||
<LineChart data={stats.taskDailyData}>
|
|
||||||
<CartesianGrid strokeDasharray="3 3" />
|
|
||||||
<XAxis
|
|
||||||
dataKey="date"
|
|
||||||
tickFormatter={(d) => dayjs(d).format('DD.MM')}
|
|
||||||
/>
|
|
||||||
<YAxis />
|
|
||||||
<Tooltip
|
|
||||||
labelFormatter={(d) => dayjs(d).format('DD.MM.YYYY')}
|
|
||||||
formatter={(value: any, name: any) => [
|
|
||||||
value,
|
|
||||||
name === 'created' ? 'Создано' : 'Выполнено'
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
<Legend
|
|
||||||
formatter={(value) =>
|
|
||||||
value === 'created' ? 'Создано' : 'Выполнено'
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Line
|
|
||||||
type="monotone"
|
|
||||||
dataKey="created"
|
|
||||||
stroke="#228be6"
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4 }}
|
|
||||||
/>
|
|
||||||
<Line
|
|
||||||
type="monotone"
|
|
||||||
dataKey="completed"
|
|
||||||
stroke="#12b886"
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4 }}
|
|
||||||
/>
|
|
||||||
</LineChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</Paper>
|
|
||||||
</SimpleGrid>
|
|
||||||
|
|
||||||
{/* Разбивка по категориям + узкие места */}
|
|
||||||
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
|
|
||||||
{/* Разбивка по категориям */}
|
|
||||||
<Paper withBorder p="md" radius="md">
|
<Paper withBorder p="md" radius="md">
|
||||||
<Group mb="md">
|
<Group mb="md">
|
||||||
<ThemeIcon variant="light" color="violet" size="lg">
|
<ThemeIcon variant="light" color="violet" size="lg">
|
||||||
<IconCategory size={18} />
|
<IconTrendingUp size={18} />
|
||||||
</ThemeIcon>
|
</ThemeIcon>
|
||||||
<Text fw={600}>Заявки по категориям</Text>
|
<Text fw={600}>Топ-5 самых активных тем</Text>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
{stats.categoryBreakdown.length === 0 ? (
|
{stats.topTopics.length === 0 ? (
|
||||||
<Center h={200}>
|
<Center h={200}>
|
||||||
<Text c="dimmed">Нет данных</Text>
|
<Text c="dimmed">Нет данных</Text>
|
||||||
</Center>
|
</Center>
|
||||||
) : (
|
) : (
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
{stats.categoryBreakdown.map((cat) => {
|
{stats.topTopics.map((topic, index) => {
|
||||||
const maxCount = Math.max(...stats.categoryBreakdown.map(c => c.total_count))
|
const maxCount = Math.max(...stats.topTopics.map(t => t.total_count))
|
||||||
const percent = maxCount > 0 ? (cat.total_count / maxCount) * 100 : 0
|
const percent = (topic.total_count / maxCount) * 100
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box key={cat.id}>
|
<Box key={topic.id}>
|
||||||
<Group justify="space-between" mb={4}>
|
<Group justify="space-between" mb={4}>
|
||||||
<Text size="sm" fw={500}>{cat.name}</Text>
|
|
||||||
<Group gap="xs">
|
<Group gap="xs">
|
||||||
<Text size="sm" fw={600}>{cat.total_count}</Text>
|
<Badge size="sm" variant="light" color="gray">
|
||||||
{cat.pending_count > 0 && (
|
#{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">
|
<Badge size="xs" color="blue" variant="light">
|
||||||
{cat.pending_count} в работе
|
{topic.pending_count} в работе
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
|
|
@ -544,7 +305,70 @@ export default function Dashboard() {
|
||||||
</Stack>
|
</Stack>
|
||||||
)}
|
)}
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
{/* Топ согласующих */}
|
||||||
|
<Paper withBorder p="md" radius="md">
|
||||||
|
<Group mb="md">
|
||||||
|
<ThemeIcon variant="light" color="blue" size="lg">
|
||||||
|
<IconUsers size={18} />
|
||||||
|
</ThemeIcon>
|
||||||
|
<Text fw={600}>Топ-5 согласующих</Text>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
{stats.topApprovers.length === 0 ? (
|
||||||
|
<Center h={200}>
|
||||||
|
<Text c="dimmed">Нет данных</Text>
|
||||||
|
</Center>
|
||||||
|
) : (
|
||||||
|
<Stack gap="sm">
|
||||||
|
{stats.topApprovers.map((approver, index) => {
|
||||||
|
const maxSteps = Math.max(...stats.topApprovers.map(a => a.total_steps))
|
||||||
|
const percent = (approver.total_steps / maxSteps) * 100
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box key={approver.user_id}>
|
||||||
|
<Group justify="space-between" mb={4}>
|
||||||
|
<Group gap="xs">
|
||||||
|
<Badge size="sm" variant="light" color="gray">
|
||||||
|
#{index + 1}
|
||||||
|
</Badge>
|
||||||
|
<div>
|
||||||
|
<Text size="sm" fw={500}>{approver.full_name}</Text>
|
||||||
|
<Text size="xs" c="dimmed">{approver.department_name}</Text>
|
||||||
|
</div>
|
||||||
|
</Group>
|
||||||
|
<Group gap="xs">
|
||||||
|
<Text size="sm" fw={600}>{approver.total_steps}</Text>
|
||||||
|
{approver.pending_steps > 0 && (
|
||||||
|
<Badge size="xs" color="orange" variant="light">
|
||||||
|
{approver.pending_steps} ожидают
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
</Group>
|
||||||
|
<Progress value={percent} size="sm" color="blue" />
|
||||||
|
</Box>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</Stack>
|
||||||
|
)}
|
||||||
|
</Paper>
|
||||||
</SimpleGrid>
|
</SimpleGrid>
|
||||||
|
|
||||||
|
{/* Заявки на доработке */}
|
||||||
|
{stats.approvals.revision > 0 && (
|
||||||
|
<Paper withBorder p="md" radius="md">
|
||||||
|
<Group mb="md">
|
||||||
|
<ThemeIcon variant="light" color="orange" size="lg">
|
||||||
|
<IconClock size={18} />
|
||||||
|
</ThemeIcon>
|
||||||
|
<Text fw={600}>Требуют внимания: {stats.approvals.revision} заявок на доработке</Text>
|
||||||
|
</Group>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
Эти заявки были возвращены согласующими на доработку и требуют действий от инициаторов.
|
||||||
|
</Text>
|
||||||
|
</Paper>
|
||||||
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,333 +0,0 @@
|
||||||
import { useState } from 'react'
|
|
||||||
import {
|
|
||||||
Paper,
|
|
||||||
Table,
|
|
||||||
Group,
|
|
||||||
ActionIcon,
|
|
||||||
Text,
|
|
||||||
TextInput,
|
|
||||||
Select,
|
|
||||||
Pagination,
|
|
||||||
Loader,
|
|
||||||
Center,
|
|
||||||
Tooltip,
|
|
||||||
Box,
|
|
||||||
Stack,
|
|
||||||
Badge,
|
|
||||||
} from '@mantine/core'
|
|
||||||
import { DatePickerInput } from '@mantine/dates'
|
|
||||||
import { IconTrash, IconSearch, IconX, IconEye } from '@tabler/icons-react'
|
|
||||||
import { modals } from '@mantine/modals'
|
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
|
||||||
import { useAdminLogs, useDeleteAdminLog } from '@/features/adminLogs/hooks/useAdminLogs'
|
|
||||||
import type { AdminActionLog } from '@/api/adminLogs'
|
|
||||||
import AdminLogDetailModal from './components/AdminLogDetailModal'
|
|
||||||
import dayjs from 'dayjs'
|
|
||||||
import 'dayjs/locale/ru'
|
|
||||||
import {formatMsk} from "@/utils/date.ts";
|
|
||||||
|
|
||||||
dayjs.locale('ru')
|
|
||||||
|
|
||||||
const LIMIT = 50
|
|
||||||
|
|
||||||
const ACTION_COLORS: Record<string, string> = {
|
|
||||||
create: 'green',
|
|
||||||
update: 'blue',
|
|
||||||
delete: 'red',
|
|
||||||
}
|
|
||||||
const ACTION_LABELS: Record<string, string> = {
|
|
||||||
create: 'Создание',
|
|
||||||
update: 'Изменение',
|
|
||||||
delete: 'Удаление',
|
|
||||||
}
|
|
||||||
|
|
||||||
const ENTITY_TYPE_OPTIONS = [
|
|
||||||
{ value: 'user', label: 'Пользователь' },
|
|
||||||
{ value: 'admin', label: 'Администратор' },
|
|
||||||
{ value: 'department', label: 'Отдел' },
|
|
||||||
{ value: 'role', label: 'Роль' },
|
|
||||||
{ value: 'permission', label: 'Право' },
|
|
||||||
{ value: 'category', label: 'Категория' },
|
|
||||||
{ value: 'topic', label: 'Тема' },
|
|
||||||
{ value: 'topic_executor', label: 'Исполнитель темы' },
|
|
||||||
{ value: 'hierarchy', label: 'Иерархия' },
|
|
||||||
{ value: 'flow_node', label: 'Узел дерева' },
|
|
||||||
{ value: 'flow_tree', label: 'Дерево категории' },
|
|
||||||
{ value: 'user_role', label: 'Роль пользователя' },
|
|
||||||
{ value: 'user_roles', label: 'Роли пользователя (массово)' },
|
|
||||||
{ value: 'approval_task', label: 'Задача' },
|
|
||||||
{ value: 'notification', label: 'Рассылка' },
|
|
||||||
]
|
|
||||||
|
|
||||||
export default function AdminLogPage() {
|
|
||||||
const { user: currentUser } = useAuth()
|
|
||||||
const isRoot = currentUser?.is_root === true
|
|
||||||
|
|
||||||
const [page, setPage] = useState(1)
|
|
||||||
const [adminLogin, setAdminLogin] = useState('')
|
|
||||||
const [action, setAction] = useState<string | null>(null)
|
|
||||||
const [entityType, setEntityType] = useState<string | null>(null)
|
|
||||||
const [entityId, setEntityId] = useState('')
|
|
||||||
const [search, setSearch] = useState('')
|
|
||||||
const [dateFrom, setDateFrom] = useState<Date | null>(null)
|
|
||||||
const [dateTo, setDateTo] = useState<Date | null>(null)
|
|
||||||
const [selectedLog, setSelectedLog] = useState<AdminActionLog | null>(null)
|
|
||||||
|
|
||||||
const { data, isLoading, isFetching } = useAdminLogs({
|
|
||||||
offset: (page - 1) * LIMIT,
|
|
||||||
limit: LIMIT,
|
|
||||||
...(adminLogin && { admin_login: adminLogin }),
|
|
||||||
...(action && { action }),
|
|
||||||
...(entityType && { entity_type: entityType }),
|
|
||||||
...(entityId && { entity_id: Number(entityId) }),
|
|
||||||
...(search && { search }),
|
|
||||||
...(dateFrom && { date_from: dayjs(dateFrom).format('YYYY-MM-DD') }),
|
|
||||||
...(dateTo && { date_to: dayjs(dateTo).format('YYYY-MM-DD') }),
|
|
||||||
})
|
|
||||||
|
|
||||||
const deleteLog = useDeleteAdminLog()
|
|
||||||
|
|
||||||
const logs = data?.data || []
|
|
||||||
const totalCount = data?.total_count || 0
|
|
||||||
const totalPages = totalCount ? Math.ceil(totalCount / LIMIT) : 1
|
|
||||||
|
|
||||||
const hasActiveFilters = adminLogin || action || entityType || entityId || search || dateFrom || dateTo
|
|
||||||
|
|
||||||
const handleResetFilters = () => {
|
|
||||||
setAdminLogin('')
|
|
||||||
setAction(null)
|
|
||||||
setEntityType(null)
|
|
||||||
setEntityId('')
|
|
||||||
setSearch('')
|
|
||||||
setDateFrom(null)
|
|
||||||
setDateTo(null)
|
|
||||||
setPage(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDelete = (entry: AdminActionLog) => {
|
|
||||||
modals.openConfirmModal({
|
|
||||||
title: 'Удалить запись журнала?',
|
|
||||||
children: (
|
|
||||||
<Text size="sm">
|
|
||||||
Это действие доступно только root-администратору и необратимо.
|
|
||||||
Обычно записи журнала не удаляют — используйте только если запись
|
|
||||||
ошибочна или содержит чувствительные данные, которые нужно убрать.
|
|
||||||
</Text>
|
|
||||||
),
|
|
||||||
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
|
||||||
confirmProps: { color: 'red' },
|
|
||||||
onConfirm: () => deleteLog.mutate(entry.id),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Stack gap="md">
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="xl" fw={700}>Журнал действий администраторов</Text>
|
|
||||||
<Text c="dimmed" size="sm">Всего: {totalCount}</Text>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Paper withBorder p="md">
|
|
||||||
<Stack gap="md">
|
|
||||||
<Group gap="md" align="flex-end" grow>
|
|
||||||
<TextInput
|
|
||||||
label="Администратор"
|
|
||||||
placeholder="Логин..."
|
|
||||||
leftSection={<IconSearch size={16} />}
|
|
||||||
value={adminLogin}
|
|
||||||
onChange={(e) => {
|
|
||||||
setAdminLogin(e.currentTarget.value)
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Действие"
|
|
||||||
placeholder="Все"
|
|
||||||
data={[
|
|
||||||
{ value: 'create', label: 'Создание' },
|
|
||||||
{ value: 'update', label: 'Изменение' },
|
|
||||||
{ value: 'delete', label: 'Удаление' },
|
|
||||||
]}
|
|
||||||
value={action}
|
|
||||||
onChange={(v) => {
|
|
||||||
setAction(v)
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
clearable
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Тип сущности"
|
|
||||||
placeholder="Все"
|
|
||||||
data={ENTITY_TYPE_OPTIONS}
|
|
||||||
value={entityType}
|
|
||||||
onChange={(v) => {
|
|
||||||
setEntityType(v)
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
clearable
|
|
||||||
searchable
|
|
||||||
/>
|
|
||||||
|
|
||||||
<TextInput
|
|
||||||
label="ID сущности"
|
|
||||||
placeholder="Например, 19"
|
|
||||||
value={entityId}
|
|
||||||
onChange={(e) => {
|
|
||||||
setEntityId(e.currentTarget.value.replace(/\D/g, ''))
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Group gap="md" align="flex-end" grow>
|
|
||||||
<TextInput
|
|
||||||
label="Поиск по описанию"
|
|
||||||
placeholder="Введите текст..."
|
|
||||||
leftSection={<IconSearch size={16} />}
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => {
|
|
||||||
setSearch(e.currentTarget.value)
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
rightSection={
|
|
||||||
search && (
|
|
||||||
<ActionIcon variant="subtle" onClick={() => setSearch('')}>
|
|
||||||
<IconX size={14} />
|
|
||||||
</ActionIcon>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<DatePickerInput
|
|
||||||
label="С даты"
|
|
||||||
placeholder="Выберите дату"
|
|
||||||
value={dateFrom}
|
|
||||||
onChange={(val) => {
|
|
||||||
setDateFrom(val as Date | null)
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
clearable
|
|
||||||
maxDate={dateTo || undefined}
|
|
||||||
/>
|
|
||||||
<DatePickerInput
|
|
||||||
label="По дату"
|
|
||||||
placeholder="Выберите дату"
|
|
||||||
value={dateTo}
|
|
||||||
onChange={(val) => {
|
|
||||||
setDateTo(val as Date | null)
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
clearable
|
|
||||||
minDate={dateFrom || undefined}
|
|
||||||
/>
|
|
||||||
<Box>
|
|
||||||
{hasActiveFilters && (
|
|
||||||
<ActionIcon variant="light" color="gray" size="lg" onClick={handleResetFilters} title="Сбросить фильтры">
|
|
||||||
<IconX size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<Paper withBorder>
|
|
||||||
{isLoading ? (
|
|
||||||
<Center p={60}>
|
|
||||||
<Loader />
|
|
||||||
</Center>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Table striped highlightOnHover>
|
|
||||||
<Table.Thead>
|
|
||||||
<Table.Tr>
|
|
||||||
<Table.Th style={{ width: 160 }}>Когда</Table.Th>
|
|
||||||
<Table.Th>Администратор</Table.Th>
|
|
||||||
<Table.Th style={{ width: 120 }}>Действие</Table.Th>
|
|
||||||
<Table.Th style={{ width: 160 }}>Сущность</Table.Th>
|
|
||||||
<Table.Th>Описание</Table.Th>
|
|
||||||
<Table.Th style={{ width: 90 }}>—</Table.Th>
|
|
||||||
</Table.Tr>
|
|
||||||
</Table.Thead>
|
|
||||||
<Table.Tbody>
|
|
||||||
{logs.length === 0 ? (
|
|
||||||
<Table.Tr>
|
|
||||||
<Table.Td colSpan={6}>
|
|
||||||
<Center p={40}>
|
|
||||||
<Text c="dimmed">Записей не найдено</Text>
|
|
||||||
</Center>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
) : (
|
|
||||||
logs.map((entry) => (
|
|
||||||
<Table.Tr key={entry.id} style={{ cursor: 'pointer' }} onClick={() => setSelectedLog(entry)}>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="xs" c="dimmed">
|
|
||||||
{formatMsk(entry.created_at)}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" fw={500}>{entry.admin_login}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Badge size="sm" color={ACTION_COLORS[entry.action] || 'gray'} variant="light">
|
|
||||||
{ACTION_LABELS[entry.action] || entry.action}
|
|
||||||
</Badge>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Badge size="sm" variant="outline" color="gray">
|
|
||||||
{entry.entity_type}{entry.entity_id ? ` #${entry.entity_id}` : ''}
|
|
||||||
</Badge>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" lineClamp={1}>{entry.description}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td onClick={(e) => e.stopPropagation()}>
|
|
||||||
<Group gap="xs">
|
|
||||||
<Tooltip label="Детали">
|
|
||||||
<ActionIcon variant="light" color="blue" onClick={() => setSelectedLog(entry)}>
|
|
||||||
<IconEye size={14} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
{isRoot && (
|
|
||||||
<Tooltip label="Удалить (только root)">
|
|
||||||
<ActionIcon variant="light" color="red" onClick={() => handleDelete(entry)}>
|
|
||||||
<IconTrash size={14} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Table.Tbody>
|
|
||||||
</Table>
|
|
||||||
|
|
||||||
{totalPages > 1 && (
|
|
||||||
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">Страница {page} из {totalPages}</Text>
|
|
||||||
<Pagination value={page} onChange={setPage} total={totalPages} withEdges />
|
|
||||||
</Group>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{isFetching && !isLoading && (
|
|
||||||
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
|
|
||||||
<Loader size="xs" />
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<AdminLogDetailModal
|
|
||||||
log={selectedLog}
|
|
||||||
opened={selectedLog !== null}
|
|
||||||
onClose={() => setSelectedLog(null)}
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,105 +0,0 @@
|
||||||
import { useMemo } from 'react'
|
|
||||||
import { Modal, Stack, Text, Table, Badge, Group, Code, Center } from '@mantine/core'
|
|
||||||
import type { AdminActionLog } from '@/api/adminLogs'
|
|
||||||
|
|
||||||
interface FieldChange {
|
|
||||||
field: string
|
|
||||||
old: unknown
|
|
||||||
new: unknown
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AdminLogDetailModalProps {
|
|
||||||
log: AdminActionLog | null
|
|
||||||
opened: boolean
|
|
||||||
onClose: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatValue(v: unknown): string {
|
|
||||||
if (v === null || v === undefined || v === '') return '—'
|
|
||||||
if (typeof v === 'boolean') return v ? 'да' : 'нет'
|
|
||||||
if (Array.isArray(v)) return v.length ? v.join(', ') : '—'
|
|
||||||
return String(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function AdminLogDetailModal({ log, opened, onClose }: AdminLogDetailModalProps) {
|
|
||||||
const parsed = useMemo(() => {
|
|
||||||
if (!log?.metadata) return null
|
|
||||||
try {
|
|
||||||
return JSON.parse(log.metadata) as {
|
|
||||||
changes?: FieldChange[]
|
|
||||||
snapshot?: Record<string, unknown>
|
|
||||||
[key: string]: unknown
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}, [log])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal opened={opened} onClose={onClose} title="Детали действия" size="lg">
|
|
||||||
{!log ? null : (
|
|
||||||
<Stack gap="md">
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">{log.admin_login}</Text>
|
|
||||||
<Badge variant="light">{log.entity_type}</Badge>
|
|
||||||
</Group>
|
|
||||||
<Text>{log.description}</Text>
|
|
||||||
|
|
||||||
{parsed?.changes && parsed.changes.length > 0 && (
|
|
||||||
<Table striped withTableBorder>
|
|
||||||
<Table.Thead>
|
|
||||||
<Table.Tr>
|
|
||||||
<Table.Th>Поле</Table.Th>
|
|
||||||
<Table.Th>Было</Table.Th>
|
|
||||||
<Table.Th>Стало</Table.Th>
|
|
||||||
</Table.Tr>
|
|
||||||
</Table.Thead>
|
|
||||||
<Table.Tbody>
|
|
||||||
{parsed.changes.map((c, i) => (
|
|
||||||
<Table.Tr key={i}>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" ff="monospace">{c.field}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" c="red">{formatValue(c.old)}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" c="green">{formatValue(c.new)}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
))}
|
|
||||||
</Table.Tbody>
|
|
||||||
</Table>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{parsed?.snapshot && (
|
|
||||||
<Table striped withTableBorder>
|
|
||||||
<Table.Tbody>
|
|
||||||
{Object.entries(parsed.snapshot).map(([key, value]) => (
|
|
||||||
<Table.Tr key={key}>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" ff="monospace" c="dimmed">{key}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm">{formatValue(value)}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
))}
|
|
||||||
</Table.Tbody>
|
|
||||||
</Table>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!parsed?.changes && !parsed?.snapshot && parsed && (
|
|
||||||
<Code block>{JSON.stringify(parsed, null, 2)}</Code>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!log.metadata && (
|
|
||||||
<Center p="md">
|
|
||||||
<Text c="dimmed" size="sm">Дополнительных данных нет</Text>
|
|
||||||
</Center>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -24,7 +24,6 @@ import {
|
||||||
IconLockOpen,
|
IconLockOpen,
|
||||||
IconPencil,
|
IconPencil,
|
||||||
IconShield,
|
IconShield,
|
||||||
IconUser, IconChartBar,
|
|
||||||
} from '@tabler/icons-react'
|
} from '@tabler/icons-react'
|
||||||
import { modals } from '@mantine/modals'
|
import { modals } from '@mantine/modals'
|
||||||
import { notifications } from '@mantine/notifications'
|
import { notifications } from '@mantine/notifications'
|
||||||
|
|
@ -39,7 +38,6 @@ import EditAdminModal from './components/EditAdminModal'
|
||||||
import type { Admin } from '@/types/api'
|
import type { Admin } from '@/types/api'
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
import 'dayjs/locale/ru'
|
import 'dayjs/locale/ru'
|
||||||
import {formatMsk} from "@/utils/date.ts";
|
|
||||||
|
|
||||||
dayjs.locale('ru')
|
dayjs.locale('ru')
|
||||||
|
|
||||||
|
|
@ -209,8 +207,6 @@ export default function AdminsPage() {
|
||||||
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
||||||
<Table.Th>Логин</Table.Th>
|
<Table.Th>Логин</Table.Th>
|
||||||
<Table.Th>Имя</Table.Th>
|
<Table.Th>Имя</Table.Th>
|
||||||
<Table.Th>Роль</Table.Th>
|
|
||||||
<Table.Th>Telegram</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>Последний IP</Table.Th>
|
||||||
|
|
@ -221,7 +217,7 @@ export default function AdminsPage() {
|
||||||
<Table.Tbody>
|
<Table.Tbody>
|
||||||
{data?.data?.length === 0 ? (
|
{data?.data?.length === 0 ? (
|
||||||
<Table.Tr>
|
<Table.Tr>
|
||||||
<Table.Td colSpan={10}>
|
<Table.Td colSpan={8}>
|
||||||
<Center p={40}>
|
<Center p={40}>
|
||||||
<Text c="dimmed">Администраторы не найдены</Text>
|
<Text c="dimmed">Администраторы не найдены</Text>
|
||||||
</Center>
|
</Center>
|
||||||
|
|
@ -257,50 +253,17 @@ export default function AdminsPage() {
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Text size="sm">{admin.name || '—'}</Text>
|
<Text size="sm">{admin.name || '—'}</Text>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
|
||||||
<Group gap={4}>
|
|
||||||
{isAdminRoot && (
|
|
||||||
<Badge size="xs" color="red" variant="filled" leftSection={<IconShield size={10} />}>
|
|
||||||
ROOT
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{admin.is_analyst && (
|
|
||||||
<Badge size="xs" color="grape" variant="filled" leftSection={<IconChartBar size={10} />}>
|
|
||||||
Аналитик
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{admin.is_observer && (
|
|
||||||
<Badge size="xs" color="blue" variant="filled" leftSection={<IconUser size={10} />}>
|
|
||||||
Наблюдатель
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{!isAdminRoot && !admin.is_observer && !admin.is_analyst && (
|
|
||||||
<Badge size="xs" color="gray" variant="light">
|
|
||||||
Менеджер / Админ
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
{admin.telegram_user ? (
|
|
||||||
<Text size="sm">{admin.telegram_user.full_name || admin.telegram_user.username || '—'}</Text>
|
|
||||||
) : admin.telegram_id ? (
|
|
||||||
<Text size="sm" c="dimmed">ID: {admin.telegram_id}</Text>
|
|
||||||
) : (
|
|
||||||
<Text size="sm" c="dimmed">—</Text>
|
|
||||||
)}
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Text size="sm" c="dimmed">
|
<Text size="sm" c="dimmed">
|
||||||
{admin.created_at
|
{admin.created_at
|
||||||
? formatMsk(admin.created_at)
|
? dayjs(admin.created_at).format('DD.MM.YYYY')
|
||||||
: '—'}
|
: '—'}
|
||||||
</Text>
|
</Text>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Text size="sm" c="dimmed">
|
<Text size="sm" c="dimmed">
|
||||||
{admin.last_login
|
{admin.last_login
|
||||||
? formatMsk(admin.last_login)
|
? dayjs(admin.last_login).format('DD.MM.YYYY HH:mm')
|
||||||
: '—'}
|
: '—'}
|
||||||
</Text>
|
</Text>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useState, useEffect } from 'react'
|
import { useState } from 'react'
|
||||||
import {
|
import {
|
||||||
Modal,
|
Modal,
|
||||||
Stack,
|
Stack,
|
||||||
|
|
@ -13,21 +13,10 @@ import {
|
||||||
Paper,
|
Paper,
|
||||||
Code,
|
Code,
|
||||||
Switch,
|
Switch,
|
||||||
Select,
|
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { useForm } from '@mantine/form'
|
import { useForm } from '@mantine/form'
|
||||||
import {
|
import { IconCheck, IconCopy, IconKey, IconAlertCircle, IconShield } from '@tabler/icons-react'
|
||||||
IconCheck,
|
|
||||||
IconCopy,
|
|
||||||
IconKey,
|
|
||||||
IconAlertCircle,
|
|
||||||
IconShield,
|
|
||||||
IconUser,
|
|
||||||
IconChartBar,
|
|
||||||
IconBriefcase // 🟢 Добавили иконку для менеджера
|
|
||||||
} from '@tabler/icons-react'
|
|
||||||
import { useCreateAdmin } from '@/features/admins/hooks/useAdmins'
|
import { useCreateAdmin } from '@/features/admins/hooks/useAdmins'
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
|
||||||
import type { Admin } from '@/types/api'
|
import type { Admin } from '@/types/api'
|
||||||
|
|
||||||
interface CreateAdminModalProps {
|
interface CreateAdminModalProps {
|
||||||
|
|
@ -38,17 +27,12 @@ interface CreateAdminModalProps {
|
||||||
export default function CreateAdminModal({ opened, onClose }: CreateAdminModalProps) {
|
export default function CreateAdminModal({ opened, onClose }: CreateAdminModalProps) {
|
||||||
const [createdAdmin, setCreatedAdmin] = useState<Admin | null>(null)
|
const [createdAdmin, setCreatedAdmin] = useState<Admin | null>(null)
|
||||||
const createAdmin = useCreateAdmin()
|
const createAdmin = useCreateAdmin()
|
||||||
const { data: usersData } = useUsers({ limit: 1000 })
|
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
initialValues: {
|
initialValues: {
|
||||||
login: '',
|
login: '',
|
||||||
name: '',
|
name: '',
|
||||||
is_root: false,
|
is_root: false,
|
||||||
is_observer: false,
|
|
||||||
is_analyst: false,
|
|
||||||
is_manager: false, // 🟢 Виртуальный флаг только для формы
|
|
||||||
telegram_id: null as number | null,
|
|
||||||
},
|
},
|
||||||
validate: {
|
validate: {
|
||||||
login: (value) => {
|
login: (value) => {
|
||||||
|
|
@ -56,40 +40,15 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
if (!/^[a-zA-Z0-9_]+$/.test(value)) return 'Логин может содержать только буквы, цифры и подчеркивания'
|
if (!/^[a-zA-Z0-9_]+$/.test(value)) return 'Логин может содержать только буквы, цифры и подчеркивания'
|
||||||
return null
|
return null
|
||||||
},
|
},
|
||||||
telegram_id: (value, values) => {
|
|
||||||
// 🟢 Требуем Telegram ID и для наблюдателя, и для менеджера
|
|
||||||
if ((values.is_observer || values.is_manager) && !value) {
|
|
||||||
return 'Для этой роли обязательно выберите Telegram-аккаунт'
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
// Сброс telegram_id при снятии галочек
|
|
||||||
useEffect(() => {
|
|
||||||
if (!form.values.is_observer && !form.values.is_manager) {
|
|
||||||
form.setFieldValue('telegram_id', null)
|
|
||||||
}
|
|
||||||
}, [form.values.is_observer, form.values.is_manager])
|
|
||||||
|
|
||||||
const userOptions = usersData?.data
|
|
||||||
?.filter((u) => u.telegram_id && u.telegram_id > 0)
|
|
||||||
.map((u) => ({
|
|
||||||
value: String(u.telegram_id),
|
|
||||||
label: u.full_name || u.username || `ID: ${u.telegram_id}`,
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const handleSubmit = async (values: typeof form.values) => {
|
const handleSubmit = async (values: typeof form.values) => {
|
||||||
try {
|
try {
|
||||||
const admin = await createAdmin.mutateAsync({
|
const admin = await createAdmin.mutateAsync({
|
||||||
login: values.login,
|
login: values.login,
|
||||||
name: values.name || undefined,
|
name: values.name || undefined,
|
||||||
is_root: values.is_root,
|
is_root: values.is_root,
|
||||||
is_analyst: values.is_analyst,
|
|
||||||
is_observer: values.is_observer,
|
|
||||||
// 🟢 Отправляем telegram_id, если выбран наблюдатель или менеджер
|
|
||||||
telegram_id: (values.is_observer || values.is_manager) ? values.telegram_id! : undefined,
|
|
||||||
})
|
})
|
||||||
setCreatedAdmin(admin)
|
setCreatedAdmin(admin)
|
||||||
form.reset()
|
form.reset()
|
||||||
|
|
@ -100,7 +59,6 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
|
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
setCreatedAdmin(null)
|
setCreatedAdmin(null)
|
||||||
form.reset()
|
|
||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -115,16 +73,16 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
<Alert
|
<Alert
|
||||||
icon={<IconKey size={16} />}
|
icon={<IconKey size={16} />}
|
||||||
title="Учетная запись создана"
|
title="Администратор создан"
|
||||||
color="green"
|
color="green"
|
||||||
variant="light"
|
variant="light"
|
||||||
>
|
>
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
Логин: <Code>{createdAdmin.login}</Code>
|
Администратор <Code>{createdAdmin.login}</Code> успешно создан.
|
||||||
{createdAdmin.is_root && <Text size="sm" fw={600} mt={4}>Выданы root-права</Text>}
|
{createdAdmin.is_root && (
|
||||||
{createdAdmin.is_observer && <Text size="sm" fw={600} mt={4}>Роль: Наблюдатель</Text>}
|
<Text size="sm" fw={600} mt={4}>
|
||||||
{!createdAdmin.is_root && !createdAdmin.is_observer && !createdAdmin.is_analyst && (
|
Выданы root-права 👑
|
||||||
<Text size="sm" fw={600} mt={4}>Роль: Менеджер</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
</Text>
|
</Text>
|
||||||
</Alert>
|
</Alert>
|
||||||
|
|
@ -175,7 +133,7 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
<TextInput
|
<TextInput
|
||||||
label="Логин"
|
label="Логин"
|
||||||
placeholder="user_login"
|
placeholder="admin_user"
|
||||||
required
|
required
|
||||||
description="Уникальный идентификатор (буквы, цифры, подчеркивания)"
|
description="Уникальный идентификатор (буквы, цифры, подчеркивания)"
|
||||||
{...form.getInputProps('login')}
|
{...form.getInputProps('login')}
|
||||||
|
|
@ -184,35 +142,10 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
<TextInput
|
<TextInput
|
||||||
label="Имя (опционально)"
|
label="Имя (опционально)"
|
||||||
placeholder="Иванов Иван"
|
placeholder="Иванов Иван"
|
||||||
description="Отображаемое имя пользователя"
|
description="Отображаемое имя администратора"
|
||||||
{...form.getInputProps('name')}
|
{...form.getInputProps('name')}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 🟢 НОВЫЙ БЛОК: МЕНЕДЖЕР */}
|
|
||||||
<Paper withBorder p="md" bg={form.values.is_manager ? 'teal.0' : 'gray.0'}>
|
|
||||||
<Switch
|
|
||||||
label={
|
|
||||||
<Group gap="xs">
|
|
||||||
<IconBriefcase size={16} color="teal" />
|
|
||||||
<Text fw={600}>Менеджер</Text>
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
description="Только доступ к приложению заказов. Обязательна привязка к Telegram."
|
|
||||||
checked={form.values.is_manager}
|
|
||||||
onChange={(e) => {
|
|
||||||
const checked = e.currentTarget.checked;
|
|
||||||
form.setFieldValue('is_manager', checked);
|
|
||||||
// Если включаем менеджера, сбрасываем админские права
|
|
||||||
if (checked) {
|
|
||||||
form.setFieldValue('is_root', false);
|
|
||||||
form.setFieldValue('is_analyst', false);
|
|
||||||
form.setFieldValue('is_observer', false);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
color="teal"
|
|
||||||
/>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<Paper withBorder p="md" bg={form.values.is_root ? 'red.0' : 'gray.0'}>
|
<Paper withBorder p="md" bg={form.values.is_root ? 'red.0' : 'gray.0'}>
|
||||||
<Switch
|
<Switch
|
||||||
label={
|
label={
|
||||||
|
|
@ -221,64 +154,19 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
<Text fw={600}>Выдать root-права</Text>
|
<Text fw={600}>Выдать root-права</Text>
|
||||||
</Group>
|
</Group>
|
||||||
}
|
}
|
||||||
description="Полный контроль над админ-панелью"
|
description="Администратор сможет создавать других администраторов и управлять root-правами"
|
||||||
checked={form.values.is_root}
|
checked={form.values.is_root}
|
||||||
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
||||||
color="red"
|
color="red"
|
||||||
disabled={form.values.is_observer || form.values.is_manager}
|
|
||||||
/>
|
/>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
<Paper withBorder p="md" bg={form.values.is_analyst ? 'grape.0' : 'gray.0'}>
|
{form.values.is_root && (
|
||||||
<Switch
|
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
|
||||||
label={
|
<Text size="sm">
|
||||||
<Group gap="xs">
|
<b>Внимание!</b> Root-права дают полный доступ к системе, включая создание и удаление других администраторов.
|
||||||
<IconChartBar size={16} color="grape" />
|
</Text>
|
||||||
<Text fw={600}>Аналитик</Text>
|
</Alert>
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
description="Доступ к настройкам и просмотру всех заказов на месяц."
|
|
||||||
checked={form.values.is_analyst}
|
|
||||||
onChange={(e) => form.setFieldValue('is_analyst', e.currentTarget.checked)}
|
|
||||||
color="grape"
|
|
||||||
disabled={form.values.is_root || form.values.is_observer || form.values.is_manager}
|
|
||||||
/>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<Paper withBorder p="md" bg={form.values.is_observer ? 'blue.0' : 'gray.0'}>
|
|
||||||
<Switch
|
|
||||||
label={
|
|
||||||
<Group gap="xs">
|
|
||||||
<IconUser size={16} color="blue" />
|
|
||||||
<Text fw={600}>Наблюдатель</Text>
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
description="Ограниченный доступ к заявкам. Обязательна привязка к Telegram."
|
|
||||||
checked={form.values.is_observer}
|
|
||||||
onChange={(e) => {
|
|
||||||
const checked = e.currentTarget.checked;
|
|
||||||
form.setFieldValue('is_observer', checked);
|
|
||||||
if (checked) form.setFieldValue('is_manager', false);
|
|
||||||
}}
|
|
||||||
color="blue"
|
|
||||||
disabled={form.values.is_root || form.values.is_manager}
|
|
||||||
/>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{/* 🟢 ИСПРАВЛЕННОЕ УСЛОВИЕ */}
|
|
||||||
{(form.values.is_observer || form.values.is_manager) && (
|
|
||||||
<Select
|
|
||||||
label="Telegram-аккаунт"
|
|
||||||
placeholder="Выберите пользователя"
|
|
||||||
data={userOptions}
|
|
||||||
value={form.values.telegram_id ? String(form.values.telegram_id) : null}
|
|
||||||
onChange={(v) => form.setFieldValue('telegram_id', v ? Number(v) : null)}
|
|
||||||
searchable
|
|
||||||
required
|
|
||||||
error={form.errors.telegram_id}
|
|
||||||
description="Связь с реальным сотрудником из бота"
|
|
||||||
nothingFoundMessage="Пользователи не найдены"
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Group justify="flex-end" mt="md">
|
<Group justify="flex-end" mt="md">
|
||||||
|
|
|
||||||
|
|
@ -10,13 +10,11 @@ import {
|
||||||
Switch,
|
Switch,
|
||||||
Paper,
|
Paper,
|
||||||
Alert,
|
Alert,
|
||||||
Select,
|
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { useForm } from '@mantine/form'
|
import { useForm } from '@mantine/form'
|
||||||
import { IconShield, IconAlertCircle, IconUser, IconChartBar, IconBriefcase } from '@tabler/icons-react'
|
import { IconShield, IconAlertCircle } from '@tabler/icons-react'
|
||||||
import { useUpdateAdmin } from '@/features/admins/hooks/useAdmins'
|
import { useUpdateAdmin } from '@/features/admins/hooks/useAdmins'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
|
||||||
import type { Admin } from '@/types/api'
|
import type { Admin } from '@/types/api'
|
||||||
|
|
||||||
interface EditAdminModalProps {
|
interface EditAdminModalProps {
|
||||||
|
|
@ -28,72 +26,31 @@ interface EditAdminModalProps {
|
||||||
export default function EditAdminModal({ admin, opened, onClose }: EditAdminModalProps) {
|
export default function EditAdminModal({ admin, opened, onClose }: EditAdminModalProps) {
|
||||||
const updateAdmin = useUpdateAdmin()
|
const updateAdmin = useUpdateAdmin()
|
||||||
const { user: currentUser } = useAuth()
|
const { user: currentUser } = useAuth()
|
||||||
const { data: usersData } = useUsers({ limit: 1000 })
|
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
initialValues: {
|
initialValues: {
|
||||||
name: '',
|
name: '',
|
||||||
is_root: false,
|
is_root: false,
|
||||||
is_observer: false,
|
|
||||||
is_analyst: false,
|
|
||||||
is_manager: false,
|
|
||||||
telegram_id: null as number | null,
|
|
||||||
},
|
|
||||||
validate: {
|
|
||||||
telegram_id: (value: any, values: { is_observer: any; is_manager: any }) => {
|
|
||||||
// Требуем Telegram ID для наблюдателя или менеджера
|
|
||||||
if ((values.is_observer || values.is_manager) && !value) {
|
|
||||||
return 'Для этой роли обязательно выберите Telegram-аккаунт'
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (admin) {
|
if (admin) {
|
||||||
const isManagerAccount = !admin.is_root && !admin.is_observer && !admin.is_analyst
|
|
||||||
|
|
||||||
form.setValues({
|
form.setValues({
|
||||||
name: admin.name || '',
|
name: admin.name || '',
|
||||||
is_root: admin.is_root ?? false,
|
is_root: admin.is_root ?? false,
|
||||||
is_observer: admin.is_observer ?? false,
|
|
||||||
is_analyst: admin.is_analyst ?? false,
|
|
||||||
is_manager: isManagerAccount,
|
|
||||||
telegram_id: admin.telegram_id || null,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}, [admin])
|
}, [admin])
|
||||||
|
|
||||||
// Сброс telegram_id, если ни наблюдатель, ни менеджер не выбраны
|
|
||||||
useEffect(() => {
|
|
||||||
if (!form.values.is_observer && !form.values.is_manager) {
|
|
||||||
form.setFieldValue('telegram_id', null)
|
|
||||||
}
|
|
||||||
}, [form.values.is_observer, form.values.is_manager])
|
|
||||||
|
|
||||||
const isCurrentUser = currentUser?.id === admin?.id
|
const isCurrentUser = currentUser?.id === admin?.id
|
||||||
|
|
||||||
const userOptions = usersData?.data
|
|
||||||
?.filter((u) => u.telegram_id && u.telegram_id > 0)
|
|
||||||
.map((u) => ({
|
|
||||||
value: String(u.telegram_id),
|
|
||||||
label: u.full_name || u.username || `ID: ${u.telegram_id}`,
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const handleSubmit = async (values: typeof form.values) => {
|
const handleSubmit = async (values: typeof form.values) => {
|
||||||
if (!admin?.id) return
|
if (!admin?.id) return
|
||||||
|
|
||||||
// Если выбран менеджер, то все административные флаги сбрасываются в false
|
|
||||||
const isManager = values.is_manager
|
|
||||||
|
|
||||||
await updateAdmin.mutateAsync({
|
await updateAdmin.mutateAsync({
|
||||||
id: admin.id,
|
id: admin.id,
|
||||||
name: values.name || undefined,
|
name: values.name || undefined,
|
||||||
is_root: isManager ? false : values.is_root,
|
is_root: values.is_root,
|
||||||
is_analyst: isManager ? false : values.is_analyst,
|
|
||||||
is_observer: isManager ? false : values.is_observer,
|
|
||||||
telegram_id: (values.is_observer || isManager) ? values.telegram_id! : null,
|
|
||||||
})
|
})
|
||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
@ -111,21 +68,6 @@ export default function EditAdminModal({ admin, opened, onClose }: EditAdminModa
|
||||||
ROOT
|
ROOT
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
{admin?.is_analyst && (
|
|
||||||
<Badge color="grape" variant="filled" leftSection={<IconChartBar size={12} />}>
|
|
||||||
Аналитик
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{admin?.is_observer && (
|
|
||||||
<Badge color="blue" variant="filled" leftSection={<IconUser size={12} />}>
|
|
||||||
Наблюдатель
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{!admin?.is_root && !admin?.is_analyst && !admin?.is_observer && (
|
|
||||||
<Badge color="teal" variant="light" leftSection={<IconBriefcase size={12} />}>
|
|
||||||
Менеджер
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
</Group>
|
||||||
}
|
}
|
||||||
size="md"
|
size="md"
|
||||||
|
|
@ -146,32 +88,6 @@ export default function EditAdminModal({ admin, opened, onClose }: EditAdminModa
|
||||||
{...form.getInputProps('name')}
|
{...form.getInputProps('name')}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Менеджер (Веб-приложение) */}
|
|
||||||
<Paper withBorder p="md" bg={form.values.is_manager ? 'teal.0' : 'gray.0'}>
|
|
||||||
<Switch
|
|
||||||
label={
|
|
||||||
<Group gap="xs">
|
|
||||||
<IconBriefcase size={16} color="teal" />
|
|
||||||
<Text fw={600}>Менеджер (Веб-приложение)</Text>
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
description="Только доступ к приложению заказов. Обязательна привязка к Telegram."
|
|
||||||
checked={form.values.is_manager}
|
|
||||||
onChange={(e) => {
|
|
||||||
const checked = e.currentTarget.checked;
|
|
||||||
form.setFieldValue('is_manager', checked);
|
|
||||||
if (checked) {
|
|
||||||
form.setFieldValue('is_root', false);
|
|
||||||
form.setFieldValue('is_analyst', false);
|
|
||||||
form.setFieldValue('is_observer', false);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
color="teal"
|
|
||||||
disabled={isCurrentUser}
|
|
||||||
/>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{/* Root-права */}
|
|
||||||
<Paper withBorder p="md" bg={form.values.is_root ? 'red.0' : 'gray.0'}>
|
<Paper withBorder p="md" bg={form.values.is_root ? 'red.0' : 'gray.0'}>
|
||||||
<Switch
|
<Switch
|
||||||
label={
|
label={
|
||||||
|
|
@ -184,68 +100,24 @@ export default function EditAdminModal({ admin, opened, onClose }: EditAdminModa
|
||||||
checked={form.values.is_root}
|
checked={form.values.is_root}
|
||||||
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
||||||
color="red"
|
color="red"
|
||||||
disabled={isCurrentUser || form.values.is_observer || form.values.is_manager || form.values.is_analyst}
|
disabled={isCurrentUser}
|
||||||
/>
|
/>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
{/* Аналитик */}
|
|
||||||
<Paper withBorder p="md" bg={form.values.is_analyst ? 'grape.0' : 'gray.0'}>
|
|
||||||
<Switch
|
|
||||||
label={
|
|
||||||
<Group gap="xs">
|
|
||||||
<IconChartBar size={16} color="grape" />
|
|
||||||
<Text fw={600}>Аналитик (Заказы)</Text>
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
description="Доступ к настройкам и просмотру всех заказов на месяц."
|
|
||||||
checked={form.values.is_analyst}
|
|
||||||
onChange={(e) => form.setFieldValue('is_analyst', e.currentTarget.checked)}
|
|
||||||
color="grape"
|
|
||||||
disabled={isCurrentUser || form.values.is_root || form.values.is_observer || form.values.is_manager}
|
|
||||||
/>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{/* Наблюдатель */}
|
|
||||||
<Paper withBorder p="md" bg={form.values.is_observer ? 'blue.0' : 'gray.0'}>
|
|
||||||
<Switch
|
|
||||||
label={
|
|
||||||
<Group gap="xs">
|
|
||||||
<IconUser size={16} color="blue" />
|
|
||||||
<Text fw={600}>Наблюдатель</Text>
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
description="Ограниченный доступ: только пользователи, заявки и задачи"
|
|
||||||
checked={form.values.is_observer}
|
|
||||||
onChange={(e) => {
|
|
||||||
const checked = e.currentTarget.checked;
|
|
||||||
form.setFieldValue('is_observer', checked);
|
|
||||||
if (checked) form.setFieldValue('is_manager', false);
|
|
||||||
}}
|
|
||||||
color="blue"
|
|
||||||
disabled={isCurrentUser || form.values.is_root || form.values.is_manager || form.values.is_analyst}
|
|
||||||
/>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{/* Выбор Telegram аккаунта для Наблюдателя или Менеджера */}
|
|
||||||
{(form.values.is_observer || form.values.is_manager) && (
|
|
||||||
<Select
|
|
||||||
label="Telegram-аккаунт"
|
|
||||||
placeholder="Выберите пользователя"
|
|
||||||
data={userOptions}
|
|
||||||
value={form.values.telegram_id ? String(form.values.telegram_id) : null}
|
|
||||||
onChange={(v) => form.setFieldValue('telegram_id', v ? Number(v) : null)}
|
|
||||||
searchable
|
|
||||||
required
|
|
||||||
error={form.errors.telegram_id}
|
|
||||||
description="Связь с реальным сотрудником из бота"
|
|
||||||
nothingFoundMessage="Пользователи не найдены"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{isCurrentUser && (
|
{isCurrentUser && (
|
||||||
<Alert icon={<IconAlertCircle size={16} />} color="yellow" variant="light">
|
<Alert icon={<IconAlertCircle size={16} />} color="yellow" variant="light">
|
||||||
<Text size="sm">
|
<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>
|
</Text>
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
|
|
@ -18,28 +18,20 @@ import {
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { IconEye, IconTrash, IconSearch } from '@tabler/icons-react'
|
import { IconEye, IconTrash, IconSearch } from '@tabler/icons-react'
|
||||||
import { modals } from '@mantine/modals'
|
import { modals } from '@mantine/modals'
|
||||||
import { useSearchParams } from 'react-router-dom'
|
|
||||||
import { useApprovalTasks, useDeleteApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
|
import { useApprovalTasks, useDeleteApprovalTask } from '@/features/approvalTasks/hooks/useApprovalTasks'
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||||
import { TASK_STATUSES, STATUS_COLORS, STATUS_LABELS } from '@/features/approvalTasks/const'
|
import { TASK_STATUSES, STATUS_COLORS, STATUS_LABELS } from '@/features/approvalTasks/const'
|
||||||
import ApprovalTaskDetailsModal from './components/ApprovalTaskDetailsModal'
|
import ApprovalTaskDetailsModal from './components/ApprovalTaskDetailsModal'
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
import 'dayjs/locale/ru'
|
import 'dayjs/locale/ru'
|
||||||
import {formatMsk} from "@/utils/date.ts";
|
|
||||||
|
|
||||||
dayjs.locale('ru')
|
dayjs.locale('ru')
|
||||||
|
|
||||||
const LIMIT = 20
|
const LIMIT = 20
|
||||||
|
|
||||||
export default function ApprovalTasksPage() {
|
export default function ApprovalTasksPage() {
|
||||||
// 🆕 Начальный статус берём из URL (например, с дашборда:
|
|
||||||
// /approval-tasks?status=completed) — читаем один раз при монтировании.
|
|
||||||
const [searchParams] = useSearchParams()
|
|
||||||
|
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [statusFilter, setStatusFilter] = useState<string | null>(
|
const [statusFilter, setStatusFilter] = useState<string | null>(null)
|
||||||
() => searchParams.get('status')
|
|
||||||
)
|
|
||||||
const [executorFilter, setExecutorFilter] = useState<string | null>(null)
|
const [executorFilter, setExecutorFilter] = useState<string | null>(null)
|
||||||
const [requireFileFilter, setRequireFileFilter] = useState<boolean | null>(null)
|
const [requireFileFilter, setRequireFileFilter] = useState<boolean | null>(null)
|
||||||
const [selectedTaskId, setSelectedTaskId] = useState<number | null>(null)
|
const [selectedTaskId, setSelectedTaskId] = useState<number | null>(null)
|
||||||
|
|
@ -212,14 +204,14 @@ export default function ApprovalTasksPage() {
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Text size="xs" c="dimmed">
|
<Text size="xs" c="dimmed">
|
||||||
{task.created_at
|
{task.created_at
|
||||||
? formatMsk(task.created_at)
|
? dayjs(task.created_at).format('DD.MM.YYYY HH:mm')
|
||||||
: '—'}
|
: '—'}
|
||||||
</Text>
|
</Text>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Text size="xs" c="dimmed">
|
<Text size="xs" c="dimmed">
|
||||||
{task.completed_at
|
{task.completed_at
|
||||||
? formatMsk(task.created_at)
|
? dayjs(task.completed_at).format('DD.MM.YYYY HH:mm')
|
||||||
: '—'}
|
: '—'}
|
||||||
</Text>
|
</Text>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,6 @@ import { TASK_STATUSES, STATUS_COLORS, STATUS_LABELS } from '@/features/approval
|
||||||
import FilePreviewModal from '@/pages/approvals/components/FilePreviewModal'
|
import FilePreviewModal from '@/pages/approvals/components/FilePreviewModal'
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
import 'dayjs/locale/ru'
|
import 'dayjs/locale/ru'
|
||||||
import {formatMsk} from "@/utils/date.ts";
|
|
||||||
|
|
||||||
dayjs.locale('ru')
|
dayjs.locale('ru')
|
||||||
|
|
||||||
|
|
@ -321,7 +320,7 @@ export default function ApprovalTaskDetailsModal({
|
||||||
<IconCalendar size={16} />
|
<IconCalendar size={16} />
|
||||||
<Text>
|
<Text>
|
||||||
{task.created_at
|
{task.created_at
|
||||||
? formatMsk(task.created_at)
|
? dayjs(task.created_at).format('DD.MM.YYYY HH:mm')
|
||||||
: '—'}
|
: '—'}
|
||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
@ -330,7 +329,7 @@ export default function ApprovalTaskDetailsModal({
|
||||||
<Text size="sm" c="dimmed">Обновлена:</Text>
|
<Text size="sm" c="dimmed">Обновлена:</Text>
|
||||||
<Text>
|
<Text>
|
||||||
{task.updated_at
|
{task.updated_at
|
||||||
? formatMsk(task.created_at)
|
? dayjs(task.updated_at).format('DD.MM.YYYY HH:mm')
|
||||||
: '—'}
|
: '—'}
|
||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
@ -340,7 +339,7 @@ export default function ApprovalTaskDetailsModal({
|
||||||
<Group gap="xs">
|
<Group gap="xs">
|
||||||
<IconCheck size={16} color="green" />
|
<IconCheck size={16} color="green" />
|
||||||
<Text c="green">
|
<Text c="green">
|
||||||
{formatMsk(task.created_at)}
|
{dayjs(task.completed_at).format('DD.MM.YYYY HH:mm')}
|
||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useEffect, useState, useMemo } from 'react'
|
import {useEffect, useState} from 'react'
|
||||||
import {
|
import {
|
||||||
Paper,
|
Paper,
|
||||||
Table,
|
Table,
|
||||||
|
|
@ -9,7 +9,6 @@ import {
|
||||||
Text,
|
Text,
|
||||||
TextInput,
|
TextInput,
|
||||||
Select,
|
Select,
|
||||||
MultiSelect,
|
|
||||||
Pagination,
|
Pagination,
|
||||||
Loader,
|
Loader,
|
||||||
Center,
|
Center,
|
||||||
|
|
@ -20,28 +19,17 @@ import {
|
||||||
Alert,
|
Alert,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { DatePickerInput } from '@mantine/dates'
|
import { DatePickerInput } from '@mantine/dates'
|
||||||
import {
|
import {IconEye, IconSearch, IconFileText, IconFileExcel, IconInfoCircle, IconX} from '@tabler/icons-react'
|
||||||
IconEye,
|
|
||||||
IconSearch,
|
|
||||||
IconFileText,
|
|
||||||
IconFileExcel,
|
|
||||||
IconInfoCircle,
|
|
||||||
IconX,
|
|
||||||
IconFilter,
|
|
||||||
} from '@tabler/icons-react'
|
|
||||||
import { notifications } from '@mantine/notifications'
|
import { notifications } from '@mantine/notifications'
|
||||||
import { useSearchParams } from 'react-router-dom'
|
|
||||||
import { useApprovals } from '@/features/approvals/hooks/useApprovals'
|
import { useApprovals } from '@/features/approvals/hooks/useApprovals'
|
||||||
import { useTopics } from '@/features/topics/hooks/useTopics'
|
import { useTopics } from '@/features/topics/hooks/useTopics'
|
||||||
import { useDepartments } from '@/features/departments/hooks/useDepartments'
|
import { useDepartments } from '@/features/departments/hooks/useDepartments'
|
||||||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
import { useCategories } from '@/features/categories/hooks/useCategories'
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
|
||||||
import { approvalsApi } from '@/api/approvals'
|
import { approvalsApi } from '@/api/approvals'
|
||||||
import ApprovalDetailsModal from './components/ApprovalDetailsModal'
|
import ApprovalDetailsModal from './components/ApprovalDetailsModal'
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
import 'dayjs/locale/ru'
|
import 'dayjs/locale/ru'
|
||||||
import { useDebouncedValue } from '@mantine/hooks'
|
import {useDebouncedValue} from "@mantine/hooks";
|
||||||
import {formatMsk} from "@/utils/date.ts";
|
|
||||||
|
|
||||||
dayjs.locale('ru')
|
dayjs.locale('ru')
|
||||||
|
|
||||||
|
|
@ -64,44 +52,24 @@ const STATUS_LABELS: Record<string, string> = {
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function ApprovalsPage() {
|
export default function ApprovalsPage() {
|
||||||
// 🆕 Значения фильтров, с которыми пришли по ссылке (например, с
|
// Фильтры списка
|
||||||
// дашборда: /approvals?status=pending&date_to=2026-07-20). Читаем
|
|
||||||
// только один раз при монтировании — страница не синхронизирует
|
|
||||||
// фильтры с URL постоянно, только принимает начальное состояние.
|
|
||||||
const [searchParams] = useSearchParams()
|
|
||||||
|
|
||||||
// === Состояния фильтров ===
|
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [idInput, setIdInput] = useState('')
|
|
||||||
const [searchInput, setSearchInput] = useState('')
|
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
const [searchError, setSearchError] = useState<string | null>(null)
|
const [statusFilter, setStatusFilter] = useState<string | null>(null)
|
||||||
const [debouncedSearch] = useDebouncedValue(searchInput, 400)
|
const [categoryFilter, setCategoryFilter] = useState<string | null>(null)
|
||||||
|
const [topicFilter, setTopicFilter] = useState<string | null>(null)
|
||||||
const [statusFilter, setStatusFilter] = useState<string | null>(
|
|
||||||
() => searchParams.get('status')
|
|
||||||
)
|
|
||||||
const [categoryFilter, setCategoryFilter] = useState<string[]>([])
|
|
||||||
const [topicFilter, setTopicFilter] = useState<string[]>([])
|
|
||||||
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
|
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
|
||||||
const [initiatorFilter, setInitiatorFilter] = useState<string | null>(null)
|
|
||||||
const [dateFrom, setDateFrom] = useState<Date | null>(() => {
|
|
||||||
const v = searchParams.get('date_from')
|
|
||||||
return v ? dayjs(v).toDate() : null
|
|
||||||
})
|
|
||||||
const [dateTo, setDateTo] = useState<Date | null>(() => {
|
|
||||||
const v = searchParams.get('date_to')
|
|
||||||
return v ? dayjs(v).toDate() : null
|
|
||||||
})
|
|
||||||
|
|
||||||
// === Отчёт ===
|
|
||||||
const [reportDateFrom, setReportDateFrom] = useState<Date | null>(null)
|
const [reportDateFrom, setReportDateFrom] = useState<Date | null>(null)
|
||||||
const [reportDateTo, setReportDateTo] = useState<Date | null>(null)
|
const [reportDateTo, setReportDateTo] = useState<Date | null>(null)
|
||||||
const [reportLoading, setReportLoading] = useState(false)
|
const [reportLoading, setReportLoading] = useState(false)
|
||||||
|
|
||||||
const [selectedApprovalId, setSelectedApprovalId] = useState<number | null>(null)
|
const [selectedApprovalId, setSelectedApprovalId] = useState<number | null>(null)
|
||||||
|
|
||||||
// === Обработка поиска ===
|
const [searchInput, setSearchInput] = useState('')
|
||||||
|
const [searchError, setSearchError] = useState<string | null>(null)
|
||||||
|
const [debouncedSearch] = useDebouncedValue(searchInput, 400)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (debouncedSearch === '') {
|
if (debouncedSearch === '') {
|
||||||
setSearch('')
|
setSearch('')
|
||||||
|
|
@ -109,153 +77,89 @@ export default function ApprovalsPage() {
|
||||||
setPage(1)
|
setPage(1)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (debouncedSearch.length < 2) {
|
if (debouncedSearch.length < 2) {
|
||||||
setSearchError('Введите минимум 2 символа')
|
setSearchError('Введите минимум 2 символа')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
setSearchError(null)
|
setSearchError(null)
|
||||||
setSearch(debouncedSearch)
|
setSearch(debouncedSearch)
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}, [debouncedSearch])
|
}, [debouncedSearch])
|
||||||
|
|
||||||
// === Загрузка справочников ===
|
const { data: categoryTopics } = useTopics({
|
||||||
|
limit: 1000,
|
||||||
|
...(categoryFilter && { category_id: Number(categoryFilter) }),
|
||||||
|
})
|
||||||
|
|
||||||
|
const effectiveTopicFilter = categoryFilter && categoryTopics?.data?.length === 1
|
||||||
|
? String(categoryTopics.data[0].id)
|
||||||
|
: topicFilter
|
||||||
|
|
||||||
|
const { data, isLoading, isFetching } = useApprovals({
|
||||||
|
offset: (page - 1) * LIMIT,
|
||||||
|
limit: LIMIT,
|
||||||
|
...(search && { content: search }),
|
||||||
|
...(statusFilter && { status: statusFilter }),
|
||||||
|
...(effectiveTopicFilter && { topic_id: Number(effectiveTopicFilter) }),
|
||||||
|
...(departmentFilter && { department_id: Number(departmentFilter) }),
|
||||||
|
})
|
||||||
|
|
||||||
const { data: categories } = useCategories({ limit: 1000 })
|
const { data: categories } = useCategories({ limit: 1000 })
|
||||||
const { data: allTopics } = useTopics({ limit: 1000 })
|
const { data: topics } = useTopics({ limit: 1000 })
|
||||||
const { data: departments } = useDepartments()
|
const { data: departments } = useDepartments()
|
||||||
const { data: users } = useUsers({ limit: 1000 })
|
|
||||||
|
|
||||||
// === Темы, отфильтрованные по выбранным категориям ===
|
|
||||||
const filteredTopics = useMemo(() => {
|
|
||||||
if (!allTopics?.data) return []
|
|
||||||
if (categoryFilter.length === 0) return allTopics.data
|
|
||||||
const categoryIds = categoryFilter.map(Number)
|
|
||||||
return allTopics.data.filter((t) =>
|
|
||||||
t.category_id && categoryIds.includes(t.category_id)
|
|
||||||
)
|
|
||||||
}, [allTopics, categoryFilter])
|
|
||||||
|
|
||||||
// === Сброс невалидных тем при изменении категорий ===
|
|
||||||
useEffect(() => {
|
|
||||||
if (categoryFilter.length > 0 && topicFilter.length > 0) {
|
|
||||||
const validTopicIds = new Set(filteredTopics.map((t) => String(t.id)))
|
|
||||||
const validSelected = topicFilter.filter((id) => validTopicIds.has(id))
|
|
||||||
if (validSelected.length !== topicFilter.length) {
|
|
||||||
setTopicFilter(validSelected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Если категории сброшены — темы остаются как есть
|
|
||||||
}, [categoryFilter, filteredTopics, topicFilter])
|
|
||||||
|
|
||||||
// === Опции для Select/MultiSelect ===
|
|
||||||
const categoryOptions = useMemo(
|
|
||||||
() =>
|
|
||||||
categories?.data?.map((c) => ({
|
|
||||||
value: String(c.id),
|
|
||||||
label: c.name || '',
|
|
||||||
})) || [],
|
|
||||||
[categories]
|
|
||||||
)
|
|
||||||
|
|
||||||
const topicOptions = useMemo(
|
|
||||||
() =>
|
|
||||||
filteredTopics.map((t) => ({
|
|
||||||
value: String(t.id),
|
|
||||||
label: `${t.category?.name || '—'} / ${t.name || ''}`,
|
|
||||||
})),
|
|
||||||
[filteredTopics]
|
|
||||||
)
|
|
||||||
|
|
||||||
const departmentOptions = useMemo(
|
|
||||||
() =>
|
|
||||||
departments?.data?.map((d) => ({
|
|
||||||
value: String(d.id),
|
|
||||||
label: d.name || '',
|
|
||||||
})) || [],
|
|
||||||
[departments]
|
|
||||||
)
|
|
||||||
|
|
||||||
const userOptions = useMemo(
|
|
||||||
() =>
|
|
||||||
users?.data?.map((u) => ({
|
|
||||||
value: String(u.id),
|
|
||||||
label: u.full_name || u.username || `ID: ${u.id}`,
|
|
||||||
})) || [],
|
|
||||||
[users]
|
|
||||||
)
|
|
||||||
|
|
||||||
// === Формирование параметров запроса ===
|
|
||||||
const requestParams = useMemo(() => {
|
|
||||||
const params: any = {
|
|
||||||
offset: (page - 1) * LIMIT,
|
|
||||||
limit: LIMIT,
|
|
||||||
}
|
|
||||||
if (idInput) params.id = Number(idInput)
|
|
||||||
if (search) params.content = search
|
|
||||||
if (statusFilter) params.status = statusFilter
|
|
||||||
if (departmentFilter) params.department_id = Number(departmentFilter)
|
|
||||||
if (initiatorFilter) params.initiator_id = Number(initiatorFilter)
|
|
||||||
if (categoryFilter.length > 0) {
|
|
||||||
params.category_ids = categoryFilter.map(Number)
|
|
||||||
}
|
|
||||||
if (topicFilter.length > 0) {
|
|
||||||
params.topic_ids = topicFilter.map(Number)
|
|
||||||
}
|
|
||||||
if (dateFrom) params.date_from = dayjs(dateFrom).format('YYYY-MM-DD')
|
|
||||||
if (dateTo) params.date_to = dayjs(dateTo).format('YYYY-MM-DD')
|
|
||||||
return params
|
|
||||||
}, [page, search, statusFilter, departmentFilter, initiatorFilter, categoryFilter, topicFilter, dateFrom, dateTo, idInput])
|
|
||||||
|
|
||||||
// === Запрос списка заявок ===
|
|
||||||
const { data, isLoading, isFetching } = useApprovals(requestParams)
|
|
||||||
|
|
||||||
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
||||||
|
|
||||||
// === Сброс фильтров ===
|
const categoryOptions = categories?.data?.map((c) => ({
|
||||||
const handleResetFilters = () => {
|
value: String(c.id),
|
||||||
setSearchInput('')
|
label: c.name || '',
|
||||||
setIdInput('')
|
})) || []
|
||||||
setSearch('')
|
|
||||||
setStatusFilter(null)
|
const topicOptions = topics?.data?.map((t) => ({
|
||||||
setCategoryFilter([])
|
value: String(t.id),
|
||||||
setTopicFilter([])
|
label: t.name || '',
|
||||||
setDepartmentFilter(null)
|
})) || []
|
||||||
setInitiatorFilter(null)
|
|
||||||
setDateFrom(null)
|
const departmentOptions = departments?.data?.map((d) => ({
|
||||||
setDateTo(null)
|
value: String(d.id),
|
||||||
|
label: d.name || '',
|
||||||
|
})) || []
|
||||||
|
|
||||||
|
const handleCategoryChange = (value: string | null) => {
|
||||||
|
setCategoryFilter(value)
|
||||||
|
setTopicFilter(null)
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasActiveFilters =
|
// 🆕 Генерация отчёта
|
||||||
search ||
|
|
||||||
idInput ||
|
|
||||||
statusFilter ||
|
|
||||||
categoryFilter.length > 0 ||
|
|
||||||
topicFilter.length > 0 ||
|
|
||||||
departmentFilter ||
|
|
||||||
initiatorFilter ||
|
|
||||||
dateFrom ||
|
|
||||||
dateTo
|
|
||||||
|
|
||||||
// === Генерация отчёта ===
|
|
||||||
const handleGenerateReport = async () => {
|
const handleGenerateReport = async () => {
|
||||||
setReportLoading(true)
|
setReportLoading(true)
|
||||||
try {
|
try {
|
||||||
const params: any = { all_access: true }
|
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')
|
if (reportDateFrom) {
|
||||||
|
params.date_from = dayjs(reportDateFrom).format('YYYY-MM-DD')
|
||||||
|
}
|
||||||
|
if (reportDateTo) {
|
||||||
|
params.date_to = dayjs(reportDateTo).format('YYYY-MM-DD')
|
||||||
|
}
|
||||||
|
|
||||||
const response = await approvalsApi.downloadReport(params)
|
const response = await approvalsApi.downloadReport(params)
|
||||||
|
|
||||||
const blob = new Blob([response.data], {
|
const blob = new Blob([response.data], {
|
||||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
})
|
})
|
||||||
|
|
||||||
const url = window.URL.createObjectURL(blob)
|
const url = window.URL.createObjectURL(blob)
|
||||||
const link = document.createElement('a')
|
const link = document.createElement('a')
|
||||||
link.href = url
|
link.href = url
|
||||||
|
|
||||||
const now = dayjs()
|
const now = dayjs()
|
||||||
link.setAttribute(
|
let fileName = `Согласования_${now.format('DD.MM.YYYY')}_${now.format('HH-mm')}.xlsx`
|
||||||
'download',
|
|
||||||
`Согласования_${now.format('DD.MM.YYYY')}_${now.format('HH-mm')}.xlsx`
|
link.setAttribute('download', fileName)
|
||||||
)
|
|
||||||
document.body.appendChild(link)
|
document.body.appendChild(link)
|
||||||
link.click()
|
link.click()
|
||||||
link.remove()
|
link.remove()
|
||||||
|
|
@ -267,11 +171,20 @@ export default function ApprovalsPage() {
|
||||||
color: 'green',
|
color: 'green',
|
||||||
})
|
})
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
notifications.show({
|
if (error.response?.data instanceof Blob) {
|
||||||
title: 'Ошибка',
|
const text = await error.response.data.text()
|
||||||
message: error.response?.data?.error_description || 'Не удалось сформировать отчёт',
|
notifications.show({
|
||||||
color: 'red',
|
title: 'Ошибка',
|
||||||
})
|
message: text || 'Не удалось сформировать отчёт',
|
||||||
|
color: 'red',
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
notifications.show({
|
||||||
|
title: 'Ошибка',
|
||||||
|
message: error.response?.data?.error_description || 'Не удалось сформировать отчёт',
|
||||||
|
color: 'red',
|
||||||
|
})
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setReportLoading(false)
|
setReportLoading(false)
|
||||||
}
|
}
|
||||||
|
|
@ -279,7 +192,7 @@ export default function ApprovalsPage() {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{/* Заголовок */}
|
{/* Заголовок и кнопка отчёта */}
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Text size="xl" fw={700}>Заявки</Text>
|
<Text size="xl" fw={700}>Заявки</Text>
|
||||||
<Text c="dimmed" size="sm">
|
<Text c="dimmed" size="sm">
|
||||||
|
|
@ -287,7 +200,7 @@ export default function ApprovalsPage() {
|
||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
{/* Секция отчёта */}
|
{/* 🆕 Секция формирования отчёта */}
|
||||||
<Paper withBorder p="md" bg="blue.0">
|
<Paper withBorder p="md" bg="blue.0">
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
|
|
@ -338,53 +251,11 @@ export default function ApprovalsPage() {
|
||||||
|
|
||||||
{/* Фильтры списка */}
|
{/* Фильтры списка */}
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Group justify="space-between" mb="sm">
|
<Text fw={600} size="lg" mb="sm">Фильтры списка</Text>
|
||||||
<Group gap="xs">
|
|
||||||
<IconFilter size={20} />
|
|
||||||
<Text fw={600} size="lg">Фильтры</Text>
|
|
||||||
</Group>
|
|
||||||
{hasActiveFilters && (
|
|
||||||
<Button
|
|
||||||
variant="subtle"
|
|
||||||
color="gray"
|
|
||||||
size="xs"
|
|
||||||
leftSection={<IconX size={14} />}
|
|
||||||
onClick={handleResetFilters}
|
|
||||||
>
|
|
||||||
Сбросить фильтры
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{/* Строка 1: ID + Поиск + Статус + Инициатор */}
|
<Group gap="md" align="flex-end">
|
||||||
<Group gap="md" align="flex-end" grow>
|
|
||||||
<TextInput
|
<TextInput
|
||||||
label="ID заявки"
|
label="Поиск по тексту заявки"
|
||||||
placeholder="Например, 1036"
|
|
||||||
leftSection={<IconSearch size={16} />}
|
|
||||||
value={idInput}
|
|
||||||
onChange={(e) => {
|
|
||||||
// Оставляем только цифры
|
|
||||||
setIdInput(e.currentTarget.value.replace(/\D/g, ''))
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
rightSection={
|
|
||||||
idInput && (
|
|
||||||
<ActionIcon
|
|
||||||
variant="subtle"
|
|
||||||
onClick={() => {
|
|
||||||
setIdInput('')
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<IconX size={14} />
|
|
||||||
</ActionIcon>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<TextInput
|
|
||||||
label="Поиск по тексту"
|
|
||||||
placeholder="Введите 2+ символа..."
|
placeholder="Введите 2+ символа..."
|
||||||
leftSection={<IconSearch size={16} />}
|
leftSection={<IconSearch size={16} />}
|
||||||
value={searchInput}
|
value={searchInput}
|
||||||
|
|
@ -400,6 +271,7 @@ export default function ApprovalsPage() {
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
style={{ flex: 1 }}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Select
|
<Select
|
||||||
|
|
@ -418,45 +290,14 @@ export default function ApprovalsPage() {
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}}
|
}}
|
||||||
clearable
|
clearable
|
||||||
/>
|
style={{ minWidth: 180 }}
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Инициатор"
|
|
||||||
placeholder="Все инициаторы"
|
|
||||||
data={userOptions}
|
|
||||||
value={initiatorFilter}
|
|
||||||
onChange={(v) => {
|
|
||||||
setInitiatorFilter(v)
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
clearable
|
|
||||||
searchable
|
|
||||||
/>
|
/>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
{/* Строка 2: Категории + Темы + Отдел */}
|
<Group gap="md" align="flex-end">
|
||||||
<Group gap="md" align="flex-end" grow>
|
<Select
|
||||||
<MultiSelect
|
label="Тема"
|
||||||
label="Категории"
|
placeholder="Все темы"
|
||||||
placeholder="Все категории"
|
|
||||||
data={categoryOptions}
|
|
||||||
value={categoryFilter}
|
|
||||||
onChange={(v) => {
|
|
||||||
setCategoryFilter(v)
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
clearable
|
|
||||||
searchable
|
|
||||||
nothingFoundMessage="Категории не найдены"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<MultiSelect
|
|
||||||
label="Темы"
|
|
||||||
placeholder={
|
|
||||||
categoryFilter.length > 0
|
|
||||||
? 'Выберите темы'
|
|
||||||
: 'Все темы'
|
|
||||||
}
|
|
||||||
data={topicOptions}
|
data={topicOptions}
|
||||||
value={topicFilter}
|
value={topicFilter}
|
||||||
onChange={(v) => {
|
onChange={(v) => {
|
||||||
|
|
@ -465,13 +306,8 @@ export default function ApprovalsPage() {
|
||||||
}}
|
}}
|
||||||
clearable
|
clearable
|
||||||
searchable
|
searchable
|
||||||
disabled={filteredTopics.length === 0}
|
style={{ minWidth: 200 }}
|
||||||
nothingFoundMessage="Темы не найдены"
|
disabled={!!categoryFilter}
|
||||||
description={
|
|
||||||
categoryFilter.length > 0
|
|
||||||
? `Показаны темы выбранных категорий (${filteredTopics.length})`
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Select
|
<Select
|
||||||
|
|
@ -484,35 +320,9 @@ export default function ApprovalsPage() {
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}}
|
}}
|
||||||
clearable
|
clearable
|
||||||
|
style={{ minWidth: 180 }}
|
||||||
/>
|
/>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
{/* Строка 3: Период дат */}
|
|
||||||
<Group gap="md" align="flex-end" grow>
|
|
||||||
<DatePickerInput
|
|
||||||
label="Дата создания от"
|
|
||||||
placeholder="Выберите дату"
|
|
||||||
value={dateFrom}
|
|
||||||
onChange={(val) => {
|
|
||||||
setDateFrom(val as Date | null)
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
clearable
|
|
||||||
maxDate={dateTo || undefined}
|
|
||||||
/>
|
|
||||||
<DatePickerInput
|
|
||||||
label="Дата создания до"
|
|
||||||
placeholder="Выберите дату"
|
|
||||||
value={dateTo}
|
|
||||||
onChange={(val) => {
|
|
||||||
setDateTo(val as Date | null)
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
clearable
|
|
||||||
minDate={dateFrom || undefined}
|
|
||||||
/>
|
|
||||||
<Box style={{ flex: 1 }} />
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
|
@ -576,7 +386,9 @@ export default function ApprovalsPage() {
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Text size="sm" c="dimmed">
|
<Text size="sm" c="dimmed">
|
||||||
{approval.created_at ? formatMsk(approval.created_at) : '—'}
|
{approval.created_at
|
||||||
|
? dayjs(approval.created_at).format('DD.MM.YYYY HH:mm')
|
||||||
|
: '—'}
|
||||||
</Text>
|
</Text>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
|
|
@ -624,7 +436,14 @@ export default function ApprovalsPage() {
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
{isFetching && !isLoading && (
|
{isFetching && !isLoading && (
|
||||||
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
|
<Box
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
top: 70,
|
||||||
|
right: 20,
|
||||||
|
zIndex: 1000
|
||||||
|
}}
|
||||||
|
>
|
||||||
<Loader size="xs" />
|
<Loader size="xs" />
|
||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
|
|
@ -11,10 +11,7 @@ import {
|
||||||
Timeline,
|
Timeline,
|
||||||
ScrollArea,
|
ScrollArea,
|
||||||
Box,
|
Box,
|
||||||
ActionIcon,
|
ActionIcon, Tooltip,
|
||||||
Tooltip,
|
|
||||||
Alert,
|
|
||||||
Divider,
|
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import {
|
import {
|
||||||
IconUser,
|
IconUser,
|
||||||
|
|
@ -27,25 +24,15 @@ import {
|
||||||
IconAlertCircle,
|
IconAlertCircle,
|
||||||
IconEye,
|
IconEye,
|
||||||
IconDownload,
|
IconDownload,
|
||||||
IconMessageCircle,
|
|
||||||
IconUserPlus,
|
|
||||||
IconEyeglass,
|
|
||||||
IconRotate,
|
|
||||||
IconChecklist,
|
|
||||||
IconAlertTriangle,
|
|
||||||
} from '@tabler/icons-react'
|
} from '@tabler/icons-react'
|
||||||
import { notifications } from '@mantine/notifications'
|
import { notifications } from '@mantine/notifications'
|
||||||
import {
|
import { useApproval } from '@/features/approvals/hooks/useApprovals'
|
||||||
useApproval,
|
|
||||||
useAdditionalApprovers,
|
|
||||||
useApprovalComments,
|
|
||||||
useApprovalObservers,
|
|
||||||
useRevocationRequest,
|
|
||||||
useApprovalTasks,
|
|
||||||
} from '@/features/approvals/hooks/useApprovals'
|
|
||||||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
import { useCategories } from '@/features/categories/hooks/useCategories'
|
||||||
import FilePreviewModal from './FilePreviewModal'
|
import FilePreviewModal from './FilePreviewModal'
|
||||||
import { formatMsk } from '@/utils/date'
|
import dayjs from 'dayjs'
|
||||||
|
import 'dayjs/locale/ru'
|
||||||
|
|
||||||
|
dayjs.locale('ru')
|
||||||
|
|
||||||
interface ApprovalDetailsModalProps {
|
interface ApprovalDetailsModalProps {
|
||||||
approvalId: number | null
|
approvalId: number | null
|
||||||
|
|
@ -86,57 +73,7 @@ const STEP_STATUS_COLORS: Record<string, string> = {
|
||||||
cancelled_any_of: 'orange',
|
cancelled_any_of: 'orange',
|
||||||
}
|
}
|
||||||
|
|
||||||
// Статусы "доп. согласующего" — те же значения, что в handleDecision
|
// 🆕 Типы файлов, для которых доступен предпросмотр
|
||||||
// (isAdditionalApprover): "pending" / "approved" / "rejected".
|
|
||||||
const ADDITIONAL_APPROVER_LABELS: Record<string, string> = {
|
|
||||||
pending: 'Ожидает решения',
|
|
||||||
approved: 'Одобрил',
|
|
||||||
rejected: 'Отклонил',
|
|
||||||
}
|
|
||||||
|
|
||||||
const ADDITIONAL_APPROVER_COLORS: Record<string, string> = {
|
|
||||||
pending: 'blue',
|
|
||||||
approved: 'green',
|
|
||||||
rejected: 'red',
|
|
||||||
}
|
|
||||||
|
|
||||||
// Статусы согласующего на запрос отзыва (см. HandleRevocationApproverDecision
|
|
||||||
// в telegram_service).
|
|
||||||
const REVOCATION_APPROVER_LABELS: Record<string, string> = {
|
|
||||||
pending: 'Ещё не ответил',
|
|
||||||
approved: 'Согласен на отзыв',
|
|
||||||
rejected: 'Против отзыва',
|
|
||||||
}
|
|
||||||
|
|
||||||
const REVOCATION_APPROVER_COLORS: Record<string, string> = {
|
|
||||||
pending: 'gray',
|
|
||||||
approved: 'green',
|
|
||||||
rejected: 'red',
|
|
||||||
}
|
|
||||||
|
|
||||||
const APPROVAL_MODE_LABELS: Record<string, string> = {
|
|
||||||
sequential: 'Последовательно',
|
|
||||||
any_of: 'Любой из согласующих',
|
|
||||||
}
|
|
||||||
|
|
||||||
// Статусы задач — те же значения и подписи, что в отчёте (reportcore.go)
|
|
||||||
// и в "Стадиях согласования" бота.
|
|
||||||
const TASK_STATUS_LABELS: Record<string, string> = {
|
|
||||||
pending: 'В работе',
|
|
||||||
waiting: 'Ожидает',
|
|
||||||
completed: 'Выполнена',
|
|
||||||
cancelled: 'Отменена',
|
|
||||||
cancellation: 'Требует отмены изменений',
|
|
||||||
}
|
|
||||||
|
|
||||||
const TASK_STATUS_COLORS: Record<string, string> = {
|
|
||||||
pending: 'blue',
|
|
||||||
waiting: 'gray',
|
|
||||||
completed: 'green',
|
|
||||||
cancelled: 'red',
|
|
||||||
cancellation: 'orange',
|
|
||||||
}
|
|
||||||
|
|
||||||
const PREVIEWABLE_TYPES = [
|
const PREVIEWABLE_TYPES = [
|
||||||
'image/jpeg',
|
'image/jpeg',
|
||||||
'image/png',
|
'image/png',
|
||||||
|
|
@ -147,25 +84,27 @@ const PREVIEWABLE_TYPES = [
|
||||||
'text/plain',
|
'text/plain',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
// 🆕 Определение MIME типа по расширению
|
||||||
const getMimeType = (fileName: string): string => {
|
const getMimeType = (fileName: string): string => {
|
||||||
const ext = fileName.split('.').pop()?.toLowerCase() || ''
|
const ext = fileName.split('.').pop()?.toLowerCase() || ''
|
||||||
const mimeTypes: Record<string, string> = {
|
const mimeTypes: Record<string, string> = {
|
||||||
jpg: 'image/jpeg',
|
'jpg': 'image/jpeg',
|
||||||
jpeg: 'image/jpeg',
|
'jpeg': 'image/jpeg',
|
||||||
png: 'image/png',
|
'png': 'image/png',
|
||||||
gif: 'image/gif',
|
'gif': 'image/gif',
|
||||||
webp: 'image/webp',
|
'webp': 'image/webp',
|
||||||
svg: 'image/svg+xml',
|
'svg': 'image/svg+xml',
|
||||||
pdf: 'application/pdf',
|
'pdf': 'application/pdf',
|
||||||
txt: 'text/plain',
|
'txt': 'text/plain',
|
||||||
doc: 'application/msword',
|
'doc': 'application/msword',
|
||||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||||
xls: 'application/vnd.ms-excel',
|
'xls': 'application/vnd.ms-excel',
|
||||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
}
|
}
|
||||||
return mimeTypes[ext] || 'application/octet-stream'
|
return mimeTypes[ext] || 'application/octet-stream'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 🆕 Генерация HMAC подписи (вынесена в отдельную функцию)
|
||||||
const generateSignature = async (): Promise<{ signature: string; timestamp: string; deviceId: string }> => {
|
const generateSignature = async (): Promise<{ signature: string; timestamp: string; deviceId: string }> => {
|
||||||
const timestamp = Math.floor(Date.now() / 1000).toString()
|
const timestamp = Math.floor(Date.now() / 1000).toString()
|
||||||
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
||||||
|
|
@ -177,12 +116,13 @@ const generateSignature = async (): Promise<{ signature: string; timestamp: stri
|
||||||
return { signature, timestamp, deviceId }
|
return { signature, timestamp, deviceId }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 🆕 Получение заголовков авторизации
|
||||||
const getAuthHeaders = async () => {
|
const getAuthHeaders = async () => {
|
||||||
const token = localStorage.getItem('token')
|
const token = localStorage.getItem('token')
|
||||||
const { signature, timestamp, deviceId } = await generateSignature()
|
const { signature, timestamp, deviceId } = await generateSignature()
|
||||||
return {
|
return {
|
||||||
Authorization: `Bearer ${token}`,
|
'Authorization': `Bearer ${token}`,
|
||||||
ApiKey: signature,
|
'ApiKey': signature,
|
||||||
'X-Timestamp': timestamp,
|
'X-Timestamp': timestamp,
|
||||||
'x-device-id': deviceId,
|
'x-device-id': deviceId,
|
||||||
}
|
}
|
||||||
|
|
@ -196,21 +136,7 @@ export default function ApprovalDetailsModal({
|
||||||
const { data: approval, isLoading } = useApproval(approvalId)
|
const { data: approval, isLoading } = useApproval(approvalId)
|
||||||
const { data: categories } = useCategories({ limit: 1000 })
|
const { data: categories } = useCategories({ limit: 1000 })
|
||||||
|
|
||||||
// Хуки отдают ApiResponse<T> целиком (как useFlowNodesTree раньше) —
|
// 🆕 Состояние для предпросмотра файла
|
||||||
// разворачиваем здесь, а не в самих хуках, чтобы не плодить два разных
|
|
||||||
// соглашения об обёртке в одном проекте.
|
|
||||||
const { data: additionalApproversResponse } = useAdditionalApprovers(approvalId)
|
|
||||||
const { data: commentsResponse } = useApprovalComments(approvalId)
|
|
||||||
const { data: observersResponse } = useApprovalObservers(approvalId)
|
|
||||||
const { data: revocationRequestResponse } = useRevocationRequest(approvalId)
|
|
||||||
const { data: tasksResponse } = useApprovalTasks(approvalId)
|
|
||||||
|
|
||||||
const additionalApprovers = additionalApproversResponse?.data
|
|
||||||
const comments = commentsResponse?.data
|
|
||||||
const observers = observersResponse?.data
|
|
||||||
const revocationRequest = revocationRequestResponse?.data
|
|
||||||
const tasksData = tasksResponse?.data
|
|
||||||
|
|
||||||
const [previewFileId, setPreviewFileId] = useState<number | null>(null)
|
const [previewFileId, setPreviewFileId] = useState<number | null>(null)
|
||||||
const [previewFileName, setPreviewFileName] = useState('')
|
const [previewFileName, setPreviewFileName] = useState('')
|
||||||
const [previewFileType, setPreviewFileType] = useState('')
|
const [previewFileType, setPreviewFileType] = useState('')
|
||||||
|
|
@ -219,18 +145,24 @@ export default function ApprovalDetailsModal({
|
||||||
? categories.data.find((c) => c.id === approval.topic?.category_id)
|
? categories.data.find((c) => c.id === approval.topic?.category_id)
|
||||||
: null
|
: null
|
||||||
|
|
||||||
|
// 🆕 Открытие предпросмотра
|
||||||
const handleFilePreview = (fileId: number, fileName: string) => {
|
const handleFilePreview = (fileId: number, fileName: string) => {
|
||||||
setPreviewFileId(fileId)
|
setPreviewFileId(fileId)
|
||||||
setPreviewFileName(fileName)
|
setPreviewFileName(fileName)
|
||||||
setPreviewFileType(getMimeType(fileName))
|
setPreviewFileType(getMimeType(fileName))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 🆕 Скачивание файла
|
||||||
const handleFileDownload = async (fileId: number, fileName: string) => {
|
const handleFileDownload = async (fileId: number, fileName: string) => {
|
||||||
try {
|
try {
|
||||||
const headers = await getAuthHeaders()
|
const headers = await getAuthHeaders()
|
||||||
const url = `/api/approvals/${approvalId}/files/${fileId}/download`
|
const url = `/api/approvals/${approvalId}/files/${fileId}/download`
|
||||||
|
|
||||||
const response = await fetch(url, { method: 'GET', headers })
|
const response = await fetch(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers,
|
||||||
|
})
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error('Failed to download file')
|
throw new Error('Failed to download file')
|
||||||
}
|
}
|
||||||
|
|
@ -245,21 +177,21 @@ export default function ApprovalDetailsModal({
|
||||||
link.remove()
|
link.remove()
|
||||||
window.URL.revokeObjectURL(blobUrl)
|
window.URL.revokeObjectURL(blobUrl)
|
||||||
|
|
||||||
notifications.show({ title: 'Успешно', message: 'Файл скачан', color: 'green' })
|
notifications.show({
|
||||||
|
title: 'Успешно',
|
||||||
|
message: 'Файл скачан',
|
||||||
|
color: 'green',
|
||||||
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Download error:', error)
|
console.error('Download error:', error)
|
||||||
notifications.show({ title: 'Ошибка', message: 'Не удалось скачать файл', color: 'red' })
|
notifications.show({
|
||||||
|
title: 'Ошибка',
|
||||||
|
message: 'Не удалось скачать файл',
|
||||||
|
color: 'red',
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Показываем превью "что будет поставлено" только пока заявка ещё не
|
|
||||||
// согласована И задачи по факту ещё не созданы — как только появились
|
|
||||||
// реальные ApprovalTask, показываем уже их (ниже), а не план.
|
|
||||||
const showPlannedTasks =
|
|
||||||
approval?.status === 'pending' &&
|
|
||||||
!!tasksData?.topic_executors?.length &&
|
|
||||||
!tasksData?.tasks?.length
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Modal
|
<Modal
|
||||||
|
|
@ -276,63 +208,24 @@ export default function ApprovalDetailsModal({
|
||||||
</Group>
|
</Group>
|
||||||
}
|
}
|
||||||
size="xl"
|
size="xl"
|
||||||
styles={{ body: { height: 'calc(80vh - 120px)', padding: 0 } }}
|
styles={{
|
||||||
|
body: {
|
||||||
|
height: 'calc(80vh - 120px)',
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<Center p={40}>
|
<Center p={40}>
|
||||||
<Loader />
|
<Loader />
|
||||||
</Center>
|
</Center>
|
||||||
) : approval ? (
|
) : approval ? (
|
||||||
<ScrollArea style={{ height: 'calc(80vh - 120px)' }} offsetScrollbars>
|
<ScrollArea
|
||||||
|
style={{ height: 'calc(80vh - 120px)' }}
|
||||||
|
offsetScrollbars
|
||||||
|
>
|
||||||
<Box p="md">
|
<Box p="md">
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{/* НОВОЕ: ошибка создания задач — та же логика, что в отчёте
|
|
||||||
(reportcore.go: hasTaskError). Ставим у самого верха, это
|
|
||||||
требует внимания администратора, а не просто информация. */}
|
|
||||||
{tasksData?.has_task_error && (
|
|
||||||
<Alert icon={<IconAlertTriangle size={16} />} color="red" variant="filled">
|
|
||||||
<Text size="sm" fw={600}>
|
|
||||||
Ошибка при создании задачи
|
|
||||||
</Text>
|
|
||||||
<Text size="xs">
|
|
||||||
Для темы этой заявки настроены исполнители, заявка согласована, но ни
|
|
||||||
одной задачи по факту не создано — стоит проверить вручную.
|
|
||||||
</Text>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* НОВОЕ: активный запрос на отзыв — самое "срочное", поэтому
|
|
||||||
сверху, ещё до общей информации. Показывается, только если
|
|
||||||
такой запрос реально есть (backend отдаёт data: null иначе) */}
|
|
||||||
{revocationRequest && (
|
|
||||||
<Alert icon={<IconRotate size={16} />} color="orange" variant="light">
|
|
||||||
<Stack gap={6}>
|
|
||||||
<Text size="sm" fw={600}>
|
|
||||||
Идёт запрос на отзыв этой заявки
|
|
||||||
</Text>
|
|
||||||
<Text size="xs">
|
|
||||||
Инициатор запроса: {revocationRequest.requested_by_name}
|
|
||||||
</Text>
|
|
||||||
{revocationRequest.reason && (
|
|
||||||
<Text size="xs">Причина: {revocationRequest.reason}</Text>
|
|
||||||
)}
|
|
||||||
<Stack gap={4} mt={4}>
|
|
||||||
{revocationRequest.approvers.map((a) => (
|
|
||||||
<Group key={a.approver_id} justify="space-between" gap="xs">
|
|
||||||
<Text size="xs">{a.approver_name}</Text>
|
|
||||||
<Badge
|
|
||||||
size="xs"
|
|
||||||
color={REVOCATION_APPROVER_COLORS[a.status] || 'gray'}
|
|
||||||
>
|
|
||||||
{REVOCATION_APPROVER_LABELS[a.status] || a.status}
|
|
||||||
</Badge>
|
|
||||||
</Group>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Stack>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Основная информация */}
|
{/* Основная информация */}
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Text size="sm" c="dimmed" mb="xs">Основная информация</Text>
|
<Text size="sm" c="dimmed" mb="xs">Основная информация</Text>
|
||||||
|
|
@ -345,16 +238,6 @@ export default function ApprovalDetailsModal({
|
||||||
<Text size="sm" c="dimmed">Тема:</Text>
|
<Text size="sm" c="dimmed">Тема:</Text>
|
||||||
<Text>{approval.topic?.name || '—'}</Text>
|
<Text>{approval.topic?.name || '—'}</Text>
|
||||||
</Group>
|
</Group>
|
||||||
{/* Режим согласования — лежит на теме */}
|
|
||||||
{approval.topic?.approval_mode && (
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">Режим согласования:</Text>
|
|
||||||
<Text>
|
|
||||||
{APPROVAL_MODE_LABELS[approval.topic.approval_mode] ||
|
|
||||||
approval.topic.approval_mode}
|
|
||||||
</Text>
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Text size="sm" c="dimmed">Инициатор:</Text>
|
<Text size="sm" c="dimmed">Инициатор:</Text>
|
||||||
<Group gap="xs">
|
<Group gap="xs">
|
||||||
|
|
@ -370,94 +253,19 @@ export default function ApprovalDetailsModal({
|
||||||
</Group>
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Text size="sm" c="dimmed">Дата создания (МСК):</Text>
|
<Text size="sm" c="dimmed">Дата создания:</Text>
|
||||||
<Group gap="xs">
|
<Group gap="xs">
|
||||||
<IconCalendar size={16} />
|
<IconCalendar size={16} />
|
||||||
<Text>{formatMsk(approval.created_at)}</Text>
|
<Text>
|
||||||
|
{approval.created_at
|
||||||
|
? dayjs(approval.created_at).format('DD.MM.YYYY HH:mm')
|
||||||
|
: '—'}
|
||||||
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
{/* НОВОЕ: превью "что будет поставлено" — только для pending-заявок,
|
|
||||||
пока реальных задач ещё нет. Данные берём из ApprovalTopicExecutor
|
|
||||||
(настройка темы), а не из ApprovalTask (их ещё физически не существует). */}
|
|
||||||
{showPlannedTasks && (
|
|
||||||
<Paper withBorder p="md" bg="blue.0">
|
|
||||||
<Group gap="xs" mb="xs">
|
|
||||||
<IconChecklist size={16} />
|
|
||||||
<Text size="sm" c="dimmed">
|
|
||||||
Какие задачи будут поставлены после согласования
|
|
||||||
</Text>
|
|
||||||
</Group>
|
|
||||||
<Stack gap="xs">
|
|
||||||
{tasksData!.topic_executors
|
|
||||||
.slice()
|
|
||||||
.sort((a, b) => a.step_order - b.step_order)
|
|
||||||
.map((te) => (
|
|
||||||
<Group key={te.id} justify="space-between" wrap="nowrap">
|
|
||||||
<Text size="sm" style={{ flex: 1 }}>
|
|
||||||
{te.task_text || '—'}
|
|
||||||
</Text>
|
|
||||||
<Badge variant="light" color="blue">
|
|
||||||
{te.executor_name || 'Исполнитель не назначен'}
|
|
||||||
</Badge>
|
|
||||||
</Group>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
<Text size="xs" c="dimmed" mt="xs">
|
|
||||||
Появится автоматически, как только заявку согласуют полностью.
|
|
||||||
</Text>
|
|
||||||
</Paper>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* НОВОЕ: уже реально выставленные задачи */}
|
|
||||||
{!!tasksData?.tasks?.length && (
|
|
||||||
<Paper withBorder p="md">
|
|
||||||
<Group gap="xs" mb="xs">
|
|
||||||
<IconChecklist size={16} />
|
|
||||||
<Text size="sm" c="dimmed">Задачи</Text>
|
|
||||||
</Group>
|
|
||||||
<Stack gap="xs">
|
|
||||||
{tasksData.tasks.map((task, i) => (
|
|
||||||
<Paper key={task.id} withBorder p="sm">
|
|
||||||
<Group justify="space-between" wrap="nowrap" mb={4}>
|
|
||||||
<Text size="sm" fw={500}>
|
|
||||||
Выставлена задача №{i + 1}
|
|
||||||
</Text>
|
|
||||||
<Badge size="xs" color={TASK_STATUS_COLORS[task.status] || 'gray'}>
|
|
||||||
{TASK_STATUS_LABELS[task.status] || task.status}
|
|
||||||
</Badge>
|
|
||||||
</Group>
|
|
||||||
<Text size="sm">{task.task_text || '—'}</Text>
|
|
||||||
<Text size="xs" c="dimmed" mt={4}>
|
|
||||||
Исполнитель: {task.executor_name || '—'}
|
|
||||||
{task.completed_at && <> · Выполнена {formatMsk(task.completed_at)}</>}
|
|
||||||
</Text>
|
|
||||||
</Paper>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Наблюдатели — вычисляются динамически по категории/теме
|
|
||||||
(не хранимая связь), поэтому отдельным запросом */}
|
|
||||||
{observers && observers.length > 0 && (
|
|
||||||
<Paper withBorder p="md">
|
|
||||||
<Group gap="xs" mb="xs">
|
|
||||||
<IconEyeglass size={16} />
|
|
||||||
<Text size="sm" c="dimmed">Наблюдатели</Text>
|
|
||||||
</Group>
|
|
||||||
<Group gap="xs">
|
|
||||||
{observers.map((o) => (
|
|
||||||
<Badge key={o.id} variant="light" color="gray">
|
|
||||||
{o.full_name}
|
|
||||||
</Badge>
|
|
||||||
))}
|
|
||||||
</Group>
|
|
||||||
</Paper>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Текст заявки */}
|
{/* Текст заявки */}
|
||||||
{approval.content && (
|
{approval.content && (
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
|
|
@ -482,7 +290,7 @@ export default function ApprovalDetailsModal({
|
||||||
</Paper>
|
</Paper>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Файлы */}
|
{/* 🆕 Файлы */}
|
||||||
{approval.files && approval.files.length > 0 && (
|
{approval.files && approval.files.length > 0 && (
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Text size="sm" c="dimmed" mb="xs">Прикреплённые файлы</Text>
|
<Text size="sm" c="dimmed" mb="xs">Прикреплённые файлы</Text>
|
||||||
|
|
@ -491,7 +299,7 @@ export default function ApprovalDetailsModal({
|
||||||
const mimeType = getMimeType(file.file_name || '')
|
const mimeType = getMimeType(file.file_name || '')
|
||||||
const canPreview = PREVIEWABLE_TYPES.includes(mimeType)
|
const canPreview = PREVIEWABLE_TYPES.includes(mimeType)
|
||||||
const fileSizeKB = file.file_base64
|
const fileSizeKB = file.file_base64
|
||||||
? Math.round((file.file_base64.length * 3) / 4 / 1024)
|
? Math.round((file.file_base64.length * 3 / 4) / 1024)
|
||||||
: 0
|
: 0
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -558,7 +366,10 @@ export default function ApprovalDetailsModal({
|
||||||
<Text size="sm" fw={500}>
|
<Text size="sm" fw={500}>
|
||||||
Шаг {index + 1}: {step.approver_name_snapshot || 'Согласующий'}
|
Шаг {index + 1}: {step.approver_name_snapshot || 'Согласующий'}
|
||||||
</Text>
|
</Text>
|
||||||
<Badge size="xs" color={STEP_STATUS_COLORS[step.status || ''] || 'gray'}>
|
<Badge
|
||||||
|
size="xs"
|
||||||
|
color={STEP_STATUS_COLORS[step.status || ''] || 'gray'}
|
||||||
|
>
|
||||||
{step.status}
|
{step.status}
|
||||||
</Badge>
|
</Badge>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
@ -569,7 +380,7 @@ export default function ApprovalDetailsModal({
|
||||||
{step.acted_at && (
|
{step.acted_at && (
|
||||||
<>
|
<>
|
||||||
{' • '}
|
{' • '}
|
||||||
{formatMsk(step.acted_at)}
|
{dayjs(step.acted_at).format('DD.MM.YYYY HH:mm')}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Text>
|
</Text>
|
||||||
|
|
@ -585,55 +396,6 @@ export default function ApprovalDetailsModal({
|
||||||
</Paper>
|
</Paper>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Дополнительные согласующие */}
|
|
||||||
{additionalApprovers && additionalApprovers.length > 0 && (
|
|
||||||
<Paper withBorder p="md">
|
|
||||||
<Group gap="xs" mb="xs">
|
|
||||||
<IconUserPlus size={16} />
|
|
||||||
<Text size="sm" c="dimmed">Дополнительные согласующие</Text>
|
|
||||||
</Group>
|
|
||||||
<Stack gap="xs">
|
|
||||||
{additionalApprovers.map((aa) => (
|
|
||||||
<Group key={aa.id} justify="space-between">
|
|
||||||
<Text size="sm">{aa.approver_name}</Text>
|
|
||||||
<Group gap="xs">
|
|
||||||
{aa.acted_at && (
|
|
||||||
<Text size="xs" c="dimmed">{formatMsk(aa.acted_at)}</Text>
|
|
||||||
)}
|
|
||||||
<Badge size="xs" color={ADDITIONAL_APPROVER_COLORS[aa.status] || 'blue'}>
|
|
||||||
{ADDITIONAL_APPROVER_LABELS[aa.status] || aa.status}
|
|
||||||
</Badge>
|
|
||||||
</Group>
|
|
||||||
</Group>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Комментарии */}
|
|
||||||
{comments && comments.length > 0 && (
|
|
||||||
<Paper withBorder p="md">
|
|
||||||
<Group gap="xs" mb="xs">
|
|
||||||
<IconMessageCircle size={16} />
|
|
||||||
<Text size="sm" c="dimmed">Комментарии ({comments.length})</Text>
|
|
||||||
</Group>
|
|
||||||
<Stack gap="sm">
|
|
||||||
{comments.map((c, i) => (
|
|
||||||
<Box key={c.id}>
|
|
||||||
<Group justify="space-between" gap="xs">
|
|
||||||
<Text size="xs" fw={600}>{c.user_name}</Text>
|
|
||||||
{c.created_at && (
|
|
||||||
<Text size="xs" c="dimmed">{formatMsk(c.created_at)}</Text>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
<Text size="sm">{c.comment}</Text>
|
|
||||||
{i < comments.length - 1 && <Divider mt="sm" />}
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Информация об отзыве */}
|
{/* Информация об отзыве */}
|
||||||
{approval.status === 'revoked' && approval.revoked_by && (
|
{approval.status === 'revoked' && approval.revoked_by && (
|
||||||
<Paper withBorder p="md" bg="orange.0">
|
<Paper withBorder p="md" bg="orange.0">
|
||||||
|
|
@ -642,7 +404,9 @@ export default function ApprovalDetailsModal({
|
||||||
<IconAlertCircle size={16} />
|
<IconAlertCircle size={16} />
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
Отозвана: {approval.revoked_by.full_name}
|
Отозвана: {approval.revoked_by.full_name}
|
||||||
{approval.revoked_at && <> {formatMsk(approval.revoked_at)}</>}
|
{approval.revoked_at && (
|
||||||
|
<> {dayjs(approval.revoked_at).format('DD.MM.YYYY HH:mm')}</>
|
||||||
|
)}
|
||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
@ -676,6 +440,7 @@ export default function ApprovalDetailsModal({
|
||||||
)}
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
|
{/* 🆕 Модальное окно предпросмотра файла */}
|
||||||
{previewFileId && approvalId && (
|
{previewFileId && approvalId && (
|
||||||
<FilePreviewModal
|
<FilePreviewModal
|
||||||
approvalId={approvalId}
|
approvalId={approvalId}
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,4 +1,4 @@
|
||||||
import {useState, useMemo, useEffect} from 'react'
|
import { useState, useMemo } from 'react'
|
||||||
import {
|
import {
|
||||||
Paper,
|
Paper,
|
||||||
Group,
|
Group,
|
||||||
|
|
@ -8,116 +8,126 @@ import {
|
||||||
Loader,
|
Loader,
|
||||||
Center,
|
Center,
|
||||||
Stack,
|
Stack,
|
||||||
|
Box,
|
||||||
Badge,
|
Badge,
|
||||||
|
Textarea,
|
||||||
|
Code,
|
||||||
|
Divider,
|
||||||
Alert,
|
Alert,
|
||||||
|
Collapse,
|
||||||
|
ActionIcon,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { IconPlus, IconInfoCircle, IconBook, IconFolderPlus, IconRefresh, IconAlertTriangle } from '@tabler/icons-react'
|
import {
|
||||||
|
IconPlus,
|
||||||
|
IconDeviceFloppy,
|
||||||
|
IconRefresh,
|
||||||
|
IconChevronDown,
|
||||||
|
IconChevronRight,
|
||||||
|
IconInfoCircle, IconBook,
|
||||||
|
} from '@tabler/icons-react'
|
||||||
import { modals } from '@mantine/modals'
|
import { modals } from '@mantine/modals'
|
||||||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
import { useTopics } from '@/features/topics/hooks/useTopics'
|
||||||
import {
|
import {
|
||||||
useFlowNodesTree,
|
useFlowNodesTree,
|
||||||
useDeleteFlowNode,
|
useDeleteFlowNode,
|
||||||
|
useSaveFlowTree,
|
||||||
|
useMoveFlowNode,
|
||||||
useDuplicateFlowNode,
|
useDuplicateFlowNode,
|
||||||
useReloadBot,
|
|
||||||
useUpdateFlowNode,
|
|
||||||
} from '@/features/flowNodes/hooks/useFlowNodes'
|
} from '@/features/flowNodes/hooks/useFlowNodes'
|
||||||
import { findParent } from '@/features/flowNodes/utils/treeWalk'
|
import { useUpdateTopic } from '@/features/topics/hooks/useTopics'
|
||||||
import type { ApprovalFlowNode, ApprovalTopicCategory } from '@/types/api'
|
import FlowTreeNode from './components/FlowTreeNode'
|
||||||
|
import FlowNodeEditModal from './components/FlowNodeEditModal'
|
||||||
|
import type { ApprovalFlowNode, ApprovalTopic } from '@/types/api'
|
||||||
import { useNavigate } from 'react-router-dom'
|
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() {
|
export default function FlowTreePage() {
|
||||||
const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null)
|
const [selectedTopicId, setSelectedTopicId] = useState<number | null>(null)
|
||||||
const [categoryModalOpened, setCategoryModalOpened] = useState(false)
|
const [showTemplates, setShowTemplates] = useState(false)
|
||||||
|
|
||||||
|
// Модалка редактирования узла
|
||||||
const [editModal, setEditModal] = useState<{
|
const [editModal, setEditModal] = useState<{
|
||||||
opened: boolean
|
opened: boolean
|
||||||
parentNode: ApprovalFlowNode | null
|
parentNode: ApprovalFlowNode | null
|
||||||
editNode: ApprovalFlowNode | null
|
editNode: ApprovalFlowNode | null
|
||||||
}>({ opened: false, parentNode: null, editNode: null })
|
}>({
|
||||||
|
opened: false,
|
||||||
|
parentNode: null,
|
||||||
|
editNode: null,
|
||||||
|
})
|
||||||
|
|
||||||
const { data: categoriesData } = useCategories({ limit: 1000, is_active: true })
|
// Загружаем все темы
|
||||||
const categories = categoriesData?.data || []
|
const { data: topicsData } = useTopics({
|
||||||
|
limit: 1000,
|
||||||
|
is_tree_root: true
|
||||||
|
})
|
||||||
|
const topics = topicsData?.data || []
|
||||||
|
|
||||||
const { data: treeData, isLoading: treeLoading } = useFlowNodesTree(selectedCategoryId)
|
// Загружаем дерево для выбранной темы
|
||||||
|
const { data: treeData, isLoading: treeLoading } = useFlowNodesTree(selectedTopicId)
|
||||||
const tree = treeData?.data || []
|
const tree = treeData?.data || []
|
||||||
|
|
||||||
const deleteFlowNode = useDeleteFlowNode()
|
const deleteFlowNode = useDeleteFlowNode()
|
||||||
|
const saveTree = useSaveFlowTree()
|
||||||
|
const moveFlowNode = useMoveFlowNode()
|
||||||
const duplicateFlowNode = useDuplicateFlowNode()
|
const duplicateFlowNode = useDuplicateFlowNode()
|
||||||
const reloadBot = useReloadBot()
|
const updateTopic = useUpdateTopic()
|
||||||
|
|
||||||
// Вычисляем недостающие ключи в шаблоне сообщения
|
|
||||||
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 navigate = useNavigate()
|
||||||
|
|
||||||
const selectedCategory = useMemo<ApprovalTopicCategory | null>(
|
// Выбранная тема
|
||||||
() => categories.find((c) => c.id === selectedCategoryId) || null,
|
const selectedTopic = useMemo(() => {
|
||||||
[selectedCategoryId]
|
return topics.find((t) => t.id === selectedTopicId) || null
|
||||||
)
|
}, [topics, selectedTopicId])
|
||||||
|
|
||||||
const categoryOptions = categories.map((c) => ({ value: String(c.id), label: `${c.name} (${c.code})` }))
|
const topicOptions = topics.map((t) => ({
|
||||||
|
value: String(t.id),
|
||||||
|
label: `${t.name} (${t.code})`,
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Подсчёт узлов
|
||||||
const countNodes = (nodes: ApprovalFlowNode[]): number => {
|
const countNodes = (nodes: ApprovalFlowNode[]): number => {
|
||||||
let count = nodes.length
|
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
|
return count
|
||||||
}
|
}
|
||||||
const totalNodes = countNodes(tree)
|
const totalNodes = countNodes(tree)
|
||||||
|
|
||||||
|
// Обработчики
|
||||||
const handleEdit = (node: ApprovalFlowNode) => {
|
const handleEdit = (node: ApprovalFlowNode) => {
|
||||||
|
// Находим родителя
|
||||||
const parent = findParent(tree, node.id!)
|
const parent = findParent(tree, node.id!)
|
||||||
setEditModal({ opened: true, parentNode: parent, editNode: node })
|
setEditModal({
|
||||||
|
opened: true,
|
||||||
|
parentNode: parent,
|
||||||
|
editNode: node,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleAddChild = (parent: ApprovalFlowNode) => {
|
const handleAddChild = (parent: ApprovalFlowNode) => {
|
||||||
setEditModal({ opened: true, parentNode: parent, editNode: null })
|
setEditModal({
|
||||||
|
opened: true,
|
||||||
|
parentNode: parent,
|
||||||
|
editNode: null,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleAddRoot = () => {
|
const handleAddRoot = () => {
|
||||||
setEditModal({ opened: true, parentNode: null, editNode: null })
|
setEditModal({
|
||||||
|
opened: true,
|
||||||
|
parentNode: null,
|
||||||
|
editNode: null,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleDelete = (node: ApprovalFlowNode) => {
|
const handleDelete = (node: ApprovalFlowNode) => {
|
||||||
modals.openConfirmModal({
|
modals.openConfirmModal({
|
||||||
title: 'Удалить этот шаг?',
|
title: 'Удалить узел?',
|
||||||
children: (
|
children: (
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
Удалить шаг <b>{node.label}</b>? Все шаги, которые идут после него, тоже удалятся.
|
Удалить узел <b>{node.label}</b>? Все дочерние узлы также будут удалены.
|
||||||
</Text>
|
</Text>
|
||||||
),
|
),
|
||||||
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
||||||
|
|
@ -126,173 +136,199 @@ export default function FlowTreePage() {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleConfigureTopic = async (node: ApprovalFlowNode) => {
|
const handleDuplicate = (node: ApprovalFlowNode) => {
|
||||||
if (!selectedCategoryId || !node.id) return
|
duplicateFlowNode.mutate(node.id!)
|
||||||
|
}
|
||||||
|
|
||||||
const collected: Record<string, string> = {}
|
const handleMoveUp = (node: ApprovalFlowNode) => {
|
||||||
const nodeMap = new Map<number, ApprovalFlowNode>()
|
const parent = findParent(tree, node.id!)
|
||||||
|
const siblings = parent ? parent.children! : tree
|
||||||
const walk = (nodes: ApprovalFlowNode[]) => {
|
const index = siblings.findIndex((n) => n.id === node.id)
|
||||||
for (const n of nodes) {
|
if (index > 0) {
|
||||||
if (n.id) nodeMap.set(n.id, n)
|
moveFlowNode.mutate({
|
||||||
if (n.children) walk(n.children)
|
id: node.id!,
|
||||||
}
|
data: { new_sort_order: index - 1 },
|
||||||
}
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
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 handleDuplicate = (node: ApprovalFlowNode) => duplicateFlowNode.mutate(node.id!)
|
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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Text size="xl" fw={700}>
|
<Text size="xl" fw={700}>Конструктор деревьев</Text>
|
||||||
Конструктор тем
|
|
||||||
</Text>
|
|
||||||
<Group>
|
<Group>
|
||||||
{selectedCategory && <Badge size="lg" variant="light">{totalNodes} шагов</Badge>}
|
{selectedTopic && (
|
||||||
<Tooltip label="Заставить бота немедленно перечитать разделы/деревья/темы из базы, не дожидаясь автоматической проверки">
|
<Badge size="lg" variant="light">{totalNodes} узлов</Badge>
|
||||||
<Button
|
)}
|
||||||
variant="light"
|
<Button
|
||||||
color="orange"
|
variant="light"
|
||||||
leftSection={<IconRefresh size={16} />}
|
leftSection={<IconBook size={16} />}
|
||||||
onClick={() => reloadBot.mutate()}
|
onClick={() => navigate('/guide/flow-trees')}
|
||||||
loading={reloadBot.isPending}
|
>
|
||||||
>
|
|
||||||
Обновить бота
|
|
||||||
</Button>
|
|
||||||
</Tooltip>
|
|
||||||
<Button variant="light" leftSection={<IconBook size={16} />} onClick={() => navigate('/guide/flow-trees')}>
|
|
||||||
Руководство
|
Руководство
|
||||||
</Button>
|
</Button>
|
||||||
</Group>
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
|
{/* Выбор темы */}
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Group align="end" gap="sm">
|
<Stack gap="md">
|
||||||
<Select
|
<Select
|
||||||
label="Раздел заявок"
|
label="Тема"
|
||||||
placeholder="Выберите раздел, дерево которого будете настраивать"
|
placeholder="Выберите тему для редактирования дерева"
|
||||||
data={categoryOptions}
|
data={topicOptions}
|
||||||
value={selectedCategoryId ? String(selectedCategoryId) : null}
|
value={selectedTopicId ? String(selectedTopicId) : null}
|
||||||
onChange={(v) => setSelectedCategoryId(v ? Number(v) : null)}
|
onChange={(v) => setSelectedTopicId(v ? Number(v) : null)}
|
||||||
searchable
|
searchable
|
||||||
style={{ flex: 1 }}
|
required
|
||||||
/>
|
/>
|
||||||
<Tooltip label="Завести новый раздел заявок, не выходя отсюда">
|
|
||||||
<Button
|
{/* Шаблоны темы */}
|
||||||
variant="default"
|
{selectedTopic && (
|
||||||
leftSection={<IconFolderPlus size={16} />}
|
<>
|
||||||
onClick={() => setCategoryModalOpened(true)}
|
<Divider label="Шаблоны темы" labelPosition="center" />
|
||||||
>
|
|
||||||
Новый раздел
|
<Box>
|
||||||
</Button>
|
<Group
|
||||||
</Tooltip>
|
justify="space-between"
|
||||||
</Group>
|
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>
|
||||||
|
<Button
|
||||||
|
size="xs"
|
||||||
|
variant="light"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
handleSaveTemplates()
|
||||||
|
}}
|
||||||
|
loading={updateTopic.isPending}
|
||||||
|
leftSection={<IconDeviceFloppy size={14} />}
|
||||||
|
>
|
||||||
|
Сохранить шаблоны
|
||||||
|
</Button>
|
||||||
|
</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>
|
</Paper>
|
||||||
|
|
||||||
{selectedCategoryId && (
|
{/* Дерево */}
|
||||||
|
{selectedTopicId && (
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Group gap="xs">
|
<Group gap="xs">
|
||||||
|
<Text fw={600}>Дерево навигации</Text>
|
||||||
{treeLoading && <Loader size="xs" />}
|
{treeLoading && <Loader size="xs" />}
|
||||||
</Group>
|
</Group>
|
||||||
<Button leftSection={<IconPlus size={16} />} onClick={handleAddRoot} disabled={tree.length > 0}>
|
<Group>
|
||||||
Добавить первый вопрос
|
<Tooltip label="Обновить">
|
||||||
</Button>
|
<ActionIcon
|
||||||
|
variant="light"
|
||||||
|
onClick={() => {
|
||||||
|
if (selectedTopicId) {
|
||||||
|
// Инвалидация кэша
|
||||||
|
window.location.reload()
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<IconRefresh size={16} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
<Button
|
||||||
|
leftSection={<IconPlus size={16} />}
|
||||||
|
onClick={handleAddRoot}
|
||||||
|
>
|
||||||
|
Добавить корневой узел
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
</Group>
|
</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">
|
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
Перетаскивайте шаги за значок ⠿ слева, чтобы менять порядок и вложенность — тяните
|
<b>Совет:</b> Используйте кнопки ↑ ↓ для изменения порядка,{' '}
|
||||||
влево/вправо во время перетаскивания, чтобы изменить уровень. Первый шаг дерева
|
<b>+</b> для добавления дочернего узла, <b>📋</b> для дублирования.
|
||||||
(с пометкой «начало дерева») не перетаскивается.
|
Все изменения сохраняются автоматически.
|
||||||
</Text>
|
</Text>
|
||||||
</Alert>
|
</Alert>
|
||||||
|
|
||||||
|
|
@ -303,44 +339,64 @@ export default function FlowTreePage() {
|
||||||
) : tree.length === 0 ? (
|
) : tree.length === 0 ? (
|
||||||
<Center p={40}>
|
<Center p={40}>
|
||||||
<Stack gap="sm" align="center">
|
<Stack gap="sm" align="center">
|
||||||
<Text c="dimmed">В этом разделе пока нет вопросов</Text>
|
<Text c="dimmed">Дерево пустое</Text>
|
||||||
<Button leftSection={<IconPlus size={16} />} onClick={handleAddRoot}>
|
<Button
|
||||||
Добавить первый вопрос
|
leftSection={<IconPlus size={16} />}
|
||||||
|
onClick={handleAddRoot}
|
||||||
|
>
|
||||||
|
Добавить первый узел
|
||||||
</Button>
|
</Button>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Center>
|
</Center>
|
||||||
) : (
|
) : (
|
||||||
<SortableFlowTree
|
<Stack gap={4}>
|
||||||
tree={tree}
|
{tree.map((node, idx) => (
|
||||||
onEdit={handleEdit}
|
<FlowTreeNode
|
||||||
onAddChild={handleAddChild}
|
key={node.id}
|
||||||
onDelete={handleDelete}
|
node={node}
|
||||||
onDuplicate={handleDuplicate}
|
depth={0}
|
||||||
onConfigureTopic={handleConfigureTopic}
|
siblings={tree}
|
||||||
/>
|
onEdit={handleEdit}
|
||||||
|
onAddChild={handleAddChild}
|
||||||
|
onDelete={handleDelete}
|
||||||
|
onDuplicate={handleDuplicate}
|
||||||
|
onMoveUp={handleMoveUp}
|
||||||
|
onMoveDown={handleMoveDown}
|
||||||
|
index={idx}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
)}
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{selectedCategoryId && tree.length > 0 && <TreeHealthPanel categoryId={selectedCategoryId} tree={tree} />}
|
{/* Модалка редактирования узла */}
|
||||||
|
{selectedTopicId && (
|
||||||
{selectedCategoryId && (
|
|
||||||
<FlowNodeEditModal
|
<FlowNodeEditModal
|
||||||
categoryId={selectedCategoryId}
|
topicId={selectedTopicId}
|
||||||
tree={tree}
|
|
||||||
parentNode={editModal.parentNode}
|
parentNode={editModal.parentNode}
|
||||||
editNode={editModal.editNode}
|
editNode={editModal.editNode}
|
||||||
opened={editModal.opened}
|
opened={editModal.opened}
|
||||||
onClose={() => setEditModal({ opened: false, parentNode: null, editNode: null })}
|
onClose={() => setEditModal({ opened: false, parentNode: null, editNode: null })}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<CategoryCreateModal
|
|
||||||
opened={categoryModalOpened}
|
|
||||||
onClose={() => setCategoryModalOpened(false)}
|
|
||||||
onCreated={(newId) => setSelectedCategoryId(newId)}
|
|
||||||
/>
|
|
||||||
</Stack>
|
</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
|
||||||
|
}
|
||||||
|
|
@ -1,121 +0,0 @@
|
||||||
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
|
|
@ -0,0 +1,227 @@
|
||||||
|
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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -1,286 +0,0 @@
|
||||||
import { useMemo, useState } from 'react'
|
|
||||||
import {
|
|
||||||
DndContext,
|
|
||||||
DragOverlay,
|
|
||||||
PointerSensor,
|
|
||||||
useSensor,
|
|
||||||
useSensors,
|
|
||||||
closestCenter,
|
|
||||||
type DragStartEvent,
|
|
||||||
type DragMoveEvent,
|
|
||||||
type DragOverEvent,
|
|
||||||
type DragEndEvent,
|
|
||||||
} from '@dnd-kit/core'
|
|
||||||
import { SortableContext, verticalListSortingStrategy, useSortable } from '@dnd-kit/sortable'
|
|
||||||
import { CSS } from '@dnd-kit/utilities'
|
|
||||||
import { Paper, Group, Text, ActionIcon, Tooltip, Badge, Box, Alert } from '@mantine/core'
|
|
||||||
import {
|
|
||||||
IconGripVertical,
|
|
||||||
IconPlus,
|
|
||||||
IconEdit,
|
|
||||||
IconTrash,
|
|
||||||
IconCopy,
|
|
||||||
IconChevronDown,
|
|
||||||
IconChevronRight,
|
|
||||||
IconArrowsMove,
|
|
||||||
IconRoute,
|
|
||||||
} from '@tabler/icons-react'
|
|
||||||
import type { ApprovalFlowNode } from '@/types/api'
|
|
||||||
import { useReorderNodes } from '@/features/flowNodes/hooks/useFlowNodes'
|
|
||||||
import {buildReorderPlan, FlatFlowNode, flattenTree, getProjection} from "@/features/flowNodes/utils/flattenTree.ts";
|
|
||||||
|
|
||||||
const INDENTATION = 24
|
|
||||||
|
|
||||||
interface SortableFlowTreeProps {
|
|
||||||
tree: ApprovalFlowNode[]
|
|
||||||
onEdit: (node: ApprovalFlowNode) => void
|
|
||||||
onAddChild: (parent: ApprovalFlowNode) => void
|
|
||||||
onDelete: (node: ApprovalFlowNode) => void
|
|
||||||
onDuplicate: (node: ApprovalFlowNode) => void
|
|
||||||
onConfigureTopic: (node: ApprovalFlowNode) => void
|
|
||||||
}
|
|
||||||
|
|
||||||
function nodeIcon(node: ApprovalFlowNode): string {
|
|
||||||
if (node.is_input) return '📝'
|
|
||||||
if (node.is_multi_select) return '☑️'
|
|
||||||
return '🔘'
|
|
||||||
}
|
|
||||||
|
|
||||||
function nodeKindLabel(node: ApprovalFlowNode): string {
|
|
||||||
if (node.is_input) return 'Текстовый ввод — здесь сотрудник пишет заявку'
|
|
||||||
if (node.is_multi_select) return 'Можно выбрать несколько вариантов'
|
|
||||||
return 'Кнопка'
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function SortableFlowTree({ tree, onEdit, onAddChild, onDelete, onDuplicate, onConfigureTopic }: SortableFlowTreeProps) {
|
|
||||||
const [collapsed, setCollapsed] = useState<Set<number>>(new Set())
|
|
||||||
const [activeId, setActiveId] = useState<number | null>(null)
|
|
||||||
const [overId, setOverId] = useState<number | null>(null)
|
|
||||||
const [offsetX, setOffsetX] = useState(0)
|
|
||||||
const reorder = useReorderNodes()
|
|
||||||
|
|
||||||
const flatItems = useMemo(() => flattenTree(tree, collapsed), [tree, collapsed])
|
|
||||||
const sortableIds = useMemo(() => flatItems.map((n) => n.id!), [flatItems])
|
|
||||||
|
|
||||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))
|
|
||||||
|
|
||||||
const projected = useMemo(() => {
|
|
||||||
if (activeId == null || overId == null) return null
|
|
||||||
return getProjection(flatItems, activeId, overId, offsetX, INDENTATION)
|
|
||||||
}, [flatItems, activeId, overId, offsetX])
|
|
||||||
|
|
||||||
const activeNode = flatItems.find((n) => n.id === activeId) || null
|
|
||||||
const projectedParentLabel = projected
|
|
||||||
? flatItems.find((n) => n.id === projected.parentId)?.label || null
|
|
||||||
: null
|
|
||||||
|
|
||||||
const toggleCollapse = (id: number) => {
|
|
||||||
setCollapsed((prev) => {
|
|
||||||
const next = new Set(prev)
|
|
||||||
if (next.has(id)) next.delete(id)
|
|
||||||
else next.add(id)
|
|
||||||
return next
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDragStart = (event: DragStartEvent) => {
|
|
||||||
setActiveId(event.active.id as number)
|
|
||||||
setOverId(event.active.id as number)
|
|
||||||
setOffsetX(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDragMove = (event: DragMoveEvent) => {
|
|
||||||
setOffsetX(event.delta.x)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDragOver = (event: DragOverEvent) => {
|
|
||||||
setOverId((event.over?.id as number) ?? null)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDragEnd = (event: DragEndEvent) => {
|
|
||||||
const { active, over } = event
|
|
||||||
const currentProjected = projected
|
|
||||||
|
|
||||||
setActiveId(null)
|
|
||||||
setOverId(null)
|
|
||||||
setOffsetX(0)
|
|
||||||
|
|
||||||
if (!over || !currentProjected) return
|
|
||||||
|
|
||||||
const activeIdNum = active.id as number
|
|
||||||
const overIdNum = over.id as number
|
|
||||||
const activeNodeBefore = flatItems.find((n) => n.id === activeIdNum)
|
|
||||||
if (!activeNodeBefore) return
|
|
||||||
|
|
||||||
const noParentChange = (activeNodeBefore.parent_id ?? null) === currentProjected.parentId
|
|
||||||
const droppedOnSelf = activeIdNum === overIdNum
|
|
||||||
if (noParentChange && droppedOnSelf) return
|
|
||||||
|
|
||||||
const ops = buildReorderPlan(tree, activeIdNum, currentProjected.parentId, overIdNum)
|
|
||||||
if (ops.length > 0) {
|
|
||||||
reorder.mutate(ops)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<DndContext
|
|
||||||
sensors={sensors}
|
|
||||||
collisionDetection={closestCenter}
|
|
||||||
onDragStart={handleDragStart}
|
|
||||||
onDragMove={handleDragMove}
|
|
||||||
onDragOver={handleDragOver}
|
|
||||||
onDragEnd={handleDragEnd}
|
|
||||||
>
|
|
||||||
{activeNode && (
|
|
||||||
<Alert color="blue" variant="light" mb={6} icon={<IconArrowsMove size={16} />}>
|
|
||||||
<Text size="xs">
|
|
||||||
«{activeNode.label}» станет шагом внутри «{projectedParentLabel || '…'}» — потяните влево/вправо,
|
|
||||||
чтобы поменять уровень вложенности
|
|
||||||
</Text>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
<SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>
|
|
||||||
<Box>
|
|
||||||
{flatItems.map((node) => (
|
|
||||||
<SortableRow
|
|
||||||
key={node.id}
|
|
||||||
node={node}
|
|
||||||
hasChildren={!!node.children?.length}
|
|
||||||
collapsed={node.id != null && collapsed.has(node.id)}
|
|
||||||
onToggleCollapse={() => node.id != null && toggleCollapse(node.id)}
|
|
||||||
onEdit={onEdit}
|
|
||||||
onAddChild={onAddChild}
|
|
||||||
onDelete={onDelete}
|
|
||||||
onDuplicate={onDuplicate}
|
|
||||||
onConfigureTopic={onConfigureTopic}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Box>
|
|
||||||
</SortableContext>
|
|
||||||
<DragOverlay>
|
|
||||||
{activeNode ? (
|
|
||||||
<Paper withBorder p="xs" shadow="md">
|
|
||||||
<Group gap={6}>
|
|
||||||
<IconGripVertical size={14} />
|
|
||||||
<Text size="lg">{nodeIcon(activeNode)}</Text>
|
|
||||||
<Text fw={600}>{activeNode.label}</Text>
|
|
||||||
</Group>
|
|
||||||
</Paper>
|
|
||||||
) : null}
|
|
||||||
</DragOverlay>
|
|
||||||
</DndContext>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SortableRowProps {
|
|
||||||
node: FlatFlowNode
|
|
||||||
hasChildren: boolean
|
|
||||||
collapsed: boolean
|
|
||||||
onToggleCollapse: () => void
|
|
||||||
onEdit: (node: ApprovalFlowNode) => void
|
|
||||||
onAddChild: (parent: ApprovalFlowNode) => void
|
|
||||||
onDelete: (node: ApprovalFlowNode) => void
|
|
||||||
onDuplicate: (node: ApprovalFlowNode) => void
|
|
||||||
onConfigureTopic: (node: ApprovalFlowNode) => void
|
|
||||||
}
|
|
||||||
|
|
||||||
function SortableRow({ node, hasChildren, collapsed, onToggleCollapse, onEdit, onAddChild, onDelete, onDuplicate, onConfigureTopic }: SortableRowProps) {
|
|
||||||
const isRoot = node.depth === 0
|
|
||||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
|
||||||
id: node.id!,
|
|
||||||
disabled: isRoot, // корень дерева не перетаскивается — его ключ жёстко привязан к коду раздела
|
|
||||||
})
|
|
||||||
|
|
||||||
const style = {
|
|
||||||
transform: CSS.Translate.toString(transform),
|
|
||||||
transition,
|
|
||||||
marginLeft: node.depth * INDENTATION,
|
|
||||||
opacity: isDragging ? 0.4 : 1,
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div ref={setNodeRef} style={style}>
|
|
||||||
<Paper withBorder p="xs" mb={4} bg={isRoot ? 'var(--mantine-color-blue-0)' : undefined}>
|
|
||||||
<Group justify="space-between" wrap="nowrap">
|
|
||||||
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
|
|
||||||
{!isRoot ? (
|
|
||||||
<ActionIcon
|
|
||||||
variant="subtle"
|
|
||||||
size="sm"
|
|
||||||
{...attributes}
|
|
||||||
{...listeners}
|
|
||||||
style={{ cursor: 'grab', touchAction: 'none' }}
|
|
||||||
>
|
|
||||||
<IconGripVertical size={14} />
|
|
||||||
</ActionIcon>
|
|
||||||
) : (
|
|
||||||
<Tooltip label="Первый шаг дерева нельзя перемещать">
|
|
||||||
<Box w={28} />
|
|
||||||
</Tooltip>
|
|
||||||
)}
|
|
||||||
{hasChildren ? (
|
|
||||||
<ActionIcon size="sm" variant="subtle" onClick={onToggleCollapse}>
|
|
||||||
{collapsed ? <IconChevronRight size={14} /> : <IconChevronDown size={14} />}
|
|
||||||
</ActionIcon>
|
|
||||||
) : (
|
|
||||||
<Box w={22} />
|
|
||||||
)}
|
|
||||||
<Text size="lg">{nodeIcon(node)}</Text>
|
|
||||||
<Box style={{ minWidth: 0 }}>
|
|
||||||
<Group gap={6}>
|
|
||||||
<Text fw={600} truncate>
|
|
||||||
{node.label}
|
|
||||||
</Text>
|
|
||||||
{isRoot && (
|
|
||||||
<Badge size="xs" color="blue" variant="light">
|
|
||||||
начало дерева
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
<Text size="xs" c="dimmed">
|
|
||||||
{nodeKindLabel(node)}
|
|
||||||
{node.data_key ? ` · запоминает: ${node.data_key} = ${node.data_value}` : ''}
|
|
||||||
</Text>
|
|
||||||
</Box>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Group gap={2} wrap="nowrap">
|
|
||||||
{hasChildren && (
|
|
||||||
<Tooltip label="Настроить маршрут согласования для этого этапа">
|
|
||||||
<ActionIcon
|
|
||||||
variant="light"
|
|
||||||
size="sm"
|
|
||||||
color="violet"
|
|
||||||
onClick={() => onConfigureTopic(node)}
|
|
||||||
>
|
|
||||||
<IconRoute size={14} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Tooltip label="Добавить следующий шаг после этой кнопки">
|
|
||||||
<ActionIcon variant="subtle" size="sm" color="blue" onClick={() => onAddChild(node)}>
|
|
||||||
<IconPlus size={14} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip label="Изменить">
|
|
||||||
<ActionIcon variant="subtle" size="sm" onClick={() => onEdit(node)}>
|
|
||||||
<IconEdit size={14} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip label="Сделать копию этого шага со всеми вложенными">
|
|
||||||
<ActionIcon variant="subtle" size="sm" onClick={() => onDuplicate(node)}>
|
|
||||||
<IconCopy size={14} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip label="Удалить (вместе со всеми вложенными шагами)">
|
|
||||||
<ActionIcon variant="subtle" size="sm" color="red" onClick={() => onDelete(node)}>
|
|
||||||
<IconTrash size={14} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
</Group>
|
|
||||||
</Group>
|
|
||||||
</Paper>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,152 +0,0 @@
|
||||||
import { useState } from 'react'
|
|
||||||
import { Paper, Group, Text, Button, Table, Badge, Loader, Alert } from '@mantine/core'
|
|
||||||
import { IconStethoscope, IconInfoCircle, IconCirclePlus } from '@tabler/icons-react'
|
|
||||||
import { flowNodesApi, type PreviewFlowResponse } from '@/api/flowNodes'
|
|
||||||
import { useCreateTopic } from '@/features/topics/hooks/useTopics'
|
|
||||||
import type { CreateTopicRequest } from '@/api/topics'
|
|
||||||
import { collectFromPath, collectLeafPaths, pathLabel } from '@/features/flowNodes/utils/treeWalk'
|
|
||||||
import type { ApprovalFlowNode } from '@/types/api'
|
|
||||||
|
|
||||||
interface TreeHealthPanelProps {
|
|
||||||
categoryId: number
|
|
||||||
tree: ApprovalFlowNode[]
|
|
||||||
}
|
|
||||||
|
|
||||||
interface HealthRow {
|
|
||||||
key: string
|
|
||||||
label: string
|
|
||||||
result: PreviewFlowResponse | null
|
|
||||||
error?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
// Проходит по каждой готовой ветке дерева ("от начала до текстового ввода")
|
|
||||||
// и проверяет через реальный движок бэкенда, есть ли для неё настроенная
|
|
||||||
// тема. Так администратор видит проблему ДО того, как сотрудник наткнётся
|
|
||||||
// на неё в боте — а не после жалобы, что "заявка не отправляется".
|
|
||||||
export default function TreeHealthPanel({ categoryId, tree }: TreeHealthPanelProps) {
|
|
||||||
const [rows, setRows] = useState<HealthRow[] | null>(null)
|
|
||||||
const [checking, setChecking] = useState(false)
|
|
||||||
const createTopic = useCreateTopic()
|
|
||||||
|
|
||||||
const runCheck = async () => {
|
|
||||||
setChecking(true)
|
|
||||||
const leafPaths = collectLeafPaths(tree)
|
|
||||||
const results = await Promise.all(
|
|
||||||
leafPaths.map(async (path) => {
|
|
||||||
const key = path.map((n) => n.id).join('-')
|
|
||||||
const label = pathLabel(path)
|
|
||||||
try {
|
|
||||||
const response = await flowNodesApi.preview(categoryId, {
|
|
||||||
collected: collectFromPath(path),
|
|
||||||
})
|
|
||||||
return { key, label, result: response.data } as HealthRow
|
|
||||||
} catch {
|
|
||||||
return { key, label, result: null, error: true } as HealthRow
|
|
||||||
}
|
|
||||||
})
|
|
||||||
)
|
|
||||||
setRows(results)
|
|
||||||
setChecking(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleCreateTopic = async (row: HealthRow) => {
|
|
||||||
if (!row.result?.code) return
|
|
||||||
const payload: CreateTopicRequest = {
|
|
||||||
category_id: categoryId,
|
|
||||||
code: row.result.code,
|
|
||||||
name: row.label,
|
|
||||||
is_active: true,
|
|
||||||
}
|
|
||||||
await createTopic.mutateAsync(payload)
|
|
||||||
runCheck()
|
|
||||||
}
|
|
||||||
|
|
||||||
const missingCount = rows?.filter((r) => r.result && !r.result.incomplete && !r.result.topic_exists).length || 0
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Paper withBorder p="md">
|
|
||||||
<Group justify="space-between" mb="sm">
|
|
||||||
<Text fw={600}>Проверка дерева</Text>
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
leftSection={<IconStethoscope size={14} />}
|
|
||||||
onClick={runCheck}
|
|
||||||
loading={checking}
|
|
||||||
>
|
|
||||||
Проверить все ветки
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light" mb="sm">
|
|
||||||
<Text size="xs">
|
|
||||||
Пройдёт по каждому возможному пути в дереве и проверит, для всех ли есть настроенная тема
|
|
||||||
заявки. Если для какого-то пути темы нет — заявку по нему бот не сможет отправить.
|
|
||||||
</Text>
|
|
||||||
</Alert>
|
|
||||||
|
|
||||||
{rows && missingCount > 0 && (
|
|
||||||
<Alert color="orange" variant="light" mb="sm">
|
|
||||||
<Text size="sm">Не хватает тем для {missingCount} путей — см. таблицу ниже.</Text>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
{rows && missingCount === 0 && (
|
|
||||||
<Alert color="teal" variant="light" mb="sm">
|
|
||||||
<Text size="sm">Все ветки дерева ведут к настроенным темам ✅</Text>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{checking && <Loader size="sm" />}
|
|
||||||
|
|
||||||
{rows && (
|
|
||||||
<Table striped withTableBorder>
|
|
||||||
<Table.Thead>
|
|
||||||
<Table.Tr>
|
|
||||||
<Table.Th>Путь</Table.Th>
|
|
||||||
<Table.Th>Код темы</Table.Th>
|
|
||||||
<Table.Th>Статус</Table.Th>
|
|
||||||
<Table.Th />
|
|
||||||
</Table.Tr>
|
|
||||||
</Table.Thead>
|
|
||||||
<Table.Tbody>
|
|
||||||
{rows.map((row) => (
|
|
||||||
<Table.Tr key={row.key}>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="xs">{row.label}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="xs" ff="monospace">
|
|
||||||
{row.result?.code || '—'}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
{row.error ? (
|
|
||||||
<Badge color="red">Ошибка проверки</Badge>
|
|
||||||
) : row.result?.incomplete ? (
|
|
||||||
<Badge color="gray">Путь не завершён</Badge>
|
|
||||||
) : row.result?.topic_exists ? (
|
|
||||||
<Badge color="teal">Есть тема</Badge>
|
|
||||||
) : (
|
|
||||||
<Badge color="orange">Темы нет</Badge>
|
|
||||||
)}
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
{row.result && !row.result.incomplete && !row.result.topic_exists && (
|
|
||||||
<Button
|
|
||||||
size="compact-xs"
|
|
||||||
leftSection={<IconCirclePlus size={12} />}
|
|
||||||
onClick={() => handleCreateTopic(row)}
|
|
||||||
loading={createTopic.isPending}
|
|
||||||
>
|
|
||||||
Создать
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
))}
|
|
||||||
</Table.Tbody>
|
|
||||||
</Table>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -16,22 +16,20 @@ import {
|
||||||
Badge,
|
Badge,
|
||||||
Alert,
|
Alert,
|
||||||
ScrollArea,
|
ScrollArea,
|
||||||
Pagination,
|
|
||||||
Checkbox,
|
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import {
|
import {
|
||||||
IconPencil,
|
IconPencil,
|
||||||
IconTrash,
|
IconTrash,
|
||||||
IconPlus,
|
IconPlus,
|
||||||
|
IconList,
|
||||||
|
IconRoute,
|
||||||
IconInfoCircle,
|
IconInfoCircle,
|
||||||
IconUsers,
|
|
||||||
} from '@tabler/icons-react'
|
} from '@tabler/icons-react'
|
||||||
import { modals } from '@mantine/modals'
|
import { modals } from '@mantine/modals'
|
||||||
import { notifications } from '@mantine/notifications'
|
import { notifications } from '@mantine/notifications'
|
||||||
import {
|
import {
|
||||||
useHierarchies,
|
useHierarchies,
|
||||||
useDeleteHierarchy,
|
useDeleteHierarchy
|
||||||
useUpdateHierarchy, HIERARCHIES_QUERY_KEY,
|
|
||||||
} from '@/features/hierarchies/hooks/useHierarchies'
|
} from '@/features/hierarchies/hooks/useHierarchies'
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||||
import { useDepartments } from '@/features/departments/hooks/useDepartments'
|
import { useDepartments } from '@/features/departments/hooks/useDepartments'
|
||||||
|
|
@ -44,57 +42,22 @@ import {
|
||||||
type ChainGroup,
|
type ChainGroup,
|
||||||
} from '@/features/hierarchies/utils'
|
} from '@/features/hierarchies/utils'
|
||||||
import ChainVisualization from './components/ChainVisualization'
|
import ChainVisualization from './components/ChainVisualization'
|
||||||
import ChainDuplicateModal from './components/ChainDuplicateModal'
|
|
||||||
import HierarchyEditModal from './components/HierarchyEditModal'
|
import HierarchyEditModal from './components/HierarchyEditModal'
|
||||||
import PersonDuplicateModal from './components/PersonDuplicateModal'
|
|
||||||
import type { UserHierarchy } from '@/types/api'
|
import type { UserHierarchy } from '@/types/api'
|
||||||
import { hierarchiesApi } from '@/api/hierarchies'
|
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
|
||||||
|
|
||||||
const LIMIT = 20
|
|
||||||
|
|
||||||
type ViewMode = 'chains' | 'table'
|
type ViewMode = 'chains' | 'table'
|
||||||
|
|
||||||
export default function HierarchiesPage() {
|
export default function HierarchiesPage() {
|
||||||
const [viewMode, setViewMode] = useState<ViewMode>('chains')
|
const [viewMode, setViewMode] = useState<ViewMode>('chains')
|
||||||
const [page, setPage] = useState(1)
|
|
||||||
|
|
||||||
// Фильтры
|
|
||||||
const [subordinateFilter, setSubordinateFilter] = useState<string | null>(null)
|
const [subordinateFilter, setSubordinateFilter] = useState<string | null>(null)
|
||||||
const [approverFilter, setApproverFilter] = useState<string | null>(null)
|
|
||||||
const [userStatusFilter, setUserStatusFilter] = useState<string | null>(null)
|
|
||||||
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
|
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
|
||||||
const [categoryFilter, setCategoryFilter] = useState<string | null>(null)
|
|
||||||
const [topicFilter, setTopicFilter] = useState<string | null>(null)
|
|
||||||
|
|
||||||
// Массовое удаление
|
|
||||||
const [selectedIds, setSelectedIds] = useState<number[]>([])
|
|
||||||
const [isDeleting, setIsDeleting] = useState(false)
|
|
||||||
|
|
||||||
// Модалки
|
|
||||||
const [editHierarchy, setEditHierarchy] = useState<UserHierarchy | null>(null)
|
const [editHierarchy, setEditHierarchy] = useState<UserHierarchy | null>(null)
|
||||||
const [createModalOpened, setCreateModalOpened] = useState(false)
|
const [createModalOpened, setCreateModalOpened] = useState(false)
|
||||||
const [presetGroup, setPresetGroup] = useState<ChainGroup | null>(null)
|
const [presetGroup, setPresetGroup] = useState<ChainGroup | null>(null)
|
||||||
const [duplicateGroup, setDuplicateGroup] = useState<ChainGroup | null>(null)
|
|
||||||
const [duplicateModalOpened, setDuplicateModalOpened] = useState(false)
|
|
||||||
const [personDuplicateOpened, setPersonDuplicateOpened] = useState(false)
|
|
||||||
|
|
||||||
const { data: categoryTopics } = useTopics({
|
|
||||||
limit: 1000,
|
|
||||||
...(categoryFilter && { category_id: Number(categoryFilter) }),
|
|
||||||
})
|
|
||||||
|
|
||||||
const { data, isLoading, isFetching } = useHierarchies({
|
const { data, isLoading, isFetching } = useHierarchies({
|
||||||
offset: (page - 1) * LIMIT,
|
|
||||||
limit: LIMIT,
|
|
||||||
...(subordinateFilter && { subordinate_id: Number(subordinateFilter) }),
|
...(subordinateFilter && { subordinate_id: Number(subordinateFilter) }),
|
||||||
...(approverFilter && { approver_id: Number(approverFilter) }),
|
|
||||||
...(departmentFilter && { department_id: Number(departmentFilter) }),
|
...(departmentFilter && { department_id: Number(departmentFilter) }),
|
||||||
...(categoryFilter && { topic_category_id: Number(categoryFilter) }),
|
|
||||||
...(topicFilter && { topic_id: Number(topicFilter) }),
|
|
||||||
...(userStatusFilter && {
|
|
||||||
user_status: userStatusFilter as 'active' | 'fired' | 'blocked',
|
|
||||||
}),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const { data: users } = useUsers({ limit: 1000 })
|
const { data: users } = useUsers({ limit: 1000 })
|
||||||
|
|
@ -103,15 +66,14 @@ export default function HierarchiesPage() {
|
||||||
const { data: topics } = useTopics({ limit: 1000 })
|
const { data: topics } = useTopics({ limit: 1000 })
|
||||||
|
|
||||||
const deleteHierarchy = useDeleteHierarchy()
|
const deleteHierarchy = useDeleteHierarchy()
|
||||||
const updateHierarchy = useUpdateHierarchy()
|
|
||||||
|
|
||||||
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
|
||||||
|
|
||||||
|
// Группируем в цепочки
|
||||||
const chains = useMemo(() => {
|
const chains = useMemo(() => {
|
||||||
if (!data?.data) return []
|
if (!data?.data) return []
|
||||||
return groupHierarchiesIntoChains(data.data)
|
return groupHierarchiesIntoChains(data.data)
|
||||||
}, [data])
|
}, [data])
|
||||||
|
|
||||||
|
// Обогатим цепочки названиями объектов
|
||||||
const enrichedChains = useMemo(() => {
|
const enrichedChains = useMemo(() => {
|
||||||
return chains.map((chain) => {
|
return chains.map((chain) => {
|
||||||
let scopeObjectName = 'Все темы'
|
let scopeObjectName = 'Все темы'
|
||||||
|
|
@ -126,160 +88,27 @@ export default function HierarchiesPage() {
|
||||||
})
|
})
|
||||||
}, [chains, categories, topics])
|
}, [chains, categories, topics])
|
||||||
|
|
||||||
const filteredUsers = useMemo(() => {
|
const userOptions = users?.data?.map((u) => ({
|
||||||
if (!users?.data) return []
|
|
||||||
return users.data.filter((u) => {
|
|
||||||
if (userStatusFilter === 'active') return !u.is_blocked && !u.is_fired
|
|
||||||
if (userStatusFilter === 'fired') return !!u.is_fired
|
|
||||||
if (userStatusFilter === 'blocked') return !!u.is_blocked
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
}, [users, userStatusFilter])
|
|
||||||
|
|
||||||
const userOptions =
|
|
||||||
filteredUsers.map((u) => ({
|
|
||||||
value: String(u.id),
|
|
||||||
label: u.full_name || `Пользователь #${u.id}`,
|
|
||||||
})) || []
|
|
||||||
users?.data?.map((u) => ({
|
|
||||||
value: String(u.id),
|
value: String(u.id),
|
||||||
label: u.full_name || `Пользователь #${u.id}`,
|
label: u.full_name || `Пользователь #${u.id}`,
|
||||||
})) || [];
|
})) || []
|
||||||
|
|
||||||
const allUserOptions =
|
const departmentOptions = departments?.data?.map((d) => ({
|
||||||
users?.data?.map((u) => ({
|
value: String(d.id),
|
||||||
value: String(u.id),
|
label: d.name || '',
|
||||||
label: u.full_name || `Пользователь #${u.id}`,
|
})) || []
|
||||||
})) || []
|
|
||||||
|
|
||||||
const departmentOptions =
|
|
||||||
departments?.data?.map((d) => ({
|
|
||||||
value: String(d.id),
|
|
||||||
label: d.name || '',
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const categoryOptions =
|
|
||||||
categories?.data?.map((c) => ({
|
|
||||||
value: String(c.id),
|
|
||||||
label: c.name || '',
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const topicOptions =
|
|
||||||
(categoryFilter ? categoryTopics?.data : topics?.data)?.map((t) => ({
|
|
||||||
value: String(t.id),
|
|
||||||
label: t.name || '',
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const handleSelectAll = () => {
|
|
||||||
if (selectedIds.length === data?.data?.length) {
|
|
||||||
setSelectedIds([])
|
|
||||||
} else {
|
|
||||||
setSelectedIds(data?.data?.map((h) => h.id!) || [])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleSelectOne = (id: number) => {
|
|
||||||
setSelectedIds((prev) =>
|
|
||||||
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleFilterChange =
|
|
||||||
(setter: (value: string | null) => void) => (value: string | null) => {
|
|
||||||
setter(value)
|
|
||||||
setPage(1)
|
|
||||||
setSelectedIds([])
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
|
|
||||||
const handleBulkDelete = () => {
|
|
||||||
modals.openConfirmModal({
|
|
||||||
title: 'Подтвердите массовое удаление',
|
|
||||||
children: (
|
|
||||||
<Text size="sm">
|
|
||||||
Вы уверены, что хотите удалить <strong>{selectedIds.length}</strong>{' '}
|
|
||||||
записей? Это действие необратимо.
|
|
||||||
</Text>
|
|
||||||
),
|
|
||||||
labels: { confirm: 'Удалить все', cancel: 'Отмена' },
|
|
||||||
confirmProps: { color: 'red', loading: isDeleting },
|
|
||||||
onConfirm: async () => {
|
|
||||||
setIsDeleting(true)
|
|
||||||
try {
|
|
||||||
// Удаляем напрямую через API, не вызывая мутацию поштучно
|
|
||||||
await Promise.all(selectedIds.map((id) => hierarchiesApi.delete(id)))
|
|
||||||
|
|
||||||
// Обновляем список один раз
|
|
||||||
queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] })
|
|
||||||
|
|
||||||
notifications.show({
|
|
||||||
title: 'Успешно',
|
|
||||||
message: `Успешно удалено записей: ${selectedIds.length}`,
|
|
||||||
color: 'green',
|
|
||||||
})
|
|
||||||
setSelectedIds([])
|
|
||||||
} catch (error) {
|
|
||||||
notifications.show({
|
|
||||||
title: 'Ошибка',
|
|
||||||
message: 'Не удалось удалить некоторые записи',
|
|
||||||
color: 'red',
|
|
||||||
})
|
|
||||||
} finally {
|
|
||||||
setIsDeleting(false)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDelete = (id: number) => {
|
const handleDelete = (id: number) => {
|
||||||
modals.openConfirmModal({
|
modals.openConfirmModal({
|
||||||
title: 'Подтвердите удаление',
|
title: 'Подтвердите удаление',
|
||||||
children: (
|
children: (
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
Вы уверены, что хотите удалить эту связь?
|
Вы уверены, что хотите удалить эту связь? Это может повлиять на процесс согласования.
|
||||||
</Text>
|
</Text>
|
||||||
),
|
),
|
||||||
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
||||||
confirmProps: { color: 'red' },
|
confirmProps: { color: 'red' },
|
||||||
onConfirm: async () => {
|
onConfirm: () => deleteHierarchy.mutate(id),
|
||||||
await deleteHierarchy.mutateAsync(id)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDeleteChain = (group: ChainGroup) => {
|
|
||||||
const stepIds = group.steps.map((s) => s.id!).filter(Boolean)
|
|
||||||
if (stepIds.length === 0) return
|
|
||||||
|
|
||||||
modals.openConfirmModal({
|
|
||||||
title: 'Удалить всю цепочку',
|
|
||||||
children: (
|
|
||||||
<Text size="sm">
|
|
||||||
Вы уверены, что хотите удалить всю цепочку согласования для{' '}
|
|
||||||
<strong>{group.subordinateName}</strong> ({group.scopeObjectName}, шагов:{' '}
|
|
||||||
{stepIds.length})? Это действие необратимо.
|
|
||||||
</Text>
|
|
||||||
),
|
|
||||||
labels: { confirm: 'Удалить цепочку', cancel: 'Отмена' },
|
|
||||||
confirmProps: { color: 'red' },
|
|
||||||
onConfirm: async () => {
|
|
||||||
try {
|
|
||||||
await Promise.all(stepIds.map((id) => hierarchiesApi.delete(id)))
|
|
||||||
queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] })
|
|
||||||
notifications.show({
|
|
||||||
title: 'Успешно',
|
|
||||||
message: `Цепочка удалена (удалено шагов: ${stepIds.length})`,
|
|
||||||
color: 'green',
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
notifications.show({
|
|
||||||
title: 'Ошибка',
|
|
||||||
message: 'Не удалось удалить цепочку полностью',
|
|
||||||
color: 'red',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -295,78 +124,26 @@ export default function HierarchiesPage() {
|
||||||
setCreateModalOpened(true)
|
setCreateModalOpened(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleDuplicateChain = (group: ChainGroup) => {
|
|
||||||
setDuplicateGroup(group)
|
|
||||||
setDuplicateModalOpened(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleCloseModal = () => {
|
const handleCloseModal = () => {
|
||||||
setEditHierarchy(null)
|
setEditHierarchy(null)
|
||||||
setCreateModalOpened(false)
|
setCreateModalOpened(false)
|
||||||
setPresetGroup(null)
|
setPresetGroup(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleCloseDuplicateModal = () => {
|
|
||||||
setDuplicateGroup(null)
|
|
||||||
setDuplicateModalOpened(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
const isAllSelected =
|
|
||||||
(data?.data?.length ?? 0) > 0 && selectedIds.length === (data?.data?.length ?? 0)
|
|
||||||
const isIndeterminate =
|
|
||||||
selectedIds.length > 0 && selectedIds.length < (data?.data?.length || 0)
|
|
||||||
|
|
||||||
const handleBulkUpdateSystem = async (group: ChainGroup, targetSystem: string | null) => {
|
|
||||||
try {
|
|
||||||
// Обновляем все шаги в выбранной цепочке асинхронно
|
|
||||||
await Promise.all(
|
|
||||||
group.steps.map((step) =>
|
|
||||||
updateHierarchy.mutateAsync({
|
|
||||||
id: step.id!,
|
|
||||||
subordinate_id: step.subordinate_id,
|
|
||||||
approver_id: step.approver_id,
|
|
||||||
department_id: step.department_id,
|
|
||||||
topic_category_id: step.topic_category_id,
|
|
||||||
topic_id: step.topic_id,
|
|
||||||
priority: step.priority,
|
|
||||||
target_system: targetSystem, // Применяем новую систему
|
|
||||||
})
|
|
||||||
)
|
|
||||||
)
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Ошибка при массовом обновлении систем цепочки", error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{/* Заголовок */}
|
{/* Заголовок */}
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Text size="xl" fw={700}>Иерархия согласований</Text>
|
<Text size="xl" fw={700}>Иерархия согласований</Text>
|
||||||
<Group>
|
<Group>
|
||||||
<Text c="dimmed" size="sm">
|
|
||||||
Всего: {data?.total_count || 0}
|
|
||||||
</Text>
|
|
||||||
<SegmentedControl
|
<SegmentedControl
|
||||||
value={viewMode}
|
value={viewMode}
|
||||||
onChange={(v) => {
|
onChange={(v) => setViewMode(v as ViewMode)}
|
||||||
setViewMode(v as ViewMode)
|
|
||||||
setSelectedIds([])
|
|
||||||
}}
|
|
||||||
data={[
|
data={[
|
||||||
{ value: 'chains', label: 'Цепочки' },
|
{ value: 'chains', label: 'Цепочки' },
|
||||||
{ value: 'table', label: 'Таблица' },
|
{ value: 'table', label: 'Таблица'},
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
<Tooltip label="Скопировать все цепочки одного сотрудника для другого — например, для нового сотрудника с такой же ролью">
|
|
||||||
<Button
|
|
||||||
variant="light"
|
|
||||||
leftSection={<IconUsers size={16} />}
|
|
||||||
onClick={() => setPersonDuplicateOpened(true)}
|
|
||||||
>
|
|
||||||
Дублировать по сотруднику
|
|
||||||
</Button>
|
|
||||||
</Tooltip>
|
|
||||||
<Button
|
<Button
|
||||||
leftSection={<IconPlus size={16} />}
|
leftSection={<IconPlus size={16} />}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
|
|
@ -379,308 +156,164 @@ export default function HierarchiesPage() {
|
||||||
</Group>
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
|
{/* Подсказка */}
|
||||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
Иерархия определяет порядок согласования заявок. Каждая цепочка показывает,
|
Иерархия определяет порядок согласования заявок. Каждая цепочка показывает,
|
||||||
через каких согласующих проходит заявка от конкретного сотрудника.
|
через каких согласующих проходит заявка от конкретного сотрудника.
|
||||||
|
Шаги выполняются последовательно в порядке возрастания приоритета.
|
||||||
</Text>
|
</Text>
|
||||||
</Alert>
|
</Alert>
|
||||||
|
|
||||||
{/* Фильтры */}
|
{/* Фильтры */}
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Stack gap="md">
|
<Group gap="md" align="flex-end">
|
||||||
<Group gap="md" align="flex-end">
|
<Select
|
||||||
<Select
|
label="Сотрудник"
|
||||||
label="Сотрудник (инициатор)"
|
placeholder="Все пользователи"
|
||||||
placeholder="Все пользователи"
|
data={userOptions}
|
||||||
data={userOptions}
|
value={subordinateFilter}
|
||||||
value={subordinateFilter}
|
onChange={setSubordinateFilter}
|
||||||
onChange={handleFilterChange(setSubordinateFilter)}
|
clearable
|
||||||
clearable
|
searchable
|
||||||
searchable
|
style={{ minWidth: 250 }}
|
||||||
style={{ flex: 1, minWidth: 220 }}
|
/>
|
||||||
/>
|
|
||||||
<Select
|
<Select
|
||||||
label="Статус сотрудника"
|
label="Отдел"
|
||||||
placeholder="Все статусы"
|
placeholder="Все отделы"
|
||||||
data={[
|
data={departmentOptions}
|
||||||
{ value: 'active', label: 'Активен' },
|
value={departmentFilter}
|
||||||
{ value: 'fired', label: 'Уволен' },
|
onChange={setDepartmentFilter}
|
||||||
{ value: 'blocked', label: 'Заблокирован' },
|
clearable
|
||||||
]}
|
style={{ minWidth: 200 }}
|
||||||
value={userStatusFilter}
|
/>
|
||||||
onChange={handleFilterChange(setUserStatusFilter)}
|
|
||||||
clearable
|
<Text c="dimmed" size="sm">
|
||||||
style={{ width: 180 }}
|
Всего связей: {data?.data?.length || 0}
|
||||||
/>
|
</Text>
|
||||||
<Select
|
</Group>
|
||||||
label="Согласующий"
|
|
||||||
placeholder="Все согласующие"
|
|
||||||
data={allUserOptions}
|
|
||||||
value={approverFilter}
|
|
||||||
onChange={handleFilterChange(setApproverFilter)}
|
|
||||||
clearable
|
|
||||||
searchable
|
|
||||||
style={{ flex: 1, minWidth: 220 }}
|
|
||||||
/>
|
|
||||||
</Group>
|
|
||||||
<Group gap="md" align="flex-end">
|
|
||||||
<Select
|
|
||||||
label="Отдел"
|
|
||||||
placeholder="Все отделы"
|
|
||||||
data={departmentOptions}
|
|
||||||
value={departmentFilter}
|
|
||||||
onChange={handleFilterChange(setDepartmentFilter)}
|
|
||||||
clearable
|
|
||||||
style={{ flex: 1, minWidth: 200 }}
|
|
||||||
/>
|
|
||||||
<Select
|
|
||||||
label="Категория"
|
|
||||||
placeholder="Все категории"
|
|
||||||
data={categoryOptions}
|
|
||||||
value={categoryFilter}
|
|
||||||
onChange={(v) => {
|
|
||||||
handleFilterChange(setCategoryFilter)(v)
|
|
||||||
setTopicFilter(null)
|
|
||||||
}}
|
|
||||||
clearable
|
|
||||||
searchable
|
|
||||||
style={{ flex: 1, minWidth: 200 }}
|
|
||||||
/>
|
|
||||||
<Select
|
|
||||||
label="Тема"
|
|
||||||
placeholder="Все темы"
|
|
||||||
data={topicOptions}
|
|
||||||
value={topicFilter}
|
|
||||||
onChange={handleFilterChange(setTopicFilter)}
|
|
||||||
clearable
|
|
||||||
searchable
|
|
||||||
style={{ flex: 1, minWidth: 200 }}
|
|
||||||
/>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
{/* Контент */}
|
{/* Контент */}
|
||||||
<Paper withBorder>
|
{isLoading ? (
|
||||||
{isLoading ? (
|
<Center p={60}>
|
||||||
<Center p={60}>
|
<Loader />
|
||||||
<Loader />
|
</Center>
|
||||||
</Center>
|
) : viewMode === 'chains' ? (
|
||||||
) : viewMode === 'chains' ? (
|
// Режим цепочек
|
||||||
<ScrollArea p="md">
|
<ScrollArea>
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{enrichedChains.length === 0 ? (
|
{enrichedChains.length === 0 ? (
|
||||||
<Center p={40}>
|
<Paper withBorder p={40}>
|
||||||
|
<Center>
|
||||||
<Text c="dimmed">Связи не найдены</Text>
|
<Text c="dimmed">Связи не найдены</Text>
|
||||||
</Center>
|
</Center>
|
||||||
) : (
|
</Paper>
|
||||||
enrichedChains.map((chain) => (
|
) : (
|
||||||
<ChainVisualization
|
enrichedChains.map((chain) => (
|
||||||
key={chain.key}
|
<ChainVisualization
|
||||||
group={chain}
|
key={chain.key}
|
||||||
onEditStep={handleEditStep}
|
group={chain}
|
||||||
onDeleteStep={handleDelete}
|
onEditStep={handleEditStep}
|
||||||
onDeleteChain={handleDeleteChain}
|
onDeleteStep={handleDelete}
|
||||||
onAddStep={handleAddStep}
|
onAddStep={handleAddStep}
|
||||||
onDuplicateChain={handleDuplicateChain}
|
/>
|
||||||
onBulkUpdateSystem={handleBulkUpdateSystem}
|
))
|
||||||
/>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</ScrollArea>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
{selectedIds.length > 0 && (
|
|
||||||
<Box
|
|
||||||
p="sm"
|
|
||||||
bg="red.0"
|
|
||||||
style={{ borderBottom: '1px solid var(--mantine-color-red-3)' }}
|
|
||||||
>
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" fw={500}>
|
|
||||||
Выбрано записей: <strong>{selectedIds.length}</strong>
|
|
||||||
</Text>
|
|
||||||
<Group gap="xs">
|
|
||||||
<Button
|
|
||||||
variant="subtle"
|
|
||||||
size="xs"
|
|
||||||
onClick={() => setSelectedIds([])}
|
|
||||||
>
|
|
||||||
Снять выделение
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
color="red"
|
|
||||||
size="xs"
|
|
||||||
leftSection={<IconTrash size={14} />}
|
|
||||||
onClick={handleBulkDelete}
|
|
||||||
loading={isDeleting}
|
|
||||||
>
|
|
||||||
Удалить выбранные
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Group>
|
|
||||||
</Box>
|
|
||||||
)}
|
)}
|
||||||
|
</Stack>
|
||||||
|
</ScrollArea>
|
||||||
|
) : (
|
||||||
|
// Режим таблицы
|
||||||
|
<Paper withBorder>
|
||||||
|
<Table striped highlightOnHover>
|
||||||
|
<Table.Thead>
|
||||||
|
<Table.Tr>
|
||||||
|
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
||||||
|
<Table.Th>Подчинённый</Table.Th>
|
||||||
|
<Table.Th>Согласующий</Table.Th>
|
||||||
|
<Table.Th>Отдел</Table.Th>
|
||||||
|
<Table.Th>Область</Table.Th>
|
||||||
|
<Table.Th>Объект</Table.Th>
|
||||||
|
<Table.Th style={{ width: 80 }}>Порядок</Table.Th>
|
||||||
|
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
|
||||||
|
</Table.Tr>
|
||||||
|
</Table.Thead>
|
||||||
|
<Table.Tbody>
|
||||||
|
{data?.data?.map((h) => {
|
||||||
|
const scopeType = h.topic_id ? 'topic' :
|
||||||
|
h.topic_category_id ? 'category' : 'global'
|
||||||
|
let scopeObjectName = 'Все темы'
|
||||||
|
if (scopeType === 'category' && h.topic_category_id) {
|
||||||
|
const cat = categories?.data?.find((c) => c.id === h.topic_category_id)
|
||||||
|
scopeObjectName = cat?.name || `#${h.topic_category_id}`
|
||||||
|
} else if (scopeType === 'topic' && h.topic_id) {
|
||||||
|
const topic = topics?.data?.find((t) => t.id === h.topic_id)
|
||||||
|
scopeObjectName = topic?.name || `#${h.topic_id}`
|
||||||
|
}
|
||||||
|
|
||||||
<Table striped highlightOnHover>
|
return (
|
||||||
<Table.Thead>
|
<Table.Tr key={h.id}>
|
||||||
<Table.Tr>
|
<Table.Td>{h.id}</Table.Td>
|
||||||
<Table.Th style={{ width: 50 }}>
|
<Table.Td>
|
||||||
<Checkbox
|
<Text size="sm" fw={500}>
|
||||||
checked={isAllSelected}
|
{h.subordinate?.full_name || '—'}
|
||||||
indeterminate={isIndeterminate}
|
</Text>
|
||||||
onChange={handleSelectAll}
|
</Table.Td>
|
||||||
/>
|
<Table.Td>
|
||||||
</Table.Th>
|
<Text size="sm" fw={500}>
|
||||||
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
{h.approver?.full_name || '—'}
|
||||||
<Table.Th>Подчинённый</Table.Th>
|
</Text>
|
||||||
<Table.Th>Согласующий</Table.Th>
|
</Table.Td>
|
||||||
<Table.Th>Отдел</Table.Th>
|
<Table.Td>
|
||||||
<Table.Th>Область</Table.Th>
|
<Text size="sm">{h.department?.name || '—'}</Text>
|
||||||
<Table.Th>Объект</Table.Th>
|
</Table.Td>
|
||||||
<Table.Th style={{ width: 80 }}>Порядок</Table.Th>
|
<Table.Td>
|
||||||
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
|
<Badge
|
||||||
</Table.Tr>
|
size="xs"
|
||||||
</Table.Thead>
|
color={SCOPE_COLORS[scopeType as keyof typeof SCOPE_COLORS]}
|
||||||
<Table.Tbody>
|
variant="light"
|
||||||
{data?.data?.length === 0 ? (
|
>
|
||||||
<Table.Tr>
|
{SCOPE_LABELS[scopeType as keyof typeof SCOPE_LABELS]}
|
||||||
<Table.Td colSpan={9}>
|
</Badge>
|
||||||
<Center p={40}>
|
</Table.Td>
|
||||||
<Text c="dimmed">Связи не найдены</Text>
|
<Table.Td>
|
||||||
</Center>
|
<Text size="sm" lineClamp={1}>{scopeObjectName}</Text>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Badge variant="light" color="gray">
|
||||||
|
#{h.priority}
|
||||||
|
</Badge>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Group gap="xs">
|
||||||
|
<Tooltip label="Редактировать">
|
||||||
|
<ActionIcon
|
||||||
|
variant="light"
|
||||||
|
color="blue"
|
||||||
|
onClick={() => setEditHierarchy(h)}
|
||||||
|
>
|
||||||
|
<IconPencil size={16} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip label="Удалить">
|
||||||
|
<ActionIcon
|
||||||
|
variant="light"
|
||||||
|
color="red"
|
||||||
|
onClick={() => handleDelete(h.id!)}
|
||||||
|
>
|
||||||
|
<IconTrash size={16} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
</Group>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
</Table.Tr>
|
</Table.Tr>
|
||||||
) : (
|
)
|
||||||
data?.data?.map((h) => {
|
})}
|
||||||
const scopeType = h.topic_id
|
</Table.Tbody>
|
||||||
? 'topic'
|
</Table>
|
||||||
: h.topic_category_id
|
</Paper>
|
||||||
? 'category'
|
)}
|
||||||
: 'global'
|
|
||||||
let scopeObjectName = 'Все темы'
|
|
||||||
if (scopeType === 'category' && h.topic_category_id) {
|
|
||||||
const cat = categories?.data?.find(
|
|
||||||
(c) => c.id === h.topic_category_id
|
|
||||||
)
|
|
||||||
scopeObjectName = cat?.name || `#${h.topic_category_id}`
|
|
||||||
} else if (scopeType === 'topic' && h.topic_id) {
|
|
||||||
const topic = topics?.data?.find(
|
|
||||||
(t) => t.id === h.topic_id
|
|
||||||
)
|
|
||||||
scopeObjectName = topic?.name || `#${h.topic_id}`
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Table.Tr
|
|
||||||
key={h.id}
|
|
||||||
style={{
|
|
||||||
backgroundColor: selectedIds.includes(h.id!)
|
|
||||||
? 'var(--mantine-color-blue-0)'
|
|
||||||
: undefined,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Table.Td>
|
|
||||||
<Checkbox
|
|
||||||
checked={selectedIds.includes(h.id!)}
|
|
||||||
onChange={() => handleSelectOne(h.id!)}
|
|
||||||
/>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>{h.id}</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" fw={500}>
|
|
||||||
{h.subordinate?.full_name || '—'}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" fw={500}>
|
|
||||||
{h.approver?.full_name || '—'}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm">
|
|
||||||
{h.department?.name || '—'}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Badge
|
|
||||||
size="xs"
|
|
||||||
color={
|
|
||||||
SCOPE_COLORS[
|
|
||||||
scopeType as keyof typeof SCOPE_COLORS
|
|
||||||
]
|
|
||||||
}
|
|
||||||
variant="light"
|
|
||||||
>
|
|
||||||
{
|
|
||||||
SCOPE_LABELS[
|
|
||||||
scopeType as keyof typeof SCOPE_LABELS
|
|
||||||
]
|
|
||||||
}
|
|
||||||
</Badge>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" lineClamp={1}>
|
|
||||||
{scopeObjectName}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Badge variant="light" color="gray">
|
|
||||||
#{h.priority}
|
|
||||||
</Badge>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Group gap="xs">
|
|
||||||
<Tooltip label="Редактировать">
|
|
||||||
<ActionIcon
|
|
||||||
variant="light"
|
|
||||||
color="blue"
|
|
||||||
onClick={() => setEditHierarchy(h)}
|
|
||||||
>
|
|
||||||
<IconPencil size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip label="Удалить">
|
|
||||||
<ActionIcon
|
|
||||||
variant="light"
|
|
||||||
color="red"
|
|
||||||
onClick={() => handleDelete(h.id!)}
|
|
||||||
>
|
|
||||||
<IconTrash size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
</Group>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
)
|
|
||||||
})
|
|
||||||
)}
|
|
||||||
</Table.Tbody>
|
|
||||||
</Table>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{totalPages > 1 && (
|
|
||||||
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">
|
|
||||||
Страница {page} из {totalPages}
|
|
||||||
</Text>
|
|
||||||
<Pagination
|
|
||||||
value={page}
|
|
||||||
onChange={(newPage) => {
|
|
||||||
setPage(newPage)
|
|
||||||
setSelectedIds([])
|
|
||||||
}}
|
|
||||||
total={totalPages}
|
|
||||||
withEdges
|
|
||||||
/>
|
|
||||||
</Group>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{isFetching && !isLoading && (
|
{isFetching && !isLoading && (
|
||||||
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
|
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
|
||||||
|
|
@ -688,7 +321,7 @@ export default function HierarchiesPage() {
|
||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Модалки */}
|
{/* Модальные окна */}
|
||||||
<HierarchyEditModal
|
<HierarchyEditModal
|
||||||
hierarchy={editHierarchy}
|
hierarchy={editHierarchy}
|
||||||
opened={editHierarchy !== null}
|
opened={editHierarchy !== null}
|
||||||
|
|
@ -701,17 +334,6 @@ export default function HierarchiesPage() {
|
||||||
opened={createModalOpened}
|
opened={createModalOpened}
|
||||||
onClose={handleCloseModal}
|
onClose={handleCloseModal}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ChainDuplicateModal
|
|
||||||
group={duplicateGroup}
|
|
||||||
opened={duplicateModalOpened}
|
|
||||||
onClose={handleCloseDuplicateModal}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<PersonDuplicateModal
|
|
||||||
opened={personDuplicateOpened}
|
|
||||||
onClose={() => setPersonDuplicateOpened(false)}
|
|
||||||
/>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -1,527 +0,0 @@
|
||||||
import { useEffect } from 'react'
|
|
||||||
import {
|
|
||||||
Modal,
|
|
||||||
Stack,
|
|
||||||
Select,
|
|
||||||
Group,
|
|
||||||
Button,
|
|
||||||
Text,
|
|
||||||
Paper,
|
|
||||||
Divider,
|
|
||||||
ActionIcon,
|
|
||||||
Badge,
|
|
||||||
Avatar,
|
|
||||||
Box,
|
|
||||||
Radio,
|
|
||||||
Alert,
|
|
||||||
} from '@mantine/core'
|
|
||||||
import { useForm } from '@mantine/form'
|
|
||||||
import {
|
|
||||||
IconInfoCircle,
|
|
||||||
IconPlus,
|
|
||||||
IconTrash,
|
|
||||||
IconCopy,
|
|
||||||
IconChevronRight,
|
|
||||||
} from '@tabler/icons-react'
|
|
||||||
import { notifications } from '@mantine/notifications'
|
|
||||||
import { useCreateHierarchy } from '@/features/hierarchies/hooks/useHierarchies'
|
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
|
||||||
import { useDepartments } from '@/features/departments/hooks/useDepartments'
|
|
||||||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
|
||||||
import { useTopics } from '@/features/topics/hooks/useTopics'
|
|
||||||
import { useAllSystemOptions } from '@/features/hierarchies/hooks/useSystemOptions' // 👈 ИМПОРТИРОВАЛИ ХУК
|
|
||||||
import type { ChainGroup } from '@/features/hierarchies/utils'
|
|
||||||
|
|
||||||
interface ChainDuplicateModalProps {
|
|
||||||
group: ChainGroup | null
|
|
||||||
opened: boolean
|
|
||||||
onClose: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
type ScopeType = 'global' | 'category' | 'topic'
|
|
||||||
|
|
||||||
interface StepForm {
|
|
||||||
approver_id: number | null
|
|
||||||
priority: number
|
|
||||||
target_system: string | null // 👈 ДОБАВИЛИ ПОЛЕ В ИНТЕРФЕЙС
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ChainDuplicateModal({
|
|
||||||
group,
|
|
||||||
opened,
|
|
||||||
onClose,
|
|
||||||
}: ChainDuplicateModalProps) {
|
|
||||||
const createHierarchy = useCreateHierarchy()
|
|
||||||
const { data: users } = useUsers({ limit: 1000 })
|
|
||||||
const { data: departments } = useDepartments()
|
|
||||||
const { data: categories } = useCategories({ limit: 1000 })
|
|
||||||
|
|
||||||
// Подтягиваем доступные системы
|
|
||||||
const { options: systemOptions } = useAllSystemOptions()
|
|
||||||
|
|
||||||
const { data: allTopics } = useTopics({ limit: 1000 })
|
|
||||||
|
|
||||||
const form = useForm({
|
|
||||||
initialValues: {
|
|
||||||
subordinate_id: null as number | null,
|
|
||||||
department_id: null as number | null,
|
|
||||||
scope_type: 'global' as ScopeType,
|
|
||||||
topic_category_id: null as number | null,
|
|
||||||
topic_id: null as number | null,
|
|
||||||
steps: [] as StepForm[],
|
|
||||||
},
|
|
||||||
validate: {
|
|
||||||
subordinate_id: (v) => (v === null ? 'Выберите инициатора' : null),
|
|
||||||
department_id: (v) => (v === null ? 'Выберите отдел' : null),
|
|
||||||
topic_category_id: (v, values) => {
|
|
||||||
if (
|
|
||||||
(values.scope_type === 'category' || values.scope_type === 'topic') &&
|
|
||||||
v === null
|
|
||||||
) {
|
|
||||||
return 'Выберите категорию'
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
},
|
|
||||||
topic_id: (v, values) => {
|
|
||||||
if (values.scope_type === 'topic' && v === null) {
|
|
||||||
return 'Выберите тему'
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
},
|
|
||||||
steps: {
|
|
||||||
approver_id: (v) => (v === null ? 'Выберите согласующего' : null),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const { data: categoryTopics } = useTopics({
|
|
||||||
limit: 1000,
|
|
||||||
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
|
|
||||||
})
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (group && opened) {
|
|
||||||
let resolvedCategoryId: number | null = null
|
|
||||||
if (group.scopeType === 'category') {
|
|
||||||
resolvedCategoryId = group.scopeObjectId
|
|
||||||
} else if (group.scopeType === 'topic') {
|
|
||||||
const matchedTopic = allTopics?.data?.find((t) => t.id === group.scopeObjectId)
|
|
||||||
resolvedCategoryId = matchedTopic?.category_id || null
|
|
||||||
}
|
|
||||||
|
|
||||||
form.setValues({
|
|
||||||
subordinate_id: group.subordinateId,
|
|
||||||
department_id: group.departmentId,
|
|
||||||
scope_type: group.scopeType,
|
|
||||||
topic_category_id: resolvedCategoryId,
|
|
||||||
topic_id: group.scopeType === 'topic' ? group.scopeObjectId : null,
|
|
||||||
steps: group.steps.map((s, idx) => ({
|
|
||||||
approver_id: s.approver_id || null,
|
|
||||||
priority: idx,
|
|
||||||
target_system: s.target_system || null, // 👈 ИНИЦИАЛИЗИРУЕМ ИЗ БД
|
|
||||||
})),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [group, opened, allTopics])
|
|
||||||
|
|
||||||
const handleScopeTypeChange = (value: ScopeType) => {
|
|
||||||
form.setFieldValue('scope_type', value)
|
|
||||||
if (value === 'global') {
|
|
||||||
form.setFieldValue('topic_category_id', null)
|
|
||||||
form.setFieldValue('topic_id', null)
|
|
||||||
} else if (value === 'category') {
|
|
||||||
form.setFieldValue('topic_id', null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const addStep = () => {
|
|
||||||
form.insertListItem('steps', {
|
|
||||||
approver_id: null,
|
|
||||||
priority: form.values.steps.length,
|
|
||||||
target_system: null, // 👈 ИНИЦИАЛИЗИРУЕМ ДЛЯ НОВОГО ШАГА
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const removeStep = (index: number) => {
|
|
||||||
form.removeListItem('steps', index)
|
|
||||||
form.values.steps.forEach((_, idx) => {
|
|
||||||
form.setFieldValue(`steps.${idx}.priority`, idx)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const userOptions =
|
|
||||||
users?.data?.map((u) => ({
|
|
||||||
value: String(u.id),
|
|
||||||
label: u.full_name || `Пользователь #${u.id}`,
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const departmentOptions =
|
|
||||||
departments?.data?.map((d) => ({
|
|
||||||
value: String(d.id),
|
|
||||||
label: d.name || '',
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const categoryOptions =
|
|
||||||
categories?.data?.map((c) => ({
|
|
||||||
value: String(c.id),
|
|
||||||
label: c.name || '',
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const topicOptions =
|
|
||||||
categoryTopics?.data?.map((t) => ({
|
|
||||||
value: String(t.id),
|
|
||||||
label: t.name || '',
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const handleSubmit = async (values: typeof form.values) => {
|
|
||||||
if (values.steps.length === 0) {
|
|
||||||
notifications.show({
|
|
||||||
title: 'Ошибка',
|
|
||||||
message: 'Добавьте хотя бы один шаг согласования',
|
|
||||||
color: 'red',
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
for (const step of values.steps) {
|
|
||||||
await createHierarchy.mutateAsync({
|
|
||||||
subordinate_id: values.subordinate_id!,
|
|
||||||
approver_id: step.approver_id!,
|
|
||||||
department_id: values.department_id!,
|
|
||||||
priority: step.priority,
|
|
||||||
target_system: step.target_system || null, // 👈 ОТПРАВЛЯЕМ СИСТЕМУ
|
|
||||||
topic_category_id:
|
|
||||||
values.scope_type === 'global'
|
|
||||||
? null
|
|
||||||
: values.scope_type === 'category'
|
|
||||||
? values.topic_category_id
|
|
||||||
: null,
|
|
||||||
topic_id: values.scope_type === 'topic' ? values.topic_id : null,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
notifications.show({
|
|
||||||
title: 'Успешно',
|
|
||||||
message: `Цепочка дублирована (${values.steps.length} шагов)`,
|
|
||||||
color: 'green',
|
|
||||||
})
|
|
||||||
onClose()
|
|
||||||
} catch (error) {
|
|
||||||
notifications.show({
|
|
||||||
title: 'Ошибка',
|
|
||||||
message: 'Не удалось дублировать цепочку',
|
|
||||||
color: 'red',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const isSubmitting = createHierarchy.isPending
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal
|
|
||||||
opened={opened}
|
|
||||||
onClose={onClose}
|
|
||||||
title={
|
|
||||||
<Group gap="xs">
|
|
||||||
<IconCopy size={20} />
|
|
||||||
<Text fw={600}>Дублирование цепочки</Text>
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
size="lg"
|
|
||||||
centered
|
|
||||||
>
|
|
||||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
|
||||||
<Stack gap="md">
|
|
||||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
|
||||||
<Text size="sm">
|
|
||||||
Создайте новую цепочку на основе существующей. Вы можете изменить
|
|
||||||
инициатора, отдел, область действия и согласующих.
|
|
||||||
</Text>
|
|
||||||
</Alert>
|
|
||||||
|
|
||||||
{/* Общие параметры */}
|
|
||||||
<Paper withBorder p="md">
|
|
||||||
<Text size="sm" fw={600} mb="sm" c="dark">
|
|
||||||
Общие параметры
|
|
||||||
</Text>
|
|
||||||
<Stack gap="sm">
|
|
||||||
<Select
|
|
||||||
label="Инициатор"
|
|
||||||
placeholder="Выберите пользователя"
|
|
||||||
data={userOptions}
|
|
||||||
value={
|
|
||||||
form.values.subordinate_id
|
|
||||||
? String(form.values.subordinate_id)
|
|
||||||
: null
|
|
||||||
}
|
|
||||||
onChange={(v) =>
|
|
||||||
form.setFieldValue(
|
|
||||||
'subordinate_id',
|
|
||||||
v ? Number(v) : null
|
|
||||||
)
|
|
||||||
}
|
|
||||||
searchable
|
|
||||||
required
|
|
||||||
error={form.errors.subordinate_id}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Отдел"
|
|
||||||
placeholder="Выберите отдел"
|
|
||||||
data={departmentOptions}
|
|
||||||
value={
|
|
||||||
form.values.department_id
|
|
||||||
? String(form.values.department_id)
|
|
||||||
: null
|
|
||||||
}
|
|
||||||
onChange={(v) =>
|
|
||||||
form.setFieldValue(
|
|
||||||
'department_id',
|
|
||||||
v ? Number(v) : null
|
|
||||||
)
|
|
||||||
}
|
|
||||||
searchable
|
|
||||||
required
|
|
||||||
error={form.errors.department_id}
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{/* Область действия */}
|
|
||||||
<Paper withBorder p="md">
|
|
||||||
<Text size="sm" fw={600} mb="sm" c="dark">
|
|
||||||
Область действия
|
|
||||||
</Text>
|
|
||||||
<Stack gap="sm">
|
|
||||||
<Radio.Group
|
|
||||||
value={form.values.scope_type}
|
|
||||||
onChange={(v) => handleScopeTypeChange(v as ScopeType)}
|
|
||||||
>
|
|
||||||
<Stack gap="xs">
|
|
||||||
<Radio
|
|
||||||
value="global"
|
|
||||||
label="Глобальное правило"
|
|
||||||
description="Для всех тем согласований"
|
|
||||||
/>
|
|
||||||
<Radio
|
|
||||||
value="category"
|
|
||||||
label="Для категории тем"
|
|
||||||
description="Только для тем выбранной категории"
|
|
||||||
/>
|
|
||||||
<Radio
|
|
||||||
value="topic"
|
|
||||||
label="Для конкретной темы"
|
|
||||||
description="Только для выбранной темы"
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
</Radio.Group>
|
|
||||||
|
|
||||||
{(form.values.scope_type === 'category' ||
|
|
||||||
form.values.scope_type === 'topic') && (
|
|
||||||
<Select
|
|
||||||
label="Категория"
|
|
||||||
placeholder="Выберите категорию"
|
|
||||||
data={categoryOptions}
|
|
||||||
value={
|
|
||||||
form.values.topic_category_id
|
|
||||||
? String(form.values.topic_category_id)
|
|
||||||
: null
|
|
||||||
}
|
|
||||||
onChange={(v) => {
|
|
||||||
form.setFieldValue(
|
|
||||||
'topic_category_id',
|
|
||||||
v ? Number(v) : null
|
|
||||||
)
|
|
||||||
form.setFieldValue('topic_id', null)
|
|
||||||
}}
|
|
||||||
searchable
|
|
||||||
required
|
|
||||||
error={form.errors.topic_category_id}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{form.values.scope_type === 'topic' && (
|
|
||||||
<Select
|
|
||||||
label="Тема"
|
|
||||||
placeholder="Выберите тему"
|
|
||||||
data={topicOptions}
|
|
||||||
value={
|
|
||||||
form.values.topic_id
|
|
||||||
? String(form.values.topic_id)
|
|
||||||
: null
|
|
||||||
}
|
|
||||||
onChange={(v) =>
|
|
||||||
form.setFieldValue('topic_id', v ? Number(v) : null)
|
|
||||||
}
|
|
||||||
searchable
|
|
||||||
required
|
|
||||||
disabled={!form.values.topic_category_id}
|
|
||||||
error={form.errors.topic_id}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{/* Шаги согласования */}
|
|
||||||
<Paper withBorder p="md">
|
|
||||||
<Group justify="space-between" mb="sm">
|
|
||||||
<Text size="sm" fw={600} c="dark">
|
|
||||||
Шаги согласования
|
|
||||||
</Text>
|
|
||||||
<Button
|
|
||||||
variant="subtle"
|
|
||||||
size="xs"
|
|
||||||
leftSection={<IconPlus size={14} />}
|
|
||||||
onClick={addStep}
|
|
||||||
>
|
|
||||||
Добавить шаг
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Stack gap="sm">
|
|
||||||
{form.values.steps.length === 0 ? (
|
|
||||||
<Box py="md">
|
|
||||||
<Text size="sm" c="dimmed" ta="center">
|
|
||||||
Нет шагов согласования. Добавьте хотя бы один.
|
|
||||||
</Text>
|
|
||||||
</Box>
|
|
||||||
) : (
|
|
||||||
form.values.steps.map((step, index) => (
|
|
||||||
<Paper
|
|
||||||
key={index}
|
|
||||||
withBorder
|
|
||||||
p="sm"
|
|
||||||
style={{
|
|
||||||
borderColor: 'var(--mantine-color-gray-3)',
|
|
||||||
backgroundColor: 'var(--mantine-color-gray-0)',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Group gap="sm" align="flex-start">
|
|
||||||
<Avatar
|
|
||||||
size="sm"
|
|
||||||
radius="xl"
|
|
||||||
color="blue"
|
|
||||||
variant="filled"
|
|
||||||
mt={4}
|
|
||||||
>
|
|
||||||
{index + 1}
|
|
||||||
</Avatar>
|
|
||||||
|
|
||||||
<Stack gap="xs" style={{ flex: 1 }}>
|
|
||||||
<Group gap="xs">
|
|
||||||
<Badge
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color="gray"
|
|
||||||
tt="none"
|
|
||||||
>
|
|
||||||
Шаг {index + 1}
|
|
||||||
</Badge>
|
|
||||||
<Badge
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color="gray"
|
|
||||||
tt="none"
|
|
||||||
>
|
|
||||||
Priority: {step.priority}
|
|
||||||
</Badge>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Group grow gap="xs">
|
|
||||||
<Select
|
|
||||||
placeholder="Выберите согласующего"
|
|
||||||
data={userOptions}
|
|
||||||
value={step.approver_id ? String(step.approver_id) : null}
|
|
||||||
onChange={(v) =>
|
|
||||||
form.setFieldValue(`steps.${index}.approver_id`, v ? Number(v) : null)
|
|
||||||
}
|
|
||||||
searchable
|
|
||||||
error={
|
|
||||||
Array.isArray(form.errors.steps) && form.errors.steps[index]
|
|
||||||
? (form.errors.steps[index] as any)?.approver_id
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* 👈 ДОБАВЛЕННЫЙ ВЫБОР СИСТЕМЫ */}
|
|
||||||
<Select
|
|
||||||
placeholder="Система: Все (по умолчанию)"
|
|
||||||
data={[
|
|
||||||
{ value: 'all', label: 'Система: Все' },
|
|
||||||
...systemOptions.map((s) => ({ value: s.value, label: `Система: ${s.label}` })),
|
|
||||||
]}
|
|
||||||
value={step.target_system || 'all'}
|
|
||||||
onChange={(v) =>
|
|
||||||
form.setFieldValue(
|
|
||||||
`steps.${index}.target_system`,
|
|
||||||
(v === 'all' || !v) ? null : v
|
|
||||||
)
|
|
||||||
}
|
|
||||||
clearable
|
|
||||||
/>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<ActionIcon
|
|
||||||
variant="subtle"
|
|
||||||
color="red"
|
|
||||||
size="md"
|
|
||||||
mt={4}
|
|
||||||
onClick={() => removeStep(index)}
|
|
||||||
>
|
|
||||||
<IconTrash size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Group>
|
|
||||||
</Paper>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{/* Предпросмотр */}
|
|
||||||
{form.values.steps.length > 0 && (
|
|
||||||
<Paper withBorder p="md" bg="gray.0">
|
|
||||||
<Text size="xs" fw={600} c="dimmed" mb="xs" tt="uppercase">
|
|
||||||
Предпросмотр цепочки
|
|
||||||
</Text>
|
|
||||||
<Group gap="xs" wrap="nowrap" style={{ overflowX: 'auto' }}>
|
|
||||||
<Badge variant="light" color="gray" tt="none">
|
|
||||||
{users?.data?.find(
|
|
||||||
(u) => u.id === form.values.subordinate_id
|
|
||||||
)?.full_name || 'Инициатор'}
|
|
||||||
</Badge>
|
|
||||||
{form.values.steps.map((step, index) => (
|
|
||||||
<Group key={index} gap={4} wrap="nowrap">
|
|
||||||
<IconChevronRight
|
|
||||||
size={14}
|
|
||||||
color="var(--mantine-color-gray-5)"
|
|
||||||
/>
|
|
||||||
<Badge variant="light" color="blue" tt="none">
|
|
||||||
{users?.data?.find(
|
|
||||||
(u) => u.id === step.approver_id
|
|
||||||
)?.full_name || `Шаг ${index + 1}`}
|
|
||||||
{step.target_system && ` (${step.target_system})`}
|
|
||||||
</Badge>
|
|
||||||
</Group>
|
|
||||||
))}
|
|
||||||
</Group>
|
|
||||||
</Paper>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Divider />
|
|
||||||
|
|
||||||
<Group justify="flex-end" gap="sm">
|
|
||||||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
|
||||||
Отмена
|
|
||||||
</Button>
|
|
||||||
<Button type="submit" loading={isSubmitting}>
|
|
||||||
Дублировать цепочку
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</form>
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,5 +1,3 @@
|
||||||
// ChainVisualization.tsx
|
|
||||||
import {useMemo, useState} from 'react'
|
|
||||||
import {
|
import {
|
||||||
Paper,
|
Paper,
|
||||||
Group,
|
Group,
|
||||||
|
|
@ -9,220 +7,92 @@ import {
|
||||||
ActionIcon,
|
ActionIcon,
|
||||||
Avatar,
|
Avatar,
|
||||||
Box,
|
Box,
|
||||||
Divider,
|
ThemeIcon,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
Select,
|
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import {
|
import {
|
||||||
IconChevronRight,
|
IconArrowRight,
|
||||||
IconPencil,
|
IconPencil,
|
||||||
IconTrash,
|
IconTrash,
|
||||||
|
IconUser,
|
||||||
IconWorld,
|
IconWorld,
|
||||||
IconCategory,
|
IconCategory,
|
||||||
IconFileText,
|
IconFileText,
|
||||||
IconCopy,
|
|
||||||
IconPlus,
|
|
||||||
IconServer,
|
|
||||||
} from '@tabler/icons-react'
|
} from '@tabler/icons-react'
|
||||||
import type { ChainGroup } from '@/features/hierarchies/utils'
|
import type { ChainGroup } from '@/features/hierarchies/utils'
|
||||||
import { SCOPE_COLORS, SCOPE_LABELS } from '@/features/hierarchies/utils'
|
import { SCOPE_COLORS, SCOPE_LABELS } from '@/features/hierarchies/utils'
|
||||||
import {
|
|
||||||
useCategorySystemOptions,
|
|
||||||
ALL_SYSTEMS_VALUE,
|
|
||||||
useAllSystemOptions
|
|
||||||
} from '@/features/hierarchies/hooks/useSystemOptions'
|
|
||||||
import {useTopics} from "@/features/topics/hooks/useTopics.ts";
|
|
||||||
|
|
||||||
interface ChainVisualizationProps {
|
interface ChainVisualizationProps {
|
||||||
group: ChainGroup
|
group: ChainGroup
|
||||||
onEditStep: (hierarchyId: number) => void
|
onEditStep: (hierarchyId: number) => void
|
||||||
onDeleteStep: (hierarchyId: number) => void
|
onDeleteStep: (hierarchyId: number) => void
|
||||||
onDeleteChain: (group: ChainGroup) => void // <-- ДОБАВЛЕНО
|
|
||||||
onAddStep: (group: ChainGroup) => void
|
onAddStep: (group: ChainGroup) => void
|
||||||
onDuplicateChain: (group: ChainGroup) => void
|
|
||||||
onBulkUpdateSystem?: (group: ChainGroup, targetSystem: string | null) => void
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const ScopeIcon = ({ type }: { type: string }) => {
|
const ScopeIcon = ({ type }: { type: string }) => {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case 'global':
|
case 'global': return <IconWorld size={14} />
|
||||||
return <IconWorld size={13} />
|
case 'category': return <IconCategory size={14} />
|
||||||
case 'category':
|
case 'topic': return <IconFileText size={14} />
|
||||||
return <IconCategory size={13} />
|
default: return <IconWorld size={14} />
|
||||||
case 'topic':
|
|
||||||
return <IconFileText size={13} />
|
|
||||||
default:
|
|
||||||
return <IconWorld size={13} />
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Внутри компонента ChainVisualization:
|
|
||||||
export default function ChainVisualization({
|
export default function ChainVisualization({
|
||||||
group,
|
group,
|
||||||
onEditStep,
|
onEditStep,
|
||||||
onDeleteStep,
|
onDeleteStep,
|
||||||
onDeleteChain,
|
|
||||||
onAddStep,
|
onAddStep,
|
||||||
onDuplicateChain,
|
|
||||||
onBulkUpdateSystem,
|
|
||||||
}: ChainVisualizationProps) {
|
}: ChainVisualizationProps) {
|
||||||
// Получаем все темы, чтобы уметь мапить topicId -> categoryId, если scopeType === 'topic'
|
|
||||||
const { data: allTopics } = useTopics({ limit: 1000 })
|
|
||||||
|
|
||||||
const resolvedCategoryId = useMemo(() => {
|
|
||||||
if (group.scopeType === 'category') {
|
|
||||||
return group.scopeObjectId
|
|
||||||
}
|
|
||||||
if (group.scopeType === 'topic' && group.scopeObjectId && allTopics?.data) {
|
|
||||||
const foundTopic = allTopics.data.find(t => t.id === group.scopeObjectId)
|
|
||||||
return foundTopic?.category_id || null
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}, [group.scopeType, group.scopeObjectId, allTopics?.data])
|
|
||||||
|
|
||||||
// Если цепочка глобальная (resolvedCategoryId === null), берем вообще все системы через useAllSystemOptions,
|
|
||||||
// иначе — системы конкретной категории через useCategorySystemOptions.
|
|
||||||
const categoryOptionsResult = useCategorySystemOptions(resolvedCategoryId)
|
|
||||||
const allOptionsResult = useAllSystemOptions(group.scopeType === 'global')
|
|
||||||
|
|
||||||
const systemOptions = group.scopeType === 'global' ? allOptionsResult.options : categoryOptionsResult.options
|
|
||||||
|
|
||||||
console.log(`[ChainVisualization] Группа ${group.key} (scope: ${group.scopeType}): resolvedCategoryId = ${resolvedCategoryId}, доступно систем:`, systemOptions)
|
|
||||||
|
|
||||||
// Текущая система цепочки (если у всех шагов одинаковая система, иначе 'all')
|
|
||||||
const currentChainSystem = group.steps.every(
|
|
||||||
(s) => s.target_system === group.steps[0]?.target_system
|
|
||||||
)
|
|
||||||
? group.steps[0]?.target_system || ALL_SYSTEMS_VALUE
|
|
||||||
: ALL_SYSTEMS_VALUE
|
|
||||||
|
|
||||||
// Формируем опции для Select
|
|
||||||
const selectData = [
|
|
||||||
{ value: ALL_SYSTEMS_VALUE, label: 'Система: Все' },
|
|
||||||
...systemOptions.map((opt) => ({
|
|
||||||
value: opt.value,
|
|
||||||
label: `Система: ${opt.label}`,
|
|
||||||
})),
|
|
||||||
]
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Paper
|
<Paper withBorder p="md" mb="md">
|
||||||
withBorder
|
|
||||||
p="lg"
|
|
||||||
style={{
|
|
||||||
backgroundColor: 'var(--mantine-color-white)',
|
|
||||||
borderColor: 'var(--mantine-color-gray-3)',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{/* Заголовок группы */}
|
{/* Заголовок группы */}
|
||||||
<Group justify="space-between" mb="lg">
|
<Group justify="space-between" mb="md">
|
||||||
<Group gap="md">
|
<Group gap="md">
|
||||||
<Avatar size="md" radius="xl" color="gray" variant="filled">
|
<Avatar size="sm" radius="xl" color="blue">
|
||||||
{group.subordinateName.charAt(0).toUpperCase()}
|
{group.subordinateName.charAt(0)}
|
||||||
</Avatar>
|
</Avatar>
|
||||||
|
|
||||||
<Stack gap={0}>
|
<Stack gap={0}>
|
||||||
<Text fw={600} size="sm" c="dark">
|
<Text fw={600} size="sm">{group.subordinateName}</Text>
|
||||||
{group.subordinateName}
|
<Text size="xs" c="dimmed">{group.departmentName}</Text>
|
||||||
</Text>
|
|
||||||
<Text size="xs" c="dimmed">
|
|
||||||
{group.departmentName}
|
|
||||||
</Text>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
<Divider orientation="vertical" />
|
|
||||||
|
|
||||||
<Badge
|
<Badge
|
||||||
variant="outline"
|
variant="light"
|
||||||
color={SCOPE_COLORS[group.scopeType]}
|
color={SCOPE_COLORS[group.scopeType]}
|
||||||
leftSection={<ScopeIcon type={group.scopeType} />}
|
leftSection={<ScopeIcon type={group.scopeType} />}
|
||||||
size="sm"
|
|
||||||
tt="none"
|
|
||||||
>
|
>
|
||||||
{SCOPE_LABELS[group.scopeType]}: {group.scopeObjectName}
|
{SCOPE_LABELS[group.scopeType]}: {group.scopeObjectName}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
|
||||||
{/* Выпадающий список систем отображается ТОЛЬКО если у темы/категории есть заданные systems */}
|
|
||||||
{systemOptions.length > 0 && (
|
|
||||||
<Select
|
|
||||||
size="xs"
|
|
||||||
leftSection={<IconServer size={14} />}
|
|
||||||
data={selectData}
|
|
||||||
value={currentChainSystem}
|
|
||||||
onChange={(val) => {
|
|
||||||
const newSystem = val === ALL_SYSTEMS_VALUE ? "" : val
|
|
||||||
if (onBulkUpdateSystem) {
|
|
||||||
onBulkUpdateSystem(group, newSystem)
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
style={{ width: 180 }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<Group gap="xs">
|
<Tooltip label="Добавить шаг">
|
||||||
<Tooltip label="Добавить шаг" withArrow>
|
<ActionIcon
|
||||||
<ActionIcon
|
variant="light"
|
||||||
variant="subtle"
|
color="green"
|
||||||
color="gray"
|
onClick={() => onAddStep(group)}
|
||||||
size="md"
|
>
|
||||||
onClick={() => onAddStep(group)}
|
<IconUser size={16} />
|
||||||
>
|
</ActionIcon>
|
||||||
<IconPlus size={18} />
|
</Tooltip>
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip label="Дублировать цепочку" withArrow>
|
|
||||||
<ActionIcon
|
|
||||||
variant="subtle"
|
|
||||||
color="gray"
|
|
||||||
size="md"
|
|
||||||
onClick={() => onDuplicateChain(group)}
|
|
||||||
>
|
|
||||||
<IconCopy size={18} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip label="Удалить всю цепочку" withArrow>
|
|
||||||
<ActionIcon
|
|
||||||
variant="subtle"
|
|
||||||
color="red"
|
|
||||||
size="md"
|
|
||||||
onClick={() => onDeleteChain(group)}
|
|
||||||
>
|
|
||||||
<IconTrash size={18} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
</Group>
|
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<Divider mb="lg" />
|
|
||||||
|
|
||||||
{/* Цепочка согласования */}
|
|
||||||
<Box style={{ overflowX: 'auto' }}>
|
<Box style={{ overflowX: 'auto' }}>
|
||||||
<Group gap={0} wrap="nowrap" align="stretch">
|
<Group gap="xs" wrap="nowrap" align="center">
|
||||||
{/* Карточка инициатора */}
|
|
||||||
<Paper
|
<Paper
|
||||||
withBorder
|
withBorder
|
||||||
p="md"
|
p="sm"
|
||||||
style={{
|
style={{
|
||||||
minWidth: 180,
|
minWidth: 140,
|
||||||
borderColor: 'var(--mantine-color-gray-3)',
|
|
||||||
backgroundColor: 'var(--mantine-color-gray-0)',
|
backgroundColor: 'var(--mantine-color-gray-0)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Stack gap="xs" align="center">
|
<Stack gap={4} align="center">
|
||||||
<Text
|
<Text size="xs" c="dimmed" fw={600}>ИНИЦИАТОР</Text>
|
||||||
size="xs"
|
<Avatar size="md" radius="xl" color="gray">
|
||||||
fw={600}
|
{group.subordinateName.charAt(0)}
|
||||||
c="dimmed"
|
|
||||||
tt="uppercase"
|
|
||||||
style={{ letterSpacing: '0.5px' }}
|
|
||||||
>
|
|
||||||
Инициатор
|
|
||||||
</Text>
|
|
||||||
<Avatar size="md" radius="xl" color="gray" variant="filled">
|
|
||||||
{group.subordinateName.charAt(0).toUpperCase()}
|
|
||||||
</Avatar>
|
</Avatar>
|
||||||
<Text size="sm" fw={500} ta="center" lineClamp={2} c="dark">
|
<Text size="xs" fw={500} ta="center" lineClamp={2}>
|
||||||
{group.subordinateName}
|
{group.subordinateName}
|
||||||
</Text>
|
</Text>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
@ -230,98 +100,65 @@ export default function ChainVisualization({
|
||||||
|
|
||||||
{/* Шаги согласования */}
|
{/* Шаги согласования */}
|
||||||
{group.steps.map((step, index) => (
|
{group.steps.map((step, index) => (
|
||||||
<Group key={step.id} gap={0} wrap="nowrap" align="stretch">
|
<Group key={step.id} gap="xs" wrap="nowrap" align="center">
|
||||||
<Stack
|
{/* Стрелка */}
|
||||||
gap={2}
|
<IconArrowRight size={20} color="var(--mantine-color-gray-5)" />
|
||||||
align="center"
|
|
||||||
justify="center"
|
|
||||||
px="xs"
|
|
||||||
style={{ minWidth: 60 }}
|
|
||||||
>
|
|
||||||
<IconChevronRight size={20} color="var(--mantine-color-gray-5)" />
|
|
||||||
<Badge size="xs" variant="light" color="gray" tt="none">
|
|
||||||
{index + 1}
|
|
||||||
</Badge>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
{/* Карточка согласующего */}
|
{/* Карточка согласующего */}
|
||||||
<Paper
|
<Paper
|
||||||
withBorder
|
withBorder
|
||||||
p="md"
|
p="sm"
|
||||||
style={{
|
style={{
|
||||||
minWidth: 180,
|
minWidth: 140,
|
||||||
borderColor: 'var(--mantine-color-gray-3)',
|
|
||||||
backgroundColor: 'var(--mantine-color-white)',
|
|
||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
transition: 'border-color 0.15s ease',
|
transition: 'all 0.2s',
|
||||||
position: 'relative',
|
borderColor: 'var(--mantine-color-blue-4)',
|
||||||
}}
|
}}
|
||||||
onClick={() => onEditStep(step.id!)}
|
onClick={() => onEditStep(step.id!)}
|
||||||
onMouseEnter={(e) => {
|
className="hover-shadow"
|
||||||
e.currentTarget.style.borderColor = 'var(--mantine-color-blue-5)'
|
|
||||||
}}
|
|
||||||
onMouseLeave={(e) => {
|
|
||||||
e.currentTarget.style.borderColor = 'var(--mantine-color-gray-3)'
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Stack gap="xs" align="center">
|
<Stack gap={4} align="center">
|
||||||
<Group gap={6}>
|
<Group gap={4}>
|
||||||
<Text
|
<Text size="xs" c="dimmed" fw={600}>
|
||||||
size="xs"
|
ШАГ {index + 1}
|
||||||
fw={600}
|
|
||||||
c="dimmed"
|
|
||||||
tt="uppercase"
|
|
||||||
style={{ letterSpacing: '0.5px' }}
|
|
||||||
>
|
|
||||||
Шаг {index + 1}
|
|
||||||
</Text>
|
</Text>
|
||||||
<Badge size="xs" variant="light" color="gray" tt="none">
|
<Badge size="xs" variant="light" color="blue">
|
||||||
#{step.priority}
|
#{step.priority}
|
||||||
</Badge>
|
</Badge>
|
||||||
</Group>
|
</Group>
|
||||||
|
<Avatar size="md" radius="xl" color="blue">
|
||||||
<Avatar size="md" radius="xl" color="blue" variant="filled">
|
{step.approver?.full_name?.charAt(0) || '?'}
|
||||||
{step.approver?.full_name?.charAt(0).toUpperCase() || '?'}
|
|
||||||
</Avatar>
|
</Avatar>
|
||||||
|
<Text size="xs" fw={500} ta="center" lineClamp={2}>
|
||||||
<Text size="sm" fw={500} ta="center" lineClamp={2} c="dark">
|
|
||||||
{step.approver?.full_name || '—'}
|
{step.approver?.full_name || '—'}
|
||||||
</Text>
|
</Text>
|
||||||
|
|
||||||
{/* Бейдж конкретной целевой системы для шага (если выбрано) */}
|
{/* Кнопки действий */}
|
||||||
{step.target_system && (
|
<Group gap={4} mt={4}>
|
||||||
<Badge size="xs" color="cyan" variant="light">
|
<Tooltip label="Редактировать">
|
||||||
Система: {step.target_system}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Divider style={{ width: '100%', margin: '4px 0' }} />
|
|
||||||
|
|
||||||
<Group gap="xs" justify="center">
|
|
||||||
<Tooltip label="Редактировать" withArrow>
|
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
color="gray"
|
color="blue"
|
||||||
size="sm"
|
size="xs"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation()
|
e.stopPropagation()
|
||||||
onEditStep(step.id!)
|
onEditStep(step.id!)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<IconPencil size={14} />
|
<IconPencil size={12} />
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<Tooltip label="Удалить" withArrow>
|
<Tooltip label="Удалить">
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
color="red"
|
color="red"
|
||||||
size="sm"
|
size="xs"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation()
|
e.stopPropagation()
|
||||||
onDeleteStep(step.id!)
|
onDeleteStep(step.id!)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<IconTrash size={14} />
|
<IconTrash size={12} />
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
@ -331,6 +168,13 @@ export default function ChainVisualization({
|
||||||
))}
|
))}
|
||||||
</Group>
|
</Group>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
<style>{`
|
||||||
|
.hover-shadow:hover {
|
||||||
|
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||||
|
transform: translateY(-2px);
|
||||||
|
}
|
||||||
|
`}</style>
|
||||||
</Paper>
|
</Paper>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -7,14 +7,15 @@ import {
|
||||||
Group,
|
Group,
|
||||||
Button,
|
Button,
|
||||||
Text,
|
Text,
|
||||||
|
Loader,
|
||||||
|
Center,
|
||||||
Badge,
|
Badge,
|
||||||
Paper,
|
Paper,
|
||||||
Alert,
|
Alert,
|
||||||
Radio,
|
Radio,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { useForm } from '@mantine/form'
|
import { useForm } from '@mantine/form'
|
||||||
import { IconInfoCircle, IconAlertCircle, IconCopy } from '@tabler/icons-react'
|
import { IconInfoCircle } from '@tabler/icons-react'
|
||||||
import { notifications } from '@mantine/notifications'
|
|
||||||
import {
|
import {
|
||||||
useCreateHierarchy,
|
useCreateHierarchy,
|
||||||
useUpdateHierarchy
|
useUpdateHierarchy
|
||||||
|
|
@ -25,7 +26,6 @@ import { useCategories } from '@/features/categories/hooks/useCategories'
|
||||||
import { useTopics } from '@/features/topics/hooks/useTopics'
|
import { useTopics } from '@/features/topics/hooks/useTopics'
|
||||||
import type { UserHierarchy } from '@/types/api'
|
import type { UserHierarchy } from '@/types/api'
|
||||||
import type { ChainGroup } from '@/features/hierarchies/utils'
|
import type { ChainGroup } from '@/features/hierarchies/utils'
|
||||||
import { useAllSystemOptions } from '@/features/hierarchies/hooks/useSystemOptions'
|
|
||||||
|
|
||||||
interface HierarchyEditModalProps {
|
interface HierarchyEditModalProps {
|
||||||
hierarchy: UserHierarchy | null
|
hierarchy: UserHierarchy | null
|
||||||
|
|
@ -48,7 +48,6 @@ export default function HierarchyEditModal({
|
||||||
const { data: users } = useUsers({ limit: 1000 })
|
const { data: users } = useUsers({ limit: 1000 })
|
||||||
const { data: departments } = useDepartments()
|
const { data: departments } = useDepartments()
|
||||||
const { data: categories } = useCategories({ limit: 1000 })
|
const { data: categories } = useCategories({ limit: 1000 })
|
||||||
const { options: systemOptions } = useAllSystemOptions()
|
|
||||||
|
|
||||||
const isEditMode = hierarchy !== null
|
const isEditMode = hierarchy !== null
|
||||||
|
|
||||||
|
|
@ -61,26 +60,18 @@ export default function HierarchyEditModal({
|
||||||
topic_category_id: null as number | null,
|
topic_category_id: null as number | null,
|
||||||
topic_id: null as number | null,
|
topic_id: null as number | null,
|
||||||
priority: 0,
|
priority: 0,
|
||||||
target_system: null as string | null
|
|
||||||
},
|
},
|
||||||
validate: {
|
validate: {
|
||||||
subordinate_id: (v) => (v === null ? 'Выберите подчинённого' : null),
|
subordinate_id: (v) => (v === null ? 'Выберите подчинённого' : null),
|
||||||
approver_id: (v) => (v === null ? 'Выберите согласующего' : null),
|
approver_id: (v) => (v === null ? 'Выберите согласующего' : null),
|
||||||
// department_id/topic_category_id/topic_id заблокированы в режиме
|
department_id: (v) => (v === null ? 'Выберите отдел' : null),
|
||||||
// редактирования (см. disabled ниже) — если их всё же валидировать
|
|
||||||
// как обязательные, а на самой записи значение почему-то пустое,
|
|
||||||
// форма зависает намертво: поле нельзя ни заполнить (заблокировано),
|
|
||||||
// ни пропустить (обязательное).
|
|
||||||
department_id: (v) => (!isEditMode && v === null ? 'Выберите отдел' : null),
|
|
||||||
topic_category_id: (v, values) => {
|
topic_category_id: (v, values) => {
|
||||||
if (isEditMode) return null
|
|
||||||
if ((values.scope_type === 'category' || values.scope_type === 'topic') && v === null) {
|
if ((values.scope_type === 'category' || values.scope_type === 'topic') && v === null) {
|
||||||
return 'Выберите категорию'
|
return 'Выберите категорию'
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
},
|
},
|
||||||
topic_id: (v, values) => {
|
topic_id: (v, values) => {
|
||||||
if (isEditMode) return null
|
|
||||||
if (values.scope_type === 'topic' && v === null) {
|
if (values.scope_type === 'topic' && v === null) {
|
||||||
return 'Выберите тему'
|
return 'Выберите тему'
|
||||||
}
|
}
|
||||||
|
|
@ -89,19 +80,12 @@ export default function HierarchyEditModal({
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
// Темы выбранной категории — для выпадающего списка "Тема" при создании.
|
// Загружаем темы выбранной категории
|
||||||
const { data: categoryTopics } = useTopics({
|
const { data: categoryTopics } = useTopics({
|
||||||
limit: 1000,
|
limit: 1000,
|
||||||
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
|
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
|
||||||
})
|
})
|
||||||
|
|
||||||
// Полный список тем без фильтра — нужен, чтобы восстановить
|
|
||||||
// topic_category_id по topic_id (см. useEffect ниже), когда сама
|
|
||||||
// категория не сохранена явно — и на записи из БД (режим редактирования),
|
|
||||||
// и в presetGroup (добавление шага в существующую цепочку с областью
|
|
||||||
// действия "тема" — это и был баг №5).
|
|
||||||
const { data: allTopics } = useTopics({ limit: 1000 })
|
|
||||||
|
|
||||||
// Заполняем форму данными
|
// Заполняем форму данными
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (hierarchy) {
|
if (hierarchy) {
|
||||||
|
|
@ -109,36 +93,22 @@ export default function HierarchyEditModal({
|
||||||
if (hierarchy.topic_id) scopeType = 'topic'
|
if (hierarchy.topic_id) scopeType = 'topic'
|
||||||
else if (hierarchy.topic_category_id) scopeType = 'category'
|
else if (hierarchy.topic_category_id) scopeType = 'category'
|
||||||
|
|
||||||
let resolvedCategoryId = hierarchy.topic_category_id || null
|
|
||||||
if (scopeType === 'topic' && !resolvedCategoryId && allTopics?.data) {
|
|
||||||
const matchedTopic = allTopics.data.find((t) => t.id === hierarchy.topic_id)
|
|
||||||
resolvedCategoryId = matchedTopic?.category_id || null
|
|
||||||
}
|
|
||||||
|
|
||||||
form.setValues({
|
form.setValues({
|
||||||
subordinate_id: hierarchy.subordinate_id || null,
|
subordinate_id: hierarchy.subordinate_id || null,
|
||||||
approver_id: hierarchy.approver_id || null,
|
approver_id: hierarchy.approver_id || null,
|
||||||
department_id: hierarchy.department_id || null,
|
department_id: hierarchy.department_id || null,
|
||||||
scope_type: scopeType,
|
scope_type: scopeType,
|
||||||
topic_category_id: resolvedCategoryId,
|
topic_category_id: hierarchy.topic_category_id || null,
|
||||||
topic_id: hierarchy.topic_id || null,
|
topic_id: hierarchy.topic_id || null,
|
||||||
target_system: hierarchy.target_system || null,
|
|
||||||
priority: hierarchy.priority ?? 0,
|
priority: hierarchy.priority ?? 0,
|
||||||
})
|
})
|
||||||
} else if (presetGroup) {
|
} else if (presetGroup) {
|
||||||
let resolvedCategoryId: number | null = null
|
// Предзаполняем из группы (для добавления шага)
|
||||||
if (presetGroup.scopeType === 'category') {
|
|
||||||
resolvedCategoryId = presetGroup.scopeObjectId
|
|
||||||
} else if (presetGroup.scopeType === 'topic') {
|
|
||||||
const matchedTopic = allTopics?.data?.find((t) => t.id === presetGroup.scopeObjectId)
|
|
||||||
resolvedCategoryId = matchedTopic?.category_id || null
|
|
||||||
}
|
|
||||||
|
|
||||||
form.setValues({
|
form.setValues({
|
||||||
subordinate_id: presetGroup.subordinateId,
|
subordinate_id: presetGroup.subordinateId,
|
||||||
department_id: presetGroup.departmentId,
|
department_id: presetGroup.departmentId,
|
||||||
scope_type: presetGroup.scopeType,
|
scope_type: presetGroup.scopeType,
|
||||||
topic_category_id: resolvedCategoryId,
|
topic_category_id: presetGroup.scopeType === 'category' ? presetGroup.scopeObjectId : null,
|
||||||
topic_id: presetGroup.scopeType === 'topic' ? presetGroup.scopeObjectId : null,
|
topic_id: presetGroup.scopeType === 'topic' ? presetGroup.scopeObjectId : null,
|
||||||
priority: presetGroup.steps.length, // Следующий priority
|
priority: presetGroup.steps.length, // Следующий priority
|
||||||
approver_id: null,
|
approver_id: null,
|
||||||
|
|
@ -146,8 +116,7 @@ export default function HierarchyEditModal({
|
||||||
} else {
|
} else {
|
||||||
form.reset()
|
form.reset()
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
}, [hierarchy, presetGroup, opened])
|
||||||
}, [hierarchy, presetGroup, opened, allTopics])
|
|
||||||
|
|
||||||
const handleScopeTypeChange = (value: ScopeType) => {
|
const handleScopeTypeChange = (value: ScopeType) => {
|
||||||
form.setFieldValue('scope_type', value)
|
form.setFieldValue('scope_type', value)
|
||||||
|
|
@ -180,19 +149,16 @@ export default function HierarchyEditModal({
|
||||||
label: t.name || '',
|
label: t.name || '',
|
||||||
})) || []
|
})) || []
|
||||||
|
|
||||||
const buildPayload = (values: typeof form.values) => ({
|
|
||||||
subordinate_id: values.subordinate_id!,
|
|
||||||
approver_id: values.approver_id!,
|
|
||||||
department_id: values.department_id!,
|
|
||||||
priority: values.priority,
|
|
||||||
target_system: values.target_system || null,
|
|
||||||
topic_category_id: values.scope_type === 'global' ? null :
|
|
||||||
values.scope_type === 'category' ? values.topic_category_id : null,
|
|
||||||
topic_id: values.scope_type === 'topic' ? values.topic_id : null,
|
|
||||||
})
|
|
||||||
|
|
||||||
const handleSubmit = async (values: typeof form.values) => {
|
const handleSubmit = async (values: typeof form.values) => {
|
||||||
const payload = buildPayload(values)
|
const payload = {
|
||||||
|
subordinate_id: values.subordinate_id!,
|
||||||
|
approver_id: values.approver_id!,
|
||||||
|
department_id: values.department_id!,
|
||||||
|
priority: values.priority,
|
||||||
|
topic_category_id: values.scope_type === 'global' ? null :
|
||||||
|
values.scope_type === 'category' ? values.topic_category_id : null,
|
||||||
|
topic_id: values.scope_type === 'topic' ? values.topic_id : null,
|
||||||
|
}
|
||||||
|
|
||||||
if (isEditMode && hierarchy?.id) {
|
if (isEditMode && hierarchy?.id) {
|
||||||
await updateHierarchy.mutateAsync({
|
await updateHierarchy.mutateAsync({
|
||||||
|
|
@ -205,33 +171,7 @@ export default function HierarchyEditModal({
|
||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
// НОВОЕ (пункт 3): дублирование прямо из окна редактирования — создаёт
|
|
||||||
// новую запись с теми же значениями, что сейчас на экране, не трогая
|
|
||||||
// ту, что редактируется. Доступно только в режиме редактирования —
|
|
||||||
// дублировать ещё не сохранённую форму нечего.
|
|
||||||
const handleDuplicate = async () => {
|
|
||||||
if (!isEditMode) return
|
|
||||||
try {
|
|
||||||
await createHierarchy.mutateAsync(buildPayload(form.values))
|
|
||||||
notifications.show({
|
|
||||||
title: 'Успешно',
|
|
||||||
message: 'Связь продублирована — можно найти копию в списке и отредактировать при необходимости',
|
|
||||||
color: 'green',
|
|
||||||
})
|
|
||||||
onClose()
|
|
||||||
} catch (error) {
|
|
||||||
notifications.show({
|
|
||||||
title: 'Ошибка',
|
|
||||||
message: 'Не удалось продублировать связь',
|
|
||||||
color: 'red',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const isSubmitting = createHierarchy.isPending || updateHierarchy.isPending
|
const isSubmitting = createHierarchy.isPending || updateHierarchy.isPending
|
||||||
const hasErrors = Object.keys(form.errors).length > 0
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
|
|
@ -249,12 +189,7 @@ export default function HierarchyEditModal({
|
||||||
>
|
>
|
||||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{hasErrors && (
|
{/* Подчинённый */}
|
||||||
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
|
|
||||||
<Text size="sm">Проверьте поля, отмеченные красным, ниже.</Text>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Select
|
<Select
|
||||||
label="Сотрудник (инициатор)"
|
label="Сотрудник (инициатор)"
|
||||||
placeholder="Выберите пользователя"
|
placeholder="Выберите пользователя"
|
||||||
|
|
@ -263,9 +198,8 @@ export default function HierarchyEditModal({
|
||||||
onChange={(v) => form.setFieldValue('subordinate_id', v ? Number(v) : null)}
|
onChange={(v) => form.setFieldValue('subordinate_id', v ? Number(v) : null)}
|
||||||
searchable
|
searchable
|
||||||
required
|
required
|
||||||
disabled={!!presetGroup}
|
disabled={isEditMode || !!presetGroup}
|
||||||
description="Пользователь, для которого настраивается согласование"
|
description="Пользователь, для которого настраивается согласование"
|
||||||
error={form.errors.subordinate_id}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Отдел */}
|
{/* Отдел */}
|
||||||
|
|
@ -276,9 +210,8 @@ export default function HierarchyEditModal({
|
||||||
value={form.values.department_id ? String(form.values.department_id) : null}
|
value={form.values.department_id ? String(form.values.department_id) : null}
|
||||||
onChange={(v) => form.setFieldValue('department_id', v ? Number(v) : null)}
|
onChange={(v) => form.setFieldValue('department_id', v ? Number(v) : null)}
|
||||||
searchable
|
searchable
|
||||||
required={!isEditMode}
|
required
|
||||||
disabled={isEditMode || !!presetGroup}
|
disabled={isEditMode || !!presetGroup}
|
||||||
error={form.errors.department_id}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Согласующий */}
|
{/* Согласующий */}
|
||||||
|
|
@ -291,7 +224,6 @@ export default function HierarchyEditModal({
|
||||||
searchable
|
searchable
|
||||||
required
|
required
|
||||||
description="Пользователь, который будет согласовывать заявки"
|
description="Пользователь, который будет согласовывать заявки"
|
||||||
error={form.errors.approver_id}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Область действия */}
|
{/* Область действия */}
|
||||||
|
|
@ -308,19 +240,16 @@ export default function HierarchyEditModal({
|
||||||
value="global"
|
value="global"
|
||||||
label="Глобальное правило"
|
label="Глобальное правило"
|
||||||
description="Для всех тем согласований"
|
description="Для всех тем согласований"
|
||||||
disabled={isEditMode}
|
|
||||||
/>
|
/>
|
||||||
<Radio
|
<Radio
|
||||||
value="category"
|
value="category"
|
||||||
label="Для категории тем"
|
label="Для категории тем"
|
||||||
description="Только для тем выбранной категории"
|
description="Только для тем выбранной категории"
|
||||||
disabled={isEditMode}
|
|
||||||
/>
|
/>
|
||||||
<Radio
|
<Radio
|
||||||
value="topic"
|
value="topic"
|
||||||
label="Для конкретной темы"
|
label="Для конкретной темы"
|
||||||
description="Только для выбранной темы"
|
description="Только для выбранной темы"
|
||||||
disabled={isEditMode}
|
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Radio.Group>
|
</Radio.Group>
|
||||||
|
|
@ -338,9 +267,8 @@ export default function HierarchyEditModal({
|
||||||
form.setFieldValue('topic_id', null)
|
form.setFieldValue('topic_id', null)
|
||||||
}}
|
}}
|
||||||
searchable
|
searchable
|
||||||
required={!isEditMode}
|
required
|
||||||
disabled={isEditMode || !!presetGroup}
|
disabled={isEditMode || !!presetGroup}
|
||||||
error={form.errors.topic_category_id}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -353,25 +281,12 @@ export default function HierarchyEditModal({
|
||||||
value={form.values.topic_id ? String(form.values.topic_id) : null}
|
value={form.values.topic_id ? String(form.values.topic_id) : null}
|
||||||
onChange={(v) => form.setFieldValue('topic_id', v ? Number(v) : null)}
|
onChange={(v) => form.setFieldValue('topic_id', v ? Number(v) : null)}
|
||||||
searchable
|
searchable
|
||||||
required={!isEditMode}
|
required
|
||||||
disabled={!form.values.topic_category_id || isEditMode || !!presetGroup}
|
disabled={!form.values.topic_category_id || isEditMode || !!presetGroup}
|
||||||
description={!form.values.topic_category_id && !isEditMode ? 'Сначала выберите категорию' : undefined}
|
description={!form.values.topic_category_id ? 'Сначала выберите категорию' : undefined}
|
||||||
error={form.errors.topic_id}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Целевая система шага"
|
|
||||||
placeholder="Все системы (по умолчанию)"
|
|
||||||
data={[
|
|
||||||
{ value: 'all', label: 'Все системы' },
|
|
||||||
...systemOptions.map((s) => ({ value: s.value, label: s.label })),
|
|
||||||
]}
|
|
||||||
value={form.values.target_system || 'all'}
|
|
||||||
onChange={(v) => form.setFieldValue('target_system', (v === 'all' || !v) ? "" : v)}
|
|
||||||
description="Укажите систему, если данный шаг согласующего применяется только к определенной системе"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Priority */}
|
{/* Priority */}
|
||||||
<NumberInput
|
<NumberInput
|
||||||
label="Порядок шага (priority)"
|
label="Порядок шага (priority)"
|
||||||
|
|
@ -386,33 +301,17 @@ export default function HierarchyEditModal({
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
Шаги выполняются последовательно в порядке возрастания priority.
|
Шаги выполняются последовательно в порядке возрастания priority.
|
||||||
Заявка переходит к следующему согласующему только после одобрения предыдущим.
|
Заявка переходит к следующему согласующему только после одобрения предыдущим.
|
||||||
{isEditMode && ' Область действия и отдел при редактировании не меняются — чтобы поменять их, удалите связь и создайте новую.'}
|
|
||||||
</Text>
|
</Text>
|
||||||
</Alert>
|
</Alert>
|
||||||
|
|
||||||
{/* Кнопки */}
|
{/* Кнопки */}
|
||||||
<Group justify="space-between" mt="md">
|
<Group justify="flex-end" mt="md">
|
||||||
{isEditMode ? (
|
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
||||||
<Button
|
Отмена
|
||||||
variant="light"
|
</Button>
|
||||||
color="teal"
|
<Button type="submit" loading={isSubmitting}>
|
||||||
leftSection={<IconCopy size={16} />}
|
{isEditMode ? 'Сохранить' : 'Создать'}
|
||||||
onClick={handleDuplicate}
|
</Button>
|
||||||
disabled={isSubmitting}
|
|
||||||
>
|
|
||||||
Дублировать
|
|
||||||
</Button>
|
|
||||||
) : (
|
|
||||||
<div />
|
|
||||||
)}
|
|
||||||
<Group>
|
|
||||||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
|
||||||
Отмена
|
|
||||||
</Button>
|
|
||||||
<Button type="submit" loading={isSubmitting}>
|
|
||||||
{isEditMode ? 'Сохранить' : 'Создать'}
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Group>
|
</Group>
|
||||||
</Stack>
|
</Stack>
|
||||||
</form>
|
</form>
|
||||||
|
|
|
||||||
|
|
@ -1,401 +0,0 @@
|
||||||
import { useState, useMemo, useEffect } from 'react'
|
|
||||||
import {
|
|
||||||
Modal,
|
|
||||||
Stack,
|
|
||||||
Select,
|
|
||||||
Group,
|
|
||||||
Button,
|
|
||||||
Text,
|
|
||||||
Paper,
|
|
||||||
Alert,
|
|
||||||
Badge,
|
|
||||||
Loader,
|
|
||||||
Center,
|
|
||||||
Radio,
|
|
||||||
Checkbox,
|
|
||||||
Divider,
|
|
||||||
} from '@mantine/core'
|
|
||||||
import { IconInfoCircle, IconUsers } from '@tabler/icons-react'
|
|
||||||
import { notifications } from '@mantine/notifications'
|
|
||||||
import {
|
|
||||||
useHierarchies,
|
|
||||||
HIERARCHIES_QUERY_KEY,
|
|
||||||
} from '@/features/hierarchies/hooks/useHierarchies'
|
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
|
||||||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
|
||||||
import { useTopics } from '@/features/topics/hooks/useTopics'
|
|
||||||
import { hierarchiesApi } from '@/api/hierarchies'
|
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
|
||||||
import type { UserHierarchy } from '@/types/api'
|
|
||||||
|
|
||||||
interface PersonDuplicateModalProps {
|
|
||||||
opened: boolean
|
|
||||||
onClose: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
type DuplicateMode = 'replace' | 'append' | 'manual'
|
|
||||||
|
|
||||||
const NO_USER_SENTINEL = 0
|
|
||||||
|
|
||||||
export default function PersonDuplicateModal({ opened, onClose }: PersonDuplicateModalProps) {
|
|
||||||
const [sourceId, setSourceId] = useState<string | null>(null)
|
|
||||||
const [targetId, setTargetId] = useState<string | null>(null)
|
|
||||||
const [mode, setMode] = useState<DuplicateMode>('append')
|
|
||||||
const [selectedScopeKeys, setSelectedScopeKeys] = useState<string[]>([])
|
|
||||||
const [isDuplicating, setIsDuplicating] = useState(false)
|
|
||||||
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const { data: users } = useUsers({ limit: 1000 })
|
|
||||||
const { data: categories } = useCategories({ limit: 1000 })
|
|
||||||
const { data: topics } = useTopics({ limit: 1000 })
|
|
||||||
|
|
||||||
// Связи исходного сотрудника
|
|
||||||
const { data: sourceHierarchies, isLoading: sourceLoading } = useHierarchies({
|
|
||||||
subordinate_id: sourceId ? Number(sourceId) : NO_USER_SENTINEL,
|
|
||||||
limit: 1000,
|
|
||||||
})
|
|
||||||
|
|
||||||
// Связи целевого сотрудника (нужны для удаления при 'replace' и проверки дублей при 'append')
|
|
||||||
const { data: targetHierarchies, isLoading: targetLoading } = useHierarchies({
|
|
||||||
subordinate_id: targetId ? Number(targetId) : NO_USER_SENTINEL,
|
|
||||||
limit: 1000,
|
|
||||||
})
|
|
||||||
|
|
||||||
const sourceRows = sourceId ? sourceHierarchies?.data || [] : []
|
|
||||||
const targetRows = targetId ? targetHierarchies?.data || [] : []
|
|
||||||
|
|
||||||
const userOptions =
|
|
||||||
users?.data?.map((u) => ({
|
|
||||||
value: String(u.id),
|
|
||||||
label: u.full_name || `Пользователь #${u.id}`,
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
// Определяем ключ категории/области для группировки при ручном выборе
|
|
||||||
const getCategoryKeyAndLabel = (h: UserHierarchy) => {
|
|
||||||
if (h.topic_category_id) {
|
|
||||||
const c = categories?.data?.find((cat) => cat.id === h.topic_category_id)
|
|
||||||
return {
|
|
||||||
key: `cat_${h.topic_category_id}`,
|
|
||||||
label: `Категория: ${c?.name || `#${h.topic_category_id}`}`,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (h.topic_id) {
|
|
||||||
const t = topics?.data?.find((top) => top.id === h.topic_id)
|
|
||||||
if (t?.category_id) {
|
|
||||||
const c = categories?.data?.find((cat) => cat.id === t.category_id)
|
|
||||||
return {
|
|
||||||
key: `cat_${t.category_id}`,
|
|
||||||
label: `Категория: ${c?.name || `#${t.category_id}`} (включая темы)`,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
key: `topic_${h.topic_id}`,
|
|
||||||
label: `Тема: ${t?.name || `#${h.topic_id}`}`,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
key: 'global',
|
|
||||||
label: 'Глобальные правила (Все темы)',
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Группируем связи исходного пользователя по категориям для режима "Выбрать вручную"
|
|
||||||
const availableScopes = useMemo(() => {
|
|
||||||
const map = new Map<string, { key: string; label: string; rows: UserHierarchy[] }>()
|
|
||||||
for (const h of sourceRows) {
|
|
||||||
const { key, label } = getCategoryKeyAndLabel(h)
|
|
||||||
if (!map.has(key)) {
|
|
||||||
map.set(key, { key, label, rows: [] })
|
|
||||||
}
|
|
||||||
map.get(key)!.rows.push(h)
|
|
||||||
}
|
|
||||||
return Array.from(map.values())
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [sourceRows, categories, topics])
|
|
||||||
|
|
||||||
// При смене исходного пользователя по умолчанию выделяем все доступные категории
|
|
||||||
useEffect(() => {
|
|
||||||
setSelectedScopeKeys(availableScopes.map((s) => s.key))
|
|
||||||
}, [sourceId, availableScopes.length])
|
|
||||||
|
|
||||||
const describeScope = (h: { topic_id?: number | null; topic_category_id?: number | null }) => {
|
|
||||||
if (h.topic_id) {
|
|
||||||
const t = topics?.data?.find((t) => t.id === h.topic_id)
|
|
||||||
return `Тема: ${t?.name || `#${h.topic_id}`}`
|
|
||||||
}
|
|
||||||
if (h.topic_category_id) {
|
|
||||||
const c = categories?.data?.find((c) => c.id === h.topic_category_id)
|
|
||||||
return `Категория: ${c?.name || `#${h.topic_category_id}`}`
|
|
||||||
}
|
|
||||||
return 'Глобально'
|
|
||||||
}
|
|
||||||
|
|
||||||
// Вычисляем итоговый список записей для создания
|
|
||||||
const rowsToCreate = useMemo(() => {
|
|
||||||
let baseRows = sourceRows
|
|
||||||
if (mode === 'manual') {
|
|
||||||
baseRows = sourceRows.filter((h) => {
|
|
||||||
const { key } = getCategoryKeyAndLabel(h)
|
|
||||||
return selectedScopeKeys.includes(key)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mode === 'append' || mode === 'manual') {
|
|
||||||
// Исключаем те шаги, которые уже точно существуют у целевого пользователя
|
|
||||||
return baseRows.filter(
|
|
||||||
(src) =>
|
|
||||||
!targetRows.some(
|
|
||||||
(trg) =>
|
|
||||||
trg.approver_id === src.approver_id &&
|
|
||||||
trg.department_id === src.department_id &&
|
|
||||||
(trg.topic_category_id ?? null) === (src.topic_category_id ?? null) &&
|
|
||||||
(trg.topic_id ?? null) === (src.topic_id ?? null) &&
|
|
||||||
(trg.target_system || null) === (src.target_system || null)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return baseRows
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [sourceRows, targetRows, mode, selectedScopeKeys, categories, topics])
|
|
||||||
|
|
||||||
const handleClose = () => {
|
|
||||||
setSourceId(null)
|
|
||||||
setTargetId(null)
|
|
||||||
setMode('append')
|
|
||||||
setSelectedScopeKeys([])
|
|
||||||
onClose()
|
|
||||||
}
|
|
||||||
|
|
||||||
const toggleScopeKey = (key: string) => {
|
|
||||||
setSelectedScopeKeys((prev) =>
|
|
||||||
prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDuplicate = async () => {
|
|
||||||
if (!sourceId || !targetId) return
|
|
||||||
if (mode === 'manual' && selectedScopeKeys.length === 0) return
|
|
||||||
|
|
||||||
setIsDuplicating(true)
|
|
||||||
try {
|
|
||||||
// 1. Если выбран режим "Заменить текущие", сначала удаляем все старые цепочки целевого пользователя
|
|
||||||
if (mode === 'replace' && targetRows.length > 0) {
|
|
||||||
for (const oldRow of targetRows) {
|
|
||||||
if (oldRow.id) {
|
|
||||||
await hierarchiesApi.delete(oldRow.id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Создаём новые записи
|
|
||||||
let createdCount = 0
|
|
||||||
for (const h of rowsToCreate) {
|
|
||||||
if (!h.approver_id || !h.department_id) continue
|
|
||||||
await hierarchiesApi.create({
|
|
||||||
subordinate_id: Number(targetId),
|
|
||||||
approver_id: h.approver_id,
|
|
||||||
department_id: h.department_id,
|
|
||||||
priority: h.priority ?? 0,
|
|
||||||
topic_category_id: h.topic_category_id ?? null,
|
|
||||||
topic_id: h.topic_id ?? null,
|
|
||||||
target_system: h.target_system ?? null,
|
|
||||||
})
|
|
||||||
createdCount++
|
|
||||||
}
|
|
||||||
|
|
||||||
await queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] })
|
|
||||||
|
|
||||||
notifications.show({
|
|
||||||
title: 'Успешно',
|
|
||||||
message:
|
|
||||||
mode === 'replace'
|
|
||||||
? `Старые связи удалены (${targetRows.length}), создано новых: ${createdCount}`
|
|
||||||
: `Добавлено новых связей: ${createdCount}`,
|
|
||||||
color: 'green',
|
|
||||||
})
|
|
||||||
handleClose()
|
|
||||||
} catch (error) {
|
|
||||||
notifications.show({
|
|
||||||
title: 'Ошибка',
|
|
||||||
message: 'Произошла ошибка при дублировании связей. Проверьте список.',
|
|
||||||
color: 'red',
|
|
||||||
})
|
|
||||||
} finally {
|
|
||||||
setIsDuplicating(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal
|
|
||||||
opened={opened}
|
|
||||||
onClose={handleClose}
|
|
||||||
title={
|
|
||||||
<Group gap="xs">
|
|
||||||
<IconUsers size={20} />
|
|
||||||
<Text fw={600}>Дублировать связи сотрудника</Text>
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
size="lg"
|
|
||||||
centered
|
|
||||||
>
|
|
||||||
<Stack gap="md">
|
|
||||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
|
||||||
<Text size="sm">
|
|
||||||
Скопирует цепочки согласования выбранного сотрудника для другого сотрудника.
|
|
||||||
Вы можете полностью заменить текущие цепочки, дополнить их недостающими или
|
|
||||||
выбрать нужные категории вручную.
|
|
||||||
</Text>
|
|
||||||
</Alert>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="От кого копировать (образец)"
|
|
||||||
placeholder="Выберите сотрудника, чьи связи нужно скопировать"
|
|
||||||
data={userOptions.filter((o) => o.value !== targetId)}
|
|
||||||
value={sourceId}
|
|
||||||
onChange={setSourceId}
|
|
||||||
searchable
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Кому назначить связи"
|
|
||||||
placeholder="Выберите сотрудника"
|
|
||||||
data={userOptions.filter((o) => o.value !== sourceId)}
|
|
||||||
value={targetId}
|
|
||||||
onChange={setTargetId}
|
|
||||||
searchable
|
|
||||||
required
|
|
||||||
disabled={!sourceId}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{sourceId && targetId && (
|
|
||||||
<Paper withBorder p="md">
|
|
||||||
<Text size="sm" fw={600} mb="sm">
|
|
||||||
Режим дублирования
|
|
||||||
</Text>
|
|
||||||
<Radio.Group
|
|
||||||
value={mode}
|
|
||||||
onChange={(val) => setMode(val as DuplicateMode)}
|
|
||||||
>
|
|
||||||
<Stack gap="xs">
|
|
||||||
<Radio
|
|
||||||
value="replace"
|
|
||||||
label="Заменить текущие цепочки"
|
|
||||||
description={`Полностью удалит старые связи сотрудника (${targetRows.length}) и заменит их связями образца`}
|
|
||||||
/>
|
|
||||||
<Radio
|
|
||||||
value="append"
|
|
||||||
label="Дополнить текущие"
|
|
||||||
description="К существующим цепочкам будут добавлены только недостающие шаги"
|
|
||||||
/>
|
|
||||||
<Radio
|
|
||||||
value="manual"
|
|
||||||
label="Выбрать вручную"
|
|
||||||
description="Выберите галочками категории образца, которые нужно продублировать"
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
</Radio.Group>
|
|
||||||
|
|
||||||
{mode === 'manual' && availableScopes.length > 0 && (
|
|
||||||
<>
|
|
||||||
<Divider my="sm" />
|
|
||||||
<Group justify="space-between" mb="xs">
|
|
||||||
<Text size="xs" fw={600} c="dimmed" tt="uppercase">
|
|
||||||
Категории для копирования
|
|
||||||
</Text>
|
|
||||||
<Button
|
|
||||||
variant="subtle"
|
|
||||||
size="compact-xs"
|
|
||||||
onClick={() =>
|
|
||||||
setSelectedScopeKeys(
|
|
||||||
selectedScopeKeys.length === availableScopes.length
|
|
||||||
? []
|
|
||||||
: availableScopes.map((s) => s.key)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{selectedScopeKeys.length === availableScopes.length
|
|
||||||
? 'Снять все'
|
|
||||||
: 'Выбрать все'}
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
<Stack gap="xs">
|
|
||||||
{availableScopes.map((scope) => (
|
|
||||||
<Checkbox
|
|
||||||
key={scope.key}
|
|
||||||
checked={selectedScopeKeys.includes(scope.key)}
|
|
||||||
onChange={() => toggleScopeKey(scope.key)}
|
|
||||||
label={
|
|
||||||
<Group gap="xs">
|
|
||||||
<Text size="sm">{scope.label}</Text>
|
|
||||||
<Badge size="xs" variant="light" color="blue">
|
|
||||||
шагов: {scope.rows.length}
|
|
||||||
</Badge>
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{sourceId && (
|
|
||||||
<Paper withBorder p="md" bg="gray.0">
|
|
||||||
<Text size="xs" fw={600} c="dimmed" mb="xs" tt="uppercase">
|
|
||||||
Будет создано связей ({rowsToCreate.length})
|
|
||||||
</Text>
|
|
||||||
{sourceLoading || targetLoading ? (
|
|
||||||
<Center p="md">
|
|
||||||
<Loader size="sm" />
|
|
||||||
</Center>
|
|
||||||
) : sourceRows.length === 0 ? (
|
|
||||||
<Text size="sm" c="dimmed">
|
|
||||||
У исходного сотрудника нет настроенных связей.
|
|
||||||
</Text>
|
|
||||||
) : rowsToCreate.length === 0 ? (
|
|
||||||
<Text size="sm" c="dimmed">
|
|
||||||
Нет новых связей для добавления (все выбранные связи уже существуют у сотрудника или не выбрана ни одна категория).
|
|
||||||
</Text>
|
|
||||||
) : (
|
|
||||||
<Stack gap={6} style={{ maxHeight: 220, overflowY: 'auto' }}>
|
|
||||||
{rowsToCreate.map((h) => (
|
|
||||||
<Group key={h.id} justify="space-between" wrap="nowrap">
|
|
||||||
<Text size="sm">
|
|
||||||
{h.approver?.full_name || `Согласующий #${h.approver_id}`}
|
|
||||||
</Text>
|
|
||||||
<Badge size="xs" variant="light" color="gray" tt="none">
|
|
||||||
{describeScope(h)}
|
|
||||||
</Badge>
|
|
||||||
</Group>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Group justify="flex-end" mt="md">
|
|
||||||
<Button variant="default" onClick={handleClose} disabled={isDuplicating}>
|
|
||||||
Отмена
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={handleDuplicate}
|
|
||||||
loading={isDuplicating}
|
|
||||||
disabled={
|
|
||||||
!sourceId ||
|
|
||||||
!targetId ||
|
|
||||||
(mode !== 'replace' && rowsToCreate.length === 0) ||
|
|
||||||
(mode === 'replace' && sourceRows.length === 0)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{mode === 'replace'
|
|
||||||
? `Заменить (${rowsToCreate.length})`
|
|
||||||
: `Продублировать (${rowsToCreate.length})`}
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,109 +0,0 @@
|
||||||
import { useEffect } from 'react'
|
|
||||||
import { Box, Button, Group, NumberInput, Paper, Stack, Title, Text, Select, Textarea } from '@mantine/core'
|
|
||||||
import { DateTimePicker } from '@mantine/dates'
|
|
||||||
import { useForm } from '@mantine/form'
|
|
||||||
import { useMonthlyOrderSettings, useSaveMonthlyOrderSettings } from '@/features/monthlyOrders/hooks/useMonthlyOrderSettings'
|
|
||||||
import dayjs from 'dayjs'
|
|
||||||
import { IconDeviceFloppy } from '@tabler/icons-react'
|
|
||||||
|
|
||||||
interface SettingsFormValues {
|
|
||||||
deadline_date: Date | null
|
|
||||||
assembly_time_days: number
|
|
||||||
market_stage: string | null
|
|
||||||
market_stage_comment: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function MonthlyOrdersSettingsPage() {
|
|
||||||
const { data: currentSettings, isLoading } = useMonthlyOrderSettings()
|
|
||||||
const { mutate: saveSettings, isPending } = useSaveMonthlyOrderSettings()
|
|
||||||
|
|
||||||
const form = useForm<SettingsFormValues>({
|
|
||||||
initialValues: {
|
|
||||||
deadline_date: null,
|
|
||||||
assembly_time_days: 3,
|
|
||||||
market_stage: null,
|
|
||||||
market_stage_comment: '',
|
|
||||||
},
|
|
||||||
validate: {
|
|
||||||
deadline_date: (value) => (!value ? 'Укажите граничную дату и время' : null),
|
|
||||||
assembly_time_days: (value) => (value < 0 ? 'Срок не может быть отрицательным' : null),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (currentSettings) {
|
|
||||||
form.setValues({
|
|
||||||
deadline_date: currentSettings.deadline_date ? new Date(currentSettings.deadline_date) : null,
|
|
||||||
assembly_time_days: currentSettings.assembly_time_days || 3,
|
|
||||||
market_stage: currentSettings.market_stage || null,
|
|
||||||
market_stage_comment: currentSettings.market_stage_comment || '',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}, [currentSettings])
|
|
||||||
|
|
||||||
const handleSubmit = (values: SettingsFormValues) => {
|
|
||||||
saveSettings({
|
|
||||||
deadline_date: values.deadline_date ? dayjs(values.deadline_date).format() : null,
|
|
||||||
assembly_time_days: values.assembly_time_days,
|
|
||||||
market_stage: values.market_stage,
|
|
||||||
market_stage_comment: values.market_stage_comment,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isLoading) return <Text>Загрузка...</Text>
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Title order={2} mb="lg">Настройки: Заказ товаров на месяц</Title>
|
|
||||||
|
|
||||||
<Paper withBorder shadow="sm" p="md" radius="md" maw={500}>
|
|
||||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
|
||||||
<Stack gap="md">
|
|
||||||
<Text c="dimmed" size="sm">
|
|
||||||
Эти настройки применяются к текущему месяцу. Заказы открываются автоматически 15-го числа и закрываются в указанную дату.
|
|
||||||
</Text>
|
|
||||||
|
|
||||||
<DateTimePicker
|
|
||||||
label="Крайняя дата и время"
|
|
||||||
description="После этого времени менеджеры не смогут редактировать заказы на месяц и они отправятся на согласование."
|
|
||||||
placeholder="Выберите дату и время"
|
|
||||||
valueFormat="DD.MM.YYYY HH:mm"
|
|
||||||
withSeconds={false}
|
|
||||||
{...form.getInputProps('deadline_date')}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Стадия рынка"
|
|
||||||
placeholder="Выберите текущую стадию"
|
|
||||||
data={[
|
|
||||||
{ value: 'растущий', label: 'Растущий' },
|
|
||||||
{ value: 'падающий', label: 'Падающий' },
|
|
||||||
{ value: 'стоячий', label: 'Стоячий' },
|
|
||||||
]}
|
|
||||||
clearable
|
|
||||||
{...form.getInputProps('market_stage')}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Textarea
|
|
||||||
label="Комментарий к стадии рынка"
|
|
||||||
placeholder="Опишите подробности текущей ситуации на рынке"
|
|
||||||
minRows={3}
|
|
||||||
autosize
|
|
||||||
{...form.getInputProps('market_stage_comment')}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Group justify="flex-end" mt="md">
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
loading={isPending}
|
|
||||||
leftSection={<IconDeviceFloppy size={18} />}
|
|
||||||
>
|
|
||||||
Сохранить настройки
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</form>
|
|
||||||
</Paper>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,45 +0,0 @@
|
||||||
import { Stack, Tabs, Text, Alert } from '@mantine/core'
|
|
||||||
import { IconSend, IconHistory, IconLock } from '@tabler/icons-react'
|
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
|
||||||
import SendNotificationForm from './components/SendNotificationForm'
|
|
||||||
import NotificationsHistoryTable from './components/NotificationsHistoryTable'
|
|
||||||
|
|
||||||
export default function NotificationsPage() {
|
|
||||||
const { user } = useAuth()
|
|
||||||
const isObserver = user?.is_observer === true
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Stack gap="md">
|
|
||||||
<Text size="xl" fw={700}>Уведомления</Text>
|
|
||||||
|
|
||||||
<Tabs defaultValue={isObserver ? 'history' : 'send'}>
|
|
||||||
<Tabs.List>
|
|
||||||
{!isObserver && (
|
|
||||||
<Tabs.Tab value="send" leftSection={<IconSend size={16} />}>
|
|
||||||
Отправить
|
|
||||||
</Tabs.Tab>
|
|
||||||
)}
|
|
||||||
<Tabs.Tab value="history" leftSection={<IconHistory size={16} />}>
|
|
||||||
История
|
|
||||||
</Tabs.Tab>
|
|
||||||
</Tabs.List>
|
|
||||||
|
|
||||||
{!isObserver && (
|
|
||||||
<Tabs.Panel value="send" pt="md">
|
|
||||||
<SendNotificationForm />
|
|
||||||
</Tabs.Panel>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Tabs.Panel value="history" pt="md">
|
|
||||||
<NotificationsHistoryTable />
|
|
||||||
</Tabs.Panel>
|
|
||||||
</Tabs>
|
|
||||||
|
|
||||||
{isObserver && (
|
|
||||||
<Alert color="blue" variant="light" icon={<IconLock size={16} />}>
|
|
||||||
В режиме наблюдателя доступен только просмотр истории уведомлений
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,75 +0,0 @@
|
||||||
import { useNotification } from '@/features/notifications/hooks/useNotifications'
|
|
||||||
import { Modal, Stack, Text, Badge, ScrollArea, Table, Divider, Loader, Center } from '@mantine/core'
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
notificationId: number | null
|
|
||||||
opened: boolean
|
|
||||||
onClose: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
const RECIPIENT_STATUS_LABELS: Record<string, { label: string; color: string }> = {
|
|
||||||
pending: { label: 'В очереди', color: 'gray' },
|
|
||||||
sent: { label: 'Доставлено', color: 'green' },
|
|
||||||
failed: { label: 'Ошибка', color: 'red' },
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function NotificationDetailsModal({ notificationId, opened, onClose }: Props) {
|
|
||||||
const { data: notification, isLoading } = useNotification(notificationId)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal opened={opened} onClose={onClose} title="Детали уведомления" size="lg">
|
|
||||||
{isLoading || !notification ? (
|
|
||||||
<Center p={40}>
|
|
||||||
<Loader />
|
|
||||||
</Center>
|
|
||||||
) : (
|
|
||||||
<Stack gap="md">
|
|
||||||
<Stack gap={4}>
|
|
||||||
<Text fw={600}>{notification.title}</Text>
|
|
||||||
<div
|
|
||||||
style={{ fontSize: 14 }}
|
|
||||||
dangerouslySetInnerHTML={{ __html: notification.message_html }}
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<Divider label="Получатели" labelPosition="left" />
|
|
||||||
|
|
||||||
<ScrollArea h={300}>
|
|
||||||
<Table striped>
|
|
||||||
<Table.Thead>
|
|
||||||
<Table.Tr>
|
|
||||||
<Table.Th>Пользователь</Table.Th>
|
|
||||||
<Table.Th style={{ width: 120 }}>Статус</Table.Th>
|
|
||||||
<Table.Th>Ошибка</Table.Th>
|
|
||||||
</Table.Tr>
|
|
||||||
</Table.Thead>
|
|
||||||
<Table.Tbody>
|
|
||||||
{(notification.recipients || []).map((r) => {
|
|
||||||
const statusInfo = RECIPIENT_STATUS_LABELS[r.status || ''] || {
|
|
||||||
label: r.status || '—',
|
|
||||||
color: 'gray',
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<Table.Tr key={r.id}>
|
|
||||||
<Table.Td>{r.user?.full_name || `ID ${r.user_id}`}</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Badge color={statusInfo.color} variant="light" size="sm">
|
|
||||||
{statusInfo.label}
|
|
||||||
</Badge>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="xs" c="red">
|
|
||||||
{r.error_message || ''}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</Table.Tbody>
|
|
||||||
</Table>
|
|
||||||
</ScrollArea>
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,125 +0,0 @@
|
||||||
import { useState } from 'react'
|
|
||||||
import {
|
|
||||||
Paper, Table, Badge, Group, Text, Pagination, Loader, Center, Box, Stack,
|
|
||||||
} from '@mantine/core'
|
|
||||||
import NotificationDetailsModal from './NotificationDetailsModal'
|
|
||||||
import { useNotifications } from '@/features/notifications/hooks/useNotifications'
|
|
||||||
|
|
||||||
const LIMIT = 20
|
|
||||||
|
|
||||||
const STATUS_LABELS: Record<string, { label: string; color: string }> = {
|
|
||||||
pending: { label: 'В очереди', color: 'gray' },
|
|
||||||
sending: { label: 'Отправляется', color: 'blue' },
|
|
||||||
completed: { label: 'Завершено', color: 'green' },
|
|
||||||
failed: { label: 'Ошибка', color: 'red' },
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function NotificationsHistoryTable() {
|
|
||||||
const [page, setPage] = useState(1)
|
|
||||||
const [selectedId, setSelectedId] = useState<number | null>(null)
|
|
||||||
|
|
||||||
const { data, isLoading } = useNotifications({
|
|
||||||
offset: (page - 1) * LIMIT,
|
|
||||||
limit: LIMIT,
|
|
||||||
})
|
|
||||||
|
|
||||||
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Stack gap="md">
|
|
||||||
<Paper withBorder>
|
|
||||||
{isLoading ? (
|
|
||||||
<Center p={60}>
|
|
||||||
<Loader />
|
|
||||||
</Center>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Table striped highlightOnHover>
|
|
||||||
<Table.Thead>
|
|
||||||
<Table.Tr>
|
|
||||||
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
|
||||||
<Table.Th>Заголовок</Table.Th>
|
|
||||||
<Table.Th style={{ width: 120 }}>Статус</Table.Th>
|
|
||||||
<Table.Th style={{ width: 160 }}>Доставлено</Table.Th>
|
|
||||||
<Table.Th style={{ width: 160 }}>Дата отправки</Table.Th>
|
|
||||||
</Table.Tr>
|
|
||||||
</Table.Thead>
|
|
||||||
<Table.Tbody>
|
|
||||||
{data?.data?.length === 0 ? (
|
|
||||||
<Table.Tr>
|
|
||||||
<Table.Td colSpan={5}>
|
|
||||||
<Center p={40}>
|
|
||||||
<Text c="dimmed">Уведомления не отправлялись</Text>
|
|
||||||
</Center>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
) : (
|
|
||||||
(data?.data || []).map((n) => {
|
|
||||||
const statusInfo = STATUS_LABELS[n.status || ''] || {
|
|
||||||
label: n.status || '—',
|
|
||||||
color: 'gray',
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<Table.Tr
|
|
||||||
key={n.id}
|
|
||||||
style={{ cursor: 'pointer' }}
|
|
||||||
onClick={() => setSelectedId(n.id!)}
|
|
||||||
>
|
|
||||||
<Table.Td>{n.id}</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text fw={500}>{n.title}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Badge color={statusInfo.color} variant="light">
|
|
||||||
{statusInfo.label}
|
|
||||||
</Badge>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Group gap={6}>
|
|
||||||
<Badge color="green" variant="light" size="sm">
|
|
||||||
{n.sent_count ?? 0}
|
|
||||||
</Badge>
|
|
||||||
{(n.failed_count ?? 0) > 0 && (
|
|
||||||
<Badge color="red" variant="light" size="sm">
|
|
||||||
{n.failed_count} ошибок
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
<Text size="xs" c="dimmed">
|
|
||||||
из {n.total_count ?? 0}
|
|
||||||
</Text>
|
|
||||||
</Group>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" c="dimmed">
|
|
||||||
{n.sent_at ? new Date(n.sent_at).toLocaleString('ru-RU') : '—'}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
)
|
|
||||||
})
|
|
||||||
)}
|
|
||||||
</Table.Tbody>
|
|
||||||
</Table>
|
|
||||||
|
|
||||||
{totalPages > 1 && (
|
|
||||||
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">
|
|
||||||
Страница {page} из {totalPages}
|
|
||||||
</Text>
|
|
||||||
<Pagination value={page} onChange={setPage} total={totalPages} withEdges />
|
|
||||||
</Group>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<NotificationDetailsModal
|
|
||||||
notificationId={selectedId}
|
|
||||||
opened={selectedId !== null}
|
|
||||||
onClose={() => setSelectedId(null)}
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,446 +0,0 @@
|
||||||
import { useState, useMemo } from 'react'
|
|
||||||
import {
|
|
||||||
Paper, Stack, TextInput, Button, Group, MultiSelect, Checkbox,
|
|
||||||
Text, FileButton, Image, ActionIcon, Divider, Alert, Badge, Grid,
|
|
||||||
ThemeIcon,
|
|
||||||
} from '@mantine/core'
|
|
||||||
import {
|
|
||||||
IconPhoto, IconX, IconSend, IconAlertCircle, IconUsers,
|
|
||||||
IconUser, IconMask, IconBuilding, IconTag, IconEye, IconMessage,
|
|
||||||
} from '@tabler/icons-react'
|
|
||||||
import { RichTextEditor, Link } from '@mantine/tiptap'
|
|
||||||
import { useEditor } from '@tiptap/react'
|
|
||||||
import StarterKit from '@tiptap/starter-kit'
|
|
||||||
import Underline from '@tiptap/extension-underline'
|
|
||||||
import { useDebouncedValue } from '@mantine/hooks'
|
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
|
||||||
import { useDepartments } from '@/features/departments/hooks/useDepartments'
|
|
||||||
import { useAllRoles } from '@/features/roles/hooks/useAllRoles'
|
|
||||||
import { useCreateNotification } from '@/features/notifications/hooks/useNotifications.ts'
|
|
||||||
import { convertHtmlToTelegram } from '@/features/notifications/utils/telegramHtml.ts'
|
|
||||||
import { notifications } from '@mantine/notifications'
|
|
||||||
import { Modal } from '@mantine/core'
|
|
||||||
import '@mantine/tiptap/styles.css'
|
|
||||||
|
|
||||||
const ROLE_TYPE_OPTIONS = [
|
|
||||||
{ value: 'director', label: 'Директора', icon: '👔' },
|
|
||||||
{ value: 'approver', label: 'Согласующие', icon: '✅' },
|
|
||||||
{ value: 'observer', label: 'Наблюдатели', icon: '👀' },
|
|
||||||
{ value: 'executor', label: 'Исполнители', icon: '⚙️' },
|
|
||||||
{ value: 'controller', label: 'Контролёры', icon: '🎯' },
|
|
||||||
]
|
|
||||||
|
|
||||||
export default function SendNotificationForm() {
|
|
||||||
const [title, setTitle] = useState('')
|
|
||||||
const [userSearch, setUserSearch] = useState('')
|
|
||||||
const [debouncedUserSearch] = useDebouncedValue(userSearch, 300)
|
|
||||||
|
|
||||||
const [selectedUserIds, setSelectedUserIds] = useState<string[]>([])
|
|
||||||
const [selectedRoleIds, setSelectedRoleIds] = useState<string[]>([])
|
|
||||||
const [selectedRoleFlags, setSelectedRoleFlags] = useState<string[]>([])
|
|
||||||
const [selectedDepartmentIds, setSelectedDepartmentIds] = useState<string[]>([])
|
|
||||||
|
|
||||||
const [photoBase64, setPhotoBase64] = useState<string | null>(null)
|
|
||||||
const [photoFileName, setPhotoFileName] = useState<string | null>(null)
|
|
||||||
const [photoPreviewUrl, setPhotoPreviewUrl] = useState<string | null>(null)
|
|
||||||
|
|
||||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
|
||||||
|
|
||||||
const { data: usersData } = useUsers({
|
|
||||||
limit: 50,
|
|
||||||
...(debouncedUserSearch && { full_name: debouncedUserSearch }),
|
|
||||||
})
|
|
||||||
const { data: roles = [] } = useAllRoles()
|
|
||||||
const { data: departmentsResponse } = useDepartments({ limit: 1000 })
|
|
||||||
const departments = departmentsResponse?.data || []
|
|
||||||
|
|
||||||
const createNotification = useCreateNotification()
|
|
||||||
|
|
||||||
const editor = useEditor({
|
|
||||||
extensions: [StarterKit, Underline, Link],
|
|
||||||
content: '',
|
|
||||||
})
|
|
||||||
|
|
||||||
const userOptions = useMemo(
|
|
||||||
() => (usersData?.data || []).map((u) => ({
|
|
||||||
value: String(u.id),
|
|
||||||
label: u.full_name + (u.username ? ` (@${u.username})` : ''),
|
|
||||||
})),
|
|
||||||
[usersData],
|
|
||||||
)
|
|
||||||
const roleOptions = useMemo(
|
|
||||||
() => roles.map((r) => ({ value: String(r.id), label: r.name })),
|
|
||||||
[roles],
|
|
||||||
)
|
|
||||||
const departmentOptions = useMemo(
|
|
||||||
() => departments.map((d) => ({ value: String(d.id), label: d.name })),
|
|
||||||
[departments],
|
|
||||||
)
|
|
||||||
|
|
||||||
const MAX_ASPECT_RATIO = 20
|
|
||||||
|
|
||||||
const handlePhotoChange = (file: File | null) => {
|
|
||||||
if (!file) {
|
|
||||||
setPhotoBase64(null)
|
|
||||||
setPhotoFileName(null)
|
|
||||||
setPhotoPreviewUrl(null)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const reader = new FileReader()
|
|
||||||
reader.onload = () => {
|
|
||||||
const result = reader.result as string
|
|
||||||
const img = new window.Image()
|
|
||||||
img.onload = () => {
|
|
||||||
const ratio = Math.max(img.width, img.height) / Math.min(img.width, img.height)
|
|
||||||
const sumDimensions = img.width + img.height
|
|
||||||
if (ratio > MAX_ASPECT_RATIO || sumDimensions > 10000) {
|
|
||||||
notifications.show({
|
|
||||||
title: 'Некорректное изображение',
|
|
||||||
message: `Telegram не примет это фото: слишком вытянутые пропорции (${img.width}×${img.height}).`,
|
|
||||||
color: 'red',
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setPhotoBase64(result.split(',')[1] || '')
|
|
||||||
setPhotoFileName(file.name)
|
|
||||||
setPhotoPreviewUrl(result)
|
|
||||||
}
|
|
||||||
img.src = result
|
|
||||||
}
|
|
||||||
reader.readAsDataURL(file)
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasAnyTarget =
|
|
||||||
selectedUserIds.length > 0 ||
|
|
||||||
selectedRoleIds.length > 0 ||
|
|
||||||
selectedRoleFlags.length > 0 ||
|
|
||||||
selectedDepartmentIds.length > 0
|
|
||||||
|
|
||||||
const messageHtml = editor?.getHTML() ?? ''
|
|
||||||
const messageText = editor?.getText() ?? ''
|
|
||||||
const isMessageEmpty = editor?.isEmpty ?? true
|
|
||||||
|
|
||||||
const canSubmit = title.trim().length > 0 && !isMessageEmpty && hasAnyTarget
|
|
||||||
|
|
||||||
const totalCriteria =
|
|
||||||
(selectedUserIds.length > 0 ? 1 : 0) +
|
|
||||||
(selectedRoleIds.length > 0 ? 1 : 0) +
|
|
||||||
(selectedRoleFlags.length > 0 ? 1 : 0) +
|
|
||||||
(selectedDepartmentIds.length > 0 ? 1 : 0)
|
|
||||||
|
|
||||||
const doSubmit = () => {
|
|
||||||
setConfirmOpen(false)
|
|
||||||
createNotification.mutate(
|
|
||||||
{
|
|
||||||
title: title.trim(),
|
|
||||||
message_html: convertHtmlToTelegram(messageHtml),
|
|
||||||
photo_base64: photoBase64 || undefined,
|
|
||||||
photo_file_name: photoFileName || undefined,
|
|
||||||
targets: {
|
|
||||||
user_ids: selectedUserIds.map(Number),
|
|
||||||
role_ids: selectedRoleIds.map(Number),
|
|
||||||
role_type_flags: selectedRoleFlags,
|
|
||||||
department_ids: selectedDepartmentIds.map(Number),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onSuccess: () => {
|
|
||||||
setTitle('')
|
|
||||||
editor?.commands.clearContent()
|
|
||||||
setSelectedUserIds([])
|
|
||||||
setSelectedRoleIds([])
|
|
||||||
setSelectedRoleFlags([])
|
|
||||||
setSelectedDepartmentIds([])
|
|
||||||
handlePhotoChange(null)
|
|
||||||
notifications.show({
|
|
||||||
title: 'Успешно',
|
|
||||||
message: 'Уведомление отправлено',
|
|
||||||
color: 'green',
|
|
||||||
})
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Paper withBorder p={{ base: 'md', md: 'xl' }} radius="md">
|
|
||||||
{/* ===== HEADER ===== */}
|
|
||||||
<Group justify="space-between" align="center" mb="lg">
|
|
||||||
<Group gap="sm">
|
|
||||||
<ThemeIcon size="lg" radius="md" variant="light" color="blue">
|
|
||||||
<IconMessage size={20} />
|
|
||||||
</ThemeIcon>
|
|
||||||
<div>
|
|
||||||
<Text size="xl" fw={700}>Новая рассылка</Text>
|
|
||||||
<Text size="xs" c="dimmed">Отправится через Telegram Bot</Text>
|
|
||||||
</div>
|
|
||||||
</Group>
|
|
||||||
{totalCriteria > 0 && (
|
|
||||||
<Badge size="lg" variant="light" color="blue" radius="sm">
|
|
||||||
{totalCriteria} {totalCriteria === 1 ? 'критерий' : 'критериев'}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Grid gap="xl">
|
|
||||||
<Grid.Col span={{ base: 12, lg: 7 }}>
|
|
||||||
<Stack gap="lg">
|
|
||||||
<TextInput
|
|
||||||
label="Заголовок рассылки"
|
|
||||||
description="Только для админки, в Telegram не отправляется"
|
|
||||||
placeholder="Плановые работы 15 июля"
|
|
||||||
value={title}
|
|
||||||
onChange={(e) => setTitle(e.currentTarget.value)}
|
|
||||||
required
|
|
||||||
size="md"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Редактор */}
|
|
||||||
<Stack gap={6}>
|
|
||||||
<Group justify="space-between" align="center">
|
|
||||||
<Text size="sm" fw={500}>Текст сообщения</Text>
|
|
||||||
{!isMessageEmpty && (
|
|
||||||
<Badge size="xs" variant="light" color="green" leftSection={<IconEye size={10} />}>
|
|
||||||
Заполнено
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
<RichTextEditor editor={editor} style={{ minHeight: 320 }}>
|
|
||||||
<RichTextEditor.Toolbar sticky stickyOffset={0}>
|
|
||||||
<RichTextEditor.ControlsGroup>
|
|
||||||
<RichTextEditor.Bold />
|
|
||||||
<RichTextEditor.Italic />
|
|
||||||
<RichTextEditor.Underline />
|
|
||||||
<RichTextEditor.Strikethrough />
|
|
||||||
</RichTextEditor.ControlsGroup>
|
|
||||||
<RichTextEditor.ControlsGroup>
|
|
||||||
<RichTextEditor.Code />
|
|
||||||
<RichTextEditor.CodeBlock />
|
|
||||||
<RichTextEditor.ClearFormatting />
|
|
||||||
</RichTextEditor.ControlsGroup>
|
|
||||||
<RichTextEditor.ControlsGroup>
|
|
||||||
<RichTextEditor.Link />
|
|
||||||
<RichTextEditor.Unlink />
|
|
||||||
</RichTextEditor.ControlsGroup>
|
|
||||||
</RichTextEditor.Toolbar>
|
|
||||||
<RichTextEditor.Content style={{ minHeight: 220 }} />
|
|
||||||
</RichTextEditor>
|
|
||||||
<Text size="xs" c="dimmed">
|
|
||||||
<b>жирный</b> · <i>курсив</i> · <u>подчёркнутый</u> · <s>зачёркнутый</s> · <code>код</code> · ссылки — остальное Telegram не отобразит
|
|
||||||
</Text>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
{/* Фото */}
|
|
||||||
<Stack gap={6}>
|
|
||||||
<Text size="sm" fw={500}>Фото (опционально)</Text>
|
|
||||||
{photoPreviewUrl ? (
|
|
||||||
<Group gap="sm">
|
|
||||||
<Paper withBorder p={4} radius="sm">
|
|
||||||
<Image src={photoPreviewUrl} h={90} w={90} radius="sm" fit="cover" />
|
|
||||||
</Paper>
|
|
||||||
<Stack gap={2} style={{ flex: 1 }}>
|
|
||||||
<Text size="sm" fw={500} lineClamp={1}>{photoFileName}</Text>
|
|
||||||
<Text size="xs" c="dimmed">Готово к отправке</Text>
|
|
||||||
</Stack>
|
|
||||||
<ActionIcon
|
|
||||||
color="red"
|
|
||||||
variant="light"
|
|
||||||
onClick={() => handlePhotoChange(null)}
|
|
||||||
>
|
|
||||||
<IconX size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Group>
|
|
||||||
) : (
|
|
||||||
<FileButton onChange={handlePhotoChange} accept="image/png,image/jpeg,image/webp">
|
|
||||||
{(props) => (
|
|
||||||
<Button {...props} variant="light" leftSection={<IconPhoto size={16} />}>
|
|
||||||
Прикрепить фото
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</FileButton>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</Stack>
|
|
||||||
</Grid.Col>
|
|
||||||
|
|
||||||
{/* ===== ПРАВАЯ КОЛОНКА: ПОЛУЧАТЕЛИ + ПРЕВЬЮ ===== */}
|
|
||||||
<Grid.Col span={{ base: 12, lg: 5 }}>
|
|
||||||
<Stack gap="lg">
|
|
||||||
{/* Получатели */}
|
|
||||||
<Paper withBorder p="md" radius="md">
|
|
||||||
<Group justify="space-between" mb="md">
|
|
||||||
<Group gap="xs">
|
|
||||||
<ThemeIcon size="sm" variant="light" color="violet">
|
|
||||||
<IconUsers size={14} />
|
|
||||||
</ThemeIcon>
|
|
||||||
<Text size="sm" fw={600}>Получатели</Text>
|
|
||||||
</Group>
|
|
||||||
{hasAnyTarget && (
|
|
||||||
<Badge size="xs" variant="light" color="violet">
|
|
||||||
Настроено
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Stack gap="md">
|
|
||||||
<MultiSelect
|
|
||||||
label={
|
|
||||||
<Group gap={4}>
|
|
||||||
<IconUser size={14} />
|
|
||||||
<Text size="sm" span>Конкретные пользователи</Text>
|
|
||||||
{selectedUserIds.length > 0 && (
|
|
||||||
<Badge size="xs" variant="filled" circle>{selectedUserIds.length}</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
placeholder="Начните вводить имя..."
|
|
||||||
data={userOptions}
|
|
||||||
value={selectedUserIds}
|
|
||||||
onChange={setSelectedUserIds}
|
|
||||||
searchable
|
|
||||||
searchValue={userSearch}
|
|
||||||
onSearchChange={setUserSearch}
|
|
||||||
clearable
|
|
||||||
nothingFoundMessage="Никого не найдено"
|
|
||||||
size="xs"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<MultiSelect
|
|
||||||
label={
|
|
||||||
<Group gap={4}>
|
|
||||||
<IconMask size={14} />
|
|
||||||
<Text size="sm" span>Роли</Text>
|
|
||||||
{selectedRoleIds.length > 0 && (
|
|
||||||
<Badge size="xs" variant="filled" circle>{selectedRoleIds.length}</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
placeholder="Выберите роли"
|
|
||||||
data={roleOptions}
|
|
||||||
value={selectedRoleIds}
|
|
||||||
onChange={setSelectedRoleIds}
|
|
||||||
searchable
|
|
||||||
clearable
|
|
||||||
size="xs"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Stack gap={6}>
|
|
||||||
<Group gap={4}>
|
|
||||||
<IconTag size={14} />
|
|
||||||
<Text size="sm" span>Тип роли</Text>
|
|
||||||
{selectedRoleFlags.length > 0 && (
|
|
||||||
<Badge size="xs" variant="filled" circle>{selectedRoleFlags.length}</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
<Checkbox.Group value={selectedRoleFlags} onChange={setSelectedRoleFlags}>
|
|
||||||
<Stack gap={6}>
|
|
||||||
{ROLE_TYPE_OPTIONS.map((opt) => (
|
|
||||||
<Checkbox
|
|
||||||
key={opt.value}
|
|
||||||
value={opt.value}
|
|
||||||
label={
|
|
||||||
<Group gap={6}>
|
|
||||||
<Text size="sm">{opt.icon}</Text>
|
|
||||||
<Text size="sm">{opt.label}</Text>
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Checkbox.Group>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<MultiSelect
|
|
||||||
label={
|
|
||||||
<Group gap={4}>
|
|
||||||
<IconBuilding size={14} />
|
|
||||||
<Text size="sm" span>Отделы</Text>
|
|
||||||
{selectedDepartmentIds.length > 0 && (
|
|
||||||
<Badge size="xs" variant="filled" circle>{selectedDepartmentIds.length}</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
}
|
|
||||||
placeholder="Выберите отделы"
|
|
||||||
data={departmentOptions}
|
|
||||||
value={selectedDepartmentIds}
|
|
||||||
onChange={setSelectedDepartmentIds}
|
|
||||||
searchable
|
|
||||||
clearable
|
|
||||||
size="xs"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{!hasAnyTarget && (
|
|
||||||
<Alert color="blue" variant="light" icon={<IconAlertCircle size={16} />} p="xs">
|
|
||||||
<Text size="xs">Выберите хотя бы один способ определения получателей</Text>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{/* Кнопка отправки */}
|
|
||||||
<Button
|
|
||||||
fullWidth
|
|
||||||
size="md"
|
|
||||||
leftSection={<IconSend size={18} />}
|
|
||||||
onClick={() => setConfirmOpen(true)}
|
|
||||||
loading={createNotification.isPending}
|
|
||||||
disabled={!canSubmit}
|
|
||||||
>
|
|
||||||
Отправить уведомление
|
|
||||||
</Button>
|
|
||||||
</Stack>
|
|
||||||
</Grid.Col>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
{/* ===== МОДАЛКА ПОДТВЕРЖДЕНИЯ ===== */}
|
|
||||||
<Modal
|
|
||||||
opened={confirmOpen}
|
|
||||||
onClose={() => setConfirmOpen(false)}
|
|
||||||
title="Подтверждение отправки"
|
|
||||||
centered
|
|
||||||
>
|
|
||||||
<Stack gap="md">
|
|
||||||
<Text size="sm">
|
|
||||||
Отправить уведомление <b>«{title.trim()}»</b>?
|
|
||||||
</Text>
|
|
||||||
<Paper withBorder p="sm" radius="sm">
|
|
||||||
<Stack gap={4}>
|
|
||||||
{selectedUserIds.length > 0 && (
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="xs" c="dimmed">Пользователей</Text>
|
|
||||||
<Text size="sm" fw={500}>{selectedUserIds.length}</Text>
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
{selectedRoleIds.length > 0 && (
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="xs" c="dimmed">Ролей</Text>
|
|
||||||
<Text size="sm" fw={500}>{selectedRoleIds.length}</Text>
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
{selectedRoleFlags.length > 0 && (
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="xs" c="dimmed">Типов ролей</Text>
|
|
||||||
<Text size="sm" fw={500}>{selectedRoleFlags.length}</Text>
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
{selectedDepartmentIds.length > 0 && (
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="xs" c="dimmed">Отделов</Text>
|
|
||||||
<Text size="sm" fw={500}>{selectedDepartmentIds.length}</Text>
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
<Group justify="flex-end" gap="sm" mt="xs">
|
|
||||||
<Button variant="default" onClick={() => setConfirmOpen(false)}>
|
|
||||||
Отмена
|
|
||||||
</Button>
|
|
||||||
<Button color="blue" onClick={doSubmit} loading={createNotification.isPending}>
|
|
||||||
Отправить
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</Modal>
|
|
||||||
</Paper>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -38,7 +38,6 @@ export default function RolesPage() {
|
||||||
...(roleTypeFilter === 'approver' && { is_approver: true }),
|
...(roleTypeFilter === 'approver' && { is_approver: true }),
|
||||||
...(roleTypeFilter === 'observer' && { is_observer: true }),
|
...(roleTypeFilter === 'observer' && { is_observer: true }),
|
||||||
...(roleTypeFilter === 'executor' && { is_executor: true }),
|
...(roleTypeFilter === 'executor' && { is_executor: true }),
|
||||||
...(roleTypeFilter === 'controller' && { is_controller: true }), // 🆕
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const deleteRole = useDeleteRole()
|
const deleteRole = useDeleteRole()
|
||||||
|
|
@ -135,17 +134,6 @@ export default function RolesPage() {
|
||||||
>
|
>
|
||||||
Наблюдатели
|
Наблюдатели
|
||||||
</Badge>
|
</Badge>
|
||||||
<Badge
|
|
||||||
variant={roleTypeFilter === 'controller' ? 'filled' : 'light'}
|
|
||||||
color="teal"
|
|
||||||
style={{ cursor: 'pointer' }}
|
|
||||||
onClick={() => {
|
|
||||||
setRoleTypeFilter(roleTypeFilter === 'controller' ? null : 'controller')
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Контролёры
|
|
||||||
</Badge>
|
|
||||||
<Badge
|
<Badge
|
||||||
variant={roleTypeFilter === 'executor' ? 'filled' : 'light'}
|
variant={roleTypeFilter === 'executor' ? 'filled' : 'light'}
|
||||||
color="orange"
|
color="orange"
|
||||||
|
|
@ -205,24 +193,28 @@ export default function RolesPage() {
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Group gap={4}>
|
<Group gap={4}>
|
||||||
{role.is_director && (
|
{role.is_director && (
|
||||||
<Badge size="xs" color="violet" variant="light">Директор</Badge>
|
<Badge size="xs" color="violet" variant="light">
|
||||||
|
Директор
|
||||||
|
</Badge>
|
||||||
)}
|
)}
|
||||||
{role.is_approver && (
|
{role.is_approver && (
|
||||||
<Badge size="xs" color="blue" variant="light">Согласующий</Badge>
|
<Badge size="xs" color="blue" variant="light">
|
||||||
|
Согласующий
|
||||||
|
</Badge>
|
||||||
)}
|
)}
|
||||||
{role.is_observer && (
|
{role.is_observer && (
|
||||||
<Badge size="xs" color="green" variant="light">Наблюдатель</Badge>
|
<Badge size="xs" color="green" variant="light">
|
||||||
|
Наблюдатель
|
||||||
|
</Badge>
|
||||||
)}
|
)}
|
||||||
{role.is_executor && (
|
{role.is_executor && (
|
||||||
<Badge size="xs" color="orange" variant="light">Исполнитель</Badge>
|
<Badge size="xs" color="orange" variant="light">
|
||||||
|
Исполнитель
|
||||||
|
</Badge>
|
||||||
)}
|
)}
|
||||||
{role.is_controller && (
|
{!role.is_director && !role.is_approver && !role.is_observer && !role.is_executor && (
|
||||||
<Badge size="xs" color="teal" variant="light">Контролёр</Badge>
|
<Text size="xs" c="dimmed">—</Text>
|
||||||
)}
|
)}
|
||||||
{!role.is_director && !role.is_approver && !role.is_observer &&
|
|
||||||
!role.is_executor && !role.is_controller && (
|
|
||||||
<Text size="xs" c="dimmed">—</Text>
|
|
||||||
)}
|
|
||||||
</Group>
|
</Group>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,6 @@ export default function RoleEditModal({
|
||||||
is_approver: false,
|
is_approver: false,
|
||||||
is_observer: false,
|
is_observer: false,
|
||||||
is_executor: false,
|
is_executor: false,
|
||||||
is_controller: false,
|
|
||||||
},
|
},
|
||||||
validate: {
|
validate: {
|
||||||
name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
|
name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
|
||||||
|
|
@ -72,7 +71,6 @@ export default function RoleEditModal({
|
||||||
is_approver: role.is_approver ?? false,
|
is_approver: role.is_approver ?? false,
|
||||||
is_observer: role.is_observer ?? false,
|
is_observer: role.is_observer ?? false,
|
||||||
is_executor: role.is_executor ?? false,
|
is_executor: role.is_executor ?? false,
|
||||||
is_controller: role.is_controller ?? false,
|
|
||||||
})
|
})
|
||||||
} else if (!isEditMode) {
|
} else if (!isEditMode) {
|
||||||
form.reset()
|
form.reset()
|
||||||
|
|
@ -171,18 +169,6 @@ export default function RoleEditModal({
|
||||||
onChange={(e) => form.setFieldValue('is_executor', e.currentTarget.checked)}
|
onChange={(e) => form.setFieldValue('is_executor', e.currentTarget.checked)}
|
||||||
color="orange"
|
color="orange"
|
||||||
/>
|
/>
|
||||||
<Switch
|
|
||||||
label="Контролёр"
|
|
||||||
description={
|
|
||||||
form.values.is_observer
|
|
||||||
? "Пользователь с этой ролью видит расширенный контроль по заявкам"
|
|
||||||
: "Доступно только вместе с ролью «Наблюдатель»"
|
|
||||||
}
|
|
||||||
checked={form.values.is_controller}
|
|
||||||
disabled={!form.values.is_observer}
|
|
||||||
onChange={(e) => form.setFieldValue('is_controller', e.currentTarget.checked)}
|
|
||||||
color="teal"
|
|
||||||
/>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,411 +0,0 @@
|
||||||
import { useState, useEffect, useRef } from 'react'
|
|
||||||
import {
|
|
||||||
Paper,
|
|
||||||
Table,
|
|
||||||
Badge,
|
|
||||||
Group,
|
|
||||||
ActionIcon,
|
|
||||||
Button,
|
|
||||||
Text,
|
|
||||||
Loader,
|
|
||||||
Center,
|
|
||||||
Tooltip,
|
|
||||||
Stack,
|
|
||||||
Box,
|
|
||||||
Tabs,
|
|
||||||
Alert,
|
|
||||||
Modal,
|
|
||||||
Image,
|
|
||||||
TextInput,
|
|
||||||
Checkbox
|
|
||||||
} from '@mantine/core'
|
|
||||||
import {
|
|
||||||
IconTrash,
|
|
||||||
IconPlus,
|
|
||||||
IconCircleCheck,
|
|
||||||
IconCircleX,
|
|
||||||
IconBrandTelegram,
|
|
||||||
IconBrandWhatsapp,
|
|
||||||
IconMessageCircle,
|
|
||||||
IconInfoCircle,
|
|
||||||
IconEdit,
|
|
||||||
IconMessage2
|
|
||||||
} from '@tabler/icons-react'
|
|
||||||
import { notifications } from '@mantine/notifications'
|
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
|
||||||
import dayjs from 'dayjs'
|
|
||||||
import 'dayjs/locale/ru'
|
|
||||||
import { formatMsk } from '@/utils/date.ts'
|
|
||||||
|
|
||||||
// Импорты Telegram
|
|
||||||
import AddManagerModal from './components/AddManagerModal'
|
|
||||||
import DeleteManagerModal from "./components/DeleteManagersModal"
|
|
||||||
import { useDeleteTelegramManager, useTelegramManagers } from "@/features/telegramManagers/useTelegramManagers"
|
|
||||||
import { telegramManagersApi } from '@/api/telegramManagers'
|
|
||||||
|
|
||||||
// Импорты WhatsApp
|
|
||||||
import { useDeleteWhatsAppManager, useWhatsAppManagers } from '@/features/whatsappManagers/useWhatsappManagers'
|
|
||||||
import { whatsappManagersApi } from "@/api/whatsappManagers.ts"
|
|
||||||
import {ManagerSession} from "@/types/api.ts";
|
|
||||||
|
|
||||||
dayjs.locale('ru')
|
|
||||||
|
|
||||||
// ── ПЕРЕИСПОЛЬЗУЕМЫЕ КОМПОНЕНТЫ ─────────────────────────────────────────────
|
|
||||||
|
|
||||||
interface ManagersTableProps {
|
|
||||||
managers: ManagerSession[] | undefined;
|
|
||||||
isLoading: boolean;
|
|
||||||
onDelete: (manager: ManagerSession) => void;
|
|
||||||
onEdit: (manager: ManagerSession) => void;
|
|
||||||
onViewChats: (manager: ManagerSession) => void;
|
|
||||||
emptyText?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ManagersTable({ managers, isLoading, onDelete, onEdit, onViewChats, emptyText = "Менеджеры не найдены" }: ManagersTableProps) {
|
|
||||||
if (isLoading) return <Center p={60}><Loader /></Center>;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Table striped highlightOnHover>
|
|
||||||
<Table.Thead>
|
|
||||||
<Table.Tr>
|
|
||||||
<Table.Th>ID</Table.Th>
|
|
||||||
<Table.Th>Имя</Table.Th>
|
|
||||||
<Table.Th>Телефон</Table.Th>
|
|
||||||
<Table.Th>Статус сессии</Table.Th>
|
|
||||||
<Table.Th>Последнее входящее</Table.Th>
|
|
||||||
<Table.Th>Последнее исходящее</Table.Th>
|
|
||||||
<Table.Th style={{ width: 140 }}>Действия</Table.Th>
|
|
||||||
</Table.Tr>
|
|
||||||
</Table.Thead>
|
|
||||||
<Table.Tbody>
|
|
||||||
{!managers || managers.length === 0 ? (
|
|
||||||
<Table.Tr>
|
|
||||||
<Table.Td colSpan={7}>
|
|
||||||
<Center p={40}><Text c="dimmed">{emptyText}</Text></Center>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
) : (
|
|
||||||
managers.map((mgr) => (
|
|
||||||
<Table.Tr key={mgr.manager_id}>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" style={{ wordBreak: 'break-all', maxWidth: 120 }}>{mgr.manager_id}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td><Text fw={500}>{mgr.name}</Text></Table.Td>
|
|
||||||
<Table.Td><Text size="sm" ff="monospace">+{mgr.phone}</Text></Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Badge
|
|
||||||
color={mgr.is_online ? 'green' : 'red'}
|
|
||||||
variant="light"
|
|
||||||
leftSection={mgr.is_online ? <IconCircleCheck size={12} /> : <IconCircleX size={12} />}
|
|
||||||
>
|
|
||||||
{mgr.is_online ? 'Онлайн' : 'Оффлайн'}
|
|
||||||
</Badge>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" c="dimmed">{mgr.last_incoming_message_at ? formatMsk(mgr.last_incoming_message_at) : '—'}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" c="dimmed">{mgr.last_outgoing_message_at ? formatMsk(mgr.last_outgoing_message_at) : '—'}</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Group gap="xs" wrap="nowrap">
|
|
||||||
<Tooltip label="Смотреть чаты">
|
|
||||||
<ActionIcon variant="light" color="blue" onClick={() => onViewChats(mgr)}>
|
|
||||||
<IconMessage2 size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip label="Редактировать имя">
|
|
||||||
<ActionIcon variant="light" color="orange" onClick={() => onEdit(mgr)}>
|
|
||||||
<IconEdit size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip label="Удалить сессию">
|
|
||||||
<ActionIcon variant="light" color="red" onClick={() => onDelete(mgr)}>
|
|
||||||
<IconTrash size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
</Group>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Table.Tbody>
|
|
||||||
</Table>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function EditManagerModal({ opened, onClose, manager, onSave }: { opened: boolean, onClose: () => void, manager: ManagerSession | null, onSave: (name: string) => Promise<void> }) {
|
|
||||||
const [name, setName] = useState('')
|
|
||||||
const [loading, setLoading] = useState(false)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (manager) setName(manager.name)
|
|
||||||
}, [manager])
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault()
|
|
||||||
setLoading(true)
|
|
||||||
await onSave(name)
|
|
||||||
setLoading(false)
|
|
||||||
onClose()
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal opened={opened} onClose={onClose} title="Редактировать сессию" size="sm">
|
|
||||||
<form onSubmit={handleSubmit}>
|
|
||||||
<Stack gap="md">
|
|
||||||
<TextInput label="Имя менеджера" value={name} onChange={(e) => setName(e.currentTarget.value)} required />
|
|
||||||
<TextInput label="Номер телефона" value={`+${manager?.phone || ''}`} disabled />
|
|
||||||
<Group justify="flex-end" mt="md">
|
|
||||||
<Button variant="default" onClick={onClose}>Отмена</Button>
|
|
||||||
<Button type="submit" loading={loading} color="blue">Сохранить</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</form>
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
// ── ВКЛАДКА TELEGRAM ────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function TelegramTab() {
|
|
||||||
const [createModalOpened, setCreateModalOpened] = useState(false)
|
|
||||||
const [editingManager, setEditingManager] = useState<ManagerSession | null>(null)
|
|
||||||
const [deletingManager, setDeletingManager] = useState<ManagerSession | null>(null)
|
|
||||||
|
|
||||||
const { data: managers, isLoading, isFetching } = useTelegramManagers()
|
|
||||||
const deleteManager = useDeleteTelegramManager()
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
|
|
||||||
const confirmDelete = async (wipeData: boolean) => {
|
|
||||||
if (deletingManager) {
|
|
||||||
await deleteManager.mutateAsync({ managerId: Number(deletingManager.manager_id), wipeData })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleSaveName = async (newName: string) => {
|
|
||||||
if (!editingManager) return
|
|
||||||
try {
|
|
||||||
await telegramManagersApi.updateName(Number(editingManager.manager_id), newName)
|
|
||||||
notifications.show({ title: 'Успешно', message: 'Имя обновлено', color: 'green' })
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] })
|
|
||||||
} catch (e) {
|
|
||||||
notifications.show({ title: 'Ошибка', message: 'Не удалось обновить имя', color: 'red' })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleViewChats = (mgr: ManagerSession) => {
|
|
||||||
notifications.show({ title: 'Чаты', message: `Открытие переписки для ${mgr.name}...`, color: 'blue' })
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Stack gap="md" mt="md">
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">Управление активными сессиями пользовательских Telegram аккаунтов</Text>
|
|
||||||
<Button leftSection={<IconPlus size={16} />} onClick={() => setCreateModalOpened(true)}>Подключить Telegram</Button>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Paper withBorder>
|
|
||||||
<ManagersTable
|
|
||||||
managers={managers}
|
|
||||||
isLoading={isLoading}
|
|
||||||
onDelete={setDeletingManager}
|
|
||||||
onEdit={setEditingManager}
|
|
||||||
onViewChats={handleViewChats}
|
|
||||||
/>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{isFetching && !isLoading && <Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}><Loader size="xs" /></Box>}
|
|
||||||
|
|
||||||
<AddManagerModal opened={createModalOpened} onClose={() => setCreateModalOpened(false)} />
|
|
||||||
|
|
||||||
<EditManagerModal
|
|
||||||
opened={!!editingManager}
|
|
||||||
onClose={() => setEditingManager(null)}
|
|
||||||
manager={editingManager}
|
|
||||||
onSave={handleSaveName}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<DeleteManagerModal
|
|
||||||
opened={!!deletingManager}
|
|
||||||
onClose={() => setDeletingManager(null)}
|
|
||||||
manager={deletingManager}
|
|
||||||
onConfirm={confirmDelete}
|
|
||||||
title="Отключение Telegram"
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function AddWhatsappModal({ opened, onClose }: { opened: boolean, onClose: () => void }) {
|
|
||||||
const [qrData, setQrData] = useState<{ token: string, img: string } | null>(null)
|
|
||||||
const pollingIntervalRef = useRef<number | null>(null)
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
|
|
||||||
const stopPolling = () => {
|
|
||||||
if (pollingIntervalRef.current) {
|
|
||||||
clearInterval(pollingIntervalRef.current)
|
|
||||||
pollingIntervalRef.current = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const fetchQr = async () => {
|
|
||||||
stopPolling()
|
|
||||||
try {
|
|
||||||
const res = await whatsappManagersApi.startQr()
|
|
||||||
setQrData({ token: res.data.token, img: '' })
|
|
||||||
startPolling(res.data.token)
|
|
||||||
} catch (error) {
|
|
||||||
notifications.show({ title: 'Ошибка', message: 'Не удалось загрузить QR-код', color: 'red' })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const startPolling = (token: string) => {
|
|
||||||
pollingIntervalRef.current = window.setInterval(async () => {
|
|
||||||
try {
|
|
||||||
const res = await whatsappManagersApi.checkQrStatus(token)
|
|
||||||
if (res.data.status === 'pending' && res.data.qr) {
|
|
||||||
setQrData(prev => prev ? { ...prev, img: res.data.qr } : null)
|
|
||||||
}
|
|
||||||
else if (res.data.status === 'success') {
|
|
||||||
stopPolling()
|
|
||||||
notifications.show({ title: 'Успешно', message: 'WhatsApp подключен!', color: 'green' })
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['whatsapp-managers-status'] })
|
|
||||||
onClose()
|
|
||||||
}
|
|
||||||
else if (res.data.status === 'failed') {
|
|
||||||
stopPolling()
|
|
||||||
notifications.show({ title: 'Ошибка', message: 'Ошибка сканирования', color: 'red' })
|
|
||||||
setQrData(null)
|
|
||||||
}
|
|
||||||
} catch (err) {}
|
|
||||||
}, 2000)
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (opened && !qrData) fetchQr()
|
|
||||||
|
|
||||||
if (!opened) {
|
|
||||||
stopPolling()
|
|
||||||
setQrData(null)
|
|
||||||
}
|
|
||||||
|
|
||||||
return stopPolling
|
|
||||||
}, [opened])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal opened={opened} onClose={() => { stopPolling(); onClose(); }} title="Сканируйте QR-код в WhatsApp" size="sm">
|
|
||||||
<Stack align="center" gap="md">
|
|
||||||
<Text size="sm" ta="center">Настройки → Связанные устройства → Привязка устройства</Text>
|
|
||||||
<Center style={{ width: 250, height: 250, border: '1px solid var(--mantine-color-gray-3)', borderRadius: 8 }}>
|
|
||||||
{qrData?.img ? <Image src={qrData.img} w={230} h={230} fit="contain" /> : <Loader />}
|
|
||||||
</Center>
|
|
||||||
{qrData && <Loader type="dots" size="sm" />}
|
|
||||||
</Stack>
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function WhatsappTab() {
|
|
||||||
const [createModalOpened, setCreateModalOpened] = useState(false)
|
|
||||||
const [editingManager, setEditingManager] = useState<ManagerSession | null>(null)
|
|
||||||
const [deletingManager, setDeletingManager] = useState<ManagerSession | null>(null)
|
|
||||||
|
|
||||||
const { data: managers, isLoading, isFetching } = useWhatsAppManagers()
|
|
||||||
const deleteManager = useDeleteWhatsAppManager()
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
|
|
||||||
const confirmDelete = async (wipeData: boolean) => {
|
|
||||||
if (deletingManager) {
|
|
||||||
await deleteManager.mutateAsync({ phone: deletingManager.phone, wipeData })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleSaveName = async (newName: string) => {
|
|
||||||
if (!editingManager) return
|
|
||||||
try {
|
|
||||||
await whatsappManagersApi.updateName(editingManager.phone, newName)
|
|
||||||
notifications.show({ title: 'Успешно', message: 'Имя обновлено', color: 'green' })
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['whatsapp-managers-status'] })
|
|
||||||
} catch (e) {
|
|
||||||
notifications.show({ title: 'Ошибка', message: 'Не удалось обновить имя', color: 'red' })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleViewChats = (mgr: ManagerSession) => {
|
|
||||||
notifications.show({ title: 'Чаты', message: `Открытие переписки WhatsApp для ${mgr.name}...`, color: 'green' })
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Stack gap="md" mt="md">
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">Управление активными сессиями пользовательских аккаунтов WhatsApp</Text>
|
|
||||||
<Button leftSection={<IconPlus size={16} />} onClick={() => setCreateModalOpened(true)} color="green">Подключить WhatsApp</Button>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Paper withBorder>
|
|
||||||
<ManagersTable
|
|
||||||
managers={managers}
|
|
||||||
isLoading={isLoading}
|
|
||||||
onDelete={setDeletingManager}
|
|
||||||
onEdit={setEditingManager}
|
|
||||||
onViewChats={handleViewChats}
|
|
||||||
emptyText="Подключенные WhatsApp менеджеры не найдены"
|
|
||||||
/>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
{isFetching && !isLoading && <Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}><Loader size="xs" /></Box>}
|
|
||||||
|
|
||||||
<AddWhatsappModal opened={createModalOpened} onClose={() => setCreateModalOpened(false)} />
|
|
||||||
|
|
||||||
<EditManagerModal
|
|
||||||
opened={!!editingManager}
|
|
||||||
onClose={() => setEditingManager(null)}
|
|
||||||
manager={editingManager}
|
|
||||||
onSave={handleSaveName}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<DeleteManagerModal
|
|
||||||
opened={!!deletingManager}
|
|
||||||
onClose={() => setDeletingManager(null)}
|
|
||||||
manager={deletingManager}
|
|
||||||
onConfirm={confirmDelete}
|
|
||||||
title="Отключение WhatsApp"
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── ГЛАВНАЯ СТРАНИЦА ────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export default function MessengersPage() {
|
|
||||||
const [activeTab, setActiveTab] = useState<string | null>('telegram')
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Stack gap="md">
|
|
||||||
<div>
|
|
||||||
<Text size="xl" fw={700}>Интеграции мессенджеров</Text>
|
|
||||||
<Text size="sm" c="dimmed">Подключение и мониторинг каналов связи менеджеров</Text>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Tabs value={activeTab} onChange={setActiveTab}>
|
|
||||||
<Tabs.List>
|
|
||||||
<Tabs.Tab value="telegram" leftSection={<IconBrandTelegram size={16} />}>Telegram</Tabs.Tab>
|
|
||||||
<Tabs.Tab value="whatsapp" leftSection={<IconBrandWhatsapp size={16} />}>WhatsApp</Tabs.Tab>
|
|
||||||
<Tabs.Tab value="max" leftSection={<IconMessageCircle size={16} />}>Max</Tabs.Tab>
|
|
||||||
</Tabs.List>
|
|
||||||
|
|
||||||
<Tabs.Panel value="telegram"><TelegramTab /></Tabs.Panel>
|
|
||||||
|
|
||||||
<Tabs.Panel value="whatsapp"><WhatsappTab /></Tabs.Panel>
|
|
||||||
|
|
||||||
<Tabs.Panel value="max">
|
|
||||||
<Stack gap="md" mt="md">
|
|
||||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
|
||||||
Интеграция с сервисом Max находится в стадии планирования.
|
|
||||||
</Alert>
|
|
||||||
</Stack>
|
|
||||||
</Tabs.Panel>
|
|
||||||
</Tabs>
|
|
||||||
</Stack>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,209 +0,0 @@
|
||||||
import { useState, useEffect, useRef } from 'react'
|
|
||||||
import { Modal, Stack, TextInput, Button, Text, Alert, Group, Tabs, Image, Center, Loader } from '@mantine/core'
|
|
||||||
import { useForm } from '@mantine/form'
|
|
||||||
import { notifications } from '@mantine/notifications'
|
|
||||||
import { IconDeviceMobile, IconQrcode, IconMessageCircle } from '@tabler/icons-react'
|
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
|
||||||
import {telegramManagersApi} from "@/api/telegramManagers.ts";
|
|
||||||
|
|
||||||
interface AddManagerModalProps {
|
|
||||||
opened: boolean
|
|
||||||
onClose: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function AddManagerModal({ opened, onClose }: AddManagerModalProps) {
|
|
||||||
const [activeTab, setActiveTab] = useState<string | null>('qr')
|
|
||||||
|
|
||||||
// Состояния для авторизации по номеру
|
|
||||||
const [stepPhone, setStepPhone] = useState<'phone' | 'code'>('phone')
|
|
||||||
const [loadingPhone, setLoadingPhone] = useState(false)
|
|
||||||
|
|
||||||
// Состояния для авторизации по QR
|
|
||||||
const [qrData, setQrData] = useState<{ token: string, img: string } | null>(null)
|
|
||||||
const [loadingQr, setLoadingQr] = useState(false)
|
|
||||||
const pollingIntervalRef = useRef<number | null>(null)
|
|
||||||
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
|
|
||||||
const form = useForm({
|
|
||||||
initialValues: {
|
|
||||||
phone: '',
|
|
||||||
name: '',
|
|
||||||
code: '',
|
|
||||||
password: '',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// ── ЛОГИКА АВТОРИЗАЦИИ ПО НОМЕРУ ──────────────────────────────
|
|
||||||
const handleSendCode = async (values: typeof form.values) => {
|
|
||||||
setLoadingPhone(true)
|
|
||||||
try {
|
|
||||||
await telegramManagersApi.sendCode(values.phone, values.name)
|
|
||||||
notifications.show({ title: 'Код отправлен', message: 'Проверьте Telegram-аккаунт', color: 'green' })
|
|
||||||
setStepPhone('code')
|
|
||||||
} catch (error: any) {
|
|
||||||
notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Не удалось отправить код', color: 'red' })
|
|
||||||
} finally {
|
|
||||||
setLoadingPhone(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleVerifyCode = async (values: typeof form.values) => {
|
|
||||||
setLoadingPhone(true)
|
|
||||||
try {
|
|
||||||
await telegramManagersApi.verifyCode(values.phone, values.code, values.password || undefined)
|
|
||||||
notifications.show({ title: 'Успешно', message: 'Менеджер подключен', color: 'green' })
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] })
|
|
||||||
handleClose()
|
|
||||||
} catch (error: any) {
|
|
||||||
notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Неверный код', color: 'red' })
|
|
||||||
} finally {
|
|
||||||
setLoadingPhone(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── ЛОГИКА АВТОРИЗАЦИИ ПО QR ──────────────────────────────────
|
|
||||||
const fetchQr = async () => {
|
|
||||||
setLoadingQr(true)
|
|
||||||
stopPolling()
|
|
||||||
try {
|
|
||||||
const res = await telegramManagersApi.startQr()
|
|
||||||
setQrData({ token: res.data.token, img: res.data.qr_base64 })
|
|
||||||
startPolling(res.data.token)
|
|
||||||
} catch (error: any) {
|
|
||||||
notifications.show({ title: 'Ошибка', message: 'Не удалось сгенерировать QR-код', color: 'red' })
|
|
||||||
} finally {
|
|
||||||
setLoadingQr(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const startPolling = (token: string) => {
|
|
||||||
pollingIntervalRef.current = window.setInterval(async () => {
|
|
||||||
try {
|
|
||||||
const res = await telegramManagersApi.checkQrStatus(token)
|
|
||||||
if (res.data.status === 'success') {
|
|
||||||
stopPolling()
|
|
||||||
notifications.show({ title: 'Успешно', message: `Менеджер ${res.data.name} подключен!`, color: 'green' })
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] })
|
|
||||||
handleClose()
|
|
||||||
} else if (res.data.status === 'failed') {
|
|
||||||
stopPolling()
|
|
||||||
notifications.show({ title: 'Ошибка', message: res.data.error || 'Ошибка сканирования', color: 'red' })
|
|
||||||
setQrData(null) // Сбрасываем QR, чтобы пользователь мог запросить новый
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
stopPolling()
|
|
||||||
}
|
|
||||||
}, 3000) // Проверяем статус каждые 3 секунды
|
|
||||||
}
|
|
||||||
|
|
||||||
const stopPolling = () => {
|
|
||||||
if (pollingIntervalRef.current) {
|
|
||||||
clearInterval(pollingIntervalRef.current)
|
|
||||||
pollingIntervalRef.current = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Обработка открытия/закрытия модалки
|
|
||||||
useEffect(() => {
|
|
||||||
if (opened && activeTab === 'qr' && !qrData) {
|
|
||||||
fetchQr()
|
|
||||||
}
|
|
||||||
if (!opened) {
|
|
||||||
stopPolling()
|
|
||||||
setQrData(null)
|
|
||||||
}
|
|
||||||
return stopPolling
|
|
||||||
}, [opened, activeTab])
|
|
||||||
|
|
||||||
const handleClose = () => {
|
|
||||||
setStepPhone('phone')
|
|
||||||
form.reset()
|
|
||||||
onClose()
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal opened={opened} onClose={handleClose} title="Подключение менеджера Telegram" size="md">
|
|
||||||
<Tabs value={activeTab} onChange={setActiveTab}>
|
|
||||||
<Tabs.List mb="md">
|
|
||||||
<Tabs.Tab value="qr" leftSection={<IconQrcode size={16} />}>По QR-коду</Tabs.Tab>
|
|
||||||
<Tabs.Tab value="phone" leftSection={<IconMessageCircle size={16} />}>По номеру и коду</Tabs.Tab>
|
|
||||||
</Tabs.List>
|
|
||||||
|
|
||||||
{/* ВКЛАДКА: QR КОД */}
|
|
||||||
<Tabs.Panel value="qr">
|
|
||||||
<Stack gap="md" align="center">
|
|
||||||
<Text size="sm" c="dimmed" ta="center">
|
|
||||||
Откройте Telegram на телефоне менеджера → Настройки → Устройства → Подключить устройство, и отсканируйте этот код.
|
|
||||||
</Text>
|
|
||||||
|
|
||||||
<Center style={{ width: 250, height: 250, border: '1px solid #eee', borderRadius: 8 }}>
|
|
||||||
{loadingQr ? (
|
|
||||||
<Loader />
|
|
||||||
) : qrData ? (
|
|
||||||
<Image src={qrData.img} w={230} h={230} fit="contain" />
|
|
||||||
) : (
|
|
||||||
<Button variant="light" onClick={fetchQr}>Сгенерировать новый QR</Button>
|
|
||||||
)}
|
|
||||||
</Center>
|
|
||||||
|
|
||||||
{qrData && (
|
|
||||||
<Loader type="dots" size="sm" /> // Визуальный индикатор ожидания сканирования
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</Tabs.Panel>
|
|
||||||
|
|
||||||
{/* ВКЛАДКА: НОМЕР ТЕЛЕФОНА */}
|
|
||||||
<Tabs.Panel value="phone">
|
|
||||||
{stepPhone === 'phone' ? (
|
|
||||||
<form onSubmit={form.onSubmit(handleSendCode)}>
|
|
||||||
<Stack gap="md">
|
|
||||||
<TextInput
|
|
||||||
label="Имя менеджера"
|
|
||||||
placeholder="Иван Иванов"
|
|
||||||
required
|
|
||||||
{...form.getInputProps('name')}
|
|
||||||
/>
|
|
||||||
<TextInput
|
|
||||||
label="Номер телефона"
|
|
||||||
placeholder="+79991234567"
|
|
||||||
required
|
|
||||||
description="В международном формате с плюсом"
|
|
||||||
{...form.getInputProps('phone')}
|
|
||||||
/>
|
|
||||||
<Group justify="flex-end" mt="md">
|
|
||||||
<Button variant="default" onClick={handleClose}>Отмена</Button>
|
|
||||||
<Button type="submit" loading={loadingPhone}>Далее (Запросить код)</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</form>
|
|
||||||
) : (
|
|
||||||
<form onSubmit={form.onSubmit(handleVerifyCode)}>
|
|
||||||
<Stack gap="md">
|
|
||||||
<Alert icon={<IconDeviceMobile size={16} />} color="blue" variant="light">
|
|
||||||
Код отправлен в официальное приложение Telegram на номер {form.values.phone}
|
|
||||||
</Alert>
|
|
||||||
<TextInput
|
|
||||||
label="Код из Telegram"
|
|
||||||
placeholder="12345"
|
|
||||||
required
|
|
||||||
{...form.getInputProps('code')}
|
|
||||||
/>
|
|
||||||
<TextInput
|
|
||||||
label="Облачный пароль 2FA (если установлен)"
|
|
||||||
placeholder="Пароль двухэтапной аутентификации"
|
|
||||||
type="password"
|
|
||||||
{...form.getInputProps('password')}
|
|
||||||
/>
|
|
||||||
<Group justify="flex-end" mt="md">
|
|
||||||
<Button variant="default" onClick={() => setStepPhone('phone')}>Назад</Button>
|
|
||||||
<Button type="submit" loading={loadingPhone} color="green">Подтвердить и войти</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</form>
|
|
||||||
)}
|
|
||||||
</Tabs.Panel>
|
|
||||||
</Tabs>
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
||||||
import {Button, Checkbox, Group, Modal, Stack, Text} from '@mantine/core'
|
|
||||||
import {useEffect, useState} from 'react'
|
|
||||||
import {ManagerSession} from "@/types/api.ts";
|
|
||||||
|
|
||||||
export default function DeleteManagerModal({ opened, onClose, manager, onConfirm, title }: {
|
|
||||||
opened: boolean,
|
|
||||||
onClose: () => void,
|
|
||||||
manager: ManagerSession | null,
|
|
||||||
onConfirm: (wipeData: boolean) => Promise<void>,
|
|
||||||
title: string
|
|
||||||
}) {
|
|
||||||
const [wipeData, setWipeData] = useState(false)
|
|
||||||
const [loading, setLoading] = useState(false)
|
|
||||||
|
|
||||||
useEffect(() => { if (opened) setWipeData(false) }, [opened])
|
|
||||||
|
|
||||||
const handleConfirm = async () => {
|
|
||||||
setLoading(true)
|
|
||||||
await onConfirm(wipeData)
|
|
||||||
setLoading(false)
|
|
||||||
onClose()
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal opened={opened} onClose={onClose} title={title} size="sm">
|
|
||||||
<Stack gap="md">
|
|
||||||
<Text size="sm">Вы уверены, что хотите отключить сессию менеджера <b>{manager?.name}</b>?</Text>
|
|
||||||
<Checkbox
|
|
||||||
label="Полностью удалить историю переписки"
|
|
||||||
description="Если не отмечать, сессия отключится, но чаты останутся в архиве БД"
|
|
||||||
color="red"
|
|
||||||
checked={wipeData}
|
|
||||||
onChange={(event) => setWipeData(event.currentTarget.checked)}
|
|
||||||
/>
|
|
||||||
<Group justify="flex-end" mt="md">
|
|
||||||
<Button variant="default" onClick={onClose} disabled={loading}>Отмена</Button>
|
|
||||||
<Button color="red" onClick={handleConfirm} loading={loading}>Отключить</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -21,6 +21,8 @@ import {
|
||||||
IconPencil,
|
IconPencil,
|
||||||
IconTrash,
|
IconTrash,
|
||||||
IconPlus,
|
IconPlus,
|
||||||
|
IconList,
|
||||||
|
IconUsers,
|
||||||
IconInfoCircle,
|
IconInfoCircle,
|
||||||
IconFile,
|
IconFile,
|
||||||
IconCheck,
|
IconCheck,
|
||||||
|
|
@ -33,7 +35,6 @@ import {
|
||||||
} from '@/features/topicExecutors/hooks/useTopicExecutors'
|
} from '@/features/topicExecutors/hooks/useTopicExecutors'
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||||
import { useTopics } from '@/features/topics/hooks/useTopics'
|
import { useTopics } from '@/features/topics/hooks/useTopics'
|
||||||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
|
||||||
import {
|
import {
|
||||||
groupExecutorsByTopic,
|
groupExecutorsByTopic,
|
||||||
TARGET_SYSTEMS,
|
TARGET_SYSTEMS,
|
||||||
|
|
@ -49,30 +50,14 @@ type ViewMode = 'cards' | 'table'
|
||||||
|
|
||||||
export default function TopicExecutorsPage() {
|
export default function TopicExecutorsPage() {
|
||||||
const [viewMode, setViewMode] = useState<ViewMode>('cards')
|
const [viewMode, setViewMode] = useState<ViewMode>('cards')
|
||||||
|
|
||||||
// ✅ Фильтры - адаптированы под дизайн Hierarchies
|
|
||||||
const [topicFilter, setTopicFilter] = useState<string | null>(null)
|
const [topicFilter, setTopicFilter] = useState<string | null>(null)
|
||||||
const [categoryFilter, setCategoryFilter] = useState<string | null>(null)
|
|
||||||
const [userFilter, setUserFilter] = useState<string | null>(null)
|
|
||||||
const [targetSystemFilter, setTargetSystemFilter] = useState<string | null>(null)
|
const [targetSystemFilter, setTargetSystemFilter] = useState<string | null>(null)
|
||||||
|
|
||||||
const [editExecutor, setEditExecutor] = useState<ApprovalTopicExecutor | null>(null)
|
const [editExecutor, setEditExecutor] = useState<ApprovalTopicExecutor | null>(null)
|
||||||
const [createModalOpened, setCreateModalOpened] = useState(false)
|
const [createModalOpened, setCreateModalOpened] = useState(false)
|
||||||
const [presetGroup, setPresetGroup] = useState<TopicExecutorsGroup | null>(null)
|
const [presetGroup, setPresetGroup] = useState<TopicExecutorsGroup | null>(null)
|
||||||
|
|
||||||
// ✅ Получаем категории
|
|
||||||
const { data: categories } = useCategories({ limit: 1000 })
|
|
||||||
|
|
||||||
// ✅ Получаем темы с учетом фильтра по категории
|
|
||||||
const { data: categoryTopics } = useTopics({
|
|
||||||
limit: 1000,
|
|
||||||
...(categoryFilter && { category_id: Number(categoryFilter) }),
|
|
||||||
})
|
|
||||||
|
|
||||||
const { data, isLoading, isFetching } = useTopicExecutors({
|
const { data, isLoading, isFetching } = useTopicExecutors({
|
||||||
...(topicFilter && { topic_id: Number(topicFilter) }),
|
...(topicFilter && { topic_id: Number(topicFilter) }),
|
||||||
...(userFilter && { user_id: Number(userFilter) }),
|
|
||||||
...(categoryFilter && { category_id: Number(categoryFilter) }),
|
|
||||||
...(targetSystemFilter && { target_system: targetSystemFilter }),
|
...(targetSystemFilter && { target_system: targetSystemFilter }),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -87,18 +72,7 @@ export default function TopicExecutorsPage() {
|
||||||
return groupExecutorsByTopic(data.data)
|
return groupExecutorsByTopic(data.data)
|
||||||
}, [data])
|
}, [data])
|
||||||
|
|
||||||
// ✅ Опции для фильтров
|
const topicOptions = topics?.data?.map((t) => ({
|
||||||
const userOptions = users?.data?.map((u) => ({
|
|
||||||
value: String(u.id),
|
|
||||||
label: u.full_name || `Пользователь #${u.id}`,
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const categoryOptions = categories?.data?.map((c) => ({
|
|
||||||
value: String(c.id),
|
|
||||||
label: c.name || '',
|
|
||||||
})) || []
|
|
||||||
|
|
||||||
const topicOptions = (categoryFilter ? categoryTopics?.data : topics?.data)?.map((t) => ({
|
|
||||||
value: String(t.id),
|
value: String(t.id),
|
||||||
label: t.name || '',
|
label: t.name || '',
|
||||||
})) || []
|
})) || []
|
||||||
|
|
@ -108,16 +82,6 @@ export default function TopicExecutorsPage() {
|
||||||
label: s.label,
|
label: s.label,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
// ✅ Обработчик изменения фильтров - сбрасывает страницу и выделение
|
|
||||||
const handleFilterChange =
|
|
||||||
(setter: (value: string | null) => void) => (value: string | null) => {
|
|
||||||
setter(value)
|
|
||||||
// Если меняется категория, сбрасываем тему
|
|
||||||
if (setter === setCategoryFilter) {
|
|
||||||
setTopicFilter(null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDelete = (id: number) => {
|
const handleDelete = (id: number) => {
|
||||||
modals.openConfirmModal({
|
modals.openConfirmModal({
|
||||||
title: 'Подтвердите удаление',
|
title: 'Подтвердите удаление',
|
||||||
|
|
@ -153,19 +117,16 @@ export default function TopicExecutorsPage() {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{/* Заголовок - адаптирован под дизайн Hierarchies */}
|
{/* Заголовок */}
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Text size="xl" fw={700}>Исполнители тем</Text>
|
<Text size="xl" fw={700}>Исполнители тем</Text>
|
||||||
<Group>
|
<Group>
|
||||||
<Text c="dimmed" size="sm">
|
|
||||||
Всего: {data?.data?.length || 0}
|
|
||||||
</Text>
|
|
||||||
<SegmentedControl
|
<SegmentedControl
|
||||||
value={viewMode}
|
value={viewMode}
|
||||||
onChange={(v) => setViewMode(v as ViewMode)}
|
onChange={(v) => setViewMode(v as ViewMode)}
|
||||||
data={[
|
data={[
|
||||||
{ value: 'cards', label: 'Карточки' },
|
{ value: 'cards', label: 'Карточки' },
|
||||||
{ value: 'table', label: 'Таблица' },
|
{ value: 'table', label: 'Таблица'},
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
<Button
|
<Button
|
||||||
|
|
@ -189,82 +150,67 @@ export default function TopicExecutorsPage() {
|
||||||
</Text>
|
</Text>
|
||||||
</Alert>
|
</Alert>
|
||||||
|
|
||||||
{/* ✅ Фильтры - адаптированы под дизайн Hierarchies */}
|
{/* Фильтры */}
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Stack gap="md">
|
<Group gap="md" align="flex-end">
|
||||||
<Group gap="md" align="flex-end">
|
<Select
|
||||||
<Select
|
label="Тема"
|
||||||
label="Категория"
|
placeholder="Все темы"
|
||||||
placeholder="Все категории"
|
data={topicOptions}
|
||||||
data={categoryOptions}
|
value={topicFilter}
|
||||||
value={categoryFilter}
|
onChange={setTopicFilter}
|
||||||
onChange={handleFilterChange(setCategoryFilter)}
|
clearable
|
||||||
clearable
|
searchable
|
||||||
searchable
|
style={{ minWidth: 300 }}
|
||||||
style={{ flex: 1, minWidth: 250 }}
|
/>
|
||||||
/>
|
|
||||||
<Select
|
<Select
|
||||||
label="Тема"
|
label="Целевая система"
|
||||||
placeholder="Все темы"
|
placeholder="Все системы"
|
||||||
data={topicOptions}
|
data={targetSystemOptions}
|
||||||
value={topicFilter}
|
value={targetSystemFilter}
|
||||||
onChange={handleFilterChange(setTopicFilter)}
|
onChange={setTargetSystemFilter}
|
||||||
clearable
|
clearable
|
||||||
searchable
|
style={{ minWidth: 200 }}
|
||||||
style={{ flex: 1, minWidth: 250 }}
|
/>
|
||||||
/>
|
|
||||||
</Group>
|
<Text c="dimmed" size="sm">
|
||||||
<Group gap="md" align="flex-end">
|
Всего исполнителей: {data?.data?.length || 0}
|
||||||
<Select
|
</Text>
|
||||||
label="Исполнитель"
|
</Group>
|
||||||
placeholder="Все исполнители"
|
|
||||||
data={userOptions}
|
|
||||||
value={userFilter}
|
|
||||||
onChange={handleFilterChange(setUserFilter)}
|
|
||||||
clearable
|
|
||||||
searchable
|
|
||||||
style={{ flex: 1, minWidth: 250 }}
|
|
||||||
/>
|
|
||||||
<Select
|
|
||||||
label="Целевая система"
|
|
||||||
placeholder="Все системы"
|
|
||||||
data={targetSystemOptions}
|
|
||||||
value={targetSystemFilter}
|
|
||||||
onChange={handleFilterChange(setTargetSystemFilter)}
|
|
||||||
clearable
|
|
||||||
style={{ flex: 1, minWidth: 200 }}
|
|
||||||
/>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
{/* Контент */}
|
{/* Контент */}
|
||||||
<Paper withBorder>
|
{isLoading ? (
|
||||||
{isLoading ? (
|
<Center p={60}>
|
||||||
<Center p={60}>
|
<Loader />
|
||||||
<Loader />
|
</Center>
|
||||||
</Center>
|
) : viewMode === 'cards' ? (
|
||||||
) : viewMode === 'cards' ? (
|
// Режим карточек
|
||||||
<ScrollArea p="md">
|
<ScrollArea>
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{groups.length === 0 ? (
|
{groups.length === 0 ? (
|
||||||
<Center p={40}>
|
<Paper withBorder p={40}>
|
||||||
|
<Center>
|
||||||
<Text c="dimmed">Исполнители не найдены</Text>
|
<Text c="dimmed">Исполнители не найдены</Text>
|
||||||
</Center>
|
</Center>
|
||||||
) : (
|
</Paper>
|
||||||
groups.map((group) => (
|
) : (
|
||||||
<TopicExecutorsCard
|
groups.map((group) => (
|
||||||
key={group.topicId}
|
<TopicExecutorsCard
|
||||||
group={group}
|
key={group.topicId}
|
||||||
onEditExecutor={handleEditExecutor}
|
group={group}
|
||||||
onDeleteExecutor={handleDelete}
|
onEditExecutor={handleEditExecutor}
|
||||||
onAddExecutor={handleAddExecutor}
|
onDeleteExecutor={handleDelete}
|
||||||
/>
|
onAddExecutor={handleAddExecutor}
|
||||||
))
|
/>
|
||||||
)}
|
))
|
||||||
</Stack>
|
)}
|
||||||
</ScrollArea>
|
</Stack>
|
||||||
) : (
|
</ScrollArea>
|
||||||
|
) : (
|
||||||
|
// Режим таблицы
|
||||||
|
<Paper withBorder>
|
||||||
<Table striped highlightOnHover>
|
<Table striped highlightOnHover>
|
||||||
<Table.Thead>
|
<Table.Thead>
|
||||||
<Table.Tr>
|
<Table.Tr>
|
||||||
|
|
@ -275,104 +221,94 @@ export default function TopicExecutorsPage() {
|
||||||
<Table.Th>Задача</Table.Th>
|
<Table.Th>Задача</Table.Th>
|
||||||
<Table.Th style={{ width: 120 }}>Система</Table.Th>
|
<Table.Th style={{ width: 120 }}>Система</Table.Th>
|
||||||
<Table.Th style={{ width: 80 }}>Файл</Table.Th>
|
<Table.Th style={{ width: 80 }}>Файл</Table.Th>
|
||||||
<Table.Th style={{ width: 80 }}>Статус</Table.Th>
|
<Table.Th style={{ width: 100 }}>Статус</Table.Th>
|
||||||
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
|
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
|
||||||
</Table.Tr>
|
</Table.Tr>
|
||||||
</Table.Thead>
|
</Table.Thead>
|
||||||
<Table.Tbody>
|
<Table.Tbody>
|
||||||
{data?.data?.length === 0 ? (
|
{data?.data?.map((executor) => (
|
||||||
<Table.Tr>
|
<Table.Tr key={executor.id}>
|
||||||
<Table.Td colSpan={9}>
|
<Table.Td>{executor.id}</Table.Td>
|
||||||
<Center p={40}>
|
<Table.Td>
|
||||||
<Text c="dimmed">Исполнители не найдены</Text>
|
<Text size="sm" fw={500}>
|
||||||
</Center>
|
{executor.topic?.name || '—'}
|
||||||
|
</Text>
|
||||||
|
<Text size="xs" c="dimmed" ff="monospace">
|
||||||
|
{executor.topic?.code}
|
||||||
|
</Text>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Text size="sm" fw={500}>
|
||||||
|
{executor.user?.full_name || '—'}
|
||||||
|
</Text>
|
||||||
|
<Text size="xs" c="dimmed">
|
||||||
|
{executor.user?.department?.name}
|
||||||
|
</Text>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Badge variant="light" color="orange">
|
||||||
|
#{executor.step_order}
|
||||||
|
</Badge>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Text size="xs" lineClamp={2}>
|
||||||
|
{executor.task_text || '—'}
|
||||||
|
</Text>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Badge
|
||||||
|
size="xs"
|
||||||
|
variant="light"
|
||||||
|
color={TARGET_SYSTEM_COLORS[executor.target_system || ''] || 'gray'}
|
||||||
|
>
|
||||||
|
{TARGET_SYSTEM_LABELS[executor.target_system || ''] || executor.target_system}
|
||||||
|
</Badge>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
{executor.require_file ? (
|
||||||
|
<IconFile size={16} color="var(--mantine-color-violet-6)" />
|
||||||
|
) : (
|
||||||
|
<Text size="xs" c="dimmed">—</Text>
|
||||||
|
)}
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Badge
|
||||||
|
size="xs"
|
||||||
|
variant="light"
|
||||||
|
color={executor.is_active ? 'green' : 'gray'}
|
||||||
|
leftSection={executor.is_active ? <IconCheck size={10} /> : <IconX size={10} />}
|
||||||
|
>
|
||||||
|
{executor.is_active ? 'Активен' : 'Неактивен'}
|
||||||
|
</Badge>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Group gap="xs">
|
||||||
|
<Tooltip label="Редактировать">
|
||||||
|
<ActionIcon
|
||||||
|
variant="light"
|
||||||
|
color="blue"
|
||||||
|
onClick={() => setEditExecutor(executor)}
|
||||||
|
>
|
||||||
|
<IconPencil size={16} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip label="Удалить">
|
||||||
|
<ActionIcon
|
||||||
|
variant="light"
|
||||||
|
color="red"
|
||||||
|
onClick={() => handleDelete(executor.id!)}
|
||||||
|
>
|
||||||
|
<IconTrash size={16} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
</Group>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
</Table.Tr>
|
</Table.Tr>
|
||||||
) : (
|
))}
|
||||||
data?.data?.map((executor) => (
|
|
||||||
<Table.Tr key={executor.id}>
|
|
||||||
<Table.Td>{executor.id}</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" fw={500}>
|
|
||||||
{executor.topic?.name || '—'}
|
|
||||||
</Text>
|
|
||||||
<Text size="xs" c="dimmed" ff="monospace">
|
|
||||||
{executor.topic?.code}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="sm" fw={500}>
|
|
||||||
{executor.user?.full_name || '—'}
|
|
||||||
</Text>
|
|
||||||
<Text size="xs" c="dimmed">
|
|
||||||
{executor.user?.department?.name}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Badge variant="light" color="orange">
|
|
||||||
#{executor.step_order}
|
|
||||||
</Badge>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Text size="xs" lineClamp={2}>
|
|
||||||
{executor.task_text || '—'}
|
|
||||||
</Text>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Badge
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color={TARGET_SYSTEM_COLORS[executor.target_system || ''] || 'gray'}
|
|
||||||
>
|
|
||||||
{TARGET_SYSTEM_LABELS[executor.target_system || ''] || executor.target_system}
|
|
||||||
</Badge>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
{executor.require_file ? (
|
|
||||||
<IconFile size={16} color="var(--mantine-color-violet-6)" />
|
|
||||||
) : (
|
|
||||||
<Text size="xs" c="dimmed">—</Text>
|
|
||||||
)}
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Badge
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color={executor.is_active ? 'green' : 'gray'}
|
|
||||||
leftSection={executor.is_active ? <IconCheck size={10} /> : <IconX size={10} />}
|
|
||||||
>
|
|
||||||
{executor.is_active ? 'Активен' : 'Неактивен'}
|
|
||||||
</Badge>
|
|
||||||
</Table.Td>
|
|
||||||
<Table.Td>
|
|
||||||
<Group gap="xs">
|
|
||||||
<Tooltip label="Редактировать">
|
|
||||||
<ActionIcon
|
|
||||||
variant="light"
|
|
||||||
color="blue"
|
|
||||||
onClick={() => setEditExecutor(executor)}
|
|
||||||
>
|
|
||||||
<IconPencil size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip label="Удалить">
|
|
||||||
<ActionIcon
|
|
||||||
variant="light"
|
|
||||||
color="red"
|
|
||||||
onClick={() => handleDelete(executor.id!)}
|
|
||||||
>
|
|
||||||
<IconTrash size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
</Group>
|
|
||||||
</Table.Td>
|
|
||||||
</Table.Tr>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Table.Tbody>
|
</Table.Tbody>
|
||||||
</Table>
|
</Table>
|
||||||
)}
|
</Paper>
|
||||||
</Paper>
|
)}
|
||||||
|
|
||||||
{isFetching && !isLoading && (
|
{isFetching && !isLoading && (
|
||||||
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
|
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ import {
|
||||||
Center,
|
Center,
|
||||||
Badge,
|
Badge,
|
||||||
Paper,
|
Paper,
|
||||||
|
Divider,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { useForm } from '@mantine/form'
|
import { useForm } from '@mantine/form'
|
||||||
import {
|
import {
|
||||||
|
|
@ -61,9 +62,6 @@ export default function TopicEditModal({
|
||||||
allow_approver_selection: false,
|
allow_approver_selection: false,
|
||||||
first_approver_role_code: '',
|
first_approver_role_code: '',
|
||||||
allow_observer_selection: false,
|
allow_observer_selection: false,
|
||||||
// 🆕 Делегирование обязанностей на время отсутствия — актуально
|
|
||||||
// для тем категорий "Отгул"/"Отпуск"/"Больничный".
|
|
||||||
allow_delegation_selection: false,
|
|
||||||
approval_mode: 'sequential',
|
approval_mode: 'sequential',
|
||||||
require_approver_comment: false,
|
require_approver_comment: false,
|
||||||
requires_file: false,
|
requires_file: false,
|
||||||
|
|
@ -97,7 +95,6 @@ export default function TopicEditModal({
|
||||||
allow_approver_selection: topic.allow_approver_selection ?? false,
|
allow_approver_selection: topic.allow_approver_selection ?? false,
|
||||||
first_approver_role_code: topic.first_approver_role_code || '',
|
first_approver_role_code: topic.first_approver_role_code || '',
|
||||||
allow_observer_selection: topic.allow_observer_selection ?? false,
|
allow_observer_selection: topic.allow_observer_selection ?? false,
|
||||||
allow_delegation_selection: topic.allow_delegation_selection ?? false,
|
|
||||||
approval_mode: topic.approval_mode || 'sequential',
|
approval_mode: topic.approval_mode || 'sequential',
|
||||||
require_approver_comment: topic.require_approver_comment ?? false,
|
require_approver_comment: topic.require_approver_comment ?? false,
|
||||||
requires_file: topic.requires_file ?? false,
|
requires_file: topic.requires_file ?? false,
|
||||||
|
|
@ -128,7 +125,6 @@ export default function TopicEditModal({
|
||||||
allow_approver_selection: values.allow_approver_selection,
|
allow_approver_selection: values.allow_approver_selection,
|
||||||
first_approver_role_code: values.first_approver_role_code || null,
|
first_approver_role_code: values.first_approver_role_code || null,
|
||||||
allow_observer_selection: values.allow_observer_selection,
|
allow_observer_selection: values.allow_observer_selection,
|
||||||
allow_delegation_selection: values.allow_delegation_selection,
|
|
||||||
approval_mode: values.approval_mode,
|
approval_mode: values.approval_mode,
|
||||||
require_approver_comment: values.require_approver_comment,
|
require_approver_comment: values.require_approver_comment,
|
||||||
requires_file: values.requires_file,
|
requires_file: values.requires_file,
|
||||||
|
|
@ -259,8 +255,8 @@ export default function TopicEditModal({
|
||||||
<Text size="sm" fw={600} mb="sm">Настройки согласования</Text>
|
<Text size="sm" fw={600} mb="sm">Настройки согласования</Text>
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
<Switch
|
<Switch
|
||||||
label="Выбор согласующего из иерархии"
|
label="Разрешить выбор согласующего"
|
||||||
description="Пользователь может выбрать согласующего из списка людей, прописанных в иерархии (user_hierarchy) для этой темы"
|
description="Пользователь может сам выбрать согласующего"
|
||||||
checked={form.values.allow_approver_selection}
|
checked={form.values.allow_approver_selection}
|
||||||
onChange={(e) => form.setFieldValue('allow_approver_selection', e.currentTarget.checked)}
|
onChange={(e) => form.setFieldValue('allow_approver_selection', e.currentTarget.checked)}
|
||||||
/>
|
/>
|
||||||
|
|
@ -268,9 +264,10 @@ export default function TopicEditModal({
|
||||||
<TextInput
|
<TextInput
|
||||||
label="Код роли первого согласующего"
|
label="Код роли первого согласующего"
|
||||||
placeholder="supervisor, manager..."
|
placeholder="supervisor, manager..."
|
||||||
description="Если указан — первый согласующий выбирается из пользователей с этой ролью. Работает независимо от выбора из иерархии."
|
description="Если не указан — используется иерархия"
|
||||||
value={form.values.first_approver_role_code}
|
value={form.values.first_approver_role_code}
|
||||||
onChange={(e) => form.setFieldValue('first_approver_role_code', e.currentTarget.value)}
|
onChange={(e) => form.setFieldValue('first_approver_role_code', e.currentTarget.value)}
|
||||||
|
disabled={!form.values.allow_approver_selection}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Switch
|
<Switch
|
||||||
|
|
@ -296,10 +293,10 @@ export default function TopicEditModal({
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Switch
|
<Switch
|
||||||
label="Разрешить делегирование обязанностей"
|
label="Имеет дерево навигации"
|
||||||
description="В конце заявки сотруднику предложат делегировать все согласования на время отсутствия другому человеку (актуально для отгула/отпуска/больничного)"
|
description="У этой темы будет дерево кнопок для навигации"
|
||||||
checked={form.values.allow_delegation_selection}
|
checked={form.values.is_tree_root}
|
||||||
onChange={(e) => form.setFieldValue('allow_delegation_selection', e.currentTarget.checked)}
|
onChange={(e) => form.setFieldValue('is_tree_root', e.currentTarget.checked)}
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
|
||||||
|
|
@ -5,39 +5,30 @@ import {
|
||||||
Badge,
|
Badge,
|
||||||
Group,
|
Group,
|
||||||
ActionIcon,
|
ActionIcon,
|
||||||
|
Button,
|
||||||
Text,
|
Text,
|
||||||
TextInput,
|
TextInput,
|
||||||
Select,
|
Select,
|
||||||
MultiSelect, // ✅ Добавлен
|
|
||||||
Pagination,
|
Pagination,
|
||||||
Loader,
|
Loader,
|
||||||
Center,
|
Center,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
Box,
|
Box,
|
||||||
Stack,
|
Stack,
|
||||||
Modal,
|
|
||||||
Button,
|
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { IconPencil, IconSearch, IconTrash } from '@tabler/icons-react'
|
import { IconPencil, IconSearch, IconRefresh } from '@tabler/icons-react'
|
||||||
import { useUsers, useDeleteUser } from '@/features/users/hooks/useUsers'
|
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||||
import { useDepartments } from '@/features/users/hooks/useDepartments'
|
import { useDepartments } from '@/features/users/hooks/useDepartments'
|
||||||
import { useRoles } from '@/features/users/hooks/useRoles' // ✅ Добавлен
|
import UserEditModal from "@/components/UserEditModal.tsx";
|
||||||
import UserEditModal from "@/components/UserEditModal.tsx"
|
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
|
||||||
|
|
||||||
const LIMIT = 20
|
const LIMIT = 20
|
||||||
|
|
||||||
export default function UsersPage() {
|
export default function UsersPage() {
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
const [selectedRoleIds, setSelectedRoleIds] = useState<number[]>([]) // ✅ Массив ID ролей
|
|
||||||
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
|
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
|
||||||
const [statusFilter, setStatusFilter] = useState<string | null>(null)
|
const [statusFilter, setStatusFilter] = useState<string | null>(null)
|
||||||
const [editUserId, setEditUserId] = useState<number | null>(null)
|
const [editUserId, setEditUserId] = useState<number | null>(null)
|
||||||
const [deleteUserId, setDeleteUserId] = useState<number | null>(null)
|
|
||||||
|
|
||||||
const { user: currentUser } = useAuth()
|
|
||||||
const isRootAdmin = currentUser?.is_root === true
|
|
||||||
|
|
||||||
const { data, isLoading, isFetching } = useUsers({
|
const { data, isLoading, isFetching } = useUsers({
|
||||||
offset: (page - 1) * LIMIT,
|
offset: (page - 1) * LIMIT,
|
||||||
|
|
@ -47,38 +38,19 @@ export default function UsersPage() {
|
||||||
...(statusFilter === 'fired' && { is_fired: true }),
|
...(statusFilter === 'fired' && { is_fired: true }),
|
||||||
...(statusFilter === 'active' && { is_blocked: false, is_fired: false }),
|
...(statusFilter === 'active' && { is_blocked: false, is_fired: false }),
|
||||||
...(search && { full_name: search }),
|
...(search && { full_name: search }),
|
||||||
...(selectedRoleIds.length > 0 && { role_ids: selectedRoleIds }), // ✅ Передаём массив
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const { data: departments } = useDepartments()
|
const { data: departments } = useDepartments()
|
||||||
const { data: allRoles } = useRoles({ limit: 1000 }) // ✅ Получаем все роли
|
|
||||||
const deleteUser = useDeleteUser()
|
|
||||||
|
|
||||||
const departmentOptions = useMemo(() => {
|
const departmentOptions = useMemo(() => {
|
||||||
if (!departments || !Array.isArray(departments)) return []
|
if (!departments) return []
|
||||||
return departments.map((d) => ({
|
return departments.map((d) => ({
|
||||||
value: String(d.id),
|
value: String(d.id),
|
||||||
label: d.name || '',
|
label: d.name || '',
|
||||||
}))
|
}))
|
||||||
}, [departments])
|
}, [departments])
|
||||||
|
|
||||||
const roleOptions = useMemo(() => {
|
|
||||||
if (!allRoles || !Array.isArray(allRoles)) return []
|
|
||||||
return allRoles.map((r) => ({
|
|
||||||
value: String(r.id),
|
|
||||||
label: r.name || '',
|
|
||||||
}))
|
|
||||||
}, [allRoles])
|
|
||||||
|
|
||||||
const users = Array.isArray(data?.data) ? data.data : []
|
|
||||||
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
||||||
const hasSelected = selectedRoleIds.length > 0;
|
|
||||||
|
|
||||||
const handleDelete = async () => {
|
|
||||||
if (!deleteUserId) return
|
|
||||||
await deleteUser.mutateAsync(deleteUserId)
|
|
||||||
setDeleteUserId(null)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
|
|
@ -89,6 +61,7 @@ export default function UsersPage() {
|
||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
|
{/* Фильтры */}
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Group gap="md" align="flex-end">
|
<Group gap="md" align="flex-end">
|
||||||
<TextInput
|
<TextInput
|
||||||
|
|
@ -103,35 +76,6 @@ export default function UsersPage() {
|
||||||
style={{ flex: 1 }}
|
style={{ flex: 1 }}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Box style={{ width: 250 }}>
|
|
||||||
<MultiSelect
|
|
||||||
label="Роли"
|
|
||||||
// ✅ Меняем placeholder в зависимости от количества выбранных
|
|
||||||
placeholder={hasSelected ? `Выбрано: ${selectedRoleIds.length}` : "Все роли"}
|
|
||||||
data={roleOptions}
|
|
||||||
value={selectedRoleIds.map(String)}
|
|
||||||
onChange={(v) => {
|
|
||||||
setSelectedRoleIds(v.map(Number))
|
|
||||||
setPage(1)
|
|
||||||
}}
|
|
||||||
searchable
|
|
||||||
clearable
|
|
||||||
maxDropdownHeight={400}
|
|
||||||
limit={15}
|
|
||||||
styles={{
|
|
||||||
input: {
|
|
||||||
minHeight: 36,
|
|
||||||
},
|
|
||||||
pill: {
|
|
||||||
display: 'none',
|
|
||||||
},
|
|
||||||
pillsList: {
|
|
||||||
display: 'none',
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Select
|
<Select
|
||||||
label="Отдел"
|
label="Отдел"
|
||||||
placeholder="Все отделы"
|
placeholder="Все отделы"
|
||||||
|
|
@ -164,6 +108,7 @@ export default function UsersPage() {
|
||||||
</Group>
|
</Group>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
{/* Таблица */}
|
||||||
<Paper withBorder>
|
<Paper withBorder>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<Center p={60}>
|
<Center p={60}>
|
||||||
|
|
@ -181,11 +126,11 @@ export default function UsersPage() {
|
||||||
<Table.Th>Отдел</Table.Th>
|
<Table.Th>Отдел</Table.Th>
|
||||||
<Table.Th>Роли</Table.Th>
|
<Table.Th>Роли</Table.Th>
|
||||||
<Table.Th>Статус</Table.Th>
|
<Table.Th>Статус</Table.Th>
|
||||||
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
|
<Table.Th style={{ width: 60 }}>Действия</Table.Th>
|
||||||
</Table.Tr>
|
</Table.Tr>
|
||||||
</Table.Thead>
|
</Table.Thead>
|
||||||
<Table.Tbody>
|
<Table.Tbody>
|
||||||
{users.length === 0 ? (
|
{data?.data?.length === 0 ? (
|
||||||
<Table.Tr>
|
<Table.Tr>
|
||||||
<Table.Td colSpan={8}>
|
<Table.Td colSpan={8}>
|
||||||
<Center p={40}>
|
<Center p={40}>
|
||||||
|
|
@ -194,7 +139,7 @@ export default function UsersPage() {
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
</Table.Tr>
|
</Table.Tr>
|
||||||
) : (
|
) : (
|
||||||
users.map((user) => (
|
(data?.data || []).map((user) => (
|
||||||
<Table.Tr key={user.id}>
|
<Table.Tr key={user.id}>
|
||||||
<Table.Td>{user.id}</Table.Td>
|
<Table.Td>{user.id}</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
|
|
@ -211,20 +156,17 @@ export default function UsersPage() {
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Group gap={4}>
|
<Group gap={4}>
|
||||||
{Array.isArray(user.user_roles) ? (
|
{user.user_roles?.slice(0, 3).map((ur) => (
|
||||||
<>
|
<Badge key={ur.id} size="xs" variant="light">
|
||||||
{user.user_roles.slice(0, 3).map((ur) => (
|
{ur.role?.name || 'Роль'}
|
||||||
<Badge key={ur.id} size="xs" variant="light">
|
</Badge>
|
||||||
{ur.role?.name || 'Роль'}
|
))}
|
||||||
</Badge>
|
{user.user_roles && user.user_roles.length > 3 && (
|
||||||
))}
|
<Badge size="xs" variant="outline">
|
||||||
{user.user_roles.length > 3 && (
|
+{user.user_roles.length - 3}
|
||||||
<Badge size="xs" variant="outline">
|
</Badge>
|
||||||
+{user.user_roles.length - 3}
|
)}
|
||||||
</Badge>
|
{(!user.user_roles || user.user_roles.length === 0) && (
|
||||||
)}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Text size="xs" c="dimmed">—</Text>
|
<Text size="xs" c="dimmed">—</Text>
|
||||||
)}
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
|
|
@ -236,28 +178,15 @@ export default function UsersPage() {
|
||||||
/>
|
/>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Group gap={4}>
|
<Tooltip label="Редактировать">
|
||||||
<Tooltip label="Редактировать">
|
<ActionIcon
|
||||||
<ActionIcon
|
variant="light"
|
||||||
variant="light"
|
color="blue"
|
||||||
color="blue"
|
onClick={() => setEditUserId(user.id!)}
|
||||||
onClick={() => setEditUserId(user.id!)}
|
>
|
||||||
>
|
<IconPencil size={16} />
|
||||||
<IconPencil size={16} />
|
</ActionIcon>
|
||||||
</ActionIcon>
|
</Tooltip>
|
||||||
</Tooltip>
|
|
||||||
{isRootAdmin && (
|
|
||||||
<Tooltip label="Удалить пользователя">
|
|
||||||
<ActionIcon
|
|
||||||
variant="light"
|
|
||||||
color="red"
|
|
||||||
onClick={() => setDeleteUserId(user.id!)}
|
|
||||||
>
|
|
||||||
<IconTrash size={16} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
</Table.Tr>
|
</Table.Tr>
|
||||||
))
|
))
|
||||||
|
|
@ -265,6 +194,7 @@ export default function UsersPage() {
|
||||||
</Table.Tbody>
|
</Table.Tbody>
|
||||||
</Table>
|
</Table>
|
||||||
|
|
||||||
|
{/* Пагинация */}
|
||||||
{totalPages > 1 && (
|
{totalPages > 1 && (
|
||||||
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
|
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
|
|
@ -284,48 +214,42 @@ export default function UsersPage() {
|
||||||
)}
|
)}
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
{/* Индикатор обновления */}
|
||||||
{isFetching && !isLoading && (
|
{isFetching && !isLoading && (
|
||||||
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
|
<Box
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
top: 70,
|
||||||
|
right: 20,
|
||||||
|
zIndex: 1000
|
||||||
|
}}
|
||||||
|
>
|
||||||
<Loader size="xs" />
|
<Loader size="xs" />
|
||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Модальное окно редактирования */}
|
||||||
<UserEditModal
|
<UserEditModal
|
||||||
userId={editUserId}
|
userId={editUserId}
|
||||||
opened={editUserId !== null}
|
opened={editUserId !== null}
|
||||||
onClose={() => setEditUserId(null)}
|
onClose={() => setEditUserId(null)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Modal
|
|
||||||
opened={deleteUserId !== null}
|
|
||||||
onClose={() => setDeleteUserId(null)}
|
|
||||||
title="Подтверждение удаления"
|
|
||||||
size="md"
|
|
||||||
>
|
|
||||||
<Stack gap="md">
|
|
||||||
<Text>
|
|
||||||
Вы уверены, что хотите удалить пользователя? Это действие нельзя отменить.
|
|
||||||
</Text>
|
|
||||||
<Group justify="flex-end">
|
|
||||||
<Button variant="default" onClick={() => setDeleteUserId(null)}>
|
|
||||||
Отмена
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
color="red"
|
|
||||||
onClick={handleDelete}
|
|
||||||
loading={deleteUser.isPending}
|
|
||||||
>
|
|
||||||
Удалить
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</Modal>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function UserStatusBadge({ isBlocked, isFired }: { isBlocked?: boolean; isFired?: boolean }) {
|
function UserStatusBadge({
|
||||||
if (isFired) return <Badge color="gray" variant="filled">Уволен</Badge>
|
isBlocked,
|
||||||
if (isBlocked) return <Badge color="red" variant="filled">Заблокирован</Badge>
|
isFired
|
||||||
|
}: {
|
||||||
|
isBlocked?: boolean
|
||||||
|
isFired?: boolean
|
||||||
|
}) {
|
||||||
|
if (isFired) {
|
||||||
|
return <Badge color="gray" variant="filled">Уволен</Badge>
|
||||||
|
}
|
||||||
|
if (isBlocked) {
|
||||||
|
return <Badge color="red" variant="filled">Заблокирован</Badge>
|
||||||
|
}
|
||||||
return <Badge color="green" variant="light">Активен</Badge>
|
return <Badge color="green" variant="light">Активен</Badge>
|
||||||
}
|
}
|
||||||
|
|
@ -1,17 +1,3 @@
|
||||||
export interface ManagerSession {
|
|
||||||
manager_id: number
|
|
||||||
name: string
|
|
||||||
phone: string
|
|
||||||
is_online: boolean
|
|
||||||
last_incoming_message_at: string | null
|
|
||||||
last_outgoing_message_at: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ManagersStatusResponse {
|
|
||||||
// Если ваш бэкенд возвращает массив напрямую или обертку, скорректируйте по аналогии
|
|
||||||
data: ManagerSession[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface User {
|
export interface User {
|
||||||
id?: number
|
id?: number
|
||||||
telegram_id?: number
|
telegram_id?: number
|
||||||
|
|
@ -46,7 +32,6 @@ export interface Role {
|
||||||
is_default?: boolean
|
is_default?: boolean
|
||||||
is_director?: boolean
|
is_director?: boolean
|
||||||
is_approver?: boolean
|
is_approver?: boolean
|
||||||
is_controller?: boolean
|
|
||||||
is_observer?: boolean
|
is_observer?: boolean
|
||||||
is_executor?: boolean
|
is_executor?: boolean
|
||||||
description?: string
|
description?: string
|
||||||
|
|
@ -66,20 +51,14 @@ export interface UserRole {
|
||||||
export interface Admin {
|
export interface Admin {
|
||||||
id?: number
|
id?: number
|
||||||
login: string
|
login: string
|
||||||
name?: string
|
password_hash?: string
|
||||||
is_root?: boolean
|
is_blocked?: boolean
|
||||||
is_observer?: boolean
|
|
||||||
telegram_id?: number
|
|
||||||
telegram_user?: User
|
|
||||||
is_analyst?: boolean
|
|
||||||
created_at?: string
|
|
||||||
last_login?: string
|
last_login?: string
|
||||||
last_ip_login?: string
|
last_ip_login?: string
|
||||||
is_blocked?: boolean
|
created_at?: string
|
||||||
password?: string
|
updated_at?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// 🆕 Типы для заявок
|
// 🆕 Типы для заявок
|
||||||
export interface ApprovalFile {
|
export interface ApprovalFile {
|
||||||
id?: number
|
id?: number
|
||||||
|
|
@ -205,7 +184,6 @@ export interface UserHierarchy {
|
||||||
subordinate?: User
|
subordinate?: User
|
||||||
approver?: User
|
approver?: User
|
||||||
department?: Department
|
department?: Department
|
||||||
target_system?: string | null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ApprovalTopicExecutor {
|
export interface ApprovalTopicExecutor {
|
||||||
|
|
@ -238,14 +216,16 @@ export interface ApprovalTopic {
|
||||||
first_approver_role_code?: string
|
first_approver_role_code?: string
|
||||||
allow_observer_selection?: boolean
|
allow_observer_selection?: boolean
|
||||||
approval_mode?: string
|
approval_mode?: string
|
||||||
allow_delegation_selection?: boolean
|
|
||||||
require_approver_comment?: boolean
|
require_approver_comment?: boolean
|
||||||
requires_file?: boolean
|
requires_file?: boolean
|
||||||
require_observer_selection?: boolean
|
require_observer_selection?: boolean
|
||||||
instructions?: string
|
instructions?: string
|
||||||
created_at?: string
|
created_at?: string
|
||||||
updated_at?: string
|
updated_at?: string
|
||||||
|
message_template?: string | null
|
||||||
|
code_template?: string | null
|
||||||
category?: ApprovalTopicCategory
|
category?: ApprovalTopicCategory
|
||||||
|
is_tree_root?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Admin {
|
export interface Admin {
|
||||||
|
|
@ -292,9 +272,6 @@ export interface ApprovalFlowNode {
|
||||||
topic_id?: number
|
topic_id?: number
|
||||||
parent_id?: number | null
|
parent_id?: number | null
|
||||||
key: string
|
key: string
|
||||||
category_id: number
|
|
||||||
message_template?: string | null
|
|
||||||
code_template?: string | null
|
|
||||||
label: string
|
label: string
|
||||||
data_key?: string | null
|
data_key?: string | null
|
||||||
data_value?: string | null
|
data_value?: string | null
|
||||||
|
|
@ -310,52 +287,3 @@ export interface ApprovalFlowNode {
|
||||||
updated_at?: string
|
updated_at?: string
|
||||||
children?: ApprovalFlowNode[]
|
children?: ApprovalFlowNode[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TargetFilters {
|
|
||||||
user_ids?: number[]
|
|
||||||
role_ids?: number[]
|
|
||||||
role_type_flags?: string[] // 'director' | 'approver' | 'observer' | 'executor' | 'controller'
|
|
||||||
department_ids?: number[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface NotificationRecipient {
|
|
||||||
id?: number
|
|
||||||
notification_id?: number
|
|
||||||
user_id?: number
|
|
||||||
status?: string // pending | sent | failed
|
|
||||||
error_message?: string
|
|
||||||
telegram_message_id?: number
|
|
||||||
sent_at?: string
|
|
||||||
created_at?: string
|
|
||||||
user?: User
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Notification {
|
|
||||||
id?: number
|
|
||||||
title: string
|
|
||||||
message_html: string
|
|
||||||
photo_base64?: string
|
|
||||||
photo_file_name?: string
|
|
||||||
target_filters?: string // JSON-строка от бэкенда
|
|
||||||
status?: string // pending | sending | completed | failed
|
|
||||||
total_count?: number
|
|
||||||
sent_count?: number
|
|
||||||
failed_count?: number
|
|
||||||
created_by_id?: number
|
|
||||||
created_at?: string
|
|
||||||
updated_at?: string
|
|
||||||
sent_at?: string
|
|
||||||
recipients?: NotificationRecipient[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MonthlyOrderSetting {
|
|
||||||
id?: number
|
|
||||||
month?: number
|
|
||||||
year?: number
|
|
||||||
deadline_date: string | null
|
|
||||||
assembly_time_days: number
|
|
||||||
market_stage?: string | null
|
|
||||||
market_stage_comment?: string | null
|
|
||||||
created_at?: string
|
|
||||||
updated_at?: string
|
|
||||||
}
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
import dayjs from 'dayjs'
|
|
||||||
import utc from 'dayjs/plugin/utc'
|
|
||||||
import timezone from 'dayjs/plugin/timezone'
|
|
||||||
import 'dayjs/locale/ru'
|
|
||||||
|
|
||||||
dayjs.extend(utc)
|
|
||||||
dayjs.extend(timezone)
|
|
||||||
dayjs.locale('ru')
|
|
||||||
|
|
||||||
export const MSK_TZ = 'Europe/Moscow'
|
|
||||||
|
|
||||||
// Даты с бэкенда обычно приходят в UTC (ISO-строка с 'Z') — если форматировать
|
|
||||||
// их через голый dayjs(date).format(...), время покажется в часовом поясе
|
|
||||||
// БРАУЗЕРА администратора, а не по МСК. Эта функция всегда приводит к
|
|
||||||
// Europe/Moscow независимо от того, где физически находится админ.
|
|
||||||
export function formatMsk(
|
|
||||||
date: string | Date | null | undefined,
|
|
||||||
fmt: string = 'DD.MM.YYYY HH:mm'
|
|
||||||
): string {
|
|
||||||
if (!date) return '—'
|
|
||||||
return dayjs(date).tz(MSK_TZ).format(fmt)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Текущее время по МСК — например, для имени скачиваемого файла отчёта.
|
|
||||||
export function mskNow() {
|
|
||||||
return dayjs().tz(MSK_TZ)
|
|
||||||
}
|
|
||||||
Loading…
Reference in New Issue