260303_01_ENH: TanStack Query 적용
This commit is contained in:
207
package-lock.json
generated
207
package-lock.json
generated
@@ -18,6 +18,7 @@
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@tanstack/react-query": "^5.90.21",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tiptap/extension-color": "^3.13.0",
|
||||
"@tiptap/extension-highlight": "^3.13.0",
|
||||
@@ -39,7 +40,6 @@
|
||||
"cmdk": "^1.1.1",
|
||||
"crypto-js": "^4.2.0",
|
||||
"jotai": "^2.15.1",
|
||||
"lodash": "^4.17.21",
|
||||
"lucide-react": "^0.553.0",
|
||||
"next": "^16.0.7",
|
||||
"next-themes": "^0.4.6",
|
||||
@@ -50,6 +50,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@tanstack/react-query-devtools": "^5.91.3",
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
@@ -1043,9 +1044,10 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/env": {
|
||||
"version": "16.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-16.0.10.tgz",
|
||||
"integrity": "sha512-8tuaQkyDVgeONQ1MeT9Mkk8pQmZapMKFh5B+OrFUlG3rVmYTXcXlBetBgTurKXGaIZvkoqRT9JL5K3phXcgang=="
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-16.1.6.tgz",
|
||||
"integrity": "sha512-N1ySLuZjnAtN3kFnwhAwPvZah8RJxKasD7x1f8shFqhncnWZn4JMfg37diLNuoHsLAlrDfM3g4mawVdtAG8XLQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@next/eslint-plugin-next": {
|
||||
"version": "16.0.7",
|
||||
@@ -1057,12 +1059,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-darwin-arm64": {
|
||||
"version": "16.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.0.10.tgz",
|
||||
"integrity": "sha512-4XgdKtdVsaflErz+B5XeG0T5PeXKDdruDf3CRpnhN+8UebNa5N2H58+3GDgpn/9GBurrQ1uWW768FfscwYkJRg==",
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.1.6.tgz",
|
||||
"integrity": "sha512-wTzYulosJr/6nFnqGW7FrG3jfUUlEf8UjGA0/pyypJl42ExdVgC6xJgcXQ+V8QFn6niSG2Pb8+MIG1mZr2vczw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
@@ -1072,12 +1075,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-darwin-x64": {
|
||||
"version": "16.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.0.10.tgz",
|
||||
"integrity": "sha512-spbEObMvRKkQ3CkYVOME+ocPDFo5UqHb8EMTS78/0mQ+O1nqE8toHJVioZo4TvebATxgA8XMTHHrScPrn68OGw==",
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.1.6.tgz",
|
||||
"integrity": "sha512-BLFPYPDO+MNJsiDWbeVzqvYd4NyuRrEYVB5k2N3JfWncuHAy2IVwMAOlVQDFjj+krkWzhY2apvmekMkfQR0CUQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
@@ -1087,12 +1091,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-arm64-gnu": {
|
||||
"version": "16.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.0.10.tgz",
|
||||
"integrity": "sha512-uQtWE3X0iGB8apTIskOMi2w/MKONrPOUCi5yLO+v3O8Mb5c7K4Q5KD1jvTpTF5gJKa3VH/ijKjKUq9O9UhwOYw==",
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.1.6.tgz",
|
||||
"integrity": "sha512-OJYkCd5pj/QloBvoEcJ2XiMnlJkRv9idWA/j0ugSuA34gMT6f5b7vOiCQHVRpvStoZUknhl6/UxOXL4OwtdaBw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
@@ -1102,12 +1107,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-arm64-musl": {
|
||||
"version": "16.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.0.10.tgz",
|
||||
"integrity": "sha512-llA+hiDTrYvyWI21Z0L1GiXwjQaanPVQQwru5peOgtooeJ8qx3tlqRV2P7uH2pKQaUfHxI/WVarvI5oYgGxaTw==",
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.1.6.tgz",
|
||||
"integrity": "sha512-S4J2v+8tT3NIO9u2q+S0G5KdvNDjXfAv06OhfOzNDaBn5rw84DGXWndOEB7d5/x852A20sW1M56vhC/tRVbccQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
@@ -1117,12 +1123,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-x64-gnu": {
|
||||
"version": "16.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.0.10.tgz",
|
||||
"integrity": "sha512-AK2q5H0+a9nsXbeZ3FZdMtbtu9jxW4R/NgzZ6+lrTm3d6Zb7jYrWcgjcpM1k8uuqlSy4xIyPR2YiuUr+wXsavA==",
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.1.6.tgz",
|
||||
"integrity": "sha512-2eEBDkFlMMNQnkTyPBhQOAyn2qMxyG2eE7GPH2WIDGEpEILcBPI/jdSv4t6xupSP+ot/jkfrCShLAa7+ZUPcJQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
@@ -1132,12 +1139,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-x64-musl": {
|
||||
"version": "16.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.0.10.tgz",
|
||||
"integrity": "sha512-1TDG9PDKivNw5550S111gsO4RGennLVl9cipPhtkXIFVwo31YZ73nEbLjNC8qG3SgTz/QZyYyaFYMeY4BKZR/g==",
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.1.6.tgz",
|
||||
"integrity": "sha512-oicJwRlyOoZXVlxmIMaTq7f8pN9QNbdes0q2FXfRsPhfCi8n8JmOZJm5oo1pwDaFbnnD421rVU409M3evFbIqg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
@@ -1147,12 +1155,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-arm64-msvc": {
|
||||
"version": "16.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.0.10.tgz",
|
||||
"integrity": "sha512-aEZIS4Hh32xdJQbHz121pyuVZniSNoqDVx1yIr2hy+ZwJGipeqnMZBJHyMxv2tiuAXGx6/xpTcQJ6btIiBjgmg==",
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.1.6.tgz",
|
||||
"integrity": "sha512-gQmm8izDTPgs+DCWH22kcDmuUp7NyiJgEl18bcr8irXA5N2m2O+JQIr6f3ct42GOs9c0h8QF3L5SzIxcYAAXXw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
@@ -1162,12 +1171,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-x64-msvc": {
|
||||
"version": "16.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.0.10.tgz",
|
||||
"integrity": "sha512-E+njfCoFLb01RAFEnGZn6ERoOqhK1Gl3Lfz1Kjnj0Ulfu7oJbuMyvBKNj/bw8XZnenHDASlygTjZICQW+rYW1Q==",
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.1.6.tgz",
|
||||
"integrity": "sha512-NRfO39AIrzBnixKbjuo2YiYhB6o9d8v/ymU9m/Xk8cyVk+k7XylniXkHwjs4s70wedVffc6bQNbufk5v0xEm0A==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
@@ -2435,6 +2445,61 @@
|
||||
"tailwindcss": "4.1.17"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/query-core": {
|
||||
"version": "5.90.20",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.20.tgz",
|
||||
"integrity": "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/query-devtools": {
|
||||
"version": "5.93.0",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/query-devtools/-/query-devtools-5.93.0.tgz",
|
||||
"integrity": "sha512-+kpsx1NQnOFTZsw6HAFCW3HkKg0+2cepGtAWXjiiSOJJ1CtQpt72EE2nyZb+AjAbLRPoeRmPJ8MtQd8r8gsPdg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/react-query": {
|
||||
"version": "5.90.21",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.21.tgz",
|
||||
"integrity": "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@tanstack/query-core": "5.90.20"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^18 || ^19"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/react-query-devtools": {
|
||||
"version": "5.91.3",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/react-query-devtools/-/react-query-devtools-5.91.3.tgz",
|
||||
"integrity": "sha512-nlahjMtd/J1h7IzOOfqeyDh5LNfG0eULwlltPEonYy0QL+nqrBB+nyzJfULV+moL7sZyxc2sHdNJki+vLA9BSA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@tanstack/query-devtools": "5.93.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tanstack/react-query": "^5.90.20",
|
||||
"react": "^18 || ^19"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/react-table": {
|
||||
"version": "8.21.3",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/react-table/-/react-table-8.21.3.tgz",
|
||||
@@ -3262,13 +3327,27 @@
|
||||
"typescript": ">=4.8.4 <6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
|
||||
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
|
||||
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
|
||||
"version": "5.0.3",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.3.tgz",
|
||||
"integrity": "sha512-fy6KJm2RawA5RcHkLa1z/ScpBeA762UF9KmZQxwIbDtRJrgLzM10depAiEQ+CXYcoiqW1/m96OAAoke2nE9EeA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0"
|
||||
"balanced-match": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/fast-glob": {
|
||||
@@ -3300,12 +3379,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
|
||||
"version": "9.0.5",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
|
||||
"integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",
|
||||
"version": "9.0.8",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.8.tgz",
|
||||
"integrity": "sha512-reYkDYtj/b19TeqbNZCV4q9t+Yxylf/rYBsLb42SXJatTv4/ylq5lEiAmhA/IToxO7NI2UzNMghHoHuaqDkAjw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^2.0.1"
|
||||
"brace-expansion": "^5.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
@@ -3638,10 +3718,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ajv": {
|
||||
"version": "6.12.6",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
|
||||
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
|
||||
"version": "6.14.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",
|
||||
"integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.1",
|
||||
"fast-json-stable-stringify": "^2.0.0",
|
||||
@@ -3912,7 +3993,6 @@
|
||||
"version": "2.8.27",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.8.27.tgz",
|
||||
"integrity": "sha512-2CXFpkjVnY2FT+B6GrSYxzYf65BJWEqz5tIRHCvNsZZ2F3CmsCB37h8SpYgKG7y9C4YAeTipIPWG7EmFmhAeXA==",
|
||||
"devOptional": true,
|
||||
"bin": {
|
||||
"baseline-browser-mapping": "dist/cli.js"
|
||||
}
|
||||
@@ -6270,11 +6350,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
"version": "4.17.21",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
||||
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
|
||||
},
|
||||
"node_modules/lodash.merge": {
|
||||
"version": "4.6.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
|
||||
@@ -6320,9 +6395,10 @@
|
||||
}
|
||||
},
|
||||
"node_modules/markdown-it": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz",
|
||||
"integrity": "sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==",
|
||||
"version": "14.1.1",
|
||||
"resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.1.tgz",
|
||||
"integrity": "sha512-BuU2qnTti9YKgK5N+IeMubp14ZUKUUw7yeJbkjtosvHiP0AZ5c8IAgEMk79D0eC8F23r4Ac/q8cAIFdm2FtyoA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1",
|
||||
"entities": "^4.4.0",
|
||||
@@ -6372,10 +6448,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/minimatch": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
|
||||
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
|
||||
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^1.1.7"
|
||||
},
|
||||
@@ -6437,12 +6514,14 @@
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/next": {
|
||||
"version": "16.0.10",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-16.0.10.tgz",
|
||||
"integrity": "sha512-RtWh5PUgI+vxlV3HdR+IfWA1UUHu0+Ram/JBO4vWB54cVPentCD0e+lxyAYEsDTqGGMg7qpjhKh6dc6aW7W/sA==",
|
||||
"version": "16.1.6",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-16.1.6.tgz",
|
||||
"integrity": "sha512-hkyRkcu5x/41KoqnROkfTm2pZVbKxvbZRuNvKXLRXxs3VfyO0WhY50TQS40EuKO9SW3rBj/sF3WbVwDACeMZyw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@next/env": "16.0.10",
|
||||
"@next/env": "16.1.6",
|
||||
"@swc/helpers": "0.5.15",
|
||||
"baseline-browser-mapping": "^2.8.3",
|
||||
"caniuse-lite": "^1.0.30001579",
|
||||
"postcss": "8.4.31",
|
||||
"styled-jsx": "5.1.6"
|
||||
@@ -6454,14 +6533,14 @@
|
||||
"node": ">=20.9.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@next/swc-darwin-arm64": "16.0.10",
|
||||
"@next/swc-darwin-x64": "16.0.10",
|
||||
"@next/swc-linux-arm64-gnu": "16.0.10",
|
||||
"@next/swc-linux-arm64-musl": "16.0.10",
|
||||
"@next/swc-linux-x64-gnu": "16.0.10",
|
||||
"@next/swc-linux-x64-musl": "16.0.10",
|
||||
"@next/swc-win32-arm64-msvc": "16.0.10",
|
||||
"@next/swc-win32-x64-msvc": "16.0.10",
|
||||
"@next/swc-darwin-arm64": "16.1.6",
|
||||
"@next/swc-darwin-x64": "16.1.6",
|
||||
"@next/swc-linux-arm64-gnu": "16.1.6",
|
||||
"@next/swc-linux-arm64-musl": "16.1.6",
|
||||
"@next/swc-linux-x64-gnu": "16.1.6",
|
||||
"@next/swc-linux-x64-musl": "16.1.6",
|
||||
"@next/swc-win32-arm64-msvc": "16.1.6",
|
||||
"@next/swc-win32-x64-msvc": "16.1.6",
|
||||
"sharp": "^0.34.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@tanstack/react-query": "^5.90.21",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tiptap/extension-color": "^3.13.0",
|
||||
"@tiptap/extension-highlight": "^3.13.0",
|
||||
@@ -40,7 +41,6 @@
|
||||
"cmdk": "^1.1.1",
|
||||
"crypto-js": "^4.2.0",
|
||||
"jotai": "^2.15.1",
|
||||
"lodash": "^4.17.21",
|
||||
"lucide-react": "^0.553.0",
|
||||
"next": "^16.0.7",
|
||||
"next-themes": "^0.4.6",
|
||||
@@ -51,6 +51,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@tanstack/react-query-devtools": "^5.91.3",
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
|
||||
@@ -1,138 +1,137 @@
|
||||
'use client'
|
||||
|
||||
import {useEffect, useState} from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import { DataTable } from "@/components/data-table/DataTable";
|
||||
import { getUserColumns } from "../../../../../components/table-column/UserTableColumn";
|
||||
import _ from "lodash";
|
||||
import { getUserColumns } from "@/components/table-column/UserTableColumn";
|
||||
import UserUpsertDialog from "@/components/dialog/UserUpsertDialog";
|
||||
import {UserInfo, UserInfoSaveRequest, UserUploadResponse} from "@/types/user";
|
||||
import {UserInfo, UserInfoSaveRequest} from "@/types/user";
|
||||
import UserUploadDialog from "@/components/dialog/UserUploadDialog";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {downloadBase64File, downloadFile} from "@/lib/utils";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {RoleInfo} from "@/types/role";
|
||||
import {DataVerification} from "@/types/common";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
import {KriMultiSelect} from "@/components/common/KriAutoComplete";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {DEFAULT_COMPANY_NAME, EXTERNAL_USER_ROLE} from "@/const/userConst";
|
||||
import {
|
||||
useRoleListQuery,
|
||||
useUserCompaniesQuery,
|
||||
useUsersQuery,
|
||||
useUserDetailQuery,
|
||||
useCheckUserIdDuplicateMutation,
|
||||
useUpsertUserMutation,
|
||||
useDeleteUserMutation,
|
||||
useUploadUsersExcelMutation,
|
||||
useDownloadUserExcelTemplateMutation,
|
||||
} from "@/query/user";
|
||||
|
||||
const UserManagePage = () => {
|
||||
const { showDialog } = useDialog();
|
||||
const mounted = useMounted();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const { auth } = useAuth();
|
||||
|
||||
const [userList, setUserList] = useState<UserInfo[]>([]);
|
||||
const [viewList, setViewList] = useState<UserInfo[]>([]);
|
||||
const [selectedUserArray, setSelectedUserArray] = useState<UserInfo[]>([]);
|
||||
const [userCmpnArray, setUserCmpnArray] = useState<string[]>([]);
|
||||
const [userRoleArray, setUserRoleArray] = useState<MultiSelectOption[]>([]);
|
||||
const { auth } = useAuth();
|
||||
const roleQuery = useRoleListQuery();
|
||||
const cmpnQuery = useUserCompaniesQuery();
|
||||
const usersQuery = useUsersQuery();
|
||||
|
||||
const checkDupMutation = useCheckUserIdDuplicateMutation();
|
||||
const upsertMutation = useUpsertUserMutation();
|
||||
const deleteMutation = useDeleteUserMutation();
|
||||
const uploadMutation = useUploadUsersExcelMutation();
|
||||
const downloadTemplateMutation = useDownloadUserExcelTemplateMutation();
|
||||
|
||||
const [editUserId, setEditUserId] = useState<string | null>(null);
|
||||
const userDetailQuery = useUserDetailQuery(editUserId ?? "", !!editUserId);
|
||||
|
||||
const userRoleArray: MultiSelectOption[] = useMemo(() => {
|
||||
const roles = roleQuery.data ?? [];
|
||||
return roles.map((r) => ({ value: String(r.roleCd), label: r.roleNm }));
|
||||
}, [roleQuery.data]);
|
||||
|
||||
const userCmpnArray = cmpnQuery.data ?? [];
|
||||
const userList = usersQuery.data ?? [];
|
||||
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [searchCmpn, setSearchCmpn] = useState<string[]>([]);
|
||||
const [searchRole, setSearchRole] = useState<string[]>([]);
|
||||
|
||||
const [dialogMode, setDialogMode] = useState<'create' | 'edit'>('create')
|
||||
const [editData, setEditData] = useState<Partial<UserInfoSaveRequest>>();
|
||||
|
||||
const setUserData = async () => {
|
||||
const roleList = await nextApi.get<RoleInfo[]>("/role");
|
||||
setUserRoleArray(
|
||||
roleList.map((role) => ({
|
||||
value: String(role.roleCd),
|
||||
label: role.roleNm,
|
||||
}))
|
||||
);
|
||||
const viewList = useMemo(() => {
|
||||
let temp = userList;
|
||||
|
||||
const cmpnList = await nextApi.get<string[]>("/user/cmpn");
|
||||
setUserCmpnArray(cmpnList);
|
||||
const keyword = searchText.trim();
|
||||
if (keyword) {
|
||||
const kw = keyword.toLowerCase();
|
||||
temp = temp.filter((row) =>
|
||||
[row.userId, row.userName].some((v) => (v ?? "").toLowerCase().includes(kw))
|
||||
);
|
||||
}
|
||||
|
||||
const userData = await nextApi.get<UserInfo[]>("/user");
|
||||
setUserList(userData);
|
||||
}
|
||||
if (searchCmpn.length > 0) {
|
||||
temp = temp.filter((row) => searchCmpn.includes(row.userCmpn));
|
||||
}
|
||||
|
||||
if (searchRole.length > 0) {
|
||||
temp = temp.filter((row) => searchRole.includes(String(row.userRole)));
|
||||
}
|
||||
|
||||
return temp;
|
||||
}, [userList, searchText, searchCmpn, searchRole]);
|
||||
|
||||
// 등록 버튼 클릭
|
||||
const handleCreateClick = () => {
|
||||
setDialogMode('create');
|
||||
setEditData(undefined);
|
||||
showDialog('userUpsertDialog');
|
||||
}
|
||||
setDialogMode("create");
|
||||
setEditUserId(null);
|
||||
showDialog("userUpsertDialog");
|
||||
};
|
||||
|
||||
// 중복 체크
|
||||
const handleCheckDuplicate = async (userId: string): Promise<DataVerification> => {
|
||||
return nextApi.get<DataVerification>("/user/check-user-id", {
|
||||
query: { userId },
|
||||
});
|
||||
}
|
||||
const handleCheckDuplicate = (userId: string) => {
|
||||
return checkDupMutation.mutateAsync(userId);
|
||||
};
|
||||
|
||||
|
||||
const handleSubmit = async (data: UserInfoSaveRequest): Promise<void> => {
|
||||
if (dialogMode === 'create') {
|
||||
await nextApi.put<void>("/user", data);
|
||||
await upsertMutation.mutateAsync({ mode: dialogMode, data });
|
||||
|
||||
if (dialogMode === "create") {
|
||||
alert("등록 됐습니다.");
|
||||
} else {
|
||||
await nextApi.patch<void>("/user", data);
|
||||
alert("수정 됐습니다.");
|
||||
}
|
||||
await setUserData();
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (userId: string) => {
|
||||
setDialogMode('edit');
|
||||
nextApi.get<UserInfo>(`/user/${userId}`)
|
||||
.then((data) => {
|
||||
setEditData(data);
|
||||
showDialog('userUpsertDialog');
|
||||
})
|
||||
.catch((e) => {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
});
|
||||
// 수정 로직 또는 모달 열기
|
||||
}
|
||||
setDialogMode("edit");
|
||||
setEditUserId(userId);
|
||||
showDialog("userUpsertDialog");
|
||||
};
|
||||
|
||||
const handleDelete = (userId: string) => {
|
||||
// 삭제 확인 후 데이터 삭제
|
||||
if (confirm('정말 삭제하시겠습니까?')) {
|
||||
//삭제
|
||||
nextApi.del<void>(`/user/${encodeURIComponent(userId)}`)
|
||||
.then(async () => {
|
||||
alert("삭제 됐습니다.");
|
||||
await setUserData();
|
||||
})
|
||||
.catch((e) => {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
});
|
||||
}
|
||||
}
|
||||
const handleDelete = async (userId: string) => {
|
||||
if (!confirm("정말 삭제하시겠습니까?")) return;
|
||||
|
||||
await deleteMutation.mutateAsync(userId);
|
||||
alert("삭제 됐습니다.");
|
||||
};
|
||||
|
||||
const uploadFile = async (file: File) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file); // key 이름은 백엔드 @RequestPart("file") 와 동일해야 함
|
||||
|
||||
const res = await nextApi.postForm<UserUploadResponse>("/user/excel", formData);
|
||||
const res = await uploadMutation.mutateAsync(file);
|
||||
|
||||
if (res.hasErrorFile && res.errorFileBase64) {
|
||||
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx");
|
||||
}
|
||||
else{
|
||||
await setUserData();
|
||||
alert(`${res.successCount}개의 계정을 생성했습니다.`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const downloadTemplate = async () => {
|
||||
const buffer = await nextApi.post<ArrayBuffer>(
|
||||
"/user/excel-template",
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
const buffer = await downloadTemplateMutation.mutateAsync();
|
||||
|
||||
if (buffer.byteLength > 0) {
|
||||
const blob = new Blob([buffer], {
|
||||
@@ -143,7 +142,7 @@ const UserManagePage = () => {
|
||||
} else {
|
||||
console.log("빈 파일입니다.");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const columns = getUserColumns(
|
||||
{
|
||||
@@ -153,30 +152,6 @@ const UserManagePage = () => {
|
||||
userRoleArray
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(setUserData);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let tempData = _.cloneDeep(userList);
|
||||
const keyword = searchText.trim();
|
||||
if (keyword){
|
||||
tempData = tempData.filter((row) =>
|
||||
[row.userId, row.userName].some((v) => v.toLowerCase().includes(keyword.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
if(searchCmpn.length > 0){
|
||||
tempData = tempData.filter((row) => searchCmpn.includes(row.userCmpn));
|
||||
}
|
||||
|
||||
if(searchRole.length > 0){
|
||||
tempData = tempData.filter((row) => searchRole.includes(String(row.userRole)));
|
||||
}
|
||||
|
||||
setViewList(tempData);
|
||||
}, [searchText, searchCmpn, searchRole, userList]);
|
||||
|
||||
const isInternal =
|
||||
mounted &&
|
||||
auth.user?.userRole != null &&
|
||||
@@ -240,7 +215,6 @@ const UserManagePage = () => {
|
||||
data={viewList}
|
||||
isClient={true}
|
||||
selectMode='single'
|
||||
onRowSelectionChange={setSelectedUserArray}
|
||||
defaultPageSize={10}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.userId} // row.id = userId
|
||||
@@ -249,7 +223,7 @@ const UserManagePage = () => {
|
||||
|
||||
<UserUpsertDialog
|
||||
mode={dialogMode}
|
||||
initialData={editData}
|
||||
initialData={dialogMode === "edit" ? (userDetailQuery.data ?? undefined) : undefined}
|
||||
isInternal={isInternal}
|
||||
userCmpn={userCmpn}
|
||||
userCmpnArray={userCmpnArray}
|
||||
|
||||
@@ -1,57 +1,90 @@
|
||||
'use client'
|
||||
import {useEffect, useRef, useState} from "react";
|
||||
import {useMemo, useState} from "react";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {DataTable} from "@/components/data-table/DataTable";
|
||||
import {getProjectColumns} from "../../../components/table-column/ProjectTableColumn";
|
||||
import {getProjectColumns} from "@/components/table-column/ProjectTableColumn";
|
||||
import {
|
||||
ProjectCreateRequest,
|
||||
ProjectInfo,
|
||||
ProjectListQuery,
|
||||
ProjectListRequest, ProjectOwnerResponse,
|
||||
ProjectStatus
|
||||
} from "@/types/project";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {KriMultiSelect} from "@/components/common/KriAutoComplete";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import {PaginationState, SortingState} from "@tanstack/react-table";
|
||||
import {PageRequest, PageResponse} from "@/types/common";
|
||||
import ProjectCreateDialog from "@/components/dialog/ProjectCreateDialog";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {SelectedProject} from "@/store/jotai/project";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {FW_USER_ROLE} from "@/const/userConst";
|
||||
import {useItrntUserList} from "@/hooks/useItrntUserList";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
|
||||
import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
||||
|
||||
const MainPage = () => {
|
||||
const router = useRouter();
|
||||
|
||||
const mounted = useMounted();
|
||||
const { users, isLoading } = useItrntUserList();
|
||||
const { showDialog } = useDialog();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const mounted = useMounted();
|
||||
const { auth } = useAuth();
|
||||
const { clearSelectedProject, setSelectedProject } = useSelectedProject();
|
||||
|
||||
const [statusArray, setStatusArray] = useState<MultiSelectOption[]>([]);
|
||||
const [deptArray, setDeptArray] = useState<string[]>([]);
|
||||
const [fwArray, setFwArray] = useState<string[]>([]);
|
||||
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [searchStatus, setSearchStatus] = useState<string[]>([]);
|
||||
const [searchDept, setSearchDept] = useState<string[]>([]);
|
||||
const [searchFw, setSearchFw] = useState<string[]>([]);
|
||||
const { setSelectedProject } = useSelectedProject();
|
||||
|
||||
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 });
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [query, setQuery] = useState<ProjectListQuery>();
|
||||
|
||||
const [viewList, setViewList] = useState<ProjectInfo[]>([]);
|
||||
const [pageCount, setPageCount] = useState(0);
|
||||
const [totalCount, setTotalCount] = useState(0);
|
||||
|
||||
const statusArray: MultiSelectOption[] = useMemo(() => {
|
||||
return (Object.values(ProjectStatus).filter((v) => typeof v === "number") as number[])
|
||||
.sort((a, b) => a - b)
|
||||
.map((v) => ({
|
||||
value: String(v),
|
||||
label: PROJECT_STATUS_LABEL[v as ProjectStatus],
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const enabled = mounted && !isLoading; // intranet user list 준비된 뒤에만 호출
|
||||
const ownerQuery = useProjectOwnerListQuery(enabled);
|
||||
|
||||
const deptArray = ownerQuery.data?.ownerDeptList ?? [];
|
||||
const fwArray = useMemo(() => {
|
||||
const ownerFwIDList = ownerQuery.data?.ownerFwList ?? [];
|
||||
|
||||
return ownerFwIDList.map((fwID) => ({
|
||||
value: fwID,
|
||||
label: users.find(u => u.userId === fwID)?.userNm ?? "",
|
||||
}));
|
||||
|
||||
}, [ownerQuery.data?.ownerFwList]);
|
||||
|
||||
const sort = sorting?.[0] ?? { id: "prjctIdx", desc: true as const };
|
||||
|
||||
const listQuery = useProjectListQuery({
|
||||
query,
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
sortBy: sort.id,
|
||||
sortDir: sort.desc ? "desc" : "asc",
|
||||
enabled,
|
||||
});
|
||||
|
||||
const viewList = listQuery.data?.content ?? [];
|
||||
const totalCount = listQuery.data?.totalElements ?? 0;
|
||||
const pageCount = listQuery.data?.totalPages ?? 0;
|
||||
|
||||
const createMutation = useCreateProjectMutation?.();
|
||||
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [searchStatus, setSearchStatus] = useState<string[]>([]);
|
||||
const [searchDept, setSearchDept] = useState<string[]>([]);
|
||||
const [searchFw, setSearchFw] = useState<string[]>([]);
|
||||
|
||||
const columns = getProjectColumns(users);
|
||||
const userId = auth.user?.userId ?? "";
|
||||
@@ -76,8 +109,9 @@ const MainPage = () => {
|
||||
showDialog('projectCreateDialog');
|
||||
}
|
||||
|
||||
const handleSubmit = async (data:ProjectCreateRequest): Promise<void> => {
|
||||
const projectInfo = await nextApi.put<ProjectInfo>("/project", data);
|
||||
const handleSubmit = async (data: ProjectCreateRequest): Promise<void> => {
|
||||
const projectInfo = await createMutation.mutateAsync(data);
|
||||
|
||||
setSelectedProject({
|
||||
prjctIdx: projectInfo.prjctIdx,
|
||||
prjctCd: projectInfo.prjctCd,
|
||||
@@ -87,8 +121,8 @@ const MainPage = () => {
|
||||
ownerFw: projectInfo.ownerFw,
|
||||
} as SelectedProject);
|
||||
|
||||
window.location.href = `/project/info`;
|
||||
}
|
||||
router.push("/project/info");
|
||||
};
|
||||
|
||||
const handleClick = (projectInfo:ProjectInfo) => {
|
||||
setSelectedProject({
|
||||
@@ -100,65 +134,9 @@ const MainPage = () => {
|
||||
ownerFw: projectInfo.ownerFw,
|
||||
} as SelectedProject);
|
||||
|
||||
window.location.href = `/list/manage`;
|
||||
router.push(`/list/manage`);
|
||||
}
|
||||
|
||||
// 중복 호출 방지(초기 mount에서 pagination/sorting 콜백이 각각 한번씩 날아오는 케이스 방어)
|
||||
const lastReqKeyRef = useRef<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
const reqKey = JSON.stringify({ query, pagination, sorting});
|
||||
if (lastReqKeyRef.current === reqKey) return;
|
||||
lastReqKeyRef.current = reqKey;
|
||||
|
||||
const sort = sorting?.[0] ?? {id: "prjctIdx", desc: true};
|
||||
const pageReq: PageRequest = {
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
sortBy: sort.id,
|
||||
sortDir: sort.desc ? "desc" : "asc"
|
||||
};
|
||||
|
||||
const searchBody: ProjectListRequest = {
|
||||
prjctText: query?.prjctText || "",
|
||||
prjctStatusList: query?.prjctStatusList || [],
|
||||
ownerDeptList: query?.ownerDeptList || [],
|
||||
ownerFwList: query?.ownerFwList || [],
|
||||
pageRequest: pageReq,
|
||||
}
|
||||
|
||||
withLoadingAsync(() =>
|
||||
nextApi.post<PageResponse<ProjectInfo>>("/project/list", searchBody)
|
||||
.then((r) => {
|
||||
setViewList(r.content);
|
||||
setTotalCount(r.totalElements);
|
||||
setPageCount(r.totalPages);
|
||||
})
|
||||
.catch(() => {
|
||||
setViewList([]);
|
||||
setTotalCount(0);
|
||||
setPageCount(0);
|
||||
})
|
||||
);
|
||||
|
||||
}, [query, pagination, sorting]);
|
||||
|
||||
useEffect(() => {
|
||||
clearSelectedProject();
|
||||
|
||||
const options: MultiSelectOption[] = Object.entries(ProjectStatus)
|
||||
.sort(([a], [b]) => Number(a) - Number(b))
|
||||
.map(([key, label]) => ({ value: key, label: String(label) }));
|
||||
|
||||
setStatusArray(options);
|
||||
|
||||
nextApi.get<ProjectOwnerResponse>("/project/owner-list")
|
||||
.then((res) => {
|
||||
setDeptArray(res.ownerDeptList);
|
||||
setFwArray(res.ownerFwList);
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (!mounted || isLoading) return <LoadingOverlay force />;
|
||||
|
||||
return (
|
||||
@@ -203,6 +181,8 @@ const MainPage = () => {
|
||||
items={fwArray}
|
||||
value={searchFw}
|
||||
onChange={setSearchFw}
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="담당 실사"
|
||||
widthClassName="w-60"
|
||||
heightClassName="h-9"
|
||||
|
||||
@@ -1,130 +1,130 @@
|
||||
'use client'
|
||||
|
||||
import {useCallback, useEffect, useMemo, useState} from 'react'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import {ProjectInfo} from "@/types/project";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {PROJECT_SEARCH_COUNT} from "@/const/projectConst";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {UserInfo} from "@/types/user";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {KriSelect, KriSelectItem} from "@/components/common/KriSelect";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {RoleInfo} from "@/types/role";
|
||||
import {CONTACT_USER_ROLE, FW_USER_ROLE} from "@/const/userConst";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import _ from "lodash";
|
||||
import { ProjectInfo } from "@/types/project";
|
||||
import { PROJECT_SEARCH_COUNT } from "@/const/projectConst";
|
||||
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
|
||||
import { useMounted } from "@/hooks/useMounted";
|
||||
import { UserInfo } from "@/types/user";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { KriSelect, KriSelectItem } from "@/components/common/KriSelect";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { CONTACT_USER_ROLE, FW_USER_ROLE } from "@/const/userConst";
|
||||
|
||||
import {
|
||||
useFieldworkUsersQuery,
|
||||
useRoleListQuery,
|
||||
useUserCompaniesQuery,
|
||||
} from "@/query/user";
|
||||
|
||||
import {
|
||||
useAssignedFieldworkIdsQuery,
|
||||
useSaveAssignedFieldworkMutation,
|
||||
useProjectTopQuery,
|
||||
} from "@/query/project";
|
||||
|
||||
const ProjectAssignPage = () => {
|
||||
const mounted = useMounted();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
|
||||
const [projectArray, setProjectArray] = useState<ProjectInfo[]>([]);
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0;
|
||||
|
||||
const fwUsersQuery = useFieldworkUsersQuery(enabled);
|
||||
const assignedIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled);
|
||||
const saveAssignMutation = useSaveAssignedFieldworkMutation(prjctIdx);
|
||||
|
||||
const companyQuery = useUserCompaniesQuery();
|
||||
const roleQuery = useRoleListQuery();
|
||||
|
||||
const [searchKeyword, setSearchKeyword] = useState("");
|
||||
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
|
||||
const [sourceProject, setSourceProject] = useState<ProjectInfo>();
|
||||
const projectTopQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, mounted);
|
||||
const projectArray = projectTopQuery.data ?? [];
|
||||
const companyArray = companyQuery.data ?? [];
|
||||
|
||||
const roleArray: KriSelectItem[] = useMemo(() => {
|
||||
const roles = roleQuery.data ?? [];
|
||||
return roles
|
||||
.filter(r => r.roleCd >= FW_USER_ROLE)
|
||||
.map(r => ({ value: String(r.roleCd), label: r.roleNm }));
|
||||
}, [roleQuery.data]);
|
||||
|
||||
const [companyArray, setCompanyArray] = useState<string[]>([]);
|
||||
const [companyFilter, setCompanyFilter] = useState<string>('');
|
||||
const [roleArray, setRoleArray] = useState<KriSelectItem[]>([]);
|
||||
const [roleFilter, setRoleFilter] = useState<KriSelectItem>();
|
||||
const [fwUserArray, setFwUserArray] = useState<UserInfo[]>([]);
|
||||
const [roleFilter, setRoleFilter] = useState<KriSelectItem | undefined>(undefined);
|
||||
const fwUserArray = fwUsersQuery.data ?? [];
|
||||
|
||||
const [originAssign, setOriginAssign] = useState<UserInfo[]>([]);
|
||||
const [assignUserArray, setAssignUserArray] = useState<UserInfo[]>([]);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
|
||||
// 선택/검색(좌/우)
|
||||
const [selectedAssignUser, setSelectedAssignUser] = useState<string[]>([]);
|
||||
const [searchAssign, setSearchAssign] = useState('');
|
||||
const debouncedAssign = useDebouncedValue(searchAssign, 500);
|
||||
|
||||
const [assignInfoString, setAssignInfoString] = useState<string>('');
|
||||
|
||||
const [ableUserArray, setAbleUserArray] = useState<UserInfo[]>([]);
|
||||
const [selectedAbleUser, setSelectedAbleUser] = useState<string[]>([]);
|
||||
const [searchAble, setSearchAble] = useState('');
|
||||
const debouncedAble = useDebouncedValue(searchAble, 500);
|
||||
|
||||
const searchTopProject = async (keyword: string) => {
|
||||
const res = await nextApi.get<ProjectInfo[]>(
|
||||
`/project/top/${PROJECT_SEARCH_COUNT}`,
|
||||
{ query: { keyword } }
|
||||
);
|
||||
|
||||
setProjectArray(res);
|
||||
};
|
||||
|
||||
const handleSelectProject = (info:ProjectInfo|null) => {
|
||||
if(info === null){
|
||||
setSourceProject(undefined)
|
||||
}
|
||||
else{
|
||||
setSourceProject(info);
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectAllLeft = (checked: boolean) => {
|
||||
if (checked) {
|
||||
setSelectedAssignUser(assignUserArray.map(u => u.userId))
|
||||
} else {
|
||||
setSelectedAssignUser([])
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectAllRight = (checked: boolean) => {
|
||||
if (checked) {
|
||||
setSelectedAbleUser(ableUserArray.map(u => u.userId))
|
||||
} else {
|
||||
setSelectedAbleUser([])
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleUnassign = (id: string) => {
|
||||
setSelectedAssignUser(prev =>
|
||||
prev.includes(id)
|
||||
? prev.filter(x => x !== id)
|
||||
: [...prev, id]
|
||||
)
|
||||
}
|
||||
|
||||
const handleToggleAssign = (id: string) => {
|
||||
setSelectedAbleUser(prev =>
|
||||
prev.includes(id)
|
||||
? prev.filter(x => x !== id)
|
||||
: [...prev, id]
|
||||
)
|
||||
}
|
||||
|
||||
const appendUserInfo = (
|
||||
userIdArray:string[],
|
||||
sourceArray:UserInfo[]
|
||||
) => {
|
||||
return sourceArray.filter(user => userIdArray.includes(user.userId));
|
||||
}
|
||||
|
||||
const resetSelect = () => {
|
||||
const resetSelect = useCallback(() => {
|
||||
setSelectedAssignUser([]);
|
||||
setSelectedAbleUser([]);
|
||||
|
||||
//검색도 초기화
|
||||
setSearchAssign('');
|
||||
setSearchAble('');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const resetSelectAndAssign = () => {
|
||||
const resetSelectAndAssign = useCallback(() => {
|
||||
resetSelect();
|
||||
setAssignUserArray(_.cloneDeep(originAssign));
|
||||
setAssignUserArray(structuredClone(originAssign));
|
||||
setDirty(false);
|
||||
}, [originAssign, resetSelect]);
|
||||
|
||||
const [sourceProject, setSourceProject] = useState<ProjectInfo | undefined>(undefined);
|
||||
const handleSelectProject = (info: ProjectInfo | null) => {
|
||||
setSourceProject(info ?? undefined);
|
||||
resetSelect();
|
||||
};
|
||||
|
||||
const sourcePrjctIdx = sourceProject?.prjctIdx ?? 0;
|
||||
const sourceAssignedIdsQuery = useAssignedFieldworkIdsQuery(
|
||||
sourcePrjctIdx,
|
||||
mounted && sourcePrjctIdx > 0
|
||||
);
|
||||
|
||||
const ableUserArray: UserInfo[] = useMemo(() => {
|
||||
if (sourcePrjctIdx > 0) {
|
||||
const ids = sourceAssignedIdsQuery.data ?? [];
|
||||
return fwUserArray.filter(u => ids.includes(u.userId));
|
||||
}
|
||||
return structuredClone(fwUserArray);
|
||||
}, [fwUserArray, sourcePrjctIdx, sourceAssignedIdsQuery.data]);
|
||||
|
||||
const handleSelectAllLeft = (checked: boolean) => {
|
||||
setSelectedAssignUser(checked ? assignView.map(u => u.userId) : []);
|
||||
};
|
||||
|
||||
const handleSelectAllRight = (checked: boolean) => {
|
||||
setSelectedAbleUser(checked ? ableView.map(u => u.userId) : []);
|
||||
};
|
||||
|
||||
const handleToggleUnassign = (id: string) => {
|
||||
setSelectedAssignUser(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
|
||||
};
|
||||
|
||||
const handleToggleAssign = (id: string) => {
|
||||
setSelectedAbleUser(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
|
||||
};
|
||||
|
||||
const handleCompanyChange = (v: string) => {
|
||||
resetSelectAndAssign();
|
||||
setCompanyFilter(v);
|
||||
// 필요하면 데이터도 같이 재조회/재계산 트리거
|
||||
};
|
||||
|
||||
const handleRoleChange = (item: KriSelectItem) => {
|
||||
@@ -132,170 +132,132 @@ const ProjectAssignPage = () => {
|
||||
setRoleFilter(item);
|
||||
};
|
||||
|
||||
const handleAssign = () => {
|
||||
const toAssign = ableUserArray.filter(u => selectedAbleUser.includes(u.userId));
|
||||
setAssignUserArray(prev => [...prev, ...toAssign]);
|
||||
const {
|
||||
assignBase,
|
||||
assignView,
|
||||
ableBase,
|
||||
ableView,
|
||||
} = useMemo(() => {
|
||||
const roleVal = roleFilter?.value;
|
||||
const cmpnVal = companyFilter;
|
||||
|
||||
const passBase = (u: UserInfo) =>
|
||||
(!roleVal || String(u.userRole) === roleVal) &&
|
||||
(!cmpnVal || u.userCmpn === cmpnVal);
|
||||
|
||||
const kwFilter = (u: UserInfo, k: string) =>
|
||||
u.userId.includes(k) || u.userName.includes(k);
|
||||
|
||||
// LEFT
|
||||
const _assignBase = assignUserArray.filter(passBase);
|
||||
const kAssign = debouncedAssign.trim();
|
||||
const _assignView = kAssign ? _assignBase.filter((u) => kwFilter(u, kAssign)) : _assignBase;
|
||||
|
||||
// RIGHT (exclude already assigned)
|
||||
const assignedSet = new Set(assignUserArray.map((u) => u.userId));
|
||||
const _ableBase0 = ableUserArray.filter(passBase).filter((u) => !assignedSet.has(u.userId));
|
||||
const kAble = debouncedAble.trim();
|
||||
const _ableView = kAble ? _ableBase0.filter((u) => kwFilter(u, kAble)) : _ableBase0;
|
||||
|
||||
return {
|
||||
assignBase: _assignBase,
|
||||
assignView: _assignView,
|
||||
ableBase: _ableBase0,
|
||||
ableView: _ableView,
|
||||
};
|
||||
}, [
|
||||
assignUserArray,
|
||||
ableUserArray,
|
||||
roleFilter?.value,
|
||||
companyFilter,
|
||||
debouncedAssign,
|
||||
debouncedAble,
|
||||
]);
|
||||
|
||||
const assignInfoString = useMemo(() => {
|
||||
return roleArray.map(role => {
|
||||
const cnt = originAssign.filter(u => String(u.userRole) === role.value).length;
|
||||
return `${role.label} : ${cnt}`;
|
||||
}).join(' / ');
|
||||
}, [roleArray, originAssign]);
|
||||
|
||||
const handleAssign = () => {
|
||||
const toAssign = ableView.filter(u => selectedAbleUser.includes(u.userId));
|
||||
if (toAssign.length === 0) return;
|
||||
|
||||
setAssignUserArray(prev => [...prev, ...toAssign]);
|
||||
setSelectedAbleUser([]);
|
||||
}
|
||||
setDirty(true);
|
||||
};
|
||||
|
||||
const handleRemove = () => {
|
||||
const toRemove = assignUserArray.filter(u => selectedAssignUser.includes(u.userId));
|
||||
setAssignUserArray(prev => prev.filter(u => !selectedAssignUser.includes(u.userId)));
|
||||
if (selectedAssignUser.length === 0) return;
|
||||
|
||||
setAssignUserArray(prev => prev.filter(u => !selectedAssignUser.includes(u.userId)));
|
||||
setSelectedAssignUser([]);
|
||||
}
|
||||
setDirty(true);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if(selectedProject){
|
||||
await nextApi.put(
|
||||
`/assign/prjct-fieldwork/${selectedProject.prjctIdx}`,
|
||||
assignUserArray.map(u => u.userId)
|
||||
)
|
||||
|
||||
setOriginAssign(_.cloneDeep(assignUserArray));
|
||||
|
||||
alert("저장되었습니다.");
|
||||
}
|
||||
else{
|
||||
if (!selectedProject) {
|
||||
alert("옳지 않은 요청입니다.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const baseFiltered = useCallback((users: UserInfo[]) => {
|
||||
return users.filter(
|
||||
(u) =>
|
||||
String(u.userRole) === roleFilter?.value &&
|
||||
u.userCmpn === companyFilter
|
||||
);
|
||||
}, [roleFilter, companyFilter]);
|
||||
|
||||
const withKeyword = useCallback((users: UserInfo[], keyword: string) => {
|
||||
const k = keyword.trim();
|
||||
if (!k) return users;
|
||||
|
||||
return users.filter(
|
||||
(u) => u.userId.includes(k) || u.userName.includes(k)
|
||||
);
|
||||
}, []);
|
||||
|
||||
const assignBase = useMemo(
|
||||
() => baseFiltered(assignUserArray),
|
||||
[assignUserArray, baseFiltered]
|
||||
);
|
||||
|
||||
const assignView = useMemo(
|
||||
() => withKeyword(assignBase, debouncedAssign),
|
||||
[assignBase, debouncedAssign, withKeyword]
|
||||
);
|
||||
|
||||
const assignedIdSet = useMemo(
|
||||
() => new Set(assignUserArray.map(u => u.userId)),
|
||||
[assignUserArray]
|
||||
);
|
||||
|
||||
const ableBase = useMemo(
|
||||
() => baseFiltered(ableUserArray)
|
||||
.filter((user) => !assignedIdSet.has(user.userId)),
|
||||
[ableUserArray, baseFiltered, assignedIdSet]
|
||||
);
|
||||
|
||||
const ableView = useMemo(
|
||||
() => withKeyword(ableBase, debouncedAble)
|
||||
.filter((user) => !assignedIdSet.has(user.userId)),
|
||||
[ableBase, debouncedAble, withKeyword, assignedIdSet]
|
||||
);
|
||||
await saveAssignMutation.mutateAsync(assignUserArray.map(u => u.userId));
|
||||
setOriginAssign(structuredClone(assignUserArray));
|
||||
setDirty(false);
|
||||
alert("저장되었습니다.");
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if(selectedProject){
|
||||
const keyword = debouncedKeyword.trim();
|
||||
searchTopProject(keyword);
|
||||
}
|
||||
}, [debouncedKeyword]);
|
||||
const cmpn = auth.user?.userCmpn ?? "";
|
||||
if (cmpn) setCompanyFilter(cmpn);
|
||||
}, [auth.user?.userCmpn]);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
nextApi.get<UserInfo[]>("/user/fieldwork")
|
||||
.then(res => setFwUserArray(res));
|
||||
if (roleFilter) return;
|
||||
if (roleArray.length === 0) return;
|
||||
|
||||
nextApi.get<string[]>("/user/cmpn")
|
||||
.then((res) => setCompanyArray(res));
|
||||
|
||||
const roleList = await nextApi.get<RoleInfo[]>("/role")
|
||||
const roleOptionArray = roleList
|
||||
.filter(role => role.roleCd >= FW_USER_ROLE)
|
||||
.map((role) => ({
|
||||
value: String(role.roleCd),
|
||||
label: role.roleNm,
|
||||
}))
|
||||
setRoleArray(roleOptionArray);
|
||||
const contactRole = roleOptionArray.find((role) => role.value === CONTACT_USER_ROLE.toString());
|
||||
if(contactRole){
|
||||
setRoleFilter(contactRole);
|
||||
}
|
||||
})
|
||||
|
||||
}, []);
|
||||
const contactRole = roleArray.find(r => r.value === String(CONTACT_USER_ROLE));
|
||||
setRoleFilter(contactRole ?? roleArray[0]);
|
||||
}, [roleArray, roleFilter]);
|
||||
|
||||
// prjctIdx 바뀌면: 편집 상태 초기화(서버 데이터 다시 주입 받을 준비)
|
||||
useEffect(() => {
|
||||
if(auth.user){
|
||||
setCompanyFilter(auth.user.userCmpn || "")
|
||||
}
|
||||
}, [auth.user]);
|
||||
if (!enabled) return;
|
||||
setDirty(false);
|
||||
resetSelect();
|
||||
setOriginAssign([]);
|
||||
setAssignUserArray([]);
|
||||
}, [enabled, prjctIdx, resetSelect]);
|
||||
|
||||
// 서버 배정 ids + fwUserArray 준비되면 "초기 1회" 주입
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
if(selectedProject){
|
||||
const res = await nextApi.get<string[]>(`/assign/prjct-fieldwork/${selectedProject.prjctIdx}`);
|
||||
const assignUserInfoArray = appendUserInfo(res, fwUserArray);
|
||||
if (!enabled) return;
|
||||
if (dirty) return;
|
||||
|
||||
setAssignUserArray(assignUserInfoArray);
|
||||
setOriginAssign(assignUserInfoArray);
|
||||
}else{
|
||||
setAssignUserArray([]);
|
||||
setOriginAssign([]);
|
||||
}
|
||||
resetSelect();
|
||||
});
|
||||
}, [fwUserArray, selectedProject, roleArray]);
|
||||
const ids = assignedIdsQuery.data;
|
||||
if (!ids) return;
|
||||
|
||||
useEffect(() => {
|
||||
const assignString = roleArray.map((role) => {
|
||||
const assignCount = originAssign.filter(user => user.userRole.toString() === role.value).length
|
||||
return `${role.label} : ${assignCount}`;
|
||||
}).join(' / ');
|
||||
// fwUserArray가 아직 비어있을 수 있으니 둘 다 준비된 상태에서만
|
||||
if (!fwUserArray || fwUserArray.length === 0) return;
|
||||
|
||||
setAssignInfoString(assignString);
|
||||
}, [originAssign]);
|
||||
const assignUserInfoArray = fwUserArray.filter(u => ids.includes(u.userId));
|
||||
setAssignUserArray(assignUserInfoArray);
|
||||
setOriginAssign(structuredClone(assignUserInfoArray));
|
||||
resetSelect();
|
||||
}, [enabled, dirty, assignedIdsQuery.data, fwUserArray, resetSelect]);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
let ableUserList :UserInfo[] = [];
|
||||
|
||||
if(sourceProject){
|
||||
const res = await nextApi.get<string[]>(`/assign/prjct-fieldwork/${sourceProject.prjctIdx}`);
|
||||
ableUserList = appendUserInfo(res, fwUserArray);
|
||||
}
|
||||
else{
|
||||
ableUserList = _.cloneDeep(fwUserArray);
|
||||
}
|
||||
|
||||
setAbleUserArray(ableUserList);
|
||||
});
|
||||
}, [fwUserArray, sourceProject]);
|
||||
|
||||
if (!mounted || !selectedProject) return null
|
||||
if (!mounted || !selectedProject) return null;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-1">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{/* 공용 필터 바 (회사 / 대상) */}
|
||||
<div className="mb-6 rounded-lg border border-gray-200 bg-white p-4 shadow-sm">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<div className="w-full sm:w-auto flex items-center gap-3">
|
||||
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">
|
||||
회사
|
||||
</div>
|
||||
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">회사</div>
|
||||
<KriSelect
|
||||
items={companyArray}
|
||||
value={companyFilter}
|
||||
@@ -307,9 +269,7 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
|
||||
<div className="w-full sm:w-auto flex items-center gap-3">
|
||||
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">
|
||||
대상
|
||||
</div>
|
||||
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">대상</div>
|
||||
<KriSelect
|
||||
items={roleArray}
|
||||
value={roleFilter?.value || ""}
|
||||
@@ -324,14 +284,10 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 메인 배정 영역 */}
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] gap-6 mb-6">
|
||||
{/* 왼쪽: 배정된 면접원 */}
|
||||
<div className="min-w-0">
|
||||
<div className="p-3 bg-black text-white rounded-lg content-text-lg mb-2 h-15 flex items-center">
|
||||
<span className="truncate w-full">
|
||||
{assignInfoString}
|
||||
</span>
|
||||
<span className="truncate w-full">{assignInfoString}</span>
|
||||
</div>
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||
<div className="bg-gray-50 p-3 border-b border-gray-200">
|
||||
@@ -354,12 +310,13 @@ const ProjectAssignPage = () => {
|
||||
className="border-white"
|
||||
/>
|
||||
</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">배정된 {roleFilter?.label} ( {assignBase.length}명 )</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">
|
||||
배정된 {roleFilter?.label} ( {assignBase.length}명 )
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{assignView
|
||||
.map((userInfo) => (
|
||||
{assignView.map((userInfo) => (
|
||||
<tr
|
||||
key={userInfo.userId}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
@@ -385,7 +342,6 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 가운데: 배정/제외 버튼 */}
|
||||
<div className="flex flex-col justify-center gap-4">
|
||||
<Button
|
||||
onClick={handleAssign}
|
||||
@@ -405,11 +361,9 @@ const ProjectAssignPage = () => {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 오른쪽: 전체 면접원 풀 */}
|
||||
<div className="min-w-0">
|
||||
<div className="p-3 bg-black text-white rounded-lg content-text-lg mb-2 h-15">
|
||||
<KriSingleSelect
|
||||
<ProjectInfo>
|
||||
<KriSingleSelect<ProjectInfo>
|
||||
items={projectArray}
|
||||
value={String(sourceProject?.prjctIdx ?? "")}
|
||||
onChange={() => {}}
|
||||
@@ -449,12 +403,13 @@ const ProjectAssignPage = () => {
|
||||
className="border-white"
|
||||
/>
|
||||
</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">배정 가능 {roleFilter?.label} ({ableBase.length}명 )</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">
|
||||
배정 가능 {roleFilter?.label} ({ableBase.length}명 )
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{ableView
|
||||
.map((user) => (
|
||||
{ableView.map((user) => (
|
||||
<tr
|
||||
key={user.userId}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
@@ -481,7 +436,6 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 하단 저장 버튼 */}
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import {useEffect, useState, useCallback, useRef} from 'react'
|
||||
import {useEffect, useState, useCallback, useRef, useMemo} from 'react'
|
||||
import BodyTitle from '@/components/layout/BodyTitle'
|
||||
import {Button} from '@/components/ui/button'
|
||||
import {Input} from '@/components/ui/input'
|
||||
@@ -14,7 +14,7 @@ import ResultCodeDialog from '@/components/dialog/ResultCodeDialog'
|
||||
import {useMounted} from '@/hooks/useMounted'
|
||||
import {LoadingOverlay} from '@/components/common/LoadingOverlay'
|
||||
import {
|
||||
KonKiwiProjectInfo, ProjectInfo, ProjectUpdateRequest, ResultCode,
|
||||
ProjectInfo, ProjectUpdateRequest, ResultCode,
|
||||
ProjectStatus, ResultCodeType, SurveyType
|
||||
} from "@/types/project";
|
||||
import {
|
||||
@@ -26,13 +26,20 @@ import {
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import {FW_TEAM} from "@/const/userConst";
|
||||
import {useItrntUserList} from "@/hooks/useItrntUserList";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {UserInfo} from "@/types/user";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {KriEditor} from "@/components/kri-editor";
|
||||
import _ from "lodash";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {
|
||||
useProjectInfoQuery,
|
||||
useResultCodesQuery,
|
||||
useAssignedOutsourceIdsQuery,
|
||||
useUpdateProjectMutation,
|
||||
useDeleteProjectMutation,
|
||||
useUploadScenarioImageMutation, useKartProjectListQuery,
|
||||
} from "@/query/project";
|
||||
import {useOutsourceUsersQuery} from "@/query/user";
|
||||
|
||||
const defaultProjectInfo: ProjectInfo = {
|
||||
prjctIdx: 0,
|
||||
@@ -54,80 +61,120 @@ const defaultProjectInfo: ProjectInfo = {
|
||||
|
||||
type ExternalTab = 'redirect' | 'api'
|
||||
|
||||
const baseUrl = 'https://kcont.kric.com'
|
||||
const sidParam = 'sid=${$SID}'
|
||||
|
||||
const externalUrls = {
|
||||
redirect: {
|
||||
start: `${baseUrl}/redirect/start?${sidParam}`,
|
||||
complete: `${baseUrl}/redirect/complete?${sidParam}`,
|
||||
screen: `${baseUrl}/redirect/screen?${sidParam}`,
|
||||
quota: `${baseUrl}/redirect/quota?${sidParam}`,
|
||||
},
|
||||
api: {
|
||||
start: `${baseUrl}/api/external/start?${sidParam}`,
|
||||
complete: `${baseUrl}/api/external/complete?${sidParam}`,
|
||||
screen: `${baseUrl}/api/external/screen?${sidParam}`,
|
||||
quota: `${baseUrl}/api/external/quota?${sidParam}`,
|
||||
},
|
||||
} as const
|
||||
|
||||
const internalSurvey = new Set([SurveyType.KON, SurveyType.KIWI]);
|
||||
|
||||
const ProjectInfoPage = () => {
|
||||
const router = useRouter();
|
||||
const mounted = useMounted();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog();
|
||||
const { users, isLoading } = useItrntUserList();
|
||||
const { auth } = useAuth();
|
||||
const {selectedProject} = useSelectedProject();
|
||||
const {isDialogOpen, showDialog, hideDialog} = useDialog();
|
||||
const {users} = useItrntUserList();
|
||||
const {auth} = useAuth();
|
||||
|
||||
const [projectInfo, setProjectInfo] = useState<ProjectInfo>(defaultProjectInfo);
|
||||
const [outsourceUserArray, setOutsourceUserArray] = useState<string[]>([]);
|
||||
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]);
|
||||
const [changeResultCodeType, setChangeResultCodeType] = useState<ResultCodeType[]>([]);
|
||||
|
||||
const [outsourceOptionArray, setOutsourceOptionArray] = useState<MultiSelectOption[]>([]);
|
||||
const [deptArray, setDeptArray] = useState<string[]>([]);
|
||||
const [fwArray, setFwArray] = useState<MultiSelectOption[]>([]);
|
||||
|
||||
const [surveyKeyword, setSurveyKeyword] = useState('');
|
||||
const debouncedKeyword = useDebouncedValue(surveyKeyword, 500);
|
||||
const [surveyProjectArray, setSurveyProjectArray] = useState<KonKiwiProjectInfo[]>([]);
|
||||
|
||||
const [externalTab, setExternalTab] = useState<ExternalTab>('redirect')
|
||||
const sessionTempUrlsRef = useRef<Set<string>>(new Set());
|
||||
|
||||
const internalSurvey = [SurveyType.KON, SurveyType.KIWI];
|
||||
const baseUrl = 'https://kcont.kric.com'
|
||||
const sidParam = 'sid=${$SID}'
|
||||
|
||||
const externalUrls = {
|
||||
redirect: {
|
||||
start: `${baseUrl}/redirect/start?${sidParam}`,
|
||||
complete: `${baseUrl}/redirect/complete?${sidParam}`,
|
||||
screen: `${baseUrl}/redirect/screen?${sidParam}`,
|
||||
quota: `${baseUrl}/redirect/quota?${sidParam}`,
|
||||
},
|
||||
api: {
|
||||
start: `${baseUrl}/api/external/start?${sidParam}`,
|
||||
complete: `${baseUrl}/api/external/complete?${sidParam}`,
|
||||
screen: `${baseUrl}/api/external/screen?${sidParam}`,
|
||||
quota: `${baseUrl}/api/external/quota?${sidParam}`,
|
||||
},
|
||||
} as const
|
||||
|
||||
const userTeam = auth.user?.userTeam ?? "";
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0;
|
||||
|
||||
const searchKonKiwiPrjct = async (keyword:string): Promise<void> => {
|
||||
const surveyType = projectInfo.surveyTy ?? SurveyType.NONE;
|
||||
|
||||
if(internalSurvey.includes(surveyType) && userTeam){
|
||||
const isKiwi = surveyType === SurveyType.KON? 0 : 1;
|
||||
const res = await nextApi.get<KonKiwiProjectInfo[]>(
|
||||
`/kart/project-list/${projectInfo.itrntPrjctCd}/${userTeam}/${isKiwi}`,
|
||||
{ query: keyword ? { keyword } : {} }
|
||||
);
|
||||
const surveyTy = projectInfo.surveyTy ?? SurveyType.NONE;
|
||||
const isInternalSurvey = internalSurvey.has(surveyTy);
|
||||
const isKiwi = surveyTy === SurveyType.KON ? 0 : surveyTy === SurveyType.KIWI ? 1 : 0;
|
||||
|
||||
setSurveyProjectArray(res);
|
||||
}
|
||||
}
|
||||
// 조회 쿼리들
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled);
|
||||
const outsourceUsersQuery = useOutsourceUsersQuery(enabled);
|
||||
const assignedOutsourceQuery = useAssignedOutsourceIdsQuery(prjctIdx, enabled);
|
||||
|
||||
const kartEnabled =
|
||||
mounted &&
|
||||
!!projectInfo.itrntPrjctCd &&
|
||||
!!userTeam &&
|
||||
isInternalSurvey;
|
||||
|
||||
const kartProjectListQuery = useKartProjectListQuery({
|
||||
itrntPrjctCd: projectInfo.itrntPrjctCd,
|
||||
userTeam,
|
||||
isKiwi,
|
||||
keyword: debouncedKeyword,
|
||||
enabled: kartEnabled,
|
||||
});
|
||||
|
||||
const updateMutation = useUpdateProjectMutation(prjctIdx);
|
||||
const deleteMutation = useDeleteProjectMutation(prjctIdx);
|
||||
const uploadScenarioMutation = useUploadScenarioImageMutation(prjctIdx, projectInfo.prjctCd);
|
||||
|
||||
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]);
|
||||
const [outsourceUserArray, setOutsourceUserArray] = useState<string[]>([]);
|
||||
const [changeResultCodeType, setChangeResultCodeType] = useState<ResultCodeType[]>([]);
|
||||
|
||||
const outsourceOptionArray: MultiSelectOption[] = useMemo(() => {
|
||||
const arr = outsourceUsersQuery.data ?? [];
|
||||
return arr.map((u) => ({
|
||||
value: u.userId,
|
||||
label: `${u.userCmpn} / ${u.userName}(${u.userId})`,
|
||||
}));
|
||||
}, [outsourceUsersQuery.data]);
|
||||
|
||||
|
||||
const surveyProjectArray = kartProjectListQuery.data ?? [];
|
||||
|
||||
const deptArray = useMemo(() => {
|
||||
const teams = Array.from(new Set((users ?? []).map((u) => u.userTeam).filter(Boolean)));
|
||||
|
||||
if (!teams.includes("T900")) teams.push("T900"); // TFT
|
||||
|
||||
return teams.sort((a, b) => a.localeCompare(b, "ko"));
|
||||
}, [users]);
|
||||
|
||||
const fwArray: MultiSelectOption[] = useMemo(() => {
|
||||
return (users ?? [])
|
||||
.filter((u) => u.userId === projectInfo.ownerFw || u.userTeam === FW_TEAM)
|
||||
.map((u) => ({value: u.userId, label: u.userNm}));
|
||||
}, [users, projectInfo.ownerFw]);
|
||||
|
||||
const handleChange = (field: keyof ProjectInfo, value: any) => {
|
||||
setProjectInfo((prev) => ({ ...prev, [field]: value }))
|
||||
setProjectInfo((prev) => ({...prev, [field]: value}))
|
||||
}
|
||||
|
||||
const handleImageUpload = useCallback(
|
||||
async (file: File): Promise<{ url: string }> => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
if (!projectInfo.prjctCd) {
|
||||
alert("프로젝트 코드가 없습니다. 잠시 후 다시 시도해주세요.");
|
||||
return {url: ""};
|
||||
}
|
||||
|
||||
const url = await nextApi.putForm<string>(`/project/senario-image/${projectInfo.prjctCd}`, formData);
|
||||
|
||||
// 이 세션에서 업로드한 temp 파일 목록에 기록
|
||||
const url = await uploadScenarioMutation.mutateAsync(file);
|
||||
sessionTempUrlsRef.current.add(url);
|
||||
|
||||
return { url }
|
||||
}, [projectInfo.prjctCd]);
|
||||
return {url};
|
||||
},
|
||||
[uploadScenarioMutation, projectInfo.prjctCd]
|
||||
);
|
||||
|
||||
const handleResultCodeClick = () => {
|
||||
showDialog('resultCodeDialog')
|
||||
@@ -139,62 +186,54 @@ const ProjectInfoPage = () => {
|
||||
return
|
||||
}
|
||||
|
||||
const updateCodeArray = _.cloneDeep(
|
||||
const updateCodeArray = structuredClone(
|
||||
resultCodeArray.filter((rc) => changeResultCodeType.includes(rc.resultCdTy))
|
||||
);
|
||||
|
||||
const requestUpdateProject:ProjectUpdateRequest = {
|
||||
const requestUpdateProject: ProjectUpdateRequest = {
|
||||
projectInfo: projectInfo,
|
||||
resultCodeList: updateCodeArray,
|
||||
assignUserIdList: outsourceUserArray,
|
||||
}
|
||||
|
||||
await nextApi.patch(`/project/${projectInfo.prjctIdx}`, requestUpdateProject);
|
||||
|
||||
await updateMutation.mutateAsync(requestUpdateProject);
|
||||
alert("저장되었습니다.");
|
||||
}
|
||||
|
||||
const handleDeleteClick = async () => {
|
||||
if (confirm('복구 할 수 없습니다. 정말 삭제 하시겠습니까?')) {
|
||||
if(!selectedProject){
|
||||
alert("옳지 않은 요청입니다.");
|
||||
}
|
||||
else{
|
||||
await nextApi.del(`/project/${selectedProject.prjctIdx}`)
|
||||
}
|
||||
|
||||
window.location.href = `/`;
|
||||
if (!confirm("복구 할 수 없습니다. 정말 삭제 하시겠습니까?")) return;
|
||||
if (!selectedProject) {
|
||||
alert("옳지 않은 요청입니다.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await deleteMutation.mutateAsync();
|
||||
router.push("/");
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if(selectedProject){
|
||||
nextApi.get<ProjectInfo>(`/project/info/${selectedProject.prjctIdx}`)
|
||||
.then((res) => setProjectInfo(res));
|
||||
|
||||
nextApi.get<ResultCode[]>(`/result-code/${selectedProject.prjctIdx}`)
|
||||
.then((res) => {setResultCodeArray(res)});
|
||||
|
||||
nextApi.get<UserInfo[]>(`/user/outsource`)
|
||||
.then((res) => {
|
||||
const outsourceOptions: MultiSelectOption[] = res
|
||||
.map(u => ({
|
||||
value: u.userId,
|
||||
label: `${u.userCmpn} / ${u.userName}(${u.userId})`,
|
||||
}));
|
||||
setOutsourceOptionArray(outsourceOptions)
|
||||
});
|
||||
|
||||
nextApi.get<string[]>(`/assign/prjct-outsource/${selectedProject.prjctIdx}`)
|
||||
.then((res) => setOutsourceUserArray(res));
|
||||
if (projectInfoQuery.data) {
|
||||
setProjectInfo(projectInfoQuery.data);
|
||||
}
|
||||
}, [selectedProject])
|
||||
}, [projectInfoQuery.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (resultCodesQuery.data) {
|
||||
setResultCodeArray(resultCodesQuery.data);
|
||||
}
|
||||
}, [resultCodesQuery.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (assignedOutsourceQuery.data) {
|
||||
setOutsourceUserArray(assignedOutsourceQuery.data);
|
||||
}
|
||||
}, [assignedOutsourceQuery.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (projectInfo.surveyTy !== SurveyType.EXTERNAL) {
|
||||
setExternalTab('redirect')
|
||||
|
||||
if(projectInfo.surveyPrjctCd && internalSurvey.includes(projectInfo.surveyTy || SurveyType.NONE)){
|
||||
if (projectInfo.surveyPrjctCd && internalSurvey.has(projectInfo.surveyTy || SurveyType.NONE)){
|
||||
let surveyUrl = `/project/${projectInfo.surveyPrjctCd}/INDEX.asp?${sidParam}`;
|
||||
if(projectInfo.surveyTy === SurveyType.KON){
|
||||
surveyUrl = `https://kon.kric.com` + surveyUrl
|
||||
@@ -206,32 +245,7 @@ const ProjectInfoPage = () => {
|
||||
handleChange('surveyUrl', surveyUrl)
|
||||
}
|
||||
}
|
||||
}, [projectInfo.surveyTy, projectInfo.surveyPrjctCd])
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
let userTeams = Array.from(new Set(users.map(u => u.userTeam)));
|
||||
if(!userTeams.includes("T900")){ //TFT
|
||||
userTeams.push("T900");
|
||||
}
|
||||
userTeams = userTeams.sort((a, b) => a.localeCompare(b, "ko"));
|
||||
setDeptArray(userTeams);
|
||||
}, [users]);
|
||||
|
||||
useEffect(() => {
|
||||
const userOptions: MultiSelectOption[] = users
|
||||
.filter(u => u.userId == projectInfo.ownerFw || u.userTeam == FW_TEAM)
|
||||
.map(u => ({
|
||||
value: u.userId,
|
||||
label: u.userNm,
|
||||
}));
|
||||
setFwArray(userOptions);
|
||||
}, [users, projectInfo.ownerFw]);
|
||||
|
||||
useEffect(() => {
|
||||
const keyword = debouncedKeyword.trim();
|
||||
searchKonKiwiPrjct(keyword).then();
|
||||
}, [debouncedKeyword, projectInfo.surveyTy, userTeam]);
|
||||
}, [projectInfo.surveyTy, projectInfo.surveyPrjctCd]);
|
||||
|
||||
if (!mounted) return <LoadingOverlay force />
|
||||
|
||||
|
||||
@@ -5,99 +5,67 @@ import {Button} from "@/components/ui/button";
|
||||
import {Card, CardContent, CardHeader} from "@/components/ui/card";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import React, {useEffect, useRef, useState} from "react";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import {useSearchParams} from "next/navigation";
|
||||
import {LoginUser} from "@/types/auth";
|
||||
import {useRouter, useSearchParams} from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useLoading } from "@/hooks/useLoading";
|
||||
import { useStorage } from "@/hooks/useStorage"
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
import {NONE_HTTP_ERROR} from "@/const/commonConst";
|
||||
import {useLoginMutation} from "@/query/auth";
|
||||
|
||||
const LoginPage = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { auth, setFromLoginResponse } = useAuth();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const typeParam = searchParams.get("type") ?? "";
|
||||
|
||||
const { auth } = useAuth();
|
||||
const loginMutation = useLoginMutation();
|
||||
|
||||
const { get: getSeatNumberStorage, set: setSeatNumberStorage } = useStorage(StorageKeys.SeatNumber);
|
||||
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
|
||||
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [userId, setUserId] = useState<string>("");
|
||||
const [userPw, setUserPw] = useState<string>("");
|
||||
const [seatNum, setSeatNum] = useState<string>(getSeatNumberStorage());
|
||||
const [loginType, setLoginType] = useState<string>(getLoginTypeStorage());
|
||||
const [seatNum, setSeatNum] = useState<string>("");
|
||||
const [loginType, setLoginType] = useState<string>("");
|
||||
|
||||
const passwordInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const seatNumberInputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const tryLogin = () => {
|
||||
if(!userId){
|
||||
alert("아이디를 입력해 주세요");
|
||||
return;
|
||||
}
|
||||
if(!userPw){
|
||||
alert("PW를 입력해 주세요");
|
||||
return;
|
||||
}
|
||||
if(loginType === "call" && !seatNum){
|
||||
alert("자리번호를 입력해 주세요");
|
||||
return;
|
||||
}
|
||||
const tryLogin = async () => {
|
||||
if (!userId) return alert("아이디를 입력해 주세요");
|
||||
if (!userPw) return alert("PW를 입력해 주세요");
|
||||
if (loginType === "call" && !seatNum) return alert("자리번호를 입력해 주세요");
|
||||
|
||||
setError(null);
|
||||
const loginRequestBody = {userId, userPw};
|
||||
const loginRequestOptions = {autoLogoutOnAuthError: false};
|
||||
|
||||
// withLoading 래퍼로 API 호출 전/후 로딩 표시를 자동으로 처리
|
||||
return withLoadingAsync(() =>
|
||||
nextApi.post<LoginUser>(
|
||||
"/login", loginRequestBody, loginRequestOptions
|
||||
).then(async (data) => { // Jotai 기반 전역 인증 상태 갱신
|
||||
try {
|
||||
setSeatNumberStorage(seatNum);
|
||||
setLoginTypeStorage(loginType);
|
||||
} catch (e) {
|
||||
// 저장 실패는 치명적이지 않으므로 콘솔 로깅만
|
||||
console.warn("Failed to persist SeatNumber to secure storage:", e);
|
||||
}
|
||||
|
||||
setFromLoginResponse(data, seatNum);
|
||||
}).catch((e) => {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
|
||||
if (err.status === 401 || err.status === 403) {
|
||||
setError("아이디 또는 비밀번호를 다시 확인해주세요.");
|
||||
}
|
||||
else if(err.code === NONE_HTTP_ERROR) {
|
||||
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
|
||||
}
|
||||
else {
|
||||
setError(`로그인에 실패했습니다. (status: ${err.status})`);
|
||||
}
|
||||
})
|
||||
);
|
||||
try {
|
||||
await loginMutation.mutateAsync({ userId, userPw, seatNum, loginType });
|
||||
} catch (e) {
|
||||
const err = apiError(e);
|
||||
if (err.status === 401 || err.status === 403) setError("아이디 또는 비밀번호를 다시 확인해주세요.");
|
||||
else if (err.code === NONE_HTTP_ERROR) setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
|
||||
else setError(`로그인에 실패했습니다. (status: ${err.status})`);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if(auth.user){
|
||||
window.location.replace("/");
|
||||
router.replace("/");
|
||||
}
|
||||
}, [auth.user]);
|
||||
|
||||
// URL 쿼리 파라미터에서 type 수신
|
||||
useEffect(() => {
|
||||
const typeParam = searchParams.get("type") ?? "";
|
||||
let seatNumTemp = "";
|
||||
|
||||
if(typeParam === "call") {
|
||||
seatNumTemp = getSeatNumberStorage();
|
||||
}
|
||||
setSeatNum(seatNumTemp);
|
||||
setLoginType(typeParam);
|
||||
}, [searchParams]);
|
||||
|
||||
if (typeParam === "call") {
|
||||
setSeatNum(getSeatNumberStorage() ?? "");
|
||||
} else {
|
||||
setSeatNum("");
|
||||
}
|
||||
|
||||
}, [typeParam]);
|
||||
|
||||
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
@@ -202,6 +170,7 @@ const LoginPage = () => {
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full mt-6 h-11"
|
||||
disabled={loginMutation.isPending}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
tryLogin();
|
||||
|
||||
@@ -1,49 +1,21 @@
|
||||
'use client'
|
||||
import { useLogoutMutation } from "@/query/auth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {useStorage} from "@/hooks/useStorage";
|
||||
import {StorageKeys} from "@/store/storage/storage-keys";
|
||||
import {useEffect} from "react";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
import { useEffect } from "react";
|
||||
|
||||
const LogoutPage = () => {
|
||||
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
|
||||
const { auth, logout } = useAuth();
|
||||
const { clearSelectedProject } = useSelectedProject();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const router = useRouter();
|
||||
const logoutMutation = useLogoutMutation();
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
const runLogout = async () => {
|
||||
const userId = auth.user?.userId ?? "";
|
||||
clearSelectedProject();
|
||||
logout();
|
||||
|
||||
try {
|
||||
if(userId !== ""){
|
||||
const logoutRequestOptions = {autoLogoutOnAuthError: false};
|
||||
await nextApi.post(`/logout/${userId}`, null, logoutRequestOptions);
|
||||
}
|
||||
} catch (e) {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
}
|
||||
|
||||
const loginType = getLoginTypeStorage();
|
||||
const loginUrl = loginType === "call" ? "/login?type=call" : "/login";
|
||||
|
||||
router.replace(loginUrl);
|
||||
};
|
||||
|
||||
withLoadingAsync(runLogout);
|
||||
(async () => {
|
||||
const { loginType } = await logoutMutation.mutateAsync();
|
||||
// 기존 로직 그대로: call 타입이면 쿼리 붙여서 이동
|
||||
router.replace(loginType === "call" ? "/login?type=call" : "/login");
|
||||
})();
|
||||
}, []);
|
||||
|
||||
// Nothing to render while redirecting
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export default LogoutPage;
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import {useState, useEffect, useMemo} from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -24,6 +24,7 @@ import {PROJECT_NAME_REGEX} from "@/const/projectConst";
|
||||
import {FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
import {useIntranetProjectListQuery} from "@/query/intranet";
|
||||
|
||||
export type ProjectCreateDialogProps = {
|
||||
/** Jotai로 관리할 다이얼로그 ID (기본값: 'userUpsertDialog') */
|
||||
@@ -37,8 +38,6 @@ export type ProjectCreateDialogProps = {
|
||||
onSubmit: (data: ProjectCreateRequest) => void | Promise<void>
|
||||
}
|
||||
|
||||
|
||||
|
||||
const ProjectCreateDialog = ({
|
||||
dialogId = 'projectCreateDialog',
|
||||
open,
|
||||
@@ -59,14 +58,16 @@ const ProjectCreateDialog = ({
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [formData, setFormData] = useState<ProjectCreateRequest>(defaultProjectInfo);
|
||||
|
||||
const [itrntKeyword, setItrntKeyword] = useState('');
|
||||
const debouncedKeyword = useDebouncedValue(itrntKeyword, 500);
|
||||
const [itrntPrjctArray, setItrntPrjctArray] = useState<IntranetProjectSearchResponse[]>([]);
|
||||
|
||||
// 🔹 실제로 Dialog에 넘길 open 값 (외부 open 있으면 우선)
|
||||
// 실제로 Dialog에 넘길 open 값 (외부 open 있으면 우선)
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId);
|
||||
|
||||
// 🔹 실제 onOpenChange 핸들러 (외부 콜백 + jotai 둘 다 처리)
|
||||
const [itrntKeyword, setItrntKeyword] = useState('');
|
||||
const debouncedKeyword = useDebouncedValue(itrntKeyword, 500);
|
||||
|
||||
const itrntPrjctListQuery = useIntranetProjectListQuery(debouncedKeyword, resolvedOpen);
|
||||
const itrntPrjctArray = useMemo(() => itrntPrjctListQuery.data ?? [] ,[itrntPrjctListQuery.data]);
|
||||
|
||||
// 실제 onOpenChange 핸들러 (외부 콜백 + jotai 둘 다 처리)
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
// 1) 외부에서 넘겨준 onOpenChange 먼저 호출
|
||||
onOpenChange?.(nextOpen);
|
||||
@@ -143,20 +144,6 @@ const ProjectCreateDialog = ({
|
||||
}
|
||||
}
|
||||
|
||||
const searchItrntPrjct = async (keyword:string): Promise<void> => {
|
||||
const res = await nextApi.get<IntranetProjectSearchResponse[]>(
|
||||
"/intranet/project",
|
||||
{ query: keyword ? { keyword } : {} }
|
||||
);
|
||||
|
||||
setItrntPrjctArray(res);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const keyword = debouncedKeyword.trim();
|
||||
searchItrntPrjct(keyword).then();
|
||||
}, [debouncedKeyword]);
|
||||
|
||||
useEffect(() => {
|
||||
setFormData(defaultProjectInfo);
|
||||
}, [resolvedOpen])
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import {useEffect, useState} from 'react'
|
||||
import {useEffect, useMemo, useState} from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -12,14 +12,12 @@ import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {Trash2, Plus, Download} from 'lucide-react'
|
||||
import {ProjectInfo, ResultCode, ResultCodeType} from "@/types/project";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {PROJECT_SEARCH_COUNT, RESULT_CODE_TYPE_OPTIONS} from "@/const/projectConst";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {SelectedProject} from "@/store/jotai/project";
|
||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import _ from "lodash";
|
||||
import {useProjectTopQuery, useResultCodesQuery} from "@/query/project";
|
||||
|
||||
type ResultCodeDialogProps = {
|
||||
open?: boolean
|
||||
@@ -38,37 +36,39 @@ const ResultCodeDialog = ({
|
||||
sourceArray,
|
||||
onSave,
|
||||
}: ResultCodeDialogProps) => {
|
||||
const mounted = useMounted();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
const [importMode, setImportMode] = useState(false)
|
||||
const [resultCodeType, setResultCodeType] = useState<ResultCodeType>(ResultCodeType.CONTACT)
|
||||
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([])
|
||||
const [importCodeArray, setImportCodeArray] = useState<ResultCode[]>([])
|
||||
const [importMode, setImportMode] = useState(false);
|
||||
const [resultCodeType, setResultCodeType] = useState<ResultCodeType>(ResultCodeType.CONTACT);
|
||||
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]);
|
||||
const [importProject, setImportProject] = useState<SelectedProject|undefined>(undefined);
|
||||
|
||||
const [searchKeyword, setSearchKeyword] = useState('')
|
||||
const [searchKeyword, setSearchKeyword] = useState('');
|
||||
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
|
||||
const [projectArray, setProjectArray] = useState<SelectedProject[]>([]);
|
||||
const [importProject, setImportProject] = useState<SelectedProject|undefined>(undefined)
|
||||
|
||||
const searchTopProject = async (keyword: string) => {
|
||||
const res = await nextApi.get<ProjectInfo[]>(
|
||||
`/project/top/${PROJECT_SEARCH_COUNT}`,
|
||||
{ query: { keyword } }
|
||||
);
|
||||
const topQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, !!open && importMode);
|
||||
|
||||
setProjectArray(res.filter((prjct) => prjct.prjctCd !== selectedProject?.prjctCd));
|
||||
};
|
||||
const projectArray = useMemo(() => {
|
||||
const arr = topQuery.data ?? [];
|
||||
return arr.filter((p) => p.prjctCd !== selectedProject?.prjctCd);
|
||||
}, [topQuery.data, selectedProject?.prjctCd]);
|
||||
|
||||
const handleSelectProject = (info:SelectedProject|null) => {
|
||||
if(info === null) return;
|
||||
const importPrjctIdx = importProject?.prjctIdx ?? 0;
|
||||
const importCodesQuery = useResultCodesQuery(importPrjctIdx, !!open && importMode && importPrjctIdx > 0);
|
||||
const importCodeArray = importCodesQuery.data ?? [];
|
||||
|
||||
const handleSelectProject = (info: ProjectInfo | null) => {
|
||||
if (!info) return;
|
||||
|
||||
setImportProject(info);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddCode = () => {
|
||||
if(resultCodeArray.length === 0) return setResultCodeArray([]);
|
||||
if(!resultCodeArray || resultCodeArray.length === 0){
|
||||
setResultCodeArray([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const lastCode = resultCodeArray[resultCodeArray.length - 1].resultCd;
|
||||
const lastCode = resultCodeArray.at(-1)!.resultCd;
|
||||
setResultCodeArray(prev => [
|
||||
...prev,
|
||||
{
|
||||
@@ -174,7 +174,7 @@ const ResultCodeDialog = ({
|
||||
|
||||
const handleImportApply = () => {
|
||||
if (importProject) {
|
||||
setResultCodeArray(_.cloneDeep(importCodeArray.filter(rc => rc.resultCdTy === resultCodeType)));
|
||||
setResultCodeArray(structuredClone(importCodeArray.filter(rc => rc.resultCdTy === resultCodeType)));
|
||||
|
||||
if (!changeCodeType.includes(resultCodeType)) {
|
||||
onChangeCodeType([...changeCodeType, resultCodeType]);
|
||||
@@ -219,18 +219,6 @@ const ResultCodeDialog = ({
|
||||
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if(importProject){
|
||||
nextApi.get<ResultCode[]>(`/result-code/${importProject.prjctIdx}`)
|
||||
.then((res) => setImportCodeArray(res));
|
||||
}
|
||||
}, [importProject]);
|
||||
|
||||
useEffect(() => {
|
||||
const keyword = debouncedKeyword.trim();
|
||||
searchTopProject(keyword);
|
||||
}, [debouncedKeyword]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
{/* importMode일 때 더 넓게(그리고 애니메이션으로 부드럽게) */}
|
||||
@@ -264,8 +252,7 @@ const ResultCodeDialog = ({
|
||||
) : (
|
||||
<div className="flex items-center gap-2 w-130">
|
||||
<div className="relative flex-1">
|
||||
<KriSingleSelect
|
||||
<SelectedProject>
|
||||
<KriSingleSelect<ProjectInfo>
|
||||
items={projectArray}
|
||||
value={String(importProject?.prjctIdx || "")}
|
||||
onChange={() => {}}
|
||||
|
||||
@@ -8,10 +8,8 @@ import {
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useState, useRef } from 'react'
|
||||
import {Download, Upload, X} from 'lucide-react'
|
||||
import { useLoading } from '@/hooks/useLoading'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import {apiError} from "@/lib/http-util";
|
||||
@@ -35,14 +33,14 @@ const UserUploadDialog = ({
|
||||
onUpload,
|
||||
onDownloadTemplate,
|
||||
}: UserUploadDialogProps) => {
|
||||
const { withLoadingAsync } = useLoading()
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog();
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
//실제 Dialog에 넘길 open값 (props 우선, 없으면 jotai 사용)
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId);
|
||||
|
||||
// open change 공통 처리 (부모 콜백 + jotai 동시 반영)
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
@@ -92,23 +90,23 @@ const UserUploadDialog = ({
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedFile) {
|
||||
alert('파일을 선택해주세요.')
|
||||
return
|
||||
alert("파일을 선택해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
withLoadingAsync(async () => {
|
||||
try {
|
||||
await onUpload(selectedFile)
|
||||
// 성공 시 초기화 + 닫기
|
||||
handleRemoveFile()
|
||||
handleOpenChange(false)
|
||||
} catch (e) {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
alert('업로드에 실패했습니다.')
|
||||
}
|
||||
})
|
||||
}
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await onUpload(selectedFile);
|
||||
handleRemoveFile();
|
||||
handleOpenChange(false);
|
||||
} catch (e) {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
alert("업로드에 실패했습니다.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ✅ Dialog에서 닫힐 때: 파일도 초기화 + 상태 닫기
|
||||
const handleDialogOpenChange = (nextOpen: boolean) => {
|
||||
@@ -171,11 +169,7 @@ const UserUploadDialog = ({
|
||||
|
||||
<DialogFooter>
|
||||
<div className="flex items-center justify-end w-full gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
disabled={!selectedFile}
|
||||
>
|
||||
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting}>
|
||||
확인
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -20,7 +20,7 @@ import {KriSelect, KriSelectItem} from "@/components/common/KriSelect";
|
||||
import {DataVerification} from "@/types/common";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||
import {USER_NAME_REGEX} from "@/const/userConst";
|
||||
import {FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
|
||||
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "@/const/commonConst";
|
||||
|
||||
export type UserUpsertDialogProps = {
|
||||
@@ -159,6 +159,8 @@ const UserUpsertDialog = ({
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
formData.userTeam = FW_TEAM;
|
||||
|
||||
try {
|
||||
await onSubmit(formData as UserInfoSaveRequest);
|
||||
handleOpenChange(false);
|
||||
|
||||
@@ -253,10 +253,6 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
},
|
||||
},[wysiwygKey]);
|
||||
|
||||
useEffect(() => {
|
||||
console.log(wysiwygKey)
|
||||
}, [wysiwygKey]);
|
||||
|
||||
const restoreSelection = useCallback(() => {
|
||||
if (!editor) return;
|
||||
const s = selectionRef.current;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Menu, X, ZoomIn, ZoomOut, LogOut } from "lucide-react";
|
||||
import Image from "next/image";
|
||||
@@ -29,6 +30,7 @@ export const Header = ({
|
||||
decreaseFontSize,
|
||||
increaseFontSize,
|
||||
}: HeaderProps) => {
|
||||
const router = useRouter();
|
||||
const { auth } = useAuth();
|
||||
const [userInfo, setUserInfo] = useState<LoginUser|undefined>(undefined);
|
||||
|
||||
@@ -37,7 +39,7 @@ export const Header = ({
|
||||
setUserInfo(auth.user);
|
||||
}
|
||||
else{
|
||||
window.location.replace("/logout");
|
||||
router.replace("/logout");
|
||||
}
|
||||
}, [auth.user])
|
||||
|
||||
|
||||
@@ -36,11 +36,7 @@ const MainLayout = ({ children, initialFontSize }: MainLayoutProps) => {
|
||||
|
||||
sideMenus.forEach((item) => {
|
||||
if (
|
||||
item.children &&
|
||||
item.children.some(
|
||||
(child) =>
|
||||
pathname === child.path || pathname.startsWith(child.path + "/")
|
||||
)
|
||||
item.children?.some((child) => pathname === child.path || pathname.startsWith(child.path + "/"))
|
||||
) {
|
||||
initial[item.id] = true;
|
||||
}
|
||||
@@ -76,7 +72,7 @@ const MainLayout = ({ children, initialFontSize }: MainLayoutProps) => {
|
||||
useEffect(() => {
|
||||
if(!isMain && isProjectMenu && !selectedProject){
|
||||
alert("옳지 않은 접근입니다.");
|
||||
window.location.replace("/");
|
||||
router.replace("/");
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -1,45 +1,30 @@
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {ProjectInfo} from "@/types/project";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {useEffect, useState} from "react";
|
||||
import {useMemo, useState} from "react";
|
||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {PROJECT_SEARCH_COUNT} from "@/const/projectConst";
|
||||
import {SelectedProject} from "@/store/jotai/project";
|
||||
import {useProjectTopQuery} from "@/query/project";
|
||||
|
||||
export const SidebarProjectSearch = () =>{
|
||||
const mounted = useMounted();
|
||||
|
||||
const { selectedProject, setSelectedProject } = useSelectedProject();
|
||||
|
||||
const [searchKeyword, setSearchKeyword] = useState(selectedProject?.prjctCd || "");
|
||||
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
|
||||
const [projectArray, setProjectArray] = useState<SelectedProject[]>([]);
|
||||
|
||||
const searchTopProject = async (keyword: string) => {
|
||||
const res = await nextApi.get<ProjectInfo[]>(
|
||||
`/project/top/${PROJECT_SEARCH_COUNT}`,
|
||||
{ query: { keyword } }
|
||||
);
|
||||
const enabled = mounted && !!selectedProject;
|
||||
const topQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, enabled);
|
||||
|
||||
setProjectArray(res);
|
||||
const projectArray = useMemo(() => topQuery.data ?? [] ,[topQuery.data]);
|
||||
|
||||
const handleSelectProject = (info: SelectedProject | null) => {
|
||||
if (!info) return;
|
||||
setSelectedProject(info);
|
||||
};
|
||||
|
||||
const handleSelectProject = (info:SelectedProject|null) => {
|
||||
if(info === null) return;
|
||||
|
||||
setSelectedProject(info);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if(selectedProject){
|
||||
const keyword = debouncedKeyword.trim();
|
||||
searchTopProject(keyword);
|
||||
}
|
||||
}, [debouncedKeyword]);
|
||||
|
||||
if (!mounted || !selectedProject) return null
|
||||
if (!mounted || !selectedProject) return null;
|
||||
|
||||
return (
|
||||
<KriSingleSelect
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {useCallback, useEffect, useRef, useState} from "react";
|
||||
import {listHder, ListHeaderGrade, ListHeaderType} from "@/types/list";
|
||||
import {listHder} from "@/types/list";
|
||||
import {
|
||||
ChannelType,
|
||||
MessageType,
|
||||
@@ -11,8 +11,6 @@ import {
|
||||
TemplateSms,
|
||||
TemplateSummary
|
||||
} from "@/types/messageTemplate";
|
||||
import {isTextAreaElement, isTipTapEditor} from "@/components/kri-editor/utils/editorTypeGuards";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
|
||||
import {Label} from "@/components/ui/label";
|
||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||
@@ -22,63 +20,100 @@ import {Checkbox} from "@/components/ui/checkbox";
|
||||
import {KriEditor, KriEditorCommand} from "@/components/kri-editor";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {cn, isBlank} from "@/lib/utils";
|
||||
import _ from "lodash";
|
||||
import {ProjectMainTemplateUpdateRequest} from "@/types/project";
|
||||
import {toast} from "sonner";
|
||||
import { DataVerification } from "@/types/common";
|
||||
import {
|
||||
useTemplateListQuery,
|
||||
useMainTemplateIdxQuery,
|
||||
useTemplateQuery,
|
||||
useSaveTemplateMutation,
|
||||
useUpdateMainTemplateMutation,
|
||||
useUploadTemplateBodyImageMutation,
|
||||
} from "@/query/message";
|
||||
|
||||
interface MessageTemplateProps {
|
||||
pageTitle: string;
|
||||
defaultTemplate: Template;
|
||||
}
|
||||
|
||||
const MessageTemplate = ({
|
||||
pageTitle,
|
||||
defaultTemplate,
|
||||
}: MessageTemplateProps) => {
|
||||
const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) => {
|
||||
const { selectedProject } = useSelectedProject();
|
||||
|
||||
const editorCmdRef = useRef<KriEditorCommand | null>(null);
|
||||
const sessionTempUrlsRef = useRef<Set<string>>(new Set());
|
||||
|
||||
const [mainTemplateIdx, setMainTemplateIdx] = useState<number|null>(null);
|
||||
const [listHderList, setListHderList] = useState<listHder[]>([])
|
||||
const [templateList, setTemplateList] = useState<TemplateSummary[]>([]);
|
||||
const [listHderList, setListHderList] = useState<listHder[]>([]);
|
||||
const [selectedTemplate, setSelectedTemplate] = useState<Template>(defaultTemplate);
|
||||
const [isMainTemplate, setIsMainTemplate] = useState(false);
|
||||
const [selectedTemplateIdx, setSelectedTemplateIdx] = useState<number | null>(null);
|
||||
|
||||
|
||||
const isSmsTemplate = (t: Template): t is TemplateSms =>
|
||||
const isSmsTemplate = (t: Template): t is TemplateSms =>
|
||||
(SMS_TYPE_ARRAY as readonly MessageType[]).includes(t.tmplatTy);
|
||||
|
||||
const isSms = isSmsTemplate(defaultTemplate);
|
||||
const chnnlTy:ChannelType = isSms? ChannelType.SMS : ChannelType.EMAIL;
|
||||
const chnnlTy: ChannelType = isSms ? ChannelType.SMS : ChannelType.EMAIL;
|
||||
|
||||
// 유니온의 키를 합집합으로 뽑기
|
||||
type KeysOfUnion<T> = T extends unknown ? keyof T : never;
|
||||
|
||||
// 특정 키의 값 타입을 유니온에서 안전하게 뽑기
|
||||
type ValueOfUnionKey<T, K extends KeysOfUnion<T>> =
|
||||
T extends unknown ? (K extends keyof T ? T[K] : never) : never;
|
||||
|
||||
const handleSelectTemplate = (templateIdxString: string) => {
|
||||
if(!selectedProject) return
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
|
||||
const enabled = !!selectedProject && prjctIdx > 0 && !!itrntPrjctCd;
|
||||
|
||||
if(!templateIdxString){
|
||||
const projectDefaultTemplate = _.cloneDeep(defaultTemplate);
|
||||
projectDefaultTemplate.itrntPrjctCd = selectedProject.itrntPrjctCd;
|
||||
setSelectedTemplate(projectDefaultTemplate);
|
||||
// Queries
|
||||
const templateListQuery = useTemplateListQuery(chnnlTy, itrntPrjctCd, enabled);
|
||||
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled);
|
||||
const templateDetailQuery = useTemplateQuery(selectedTemplateIdx ?? 0, enabled && !!selectedTemplateIdx);
|
||||
|
||||
const templateList: TemplateSummary[] = templateListQuery.data ?? [];
|
||||
const mainTemplateIdx = mainTemplateQuery.data ?? null;
|
||||
|
||||
// Mutations
|
||||
const saveTemplateMutation = useSaveTemplateMutation(chnnlTy, itrntPrjctCd);
|
||||
const updateMainTemplateMutation = useUpdateMainTemplateMutation(prjctIdx, chnnlTy);
|
||||
const uploadBodyImageMutation = useUploadTemplateBodyImageMutation(itrntPrjctCd);
|
||||
|
||||
// 대표 템플릿 체크 상태(사용자 의도)
|
||||
const [mainDesired, setMainDesired] = useState(false);
|
||||
|
||||
// selectedProject 변경 시 초기화
|
||||
useEffect(() => {
|
||||
if (!selectedProject) return;
|
||||
|
||||
const projectDefaultTemplate = structuredClone(defaultTemplate);
|
||||
projectDefaultTemplate.itrntPrjctCd = selectedProject.itrntPrjctCd;
|
||||
|
||||
setSelectedTemplateIdx(null);
|
||||
setSelectedTemplate(projectDefaultTemplate);
|
||||
setMainDesired(false);
|
||||
|
||||
// TODO: 프로젝트별 리스트 헤더 조회로 교체
|
||||
setListHderList([]);
|
||||
}, [selectedProject, defaultTemplate]);
|
||||
|
||||
// 템플릿 상세가 도착하면 draft에 주입
|
||||
useEffect(() => {
|
||||
const d = templateDetailQuery.data;
|
||||
if (!d) return;
|
||||
if (selectedTemplateIdx && d.tmplatIdx === selectedTemplateIdx) {
|
||||
setSelectedTemplate(d);
|
||||
}
|
||||
else{
|
||||
nextApi.get<Template>(`/message-template/${templateIdxString}`).then(setSelectedTemplate);
|
||||
}, [templateDetailQuery.data, selectedTemplateIdx]);
|
||||
|
||||
// 대표 템플릿 동기화(현재 선택 템플릿이 id를 가진 경우에만)
|
||||
useEffect(() => {
|
||||
if (selectedTemplate.tmplatIdx) {
|
||||
setMainDesired(selectedTemplate.tmplatIdx === mainTemplateIdx);
|
||||
}
|
||||
}
|
||||
}, [selectedTemplate.tmplatIdx, mainTemplateIdx]);
|
||||
|
||||
const handleChange = <K extends KeysOfUnion<Template>>(
|
||||
field: K,
|
||||
value: ValueOfUnionKey<Template, K>
|
||||
) => {
|
||||
setSelectedTemplate(prev => {
|
||||
setSelectedTemplate((prev) => {
|
||||
const next = { ...prev } as any;
|
||||
next[field] = value;
|
||||
return next as Template;
|
||||
@@ -86,66 +121,20 @@ const MessageTemplate = ({
|
||||
};
|
||||
|
||||
const setTemplateBody = (newString: string) => {
|
||||
setSelectedTemplate(prev => ({ ...prev, tmplatBody: newString }));
|
||||
setSelectedTemplate((prev) => ({ ...prev, tmplatBody: newString }));
|
||||
};
|
||||
|
||||
const setSmsType = (smsTypeString: "SMS" | "LMS") => {
|
||||
const smsType =
|
||||
smsTypeString === "SMS" ? MessageType.SMS : MessageType.LMS_MMS;
|
||||
const smsType = smsTypeString === "SMS" ? MessageType.SMS : MessageType.LMS_MMS;
|
||||
|
||||
setSelectedTemplate((prev) => {
|
||||
if (!isSmsTemplate(prev)) return prev;
|
||||
|
||||
return {
|
||||
...prev,
|
||||
tmplatTy: smsType,
|
||||
};
|
||||
return { ...prev, tmplatTy: smsType };
|
||||
});
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
await submitTemplate("put");
|
||||
};
|
||||
|
||||
const handleUpdate = async () => {
|
||||
if (!selectedTemplate.tmplatIdx) return;
|
||||
await submitTemplate("patch");
|
||||
};
|
||||
|
||||
const submitTemplate = async (method: "put" | "patch") => {
|
||||
const v = validateTemplate(selectedTemplate);
|
||||
|
||||
if (!v.success) {
|
||||
alert(v.errMessage);
|
||||
// 필요 시: 특정 필드 focus 처리도 가능
|
||||
// focusField(v.fieldName);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res =
|
||||
method === "put"
|
||||
? await nextApi.put<Template>(`/message-template`, selectedTemplate)
|
||||
: await nextApi.patch<Template>(`/message-template`, selectedTemplate);
|
||||
|
||||
settingTemplateList();
|
||||
setSelectedTemplate(res);
|
||||
updateMainTemplate(res.tmplatIdx!);
|
||||
|
||||
alert(method === "put" ? "저장되었습니다." : "수정되었습니다.");
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
alert(method === "put" ? "저장에 실패했습니다." : "수정에 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
const validateTemplate = (tpl: Template): DataVerification => {
|
||||
const ok = (): DataVerification => ({
|
||||
success: true,
|
||||
fieldName: "",
|
||||
errMessage: "",
|
||||
});
|
||||
|
||||
const ok = (): DataVerification => ({ success: true, fieldName: "", errMessage: "" });
|
||||
const fail = (fieldName: string, errMessage: string): DataVerification => ({
|
||||
success: false,
|
||||
fieldName,
|
||||
@@ -157,108 +146,132 @@ const MessageTemplate = ({
|
||||
if (isBlank(tpl.tmplatBody)) return fail("tmplatBody", "본문을 입력해 주세요.");
|
||||
if (isBlank(tpl.sendNm)) return fail("sendNm", "발신자명을 입력해 주세요.");
|
||||
|
||||
// Email 전용
|
||||
if (tpl.tmplatTy === MessageType.EMAIL) {
|
||||
if (isBlank(tpl.tmplatTitle)) return fail("tmplatTitle", "이메일 제목을 입력해 주세요.");
|
||||
if (isBlank(tpl.sendEml)) return fail("sendEml", "발신 이메일을 입력해 주세요.");
|
||||
return ok();
|
||||
}
|
||||
|
||||
// SMS 전용
|
||||
if (isBlank(tpl.sendTel)) return fail("sendTel", "발신 전화번호를 입력해 주세요.");
|
||||
|
||||
return ok();
|
||||
};
|
||||
|
||||
const updateMainTemplate = (templatIdx:number):void => {
|
||||
if(!selectedProject || !selectedProject.prjctIdx) return;
|
||||
const handleSelectTemplate = (templateIdxString: string) => {
|
||||
if (!selectedProject) return;
|
||||
|
||||
let updateFlag = false;
|
||||
let updateTemplateIdx: number | null = null;
|
||||
if (!templateIdxString) {
|
||||
const projectDefaultTemplate = structuredClone(defaultTemplate);
|
||||
projectDefaultTemplate.itrntPrjctCd = selectedProject.itrntPrjctCd;
|
||||
|
||||
if(isMainTemplate && mainTemplateIdx !== templatIdx){
|
||||
updateFlag = true;
|
||||
updateTemplateIdx = templatIdx;
|
||||
setSelectedTemplateIdx(null);
|
||||
setSelectedTemplate(projectDefaultTemplate);
|
||||
setMainDesired(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if(!isMainTemplate && mainTemplateIdx === templatIdx){
|
||||
updateFlag = true;
|
||||
}
|
||||
const idx = Number(templateIdxString);
|
||||
if (!Number.isFinite(idx)) return;
|
||||
setSelectedTemplateIdx(idx);
|
||||
};
|
||||
|
||||
if(updateFlag){
|
||||
const req:ProjectMainTemplateUpdateRequest = {
|
||||
prjctIdx: selectedProject.prjctIdx,
|
||||
chnnlTy:chnnlTy,
|
||||
tmplatIdx:updateTemplateIdx,
|
||||
}
|
||||
const toggleMainTemplate = async () => {
|
||||
if (!selectedProject) return;
|
||||
|
||||
nextApi.patch(`/project/main-template`, req);
|
||||
setMainTemplateIdx(updateTemplateIdx);
|
||||
}
|
||||
}
|
||||
const next = !mainDesired;
|
||||
setMainDesired(next);
|
||||
|
||||
const tmplatIdx = selectedTemplate.tmplatIdx ?? null;
|
||||
if (!tmplatIdx) return; // 새 템플릿(미저장)은 저장 후 대표 적용
|
||||
|
||||
// next=true => 이 템플릿을 대표로
|
||||
// next=false => 이 템플릿이 현재 대표일 때만 해제(null)
|
||||
const updateTemplateIdx = next ? tmplatIdx : (mainTemplateIdx === tmplatIdx ? null : mainTemplateIdx);
|
||||
|
||||
// 변화 없으면 요청 X
|
||||
if (updateTemplateIdx === mainTemplateIdx) return;
|
||||
|
||||
const req: ProjectMainTemplateUpdateRequest = {
|
||||
prjctIdx: selectedProject.prjctIdx,
|
||||
chnnlTy,
|
||||
tmplatIdx: updateTemplateIdx,
|
||||
};
|
||||
|
||||
await updateMainTemplateMutation.mutateAsync(req);
|
||||
};
|
||||
|
||||
const handleVariableClick = (placeholder: string) => {
|
||||
editorCmdRef.current?.insertText(placeholder);
|
||||
};
|
||||
|
||||
const toggleIsMainTemplate = () => {
|
||||
setIsMainTemplate(!isMainTemplate);
|
||||
}
|
||||
const handleImageUpload = useCallback(
|
||||
async (file: File): Promise<{ url: string }> => {
|
||||
if (!selectedProject) return { url: "" };
|
||||
const url = await uploadBodyImageMutation.mutateAsync(file);
|
||||
sessionTempUrlsRef.current.add(url);
|
||||
return { url };
|
||||
},
|
||||
[selectedProject, uploadBodyImageMutation]
|
||||
);
|
||||
|
||||
const handleImageUpload = useCallback(async (file: File): Promise<{ url: string }> => {
|
||||
if(selectedProject) {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
|
||||
const url = await nextApi.putForm<string>(`/message-template/body-image/${selectedProject?.itrntPrjctCd}`, formData);
|
||||
// 이 세션에서 업로드한 temp 파일 목록에 기록
|
||||
sessionTempUrlsRef.current.add(url);
|
||||
|
||||
return { url }
|
||||
const submitTemplate = async (method: "put" | "patch") => {
|
||||
const v = validateTemplate(selectedTemplate);
|
||||
if (!v.success) {
|
||||
alert(v.errMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
return { url: '' }
|
||||
}, [selectedProject]);
|
||||
try {
|
||||
const res = await saveTemplateMutation.mutateAsync({
|
||||
method,
|
||||
template: selectedTemplate,
|
||||
});
|
||||
|
||||
const settingTemplateList = useCallback(() => {
|
||||
if(!selectedProject) return;
|
||||
setSelectedTemplate(res);
|
||||
setSelectedTemplateIdx(res.tmplatIdx ?? null);
|
||||
|
||||
nextApi.get<TemplateSummary[]>(`/message-template/list/${chnnlTy}/${selectedProject.itrntPrjctCd}`).then(setTemplateList);
|
||||
}, [selectedProject, chnnlTy]);
|
||||
// 대표 템플릿 의도가 true면 저장된 템플릿을 대표로 반영
|
||||
if (mainDesired && selectedProject?.prjctIdx && res.tmplatIdx) {
|
||||
await updateMainTemplateMutation.mutateAsync({
|
||||
prjctIdx: selectedProject.prjctIdx,
|
||||
chnnlTy,
|
||||
tmplatIdx: res.tmplatIdx,
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if(!selectedProject) return;
|
||||
alert(method === "put" ? "저장되었습니다." : "수정되었습니다.");
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
alert(method === "put" ? "저장에 실패했습니다." : "수정에 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
settingTemplateList();
|
||||
nextApi.get<number | null>(`/project/main-template/${selectedProject.prjctIdx}/${chnnlTy}`).then(setMainTemplateIdx);
|
||||
const handleCreate = async () => {
|
||||
await submitTemplate("put");
|
||||
};
|
||||
|
||||
const projectDefaultTemplate = _.cloneDeep(defaultTemplate);
|
||||
projectDefaultTemplate.itrntPrjctCd = selectedProject.itrntPrjctCd;
|
||||
setSelectedTemplate(projectDefaultTemplate);
|
||||
|
||||
//Todo: 프로젝트 별 리스트 헤더 조회해서 세팅하기
|
||||
setListHderList([]);
|
||||
}, [selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
setIsMainTemplate(selectedTemplate.tmplatIdx === mainTemplateIdx);
|
||||
}, [selectedTemplate.tmplatIdx]);
|
||||
const handleUpdate = async () => {
|
||||
if (!selectedTemplate.tmplatIdx) return;
|
||||
await submitTemplate("patch");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
"w-full mx-auto p-6",
|
||||
isSms ? "max-w-7xl" : "max-w-4xl"
|
||||
)}>
|
||||
<div
|
||||
className={cn(
|
||||
"w-full mx-auto p-6",
|
||||
isSms ? "max-w-7xl" : "max-w-4xl"
|
||||
)}
|
||||
>
|
||||
<Card>
|
||||
<CardHeader className="border-b">
|
||||
<CardTitle className="text-center content-text-lg font-bold">{pageTitle}</CardTitle>
|
||||
<CardTitle className="text-center content-text-lg font-bold">
|
||||
{pageTitle}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="pt-6 relative">
|
||||
<div
|
||||
className={cn(
|
||||
isSms
|
||||
? "grid grid-cols-1 lg:grid-cols-[1fr_340px] gap-6 items-start"
|
||||
: ""
|
||||
isSms ? "grid grid-cols-1 lg:grid-cols-[1fr_340px] gap-6 items-start" : ""
|
||||
)}
|
||||
>
|
||||
<div className="space-y-6">
|
||||
@@ -267,17 +280,19 @@ const MessageTemplate = ({
|
||||
<Label htmlFor="tmplatNm" className="content-text-base">
|
||||
템플릿
|
||||
</Label>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="mainTemplate"
|
||||
checked={isMainTemplate}
|
||||
onClick={toggleIsMainTemplate}
|
||||
checked={mainDesired}
|
||||
onClick={toggleMainTemplate}
|
||||
/>
|
||||
<label htmlFor="mainTemplate" className="content-text-base cursor-pointer">
|
||||
대표 템플릿
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<KriSingleSelect
|
||||
items={templateList}
|
||||
value={String(selectedTemplate.tmplatIdx || "")}
|
||||
@@ -287,8 +302,8 @@ const MessageTemplate = ({
|
||||
widthClassName="w-full"
|
||||
getLabel={(item) => item.tmplatNm}
|
||||
getValue={(item) => String(item.tmplatIdx)}
|
||||
preventDeselect={true}
|
||||
useClear={true}
|
||||
preventDeselect
|
||||
useClear
|
||||
clearLabel="새 테플릿 생성"
|
||||
/>
|
||||
</div>
|
||||
@@ -299,7 +314,7 @@ const MessageTemplate = ({
|
||||
<KriSingleSelect
|
||||
items={[...SMS_TYPE_OPTIONS]}
|
||||
value={String(selectedTemplate.tmplatTy || MessageType.SMS)}
|
||||
onChange={(value) => handleChange('tmplatTy', Number(value))}
|
||||
onChange={(value) => handleChange("tmplatTy", Number(value) as any)}
|
||||
placeholder="템플릿 타입을 선택해 주세요"
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
@@ -308,6 +323,7 @@ const MessageTemplate = ({
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="tmplatNm" className="content-text-base">
|
||||
템플릿 명
|
||||
@@ -316,9 +332,10 @@ const MessageTemplate = ({
|
||||
id="tmplatNm"
|
||||
placeholder="템플릿 명을 입력하세요"
|
||||
value={selectedTemplate.tmplatNm}
|
||||
onChange={(e) => handleChange('tmplatNm', e.target.value)}
|
||||
onChange={(e) => handleChange("tmplatNm", e.target.value as any)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="tmplatTitle" className="content-text-base">
|
||||
제목
|
||||
@@ -326,49 +343,61 @@ const MessageTemplate = ({
|
||||
<Input
|
||||
id="tmplatTitle"
|
||||
placeholder="제목을 입력하세요"
|
||||
value={selectedTemplate.tmplatTitle || ''}
|
||||
onChange={(e) => handleChange('tmplatTitle', e.target.value)}
|
||||
value={selectedTemplate.tmplatTitle || ""}
|
||||
onChange={(e) => handleChange("tmplatTitle", e.target.value as any)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center">
|
||||
<Label className="content-text-base">변수 리스트</Label>
|
||||
</div>
|
||||
|
||||
<div className="border rounded-md overflow-hidden">
|
||||
<div className="bg-blue-100 grid grid-cols-2 border-b">
|
||||
<div className="py-2 px-3 text-center font-medium border-r content-text-base">리스트 헤더명</div>
|
||||
<div className="py-2 px-3 text-center font-medium content-text-base">치환 문자</div>
|
||||
<div className="py-2 px-3 text-center font-medium border-r content-text-base">
|
||||
리스트 헤더명
|
||||
</div>
|
||||
<div className="py-2 px-3 text-center font-medium content-text-base">
|
||||
치환 문자
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-h-32 overflow-y-auto">
|
||||
{listHderList.map((listHder) =>
|
||||
{
|
||||
const placeholder = `[\$${listHder.listHderNm}]`
|
||||
return (
|
||||
<div
|
||||
key={listHder.listHderId}
|
||||
className="grid grid-cols-2 border-b last:border-b-0 hover:bg-blue-50 cursor-pointer transition-colors"
|
||||
onPointerDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleVariableClick(placeholder);
|
||||
}}
|
||||
>
|
||||
<div className="py-2 px-3 text-center border-r content-text-base">{listHder.listHderNm}</div>
|
||||
<div className="py-2 px-3 text-center content-text-base">{placeholder}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
)}
|
||||
{listHderList.map((h) => {
|
||||
const placeholder = `[\$${h.listHderNm}]`;
|
||||
return (
|
||||
<div
|
||||
key={h.listHderId}
|
||||
className="grid grid-cols-2 border-b last:border-b-0 hover:bg-blue-50 cursor-pointer transition-colors"
|
||||
onPointerDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleVariableClick(placeholder);
|
||||
}}
|
||||
>
|
||||
<div className="py-2 px-3 text-center border-r content-text-base">
|
||||
{h.listHderNm}
|
||||
</div>
|
||||
<div className="py-2 px-3 text-center content-text-base">
|
||||
{placeholder}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{selectedTemplate && (
|
||||
isSmsTemplate(selectedTemplate)?
|
||||
|
||||
{selectedTemplate ? (
|
||||
isSmsTemplate(selectedTemplate) ? (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="sendTel" className="content-text-base">발신 번호</Label>
|
||||
<Label htmlFor="sendTel" className="content-text-base">
|
||||
발신 번호
|
||||
</Label>
|
||||
<Input
|
||||
id="sendTel"
|
||||
value={selectedTemplate.sendTel}
|
||||
onChange={(e) => handleChange('sendTel', e.target.value)}
|
||||
onChange={(e) => handleChange("sendTel", e.target.value as any)}
|
||||
placeholder="발신 번호를 입력하세요"
|
||||
className="w-full"
|
||||
/>
|
||||
@@ -376,18 +405,21 @@ const MessageTemplate = ({
|
||||
⚠️ 비즈 뿌리오에 등록된 발신 번호가 아니면 전송되지 않습니다.
|
||||
</p>
|
||||
</div>
|
||||
:
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="sendEmail" className="content-text-base">발신 이메일</Label>
|
||||
<Label htmlFor="sendEmail" className="content-text-base">
|
||||
발신 이메일
|
||||
</Label>
|
||||
<Input
|
||||
id="sendEmail"
|
||||
value={selectedTemplate.sendEml}
|
||||
onChange={(e) => handleChange('sendEml', e.target.value)}
|
||||
onChange={(e) => handleChange("sendEml", e.target.value as any)}
|
||||
placeholder="발신 이메일을 입력하세요"
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
)
|
||||
) : null}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="sendNm" className="content-text-base">
|
||||
@@ -397,20 +429,22 @@ const MessageTemplate = ({
|
||||
id="sendNm"
|
||||
placeholder="발신자 명을 입력하세요"
|
||||
value={selectedTemplate.sendNm}
|
||||
onChange={(e) => handleChange('sendNm', e.target.value)}
|
||||
onChange={(e) => handleChange("sendNm", e.target.value as any)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!isSms && (
|
||||
<KriEditor
|
||||
editorMode={'both'}
|
||||
editorMode={"both"}
|
||||
value={selectedTemplate.tmplatBody ?? "<p></p>"}
|
||||
onChange={(html: string) => setTemplateBody(html)}
|
||||
placeholder="이메일 내용을 입력해 주세요"
|
||||
className="w-full"
|
||||
debounceMs={600}
|
||||
onCommandReady={(cmd) => { editorCmdRef.current = cmd; }}
|
||||
onImageUpload={async (file) => await handleImageUpload(file)} // 사용 시만
|
||||
onCommandReady={(cmd) => {
|
||||
editorCmdRef.current = cmd;
|
||||
}}
|
||||
onImageUpload={async (file) => await handleImageUpload(file)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -424,13 +458,16 @@ const MessageTemplate = ({
|
||||
placeholder="문자 내용을 입력해 주세요"
|
||||
className="max-w-none mx-0"
|
||||
debounceMs={600}
|
||||
onCommandReady={(cmd) => { editorCmdRef.current = cmd; }}
|
||||
onCommandReady={(cmd) => {
|
||||
editorCmdRef.current = cmd;
|
||||
}}
|
||||
smsTitle={(selectedTemplate as TemplateSms).tmplatTitle}
|
||||
changeSmsType={(smsTypeString) => setSmsType(smsTypeString)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center gap-3 pt-4">
|
||||
<Button onClick={handleCreate} className="w-32 h-10">
|
||||
{selectedTemplate.tmplatIdx ? "복사 후 저장" : "저장"}
|
||||
@@ -448,7 +485,7 @@ const MessageTemplate = ({
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
export default MessageTemplate
|
||||
export default MessageTemplate;
|
||||
@@ -2,12 +2,17 @@
|
||||
|
||||
import { Provider as JotaiProvider } from "jotai";
|
||||
import { LoadingOverlay } from "@/components/common/LoadingOverlay";
|
||||
import { QueryProvider } from "./QueryProvider";
|
||||
import { QueryLoadingSync } from "./QueryLoadingSync";
|
||||
|
||||
export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<JotaiProvider>
|
||||
<LoadingOverlay />
|
||||
{children}
|
||||
<QueryProvider>
|
||||
<QueryLoadingSync />
|
||||
<LoadingOverlay />
|
||||
{children}
|
||||
</QueryProvider>
|
||||
</JotaiProvider>
|
||||
);
|
||||
}
|
||||
20
src/components/providers/QueryLoadingSync.tsx
Normal file
20
src/components/providers/QueryLoadingSync.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { useAtom } from "jotai";
|
||||
import { useIsFetching, useIsMutating } from "@tanstack/react-query";
|
||||
import { queryLoadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export function QueryLoadingSync() {
|
||||
const fetching = useIsFetching({
|
||||
predicate: (q) => !q.options.meta?.ignoreGlobalLoading,
|
||||
});
|
||||
const mutating = useIsMutating();
|
||||
const [, setQueryLoading] = useAtom(queryLoadingAtom);
|
||||
|
||||
useEffect(() => {
|
||||
setQueryLoading(fetching + mutating > 0);
|
||||
}, [fetching, mutating, setQueryLoading]);
|
||||
|
||||
return null;
|
||||
}
|
||||
23
src/components/providers/QueryProvider.tsx
Normal file
23
src/components/providers/QueryProvider.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
export function QueryProvider({ children }: { children: React.ReactNode }) {
|
||||
const [client] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
staleTime: 30_000,
|
||||
gcTime: 5 * 60_000,
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
|
||||
}
|
||||
@@ -1,109 +1,59 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {useCallback, useEffect, useRef, useState} from "react";
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
import { useStorage } from "@/hooks/useStorage";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
|
||||
export type ItrntUserInfo = {
|
||||
userId: string;
|
||||
userNm: string;
|
||||
userCmpn: string;
|
||||
userTeam: string;
|
||||
userRole: number;
|
||||
};
|
||||
|
||||
let inFlight: Promise<ItrntUserInfo[]> | null = null;
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
import {useIntranetUsersQuery} from "@/query/intranet";
|
||||
import {useQueryClient} from "@tanstack/react-query";
|
||||
import {qk} from "@/query/keys";
|
||||
|
||||
export const useItrntUserList = () => {
|
||||
const endpoint = "/intranet/user-list";
|
||||
const storage = useStorage(StorageKeys.ItrntUserList);
|
||||
const { get, set, remove } = storage;
|
||||
|
||||
// ✅ storage 함수 레퍼런스 고정(최신 함수는 effect로 갱신)
|
||||
// storage 함수 레퍼런스 고정(최신 함수는 effect로 갱신)
|
||||
const storageRef = useRef({ get, set, remove });
|
||||
useEffect(() => {
|
||||
storageRef.current = { get, set, remove };
|
||||
}, [get, set, remove]);
|
||||
|
||||
const [users, setUsers] = useState<ItrntUserInfo[]>([]);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
const [cachedUsers] = useState<ItrntUserInfo[] | undefined>(() => {
|
||||
const cached = storage.get();
|
||||
return Array.isArray(cached) ? (cached as ItrntUserInfo[]) : undefined;
|
||||
});
|
||||
|
||||
const mountedRef = useRef(true);
|
||||
const enabled = !cachedUsers;
|
||||
|
||||
const query = useIntranetUsersQuery({
|
||||
enabled,
|
||||
initialData: cachedUsers,
|
||||
});
|
||||
|
||||
// 서버에서 받아온 최신 데이터는 storage에 반영
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const fetchUsers = useCallback(async (): Promise<ItrntUserInfo[]> => {
|
||||
return await nextApi.get<ItrntUserInfo[]>(endpoint);
|
||||
}, [endpoint]);
|
||||
|
||||
// ✅ ensure는 이제 storage 함수들에 "직접" 의존하지 않음(루프 차단)
|
||||
const ensure = useCallback(async (force = false): Promise<ItrntUserInfo[]> => {
|
||||
const { get: sGet, set: sSet } = storageRef.current;
|
||||
|
||||
if (!force) {
|
||||
const cached = sGet();
|
||||
if (Array.isArray(cached)) return cached as ItrntUserInfo[];
|
||||
if (query.data) {
|
||||
storageRef.current.set(query.data);
|
||||
}
|
||||
}, [query.data]);
|
||||
|
||||
if (!inFlight) {
|
||||
inFlight = fetchUsers().finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
}
|
||||
|
||||
const list = await inFlight;
|
||||
sSet(list);
|
||||
return list;
|
||||
}, [fetchUsers]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const list = await ensure(false);
|
||||
if (!mountedRef.current) return;
|
||||
setUsers(list);
|
||||
} catch (e) {
|
||||
if (!mountedRef.current) return;
|
||||
setUsers([]);
|
||||
setError(e);
|
||||
} finally {
|
||||
if (!mountedRef.current) return;
|
||||
setIsLoading(false);
|
||||
}
|
||||
})();
|
||||
}, [ensure]);
|
||||
const qc = useQueryClient();
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const list = await ensure(true);
|
||||
if (!mountedRef.current) return;
|
||||
setUsers(list);
|
||||
} catch (e) {
|
||||
if (!mountedRef.current) return;
|
||||
setUsers([]);
|
||||
setError(e);
|
||||
} finally {
|
||||
if (!mountedRef.current) return;
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [ensure]);
|
||||
const res = await query.refetch();
|
||||
if (res.data) storageRef.current.set(res.data);
|
||||
}, [query]);
|
||||
|
||||
const clearCache = useCallback(() => {
|
||||
storageRef.current.remove();
|
||||
setUsers([]);
|
||||
}, []);
|
||||
qc.removeQueries({ queryKey: qk.intranetUsers() });
|
||||
}, [qc]);
|
||||
|
||||
return { users, isLoading, error, refresh, clearCache } as const;
|
||||
return {
|
||||
users: query.data ?? [],
|
||||
isLoading: query.isFetching, // 캐시 있으면 false, refetch 중이면 true
|
||||
error: query.error,
|
||||
refresh,
|
||||
clearCache,
|
||||
} as const;
|
||||
};
|
||||
@@ -2,26 +2,14 @@
|
||||
|
||||
import { useAtom } from "jotai";
|
||||
import { useCallback } from "react";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
import { manualLoadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export const useLoading = () => {
|
||||
const [isLoading, setIsLoading] = useAtom(loadingAtom);
|
||||
const [isLoading, setIsLoading] = useAtom(manualLoadingAtom);
|
||||
|
||||
const showLoading = useCallback(() => {
|
||||
setIsLoading(true);
|
||||
}, [setIsLoading]);
|
||||
const showLoading = useCallback(() => setIsLoading(true), [setIsLoading]);
|
||||
const hideLoading = useCallback(() => setIsLoading(false), [setIsLoading]);
|
||||
|
||||
const hideLoading = useCallback(() => {
|
||||
setIsLoading(false);
|
||||
}, [setIsLoading]);
|
||||
|
||||
/**
|
||||
* 비동기 함수 호출 시 편하게 쓸 수 있는 래퍼
|
||||
*
|
||||
* 예)
|
||||
* const { withLoading } = useLoading();
|
||||
* await withLoading(() => apiCall());
|
||||
*/
|
||||
const withLoadingAsync = useCallback(
|
||||
async <T,>(fn: () => Promise<T>): Promise<T> => {
|
||||
showLoading();
|
||||
@@ -31,7 +19,7 @@ export const useLoading = () => {
|
||||
hideLoading();
|
||||
}
|
||||
},
|
||||
[showLoading, hideLoading],
|
||||
[showLoading, hideLoading]
|
||||
);
|
||||
|
||||
const withLoading = useCallback(
|
||||
@@ -43,14 +31,8 @@ export const useLoading = () => {
|
||||
hideLoading();
|
||||
}
|
||||
},
|
||||
[showLoading, hideLoading],
|
||||
[showLoading, hideLoading]
|
||||
);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
showLoading,
|
||||
hideLoading,
|
||||
withLoading,
|
||||
withLoadingAsync,
|
||||
} as const;
|
||||
}
|
||||
return { isLoading, showLoading, hideLoading, withLoading, withLoadingAsync } as const;
|
||||
};
|
||||
54
src/query/auth.ts
Normal file
54
src/query/auth.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useStorage } from "@/hooks/useStorage";
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
import type { LoginUser } from "@/types/auth";
|
||||
|
||||
export const useLoginMutation = () => {
|
||||
const { setFromLoginResponse } = useAuth();
|
||||
const { set: setSeat } = useStorage(StorageKeys.SeatNumber);
|
||||
const { set: setLoginType } = useStorage(StorageKeys.LoginType);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (v: { userId: string; userPw: string; seatNum: string; loginType: string }) => {
|
||||
return nextApi.post<LoginUser>("/login", { userId: v.userId, userPw: v.userPw }, { autoLogoutOnAuthError: false });
|
||||
},
|
||||
onSuccess: (data, v) => {
|
||||
try {
|
||||
setSeat(v.seatNum);
|
||||
setLoginType(v.loginType);
|
||||
} catch {}
|
||||
setFromLoginResponse(data, v.seatNum);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export const useLogoutMutation = () => {
|
||||
const qc = useQueryClient();
|
||||
const { auth, logout } = useAuth();
|
||||
const { clearSelectedProject } = useSelectedProject();
|
||||
const { get: getLoginType } = useStorage(StorageKeys.LoginType);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
const userId = auth.user?.userId ?? "";
|
||||
try {
|
||||
if (userId){
|
||||
await nextApi.post(`/logout/${userId}`, null, { autoLogoutOnAuthError: false });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
return { loginType: getLoginType() };
|
||||
},
|
||||
onSettled: () => {
|
||||
clearSelectedProject();
|
||||
logout();
|
||||
qc.clear(); // 다음 사용자/세션에 서버상태 남지 않게
|
||||
},
|
||||
});
|
||||
}
|
||||
37
src/query/intranet.ts
Normal file
37
src/query/intranet.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import {keepPreviousData, useQuery} from "@tanstack/react-query";
|
||||
import {qk} from "@/query/keys";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
import {IntranetProjectSearchResponse, KonKiwiProjectInfo} from "@/types/project";
|
||||
|
||||
export function useIntranetProjectListQuery(keyword: string, enabled: boolean) {
|
||||
const kw = keyword.trim();
|
||||
|
||||
return useQuery({
|
||||
queryKey: qk.intranetProjectList(kw),
|
||||
queryFn: () =>
|
||||
nextApi.get<IntranetProjectSearchResponse[]>(
|
||||
`/intranet/project`,
|
||||
{ query: kw ? { keyword: kw } : {} }
|
||||
),
|
||||
enabled: enabled,
|
||||
staleTime: 0,
|
||||
placeholderData: keepPreviousData, // 검색 중 빈 배열로 깜빡임 방지
|
||||
meta: { ignoreGlobalLoading: true }, // 원하면 전역 오버레이 제외(네가 이미 메타 방식 쓰고 있었지)
|
||||
});
|
||||
}
|
||||
|
||||
export function useIntranetUsersQuery(opts?: {
|
||||
enabled?: boolean;
|
||||
initialData?: ItrntUserInfo[];
|
||||
}) {
|
||||
return useQuery({
|
||||
queryKey: qk.intranetUsers(),
|
||||
queryFn: () => nextApi.get<ItrntUserInfo[]>("/intranet/user-list"),
|
||||
enabled: opts?.enabled ?? true,
|
||||
staleTime: 10 * 60_000,
|
||||
initialData: opts?.initialData,
|
||||
});
|
||||
}
|
||||
38
src/query/keys.ts
Normal file
38
src/query/keys.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import type { ChannelType } from "@/types/messageTemplate";
|
||||
|
||||
export const qk = {
|
||||
roleList: () => ["role", "list"] as const,
|
||||
userCompanies: () => ["user", "companies"] as const,
|
||||
users: () => ["user", "list"] as const,
|
||||
user: (userId: string) => ["user", "detail", userId] as const,
|
||||
|
||||
fieldworkUsers: () => ["user", "fieldwork"] as const,
|
||||
outsourceUsers: () => ["user", "outsource"] as const,
|
||||
|
||||
projectTop: (count: number, keyword: string) => ["project", "top", count, keyword] as const,
|
||||
projectOwnerList: () => ["project", "owner-list"] as const,
|
||||
projectList: (
|
||||
query: unknown,
|
||||
pageIndex: number,
|
||||
pageSize: number,
|
||||
sortBy: string,
|
||||
sortDir: "asc" | "desc"
|
||||
) => ["project", "list", query, pageIndex, pageSize, sortBy, sortDir] as const,
|
||||
assignFieldwork: (prjctIdx: number) => ["assign", "prjct-fieldwork", prjctIdx] as const,
|
||||
assignOutsource: (prjctIdx: number) => ["assign", "prjct-outsource", prjctIdx] as const,
|
||||
|
||||
projectInfo: (prjctIdx: number) => ["project", "info", prjctIdx] as const,
|
||||
resultCodes: (prjctIdx: number) => ["result-code", prjctIdx] as const,
|
||||
|
||||
kartProjectList: (itrntPrjctCd: string, userTeam: string, isKiwi: number, keyword: string) =>
|
||||
["kart", "project-list", itrntPrjctCd, userTeam, isKiwi, keyword] as const,
|
||||
|
||||
intranetProjectList: (keyword: string) => ["intranet", "project-list", keyword] as const,
|
||||
intranetUsers: () => ["intranet", "user-list"] as const,
|
||||
|
||||
mainTemplate: (prjctIdx: number, chnnlTy: ChannelType) =>
|
||||
["project", "main-template", prjctIdx, chnnlTy] as const,
|
||||
templateList: (chnnlTy: ChannelType, itrntPrjctCd: string) =>
|
||||
["message-template", "list", chnnlTy, itrntPrjctCd] as const,
|
||||
template: (tmplatIdx: number) => ["message-template", "detail", tmplatIdx] as const,
|
||||
} as const;
|
||||
90
src/query/message.ts
Normal file
90
src/query/message.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { qk } from "@/query/keys";
|
||||
import type { ChannelType, Template, TemplateSummary } from "@/types/messageTemplate";
|
||||
import type { ProjectMainTemplateUpdateRequest } from "@/types/project";
|
||||
|
||||
export function useTemplateListQuery(chnnlTy: ChannelType, itrntPrjctCd: string, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.templateList(chnnlTy, itrntPrjctCd),
|
||||
queryFn: () => nextApi.get<TemplateSummary[]>(`/message-template/list/${chnnlTy}/${itrntPrjctCd}`),
|
||||
enabled: enabled && !!itrntPrjctCd,
|
||||
staleTime: 30_000,
|
||||
meta: { ignoreGlobalLoading: true },
|
||||
});
|
||||
}
|
||||
|
||||
export function useMainTemplateIdxQuery(prjctIdx: number, chnnlTy: ChannelType, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.mainTemplate(prjctIdx, chnnlTy),
|
||||
queryFn: () => nextApi.get<number | null>(`/project/main-template/${prjctIdx}/${chnnlTy}`),
|
||||
enabled: enabled && prjctIdx > 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useTemplateQuery(tmplatIdx: number, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.template(tmplatIdx),
|
||||
queryFn: () => nextApi.get<Template>(`/message-template/${tmplatIdx}`),
|
||||
enabled: enabled && tmplatIdx > 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
// meta: { ignoreGlobalLoading: true },
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveTemplateMutation(chnnlTy: ChannelType, itrntPrjctCd: string) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (v: { method: "put" | "patch"; template: Template }) => {
|
||||
const { method, template } = v;
|
||||
return method === "put"
|
||||
? nextApi.put<Template>(`/message-template`, template)
|
||||
: nextApi.patch<Template>(`/message-template`, template);
|
||||
},
|
||||
onSuccess: (res) => {
|
||||
if (res.tmplatIdx) {
|
||||
qc.setQueryData(qk.template(res.tmplatIdx), res);
|
||||
}
|
||||
qc.invalidateQueries({ queryKey: qk.templateList(chnnlTy, itrntPrjctCd) });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateMainTemplateMutation(prjctIdx: number, chnnlTy: ChannelType) {
|
||||
const qc = useQueryClient();
|
||||
const key = qk.mainTemplate(prjctIdx, chnnlTy);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (req: ProjectMainTemplateUpdateRequest) => {
|
||||
await nextApi.patch(`/project/main-template`, req);
|
||||
return req.tmplatIdx ?? null;
|
||||
},
|
||||
onMutate: async (req) => {
|
||||
const prev = qc.getQueryData<number | null>(key) ?? null;
|
||||
qc.setQueryData<number | null>(key, req.tmplatIdx ?? null);
|
||||
return { prev };
|
||||
},
|
||||
onError: (_err, _req, ctx) => {
|
||||
if (ctx?.prev !== undefined) qc.setQueryData<number | null>(key, ctx.prev);
|
||||
},
|
||||
onSettled: () => {
|
||||
qc.invalidateQueries({ queryKey: key });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUploadTemplateBodyImageMutation(itrntPrjctCd: string) {
|
||||
return useMutation({
|
||||
mutationFn: async (file: File): Promise<string> => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return nextApi.putForm<string>(`/message-template/body-image/${itrntPrjctCd}`, formData);
|
||||
},
|
||||
});
|
||||
}
|
||||
230
src/query/project.ts
Normal file
230
src/query/project.ts
Normal file
@@ -0,0 +1,230 @@
|
||||
"use client";
|
||||
|
||||
import {useQuery, keepPreviousData, useQueryClient, useMutation} from "@tanstack/react-query";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { qk } from "@/query/keys";
|
||||
import type {
|
||||
KonKiwiProjectInfo,
|
||||
ProjectCreateRequest,
|
||||
ProjectInfo,
|
||||
ProjectListQuery,
|
||||
ProjectListRequest,
|
||||
ProjectOwnerResponse, ProjectUpdateRequest, ResultCode
|
||||
} from "@/types/project";
|
||||
import {PageRequest, PageResponse} from "@/types/common";
|
||||
|
||||
export function useProjectOwnerListQuery(enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.projectOwnerList(),
|
||||
queryFn: () => nextApi.get<ProjectOwnerResponse>("/project/owner-list"),
|
||||
enabled,
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export type ProjectListArgs = {
|
||||
query?: ProjectListQuery;
|
||||
pageIndex: number;
|
||||
pageSize: number;
|
||||
sortBy?: string;
|
||||
sortDir?: "asc" | "desc";
|
||||
enabled?: boolean;
|
||||
};
|
||||
|
||||
export function useProjectListQuery(args: ProjectListArgs, ignoreGlobalLoading: boolean = false) {
|
||||
const {
|
||||
query,
|
||||
pageIndex,
|
||||
pageSize,
|
||||
sortBy = "prjctIdx",
|
||||
sortDir = "desc",
|
||||
enabled = true,
|
||||
} = args;
|
||||
|
||||
const pageReq: PageRequest = { pageIndex, pageSize, sortBy, sortDir };
|
||||
|
||||
const body: ProjectListRequest = {
|
||||
prjctText: query?.prjctText || "",
|
||||
prjctStatusList: query?.prjctStatusList || [],
|
||||
ownerDeptList: query?.ownerDeptList || [],
|
||||
ownerFwList: query?.ownerFwList || [],
|
||||
pageRequest: pageReq,
|
||||
};
|
||||
|
||||
return useQuery({
|
||||
queryKey: qk.projectList(body, pageIndex, pageSize, sortBy, sortDir),
|
||||
queryFn: () => nextApi.post<PageResponse<ProjectInfo>>("/project/list", body),
|
||||
enabled,
|
||||
staleTime: 0, // 항상 오래된 데이터 취급
|
||||
refetchOnMount: "always", // 컴포넌트 다시 붙을 때마다
|
||||
placeholderData: keepPreviousData, // 페이지/정렬 바뀔 때 빈 배열로 깜빡임 방지
|
||||
meta: { ignoreGlobalLoading: ignoreGlobalLoading },
|
||||
});
|
||||
}
|
||||
|
||||
export function useProjectTopQuery(count: number, keyword: string, enabled: boolean) {
|
||||
const kw = keyword.trim();
|
||||
|
||||
return useQuery({
|
||||
queryKey: qk.projectTop(count, kw),
|
||||
queryFn: () =>
|
||||
nextApi.get<ProjectInfo[]>(
|
||||
`/project/top/${count}`,
|
||||
{ query: { keyword: kw } }
|
||||
),
|
||||
enabled,
|
||||
staleTime: 0, // 항상 오래된 데이터 취급
|
||||
refetchOnMount: "always", // 컴포넌트 다시 붙을 때마다
|
||||
placeholderData: keepPreviousData,
|
||||
meta: { ignoreGlobalLoading: true },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로젝트 상세
|
||||
* - "자동 호출"은 아니고, 화면 들어올 때 최신 1회 확보 용도로 staleTime 0 + refetchOnMount always
|
||||
*/
|
||||
export function useProjectInfoQuery(prjctIdx: number, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.projectInfo(prjctIdx),
|
||||
queryFn: () => nextApi.get<ProjectInfo>(`/project/info/${prjctIdx}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 결과 코드 목록
|
||||
*/
|
||||
export function useResultCodesQuery(prjctIdx: number, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.resultCodes(prjctIdx),
|
||||
queryFn: () => nextApi.get<ResultCode[]>(`/result-code/${prjctIdx}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useKartProjectListQuery(args: {
|
||||
itrntPrjctCd: string;
|
||||
userTeam: string;
|
||||
isKiwi: number; // KON=0, KIWI=1
|
||||
keyword: string;
|
||||
enabled: boolean;
|
||||
}) {
|
||||
const kw = args.keyword.trim();
|
||||
|
||||
return useQuery({
|
||||
queryKey: qk.kartProjectList(args.itrntPrjctCd, args.userTeam, args.isKiwi, kw),
|
||||
queryFn: () =>
|
||||
nextApi.get<KonKiwiProjectInfo[]>(
|
||||
`/kart/project-list/${args.itrntPrjctCd}/${args.userTeam}/${args.isKiwi}`,
|
||||
{ query: kw ? { keyword: kw } : {} }
|
||||
),
|
||||
enabled: args.enabled,
|
||||
staleTime: 0,
|
||||
placeholderData: keepPreviousData, // 검색 중 빈 배열로 깜빡임 방지
|
||||
meta: { ignoreGlobalLoading: true }, // 원하면 전역 오버레이 제외(네가 이미 메타 방식 쓰고 있었지)
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로젝트에 배정된 외주 userId 목록
|
||||
*/
|
||||
export function useAssignedOutsourceIdsQuery(prjctIdx: number, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.assignOutsource(prjctIdx),
|
||||
queryFn: () => nextApi.get<string[]>(`/assign/prjct-outsource/${prjctIdx}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssignedFieldworkIdsQuery(prjctIdx: number, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.assignFieldwork(prjctIdx),
|
||||
queryFn: () => nextApi.get<string[]>(`/assign/prjct-fieldwork/${prjctIdx}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateProjectMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: ProjectCreateRequest) => nextApi.put<ProjectInfo>("/project", data),
|
||||
onSuccess: () => {
|
||||
// 목록 쿼리 전부 무효화(필터/페이지/정렬이 queryKey에 들어가서 prefix로)
|
||||
qc.invalidateQueries({ queryKey: ["project", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로젝트 수정
|
||||
*/
|
||||
export function useUpdateProjectMutation(prjctIdx: number) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: ProjectUpdateRequest) =>
|
||||
nextApi.patch<void>(`/project/${prjctIdx}`, payload),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: qk.projectInfo(prjctIdx) });
|
||||
// 목록 화면도 최신화 필요하면 prefix invalidate 추가 가능
|
||||
// qc.invalidateQueries({ queryKey: ["project", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveAssignedFieldworkMutation(prjctIdx: number) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (userIds: string[]) =>
|
||||
nextApi.put<void>(`/assign/prjct-fieldwork/${prjctIdx}`, userIds),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: qk.assignFieldwork(prjctIdx) });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로젝트 삭제
|
||||
*/
|
||||
export function useDeleteProjectMutation(prjctIdx: number) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: () => nextApi.del<void>(`/project/${prjctIdx}`),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["project", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 시나리오 이미지 업로드 (엔드포인트 spelling은 너 서버 기준으로)
|
||||
*/
|
||||
export function useUploadScenarioImageMutation(prjctIdx: number, prjctCd: string) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (file: File): Promise<string> => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
|
||||
// 서버가 업로드된 이미지 URL을 문자열로 반환한다는 전제
|
||||
return await nextApi.postForm<string>(`/project/senario-image/${prjctCd}`, formData);
|
||||
},
|
||||
onSuccess: () => {
|
||||
// 업로드 결과가 projectInfo에 반영된다면 해당 프로젝트만 갱신
|
||||
qc.invalidateQueries({ queryKey: qk.projectInfo(prjctIdx) });
|
||||
},
|
||||
});
|
||||
}
|
||||
129
src/query/user.ts
Normal file
129
src/query/user.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { qk } from "@/query/keys";
|
||||
|
||||
// 프로젝트에 존재하는 타입 기준(경로/이름 다르면 import만 수정)
|
||||
import type { RoleInfo } from "@/types/role";
|
||||
import type { UserInfo, UserInfoSaveRequest, UserUploadResponse } from "@/types/user";
|
||||
import type { DataVerification } from "@/types/common";
|
||||
|
||||
export function useRoleListQuery() {
|
||||
return useQuery({
|
||||
queryKey: qk.roleList(),
|
||||
queryFn: () => nextApi.get<RoleInfo[]>("/role"),
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserCompaniesQuery() {
|
||||
return useQuery({
|
||||
queryKey: qk.userCompanies(),
|
||||
queryFn: () => nextApi.get<string[]>("/user/cmpn"),
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUsersQuery() {
|
||||
return useQuery({
|
||||
queryKey: qk.users(),
|
||||
queryFn: () => nextApi.get<UserInfo[]>("/user"),
|
||||
staleTime: 0, // 항상 오래된 데이터 취급
|
||||
refetchOnMount: "always", // 컴포넌트 다시 붙을 때마다
|
||||
//refetchOnWindowFocus: true, // 탭 다시 볼 때마다
|
||||
//refetchOnReconnect: true, // 네트워크 복구 시
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserDetailQuery(userId: string, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.user(userId),
|
||||
queryFn: () => nextApi.get<UserInfo>(`/user/${encodeURIComponent(userId)}`),
|
||||
enabled,
|
||||
staleTime: 0, // 항상 오래된 데이터 취급
|
||||
refetchOnMount: "always", // 컴포넌트 다시 붙을 때마다
|
||||
//refetchOnWindowFocus: true, // 탭 다시 볼 때마다
|
||||
//refetchOnReconnect: true, // 네트워크 복구 시
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 외주 사용자 목록
|
||||
*/
|
||||
export function useOutsourceUsersQuery(enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.outsourceUsers(),
|
||||
queryFn: () => nextApi.get<UserInfo[]>("/user/outsource"),
|
||||
enabled,
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useFieldworkUsersQuery(enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.fieldworkUsers(),
|
||||
queryFn: () => nextApi.get<UserInfo[]>("/user/fieldwork"),
|
||||
enabled,
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCheckUserIdDuplicateMutation() {
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
nextApi.get<DataVerification>("/user/check-user-id", { query: { userId } }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpsertUserMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (v: { mode: "create" | "edit"; data: UserInfoSaveRequest }) => {
|
||||
return v.mode === "create"
|
||||
? nextApi.put<void>("/user", v.data)
|
||||
: nextApi.patch<void>("/user", v.data);
|
||||
},
|
||||
onSuccess: (_res, v) => {
|
||||
qc.invalidateQueries({ queryKey: qk.users() });
|
||||
|
||||
const userId = (v.data as any)?.userId;
|
||||
if (userId) {
|
||||
qc.invalidateQueries({ queryKey: qk.user(String(userId)) });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteUserMutation() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) => nextApi.del<void>(`/user/${encodeURIComponent(userId)}`),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: qk.users() }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUploadUsersExcelMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (file: File) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return nextApi.postForm<UserUploadResponse>("/user/excel", formData);
|
||||
},
|
||||
onSuccess: (res) => {
|
||||
if (!res.hasErrorFile) {
|
||||
qc.invalidateQueries({ queryKey: qk.users() });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadUserExcelTemplateMutation() {
|
||||
return useMutation({
|
||||
mutationFn: () =>
|
||||
nextApi.post<ArrayBuffer>("/user/excel-template", undefined, { expectBinary: true }),
|
||||
});
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { atom } from "jotai";
|
||||
|
||||
/**
|
||||
* 전역 로딩 상태
|
||||
*/
|
||||
export const loadingAtom = atom(false);
|
||||
export const manualLoadingAtom = atom(false);
|
||||
export const queryLoadingAtom = atom(false);
|
||||
|
||||
// 기존 LoadingOverlay가 보는 값: manual || query
|
||||
export const loadingAtom = atom((get) => get(manualLoadingAtom) || get(queryLoadingAtom));
|
||||
Reference in New Issue
Block a user