Merge pull request 'develop' (#3) from develop into master
Reviewed-on: #3
This commit is contained in:
5
.env
5
.env
@@ -1 +1,4 @@
|
||||
NEXT_PUBLIC_STORE_KEY = 4b6f7265615265736561726368-496e7465726e6174696f6e616c-49545465616d
|
||||
NEXT_PUBLIC_STORE_KEY = 4b6f7265615265736561726368-496e7465726e6174696f6e616c-49545465616d
|
||||
NEXT_PUBLIC_REQUEST_SVC = kri-contact
|
||||
NEXT_PUBLIC_API_INTERNAL=https://intranet.kric.com
|
||||
NEXT_PUBLIC_CTI_WS_URL=wss://teracall.kric.com:2302
|
||||
@@ -1,9 +1,10 @@
|
||||
NEXT_PUBLIC_ENV=dev
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000/api
|
||||
NEXT_PUBLIC_API_BASE=https://test-contact.kric.com/api
|
||||
|
||||
ENV=dev
|
||||
CONTACT_SERVER=http://localhost:4001
|
||||
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
||||
API_INTRANET_SERVER=http://localhost:3031/api/v1
|
||||
CONTACT_SERVER=http://127.0.0.1:4001
|
||||
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
|
||||
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
|
||||
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
||||
@@ -1,9 +1,10 @@
|
||||
NEXT_PUBLIC_ENV=local
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000/api
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:4000/api
|
||||
|
||||
ENV=local
|
||||
CONTACT_SERVER=http://localhost:4001
|
||||
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
||||
API_INTRANET_SERVER=http://localhost:3031/api/v1
|
||||
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
|
||||
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
||||
@@ -1,9 +1,10 @@
|
||||
NEXT_PUBLIC_ENV=prod
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000/api
|
||||
NEXT_PUBLIC_API_BASE=https://contact.kric.com/api
|
||||
|
||||
ENV=prod
|
||||
CONTACT_SERVER=http://localhost:4001
|
||||
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
||||
API_INTRANET_SERVER=http://localhost:3031/api/v1
|
||||
CONTACT_SERVER=http://127.0.0.1:4001
|
||||
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
|
||||
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
|
||||
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
||||
87
.idea/IntelliLang.xml
generated
Normal file
87
.idea/IntelliLang.xml
generated
Normal file
@@ -0,0 +1,87 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="LanguageInjectionConfiguration">
|
||||
<injection language="SpEL" injector-id="java">
|
||||
<display-name>Spring @Cacheable and @CacheEvict</display-name>
|
||||
<single-file value="true" />
|
||||
<place><![CDATA[psiMethod().withName("condition").withParameters().definedInClass("org.springframework.cache.annotation.CacheEvict")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("condition").withParameters().definedInClass("org.springframework.cache.annotation.CachePut")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("condition").withParameters().definedInClass("org.springframework.cache.annotation.Cacheable")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("key").withParameters().definedInClass("org.springframework.cache.annotation.CacheEvict")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("key").withParameters().definedInClass("org.springframework.cache.annotation.CachePut")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("key").withParameters().definedInClass("org.springframework.cache.annotation.Cacheable")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("unless").withParameters().definedInClass("org.springframework.cache.annotation.CachePut")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("unless").withParameters().definedInClass("org.springframework.cache.annotation.Cacheable")]]></place>
|
||||
</injection>
|
||||
<injection language="http-header-reference" injector-id="java">
|
||||
<display-name>Spring HttpHeaders (org.springframework.http)</display-name>
|
||||
<single-file value="true" />
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("header").definedInClass("org.springframework.http.ResponseEntity.HeadersBuilder"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("header").definedInClass("org.springframework.web.servlet.function.ServerResponse.HeadersBuilder"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("set", "add", "addAll", "getFirst", "containsKey", "get", "put", "getFirstDate", "setDate", "setInstant", "setZonedDateTime").definedInClass("org.springframework.http.HttpHeaders"))]]></place>
|
||||
</injection>
|
||||
<injection language="SpEL" injector-id="java">
|
||||
<display-name>Spring Integration/Messaging</display-name>
|
||||
<single-file value="true" />
|
||||
<place><![CDATA[psiMethod().withName("expression").withParameters().definedInClass("org.springframework.messaging.handler.annotation.Payload")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.integration.annotation.Payload")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.messaging.handler.annotation.Payload")]]></place>
|
||||
</injection>
|
||||
<injection language="SQL" injector-id="java">
|
||||
<display-name>Spring JDBC (org.springframework.jdbc.core.JdbcOperations)</display-name>
|
||||
<single-file value="true" />
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("batchUpdate").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("execute").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("query").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForInt").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForList").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForLong").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForMap").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForObject").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForRowSet").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForStream").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("sql").definedInClass("org.springframework.jdbc.core.simple.JdbcClient"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("update").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
|
||||
</injection>
|
||||
<injection language="SQL" injector-id="java">
|
||||
<display-name>Spring JDBC (org.springframework.jdbc.core.PreparedStatementCreatorFactory)</display-name>
|
||||
<single-file value="true" />
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("PreparedStatementCreatorFactory").withParameters("java.lang.String").definedInClass("org.springframework.jdbc.core.PreparedStatementCreatorFactory"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("PreparedStatementCreatorFactory").withParameters("java.lang.String", "int[]").definedInClass("org.springframework.jdbc.core.PreparedStatementCreatorFactory"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("PreparedStatementCreatorFactory").withParameters("java.lang.String", "java.util.List").definedInClass("org.springframework.jdbc.core.PreparedStatementCreatorFactory"))]]></place>
|
||||
</injection>
|
||||
<injection language="SQL" injector-id="java">
|
||||
<display-name>Spring JDBC (org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator)</display-name>
|
||||
<single-file value="true" />
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("createCustomException").withParameters("java.lang.String", "java.lang.String", "java.sql.SQLException", "java.lang.Class").definedInClass("org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("customTranslate").withParameters("java.lang.String", "java.lang.String", "java.sql.SQLException").definedInClass("org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("doTranslate").withParameters("java.lang.String", "java.lang.String", "java.sql.SQLException").definedInClass("org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("logTranslation").withParameters("java.lang.String", "java.lang.String", "java.sql.SQLException", "boolean").definedInClass("org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator"))]]></place>
|
||||
</injection>
|
||||
<injection language="SpEL" injector-id="java">
|
||||
<display-name>Spring Security @PostAuthorize/@PostFilter/@PreAuthorize/@PreFilter/@AuthenticationPrincipal</display-name>
|
||||
<single-file value="true" />
|
||||
<place><![CDATA[psiMethod().withName("expression").withParameters().definedInClass("org.springframework.security.core.annotation.AuthenticationPrincipal")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("expression").withParameters().definedInClass("org.springframework.security.core.annotation.CurrentSecurityContext")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.security.access.prepost.PostAuthorize")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.security.access.prepost.PostFilter")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.security.access.prepost.PreAuthorize")]]></place>
|
||||
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.security.access.prepost.PreFilter")]]></place>
|
||||
</injection>
|
||||
<injection language="SpEL" injector-id="java">
|
||||
<display-name>Spring State Machine</display-name>
|
||||
<single-file value="true" />
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("event").withParameters("java.lang.String").definedInClass("org.springframework.statemachine.config.configurers.SecurityConfigurer"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("guardExpression").withParameters("java.lang.String").definedInClass("org.springframework.statemachine.config.configurers.TransitionConfigurer"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("secured").withParameters("java.lang.String").definedInClass("org.springframework.statemachine.config.configurers.TransitionConfigurer"))]]></place>
|
||||
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("transition").withParameters("java.lang.String").definedInClass("org.springframework.statemachine.config.configurers.SecurityConfigurer"))]]></place>
|
||||
</injection>
|
||||
<injection language="SpEL" injector-id="xml">
|
||||
<display-name>SpEL for Spring Cache</display-name>
|
||||
<single-file value="true" />
|
||||
<place><![CDATA[xmlAttribute().withLocalName("condition").withParent(xmlTag().withNamespace(string().equalTo("http://www.springframework.org/schema/cache")))]]></place>
|
||||
<place><![CDATA[xmlAttribute().withLocalName("key").withParent(xmlTag().withNamespace(string().equalTo("http://www.springframework.org/schema/cache")))]]></place>
|
||||
<place><![CDATA[xmlAttribute().withLocalName("unless").withParent(xmlTag().withNamespace(string().equalTo("http://www.springframework.org/schema/cache")))]]></place>
|
||||
</injection>
|
||||
</component>
|
||||
</project>
|
||||
21
.idea/claudeCodeEditorTabs.xml
generated
Normal file
21
.idea/claudeCodeEditorTabs.xml
generated
Normal file
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ClaudeCodeEditorTabs">
|
||||
<option name="activeSessionId" value="92992f57-d7ca-4de2-8f74-9ef027389dc9" />
|
||||
<option name="openSessionIds">
|
||||
<list>
|
||||
<option value="92992f57-d7ca-4de2-8f74-9ef027389dc9" />
|
||||
</list>
|
||||
</option>
|
||||
<option name="sessionPaths">
|
||||
<map>
|
||||
<entry key="92992f57-d7ca-4de2-8f74-9ef027389dc9" value="/sessions/215ce9ea-6da9-4fc1-aabf-8801c4455db1" />
|
||||
</map>
|
||||
</option>
|
||||
<option name="sessionTitles">
|
||||
<map>
|
||||
<entry key="92992f57-d7ca-4de2-8f74-9ef027389dc9" value="hi" />
|
||||
</map>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
8
.idea/dictionaries/project.xml
generated
Normal file
8
.idea/dictionaries/project.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<component name="ProjectDictionaryState">
|
||||
<dictionary name="project">
|
||||
<words>
|
||||
<w>Hder</w>
|
||||
<w>prjct</w>
|
||||
</words>
|
||||
</dictionary>
|
||||
</component>
|
||||
1
.idea/misc.xml
generated
1
.idea/misc.xml
generated
@@ -1,4 +1,3 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
|
||||
2
.npmrc
Normal file
2
.npmrc
Normal file
@@ -0,0 +1,2 @@
|
||||
@kri:registry=https://gitea.kric.com/api/packages/KRi/npm/
|
||||
//gitea.kric.com/api/packages/KRi/npm/:_authToken=${GITEA_NPM_TOKEN}
|
||||
@@ -1,17 +1,36 @@
|
||||
import type { NextConfig } from "next";
|
||||
import { createEnv, createKriNextConfig, env } from "@kri/common/config";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
reactCompiler: true,
|
||||
const nextEnv = createEnv({
|
||||
CONTACT_SERVER: env.required("CONTACT_SERVER", process.env.CONTACT_SERVER),
|
||||
});
|
||||
|
||||
const nextConfig = createKriNextConfig({
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: "/contact-senario/:path*",
|
||||
destination: `${process.env.CONTACT_SERVER}/contact-senario/:path*`,
|
||||
destination: `${nextEnv.CONTACT_SERVER}/contact-senario/:path*`,
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/api/external/:path*",
|
||||
headers: [
|
||||
{ key: "Access-Control-Allow-Credentials", value: "true" },
|
||||
{ key: "Access-Control-Allow-Origin", value: "*" },
|
||||
{ key: "Access-Control-Allow-Methods", value: "GET,POST,PUT,PATCH,DELETE" },
|
||||
{
|
||||
key: "Access-Control-Allow-Headers",
|
||||
value: "Content-Type, Authorization, X-Requested-With",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
}) satisfies NextConfig;
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
2470
package-lock.json
generated
2470
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
24
package.json
24
package.json
@@ -3,12 +3,16 @@
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"dev": "next dev -p 4000",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"start": "next start -p 4000",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@kri/common": "^0.18.0",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
@@ -19,6 +23,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",
|
||||
@@ -34,25 +39,28 @@
|
||||
"@tiptap/extension-underline": "^3.13.0",
|
||||
"@tiptap/react": "^3.12.0",
|
||||
"@tiptap/starter-kit": "^3.12.0",
|
||||
"@types/lodash": "^4.17.21",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"crypto-js": "^4.2.0",
|
||||
"date-fns": "^4.4.0",
|
||||
"dompurify": "^3.4.10",
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-for-react": "^3.0.6",
|
||||
"jotai": "^2.15.1",
|
||||
"lodash": "^4.17.21",
|
||||
"lucide-react": "^0.553.0",
|
||||
"next": "^16.0.7",
|
||||
"next-themes": "^0.4.6",
|
||||
"qrcode": "^1.5.4",
|
||||
"radix-ui": "^1.6.1",
|
||||
"react": "^19.2.1",
|
||||
"react-day-picker": "^10.0.1",
|
||||
"react-dom": "^19.2.1",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"@types/node": "^20",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"babel-plugin-react-compiler": "1.0.0",
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
Before Width: | Height: | Size: 391 B |
@@ -1 +0,0 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
@@ -1 +0,0 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
Before Width: | Height: | Size: 128 B |
@@ -1 +0,0 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
Before Width: | Height: | Size: 385 B |
196
src/app/(pages)/(main)/assign/list/page.tsx
Normal file
196
src/app/(pages)/(main)/assign/list/page.tsx
Normal file
@@ -0,0 +1,196 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useMounted } from '@kri/common/hooks'
|
||||
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||
import { AssignTargetList, useAssignTargetRows } from '@/components/assign/AssignTargetList'
|
||||
import { ListSearchTable } from '@/components/list/ListSearchTable'
|
||||
import { useResultCodesQuery } from '@/query/project'
|
||||
import { useListHeaderQuery } from '@/query/list'
|
||||
import { useResetListAssignMutation, useUpsertListAssignMutation } from '@/query/assign'
|
||||
import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst'
|
||||
import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list'
|
||||
import type { ResultCode } from '@/types/project'
|
||||
|
||||
const ASSIGN_TAB_TYPES: ListHeaderAssignType[] = [
|
||||
ListHeaderAssignConst.OUTSOURCE,
|
||||
ListHeaderAssignConst.CONTACT_INTERVIEWER,
|
||||
ListHeaderAssignConst.FIELD_INTERVIEWER,
|
||||
]
|
||||
|
||||
const ASSIGNED_SENTINEL = '__ASSIGNED__'
|
||||
const UNASSIGNED_SENTINEL = '__UNASSIGNED__'
|
||||
const isAssignFilterSentinel = (value: string) => value === ASSIGNED_SENTINEL || value === UNASSIGNED_SENTINEL
|
||||
|
||||
const ListAssignPage = () => {
|
||||
const mounted = useMounted()
|
||||
const { auth } = useAuth()
|
||||
const { selectedProject } = useSelectedProject()
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0
|
||||
const enabled = mounted && prjctIdx > 0
|
||||
const userRole = auth?.user?.userRole ?? 0
|
||||
|
||||
const [assignType, setAssignType] = useState<ListHeaderAssignType>(ListHeaderAssignConst.OUTSOURCE)
|
||||
const [selectedAssignId, setSelectedAssignId] = useState<string | undefined>(undefined)
|
||||
const [assignFilterIds, setAssignFilterIds] = useState<string[]>([])
|
||||
const [transferResve, setTransferResve] = useState(false)
|
||||
const [currentListFilter, setCurrentListFilter] = useState<ListFilter>(() => createEmptyListFilter())
|
||||
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||
const upsertListAssignMutation = useUpsertListAssignMutation(prjctIdx)
|
||||
const resetListAssignMutation = useResetListAssignMutation(prjctIdx)
|
||||
const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType })
|
||||
|
||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
||||
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||
|
||||
const handleTabChange = (value: string) => {
|
||||
setAssignType(Number(value) as ListHeaderAssignType)
|
||||
setSelectedAssignId(undefined)
|
||||
}
|
||||
|
||||
// 좌측 테이블 선택값이 바뀌면 결과 필터 multiselect도 그 값으로 맞춘다.
|
||||
useEffect(() => {
|
||||
setAssignFilterIds(selectedAssignId ? [selectedAssignId] : [])
|
||||
}, [selectedAssignId])
|
||||
|
||||
// "배정됨"/"배정되지 않음"은 실제 대상 선택과 동시에 선택될 수 없다: 새로 클릭된 쪽만 남긴다.
|
||||
const handleAssignFilterChange = (next: string[]) => {
|
||||
const addedSentinel = next.find((value) => isAssignFilterSentinel(value) && !assignFilterIds.includes(value))
|
||||
if (addedSentinel) {
|
||||
setAssignFilterIds([addedSentinel])
|
||||
return
|
||||
}
|
||||
setAssignFilterIds(next.filter((value) => !isAssignFilterSentinel(value)))
|
||||
}
|
||||
|
||||
const assignFilterItems = useMemo(
|
||||
() => [
|
||||
{ id: ASSIGNED_SENTINEL, name: '배정됨' },
|
||||
{ id: UNASSIGNED_SENTINEL, name: '배정되지 않음' },
|
||||
...assignTargetRows,
|
||||
],
|
||||
[assignTargetRows],
|
||||
)
|
||||
|
||||
const externalAssignFilter = useMemo(() => {
|
||||
if (assignFilterIds[0] === ASSIGNED_SENTINEL) {
|
||||
return { type: assignType, values: [] as string[], condition: 'assigned' as const }
|
||||
}
|
||||
if (assignFilterIds[0] === UNASSIGNED_SENTINEL) {
|
||||
return { type: assignType, values: [] as string[], condition: 'unassigned' as const }
|
||||
}
|
||||
return { type: assignType, values: assignFilterIds }
|
||||
}, [assignType, assignFilterIds])
|
||||
|
||||
const handleAssign = async () => {
|
||||
if (!selectedAssignId) {
|
||||
alert('배정할 대상을 선택해주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
await upsertListAssignMutation.mutateAsync({
|
||||
assignId: selectedAssignId,
|
||||
request: {
|
||||
assignType,
|
||||
transferResve: assignType === ListHeaderAssignConst.OUTSOURCE? false : transferResve,
|
||||
listFilter: currentListFilter,
|
||||
},
|
||||
})
|
||||
alert('배정되었습니다.')
|
||||
}
|
||||
|
||||
const handleResetAssign = async () => {
|
||||
if (!confirm('정말 배정을 초기화 하시겠습니까?')) return
|
||||
|
||||
await resetListAssignMutation.mutateAsync({
|
||||
assignType,
|
||||
listFilter: currentListFilter,
|
||||
})
|
||||
alert('배정이 초기화 되었습니다.')
|
||||
}
|
||||
|
||||
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />
|
||||
|
||||
return (
|
||||
<div className="flex gap-4 text-sm">
|
||||
<div className="w-72 shrink-0 space-y-2">
|
||||
<Tabs value={String(assignType)} onValueChange={handleTabChange}>
|
||||
<TabsList className="grid w-full grid-cols-3">
|
||||
{ASSIGN_TAB_TYPES.map((type) => (
|
||||
<TabsTrigger key={type} value={String(type)}>
|
||||
{LIST_HEADER_TYPE_LABEL[type]}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
|
||||
<AssignTargetList
|
||||
prjctIdx={prjctIdx}
|
||||
enabled={enabled}
|
||||
assignType={assignType}
|
||||
selectedId={selectedAssignId}
|
||||
onSelect={setSelectedAssignId}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<ListSearchTable
|
||||
prjctIdx={prjctIdx}
|
||||
enabled={enabled}
|
||||
userRole={userRole}
|
||||
userId={auth?.user?.userId ?? ''}
|
||||
userCmpn={auth?.user?.userCmpn ?? ''}
|
||||
resultCodes={resultCodeArray}
|
||||
listHeaders={listHeaders}
|
||||
selectMode="none"
|
||||
onCurrentFilterChange={setCurrentListFilter}
|
||||
excludeFilterHeaderTypes={[assignType]}
|
||||
externalAssignFilter={externalAssignFilter}
|
||||
filterActions={
|
||||
<KriMultiSelect
|
||||
items={assignFilterItems}
|
||||
value={assignFilterIds}
|
||||
onChange={handleAssignFilterChange}
|
||||
getValue={(item) => item.id}
|
||||
getLabel={(item) => item.name}
|
||||
placeholder={`${LIST_HEADER_TYPE_LABEL[assignType]} 필터`}
|
||||
widthClassName="w-56"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
}
|
||||
rightActions={
|
||||
<>
|
||||
{assignType !== ListHeaderAssignConst.OUTSOURCE && (
|
||||
<label className="flex items-center gap-2 text-base cursor-pointer">
|
||||
<Checkbox
|
||||
checked={transferResve}
|
||||
onCheckedChange={(checked) => setTransferResve(checked === true)}
|
||||
/>
|
||||
예약 이관
|
||||
</label>
|
||||
)}
|
||||
<Button type="button" onClick={handleAssign}>
|
||||
배정
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={handleResetAssign}>
|
||||
배정 초기화
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListAssignPage
|
||||
@@ -1,130 +1,136 @@
|
||||
'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, useMounted } from "@kri/common/hooks";
|
||||
import { UserInfo } from "@/types/user";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { KriSelect, KriSelectItem } from "@/components/common/KriSelect";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
|
||||
|
||||
import {
|
||||
useFieldworkUsersQuery,
|
||||
useRoleListQuery,
|
||||
} from "@/query/user";
|
||||
import { useCmpnListQuery } from "@/query/cmpn";
|
||||
|
||||
import {
|
||||
useAssignedCmpnIdsQuery,
|
||||
useAssignedFieldworkIdsQuery,
|
||||
useSaveAssignedFieldworkMutation,
|
||||
useProjectTopQuery,
|
||||
} from "@/query/project";
|
||||
import { isFieldWorkUser } from "@/utils/userRole";
|
||||
|
||||
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 companyQuery = useCmpnListQuery();
|
||||
const fwUsersQuery = useFieldworkUsersQuery(enabled);
|
||||
const assignedCmpnIdsQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled);
|
||||
const assignedIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled);
|
||||
const saveAssignMutation = useSaveAssignedFieldworkMutation(prjctIdx);
|
||||
|
||||
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 = useMemo(() => {
|
||||
const companies = companyQuery.data ?? [];
|
||||
const assignedCmpnIds = new Set(assignedCmpnIdsQuery.data ?? []);
|
||||
return companies.filter((company) => company.ownCmpn || assignedCmpnIds.has(company.cmpnId));
|
||||
}, [assignedCmpnIdsQuery.data, companyQuery.data]);
|
||||
|
||||
const roleArray: KriSelectItem[] = useMemo(() => {
|
||||
const roles = roleQuery.data ?? [];
|
||||
return roles
|
||||
.filter(r => isFieldWorkUser(r.roleCd))
|
||||
.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,174 +138,147 @@ 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);
|
||||
const cmpn = auth.user?.userCmpn ?? "";
|
||||
const hasAuthCmpn = companyArray.some((company) => company.cmpnId === cmpn);
|
||||
|
||||
if (cmpn && hasAuthCmpn) {
|
||||
setCompanyFilter(cmpn);
|
||||
return;
|
||||
}
|
||||
}, [debouncedKeyword]);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
nextApi.get<UserInfo[]>("/user/fieldwork")
|
||||
.then(res => setFwUserArray(res));
|
||||
|
||||
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);
|
||||
}
|
||||
})
|
||||
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if(auth.user){
|
||||
setCompanyFilter(auth.user.userCmpn || "")
|
||||
if (companyFilter && !companyArray.some((company) => company.cmpnId === companyFilter)) {
|
||||
setCompanyFilter("");
|
||||
}
|
||||
}, [auth.user]);
|
||||
}, [auth.user?.userCmpn, companyArray, companyFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
if(selectedProject){
|
||||
const res = await nextApi.get<string[]>(`/assign/prjct-fieldwork/${selectedProject.prjctIdx}`);
|
||||
const assignUserInfoArray = appendUserInfo(res, fwUserArray);
|
||||
if (roleFilter) return;
|
||||
if (roleArray.length === 0) return;
|
||||
|
||||
setAssignUserArray(assignUserInfoArray);
|
||||
setOriginAssign(assignUserInfoArray);
|
||||
}else{
|
||||
setAssignUserArray([]);
|
||||
setOriginAssign([]);
|
||||
}
|
||||
resetSelect();
|
||||
});
|
||||
}, [fwUserArray, selectedProject, roleArray]);
|
||||
const contactRole = roleArray.find(r => r.value === String(CONTACT_INTERVIEWER_ROLE));
|
||||
setRoleFilter(contactRole ?? roleArray[0]);
|
||||
}, [roleArray, roleFilter]);
|
||||
|
||||
// prjctIdx 바뀌면: 편집 상태 초기화(서버 데이터 다시 주입 받을 준비)
|
||||
useEffect(() => {
|
||||
const assignString = roleArray.map((role) => {
|
||||
const assignCount = originAssign.filter(user => user.userRole.toString() === role.value).length
|
||||
return `${role.label} : ${assignCount}`;
|
||||
}).join(' / ');
|
||||
|
||||
setAssignInfoString(assignString);
|
||||
}, [originAssign]);
|
||||
if (!enabled) return;
|
||||
setDirty(false);
|
||||
resetSelect();
|
||||
setOriginAssign([]);
|
||||
setAssignUserArray([]);
|
||||
}, [enabled, prjctIdx, resetSelect]);
|
||||
|
||||
// 서버 배정 ids + fwUserArray 준비되면 "초기 1회" 주입
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
let ableUserList :UserInfo[] = [];
|
||||
if (!enabled) return;
|
||||
if (dirty) return;
|
||||
|
||||
if(sourceProject){
|
||||
const res = await nextApi.get<string[]>(`/assign/prjct-fieldwork/${sourceProject.prjctIdx}`);
|
||||
ableUserList = appendUserInfo(res, fwUserArray);
|
||||
}
|
||||
else{
|
||||
ableUserList = _.cloneDeep(fwUserArray);
|
||||
}
|
||||
const ids = assignedIdsQuery.data;
|
||||
if (!ids) return;
|
||||
|
||||
setAbleUserArray(ableUserList);
|
||||
});
|
||||
}, [fwUserArray, sourceProject]);
|
||||
// fwUserArray가 아직 비어있을 수 있으니 둘 다 준비된 상태에서만
|
||||
if (!fwUserArray || fwUserArray.length === 0) return;
|
||||
|
||||
if (!mounted || !selectedProject) return null
|
||||
const assignUserInfoArray = fwUserArray.filter(u => ids.includes(u.userId));
|
||||
setAssignUserArray(assignUserInfoArray);
|
||||
setOriginAssign(structuredClone(assignUserInfoArray));
|
||||
resetSelect();
|
||||
}, [enabled, dirty, assignedIdsQuery.data, fwUserArray, resetSelect]);
|
||||
|
||||
if (!mounted || !selectedProject) return null;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-1">
|
||||
<div className="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="mb-6 rounded-lg border border-gray-200 bg-white p-2 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 text-lg font-medium text-gray-700 whitespace-nowrap text-right">회사</div>
|
||||
<KriSelect
|
||||
items={companyArray}
|
||||
value={companyFilter}
|
||||
onChange={handleCompanyChange}
|
||||
getValue={(item) => item.cmpnId}
|
||||
getLabel={(item) => item.cmpnAlias || item.cmpnId}
|
||||
placeholder="회사 선택"
|
||||
className="w-56 h-9"
|
||||
useAll={false}
|
||||
@@ -307,9 +286,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 text-lg font-medium text-gray-700 whitespace-nowrap text-right">대상</div>
|
||||
<KriSelect
|
||||
items={roleArray}
|
||||
value={roleFilter?.value || ""}
|
||||
@@ -324,17 +301,13 @@ 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>
|
||||
<div className="p-2 bg-primary text-white rounded-lg text-lg mb-2 h-13 flex items-center">
|
||||
<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">
|
||||
<div className="bg-gray-50 p-2 border-b border-gray-200">
|
||||
<Input
|
||||
placeholder="면접원 ID Or 면접원 이름"
|
||||
value={searchAssign}
|
||||
@@ -343,23 +316,24 @@ const ProjectAssignPage = () => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-[600px] overflow-y-auto">
|
||||
<div className="h-[550px] overflow-y-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-black text-white sticky top-0">
|
||||
<thead className="bg-primary text-white sticky top-0">
|
||||
<tr>
|
||||
<th className="p-3 text-left w-12">
|
||||
<th className="p-2 text-left w-12">
|
||||
<Checkbox
|
||||
checked={selectedAssignUser.length === assignView.length && assignView.length > 0}
|
||||
onCheckedChange={handleSelectAllLeft}
|
||||
className="border-white"
|
||||
/>
|
||||
</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">배정된 {roleFilter?.label} ( {assignBase.length}명 )</th>
|
||||
<th className="p-2 text-left 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 ${
|
||||
@@ -367,14 +341,14 @@ const ProjectAssignPage = () => {
|
||||
}`}
|
||||
onClick={() => handleToggleUnassign(userInfo.userId)}
|
||||
>
|
||||
<td className="p-3">
|
||||
<td className="p-2">
|
||||
<Checkbox
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
checked={selectedAssignUser.includes(userInfo.userId)}
|
||||
onCheckedChange={() => handleToggleUnassign(userInfo.userId)}
|
||||
/>
|
||||
</td>
|
||||
<td className="p-3 content-text-base">
|
||||
<td className="p-2 text-base">
|
||||
{userInfo.userName} ({userInfo.userId})
|
||||
</td>
|
||||
</tr>
|
||||
@@ -385,12 +359,11 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 가운데: 배정/제외 버튼 */}
|
||||
<div className="flex flex-col justify-center gap-4">
|
||||
<Button
|
||||
onClick={handleAssign}
|
||||
disabled={selectedAbleUser.length === 0}
|
||||
className="bg-black hover:bg-gray-800 w-36 h-12 flex items-center justify-center content-text-base disabled:bg-gray-300"
|
||||
className="w-36 h-12 flex items-center justify-center text-base disabled:bg-gray-300"
|
||||
>
|
||||
<ChevronLeft className="w-5 h-5" />
|
||||
<span className="ml-2">배정 {selectedAbleUser.length}명</span>
|
||||
@@ -398,18 +371,16 @@ const ProjectAssignPage = () => {
|
||||
<Button
|
||||
onClick={handleRemove}
|
||||
disabled={selectedAssignUser.length === 0}
|
||||
className="bg-red-600 hover:bg-red-700 w-36 h-12 flex items-center justify-center content-text-base disabled:bg-gray-300"
|
||||
className="bg-red-600 hover:bg-red-700 w-36 h-12 flex items-center justify-center text-base disabled:bg-gray-300"
|
||||
>
|
||||
<ChevronRight className="w-5 h-5" />
|
||||
<span className="ml-2">제외 {selectedAssignUser.length}명</span>
|
||||
</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>
|
||||
<div className="p-2 bg-primary text-white rounded-lg text-lg mb-2 h-13">
|
||||
<KriSingleSelect<ProjectInfo>
|
||||
items={projectArray}
|
||||
value={String(sourceProject?.prjctIdx ?? "")}
|
||||
onChange={() => {}}
|
||||
@@ -429,7 +400,7 @@ const ProjectAssignPage = () => {
|
||||
</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">
|
||||
<div className="bg-gray-50 p-2 border-b border-gray-200">
|
||||
<Input
|
||||
placeholder="면접원 ID Or 면접원 이름"
|
||||
value={searchAble}
|
||||
@@ -438,23 +409,24 @@ const ProjectAssignPage = () => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-[600px] overflow-y-auto">
|
||||
<div className="h-[550px] overflow-y-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-black text-white sticky top-0">
|
||||
<thead className="bg-primary text-white sticky top-0">
|
||||
<tr>
|
||||
<th className="p-3 text-left w-12">
|
||||
<th className="p-2 text-left w-12">
|
||||
<Checkbox
|
||||
checked={selectedAbleUser.length === ableView.length && ableView.length > 0}
|
||||
onCheckedChange={handleSelectAllRight}
|
||||
className="border-white"
|
||||
/>
|
||||
</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">배정 가능 {roleFilter?.label} ({ableBase.length}명 )</th>
|
||||
<th className="p-2 text-left 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 ${
|
||||
@@ -462,14 +434,14 @@ const ProjectAssignPage = () => {
|
||||
}`}
|
||||
onClick={() => handleToggleAssign(user.userId)}
|
||||
>
|
||||
<td className="p-3">
|
||||
<td className="p-2">
|
||||
<Checkbox
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
checked={selectedAbleUser.includes(user.userId)}
|
||||
onCheckedChange={() => handleToggleAssign(user.userId)}
|
||||
/>
|
||||
</td>
|
||||
<td className="p-3 content-text-base">
|
||||
<td className="p-2 text-base">
|
||||
{user.userName} ({user.userId})
|
||||
</td>
|
||||
</tr>
|
||||
@@ -481,11 +453,10 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 하단 저장 버튼 */}
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
className="bg-black hover:bg-gray-800 px-12 h-11 content-text-base font-medium"
|
||||
className=" px-12 h-9 text-base font-medium"
|
||||
>
|
||||
저장
|
||||
</Button>
|
||||
@@ -495,4 +466,4 @@ const ProjectAssignPage = () => {
|
||||
)
|
||||
}
|
||||
|
||||
export default ProjectAssignPage;
|
||||
export default ProjectAssignPage;
|
||||
@@ -1,14 +1,14 @@
|
||||
import MainLayout from "@/components/layout/MainLayout";
|
||||
import AppMainLayout from "@/components/app-shell/AppMainLayout";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import {CookieKeys} from "@/store/cookie/cookie-keys";
|
||||
import {FONT_SIZE} from "@/const/commonConst";
|
||||
|
||||
function parseFontSize(raw: string | undefined | null) {
|
||||
if (!raw) return FONT_SIZE.MIN;
|
||||
if (!raw) return FONT_SIZE.DEFAULT;
|
||||
|
||||
const parsed = parseInt(raw, 10);
|
||||
if (Number.isNaN(parsed)) return FONT_SIZE.MIN;
|
||||
if (Number.isNaN(parsed)) return FONT_SIZE.DEFAULT;
|
||||
|
||||
return Math.min(
|
||||
FONT_SIZE.MAX,
|
||||
@@ -22,19 +22,17 @@ export default async function MainLayoutWrapper({
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const cookieStore = await cookies();
|
||||
const cookie = cookieStore.get(CookieKeys.FontSize);
|
||||
const accessToken = cookieStore.get("access_token")?.value;
|
||||
const initialFontSize = parseFontSize(cookie?.value);
|
||||
const fontSize = cookieStore.get(CookieKeys.FontSize);
|
||||
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
|
||||
const initialFontSize = parseFontSize(fontSize?.value);
|
||||
|
||||
if (!accessToken) {
|
||||
redirect("/logout");
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<MainLayout initialFontSize={initialFontSize}>
|
||||
{children}
|
||||
</MainLayout>
|
||||
</>
|
||||
<AppMainLayout initialFontSize={initialFontSize}>
|
||||
{children}
|
||||
</AppMainLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
const ListAssignPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
|
||||
return (<div>This is List Assign Page</div>)
|
||||
}
|
||||
|
||||
export default ListAssignPage;
|
||||
@@ -1,8 +1,166 @@
|
||||
const ListContactPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
'use client'
|
||||
|
||||
return (<div>This is List Contact Page</div>)
|
||||
import { Suspense, useEffect, useMemo, useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { ArrowLeft, CalendarClock } from "lucide-react";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useDialog } from "@/hooks/useDialog";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useListDetailQuery, useListHeaderQuery, useListReserveByUserQuery, useUpdateListMutation } from "@/query/list";
|
||||
import { useProjectInfoQuery, useResultCodesQuery } from "@/query/project";
|
||||
import ListContactInfoPanel, { buildInitialValues } from "@/components/list-contact/ListContactInfoPanel";
|
||||
import ListContactEventPanel from "@/components/list-contact/ListContactEventPanel";
|
||||
import ListUpdateHistoryPanel from "@/components/list-contact/ListUpdateHistoryPanel";
|
||||
import ReservationListDialog from "@/components/dialog/ReservationListDialog";
|
||||
import { createEmptyListFilter, type listHeader } from "@/types/list";
|
||||
import type { ResultCode } from "@/types/project";
|
||||
import { isManager } from "@/utils/userRole";
|
||||
|
||||
const ListContactPageContent = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const sid = searchParams.get("sid") ?? "";
|
||||
|
||||
const mounted = useMounted();
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
const { isDialogOpen, showDialog } = useDialog();
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const prjctCd = selectedProject?.prjctCd ?? "";
|
||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
|
||||
const userId = auth?.user?.userId ?? "";
|
||||
const userRole = auth?.user?.userRole ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0 && !!sid;
|
||||
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, mounted && prjctIdx > 0);
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, mounted && prjctIdx > 0);
|
||||
const listDetailQuery = useListDetailQuery(prjctIdx, sid, enabled);
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, mounted && prjctIdx > 0);
|
||||
const updateListMutation = useUpdateListMutation(prjctIdx);
|
||||
|
||||
const reservationDialogOpen = isDialogOpen('reservationListDialog');
|
||||
const reserveByUserQuery = useListReserveByUserQuery(prjctIdx, userId, reservationDialogOpen);
|
||||
|
||||
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]);
|
||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]);
|
||||
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const initialFormValues = useMemo(
|
||||
() => buildInitialValues(listHeaders, listDetailQuery.data),
|
||||
[listHeaders, listDetailQuery.data],
|
||||
);
|
||||
const [formValues, setFormValues] = useState<Record<number, string>>(initialFormValues);
|
||||
|
||||
useEffect(() => {
|
||||
setFormValues(initialFormValues);
|
||||
}, [initialFormValues]);
|
||||
|
||||
useEffect(() => {
|
||||
if (sid) return;
|
||||
alert("sid가 없으면 진행할 수 없습니다.");
|
||||
router.back();
|
||||
}, [sid, router]);
|
||||
|
||||
const handleNavigateToSid = (nextSid: string) => {
|
||||
router.push(`/list/contact?sid=${encodeURIComponent(nextSid)}`);
|
||||
};
|
||||
|
||||
const handleGoToListManage = () => {
|
||||
router.push("/list/manage");
|
||||
};
|
||||
|
||||
const handleFieldChange = (listHderId: number, value: string) => {
|
||||
setFormValues((prev) => ({ ...prev, [listHderId]: value }));
|
||||
};
|
||||
|
||||
const handleToggleEdit = async () => {
|
||||
if (!isEditing) {
|
||||
setIsEditing(true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await updateListMutation.mutateAsync({
|
||||
updateContents: Object.fromEntries(Object.entries(formValues)),
|
||||
listFilter: { ...createEmptyListFilter(), sidSet: [sid] },
|
||||
});
|
||||
alert("저장되었습니다.");
|
||||
setIsEditing(false);
|
||||
listDetailQuery.refetch();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert("저장 중 오류가 발생했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
if (!sid) return null;
|
||||
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<div className="flex items-center gap-3 w-1/2 pr-5">
|
||||
<Button type="button" variant="outline" size="icon" onClick={handleGoToListManage} aria-label="목록으로">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold tracking-tight">컨택 진행</h1>
|
||||
<span className="text-2xl font-bold tracking-tight">SID: {sid}</span>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('reservationListDialog')}>
|
||||
<CalendarClock className="h-4 w-4" />
|
||||
예약리스트 조회
|
||||
</Button>
|
||||
<Button type="button" disabled={updateListMutation.isPending} onClick={handleToggleEdit}>
|
||||
{isEditing ? '저장' : '수정'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
|
||||
<div className="h-[80vh] space-y-4 overflow-y-auto">
|
||||
<ListContactInfoPanel
|
||||
prjctIdx={prjctIdx}
|
||||
sid={sid}
|
||||
itrntPrjctCd={itrntPrjctCd}
|
||||
userRole={userRole}
|
||||
isEditing={isEditing}
|
||||
listHeaders={listHeaders}
|
||||
detail={listDetailQuery.data}
|
||||
surveyUrl={projectInfoQuery.data?.surveyUrl}
|
||||
formValues={formValues}
|
||||
onFieldChange={handleFieldChange}
|
||||
onSaved={() => listDetailQuery.refetch()}
|
||||
/>
|
||||
|
||||
{isManager(userRole) ? (
|
||||
<ListUpdateHistoryPanel prjctIdx={prjctIdx} sid={sid} listHeaders={listHeaders} />
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<ListContactEventPanel
|
||||
prjctIdx={prjctIdx}
|
||||
sid={sid}
|
||||
prjctCd={prjctCd}
|
||||
userId={userId}
|
||||
userRole={userRole}
|
||||
resultCodes={resultCodeArray}
|
||||
useContactSenario={projectInfoQuery.data?.useContactSenario ?? false}
|
||||
contactSenario={projectInfoQuery.data?.contactSenario}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ReservationListDialog reservations={reserveByUserQuery.data ?? []} onSelectReservation={handleNavigateToSid} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListContactPage;
|
||||
const ListContactPage = () => (
|
||||
<Suspense fallback={null}>
|
||||
<ListContactPageContent />
|
||||
</Suspense>
|
||||
);
|
||||
|
||||
export default ListContactPage;
|
||||
|
||||
@@ -1,25 +1,329 @@
|
||||
"use client";
|
||||
'use client'
|
||||
|
||||
import {useFontSizeValue} from "@/hooks/useFontSize";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import ProjectTitle from "@/components/layout/ProjectTitle";
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import type { PaginationState } from '@tanstack/react-table'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||
import { useStorage } from '@/hooks/useStorage'
|
||||
import { StorageKeys } from '@/store/storage/storage-keys'
|
||||
import { ListManageActions } from '@/components/list/ListManageActions'
|
||||
import { ListSearchTable } from '@/components/list/ListSearchTable'
|
||||
import {
|
||||
useDownloadListEventHistoryMutation,
|
||||
useDownloadListExcelTemplateMutation,
|
||||
useDownloadListItemFileMutation,
|
||||
useDownloadListMutation,
|
||||
useDownloadListUpdateHistoryMutation,
|
||||
useDownloadUploadHistoryFileMutation,
|
||||
useListHeaderQuery,
|
||||
useListUploadHistoryQuery,
|
||||
useResetListMutation,
|
||||
useUpdateListHeaderMutation,
|
||||
useUploadListExcelMutation,
|
||||
} from '@/query/list'
|
||||
import { useResultCodesQuery } from '@/query/project'
|
||||
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||
import {
|
||||
createEmptyListFilter,
|
||||
ListEventHistoryBase,
|
||||
type LastListVisit,
|
||||
type ListDownloadMode,
|
||||
type ListDownloadPayload,
|
||||
type ListFilter,
|
||||
type ListFilterTarget,
|
||||
type listHeader,
|
||||
type ListSearchUiState,
|
||||
ListResetMode,
|
||||
type ListResetScope,
|
||||
type ListUploadRequest,
|
||||
} from '@/types/list'
|
||||
import { type ResultCode, ResultCodeType } from '@/types/project'
|
||||
import ListResetDialog from '@/components/dialog/ListResetDialog'
|
||||
import ListUploadDialog from '@/components/dialog/ListUploadDialog'
|
||||
import ListHeaderManageDialog from '@/components/dialog/ListHeaderManageDialog'
|
||||
import ListDownloadDialog from '@/components/dialog/ListDownloadDialog'
|
||||
import MessageSendDialog, { type MessageSendMode } from '@/components/dialog/MessageSendDialog'
|
||||
import MessageHistoryDialog from '@/components/dialog/MessageHistoryDialog'
|
||||
import { downloadBase64File, downloadFile, XLSX_MIME_TYPE } from '@kri/common/browser'
|
||||
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
|
||||
import { isManager } from "@/utils/userRole";
|
||||
import { applyListAccessFilter } from "@/utils/listAccess";
|
||||
|
||||
const toDateTimeRange = (from?: string, to?: string) => {
|
||||
if (!from || !to) return undefined
|
||||
return {
|
||||
startDate: `${from}T00:00:00`,
|
||||
endDate: `${to}T23:59:59`,
|
||||
}
|
||||
}
|
||||
|
||||
const downloadArrayBuffer = (buffer: ArrayBuffer, filename: string, type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') => {
|
||||
downloadFile(new Blob([buffer], { type }), filename)
|
||||
}
|
||||
|
||||
const createEmptySearchUiState = (): ListSearchUiState => ({
|
||||
searchText: '',
|
||||
searchContactResult: [],
|
||||
searchInterviewResult: [],
|
||||
searchSurveyResult: [],
|
||||
filterRows: [],
|
||||
sorting: [],
|
||||
})
|
||||
|
||||
const ListManagePage = () => {
|
||||
const fontSize = useFontSizeValue();
|
||||
const mounted = useMounted();
|
||||
const router = useRouter()
|
||||
const mounted = useMounted()
|
||||
const { auth } = useAuth()
|
||||
const { showDialog } = useDialog()
|
||||
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject()
|
||||
|
||||
if (!mounted) return <LoadingOverlay force />;
|
||||
const [downloadMode, setDownloadMode] = useState<ListDownloadMode>('list')
|
||||
const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('email')
|
||||
const [selectedRows, setSelectedRows] = useState<ListTableRow[]>([])
|
||||
const [currentListFilter, setCurrentListFilter] = useState<ListFilter>(() => createEmptyListFilter())
|
||||
const [filterSummary, setFilterSummary] = useState<string[]>([])
|
||||
const [searchUiState, setSearchUiState] = useState<ListSearchUiState>(createEmptySearchUiState)
|
||||
const [listRefreshKey, setListRefreshKey] = useState(0)
|
||||
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 25 })
|
||||
const [restoredVisit, setRestoredVisit] = useState<LastListVisit | null>(null)
|
||||
const [restoreResolved, setRestoreResolved] = useState(false)
|
||||
|
||||
const { get: getLastListVisit, set: setLastListVisit, remove: removeLastListVisit } = useStorage(
|
||||
StorageKeys.LastListVisit,
|
||||
)
|
||||
|
||||
const userRole = auth?.user?.userRole ?? CONTACT_INTERVIEWER_ROLE
|
||||
const userId = auth?.user?.userId ?? ''
|
||||
const userCmpn = auth?.user?.userCmpn ?? ''
|
||||
const prjctName = selectedProject?.prjctName ?? ''
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0
|
||||
const enabled = mounted && prjctIdx > 0
|
||||
const canManageList = isManager(userRole);
|
||||
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||
const uploadHistoryQuery = useListUploadHistoryQuery(prjctIdx, enabled)
|
||||
const downloadListExcelTemplateMutation = useDownloadListExcelTemplateMutation()
|
||||
const uploadListExcelMutation = useUploadListExcelMutation(prjctIdx)
|
||||
const updateListHeaderMutation = useUpdateListHeaderMutation(prjctIdx)
|
||||
const resetListMutation = useResetListMutation(prjctIdx)
|
||||
const downloadListMutation = useDownloadListMutation(prjctIdx)
|
||||
const downloadListUpdateHistoryMutation = useDownloadListUpdateHistoryMutation(prjctIdx)
|
||||
const downloadListEventHistoryMutation = useDownloadListEventHistoryMutation(prjctIdx)
|
||||
const downloadListItemFileMutation = useDownloadListItemFileMutation(prjctIdx)
|
||||
const downloadUploadHistoryFileMutation = useDownloadUploadHistoryFileMutation(prjctIdx)
|
||||
|
||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
||||
const headerManageRows = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||
|
||||
// 컨택 진행 화면에서 돌아왔을 때 1회만 복원하고, 재방문 시 다시 나타나지 않도록 즉시 지운다.
|
||||
// ListSearchTable이 첫 마운트될 때 초기 페이지네이션 값이 확정돼 있어야 하므로(useState는 이후 prop
|
||||
// 변경을 반영하지 않음), selectedProject 하이드레이션이 끝나기 전에는 ListSearchTable을 아예 그리지 않는다.
|
||||
useEffect(() => {
|
||||
if (!mounted || !isSelectedProjectHydrated || restoreResolved) return
|
||||
const stored = getLastListVisit()
|
||||
if (stored) {
|
||||
setRestoredVisit(stored)
|
||||
removeLastListVisit()
|
||||
}
|
||||
setRestoreResolved(true)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [mounted, isSelectedProjectHydrated, restoreResolved])
|
||||
|
||||
const restoredForThisProject = restoredVisit?.prjctIdx === prjctIdx ? restoredVisit : undefined
|
||||
|
||||
const selectedSidSet = useMemo(
|
||||
() =>
|
||||
selectedRows
|
||||
.map((row) => row.sid)
|
||||
.filter((sid): sid is string | number => typeof sid === 'string' || typeof sid === 'number')
|
||||
.map(String),
|
||||
[selectedRows],
|
||||
)
|
||||
|
||||
const refreshList = () => {
|
||||
setListRefreshKey((prev) => prev + 1)
|
||||
}
|
||||
|
||||
const buildTargetFilter = (target: ListFilterTarget) => {
|
||||
if (target === 'all') {
|
||||
return applyListAccessFilter(createEmptyListFilter(), { userRole, userId, userCmpn })
|
||||
}
|
||||
if (target === 'selected') {
|
||||
return applyListAccessFilter(
|
||||
{
|
||||
...createEmptyListFilter(),
|
||||
sidSet: selectedSidSet,
|
||||
},
|
||||
{ userRole, userId, userCmpn },
|
||||
)
|
||||
}
|
||||
return applyListAccessFilter(currentListFilter, { userRole, userId, userCmpn })
|
||||
}
|
||||
|
||||
const handleStartContact = (row: ListTableRow) => {
|
||||
const sid = String(row.sid ?? '')
|
||||
setLastListVisit({
|
||||
prjctIdx,
|
||||
sid,
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
...searchUiState,
|
||||
})
|
||||
router.push(`/list/contact?sid=${encodeURIComponent(sid)}`)
|
||||
}
|
||||
|
||||
const openDownloadDialog = (mode: ListDownloadMode) => {
|
||||
setDownloadMode(mode)
|
||||
showDialog('listDownloadDialog')
|
||||
}
|
||||
|
||||
const openMessageDialog = (mode: MessageSendMode) => {
|
||||
setMessageSendMode(mode)
|
||||
showDialog('messageSendDialog')
|
||||
}
|
||||
|
||||
const handleResetConfirm = async (payload: { target: ListFilterTarget; scope: ListResetScope }) => {
|
||||
const listFilter = buildTargetFilter(payload.target)
|
||||
const resetCount = await resetListMutation.mutateAsync({
|
||||
resetMode: payload.scope === 'result-and-history' ? ListResetMode.HIST : ListResetMode.ALL,
|
||||
listFilter,
|
||||
})
|
||||
alert(`${resetCount}건 삭제 되었습니다.`)
|
||||
refreshList()
|
||||
}
|
||||
|
||||
const handleUploadConfirm = async (file: File, request: ListUploadRequest) => {
|
||||
const res = await uploadListExcelMutation.mutateAsync({ file, request })
|
||||
|
||||
if (res.hasErrorFile && res.errorFileBase64) {
|
||||
alert("업로드 중 오류가 발생하여 오류 파일을 다운로드합니다.");
|
||||
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx", XLSX_MIME_TYPE);
|
||||
}
|
||||
else{
|
||||
alert(`${res.successCount}개의 리스트를 업로드했습니다.`);
|
||||
}
|
||||
|
||||
refreshList()
|
||||
}
|
||||
|
||||
const handleDownloadTemplate = async () => {
|
||||
if (!prjctIdx) {
|
||||
alert("프로젝트를 선택해주세요.")
|
||||
return
|
||||
}
|
||||
|
||||
const buffer = await downloadListExcelTemplateMutation.mutateAsync(prjctIdx)
|
||||
downloadArrayBuffer(buffer, `${prjctName} list-upload-template.xlsx`)
|
||||
}
|
||||
|
||||
const handleHeaderManageConfirm = async (rows: listHeader[]) => {
|
||||
await updateListHeaderMutation.mutateAsync(rows)
|
||||
}
|
||||
|
||||
const handleDownloadConfirm = async (payload: ListDownloadPayload) => {
|
||||
const listFilter = buildTargetFilter(payload.target)
|
||||
|
||||
if (payload.mode === 'list') {
|
||||
const buffer = await downloadListMutation.mutateAsync(listFilter)
|
||||
downloadArrayBuffer(buffer, `${prjctName} list.xlsx`)
|
||||
return
|
||||
}
|
||||
|
||||
if (payload.mode === 'list-change-history') {
|
||||
const buffer = await downloadListUpdateHistoryMutation.mutateAsync(listFilter)
|
||||
downloadArrayBuffer(buffer, `${prjctName} update-history.xlsx`)
|
||||
return
|
||||
}
|
||||
|
||||
if (payload.mode === 'upload-file') {
|
||||
const buffer = await downloadListItemFileMutation.mutateAsync(listFilter)
|
||||
downloadArrayBuffer(buffer, `${prjctName} upload-files.zip`, 'application/zip')
|
||||
return
|
||||
}
|
||||
|
||||
const buffer = await downloadListEventHistoryMutation.mutateAsync({
|
||||
listFilter,
|
||||
resultCodeTypes: [ResultCodeType.CONTACT, ResultCodeType.INTERVIEW, ResultCodeType.SURVEY],
|
||||
searchBase: payload.contactHistoryType === 'latest' ? ListEventHistoryBase.LATEST : ListEventHistoryBase.ALL,
|
||||
dateRange: toDateTimeRange(payload.contactHistoryDateFrom, payload.contactHistoryDateTo),
|
||||
})
|
||||
downloadArrayBuffer(buffer, `${prjctName} contact-history.xlsx`)
|
||||
}
|
||||
|
||||
if (!mounted || !restoreResolved) return <LoadingOverlayAdapter force />
|
||||
|
||||
return (
|
||||
<div className="space-y-6 content-text-sm">
|
||||
<div>
|
||||
This is Manage List Page <span>{fontSize}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
<div className="space-y-6 text-sm">
|
||||
{canManageList && (
|
||||
<ListManageActions
|
||||
onReset={() => showDialog('listResetDialog')}
|
||||
onHeaderManage={() => showDialog('listHeaderManageDialog')}
|
||||
onUpload={() => showDialog('listUploadDialog')}
|
||||
onDownload={openDownloadDialog}
|
||||
onMessageSend={openMessageDialog}
|
||||
onMessageHistory={() => showDialog('messageHistoryDialog')}
|
||||
/>
|
||||
)}
|
||||
|
||||
export default ListManagePage;
|
||||
<ListSearchTable
|
||||
prjctIdx={prjctIdx}
|
||||
enabled={enabled}
|
||||
userRole={userRole}
|
||||
userId={userId}
|
||||
userCmpn={userCmpn}
|
||||
resultCodes={resultCodeArray}
|
||||
listHeaders={headerManageRows}
|
||||
enableBatchEdit={canManageList}
|
||||
refreshKey={listRefreshKey}
|
||||
onCurrentFilterChange={setCurrentListFilter}
|
||||
onFilterSummaryChange={setFilterSummary}
|
||||
onSelectedRowsChange={setSelectedRows}
|
||||
onRowClick={!canManageList ? handleStartContact : undefined}
|
||||
onRowDoubleClick={canManageList ? handleStartContact : undefined}
|
||||
initialPagination={
|
||||
restoredForThisProject
|
||||
? { pageIndex: restoredForThisProject.pageIndex, pageSize: restoredForThisProject.pageSize }
|
||||
: undefined
|
||||
}
|
||||
onPaginationChange={setPagination}
|
||||
initialSearchState={restoredForThisProject}
|
||||
onSearchStateChange={setSearchUiState}
|
||||
focusRowId={restoredForThisProject?.sid}
|
||||
/>
|
||||
|
||||
{canManageList && (
|
||||
<>
|
||||
<ListResetDialog filterSummary={filterSummary} onConfirm={handleResetConfirm} />
|
||||
<ListUploadDialog
|
||||
onUpload={handleUploadConfirm}
|
||||
onDownloadTemplate={handleDownloadTemplate}
|
||||
uploadHistory={uploadHistoryQuery.data ?? []}
|
||||
onDownloadHistory={async (item) => {
|
||||
const buffer = await downloadUploadHistoryFileMutation.mutateAsync(item.listUploadLogId)
|
||||
downloadArrayBuffer(buffer, item.fileName)
|
||||
}}
|
||||
headerRows={headerManageRows}
|
||||
/>
|
||||
<ListHeaderManageDialog prjctIdx={prjctIdx} rows={headerManageRows} onConfirm={handleHeaderManageConfirm} />
|
||||
<ListDownloadDialog mode={downloadMode} filterSummary={filterSummary} onDownload={handleDownloadConfirm} />
|
||||
<MessageSendDialog
|
||||
mode={messageSendMode}
|
||||
listHeaders={headerManageRows}
|
||||
currentFilter={currentListFilter}
|
||||
selectedRows={selectedRows}
|
||||
filterSummary={filterSummary}
|
||||
onSent={refreshList}
|
||||
/>
|
||||
<MessageHistoryDialog />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListManagePage
|
||||
|
||||
99
src/app/(pages)/(main)/manage/cmpn/page.tsx
Normal file
99
src/app/(pages)/(main)/manage/cmpn/page.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { DataTable } from "@/components/data-table/DataTable";
|
||||
import { getCmpnColumns } from "@/components/table-column/CmpnTableColumn";
|
||||
import CmpnUpsertDialog from "@/components/dialog/CmpnUpsertDialog";
|
||||
import { useDialog } from "@/hooks/useDialog";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import type { CmpnInfoSaveRequest } from "@/types/cmpn";
|
||||
import {
|
||||
useCheckCmpnIdDuplicateMutation,
|
||||
useCmpnDetailQuery,
|
||||
useCmpnListQuery,
|
||||
useUpsertCmpnMutation,
|
||||
} from "@/query/cmpn";
|
||||
|
||||
const CmpnManagePage = () => {
|
||||
const { showDialog } = useDialog();
|
||||
const mounted = useMounted();
|
||||
|
||||
const cmpnListQuery = useCmpnListQuery();
|
||||
const checkDupMutation = useCheckCmpnIdDuplicateMutation();
|
||||
const upsertMutation = useUpsertCmpnMutation();
|
||||
|
||||
const [editCmpnId, setEditCmpnId] = useState<string | null>(null);
|
||||
const [dialogMode, setDialogMode] = useState<'create' | 'edit'>('create');
|
||||
const cmpnDetailQuery = useCmpnDetailQuery(editCmpnId ?? "", !!editCmpnId);
|
||||
|
||||
const cmpnList = cmpnListQuery.data ?? [];
|
||||
|
||||
const handleCreateClick = () => {
|
||||
setDialogMode("create");
|
||||
setEditCmpnId(null);
|
||||
showDialog("cmpnUpsertDialog");
|
||||
};
|
||||
|
||||
const handleEdit = (cmpnId: string) => {
|
||||
setDialogMode("edit");
|
||||
setEditCmpnId(cmpnId);
|
||||
showDialog("cmpnUpsertDialog");
|
||||
};
|
||||
|
||||
const handleCheckDuplicate = (cmpnId: string) => {
|
||||
return checkDupMutation.mutateAsync(cmpnId);
|
||||
};
|
||||
|
||||
const handleSubmit = async (data: CmpnInfoSaveRequest): Promise<void> => {
|
||||
await upsertMutation.mutateAsync({ mode: dialogMode, data });
|
||||
|
||||
if (dialogMode === "create") {
|
||||
alert("등록되었습니다.");
|
||||
} else {
|
||||
alert("수정되었습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
const columns = getCmpnColumns({
|
||||
onEdit: handleEdit,
|
||||
});
|
||||
|
||||
if (!mounted) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText={"회사 관리"} />
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleCreateClick}>
|
||||
회사 등록
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={cmpnList}
|
||||
isClient={true}
|
||||
selectMode="single"
|
||||
defaultPageSize={10}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.cmpnId}
|
||||
maxBodyHeight="71vh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<CmpnUpsertDialog
|
||||
mode={dialogMode}
|
||||
initialData={dialogMode === "edit" ? (cmpnDetailQuery.data ?? undefined) : undefined}
|
||||
onSubmit={handleSubmit}
|
||||
onCheckDuplicate={handleCheckDuplicate}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CmpnManagePage;
|
||||
@@ -1,199 +1,177 @@
|
||||
'use client'
|
||||
'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 AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { DataTable } from "@/components/data-table/DataTable";
|
||||
import { getUserColumns } from "./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 {UserInfoSaveRequest} from "@/types/user";
|
||||
import UserUploadDialog from "@/components/dialog/UserUploadDialog";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {downloadBase64File, downloadFile, formatKst} 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 { downloadBase64File, downloadFile, XLSX_MIME_TYPE } from "@kri/common/browser";
|
||||
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 type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import {DEFAULT_COMPANY_NAME} from "@/const/userConst";
|
||||
import {Upload} from "lucide-react";
|
||||
import {
|
||||
useRoleListQuery,
|
||||
useUsersQuery,
|
||||
useUserDetailQuery,
|
||||
useCheckUserIdDuplicateMutation,
|
||||
useUpsertUserMutation,
|
||||
useDeleteUserMutation,
|
||||
useUploadUsersExcelMutation,
|
||||
useDownloadUserExcelTemplateMutation,
|
||||
} from "@/query/user";
|
||||
import { useCmpnListQuery } from "@/query/cmpn";
|
||||
import { isInternalManager } from "@/utils/userRole";
|
||||
|
||||
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 = useCmpnListQuery();
|
||||
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");
|
||||
alert("업로드 중 오류가 발생하여 오류 파일을 다운로드합니다.");
|
||||
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx", XLSX_MIME_TYPE);
|
||||
}
|
||||
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], {
|
||||
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
downloadFile(blob, "사용자 업로드 양식.xlsx");
|
||||
alert("다운로드 됐습니다.");
|
||||
downloadFile(blob, "사용자_업로드_양식.xlsx");
|
||||
alert("다운로드되었습니다.");
|
||||
} else {
|
||||
console.log("빈 파일입니다.");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const columns = getUserColumns(
|
||||
{
|
||||
onEdit: handleEdit,
|
||||
onDelete: handleDelete
|
||||
},
|
||||
userRoleArray
|
||||
userRoleArray,
|
||||
userCmpnArray
|
||||
);
|
||||
|
||||
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 &&
|
||||
auth.user.userRole < EXTERNAL_USER_ROLE
|
||||
isInternalManager(auth.user?.userRole)
|
||||
|
||||
const userCmpn = auth.user?.userCmpn ?? DEFAULT_COMPANY_NAME;
|
||||
|
||||
if (!mounted) return <LoadingOverlay force />;
|
||||
if (!mounted) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 content-text-sm">
|
||||
<BodyTitle titleText={"계정 관리"}/>
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText={"사용자 관리"}/>
|
||||
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
<Input
|
||||
placeholder="면접원 ID Or 면접원 이름"
|
||||
placeholder="사용자 ID 또는 사용자 이름"
|
||||
className="w-70 h-9 bg-white"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
@@ -204,6 +182,8 @@ const UserManagePage = () => {
|
||||
items={userCmpnArray}
|
||||
value={searchCmpn}
|
||||
onChange={setSearchCmpn}
|
||||
getValue={(item) => item.cmpnId}
|
||||
getLabel={(item) => item.cmpnAlias || item.cmpnId}
|
||||
placeholder="소속 회사"
|
||||
widthClassName="w-70"
|
||||
heightClassName="h-9"
|
||||
@@ -221,16 +201,16 @@ const UserManagePage = () => {
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
className="content-text-lg"
|
||||
onClick={handleCreateClick}
|
||||
>
|
||||
면접원 등록
|
||||
사용자 등록
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => showDialog('userUploadDialog')}
|
||||
className="gap-2 bg-green-600 hover:bg-green-700 content-text-lg"
|
||||
className="gap-2 bg-excel"
|
||||
>
|
||||
면접원 일괄 등록
|
||||
<Upload className="w-4 h-4" />
|
||||
사용자 일괄 등록
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -239,17 +219,17 @@ const UserManagePage = () => {
|
||||
columns={columns}
|
||||
data={viewList}
|
||||
isClient={true}
|
||||
selectMode='single'
|
||||
onRowSelectionChange={setSelectedUserArray}
|
||||
selectMode='none'
|
||||
defaultPageSize={10}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.userId} // row.id = userId
|
||||
maxBodyHeight="71vh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<UserUpsertDialog
|
||||
mode={dialogMode}
|
||||
initialData={editData}
|
||||
initialData={dialogMode === "edit" ? (userDetailQuery.data ?? undefined) : undefined}
|
||||
isInternal={isInternal}
|
||||
userCmpn={userCmpn}
|
||||
userCmpnArray={userCmpnArray}
|
||||
@@ -266,4 +246,4 @@ const UserManagePage = () => {
|
||||
);
|
||||
}
|
||||
|
||||
export default UserManagePage;
|
||||
export default UserManagePage;
|
||||
|
||||
@@ -1,9 +1,24 @@
|
||||
const EmailTemplatePage = () => {
|
||||
//파라미터 받기
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
import { MessageType, type TemplateEmail } from "@kri/common/noti-hub";
|
||||
import MessageTemplate from "@/components/message-template/MessageTemplate";
|
||||
|
||||
return (<div>This is Email Template Page</div>)
|
||||
const EmailTemplatePage = () => {
|
||||
|
||||
const defaultEmailTemplate : TemplateEmail = {
|
||||
tmplatIdx: undefined,
|
||||
itrntPrjctCd: '',
|
||||
tmplatTy: MessageType.EMAIL,
|
||||
tmplatNm: '',
|
||||
tmplatTitle: '',
|
||||
tmplatBody: '',
|
||||
sendEml: '',
|
||||
sendNm: ''
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<MessageTemplate pageTitle={"이메일 템플릿 관리"} defaultTemplate={defaultEmailTemplate}/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default EmailTemplatePage;
|
||||
export default EmailTemplatePage;
|
||||
|
||||
26
src/app/(pages)/(main)/message/template/sms/page.tsx
Normal file
26
src/app/(pages)/(main)/message/template/sms/page.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
'use client'
|
||||
|
||||
import { MessageType, type TemplateSms } from "@kri/common/noti-hub";
|
||||
import MessageTemplate from "@/components/message-template/MessageTemplate";
|
||||
|
||||
const SmsTemplatePage = () => {
|
||||
|
||||
const defaultSmsTemplate : TemplateSms = {
|
||||
tmplatIdx: undefined,
|
||||
itrntPrjctCd: '',
|
||||
tmplatTy: MessageType.SMS,
|
||||
tmplatNm: '',
|
||||
tmplatTitle: undefined,
|
||||
tmplatBody: '',
|
||||
sendTel: '',
|
||||
sendNm: ''
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<MessageTemplate pageTitle="문자 템플릿 관리" defaultTemplate={defaultSmsTemplate}/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SmsTemplatePage;
|
||||
@@ -1,9 +0,0 @@
|
||||
const TextTemplatePage = () => {
|
||||
//파라미터 받기
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
|
||||
return (<div>This is Text Message Template Page</div>)
|
||||
}
|
||||
|
||||
export default TextTemplatePage;
|
||||
@@ -1,61 +1,94 @@
|
||||
'use client'
|
||||
import {useEffect, useRef, useState} from "react";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import {useMemo, useState} from "react";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {DataTable} from "@/components/data-table/DataTable";
|
||||
import {getProjectColumns} from "./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 type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
import {PaginationState, SortingState} from "@tanstack/react-table";
|
||||
import {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 {ProjectStatus} from "@/const/projectConst";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import {useItrntUserList} from "@/hooks/useItrntUserList";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
|
||||
import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
||||
import {isManager} from "@/utils/userRole";
|
||||
|
||||
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 { setSelectedProject } = useSelectedProject();
|
||||
|
||||
const [statusArray, setStatusArray] = useState<MultiSelectOption[]>([]);
|
||||
const [deptArray, setDeptArray] = useState<string[]>([]);
|
||||
const [fwArray, setFwArray] = useState<string[]>([]);
|
||||
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 });
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [query, setQuery] = useState<ProjectListQuery>();
|
||||
|
||||
|
||||
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 [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 columns = getProjectColumns(users);
|
||||
const userId = auth.user?.userId ?? "";
|
||||
const userRole = auth.user?.userRole ?? FW_USER_ROLE;
|
||||
const userRole = auth.user?.userRole;
|
||||
|
||||
const handleSearchClick = () => {
|
||||
const searchStatusCode:ProjectStatus[] = searchStatus
|
||||
@@ -76,88 +109,43 @@ 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,
|
||||
prjctName: projectInfo.prjctName,
|
||||
itrntPrjctCd: projectInfo.itrntPrjctCd,
|
||||
ownerDept: projectInfo.ownerDept,
|
||||
ownerFw: projectInfo.ownerFw,
|
||||
surveyTy: projectInfo.surveyTy,
|
||||
ff: projectInfo.ff
|
||||
} as SelectedProject);
|
||||
|
||||
window.location.href = `/project/info`;
|
||||
}
|
||||
router.push("/project/info");
|
||||
};
|
||||
|
||||
const handleClick = (projectInfo:ProjectInfo) => {
|
||||
setSelectedProject({
|
||||
prjctIdx: projectInfo.prjctIdx,
|
||||
prjctCd: projectInfo.prjctCd,
|
||||
prjctName: projectInfo.prjctName,
|
||||
itrntPrjctCd: projectInfo.itrntPrjctCd,
|
||||
ownerDept: projectInfo.ownerDept,
|
||||
ownerFw: projectInfo.ownerFw,
|
||||
surveyTy: projectInfo.surveyTy,
|
||||
ff: projectInfo.ff
|
||||
} 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 searchBody: ProjectListRequest = {
|
||||
prjctText: query?.prjctText || "",
|
||||
prjctStatusList: query?.prjctStatusList || [],
|
||||
ownerDeptList: query?.ownerDeptList || [],
|
||||
ownerFwList: query?.ownerFwList || [],
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
sortBy: sort.id,
|
||||
sortDir: sort.desc ? "desc" : "asc"
|
||||
}
|
||||
|
||||
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 />;
|
||||
if (!mounted || isLoading) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 content-text-sm">
|
||||
<BodyTitle titleText={"프로젝트"}/>
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText={"프로젝트"}/>
|
||||
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
@@ -173,7 +161,7 @@ const MainPage = () => {
|
||||
}}
|
||||
/>
|
||||
{
|
||||
userRole < FW_USER_ROLE &&
|
||||
isManager(userRole) &&
|
||||
<KriMultiSelect
|
||||
items={statusArray}
|
||||
value={searchStatus}
|
||||
@@ -197,19 +185,19 @@ const MainPage = () => {
|
||||
items={fwArray}
|
||||
value={searchFw}
|
||||
onChange={setSearchFw}
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="담당 실사"
|
||||
widthClassName="w-60"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
<Button
|
||||
className="content-text-lg"
|
||||
onClick={handleSearchClick}
|
||||
>
|
||||
검색
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
className="content-text-lg"
|
||||
onClick={handleCreateClick}
|
||||
>
|
||||
프로젝트 등록
|
||||
@@ -223,12 +211,14 @@ const MainPage = () => {
|
||||
isClient={false}
|
||||
pageCount={pageCount}
|
||||
totalCount={totalCount}
|
||||
pagination={pagination}
|
||||
onPaginationChange={setPagination}
|
||||
onSortingChange={setSorting}
|
||||
selectMode='click-event'
|
||||
onRowClick={handleClick}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.prjctCd} // row.id = userId
|
||||
maxBodyHeight="71vh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -241,4 +231,4 @@ const MainPage = () => {
|
||||
)
|
||||
}
|
||||
|
||||
export default MainPage;
|
||||
export default MainPage;
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
const ContactProgressPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
'use client'
|
||||
|
||||
return (<div>This is Contact Progress Page</div>)
|
||||
}
|
||||
import { ProgressPageContent } from "@/components/progress/ProgressPageContent";
|
||||
import { ProgressEventType } from "@/types/progress";
|
||||
import { ResultCodeType } from "@/types/project";
|
||||
|
||||
export default ContactProgressPage;
|
||||
const ContactProgressPage = () => (
|
||||
<ProgressPageContent
|
||||
eventTy={ProgressEventType.CONTACT}
|
||||
resultCdTy={ResultCodeType.CONTACT}
|
||||
pageTitle="컨택 현황"
|
||||
domainLabel="컨택"
|
||||
personLabel="컨택인력"
|
||||
/>
|
||||
);
|
||||
|
||||
export default ContactProgressPage;
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
const FieldworkProgressPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
|
||||
return (<div>This is Fieldwork Progress Page</div>)
|
||||
}
|
||||
|
||||
export default FieldworkProgressPage;
|
||||
17
src/app/(pages)/(main)/progress/interview/page.tsx
Normal file
17
src/app/(pages)/(main)/progress/interview/page.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
'use client'
|
||||
|
||||
import { ProgressPageContent } from "@/components/progress/ProgressPageContent";
|
||||
import { ProgressEventType } from "@/types/progress";
|
||||
import { ResultCodeType } from "@/types/project";
|
||||
|
||||
const InterviewProgressPage = () => (
|
||||
<ProgressPageContent
|
||||
eventTy={ProgressEventType.INTERVIEW}
|
||||
resultCdTy={ResultCodeType.INTERVIEW}
|
||||
pageTitle="면접 현황"
|
||||
domainLabel="면접"
|
||||
personLabel="면접원"
|
||||
/>
|
||||
);
|
||||
|
||||
export default InterviewProgressPage;
|
||||
@@ -1,8 +1,151 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import KriDateRangePicker from "@/components/common/KriDateRangePicker";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useSendResultSummaryQuery } from "@/query/message";
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
import { MessageType } from "@kri/common/noti-hub";
|
||||
import type { SendResultSummaryResponse } from "@kri/common/noti-hub";
|
||||
|
||||
const SEND_TYPE_ORDER = [MessageType.SMS, MessageType.LMS_MMS, MessageType.EMAIL] as const;
|
||||
|
||||
const SEND_TYPE_LABEL: Record<number, string> = {
|
||||
[MessageType.SMS]: "단문",
|
||||
[MessageType.LMS_MMS]: "장문",
|
||||
[MessageType.EMAIL]: "메일",
|
||||
};
|
||||
|
||||
type SummaryRow = {
|
||||
sendTy: number;
|
||||
price: number;
|
||||
totalCount: number;
|
||||
cost: number;
|
||||
successCount: number;
|
||||
failCount: number;
|
||||
standByCount: number;
|
||||
};
|
||||
|
||||
const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) =>
|
||||
list.reduce((acc, item) => acc + (item[field] as number | undefined ?? 0), 0);
|
||||
|
||||
const buildRows = (data: SendResultSummaryResponse[]): SummaryRow[] =>
|
||||
SEND_TYPE_ORDER.map((sendTy) => {
|
||||
const matched = data.filter((item) => item.sendTy === sendTy);
|
||||
return {
|
||||
sendTy,
|
||||
price: matched[0]?.price ?? 0,
|
||||
totalCount: sum(matched, "totalCount"),
|
||||
cost: sum(matched, "cost"),
|
||||
successCount: sum(matched, "successCount"),
|
||||
failCount: sum(matched, "failCount"),
|
||||
standByCount: sum(matched, "standByCount"),
|
||||
};
|
||||
});
|
||||
|
||||
const moneyUnit = (value: number) => `${value.toLocaleString()}원`;
|
||||
const caseUnit = (value: number) => `${value.toLocaleString()}건`;
|
||||
|
||||
const getFirstDayOfMonth = (date: Date) => {
|
||||
const d = new Date(date.getFullYear(), date.getMonth(), 1);
|
||||
return d.toISOString().slice(0, 10);
|
||||
};
|
||||
|
||||
const getLastDayOfMonth = (date: Date) => {
|
||||
const d = new Date(date.getFullYear(), date.getMonth() + 1, 0);
|
||||
return d.toISOString().slice(0, 10);
|
||||
};
|
||||
|
||||
const MessageProgressPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
const mounted = useMounted();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
|
||||
return (<div>This is Message Progress Page</div>)
|
||||
}
|
||||
const [dateRange, setDateRange] = useState(() => {
|
||||
const now = new Date();
|
||||
return { from: getFirstDayOfMonth(now), to: getLastDayOfMonth(now) };
|
||||
});
|
||||
|
||||
export default MessageProgressPage;
|
||||
const prjctCd = selectedProject?.prjctCd ?? "";
|
||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
|
||||
const enabled = mounted && !!prjctCd && !!dateRange.from && !!dateRange.to;
|
||||
|
||||
const summaryQuery = useSendResultSummaryQuery(
|
||||
{
|
||||
reqstSvc: clientEnv.REQUEST_SVC,
|
||||
itrntPrjctCd,
|
||||
prjctCd,
|
||||
sendStartDt: dateRange.from ? `${dateRange.from}T00:00:00` : undefined,
|
||||
sendEndDt: dateRange.to ? `${dateRange.to}T23:59:59` : undefined,
|
||||
},
|
||||
enabled,
|
||||
);
|
||||
|
||||
const rows = useMemo(() => buildRows(summaryQuery.data ?? []), [summaryQuery.data]);
|
||||
|
||||
const total = useMemo(
|
||||
() => ({
|
||||
totalCount: rows.reduce((acc, row) => acc + row.totalCount, 0),
|
||||
cost: rows.reduce((acc, row) => acc + row.cost, 0),
|
||||
successCount: rows.reduce((acc, row) => acc + row.successCount, 0),
|
||||
failCount: rows.reduce((acc, row) => acc + row.failCount, 0),
|
||||
standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0),
|
||||
}),
|
||||
[rows],
|
||||
);
|
||||
|
||||
if (!mounted) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="발송 현황" />
|
||||
|
||||
<KriDateRangePicker value={dateRange} onChange={setDateRange} className="w-80" />
|
||||
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-blue-50">
|
||||
<tr>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">유형</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">단가</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">대상수</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">비용</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">성공</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">실패</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">발송중</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.sendTy} className="border-b last:border-b-0">
|
||||
<td className="h-10 px-3 text-center">{SEND_TYPE_LABEL[row.sendTy]}</td>
|
||||
<td className="h-10 px-3 text-center">{moneyUnit(row.price)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(row.totalCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{moneyUnit(row.cost)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(row.successCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(row.failCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(row.standByCount)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr className="bg-gray-50 font-semibold">
|
||||
<td className="h-10 px-3 text-center" colSpan={2}>합계</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(total.totalCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{moneyUnit(total.cost)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(total.successCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(total.failCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(total.standByCount)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
※ 보낸 내역을 토대로 계산된 값으로 실제 정산 금액과 차이가 발생할 수 있습니다.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MessageProgressPage;
|
||||
|
||||
68
src/app/(pages)/(main)/progress/survey/page.tsx
Normal file
68
src/app/(pages)/(main)/progress/survey/page.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useProjectInfoQuery, useSurveyRedirectUrlQuery } from "@/query/project";
|
||||
import { SurveyType } from "@/types/project";
|
||||
|
||||
const SurveyProgressPage = () => {
|
||||
const mounted = useMounted();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
const openedRef = useRef(false);
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0;
|
||||
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
|
||||
const projectInfo = projectInfoQuery.data;
|
||||
const surveyTy = projectInfo?.surveyTy ?? SurveyType.NONE;
|
||||
|
||||
const isKonKiwi = surveyTy === SurveyType.KON || surveyTy === SurveyType.KIWI;
|
||||
const isKiwi = surveyTy === SurveyType.KIWI ? 1 : 0;
|
||||
const pkey = projectInfo?.surveyPrjctCd ?? "";
|
||||
|
||||
const redirectUrlEnabled = enabled && !!projectInfo && isKonKiwi && !!pkey;
|
||||
const redirectUrlQuery = useSurveyRedirectUrlQuery(isKiwi, pkey, redirectUrlEnabled);
|
||||
|
||||
const targetUrl = isKonKiwi
|
||||
? (redirectUrlQuery.data ?? null)
|
||||
: surveyTy === SurveyType.EXTERNAL
|
||||
? (projectInfo?.surveyDashboardUrl || null)
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (openedRef.current || !targetUrl) return;
|
||||
openedRef.current = true;
|
||||
window.open(targetUrl, "_blank");
|
||||
}, [targetUrl]);
|
||||
|
||||
const isLoading = !mounted || projectInfoQuery.isLoading || (redirectUrlEnabled && redirectUrlQuery.isLoading);
|
||||
|
||||
if (isLoading) return <LoadingOverlayAdapter force />;
|
||||
|
||||
if (targetUrl) {
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="설문 현황" />
|
||||
<p>
|
||||
새 창에서 열립니다. 열리지 않았다면{" "}
|
||||
<a href={targetUrl} target="_blank" rel="noreferrer" className="text-blue-600 underline">
|
||||
여기
|
||||
</a>
|
||||
를 클릭해 주세요.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="연결 가능한 현황이 없습니다." />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SurveyProgressPage;
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import {useEffect, useState, useCallback, useRef} from 'react'
|
||||
import BodyTitle from '@/components/layout/BodyTitle'
|
||||
import {useEffect, useState, useCallback, useRef, useMemo} from 'react'
|
||||
import AppPageTitle from '@/components/app-shell/AppPageTitle'
|
||||
import {Button} from '@/components/ui/button'
|
||||
import {Input} from '@/components/ui/input'
|
||||
import {Label} from '@/components/ui/label'
|
||||
@@ -11,27 +11,34 @@ import {Tabs, TabsContent, TabsList, TabsTrigger} from '@/components/ui/tabs'
|
||||
import {KriMultiSelect, KriSingleSelect} from '@/components/common/KriAutoComplete'
|
||||
import {useDialog} from '@/hooks/useDialog'
|
||||
import ResultCodeDialog from '@/components/dialog/ResultCodeDialog'
|
||||
import {useMounted} from '@/hooks/useMounted'
|
||||
import {LoadingOverlay} from '@/components/common/LoadingOverlay'
|
||||
import {KonKiwiProjectInfo, ProjectInfo, ProjectUpdateRequest, ResultCode} from "@/types/project";
|
||||
import { useDebouncedValue, useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
||||
import {
|
||||
ProjectInfo, ProjectUpdateRequest, ResultCode,
|
||||
ProjectStatus, ResultCodeType, SurveyType
|
||||
} from "@/types/project";
|
||||
import {
|
||||
PROJECT_STATUS_LABEL,
|
||||
PROJECT_STATUS_ORDER,
|
||||
ProjectStatus, ResultCodeType,
|
||||
SURVEY_TYPE_LABEL,
|
||||
SURVEY_TYPE_ORDER,
|
||||
SurveyType
|
||||
} from "@/const/projectConst";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
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,
|
||||
useAssignedCmpnIdsQuery,
|
||||
useUpdateProjectMutation,
|
||||
useDeleteProjectMutation,
|
||||
useUploadScenarioImageMutation, useKartProjectListQuery,
|
||||
} from "@/query/project";
|
||||
import { useCmpnListQuery } from "@/query/cmpn";
|
||||
|
||||
const defaultProjectInfo: ProjectInfo = {
|
||||
prjctIdx: 0,
|
||||
@@ -44,6 +51,7 @@ const defaultProjectInfo: ProjectInfo = {
|
||||
surveyTy: SurveyType.NONE,
|
||||
surveyPrjctCd: '',
|
||||
surveyUrl: '',
|
||||
surveyDashboardUrl: '',
|
||||
ff: false,
|
||||
useContactSenario: false,
|
||||
contactSenario: '',
|
||||
@@ -53,80 +61,121 @@ 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 initialProjectInfoRef = useRef<ProjectInfo | null>(null);
|
||||
|
||||
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 cmpnListQuery = useCmpnListQuery();
|
||||
const assignedCmpnQuery = useAssignedCmpnIdsQuery(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 [assignCmpnIdArray, setAssignCmpnIdArray] = useState<string[]>([]);
|
||||
const [changeResultCodeType, setChangeResultCodeType] = useState<ResultCodeType[]>([]);
|
||||
|
||||
const cmpnOptionArray: MultiSelectOption[] = useMemo(() => {
|
||||
const arr = cmpnListQuery.data ?? [];
|
||||
return arr.filter((cmpn) => !cmpn.ownCmpn).map((cmpn) => ({
|
||||
value: cmpn.cmpnId,
|
||||
label: cmpn.cmpnAlias || cmpn.cmpnId,
|
||||
}));
|
||||
}, [cmpnListQuery.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);
|
||||
async (file: File): Promise<string> => {
|
||||
if (!projectInfo.prjctCd) {
|
||||
alert("프로젝트 코드가 없습니다. 잠시 후 다시 시도해주세요.");
|
||||
return "";
|
||||
}
|
||||
|
||||
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')
|
||||
@@ -138,120 +187,114 @@ 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,
|
||||
assignCmpnIdList: assignCmpnIdArray,
|
||||
}
|
||||
|
||||
await nextApi.patch(`/project/${projectInfo.prjctIdx}`, requestUpdateProject);
|
||||
|
||||
await updateMutation.mutateAsync(requestUpdateProject);
|
||||
initialProjectInfoRef.current = projectInfo;
|
||||
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[]>(`/project/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);
|
||||
initialProjectInfoRef.current = projectInfoQuery.data;
|
||||
}
|
||||
}, [selectedProject])
|
||||
}, [projectInfoQuery.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (resultCodesQuery.data) {
|
||||
setResultCodeArray(resultCodesQuery.data);
|
||||
}
|
||||
}, [resultCodesQuery.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (assignedCmpnQuery.data) {
|
||||
setAssignCmpnIdArray(assignedCmpnQuery.data);
|
||||
}
|
||||
}, [assignedCmpnQuery.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (projectInfo.surveyTy !== SurveyType.EXTERNAL) {
|
||||
setExternalTab('redirect')
|
||||
}
|
||||
}, [projectInfo.surveyTy]);
|
||||
|
||||
if(projectInfo.surveyPrjctCd && internalSurvey.includes(projectInfo.surveyTy || SurveyType.NONE)){
|
||||
let surveyUrl = `/project/${projectInfo.surveyPrjctCd}/INDEX.asp?${sidParam}`;
|
||||
if(projectInfo.surveyTy === SurveyType.KON){
|
||||
// KON/KIWI 프로젝트 "선택"을 사용자가 직접 바꿨을 때만 surveyUrl을 자동 생성한다.
|
||||
// 저장된 프로젝트를 불러오는 경우(조회) 등에는 저장돼 있는 surveyUrl을 그대로 보여줘야 한다.
|
||||
const handleSurveyPrjctCdChange = (value: string) => {
|
||||
setProjectInfo((prev) => {
|
||||
const next = {...prev, surveyPrjctCd: value};
|
||||
|
||||
if (value && internalSurvey.has(prev.surveyTy || SurveyType.NONE)) {
|
||||
let surveyUrl = `/project/${value}/INDEX.asp?${sidParam}`;
|
||||
if (prev.surveyTy === SurveyType.KON) {
|
||||
surveyUrl = `https://kon.kric.com` + surveyUrl
|
||||
}
|
||||
else if(projectInfo.surveyTy === SurveyType.KIWI){
|
||||
} else if (prev.surveyTy === SurveyType.KIWI) {
|
||||
surveyUrl = `https://kon.kiwisurvey.kr` + surveyUrl
|
||||
}
|
||||
|
||||
handleChange('surveyUrl', surveyUrl)
|
||||
next.surveyUrl = surveyUrl;
|
||||
}
|
||||
}
|
||||
}, [projectInfo.surveyTy, projectInfo.surveyPrjctCd])
|
||||
|
||||
return next;
|
||||
})
|
||||
}
|
||||
|
||||
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]);
|
||||
// 설문 연동(surveyTy)을 바꾸면 선택된 KON/KIWI 프로젝트, 설문 URL, 설문 대시보드 URL을 초기화한다.
|
||||
// 단, 최초 조회 시점의 surveyTy로 다시 돌아오면 그때 저장돼 있던 값을 복원한다.
|
||||
const handleSurveyTyChange = (value: string) => {
|
||||
const nextSurveyTy = Number(value) as SurveyType;
|
||||
const initial = initialProjectInfoRef.current;
|
||||
const backToInitial = !!initial && initial.surveyTy === nextSurveyTy;
|
||||
|
||||
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]);
|
||||
setProjectInfo((prev) => ({
|
||||
...prev,
|
||||
surveyTy: nextSurveyTy,
|
||||
surveyPrjctCd: backToInitial ? (initial!.surveyPrjctCd ?? '') : '',
|
||||
surveyUrl: backToInitial ? (initial!.surveyUrl ?? '') : '',
|
||||
surveyDashboardUrl: backToInitial ? (initial!.surveyDashboardUrl ?? '') : '',
|
||||
}))
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const keyword = debouncedKeyword.trim();
|
||||
searchKonKiwiPrjct(keyword).then();
|
||||
}, [debouncedKeyword, projectInfo.surveyTy, userTeam]);
|
||||
|
||||
if (!mounted) return <LoadingOverlay force />
|
||||
if (!mounted) return <LoadingOverlayAdapter force />
|
||||
|
||||
return (
|
||||
<div className="min-h-full">
|
||||
<div className="space-y-6 pb-24 px-6">
|
||||
<div className="max-w-[900px]">
|
||||
<BodyTitle titleText="프로젝트 정보" />
|
||||
<AppPageTitle titleText="프로젝트 정보" />
|
||||
|
||||
{/* 1. 기본 정보 */}
|
||||
<div className="border rounded-lg p-6 space-y-5 bg-white mt-6">
|
||||
<h3 className="content-text-xl font-semibold">프로젝트 기본 정보</h3>
|
||||
<h3 className="text-xl font-semibold">프로젝트 기본 정보</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="content-text-base">프로젝트 코드</Label>
|
||||
<Label className="text-base">프로젝트 코드</Label>
|
||||
<Input value={projectInfo.prjctCd || ''} disabled className="bg-gray-100 h-9" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-[1fr_auto] gap-3 items-end">
|
||||
<div className="space-y-2">
|
||||
<Label className="content-text-base">진행 상태</Label>
|
||||
<Label className="text-base">진행 상태</Label>
|
||||
<RadioGroup
|
||||
value={String(projectInfo.prjctStatus ?? ProjectStatus.WAITING)}
|
||||
onValueChange={(v) => handleChange('prjctStatus', Number(v) as ProjectStatus)}
|
||||
@@ -262,7 +305,7 @@ const ProjectInfoPage = () => {
|
||||
return (
|
||||
<div key={s} className="flex items-center space-x-2">
|
||||
<RadioGroupItem value={String(s)} id={id} />
|
||||
<Label htmlFor={id} className="font-normal cursor-pointer content-text-base">
|
||||
<Label htmlFor={id} className="font-normal cursor-pointer text-base">
|
||||
{PROJECT_STATUS_LABEL[s]}
|
||||
</Label>
|
||||
</div>
|
||||
@@ -271,13 +314,13 @@ const ProjectInfoPage = () => {
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
<Button onClick={handleResultCodeClick} className="h-9 content-text-base whitespace-nowrap">
|
||||
<Button onClick={handleResultCodeClick} className="h-9 text-base whitespace-nowrap">
|
||||
결과 코드 설정
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="content-text-base">
|
||||
<Label className="text-base">
|
||||
프로젝트 명<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
@@ -290,7 +333,7 @@ const ProjectInfoPage = () => {
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="content-text-base">담당 그룹</Label>
|
||||
<Label className="text-base">담당 그룹</Label>
|
||||
<KriSingleSelect
|
||||
items={deptArray}
|
||||
value={projectInfo.ownerDept || ''}
|
||||
@@ -302,7 +345,7 @@ const ProjectInfoPage = () => {
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="content-text-base">담당 실사</Label>
|
||||
<Label className="text-base">담당 실사</Label>
|
||||
<KriSingleSelect
|
||||
items={fwArray}
|
||||
value={projectInfo.ownerFw || ''}
|
||||
@@ -319,11 +362,11 @@ const ProjectInfoPage = () => {
|
||||
</div>
|
||||
|
||||
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
|
||||
<h3 className="content-text-xl font-semibold">외주사</h3>
|
||||
<h3 className="text-xl font-semibold">외주사</h3>
|
||||
<KriMultiSelect
|
||||
items={outsourceOptionArray}
|
||||
value={outsourceUserArray}
|
||||
onChange={(value) => setOutsourceUserArray(value)}
|
||||
items={cmpnOptionArray}
|
||||
value={assignCmpnIdArray}
|
||||
onChange={(value) => setAssignCmpnIdArray(value)}
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
maxCount={2}
|
||||
@@ -334,11 +377,11 @@ const ProjectInfoPage = () => {
|
||||
</div>
|
||||
|
||||
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
|
||||
<h3 className="content-text-xl font-semibold">설문 연동</h3>
|
||||
<h3 className="text-xl font-semibold">설문 연동</h3>
|
||||
|
||||
<RadioGroup
|
||||
value={String(projectInfo.surveyTy ?? SurveyType.NONE)}
|
||||
onValueChange={(v) => handleChange('surveyTy', Number(v) as SurveyType)}
|
||||
onValueChange={handleSurveyTyChange}
|
||||
className="flex gap-4"
|
||||
>
|
||||
{SURVEY_TYPE_ORDER.map((t) => {
|
||||
@@ -346,7 +389,7 @@ const ProjectInfoPage = () => {
|
||||
return (
|
||||
<div key={t} className="flex items-center space-x-2">
|
||||
<RadioGroupItem value={String(t)} id={id} />
|
||||
<Label htmlFor={id} className="font-normal cursor-pointer content-text-base">
|
||||
<Label htmlFor={id} className="font-normal cursor-pointer text-base">
|
||||
{SURVEY_TYPE_LABEL[t]}
|
||||
</Label>
|
||||
</div>
|
||||
@@ -356,11 +399,11 @@ const ProjectInfoPage = () => {
|
||||
|
||||
{(projectInfo.surveyTy === SurveyType.KON || projectInfo.surveyTy === SurveyType.KIWI) && (
|
||||
<div className="space-y-2">
|
||||
<Label className="content-text-base">{SURVEY_TYPE_LABEL[projectInfo.surveyTy]} 프로젝트</Label>
|
||||
<Label className="text-base">{SURVEY_TYPE_LABEL[projectInfo.surveyTy]} 프로젝트</Label>
|
||||
<KriSingleSelect
|
||||
items={surveyProjectArray}
|
||||
value={projectInfo.surveyPrjctCd || ''}
|
||||
onChange={(value) => handleChange('surveyPrjctCd', value)}
|
||||
onChange={handleSurveyPrjctCdChange}
|
||||
getValue={(item) => item.pkey}
|
||||
getLabel={(item) => `[${item.pkey}] ${item.title}`}
|
||||
searchMode={"inputOnly"}
|
||||
@@ -373,7 +416,7 @@ const ProjectInfoPage = () => {
|
||||
)}
|
||||
{projectInfo.surveyTy !== SurveyType.NONE && (
|
||||
<div className="space-y-2">
|
||||
<Label className="content-text-base">설문 URL</Label>
|
||||
<Label className="text-base">설문 URL</Label>
|
||||
<Input
|
||||
value={projectInfo.surveyUrl || ''}
|
||||
onChange={(e) => handleChange('surveyUrl', e.target.value)}
|
||||
@@ -383,6 +426,18 @@ const ProjectInfoPage = () => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{projectInfo.surveyTy === SurveyType.EXTERNAL && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">설문 대시보드 URL</Label>
|
||||
<Input
|
||||
value={projectInfo.surveyDashboardUrl || ''}
|
||||
onChange={(e) => handleChange('surveyDashboardUrl', e.target.value)}
|
||||
placeholder="https://"
|
||||
className="h-9"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{projectInfo.surveyTy === SurveyType.EXTERNAL && (
|
||||
<div className="space-y-2">
|
||||
<Tabs value={externalTab} onValueChange={(v) => setExternalTab(v as ExternalTab)} className="w-full">
|
||||
@@ -397,19 +452,19 @@ const ProjectInfoPage = () => {
|
||||
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 content-text-base">시작:</Label>
|
||||
<Label className="w-24 text-base">시작:</Label>
|
||||
<Input value={externalUrls.redirect.start} disabled className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 content-text-base">완료:</Label>
|
||||
<Label className="w-24 text-base">완료:</Label>
|
||||
<Input value={externalUrls.redirect.complete} disabled className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 content-text-base">스크린 아웃:</Label>
|
||||
<Label className="w-24 text-base">스크린 아웃:</Label>
|
||||
<Input value={externalUrls.redirect.screen} disabled className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 content-text-base">쿼터 풀:</Label>
|
||||
<Label className="w-24 text-base">쿼터 풀:</Label>
|
||||
<Input value={externalUrls.redirect.quota} disabled className="bg-white h-9" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -422,19 +477,19 @@ const ProjectInfoPage = () => {
|
||||
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 content-text-base">시작 API:</Label>
|
||||
<Label className="w-24 text-base">시작 API:</Label>
|
||||
<Input value={externalUrls.api.start} disabled className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 content-text-base">완료 API:</Label>
|
||||
<Label className="w-24 text-base">완료 API:</Label>
|
||||
<Input value={externalUrls.api.complete} disabled className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 content-text-base">스크린 API:</Label>
|
||||
<Label className="w-24 text-base">스크린 API:</Label>
|
||||
<Input value={externalUrls.api.screen} disabled className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 content-text-base">쿼터 API:</Label>
|
||||
<Label className="w-24 text-base">쿼터 API:</Label>
|
||||
<Input value={externalUrls.api.quota} disabled className="bg-white h-9" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -448,7 +503,7 @@ const ProjectInfoPage = () => {
|
||||
</div>
|
||||
|
||||
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
|
||||
<h3 className="content-text-xl font-semibold">기타 옵션</h3>
|
||||
<h3 className="text-xl font-semibold">기타 옵션</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
@@ -457,7 +512,7 @@ const ProjectInfoPage = () => {
|
||||
checked={projectInfo.ff || false}
|
||||
onCheckedChange={(checked) => handleChange('ff', checked === true)}
|
||||
/>
|
||||
<Label htmlFor="ff" className="font-normal cursor-pointer content-text-base">
|
||||
<Label htmlFor="ff" className="font-normal cursor-pointer text-base">
|
||||
현장 면접 진행
|
||||
</Label>
|
||||
</div>
|
||||
@@ -468,7 +523,7 @@ const ProjectInfoPage = () => {
|
||||
checked={projectInfo.useContactSenario || false}
|
||||
onCheckedChange={(checked) => handleChange('useContactSenario', checked === true)}
|
||||
/>
|
||||
<Label htmlFor="useContactSenario" className="font-normal cursor-pointer content-text-base">
|
||||
<Label htmlFor="useContactSenario" className="font-normal cursor-pointer text-base">
|
||||
컨택 시나리오
|
||||
</Label>
|
||||
</div>
|
||||
@@ -476,7 +531,6 @@ const ProjectInfoPage = () => {
|
||||
{projectInfo.useContactSenario && (
|
||||
<div className="ml-6 border rounded p-4 bg-gray-50 text-sm text-gray-600">
|
||||
<KriEditor
|
||||
//editorMode={"both"}
|
||||
value={projectInfo.contactSenario ?? "<p></p>"}
|
||||
onChange={(html: string) => handleChange("contactSenario", html)}
|
||||
placeholder="컨택 시나리오를 작성해 주세요"
|
||||
@@ -497,12 +551,12 @@ const ProjectInfoPage = () => {
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="destructive"
|
||||
className="w-32 h-10 content-text-base"
|
||||
className="w-32 h-10 text-base"
|
||||
onClick={handleDeleteClick}
|
||||
>
|
||||
삭제
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} className="w-32 h-10 content-text-base">
|
||||
<Button onClick={handleSubmit} className="w-32 h-10 text-base">
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,100 +1,49 @@
|
||||
"use client";
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
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 {useRouter, useSearchParams} from "next/navigation";
|
||||
import {LoginUser} from "@/types/auth";
|
||||
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 React, { useEffect, useRef, useState } from "react";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {apiError} from "@kri/common/http";
|
||||
import {NONE_HTTP_ERROR} from "@kri/common/http";
|
||||
import {useLoginMutation} from "@/query/auth";
|
||||
|
||||
const LoginPage = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const { auth, setFromLoginResponse } = useAuth();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const { get: getSeatNumberStorage, set: setSeatNumberStorage } = useStorage(StorageKeys.SeatNumber);
|
||||
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
|
||||
const router = useRouter();
|
||||
|
||||
const loginMutation = useLoginMutation();
|
||||
|
||||
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 passwordInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const seatNumberInputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const tryLogin = () => {
|
||||
if(!userId){
|
||||
alert("아이디를 입력해 주세요");
|
||||
}
|
||||
if(!userPw){
|
||||
alert("PW를 입력해 주세요");
|
||||
}
|
||||
if(loginType === "call" && !seatNum){
|
||||
alert("자리번호를 입력해 주세요");
|
||||
}
|
||||
const tryLogin = async () => {
|
||||
if (!userId) return alert("Please enter ID.");
|
||||
if (!userPw) return alert("Please enter password.");
|
||||
|
||||
setError(null);
|
||||
const loginRequestBody = {userId, userPw};
|
||||
const loginRequestOptions = {autoLogoutOnAuthError: false};
|
||||
|
||||
// withLoading 래퍼로 API 호출 전/후 로딩 표시를 자동으로 처리
|
||||
return withLoadingAsync(() =>
|
||||
nextApi.post<LoginUser>(
|
||||
"/login", loginRequestBody, loginRequestOptions
|
||||
).then(async (data) => { // Jotai 기반 전역 인증 상태 갱신
|
||||
setFromLoginResponse(data, seatNum);
|
||||
// 요구사항: 페이지 이동 전에 SeatNumber를 secure-local-storage에 저장
|
||||
try {
|
||||
setSeatNumberStorage(seatNum);
|
||||
setLoginTypeStorage(loginType);
|
||||
} catch (e) {
|
||||
// 저장 실패는 치명적이지 않으므로 콘솔 로깅만
|
||||
console.warn("Failed to persist SeatNumber to secure storage:", e);
|
||||
}
|
||||
}).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 });
|
||||
} catch (e) {
|
||||
const err = apiError(e, {
|
||||
fallbackMessage: "Login failed.",
|
||||
});
|
||||
if (err.status === 401 || err.status === 403) setError("아이디 또는 비밀번호를 다시 확인해주세요.");
|
||||
else if (err.code === NONE_HTTP_ERROR) setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
|
||||
else setError(`로그인에 실패했습니다. (${err.message})`);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if(auth.user){
|
||||
window.location.replace("/");
|
||||
if (loginMutation.isSuccess) {
|
||||
router.replace("/");
|
||||
}
|
||||
}, [auth]);
|
||||
|
||||
// URL 쿼리 파라미터에서 type 수신
|
||||
useEffect(() => {
|
||||
const typeParam = searchParams.get("type") ?? "";
|
||||
let seatNumTemp = "";
|
||||
|
||||
if(typeParam === "call") {
|
||||
seatNumTemp = getSeatNumberStorage();
|
||||
}
|
||||
setSeatNum(seatNumTemp);
|
||||
setLoginType(typeParam);
|
||||
}, [searchParams]);
|
||||
}, [loginMutation.isSuccess, router]);
|
||||
|
||||
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
@@ -104,19 +53,6 @@ const LoginPage = () => {
|
||||
};
|
||||
|
||||
const handlePwKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
const seatNumberInput = seatNumberInputRef.current;
|
||||
if(loginType === "call" && seatNumberInput?.value === ""){
|
||||
seatNumberInput.focus();
|
||||
}
|
||||
else{
|
||||
tryLogin();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSeatNumberKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
tryLogin();
|
||||
@@ -132,7 +68,7 @@ const LoginPage = () => {
|
||||
<Image
|
||||
src="/kri_logo.png" // public/kri_logo.png
|
||||
alt="KRI 로고"
|
||||
width={500} // 원하는 크기로 줄이기
|
||||
width={500}
|
||||
height={500}
|
||||
className="object-contain ml-10"
|
||||
priority
|
||||
@@ -143,13 +79,13 @@ const LoginPage = () => {
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">ID</label>
|
||||
<label className="text-base font-medium">ID</label>
|
||||
<Input
|
||||
id="id"
|
||||
name="id"
|
||||
type="text"
|
||||
required
|
||||
placeholder="아이디를 입력하세요"
|
||||
placeholder="ID"
|
||||
value={userId}
|
||||
onChange={(e) => setUserId(e.currentTarget.value)}
|
||||
onKeyDown={handleIdKeyDown}
|
||||
@@ -157,14 +93,14 @@ const LoginPage = () => {
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Password</label>
|
||||
<label className="text-base font-medium">Password</label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
placeholder="PW를 입력하세요"
|
||||
placeholder="password"
|
||||
value={userPw}
|
||||
onChange={(e) => setUserPw(e.currentTarget.value)}
|
||||
onKeyDown={handlePwKeyDown}
|
||||
@@ -172,24 +108,6 @@ const LoginPage = () => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{loginType === "call"?
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">자리번호 (면접원)</label>
|
||||
<Input
|
||||
id="seatNum"
|
||||
name="seatNum"
|
||||
type="text"
|
||||
placeholder="자리번호를 입력하세요"
|
||||
value={seatNum}
|
||||
onChange={(e) => setSeatNum(e.currentTarget.value)}
|
||||
onKeyDown={handleSeatNumberKeyDown}
|
||||
ref={seatNumberInputRef}
|
||||
/>
|
||||
</div>
|
||||
:
|
||||
null
|
||||
}
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-500">
|
||||
{error}
|
||||
@@ -199,6 +117,7 @@ const LoginPage = () => {
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full mt-6 h-11"
|
||||
disabled={loginMutation.isPending}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
tryLogin();
|
||||
@@ -213,4 +132,4 @@ const LoginPage = () => {
|
||||
);
|
||||
}
|
||||
|
||||
export default LoginPage;
|
||||
export default LoginPage;
|
||||
|
||||
@@ -1,49 +1,20 @@
|
||||
'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 () => {
|
||||
await logoutMutation.mutateAsync();
|
||||
router.replace("/login");
|
||||
})();
|
||||
}, []);
|
||||
|
||||
// Nothing to render while redirecting
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export default LogoutPage;
|
||||
30
src/app/(pages)/redirect/[slug]/page.tsx
Normal file
30
src/app/(pages)/redirect/[slug]/page.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import RedirectLanding from "@/components/external/RedirectLanding";
|
||||
import {notFound} from "next/navigation";
|
||||
import {ALLOW_REDIRECT} from "@/const/commonConst";
|
||||
import {RedirectSlug} from "@/types/common";
|
||||
|
||||
type redirectPageProps = {
|
||||
params: Promise<{ slug: string }>;
|
||||
searchParams?: Promise<Record<string, string | string[] | undefined>>;
|
||||
}
|
||||
|
||||
const toRedirectSlug = (slug: string): RedirectSlug | null => {
|
||||
return ALLOW_REDIRECT.has(slug.toLowerCase()) ? (slug.toLowerCase() as RedirectSlug) : null;
|
||||
}
|
||||
|
||||
const redirectPage = async ({
|
||||
params,
|
||||
searchParams,
|
||||
}: redirectPageProps) => {
|
||||
const { slug } = await params;
|
||||
const sp = searchParams ? await searchParams : undefined;
|
||||
const redirectSlug = toRedirectSlug(slug);
|
||||
|
||||
if (!redirectSlug) notFound();
|
||||
|
||||
return (
|
||||
<RedirectLanding redirectSlug={redirectSlug} />
|
||||
)
|
||||
}
|
||||
|
||||
export default redirectPage;
|
||||
35
src/app/(pages)/redirect/error/page.tsx
Normal file
35
src/app/(pages)/redirect/error/page.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import ErrorPage from "@/components/external/Error";
|
||||
import {ErrorCode} from "@/types/common";
|
||||
|
||||
function toErrorCode(raw: string | undefined): ErrorCode {
|
||||
if (raw === "500") return "500";
|
||||
// fetch_error, 기타 알 수 없는 코드 → 500으로 처리
|
||||
if (raw && raw !== "404") return "500";
|
||||
return "404";
|
||||
}
|
||||
|
||||
type RedirectErrorPageProps = {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
};
|
||||
|
||||
const RedirectErrorPage = async ({ searchParams }: RedirectErrorPageProps) => {
|
||||
const sp = await searchParams;
|
||||
|
||||
console.log(sp)
|
||||
|
||||
const code = toErrorCode(sp.code as string | undefined);
|
||||
const sid = (sp.sid as string | undefined) ?? "";
|
||||
|
||||
return (
|
||||
<ErrorPage
|
||||
code={code}
|
||||
errorDescription={
|
||||
sid
|
||||
? `오류가 발생했습니다. 관리자에게 문의할 경우 아래 코드를 전달해 주세요.\n리스트 ID : ${sid}`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default RedirectErrorPage
|
||||
@@ -1,8 +1,7 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {DataVerification, RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {UserInfo, UserUploadResponse} from "@/types/user";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
@@ -10,8 +9,8 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "prjct-outsource" && slug.length === 2) {
|
||||
const result = await contactApi.get<string[]>(`/assign/prjct-outsource/${slug[1]}`);
|
||||
if (action === "prjct-cmpn" && slug.length === 2) {
|
||||
const result = await contactApi.get<string[]>(`/assign/prjct-cmpn/${slug[1]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
@@ -32,7 +31,7 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "prjct-fieldwork" && slug.length === 2) {
|
||||
if ((action === "prjct-fieldwork" || action === "prjct-cmpn") && slug.length === 2) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
@@ -41,12 +40,43 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.put(`/assign/prjct-fieldwork/${slug[1]}`, body);
|
||||
await contactApi.put(`/assign/${action}/${slug[1]}`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (action === "list" && slug.length === 3) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await contactApi.put<number>(`/assign/list/${slug[1]}/${slug[2]}`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "list" && slug[1] === "reset" && slug.length === 3) {
|
||||
const body = await req.json().catch(() => null);
|
||||
const result = await contactApi.del<number>(`/assign/list/reset/${slug[2]}`, { json: body });
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
93
src/app/api/cmpn/[[...slug]]/route.ts
Normal file
93
src/app/api/cmpn/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createContactApi } from "@/lib/http-server";
|
||||
import type { CmpnInfo } from "@/types/cmpn";
|
||||
import type { DataVerification } from "@kri/common";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "check-cmpn-id") {
|
||||
const cmpnId = req.nextUrl.searchParams.get("cmpnId") ?? "";
|
||||
if (!cmpnId) {
|
||||
return NextResponse.json(
|
||||
{ message: "cmpnId 파라미터가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await contactApi.get<DataVerification>("/cmpn/check-cmpn-id", {
|
||||
query: { cmpnId },
|
||||
});
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (slug.length === 1) {
|
||||
const result = await contactApi.get<CmpnInfo>(`/cmpn/${encodeURIComponent(action)}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (!action) {
|
||||
const result = await contactApi.get<CmpnInfo[]>("/cmpn");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (!action) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.put("/cmpn", body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (!action) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.patch("/cmpn", body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
95
src/app/api/external/[[...slug]]/route.ts
vendored
95
src/app/api/external/[[...slug]]/route.ts
vendored
@@ -1 +1,94 @@
|
||||
//외부 설문에 뎐동 되는 API
|
||||
// External survey event API.
|
||||
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { RouteContext } from "@/types/common";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { getClientIp } from "@kri/common/server";
|
||||
import {
|
||||
EXTERNAL_ACTION_CODE_BY_SLUG,
|
||||
ExternalAction,
|
||||
ExternalEntryType,
|
||||
ExternalEventBody,
|
||||
} from "@/types/external";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
|
||||
const getHeader = (headers: Headers, name: string): string | null => {
|
||||
const value = headers.get(name);
|
||||
return value && value.trim().length > 0 ? value : null;
|
||||
};
|
||||
|
||||
const getEntryType = (headers: Headers): ExternalEntryType => {
|
||||
return getHeader(headers, "x-entry-type") === "redirect" ? "redirect" : "api";
|
||||
};
|
||||
|
||||
const toExternalAction = (value: string): ExternalAction | null => {
|
||||
return value in EXTERNAL_ACTION_CODE_BY_SLUG ? (value as ExternalAction) : null;
|
||||
};
|
||||
|
||||
const toRequiredNumber = (value: string): number | null => {
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
};
|
||||
|
||||
const buildExternalEventBody = (
|
||||
req: NextRequest,
|
||||
action: ExternalAction,
|
||||
prjctIdx: number,
|
||||
sid: number,
|
||||
): ExternalEventBody => {
|
||||
const pathname = req.nextUrl.pathname;
|
||||
const h = req.headers;
|
||||
const actionCode = EXTERNAL_ACTION_CODE_BY_SLUG[action];
|
||||
|
||||
return {
|
||||
actionCode,
|
||||
prjctIdx,
|
||||
sid,
|
||||
meta: {
|
||||
entryType: getEntryType(h),
|
||||
action,
|
||||
actionCode,
|
||||
pid: String(prjctIdx),
|
||||
sid: String(sid),
|
||||
remoteAddr: getHeader(h, "x-orig-ip") || getClientIp(req),
|
||||
uri: getHeader(h, "x-orig-uri") || pathname,
|
||||
url: getHeader(h, "x-orig-url") || req.url,
|
||||
userAgent: getHeader(h, "x-orig-user-agent") || getHeader(h, "user-agent"),
|
||||
referer: getHeader(h, "x-orig-referer") || getHeader(h, "referer"),
|
||||
origin: getHeader(h, "x-orig-origin") || getHeader(h, "origin"),
|
||||
xForwardedFor: getHeader(h, "x-orig-x-forwarded-for") || getHeader(h, "x-forwarded-for"),
|
||||
forwarded: getHeader(h, "x-orig-forwarded") || getHeader(h, "forwarded"),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const handleExternalEvent = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const { slug = [] } = await context.params;
|
||||
const action = toExternalAction((slug[0] ?? "").toLowerCase());
|
||||
|
||||
if (slug.length !== 1 || !action) {
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const prjctIdx = toRequiredNumber((searchParams.get("pid") ?? "").trim());
|
||||
const sid = toRequiredNumber((searchParams.get("sid") ?? "").trim());
|
||||
|
||||
if (!prjctIdx || !sid) {
|
||||
return NextResponse.json({ message: "pid와 sid는 필수입니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = buildExternalEventBody(req, action, prjctIdx, sid);
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
await contactApi.post(`/list-hist/survey`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const GET = handleExternalEvent;
|
||||
export const POST = handleExternalEvent;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi, createIntranetApi} from "@/lib/server-api";
|
||||
import {IntranetProjectSearchResponse, ProjectInfo, ProjectOwnerResponse} from "@/types/project";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createIntranetApi} from "@/lib/http-server";
|
||||
import {IntranetProjectSearchResponse} from "@/types/project";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
@@ -32,4 +32,4 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createKartApi} from "@/lib/server-api";
|
||||
import {createKartApi} from "@/lib/http-server";
|
||||
import {KonKiwiProjectInfo} from "@/types/project";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
@@ -21,8 +21,24 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "survey-redirect-url" && slug.length === 3){
|
||||
const [, isKiwi, pkey] = slug;
|
||||
|
||||
const skey = await kartApi.get<string>(`/encrypt/pkey`, {
|
||||
headers: { pkey, iskiwi: isKiwi },
|
||||
});
|
||||
|
||||
const shortUrl = await kartApi.post<string>(
|
||||
`/uri/short`,
|
||||
{ realURI: "/Report/Current", mode: "U" },
|
||||
{ headers: { skey } },
|
||||
);
|
||||
|
||||
return NextResponse.json(shortUrl, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
25
src/app/api/list-call-hist/[[...slug]]/route.ts
Normal file
25
src/app/api/list-call-hist/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [prjctIdx, sid] = slug;
|
||||
if (!prjctIdx || !sid) {
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ message: "요청 바디가 없습니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const contactApi = await createContactApi();
|
||||
const result = await contactApi.put(`/list-call-hist/${prjctIdx}/${sid}`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
52
src/app/api/list-hist/[[...slug]]/route.ts
Normal file
52
src/app/api/list-hist/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {ListEventHistory, ListUpdateHistory} from "@/types/list";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "event" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListEventHistory[]>(`/list-hist/event/${slug[1]}/${slug[2]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "update" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListUpdateHistory[]>(`/list-hist/update/${slug[1]}/${slug[2]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "event") {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.put(`/list-hist/event`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
174
src/app/api/list/[[...slug]]/route.ts
Normal file
174
src/app/api/list/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import type {PageResponse} from "@kri/common";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import {listHeader, ListSearchRequest, ListSearchWithFullResult} from "@/types/list";
|
||||
|
||||
const excelHeaders = {
|
||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
};
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(action === "header") {
|
||||
const result = await contactApi.get<listHeader[]>(
|
||||
`/list-header/${slug[1]}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "upload-history") {
|
||||
const result = await contactApi.get(`/list/excel/upload-history/${slug[1]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "search-sid" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListSearchWithFullResult>(`/list/search-sid/${slug[1]}/${slug[2]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(action === "search-filter"){
|
||||
const body: ListSearchRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await contactApi.post<PageResponse<ListSearchWithFullResult>>(
|
||||
`/list/search-filter/${slug[1]}`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "excel-template") {
|
||||
const prjctIdx = slug[1];
|
||||
if (!prjctIdx) {
|
||||
return NextResponse.json({ message: "prjctIdx 파라미터가 없습니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const result = await contactApi.post<ArrayBuffer>(
|
||||
`/list/excel/template/${prjctIdx}`,
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: {
|
||||
...excelHeaders,
|
||||
"Content-Disposition": 'attachment; filename="list_upload_template.xlsx"',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (action === "item-file-upload" && slug.length === 3) {
|
||||
const form = await req.formData();
|
||||
await contactApi.postForm(`/list/item-file/upload/${slug[1]}/${slug[2]}`, form);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (action === "excel-upload") {
|
||||
const form = await req.formData();
|
||||
const result = await contactApi.postForm(`/list/excel/upload/${slug[1]}`, form);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "excel-download") {
|
||||
const body = await req.json().catch(() => null);
|
||||
const result = await contactApi.post<ArrayBuffer>(`/list/excel/download/${slug[1]}`, body, { expectBinary: true });
|
||||
return new NextResponse(result, { status: 200, headers: excelHeaders });
|
||||
}
|
||||
|
||||
if (action === "excel-download-update") {
|
||||
const body = await req.json().catch(() => null);
|
||||
const result = await contactApi.post<ArrayBuffer>(`/list/excel/download/update/${slug[1]}`, body, {
|
||||
expectBinary: true,
|
||||
});
|
||||
return new NextResponse(result, { status: 200, headers: excelHeaders });
|
||||
}
|
||||
|
||||
if (action === "event-history-download") {
|
||||
const body = await req.json().catch(() => null);
|
||||
const result = await contactApi.post<ArrayBuffer>(`/list-hist/excel/download/event/${slug[1]}`, body, {
|
||||
expectBinary: true,
|
||||
});
|
||||
return new NextResponse(result, { status: 200, headers: excelHeaders });
|
||||
}
|
||||
|
||||
if (action === "item-file-download") {
|
||||
const body = await req.json().catch(() => null);
|
||||
const result = await contactApi.post<ArrayBuffer>(`/list/item-file/download/${slug[1]}`, body, {
|
||||
expectBinary: true,
|
||||
});
|
||||
return new NextResponse(result, { status: 200, headers: { "Content-Type": "application/zip" } });
|
||||
}
|
||||
|
||||
if (action === "upload-history-file") {
|
||||
const result = await contactApi.post<ArrayBuffer>(
|
||||
`/list/excel/upload-history/file/${slug[1]}/${slug[2]}`,
|
||||
undefined,
|
||||
{ expectBinary: true },
|
||||
);
|
||||
return new NextResponse(result, { status: 200, headers: excelHeaders });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const body = await req.json().catch(() => null);
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "header") {
|
||||
await contactApi.patch(`/list-header/${slug[1]}`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (action === "update") {
|
||||
const result = await contactApi.patch<number>(`/list/update/${slug[1]}`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const body = await req.json().catch(() => null);
|
||||
const contactApi = await createContactApi();
|
||||
const result = await contactApi.del<number>(`/list/${slug[0]}`, { json: body });
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -1,10 +1,11 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {LoginRequest, LoginUser} from "@/types/auth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type { LoginRequest, LoginUser } from "@kri/common";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import {CookieKeys} from "@/store/cookie/cookie-keys";
|
||||
|
||||
//실제 Backend
|
||||
//?ㅼ젣 Backend
|
||||
type LoginResponse = {
|
||||
accessToken: string;
|
||||
user: LoginUser;
|
||||
@@ -18,16 +19,16 @@ export const POST = async (req: NextRequest) => {
|
||||
const result = await contactApi.post<LoginResponse>("/auth/login", body);
|
||||
|
||||
const res = NextResponse.json(result.user, { status: 200 });
|
||||
res.cookies.set("access_token", result.accessToken, {
|
||||
res.cookies.set(CookieKeys.AuthToken, result.accessToken, {
|
||||
httpOnly: true,
|
||||
secure: serverEnv.ENV === "prod",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 24 * 60 * 60, // 24시간
|
||||
maxAge: 24 * 60 * 60, // 24?쒓컙
|
||||
});
|
||||
|
||||
return res;
|
||||
} catch (error : unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {CookieKeys} from "@/store/cookie/cookie-keys";
|
||||
|
||||
export async function POST(
|
||||
req: NextRequest,
|
||||
@@ -21,7 +22,7 @@ export async function POST(
|
||||
await contactApi.post<boolean>(url);
|
||||
const res = NextResponse.json({ ok: true });
|
||||
|
||||
res.cookies.set("access_token", "", {
|
||||
res.cookies.set(CookieKeys.AuthToken, "", {
|
||||
httpOnly: true,
|
||||
secure: serverEnv.ENV === "prod",
|
||||
sameSite: "lax",
|
||||
@@ -33,4 +34,4 @@ export async function POST(
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
82
src/app/api/message-report/[[...slug]]/route.ts
Normal file
82
src/app/api/message-report/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createNotihubApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {FileResponse, PageRequest, PageResponse} from "@kri/common";
|
||||
import type {BulkSendInfo, SendResultSummaryRequest, SendResultSummaryResponse} from "@kri/common/noti-hub";
|
||||
import type {SendResultInfo} from "@/types/message";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, sendTy, reqstSvc, prjctCd] = slug;
|
||||
const notihubApi = await createNotihubApi();
|
||||
|
||||
if (action === "bulk-list" && sendTy && reqstSvc && prjctCd) {
|
||||
const result = await notihubApi.get<BulkSendInfo[]>(
|
||||
`/report/bulk-list/${sendTy}/${reqstSvc}/${prjctCd}`,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
if (action === "send-result" && slug.length >= 4) {
|
||||
const [, sid, prjctCdParam, reqstSvcParam] = slug;
|
||||
const channelTy = req.nextUrl.searchParams.get("channelTy");
|
||||
const query = channelTy ? `?channelTy=${channelTy}` : "";
|
||||
const result = await notihubApi.get<SendResultInfo[]>(
|
||||
`/report/send-result/${sid}/${prjctCdParam}/${reqstSvcParam}${query}`,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, bulkSendKey] = slug;
|
||||
const notihubApi = await createNotihubApi();
|
||||
|
||||
if (action === "bulk-detail" && bulkSendKey) {
|
||||
const body: PageRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
const result = await notihubApi.post<PageResponse<SendResultInfo>>(
|
||||
`/report/bulk-detail/${bulkSendKey}`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
if (action === "bulk-detail-excel" && bulkSendKey) {
|
||||
const result = await notihubApi.post<FileResponse>(
|
||||
`/report/bulk-detail/excel/${bulkSendKey}`,
|
||||
undefined,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
if (action === "send-result-summary") {
|
||||
const body: SendResultSummaryRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
const result = await notihubApi.post<SendResultSummaryResponse[]>(
|
||||
`/report/send-result-summary`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
105
src/app/api/message-template/[[...slug]]/route.ts
Normal file
105
src/app/api/message-template/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createNotihubApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type { Template, TemplateSummary } from "@kri/common/noti-hub";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try{
|
||||
const { searchParams } = new URL(req.url);
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const notihubApi = await createNotihubApi();
|
||||
|
||||
if(slug.length === 1){
|
||||
const result = await notihubApi.get<Template>(
|
||||
`/template/${slug[0]}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "list" && slug.length === 3){
|
||||
const result = await notihubApi.get<TemplateSummary[]>(
|
||||
`/template/list/${slug[1]}/${slug[2]}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try{
|
||||
const { searchParams } = new URL(req.url);
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const notihubApi = await createNotihubApi();
|
||||
|
||||
if(action === "body-image" && slug.length === 2){
|
||||
const itrntPrjctCd = slug[1];
|
||||
|
||||
const formData = await req.formData();
|
||||
const file = formData.get("file") as File | null;
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json(
|
||||
{ message: "file 필드가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await notihubApi.putForm<string>(
|
||||
`/template/body-image/${itrntPrjctCd}`,
|
||||
formData
|
||||
);
|
||||
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(!action){
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await notihubApi.put<Template>(`/template`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
try{
|
||||
const { searchParams } = new URL(req.url);
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const notihubApi = await createNotihubApi();
|
||||
|
||||
if(!action){
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await notihubApi.patch<Template>(`/template`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
38
src/app/api/message/[[...slug]]/route.ts
Normal file
38
src/app/api/message/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {MessageBulkSendResponse} from "@/types/message";
|
||||
|
||||
const isChannel = (value: string): value is "sms" | "email" => value === "sms" || value === "email";
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [channel, action, prjctIdx] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (!isChannel(channel) || !prjctIdx) {
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
if (action === "single") {
|
||||
await contactApi.post(`/message/${channel}/single/${prjctIdx}`, body);
|
||||
return new NextResponse(null, {status: 204});
|
||||
}
|
||||
|
||||
if (action === "bulk") {
|
||||
const result = await contactApi.post<MessageBulkSendResponse>(`/message/${channel}/bulk/${prjctIdx}`, body);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
39
src/app/api/progress/[[...slug]]/route.ts
Normal file
39
src/app/api/progress/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {ProgressDateResponse, ProgressSearchRequest, ProgressUserResponse} from "@/types/progress";
|
||||
|
||||
const ACTION_PATH: Record<string, string> = {
|
||||
"user": "/progress/user",
|
||||
"last-date": "/progress/last-date",
|
||||
"date": "/progress/date",
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, prjctIdx, eventTy] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
const basePath = ACTION_PATH[action];
|
||||
if (!basePath || !prjctIdx || !eventTy) {
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
}
|
||||
|
||||
const body: ProgressSearchRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
if (action === "user") {
|
||||
const result = await contactApi.post<ProgressUserResponse[]>(`${basePath}/${prjctIdx}/${eventTy}`, body);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
const result = await contactApi.post<ProgressDateResponse[]>(`${basePath}/${prjctIdx}/${eventTy}`, body);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -1,8 +1,9 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {createContactApi, createIntranetApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {PageResponse, RouteContext} from "@/types/common";
|
||||
import {IntranetProjectSearchResponse, ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {createContactApi, createIntranetApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {PageResponse} from "@kri/common";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {ProjectInfo, ProjectListRequest, ProjectOwnerResponse} from "@/types/project";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
@@ -32,12 +33,12 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "result-code" && slug.length === 2){
|
||||
const result = await contactApi.get<ResultCode[]>(`/result-code/${slug[1]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
if(action === "main-template" && slug.length === 3){
|
||||
const result = await contactApi.get<number | null | "">(`/project/main-template/${slug[1]}/${slug[2]}`);
|
||||
const returValue = result === null || result === "" ? null : Number(result);
|
||||
return NextResponse.json(returValue, { status: 200 });
|
||||
}
|
||||
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
@@ -51,7 +52,7 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(action === "list"){
|
||||
const body = await req.json().catch(() => null);
|
||||
const body: ProjectListRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
@@ -133,6 +134,20 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
|
||||
if(action === "main-template"){
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.patch(`/project/main-template`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if(slug.length === 1){
|
||||
const body = await req.json().catch(() => null);
|
||||
|
||||
@@ -172,4 +187,4 @@ export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
42
src/app/api/reserve/[[...slug]]/route.ts
Normal file
42
src/app/api/reserve/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {ListReserve} from "@/types/list";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "sid" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListReserve[]>(`/reserve/${slug[1]}/sid/${slug[2]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "user" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListReserve[]>(`/reserve/${slug[1]}/user/${slug[2]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ message: "요청 바디가 없습니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const contactApi = await createContactApi();
|
||||
const result = await contactApi.put<ListReserve>(`/reserve`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
23
src/app/api/result-code/[[...slug]]/route.ts
Normal file
23
src/app/api/result-code/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(slug.length === 1){
|
||||
const result = await contactApi.get<ResultCode[]>(`/result-code/${slug[0]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {RoleInfo} from "@/types/role";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import {RouteContext} from "@/types/common";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
@@ -19,4 +19,4 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createContactApi } from "@/lib/server-api";
|
||||
import {UserInfo, UserUploadResponse} from "@/types/user";
|
||||
import {DataVerification, RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createContactApi } from "@/lib/http-server";
|
||||
import type { UserInfo } from "@/types/user";
|
||||
import type { DataVerification, ExcelUploadResult } from "@kri/common";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
@@ -25,16 +26,6 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "cmpn"){
|
||||
const result = await contactApi.get<string[]>("/user/cmpn");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "outsource"){
|
||||
const result = await contactApi.get<UserInfo[]>("/user/outsource");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "fieldwork"){
|
||||
const result = await contactApi.get<UserInfo[]>("/user/fieldwork");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
@@ -63,7 +54,7 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "excel") {
|
||||
if (action === "excel-upload") {
|
||||
const formData = await req.formData();
|
||||
const file = formData.get("file") as File | null;
|
||||
|
||||
@@ -77,8 +68,8 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
const backendForm = new FormData();
|
||||
backendForm.append("file", file, file.name);
|
||||
|
||||
const result = await contactApi.postForm<UserUploadResponse>(
|
||||
"/user/excel",
|
||||
const result = await contactApi.postForm<ExcelUploadResult>(
|
||||
"/user/excel/upload",
|
||||
backendForm
|
||||
);
|
||||
|
||||
|
||||
@@ -4,189 +4,158 @@
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
/* --content-font-size 배율 기반 font-size 스케일 (기본 text-* 유틸을 그대로 대체) */
|
||||
--text-xs: calc(var(--content-font-size) * 0.75);
|
||||
--text-sm: calc(var(--content-font-size) * 0.875);
|
||||
--text-base: var(--content-font-size);
|
||||
--text-lg: calc(var(--content-font-size) * 1.125);
|
||||
--text-xl: calc(var(--content-font-size) * 1.25);
|
||||
--text-2xl: calc(var(--content-font-size) * 1.5);
|
||||
--text-3xl: calc(var(--content-font-size) * 1.875);
|
||||
--text-4xl: calc(var(--content-font-size) * 2.25);
|
||||
--text-5xl: calc(var(--content-font-size) * 3);
|
||||
--text-6xl: calc(var(--content-font-size) * 3.75);
|
||||
--text-7xl: calc(var(--content-font-size) * 4.5);
|
||||
--text-8xl: calc(var(--content-font-size) * 6);
|
||||
--text-9xl: calc(var(--content-font-size) * 8);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
--content-font-size: 14px;
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.33 0.07 255);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.87 0.18 95);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
--content-font-size: 14px;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.55 0.09 255);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.8 0.17 95);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
/* 배율별 유틸 클래스 */
|
||||
.content-text-xs {
|
||||
font-size: calc(var(--content-font-size) * 0.75);
|
||||
.bg-excel {
|
||||
background-color: #217346;
|
||||
}
|
||||
.bg-excel:hover {
|
||||
background-color: #185c37;
|
||||
}
|
||||
|
||||
.content-text-sm {
|
||||
font-size: calc(var(--content-font-size) * 0.875);
|
||||
.bg-blue {
|
||||
background-color: var(--color-blue-600);
|
||||
}
|
||||
.bg-blue:hover {
|
||||
background-color: var(--color-blue-700);
|
||||
}
|
||||
|
||||
.content-text-base {
|
||||
font-size: var(--content-font-size);
|
||||
}
|
||||
|
||||
.content-text-lg {
|
||||
font-size: calc(var(--content-font-size) * 1.125);
|
||||
}
|
||||
|
||||
.content-text-xl {
|
||||
font-size: calc(var(--content-font-size) * 1.25);
|
||||
}
|
||||
|
||||
.content-text-2xl {
|
||||
font-size: calc(var(--content-font-size) * 1.5);
|
||||
}
|
||||
|
||||
.content-text-3xl {
|
||||
font-size: calc(var(--content-font-size) * 1.875);
|
||||
}
|
||||
|
||||
.content-text-4xl {
|
||||
font-size: calc(var(--content-font-size) * 2.25);
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.placeholder-content-text-xs::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 0.75);
|
||||
}
|
||||
|
||||
.placeholder-content-text-sm::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 0.875);
|
||||
}
|
||||
|
||||
.placeholder-content-text-base::placeholder {
|
||||
font-size: var(--content-font-size);
|
||||
}
|
||||
|
||||
.placeholder-content-text-lg::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.125);
|
||||
}
|
||||
|
||||
.placeholder-content-text-xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.25);
|
||||
}
|
||||
|
||||
.placeholder-content-text-2xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.5);
|
||||
}
|
||||
|
||||
.placeholder-content-text-3xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.875);
|
||||
}
|
||||
|
||||
.placeholder-content-text-4xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 2.25);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* [제거됨] .content-text-* / .placeholder-content-text-*
|
||||
* --font-size-* 를 @theme inline 에 등록했기 때문에
|
||||
* 기본 text-xs ~ text-4xl 유틸이 이미 --content-font-size 배율을 반영합니다.
|
||||
* placeholder 스타일도 Tailwind 기본 placeholder: variant로 대체 가능합니다.
|
||||
* 예) placeholder-content-text-sm -> placeholder:text-sm
|
||||
*/
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
/*************************TipTap 이미지 Resize Node*******************************/
|
||||
|
||||
@@ -25,9 +25,9 @@ const RootLayout = ({ children }: { children: React.ReactNode}) => {
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
<AppProvider>{children}</AppProvider>
|
||||
<Toaster />
|
||||
</body>
|
||||
<AppProvider>{children}</AppProvider>
|
||||
<Toaster />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
9
src/app/not-found.tsx
Normal file
9
src/app/not-found.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import ErrorPage from "@/components/external/Error";
|
||||
|
||||
const NotFound = () => {
|
||||
return (
|
||||
<ErrorPage code="404" />
|
||||
)
|
||||
}
|
||||
|
||||
export default NotFound
|
||||
87
src/components/app-shell/AppHeader.tsx
Normal file
87
src/components/app-shell/AppHeader.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import { LogOut, ZoomIn, ZoomOut } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { KriHeader } from "@/components/layout/KriHeader";
|
||||
import type { TopMenuItem } from "@/config/menu.types";
|
||||
import type { LoginUser } from "@kri/common";
|
||||
|
||||
interface AppHeaderProps {
|
||||
isMain: boolean;
|
||||
menuOpen: boolean;
|
||||
activeTopId: string;
|
||||
topMenus: TopMenuItem[];
|
||||
isViewProjectTitle: boolean;
|
||||
projectName?: string;
|
||||
userInfo?: LoginUser;
|
||||
fontSize: number;
|
||||
onToggleMenu: () => void;
|
||||
onNavigate: (path: string) => void;
|
||||
decreaseFontSize: () => void;
|
||||
increaseFontSize: () => void;
|
||||
}
|
||||
|
||||
export function AppHeader({
|
||||
isMain,
|
||||
menuOpen,
|
||||
activeTopId,
|
||||
topMenus,
|
||||
isViewProjectTitle,
|
||||
projectName,
|
||||
userInfo,
|
||||
fontSize,
|
||||
onToggleMenu,
|
||||
onNavigate,
|
||||
decreaseFontSize,
|
||||
increaseFontSize,
|
||||
}: AppHeaderProps) {
|
||||
return (
|
||||
<KriHeader
|
||||
logo={
|
||||
<div className="flex h-10 w-20 items-center justify-center">
|
||||
<Image
|
||||
src="/kri_logo.png"
|
||||
alt="KRI 로고"
|
||||
width={120}
|
||||
height={40}
|
||||
className="object-contain"
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
homePath="/"
|
||||
menus={topMenus}
|
||||
activeMenuId={activeTopId}
|
||||
menuOpen={menuOpen}
|
||||
showMenuButton={!isMain}
|
||||
onToggleMenu={onToggleMenu}
|
||||
onNavigate={(path) => onNavigate(path)}
|
||||
className="border-gray-200 bg-white"
|
||||
innerClassName="h-16 px-4"
|
||||
center={
|
||||
isViewProjectTitle && projectName ? (
|
||||
<h1 className="ml-3 text-2xl font-bold">{projectName}</h1>
|
||||
) : null
|
||||
}
|
||||
right={
|
||||
<>
|
||||
<div className="flex items-center gap-1 border-r pr-4">
|
||||
<Button variant="ghost" size="icon" onClick={decreaseFontSize} title="폰트 작게">
|
||||
<ZoomOut className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="min-w-[3rem] text-center text-xs text-gray-500">{fontSize}px</span>
|
||||
<Button variant="ghost" size="icon" onClick={increaseFontSize} title="폰트 크게">
|
||||
<ZoomIn className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<span className="hidden text-sm text-gray-600 sm:inline">{userInfo?.userName || ""}</span>
|
||||
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
|
||||
<LogOut className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">로그아웃</span>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
227
src/components/app-shell/AppMainLayout.tsx
Normal file
227
src/components/app-shell/AppMainLayout.tsx
Normal file
@@ -0,0 +1,227 @@
|
||||
"use client";
|
||||
|
||||
import { ReactNode, useEffect, useMemo, useState } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { getCurrentPositionMeta } from "@kri/common/browser";
|
||||
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
||||
import { AppHeader } from "@/components/app-shell/AppHeader";
|
||||
import { AppSidebar } from "@/components/app-shell/AppSidebar";
|
||||
import { useFontSize } from "@/hooks/useFontSize";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data";
|
||||
import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { FONT_SIZE } from "@/const/commonConst";
|
||||
|
||||
type AppMainLayoutProps = {
|
||||
children: ReactNode;
|
||||
initialFontSize: number;
|
||||
};
|
||||
|
||||
type AccessControlledItem = {
|
||||
path?: string;
|
||||
accessRole: number[];
|
||||
children?: AccessControlledItem[];
|
||||
match?: (pathname: string) => boolean;
|
||||
};
|
||||
|
||||
function canAccess(accessRole: number[], userRole: number | undefined): boolean {
|
||||
return accessRole.length === 0 || (userRole !== undefined && accessRole.includes(userRole));
|
||||
}
|
||||
|
||||
function filterTopMenusByRole(menus: TopMenuItem[], userRole: number | undefined): TopMenuItem[] {
|
||||
return menus.filter((menu) => canAccess(menu.accessRole, userRole));
|
||||
}
|
||||
|
||||
function filterSubMenusByRole(children: SideSubMenuItem[] | undefined, userRole: number | undefined): SideSubMenuItem[] | undefined {
|
||||
const filtered = children?.filter((child) => canAccess(child.accessRole, userRole));
|
||||
return filtered?.length ? filtered : undefined;
|
||||
}
|
||||
|
||||
function filterSideMenusByRole(menus: SideMenuItem[], userRole: number | undefined): SideMenuItem[] {
|
||||
return menus.reduce<SideMenuItem[]>((acc, menu) => {
|
||||
if (!canAccess(menu.accessRole, userRole)) return acc;
|
||||
|
||||
const children = filterSubMenusByRole(menu.children, userRole);
|
||||
if (!menu.path && menu.children?.length && !children?.length) return acc;
|
||||
|
||||
acc.push({
|
||||
...menu,
|
||||
...(children ? { children } : { children: undefined }),
|
||||
});
|
||||
return acc;
|
||||
}, []);
|
||||
}
|
||||
|
||||
function pathMatches(item: AccessControlledItem, pathname: string): boolean {
|
||||
if (item.match?.(pathname)) return true;
|
||||
return Boolean(item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`)));
|
||||
}
|
||||
|
||||
function findSideAccessChain(pathname: string, menus: SideMenuItem[]): AccessControlledItem[] | null {
|
||||
const matches: AccessControlledItem[][] = [];
|
||||
|
||||
menus.forEach((menu) => {
|
||||
if (menu.path && pathMatches(menu, pathname)) {
|
||||
matches.push([menu]);
|
||||
}
|
||||
|
||||
menu.children?.forEach((child) => {
|
||||
if (pathMatches(child, pathname)) {
|
||||
matches.push([menu, child]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (!matches.length) return null;
|
||||
|
||||
return matches.sort((a, b) => {
|
||||
const aPath = a.at(-1)?.path ?? "";
|
||||
const bPath = b.at(-1)?.path ?? "";
|
||||
return bPath.length - aPath.length;
|
||||
})[0];
|
||||
}
|
||||
|
||||
function findTopAccessChain(pathname: string, menus: TopMenuItem[]): AccessControlledItem[] | null {
|
||||
const match = menus.find((menu) => pathMatches(menu, pathname));
|
||||
return match ? [match] : null;
|
||||
}
|
||||
|
||||
function findAccessChain(pathname: string): AccessControlledItem[] | null {
|
||||
return (
|
||||
findSideAccessChain(pathname, [...projectSideMenus, ...manageSideMenus]) ??
|
||||
findTopAccessChain(pathname, topMenus)
|
||||
);
|
||||
}
|
||||
|
||||
export default function AppMainLayout({ children, initialFontSize }: AppMainLayoutProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const mounted = useMounted();
|
||||
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject();
|
||||
const [menuOpen, setMenuOpen] = useState(true);
|
||||
const [fontSize, setFontSize] = useFontSize(initialFontSize, { hydrateFromCookie: false });
|
||||
const userRole = auth.user?.userRole;
|
||||
|
||||
const isMain = pathname === "/";
|
||||
const isProjectMenu = !pathname.startsWith("/manage");
|
||||
const isViewProjectTitle = !isMain && isProjectMenu && !pathname.startsWith("/project/info");
|
||||
const visibleTopMenus = useMemo(() => filterTopMenusByRole(topMenus, userRole), [userRole]);
|
||||
const visibleProjectSideMenus = useMemo(() => filterSideMenusByRole(projectSideMenus, userRole), [userRole]);
|
||||
const visibleManageSideMenus = useMemo(() => filterSideMenusByRole(manageSideMenus, userRole), [userRole]);
|
||||
const activeTop = visibleTopMenus.find((menu) => menu.match?.(pathname)) ?? visibleTopMenus[0] ?? topMenus[0];
|
||||
const sideMenus = isProjectMenu ? visibleProjectSideMenus : visibleManageSideMenus;
|
||||
const hasRouteAccess = useMemo(() => {
|
||||
if (!auth.user) return true;
|
||||
|
||||
const accessChain = findAccessChain(pathname);
|
||||
if (!accessChain) return true;
|
||||
|
||||
return accessChain.every((item) => canAccess(item.accessRole, userRole));
|
||||
}, [auth.user, pathname, userRole]);
|
||||
|
||||
const [openMenus, setOpenMenus] = useState<Record<string, boolean>>(() => {
|
||||
const initial: Record<string, boolean> = {};
|
||||
|
||||
sideMenus.forEach((item) => {
|
||||
if (item.children?.some((child) => pathname === child.path || pathname.startsWith(`${child.path}/`))) {
|
||||
initial[item.id] = true;
|
||||
}
|
||||
});
|
||||
|
||||
return initial;
|
||||
});
|
||||
|
||||
const movePage = (path: string) => {
|
||||
router.push(path);
|
||||
};
|
||||
|
||||
const decreaseFontSize = () => {
|
||||
setFontSize(Math.max(FONT_SIZE.MIN, fontSize - 2));
|
||||
};
|
||||
|
||||
const increaseFontSize = () => {
|
||||
setFontSize(Math.min(FONT_SIZE.MAX, fontSize + 2));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
|
||||
if (!auth.user) {
|
||||
router.replace("/logout");
|
||||
}
|
||||
}, [auth.user, mounted, router]);
|
||||
|
||||
// 컨택결과 저장 시점에 GPS 권한 프롬프트가 뜨면 저장이 지연/누락될 수 있어,
|
||||
// 로그인 후 메인 진입 시점에 미리 권한을 받아 위치를 캐시해둔다(결과는 사용하지 않음).
|
||||
useEffect(() => {
|
||||
if (!mounted || !auth.user) return;
|
||||
void getCurrentPositionMeta();
|
||||
}, [mounted, auth.user]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted || !auth.user || hasRouteAccess) return;
|
||||
|
||||
alert("접근 권한이 없습니다.");
|
||||
router.replace("/");
|
||||
}, [auth.user, hasRouteAccess, mounted, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSelectedProjectHydrated) return;
|
||||
if (!hasRouteAccess) return;
|
||||
|
||||
if (!isMain && isProjectMenu && !selectedProject) {
|
||||
alert("선택된 프로젝트가 없습니다.");
|
||||
router.replace("/");
|
||||
}
|
||||
}, [hasRouteAccess, isMain, isProjectMenu, isSelectedProjectHydrated, router, selectedProject]);
|
||||
|
||||
if (mounted && auth.user && !hasRouteAccess) return null;
|
||||
|
||||
return (
|
||||
<KriMainLayout
|
||||
fullHeight={false}
|
||||
className={cn("bg-gray-50", "h-screen overflow-hidden")}
|
||||
bodyClassName={cn(!isMain && "min-h-0")}
|
||||
mainClassName={cn("p-4", "min-h-0")}
|
||||
mainStyle={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }}
|
||||
sidebarOpen={!isMain && menuOpen}
|
||||
onSidebarOpenChange={setMenuOpen}
|
||||
header={
|
||||
<AppHeader
|
||||
isMain={isMain}
|
||||
menuOpen={menuOpen}
|
||||
activeTopId={activeTop.id}
|
||||
topMenus={visibleTopMenus}
|
||||
isViewProjectTitle={isViewProjectTitle}
|
||||
projectName={selectedProject?.prjctName}
|
||||
userInfo={auth.user ?? undefined}
|
||||
fontSize={fontSize}
|
||||
onToggleMenu={() => setMenuOpen((prev) => !prev)}
|
||||
onNavigate={movePage}
|
||||
decreaseFontSize={decreaseFontSize}
|
||||
increaseFontSize={increaseFontSize}
|
||||
/>
|
||||
}
|
||||
sidebar={
|
||||
!isMain ? (
|
||||
<AppSidebar
|
||||
isProjectMenu={isProjectMenu}
|
||||
sideMenus={sideMenus}
|
||||
isOpen={menuOpen}
|
||||
pathname={pathname}
|
||||
openMenus={openMenus}
|
||||
onOpenMenusChange={setOpenMenus}
|
||||
onNavigate={movePage}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</KriMainLayout>
|
||||
);
|
||||
}
|
||||
10
src/components/app-shell/AppPageTitle.tsx
Normal file
10
src/components/app-shell/AppPageTitle.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { KriPageTitle } from "@/components/layout/KriPageTitle";
|
||||
|
||||
interface AppPageTitleProps {
|
||||
titleText: string;
|
||||
}
|
||||
|
||||
export default function AppPageTitle({ titleText }: AppPageTitleProps) {
|
||||
return <KriPageTitle title={titleText} />;
|
||||
}
|
||||
|
||||
50
src/components/app-shell/AppSidebar.tsx
Normal file
50
src/components/app-shell/AppSidebar.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import { KriSidebar } from "@/components/layout/KriSidebar";
|
||||
import { AppSidebarProjectSearch } from "@/components/app-shell/AppSidebarProjectSearch";
|
||||
import type { SideMenuItem } from "@/config/menu.types";
|
||||
|
||||
interface AppSidebarProps {
|
||||
isProjectMenu: boolean;
|
||||
sideMenus: SideMenuItem[];
|
||||
isOpen: boolean;
|
||||
pathname: string;
|
||||
openMenus: Record<string, boolean>;
|
||||
onOpenMenusChange: (openMenus: Record<string, boolean>) => void;
|
||||
onNavigate: (path: string) => void;
|
||||
}
|
||||
|
||||
export function AppSidebar({
|
||||
isProjectMenu,
|
||||
sideMenus,
|
||||
isOpen,
|
||||
pathname,
|
||||
openMenus,
|
||||
onOpenMenusChange,
|
||||
onNavigate,
|
||||
}: AppSidebarProps) {
|
||||
const openItemIds = Object.entries(openMenus)
|
||||
.filter(([, open]) => open)
|
||||
.map(([id]) => id);
|
||||
|
||||
return (
|
||||
<KriSidebar
|
||||
items={sideMenus}
|
||||
isOpen={isOpen}
|
||||
pathname={pathname}
|
||||
header={isProjectMenu ? <AppSidebarProjectSearch /> : null}
|
||||
openItemIds={openItemIds}
|
||||
onOpenItemIdsChange={(ids) => {
|
||||
onOpenMenusChange(
|
||||
sideMenus.reduce<Record<string, boolean>>((acc, item) => {
|
||||
acc[item.id] = ids.includes(item.id);
|
||||
return acc;
|
||||
}, {}),
|
||||
);
|
||||
}}
|
||||
onNavigate={(path) => onNavigate(path)}
|
||||
className="border-gray-200 bg-white"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,45 +1,32 @@
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {ProjectInfo} from "@/types/project";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {useEffect, useState} from "react";
|
||||
import { useDebouncedValue, useMounted } from "@kri/common/hooks";
|
||||
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 = () =>{
|
||||
export const AppSidebarProjectSearch = () =>{
|
||||
const mounted = useMounted();
|
||||
|
||||
const { selectedProject, setSelectedProject } = useSelectedProject();
|
||||
const [searchKeyword, setSearchKeyword] = useState(selectedProject?.prjctCd || "");
|
||||
|
||||
const [searchKeyword, setSearchKeyword] = useState("");
|
||||
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(() => {
|
||||
const data = topQuery.data ?? [];
|
||||
return selectedProject ? [selectedProject, ...data] : data;
|
||||
}, [topQuery.data, selectedProject]);
|
||||
|
||||
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
|
||||
@@ -52,7 +39,6 @@ export const SidebarProjectSearch = () =>{
|
||||
searchMode="inputOnly"
|
||||
onSearchValueChange={setSearchKeyword}
|
||||
placeholder="프로젝트 검색..."
|
||||
spanClassName="content-text-sm"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
preventDeselect
|
||||
@@ -62,4 +48,4 @@ export const SidebarProjectSearch = () =>{
|
||||
getValue={(item) => String(item.prjctIdx)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
15
src/components/app-shell/LoadingOverlayAdapter.tsx
Normal file
15
src/components/app-shell/LoadingOverlayAdapter.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import { KriLoadingOverlay, type KriLoadingOverlayProps } from "@/components/common/KriLoadingOverlay";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export type LoadingOverlayAdapterProps = Omit<KriLoadingOverlayProps, "open"> & {
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
export function LoadingOverlayAdapter({ force = false, ...props }: LoadingOverlayAdapterProps) {
|
||||
const open = useAtomValue(loadingAtom);
|
||||
|
||||
return <KriLoadingOverlay open={force || open} {...props} />;
|
||||
}
|
||||
6
src/components/app-shell/index.ts
Normal file
6
src/components/app-shell/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export { AppHeader } from "./AppHeader";
|
||||
export { AppSidebar } from "./AppSidebar";
|
||||
export { LoadingOverlayAdapter } from "./LoadingOverlayAdapter";
|
||||
export { default as AppMainLayout } from "./AppMainLayout";
|
||||
export { default as AppPageTitle } from "./AppPageTitle";
|
||||
|
||||
101
src/components/assign/AssignTargetList.tsx
Normal file
101
src/components/assign/AssignTargetList.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import { useCmpnListQuery } from '@/query/cmpn'
|
||||
import { useFieldworkUsersQuery } from '@/query/user'
|
||||
import { useAssignedCmpnIdsQuery, useAssignedFieldworkIdsQuery } from '@/query/project'
|
||||
import { ListHeaderAssignConst } from '@/const/listConst'
|
||||
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
|
||||
import type { ListHeaderAssignType } from '@/types/list'
|
||||
|
||||
export type AssignTargetListProps = {
|
||||
prjctIdx: number
|
||||
enabled: boolean
|
||||
assignType: ListHeaderAssignType
|
||||
selectedId?: string
|
||||
onSelect: (id: string) => void
|
||||
}
|
||||
|
||||
export type AssignTargetRow = {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export type UseAssignTargetRowsArgs = {
|
||||
prjctIdx: number
|
||||
enabled: boolean
|
||||
assignType: ListHeaderAssignType
|
||||
}
|
||||
|
||||
export function useAssignTargetRows({ prjctIdx, enabled, assignType }: UseAssignTargetRowsArgs): AssignTargetRow[] {
|
||||
const isOutsource = assignType === ListHeaderAssignConst.OUTSOURCE
|
||||
|
||||
const assignedCmpnIdsQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled && isOutsource)
|
||||
const cmpnListQuery = useCmpnListQuery()
|
||||
|
||||
const assignedFieldworkIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled && !isOutsource)
|
||||
const fieldworkUsersQuery = useFieldworkUsersQuery(enabled && !isOutsource)
|
||||
|
||||
return useMemo<AssignTargetRow[]>(() => {
|
||||
if (isOutsource) {
|
||||
const assignedIds = new Set(assignedCmpnIdsQuery.data ?? [])
|
||||
return (cmpnListQuery.data ?? [])
|
||||
.filter((cmpn) => assignedIds.has(cmpn.cmpnId))
|
||||
.map((cmpn) => ({ id: cmpn.cmpnId, name: cmpn.cmpnAlias || cmpn.cmpnId }))
|
||||
}
|
||||
|
||||
const targetRole =
|
||||
assignType === ListHeaderAssignConst.CONTACT_INTERVIEWER ? CONTACT_INTERVIEWER_ROLE : FIELD_INTERVIEWER_ROLE
|
||||
const assignedIds = new Set(assignedFieldworkIdsQuery.data ?? [])
|
||||
|
||||
return (fieldworkUsersQuery.data ?? [])
|
||||
.filter((user) => assignedIds.has(user.userId) && user.userRole === targetRole)
|
||||
.map((user) => ({ id: user.userId, name: user.userName }))
|
||||
}, [
|
||||
assignType,
|
||||
isOutsource,
|
||||
assignedCmpnIdsQuery.data,
|
||||
cmpnListQuery.data,
|
||||
assignedFieldworkIdsQuery.data,
|
||||
fieldworkUsersQuery.data,
|
||||
])
|
||||
}
|
||||
|
||||
export function AssignTargetList({ prjctIdx, enabled, assignType, selectedId, onSelect }: AssignTargetListProps) {
|
||||
const rows = useAssignTargetRows({ prjctIdx, enabled, assignType })
|
||||
|
||||
return (
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||
<div className="h-[78vh] overflow-y-auto">
|
||||
<table className="w-full table-fixed">
|
||||
<colgroup>
|
||||
<col className="w-28" />
|
||||
<col />
|
||||
</colgroup>
|
||||
<thead className="bg-primary text-white sticky top-0">
|
||||
<tr>
|
||||
<th className="p-2 text-left text-base font-medium">ID</th>
|
||||
<th className="p-2 text-left text-base font-medium">이름</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
selectedId === row.id ? 'bg-accent' : ''
|
||||
}`}
|
||||
onClick={() => onSelect(row.id)}
|
||||
>
|
||||
<td className="p-2 text-base truncate">{row.id}</td>
|
||||
<td className="p-2 text-base truncate">{row.name}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default AssignTargetList
|
||||
147
src/components/chart/BaseEChart.tsx
Normal file
147
src/components/chart/BaseEChart.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import type { ComponentType, CSSProperties } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { CHART_HEIGHTS } from './chart.config'
|
||||
import { useResizeKey } from './useResizeKey'
|
||||
|
||||
type EChartsSeries = NonNullable<EChartsOption['series']>
|
||||
type ReactEChartsProps = {
|
||||
option: EChartsOption
|
||||
className?: string
|
||||
style?: CSSProperties
|
||||
notMerge?: boolean
|
||||
lazyUpdate?: boolean
|
||||
onEvents?: Record<string, (params: unknown) => void>
|
||||
}
|
||||
|
||||
export type BaseEChartProps = {
|
||||
option: EChartsOption
|
||||
height?: number | string
|
||||
className?: string
|
||||
contentClassName?: string
|
||||
chartClassName?: string
|
||||
style?: CSSProperties
|
||||
contentStyle?: CSSProperties
|
||||
chartStyle?: CSSProperties
|
||||
notMerge?: boolean
|
||||
lazyUpdate?: boolean
|
||||
onEvents?: Record<string, (params: unknown) => void>
|
||||
resizeDebounceMs?: number
|
||||
normalizeValues?: boolean
|
||||
decimalPlaces?: number
|
||||
}
|
||||
|
||||
const roundNumber = (value: number, decimalPlaces: number) => {
|
||||
const factor = 10 ** decimalPlaces
|
||||
return Math.round((value + Number.EPSILON) * factor) / factor
|
||||
}
|
||||
|
||||
const normalizeDataValue = (value: unknown, decimalPlaces: number): unknown => {
|
||||
if (typeof value === 'number') {
|
||||
return roundNumber(value, decimalPlaces)
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => normalizeDataValue(item, decimalPlaces))
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object' && 'value' in value) {
|
||||
const dataItem = value as Record<string, unknown>
|
||||
|
||||
return {
|
||||
...dataItem,
|
||||
value: normalizeDataValue(dataItem.value, decimalPlaces),
|
||||
}
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const normalizeSeries = (
|
||||
series: EChartsOption['series'] | undefined,
|
||||
decimalPlaces: number,
|
||||
): EChartsOption['series'] => {
|
||||
if (!series) return series
|
||||
|
||||
const normalizeOne = (seriesOption: EChartsSeries): EChartsSeries => {
|
||||
const candidate = seriesOption as Record<string, unknown>
|
||||
const data = candidate.data
|
||||
|
||||
if (!Array.isArray(data)) {
|
||||
return seriesOption
|
||||
}
|
||||
|
||||
return {
|
||||
...candidate,
|
||||
data: data.map((value) => normalizeDataValue(value, decimalPlaces)),
|
||||
} as EChartsSeries
|
||||
}
|
||||
|
||||
return (Array.isArray(series) ? series.map((item) => normalizeOne(item as EChartsSeries)) : normalizeOne(series)) as EChartsOption['series']
|
||||
}
|
||||
|
||||
export function BaseEChart({
|
||||
option,
|
||||
height = CHART_HEIGHTS.DEFAULT,
|
||||
className,
|
||||
contentClassName,
|
||||
chartClassName,
|
||||
style,
|
||||
contentStyle,
|
||||
chartStyle,
|
||||
notMerge = true,
|
||||
lazyUpdate = false,
|
||||
onEvents,
|
||||
resizeDebounceMs = 150,
|
||||
normalizeValues = true,
|
||||
decimalPlaces = 2,
|
||||
}: BaseEChartProps) {
|
||||
const resizeKey = useResizeKey(resizeDebounceMs)
|
||||
const [ReactECharts, setReactECharts] = useState<ComponentType<ReactEChartsProps> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
void import('echarts-for-react').then((module) => {
|
||||
if (!cancelled) {
|
||||
setReactECharts(() => module.default as ComponentType<ReactEChartsProps>)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const normalizedOption = useMemo<EChartsOption>(() => {
|
||||
if (!normalizeValues) return option
|
||||
|
||||
return {
|
||||
...option,
|
||||
series: normalizeSeries(option.series, decimalPlaces),
|
||||
}
|
||||
}, [decimalPlaces, normalizeValues, option])
|
||||
|
||||
return (
|
||||
<div className={className} style={{ display: 'flex', flexDirection: 'column', height, ...style }}>
|
||||
<div className={contentClassName} style={{ flex: 1, minHeight: 0, ...contentStyle }}>
|
||||
{ReactECharts ? (
|
||||
<ReactECharts
|
||||
key={resizeKey}
|
||||
option={normalizedOption}
|
||||
className={chartClassName}
|
||||
style={{ width: '100%', height: '100%', ...chartStyle }}
|
||||
notMerge={notMerge}
|
||||
lazyUpdate={lazyUpdate}
|
||||
onEvents={onEvents}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default BaseEChart
|
||||
59
src/components/chart/KriBarChart.tsx
Normal file
59
src/components/chart/KriBarChart.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriCartesianChartProps } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriBarChartProps = KriCartesianChartProps & {
|
||||
isHorizontal?: boolean
|
||||
barWidth?: number | string
|
||||
barMaxWidth?: number | string
|
||||
}
|
||||
|
||||
export function KriBarChart({
|
||||
categories,
|
||||
series,
|
||||
isHorizontal = false,
|
||||
barWidth,
|
||||
barMaxWidth,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriBarChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const categoryAxis = { type: 'category', data: categories }
|
||||
const valueAxis = { type: 'value' }
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption(isHorizontal ? valueAxis : categoryAxis, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption(isHorizontal ? categoryAxis : valueAxis, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'bar',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
...(barWidth ? { barWidth } : {}),
|
||||
...(barMaxWidth ? { barMaxWidth } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [barMaxWidth, barWidth, categories, grid, isHorizontal, legend, option, series, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriBarChart
|
||||
|
||||
58
src/components/chart/KriLineChart.tsx
Normal file
58
src/components/chart/KriLineChart.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriCartesianChartProps } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriLineChartProps = KriCartesianChartProps & {
|
||||
smooth?: boolean
|
||||
area?: boolean
|
||||
showSymbol?: boolean
|
||||
}
|
||||
|
||||
export function KriLineChart({
|
||||
categories,
|
||||
series,
|
||||
smooth = false,
|
||||
area = false,
|
||||
showSymbol = true,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriLineChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'axis' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption({ type: 'category', data: categories, boundaryGap: false }, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption({ type: 'value' }, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'line',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
smooth,
|
||||
showSymbol,
|
||||
...(area ? { areaStyle: {} } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [area, categories, grid, legend, option, series, showSymbol, smooth, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriLineChart
|
||||
|
||||
50
src/components/chart/KriPieChart.tsx
Normal file
50
src/components/chart/KriPieChart.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriChartBaseProps, KriPieChartSeries } from './chart.types'
|
||||
import { defaultLegend, mergeChartOptions } from './chart.utils'
|
||||
|
||||
export type KriPieChartProps = KriChartBaseProps & {
|
||||
series: KriPieChartSeries[]
|
||||
}
|
||||
|
||||
const getPieCenter = (index: number, count: number) => {
|
||||
if (count === 1) return ['50%', '55%']
|
||||
|
||||
return [`${((index + 0.5) / count) * 100}%`, '55%']
|
||||
}
|
||||
|
||||
export function KriPieChart({
|
||||
series,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriPieChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'item' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
series: series.map((item, index) => ({
|
||||
type: 'pie',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
radius: item.radius ?? (series.length > 1 ? ['32%', '52%'] : '65%'),
|
||||
center: item.center ?? getPieCenter(index, series.length),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [legend, option, series, title, tooltip])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriPieChart
|
||||
|
||||
55
src/components/chart/KriRadarChart.tsx
Normal file
55
src/components/chart/KriRadarChart.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriChartBaseProps, KriRadarChartSeries, KriRadarDataItem, KriRadarIndicator } from './chart.types'
|
||||
import { defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriRadarChartProps = KriChartBaseProps & {
|
||||
indicators: KriRadarIndicator[]
|
||||
series: KriRadarChartSeries[]
|
||||
radar?: EChartsOption['radar']
|
||||
}
|
||||
|
||||
const normalizeRadarData = (series: KriRadarChartSeries): KriRadarDataItem[] => {
|
||||
if (series.data.every((value) => typeof value === 'number')) {
|
||||
return [{ name: series.name, value: series.data as number[] }]
|
||||
}
|
||||
|
||||
return series.data as KriRadarDataItem[]
|
||||
}
|
||||
|
||||
export function KriRadarChart({
|
||||
indicators,
|
||||
series,
|
||||
radar,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriRadarChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'item' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
radar: mergeObjectOption({ indicator: indicators }, radar) as EChartsOption['radar'],
|
||||
series: series.map((item) => ({
|
||||
type: 'radar',
|
||||
name: item.name,
|
||||
data: normalizeRadarData(item),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [indicators, legend, option, radar, series, title, tooltip])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriRadarChart
|
||||
|
||||
55
src/components/chart/KriScatterChart.tsx
Normal file
55
src/components/chart/KriScatterChart.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriChartBaseProps, KriScatterChartSeries } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriScatterChartProps = KriChartBaseProps & {
|
||||
series: KriScatterChartSeries[]
|
||||
grid?: EChartsOption['grid']
|
||||
xAxis?: EChartsOption['xAxis']
|
||||
yAxis?: EChartsOption['yAxis']
|
||||
symbolSize?: number | ((value: unknown, params: unknown) => number)
|
||||
}
|
||||
|
||||
export function KriScatterChart({
|
||||
series,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
symbolSize,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriScatterChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'item' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption({ type: 'value' }, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption({ type: 'value' }, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'scatter',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
...(symbolSize ? { symbolSize } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [grid, legend, option, series, symbolSize, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriScatterChart
|
||||
|
||||
62
src/components/chart/KriStackedBarChart.tsx
Normal file
62
src/components/chart/KriStackedBarChart.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriCartesianChartProps } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriStackedBarChartProps = KriCartesianChartProps & {
|
||||
isHorizontal?: boolean
|
||||
stackName?: string
|
||||
barWidth?: number | string
|
||||
barMaxWidth?: number | string
|
||||
}
|
||||
|
||||
export function KriStackedBarChart({
|
||||
categories,
|
||||
series,
|
||||
isHorizontal = false,
|
||||
stackName = 'total',
|
||||
barWidth,
|
||||
barMaxWidth,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriStackedBarChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const categoryAxis = { type: 'category', data: categories }
|
||||
const valueAxis = { type: 'value' }
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption(isHorizontal ? valueAxis : categoryAxis, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption(isHorizontal ? categoryAxis : valueAxis, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'bar',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
stack: item.stack ?? stackName,
|
||||
...(barWidth ? { barWidth } : {}),
|
||||
...(barMaxWidth ? { barMaxWidth } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [barMaxWidth, barWidth, categories, grid, isHorizontal, legend, option, series, stackName, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriStackedBarChart
|
||||
|
||||
6
src/components/chart/chart.config.ts
Normal file
6
src/components/chart/chart.config.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export const CHART_HEIGHTS = {
|
||||
DEFAULT: 320,
|
||||
SMALL: 240,
|
||||
LARGE: 420,
|
||||
} as const
|
||||
|
||||
71
src/components/chart/chart.types.ts
Normal file
71
src/components/chart/chart.types.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import type { BaseEChartProps } from './BaseEChart'
|
||||
|
||||
export type KriChartBaseProps = Omit<BaseEChartProps, 'option'> & {
|
||||
option?: EChartsOption
|
||||
title?: EChartsOption['title']
|
||||
legend?: EChartsOption['legend']
|
||||
tooltip?: EChartsOption['tooltip']
|
||||
}
|
||||
|
||||
export type KriCategoryValue = string | number
|
||||
|
||||
export type KriCategoryChartSeries = {
|
||||
name: string
|
||||
data: unknown[]
|
||||
color?: string
|
||||
stack?: string
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type KriCartesianChartProps = KriChartBaseProps & {
|
||||
categories: KriCategoryValue[]
|
||||
series: KriCategoryChartSeries[]
|
||||
grid?: EChartsOption['grid']
|
||||
xAxis?: EChartsOption['xAxis']
|
||||
yAxis?: EChartsOption['yAxis']
|
||||
}
|
||||
|
||||
export type KriNamedChartData = {
|
||||
name: string
|
||||
value: unknown
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type KriPieChartSeries = {
|
||||
name?: string
|
||||
data: KriNamedChartData[]
|
||||
radius?: string | number | Array<string | number>
|
||||
center?: Array<string | number>
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type KriRadarIndicator = {
|
||||
name: string
|
||||
max?: number
|
||||
min?: number
|
||||
color?: string
|
||||
}
|
||||
|
||||
export type KriRadarDataItem = {
|
||||
name?: string
|
||||
value: number[]
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type KriRadarChartSeries = {
|
||||
name: string
|
||||
data: number[] | KriRadarDataItem[]
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type KriScatterDataItem = [number, number] | [string, number] | KriNamedChartData
|
||||
|
||||
export type KriScatterChartSeries = {
|
||||
name: string
|
||||
data: KriScatterDataItem[]
|
||||
color?: string
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
34
src/components/chart/chart.utils.ts
Normal file
34
src/components/chart/chart.utils.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
export const mergeChartOptions = (generated: EChartsOption, option?: EChartsOption): EChartsOption => {
|
||||
if (!option) return generated
|
||||
|
||||
return {
|
||||
...generated,
|
||||
...option,
|
||||
series: option.series ?? generated.series,
|
||||
}
|
||||
}
|
||||
|
||||
export const mergeObjectOption = <TOption>(defaults: Record<string, unknown>, option?: TOption): TOption | Record<string, unknown> => {
|
||||
if (!option) return defaults
|
||||
if (Array.isArray(option)) return option
|
||||
if (typeof option === 'object') return { ...defaults, ...(option as Record<string, unknown>) }
|
||||
|
||||
return option
|
||||
}
|
||||
|
||||
export const defaultLegend = (seriesCount: number): EChartsOption['legend'] | undefined => {
|
||||
return seriesCount > 1 ? { top: 0 } : undefined
|
||||
}
|
||||
|
||||
export const defaultGrid = (seriesCount: number): EChartsOption['grid'] => {
|
||||
return {
|
||||
top: seriesCount > 1 ? 44 : 24,
|
||||
right: 24,
|
||||
bottom: 24,
|
||||
left: 24,
|
||||
containLabel: true,
|
||||
}
|
||||
}
|
||||
|
||||
29
src/components/chart/index.ts
Normal file
29
src/components/chart/index.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export { BaseEChart, default } from './BaseEChart'
|
||||
export type { BaseEChartProps } from './BaseEChart'
|
||||
export { KriBarChart } from './KriBarChart'
|
||||
export type { KriBarChartProps } from './KriBarChart'
|
||||
export { KriLineChart } from './KriLineChart'
|
||||
export type { KriLineChartProps } from './KriLineChart'
|
||||
export { KriPieChart } from './KriPieChart'
|
||||
export type { KriPieChartProps } from './KriPieChart'
|
||||
export { KriRadarChart } from './KriRadarChart'
|
||||
export type { KriRadarChartProps } from './KriRadarChart'
|
||||
export { KriScatterChart } from './KriScatterChart'
|
||||
export type { KriScatterChartProps } from './KriScatterChart'
|
||||
export { KriStackedBarChart } from './KriStackedBarChart'
|
||||
export type { KriStackedBarChartProps } from './KriStackedBarChart'
|
||||
export { CHART_HEIGHTS } from './chart.config'
|
||||
export type {
|
||||
KriCartesianChartProps,
|
||||
KriCategoryChartSeries,
|
||||
KriCategoryValue,
|
||||
KriChartBaseProps,
|
||||
KriNamedChartData,
|
||||
KriPieChartSeries,
|
||||
KriRadarChartSeries,
|
||||
KriRadarDataItem,
|
||||
KriRadarIndicator,
|
||||
KriScatterChartSeries,
|
||||
KriScatterDataItem,
|
||||
} from './chart.types'
|
||||
export { useResizeKey } from './useResizeKey'
|
||||
31
src/components/chart/useResizeKey.ts
Normal file
31
src/components/chart/useResizeKey.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
export function useResizeKey(delay = 150) {
|
||||
const [resizeKey, setResizeKey] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return
|
||||
|
||||
let timer: number | undefined
|
||||
|
||||
const handleResize = () => {
|
||||
if (timer) window.clearTimeout(timer)
|
||||
|
||||
timer = window.setTimeout(() => {
|
||||
setResizeKey((key) => key + 1)
|
||||
}, delay)
|
||||
}
|
||||
|
||||
window.addEventListener('resize', handleResize)
|
||||
|
||||
return () => {
|
||||
if (timer) window.clearTimeout(timer)
|
||||
window.removeEventListener('resize', handleResize)
|
||||
}
|
||||
}, [delay])
|
||||
|
||||
return resizeKey
|
||||
}
|
||||
|
||||
@@ -2,15 +2,17 @@
|
||||
|
||||
import * as React from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {MultiSelect, MultiSelectRef} from '@/components/ui/multi-select'
|
||||
import type { MultiSelectOption } from '@/components/ui/multi-select'
|
||||
import { MultiSelect } from '@/components/common/multi-select'
|
||||
import type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
|
||||
|
||||
type BaseProps<T> = {
|
||||
export type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
|
||||
|
||||
export interface KriAutoCompleteBaseProps<T> {
|
||||
items: T[]
|
||||
searchable?: boolean
|
||||
searchMode?: "filter" | "inputOnly";
|
||||
defaultSearchValue?: string;
|
||||
onSearchValueChange?: (value: string) => void;
|
||||
searchMode?: 'filter' | 'inputOnly'
|
||||
defaultSearchValue?: string
|
||||
onSearchValueChange?: (value: string) => void
|
||||
placeholder?: string
|
||||
widthClassName?: string
|
||||
heightClassName?: string
|
||||
@@ -19,219 +21,185 @@ type BaseProps<T> = {
|
||||
className?: string
|
||||
getValue?: (item: T) => string
|
||||
getLabel?: (item: T) => string
|
||||
|
||||
/** ✅ 옵션: 원본 item을 option.info에 실어둘지 */
|
||||
withInfo?: boolean
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
type KriMultiSelectProps<T = unknown> = BaseProps<T> & {
|
||||
export interface KriMultiSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> {
|
||||
value: string[]
|
||||
onChange: (value: string[]) => void
|
||||
maxCount?: number
|
||||
maxSelected?: number
|
||||
hideSelectAll?: boolean
|
||||
|
||||
/** ✅ withInfo=true일 때만 의미 있게 쓰면 됨 */
|
||||
onItemsChange?: (items: T[]) => void
|
||||
onOptionsChange?: (options: MultiSelectOption<T>[]) => void
|
||||
}
|
||||
|
||||
function toOptions<T>(
|
||||
items: T[],
|
||||
getValue: ((item: T) => string) | undefined,
|
||||
getLabel: ((item: T) => string) | undefined,
|
||||
withInfo: boolean,
|
||||
): MultiSelectOption<T>[] {
|
||||
return items.map((item) => ({
|
||||
value: getValue ? getValue(item) : String(item),
|
||||
label: getLabel ? getLabel(item) : String(item),
|
||||
...(withInfo ? { info: item } : {}),
|
||||
}))
|
||||
}
|
||||
|
||||
export function KriMultiSelect<T = unknown>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = "filter",
|
||||
defaultSearchValue = "",
|
||||
onSearchValueChange,
|
||||
maxCount = 1,
|
||||
maxSelected,
|
||||
hideSelectAll = false,
|
||||
placeholder = 'Select options',
|
||||
widthClassName,
|
||||
heightClassName,
|
||||
spanClassName = "content-text-lg",
|
||||
badgeClassName = "content-text-lg",
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemsChange,
|
||||
onOptionsChange,
|
||||
}: KriMultiSelectProps<T>) {
|
||||
const msRef = React.useRef<MultiSelectRef>(null);
|
||||
|
||||
const extractValue = React.useCallback(
|
||||
(item: T) => (getValue ? getValue(item) : String(item)),
|
||||
[getValue]
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
maxCount = 1,
|
||||
maxSelected,
|
||||
hideSelectAll = false,
|
||||
placeholder = 'Select options',
|
||||
widthClassName,
|
||||
heightClassName,
|
||||
spanClassName = 'text-base',
|
||||
badgeClassName = 'text-base',
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemsChange,
|
||||
onOptionsChange,
|
||||
disabled,
|
||||
}: KriMultiSelectProps<T>) {
|
||||
const options = React.useMemo(
|
||||
() => toOptions(items, getValue, getLabel, withInfo),
|
||||
[getLabel, getValue, items, withInfo],
|
||||
)
|
||||
const extractLabel = React.useCallback(
|
||||
(item: T) => (getLabel ? getLabel(item) : String(item)),
|
||||
[getLabel]
|
||||
)
|
||||
|
||||
const options = React.useMemo<MultiSelectOption<T>[]>(() => {
|
||||
return items.map((item) => ({
|
||||
value: extractValue(item),
|
||||
label: extractLabel(item),
|
||||
...(withInfo ? { info: item } : {}), // ✅ 필요할 때만 info를 실음
|
||||
}))
|
||||
}, [items, extractValue, extractLabel, withInfo])
|
||||
|
||||
return (
|
||||
<div className={cn(widthClassName, heightClassName, "flex-none overflow-hidden")}>
|
||||
<MultiSelect<T>
|
||||
ref={msRef}
|
||||
options={options}
|
||||
defaultValue={value}
|
||||
onValueChange={onChange}
|
||||
onOptionChange={onOptionsChange}
|
||||
onInfoChange={onItemsChange}
|
||||
maxSelected={maxSelected}
|
||||
placeholder={placeholder}
|
||||
className={cn("bg-white content-text-lg", className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
maxCount={maxCount}
|
||||
hideSelectAll={hideSelectAll}
|
||||
autoSize
|
||||
singleLine
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
/>
|
||||
</div>
|
||||
<div className={cn('flex-none', widthClassName, heightClassName)}>
|
||||
<MultiSelect<T>
|
||||
options={options}
|
||||
defaultValue={value}
|
||||
onValueChange={onChange}
|
||||
onOptionChange={onOptionsChange}
|
||||
onInfoChange={onItemsChange}
|
||||
maxSelected={maxSelected}
|
||||
placeholder={placeholder}
|
||||
className={cn('bg-background text-base', !widthClassName && 'w-auto', className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
maxCount={maxCount}
|
||||
hideSelectAll={hideSelectAll}
|
||||
singleLine
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type KriSingleSelectProps<T = unknown> = BaseProps<T> & {
|
||||
export interface KriSingleSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
onItemChange?: (item: T | null) => void
|
||||
onOptionChange?: (option: MultiSelectOption<T> | null) => void
|
||||
preventDeselect?: boolean;
|
||||
hideOptionCheck?: boolean;
|
||||
|
||||
preventDeselect?: boolean
|
||||
hideOptionCheck?: boolean
|
||||
useClear?: boolean
|
||||
clearLabel?: string
|
||||
clearValue?: string
|
||||
|
||||
showSelectedTooltip?: boolean
|
||||
}
|
||||
|
||||
export function KriSingleSelect<T = unknown>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = "filter",
|
||||
defaultSearchValue = "",
|
||||
onSearchValueChange,
|
||||
placeholder = 'Select an option',
|
||||
heightClassName,
|
||||
widthClassName,
|
||||
spanClassName = "content-text-lg",
|
||||
badgeClassName = "content-text-lg",
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemChange,
|
||||
onOptionChange,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
showSelectedTooltip = false,
|
||||
useClear = false,
|
||||
clearLabel = "선택 해제",
|
||||
clearValue = "__CLEAR__",
|
||||
}: KriSingleSelectProps<T>) {
|
||||
const msRef = React.useRef<MultiSelectRef>(null);
|
||||
|
||||
const extractValue = React.useCallback(
|
||||
(item: T) => (getValue ? getValue(item) : String(item)),
|
||||
[getValue]
|
||||
)
|
||||
const extractLabel = React.useCallback(
|
||||
(item: T) => (getLabel ? getLabel(item) : String(item)),
|
||||
[getLabel]
|
||||
)
|
||||
|
||||
const options = React.useMemo<MultiSelectOption<T>[]>(() => {
|
||||
const special: MultiSelectOption<T>[] = [];
|
||||
|
||||
if (useClear) special.push({ value: clearValue, label: clearLabel });
|
||||
|
||||
const normal = items.map((item) => ({
|
||||
value: extractValue(item),
|
||||
label: extractLabel(item),
|
||||
...(withInfo ? { info: item } : {}),
|
||||
}));
|
||||
|
||||
return [...special, ...normal]
|
||||
}, [items, extractValue, extractLabel, withInfo, useClear, clearLabel, clearValue])
|
||||
|
||||
const defaultValue = React.useMemo(() => (value ? [value] : []), [value])
|
||||
|
||||
const tooltipText = React.useMemo(() => {
|
||||
if (!showSelectedTooltip) return undefined;
|
||||
if (!value || !value) return undefined;
|
||||
if (useClear && value === clearValue) return undefined;
|
||||
|
||||
const label = options.find(o => o.value === value)?.label;
|
||||
return label ?? value; // options에 없으면 value라도 표시
|
||||
}, [showSelectedTooltip, value, options, useClear, clearValue]);
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
placeholder = 'Select an option',
|
||||
heightClassName,
|
||||
widthClassName,
|
||||
spanClassName = 'text-base',
|
||||
badgeClassName = 'text-base',
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemChange,
|
||||
onOptionChange,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
showSelectedTooltip = false,
|
||||
useClear = false,
|
||||
clearLabel = '선택 해제',
|
||||
clearValue = '__CLEAR__',
|
||||
disabled,
|
||||
}: KriSingleSelectProps<T>) {
|
||||
const ref = React.useRef<MultiSelectRef>(null)
|
||||
const options = React.useMemo(() => {
|
||||
const normal = toOptions(items, getValue, getLabel, withInfo)
|
||||
return useClear ? [{ value: clearValue, label: clearLabel }, ...normal] : normal
|
||||
}, [clearLabel, clearValue, getLabel, getValue, items, useClear, withInfo])
|
||||
const selectedLabel = options.find((option) => option.value === value)?.label
|
||||
|
||||
return (
|
||||
<div className={cn(widthClassName, heightClassName, "flex-none overflow-hidden")}>
|
||||
<MultiSelect<T>
|
||||
ref={msRef}
|
||||
options={options}
|
||||
defaultValue={defaultValue}
|
||||
onValueChange={(next) => {
|
||||
const v = next[0] ?? ""
|
||||
|
||||
if (v === clearValue) {
|
||||
msRef.current?.clear();
|
||||
|
||||
onChange("")
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
onChange(v)
|
||||
}}
|
||||
onOptionChange={(opts) => {
|
||||
const opt = opts[0] ?? null
|
||||
const item = withInfo ? ((opt as any)?.info ?? null) : null
|
||||
|
||||
onOptionChange?.(opt)
|
||||
onItemChange?.(item)
|
||||
}}
|
||||
selectionMode="single"
|
||||
maxCount={1}
|
||||
maxSelected={1}
|
||||
placeholder={placeholder}
|
||||
className={cn("bg-white content-text-lg", className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
preventDeselect={preventDeselect}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
hideSelectAll
|
||||
autoSize
|
||||
singleLine
|
||||
closeOnSelect
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
/>
|
||||
</div>
|
||||
<div className={cn('flex-none', widthClassName, heightClassName)}>
|
||||
<MultiSelect<T>
|
||||
ref={ref}
|
||||
options={options}
|
||||
defaultValue={value ? [value] : []}
|
||||
onValueChange={(next) => {
|
||||
const selected = next[0] ?? ''
|
||||
if (selected === clearValue) {
|
||||
ref.current?.clear()
|
||||
onChange('')
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
return
|
||||
}
|
||||
onChange(selected)
|
||||
}}
|
||||
onOptionChange={(next) => {
|
||||
const option = next[0] ?? null
|
||||
if (option?.value === clearValue) {
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
return
|
||||
}
|
||||
onOptionChange?.(option)
|
||||
onItemChange?.(option?.info ?? null)
|
||||
}}
|
||||
selectionMode="single"
|
||||
maxCount={1}
|
||||
maxSelected={1}
|
||||
placeholder={placeholder}
|
||||
className={cn('bg-background text-base', !widthClassName && 'w-auto', className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
preventDeselect={preventDeselect}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
hideSelectAll
|
||||
singleLine
|
||||
closeOnSelect
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
disabled={disabled}
|
||||
title={showSelectedTooltip ? selectedLabel ?? value : undefined}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
82
src/components/common/KriDatePicker.tsx
Normal file
82
src/components/common/KriDatePicker.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
"use client";
|
||||
|
||||
import {CalendarIcon, X} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Calendar} from "@/components/ui/calendar";
|
||||
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
|
||||
import {cn} from "@/lib/utils";
|
||||
|
||||
const parseDate = (value: string) => {
|
||||
if (!value) return undefined
|
||||
|
||||
const [year, month, day] = value.split('-').map(Number)
|
||||
if (!year || !month || !day) return undefined
|
||||
|
||||
const date = new Date(year, month - 1, day)
|
||||
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return date
|
||||
}
|
||||
|
||||
const formatDate = (date: Date | undefined) => {
|
||||
if (!date) return ''
|
||||
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
export function KriDatePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "날짜 선택",
|
||||
className,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
const selected = parseDate(value);
|
||||
|
||||
return (
|
||||
<div className={cn("relative", className)}>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={cn("h-9 w-full justify-start bg-white pr-8 text-left font-normal", !value && "text-muted-foreground")}
|
||||
>
|
||||
<CalendarIcon className="h-4 w-4" />
|
||||
{selected ? formatDate(selected) : placeholder}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={selected}
|
||||
onSelect={(date) => onChange(date ? formatDate(date) : "")}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{value && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onChange("");
|
||||
}}
|
||||
aria-label="날짜 초기화"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
122
src/components/common/KriDateRangePicker.tsx
Normal file
122
src/components/common/KriDateRangePicker.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
'use client'
|
||||
|
||||
import { CalendarIcon, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Calendar } from '@/components/ui/calendar'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type KriDateRange = {
|
||||
from: string
|
||||
to: string
|
||||
}
|
||||
|
||||
export type KriDateRangePickerProps = {
|
||||
value: KriDateRange
|
||||
onChange: (value: KriDateRange) => void
|
||||
placeholder?: string
|
||||
className?: string
|
||||
triggerClassName?: string
|
||||
contentClassName?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const parseDate = (value: string) => {
|
||||
if (!value) return undefined
|
||||
|
||||
const [year, month, day] = value.split('-').map(Number)
|
||||
if (!year || !month || !day) return undefined
|
||||
|
||||
const date = new Date(year, month - 1, day)
|
||||
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return date
|
||||
}
|
||||
|
||||
const formatDate = (date: Date | undefined) => {
|
||||
if (!date) return ''
|
||||
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
export function KriDateRangePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '조회 기간 선택',
|
||||
className,
|
||||
triggerClassName,
|
||||
contentClassName,
|
||||
disabled = false,
|
||||
}: KriDateRangePickerProps) {
|
||||
const selected = {
|
||||
from: parseDate(value.from),
|
||||
to: parseDate(value.to),
|
||||
}
|
||||
const selectedRange = selected.from || selected.to ? selected : undefined
|
||||
|
||||
const displayText = value.from && value.to
|
||||
? `${value.from} ~ ${value.to}`
|
||||
: value.from
|
||||
? `${value.from} ~`
|
||||
: value.to
|
||||
? `~ ${value.to}`
|
||||
: placeholder
|
||||
|
||||
const hasValue = value.from.length > 0 || value.to.length > 0
|
||||
|
||||
return (
|
||||
<div className={cn('relative', className)}>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
|
||||
!hasValue && 'text-muted-foreground',
|
||||
triggerClassName,
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="h-4 w-4" />
|
||||
<span className="truncate">{displayText}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
|
||||
<Calendar
|
||||
mode="range"
|
||||
selected={selectedRange}
|
||||
onSelect={(range) => {
|
||||
onChange({
|
||||
from: formatDate(range?.from),
|
||||
to: formatDate(range?.to),
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{hasValue && !disabled ? (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onChange({ from: '', to: '' })
|
||||
}}
|
||||
aria-label="조회 기간 초기화"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KriDateRangePicker
|
||||
136
src/components/common/KriDateTimePicker.tsx
Normal file
136
src/components/common/KriDateTimePicker.tsx
Normal file
@@ -0,0 +1,136 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { CalendarIcon, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Calendar } from '@/components/ui/calendar'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { KriTimePicker } from '@/components/common/KriTimePicker'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type KriDateTimePickerProps = {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder?: string
|
||||
className?: string
|
||||
triggerClassName?: string
|
||||
contentClassName?: string
|
||||
disabled?: boolean
|
||||
modalPopover?: boolean
|
||||
}
|
||||
|
||||
const parseDateTime = (value: string): { date: Date | undefined; time: string } => {
|
||||
if (!value) return { date: undefined, time: '' }
|
||||
|
||||
const [datePart, timePart = ''] = value.split('T')
|
||||
const [year, month, day] = datePart.split('-').map(Number)
|
||||
if (!year || !month || !day) return { date: undefined, time: timePart }
|
||||
|
||||
const date = new Date(year, month - 1, day)
|
||||
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
||||
return { date: undefined, time: timePart }
|
||||
}
|
||||
|
||||
return { date, time: timePart }
|
||||
}
|
||||
|
||||
const formatDate = (date: Date | undefined) => {
|
||||
if (!date) return ''
|
||||
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
const toValue = (date: Date | undefined, time: string): string => {
|
||||
const dateText = formatDate(date)
|
||||
if (!dateText) return ''
|
||||
|
||||
return `${dateText}T${time || '00:00'}`
|
||||
}
|
||||
|
||||
const toDisplayText = (date: Date | undefined, time: string, placeholder: string) => {
|
||||
const dateText = formatDate(date)
|
||||
if (!dateText) return placeholder
|
||||
|
||||
return `${dateText} ${time || '00:00'}`
|
||||
}
|
||||
|
||||
export function KriDateTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '날짜/시간 선택',
|
||||
className,
|
||||
triggerClassName,
|
||||
contentClassName,
|
||||
disabled = false,
|
||||
modalPopover = true,
|
||||
}: KriDateTimePickerProps) {
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const { date, time } = parseDateTime(value)
|
||||
const hasValue = date !== undefined
|
||||
|
||||
const handleDateSelect = (nextDate: Date | undefined) => {
|
||||
if (!nextDate) return
|
||||
onChange(toValue(nextDate, time || '00:00'))
|
||||
}
|
||||
|
||||
const handleTimeChange = (nextTime: string) => {
|
||||
if (!date) return
|
||||
onChange(toValue(date, nextTime))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('relative', className)}>
|
||||
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
|
||||
!hasValue && 'text-muted-foreground',
|
||||
triggerClassName,
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
<span className="truncate">{toDisplayText(date, time, placeholder)}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
|
||||
<div className="sm:flex">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={date}
|
||||
onSelect={handleDateSelect}
|
||||
/>
|
||||
<KriTimePicker
|
||||
value={time || '00:00'}
|
||||
onChange={handleTimeChange}
|
||||
disabled={!date}
|
||||
/>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{hasValue && !disabled ? (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onChange('')
|
||||
}}
|
||||
aria-label="날짜/시간 초기화"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KriDateTimePicker
|
||||
89
src/components/common/KriDialog.tsx
Normal file
89
src/components/common/KriDialog.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { loadingAtom } from '@/store/jotai/loading'
|
||||
|
||||
export interface KriDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
title: ReactNode
|
||||
description?: ReactNode
|
||||
children?: ReactNode
|
||||
footer?: ReactNode
|
||||
showDefaultFooter?: boolean
|
||||
closeLabel?: string
|
||||
showCloseButton?: boolean
|
||||
contentClassName?: string
|
||||
bodyClassName?: string
|
||||
footerClassName?: string
|
||||
}
|
||||
|
||||
export function KriDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
footer,
|
||||
showDefaultFooter = true,
|
||||
closeLabel = '닫기',
|
||||
showCloseButton = true,
|
||||
contentClassName,
|
||||
bodyClassName,
|
||||
footerClassName,
|
||||
}: KriDialogProps) {
|
||||
const isLoading = useAtomValue(loadingAtom)
|
||||
|
||||
const renderFooter = () => {
|
||||
if (footer !== undefined) {
|
||||
if (footer === null) return null
|
||||
return <DialogFooter className={footerClassName}>{footer}</DialogFooter>
|
||||
}
|
||||
|
||||
if (!showDefaultFooter) return null
|
||||
|
||||
return (
|
||||
<DialogFooter className={footerClassName}>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">
|
||||
{closeLabel}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
className={contentClassName}
|
||||
showCloseButton={showCloseButton}
|
||||
onInteractOutside={(e) => {
|
||||
if (isLoading) e.preventDefault()
|
||||
}}
|
||||
onEscapeKeyDown={(e) => {
|
||||
if (isLoading) e.preventDefault()
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
{description ? <DialogDescription>{description}</DialogDescription> : null}
|
||||
</DialogHeader>
|
||||
<div className={cn('min-h-0', bodyClassName)}>{children}</div>
|
||||
{renderFooter()}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
29
src/components/common/KriLoadingOverlay.tsx
Normal file
29
src/components/common/KriLoadingOverlay.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
'use client'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface KriLoadingOverlayProps {
|
||||
open: boolean
|
||||
label?: string
|
||||
className?: string
|
||||
spinnerClassName?: string
|
||||
}
|
||||
|
||||
export function KriLoadingOverlay({ open, label = '로딩 중', className, spinnerClassName }: KriLoadingOverlayProps) {
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label={label}
|
||||
className={cn('fixed inset-0 z-[9999] flex items-center justify-center bg-black/70', className)}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className={cn('size-12 animate-spin rounded-full border-4 border-gray-400 border-t-white', spinnerClassName)} />
|
||||
<span className="sr-only">{label}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -7,32 +7,18 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// ✅ 화면에 보여줄 “허용 특수문자”
|
||||
export const ALLOWED_SPECIALS_TEXT =
|
||||
`! @ # $ % ^ & * ( ) _ + - = { } [ ] : ; " ' < > , . ? /`
|
||||
|
||||
// ✅ “허용 문자만” 체크(공백/한글/기타 특수문자 차단)
|
||||
export const ONLY_ALLOWED_REGEX =
|
||||
/^[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?\/]+$/
|
||||
|
||||
// ✅ 최종 비밀번호 규칙(특수문자 필수 아님)
|
||||
// - 8~20자
|
||||
// - 영문 1개 이상 + 숫자 1개 이상
|
||||
// - 구성 문자는 허용 문자만
|
||||
export const KRI_PW_REGEX =
|
||||
/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?\/]{8,20}$/
|
||||
export const ALLOWED_SPECIALS_TEXT = `! @ # $ % ^ & * ( ) _ + - = { } [ ] : ; " ' < > , . ? /`
|
||||
export const ONLY_ALLOWED_REGEX = /^[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]+$/
|
||||
export const KRI_PW_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]{8,20}$/
|
||||
|
||||
const requirements = [
|
||||
{ regex: /[A-Za-z]/, text: '영문 1개 이상 (A–Z 또는 a–z)' },
|
||||
{ regex: /\d/, text: '숫자 1개 이상' },
|
||||
{ regex: /^.{10,}$/, text: '10자 이상' },
|
||||
{
|
||||
regex: /[!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]/,
|
||||
text: `특수문자 사용 (허용: ${ALLOWED_SPECIALS_TEXT})`,
|
||||
},
|
||||
{ test: (value: string) => /[A-Za-z]/.test(value), text: '영문 1개 이상' },
|
||||
{ test: (value: string) => /\d/.test(value), text: '숫자 1개 이상' },
|
||||
{ test: (value: string) => value.length >= 8 && value.length <= 20, text: '8~20자' },
|
||||
{ test: (value: string) => !value || ONLY_ALLOWED_REGEX.test(value), text: '허용 문자만 사용' },
|
||||
]
|
||||
|
||||
type KriPasswordProps = {
|
||||
export interface KriPasswordProps {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
id?: string
|
||||
@@ -40,156 +26,92 @@ type KriPasswordProps = {
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
showStrength?: boolean
|
||||
}
|
||||
|
||||
const KriPassword = ({
|
||||
value,
|
||||
onChange,
|
||||
id,
|
||||
label = '비밀번호',
|
||||
placeholder = '비밀번호를 입력하세요',
|
||||
disabled,
|
||||
className,
|
||||
}: KriPasswordProps) => {
|
||||
export function KriPassword({
|
||||
value,
|
||||
onChange,
|
||||
id,
|
||||
label = '비밀번호',
|
||||
placeholder = '비밀번호를 입력하세요',
|
||||
disabled,
|
||||
className,
|
||||
showStrength = true,
|
||||
}: KriPasswordProps) {
|
||||
const [isVisible, setIsVisible] = useState(false)
|
||||
|
||||
const autoId = useId()
|
||||
const inputId = id ?? autoId
|
||||
const toggleVisibility = () => setIsVisible((prev) => !prev)
|
||||
const isValid = useMemo(() => KRI_PW_REGEX.test(value), [value])
|
||||
const hasOnlyAllowedChars = useMemo(
|
||||
() => (value ? ONLY_ALLOWED_REGEX.test(value) : true),
|
||||
[value]
|
||||
)
|
||||
|
||||
const checks = useMemo(
|
||||
() =>
|
||||
requirements.map((req) => ({
|
||||
met: req.regex.test(value),
|
||||
text: req.text,
|
||||
})),
|
||||
[value]
|
||||
)
|
||||
const hasOnlyAllowedChars = useMemo(() => (value ? ONLY_ALLOWED_REGEX.test(value) : true), [value])
|
||||
const checks = useMemo(() => requirements.map((item) => ({ met: item.test(value), text: item.text })), [value])
|
||||
const score = checks.filter((item) => item.met).length
|
||||
|
||||
const statusText = useMemo(() => {
|
||||
if (!value) return '비밀번호를 입력하세요'
|
||||
if (!hasOnlyAllowedChars) return '허용되지 않는 문자가 포함되어 있어요'
|
||||
return isValid ? '사용 가능한 비밀번호입니다' : '비밀번호 규칙을 만족하지 않아요'
|
||||
}, [value, isValid, hasOnlyAllowedChars])
|
||||
return isValid ? '사용 가능한 비밀번호입니다' : '영문과 숫자를 포함한 8~20자로 입력하세요'
|
||||
}, [hasOnlyAllowedChars, isValid, value])
|
||||
|
||||
const score = useMemo(() => checks.filter((c) => c.met).length, [checks])
|
||||
|
||||
const getBarColor = (s: number) => {
|
||||
if (s === 0) return 'bg-border'
|
||||
if (s === 1) return 'bg-destructive'
|
||||
if (s === 2) return 'bg-orange-500'
|
||||
if (s === 3) return 'bg-yellow-400'
|
||||
return 'bg-green-500' // 4
|
||||
}
|
||||
|
||||
const getStrengthText = (s: number) => {
|
||||
if (s === 0) return '비밀번호를 입력하세요'
|
||||
if (s === 1) return '약함'
|
||||
if (s === 2) return '보통'
|
||||
if (s === 3) return '강함'
|
||||
return '매우 강함'
|
||||
}
|
||||
const barClass = score <= 1 ? 'bg-destructive' : score === 2 ? 'bg-orange-500' : score === 3 ? 'bg-yellow-400' : 'bg-green-500'
|
||||
|
||||
return (
|
||||
<div className={cn('w-full space-y-2', className)}>
|
||||
<Label htmlFor={inputId}>{label}</Label>
|
||||
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={inputId}
|
||||
type={isVisible ? 'text' : 'password'}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="pr-9"
|
||||
disabled={disabled}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleVisibility}
|
||||
disabled={disabled}
|
||||
className="text-muted-foreground focus-visible:ring-ring/50 absolute inset-y-0 right-0 rounded-l-none hover:bg-transparent"
|
||||
>
|
||||
{isVisible ? <EyeOffIcon /> : <EyeIcon />}
|
||||
<span className="sr-only">{isVisible ? '숨기기' : '보기'}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Strength bars */}
|
||||
<div className="flex h-1 w-full gap-1">
|
||||
{Array.from({ length: requirements.length }).map((_, index) => (
|
||||
<span
|
||||
key={index}
|
||||
className={cn(
|
||||
'h-full flex-1 rounded-full transition-all duration-300 ease-out',
|
||||
index < score ? getBarColor(score) : 'bg-border'
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-start gap-2">
|
||||
{value ? (
|
||||
isValid ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600 dark:text-green-400" />
|
||||
) : (
|
||||
<XIcon className="mt-0.5 size-4 text-destructive" />
|
||||
)
|
||||
) : (
|
||||
<span className="mt-0.5 size-4" />
|
||||
)}
|
||||
|
||||
<p
|
||||
className={cn(
|
||||
'text-xs',
|
||||
!value
|
||||
? 'text-muted-foreground'
|
||||
: isValid
|
||||
? 'text-green-600 dark:text-green-400'
|
||||
: 'text-destructive'
|
||||
)}
|
||||
>
|
||||
{statusText}
|
||||
</p>
|
||||
</div>
|
||||
{
|
||||
/*
|
||||
<p className="text-foreground text-sm font-medium">
|
||||
{getStrengthText(score)}.
|
||||
</p>
|
||||
<p className="text-foreground text-sm font-medium">
|
||||
포함 조건:
|
||||
</p>
|
||||
<ul className="space-y-1.5">
|
||||
{checks.map((c, idx) => (
|
||||
<li key={idx} className="flex items-start gap-2">
|
||||
{c.met ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600 dark:text-green-400" />
|
||||
) : (
|
||||
<XIcon className="mt-0.5 size-4 text-muted-foreground" />
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs',
|
||||
c.met ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{c.text}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
*/
|
||||
}
|
||||
<div className={cn('w-full space-y-2', className)}>
|
||||
{label ? <Label htmlFor={inputId}>{label}</Label> : null}
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={inputId}
|
||||
type={isVisible ? 'text' : 'password'}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
className="pr-9"
|
||||
disabled={disabled}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setIsVisible((current) => !current)}
|
||||
disabled={disabled}
|
||||
className="text-muted-foreground absolute inset-y-0 right-0 rounded-l-none hover:bg-transparent"
|
||||
>
|
||||
{isVisible ? <EyeOffIcon /> : <EyeIcon />}
|
||||
<span className="sr-only">{isVisible ? '숨기기' : '보기'}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showStrength ? (
|
||||
<>
|
||||
<div className="flex h-1 w-full gap-1">
|
||||
{requirements.map((item, index) => (
|
||||
<span
|
||||
key={item.text}
|
||||
className={cn(
|
||||
'h-full flex-1 rounded-full transition-colors',
|
||||
index < score && value ? barClass : 'bg-border',
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-start gap-2">
|
||||
{value ? (
|
||||
isValid ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600" />
|
||||
) : (
|
||||
<XIcon className="text-destructive mt-0.5 size-4" />
|
||||
)
|
||||
) : (
|
||||
<span className="mt-0.5 size-4" />
|
||||
)}
|
||||
<p className={cn('text-xs', !value ? 'text-muted-foreground' : isValid ? 'text-green-600' : 'text-destructive')}>
|
||||
{statusText}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import type { CSSProperties } from 'react'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -8,79 +9,90 @@ export type KriSelectItem = {
|
||||
label: string
|
||||
}
|
||||
|
||||
type KriSelectProps<T> = {
|
||||
/** options 배열: string[] 혹은 T[] */
|
||||
export type KriSelectProps<T> = {
|
||||
items: T[]
|
||||
/** 현재 선택 값 */
|
||||
value: string
|
||||
/** 값 변경 시 호출 */
|
||||
onChange?: (value: string) => void
|
||||
/** 옵션 변경시 호출 */
|
||||
onChangeOption?: (option: T) => void
|
||||
/** placeholder 텍스트 */
|
||||
placeholder?: string
|
||||
/** 기타 클래스 (예: 'w-40') */
|
||||
className?: string
|
||||
/** value를 어떻게 뽑을지 (없으면 String(item)) */
|
||||
heightClassName?: string
|
||||
triggerTextClassName?: string
|
||||
contentClassName?: string
|
||||
itemClassName?: string
|
||||
getValue?: (item: T) => string
|
||||
/** label을 어떻게 뽑을지 (없으면 String(item)) */
|
||||
getLabel?: (item: T) => string
|
||||
/** 전체 사용 여부 */
|
||||
useAll?: boolean
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const HEIGHT_CLASS_VALUE: Record<string, CSSProperties['height']> = {
|
||||
'h-6': '1.5rem',
|
||||
'h-7': '1.75rem',
|
||||
'h-8': '2rem',
|
||||
'h-9': '2.25rem',
|
||||
'h-10': '2.5rem',
|
||||
}
|
||||
|
||||
export function KriSelect<T>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
onChangeOption,
|
||||
placeholder,
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
useAll = true,
|
||||
}: KriSelectProps<T>) {
|
||||
|
||||
const extractValue = (item: T) =>
|
||||
getValue ? getValue(item) : String(item);
|
||||
|
||||
const extractLabel = (item: T) =>
|
||||
getLabel ? getLabel(item) : String(item);
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
onChangeOption,
|
||||
placeholder,
|
||||
className,
|
||||
heightClassName,
|
||||
triggerTextClassName,
|
||||
contentClassName,
|
||||
itemClassName,
|
||||
getValue,
|
||||
getLabel,
|
||||
useAll = true,
|
||||
disabled,
|
||||
}: KriSelectProps<T>) {
|
||||
const extractValue = (item: T) => (getValue ? getValue(item) : String(item))
|
||||
const extractLabel = (item: T) => (getLabel ? getLabel(item) : String(item))
|
||||
const triggerStyle: CSSProperties | undefined = heightClassName
|
||||
? { height: HEIGHT_CLASS_VALUE[heightClassName] ?? undefined }
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<Select
|
||||
value={value}
|
||||
onValueChange={(v) => {
|
||||
onChange?.(v);
|
||||
<Select
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
onValueChange={(selectedValue) => {
|
||||
onChange?.(selectedValue)
|
||||
|
||||
const selected = items.find((item) => extractValue(item) === v);
|
||||
if(selected) {
|
||||
onChangeOption?.(selected);
|
||||
}
|
||||
}}
|
||||
const selected = items.find((item) => extractValue(item) === selectedValue)
|
||||
if (selected) {
|
||||
onChangeOption?.(selected)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
className={cn('w-fit whitespace-nowrap bg-white', triggerTextClassName, heightClassName, className)}
|
||||
style={triggerStyle}
|
||||
aria-label={placeholder ?? 'select'}
|
||||
>
|
||||
<SelectTrigger
|
||||
className={cn(
|
||||
'w-fit whitespace-nowrap bg-white content-text-lg', // 폰트 사이즈
|
||||
className
|
||||
)}
|
||||
aria-label={placeholder ?? 'select'}
|
||||
>
|
||||
<SelectValue placeholder={placeholder} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ useAll? <SelectItem key="ALL" value="ALL">전체</SelectItem> :null }
|
||||
{items.map((item, idx) => {
|
||||
const v = extractValue(item);
|
||||
const label = extractLabel(item);
|
||||
<SelectValue placeholder={placeholder} />
|
||||
</SelectTrigger>
|
||||
<SelectContent className={contentClassName}>
|
||||
{useAll ? (
|
||||
<SelectItem value="ALL" className={itemClassName}>
|
||||
전체
|
||||
</SelectItem>
|
||||
) : null}
|
||||
{items.map((item, index) => {
|
||||
const itemValue = extractValue(item)
|
||||
const label = extractLabel(item)
|
||||
|
||||
return (
|
||||
<SelectItem key={v ?? idx} value={v}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
)
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
return (
|
||||
<SelectItem key={itemValue || index} value={itemValue} className={itemClassName}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
)
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
|
||||
99
src/components/common/KriTimePicker.tsx
Normal file
99
src/components/common/KriTimePicker.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type KriTimePickerProps = {
|
||||
value?: string
|
||||
onChange: (value: string) => void
|
||||
disabled?: boolean
|
||||
minuteStep?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
const parseTime = (value: string | undefined) => {
|
||||
if (!value) return { hour: undefined, minute: undefined }
|
||||
|
||||
const [hour, minute] = value.split(':').map(Number)
|
||||
|
||||
return {
|
||||
hour: Number.isInteger(hour) && hour >= 0 && hour < 24 ? hour : undefined,
|
||||
minute: Number.isInteger(minute) && minute >= 0 && minute < 60 ? minute : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
const formatTime = (hour: number, minute: number) => {
|
||||
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export function KriTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
disabled = false,
|
||||
minuteStep = 5,
|
||||
className,
|
||||
}: KriTimePickerProps) {
|
||||
const { hour: selectedHour, minute: selectedMinute } = parseTime(value)
|
||||
const normalizedMinuteStep = Number.isFinite(minuteStep) && minuteStep > 0
|
||||
? Math.min(Math.floor(minuteStep), 60)
|
||||
: 5
|
||||
const hours = Array.from({ length: 24 }, (_, index) => index)
|
||||
const minutes = Array.from(
|
||||
{ length: Math.ceil(60 / normalizedMinuteStep) },
|
||||
(_, index) => index * normalizedMinuteStep,
|
||||
).filter((minute) => minute < 60)
|
||||
|
||||
const handleTimeChange = (type: 'hour' | 'minute', nextValue: number) => {
|
||||
if (disabled) return
|
||||
|
||||
const nextHour = type === 'hour' ? nextValue : selectedHour ?? 0
|
||||
const nextMinute = type === 'minute' ? nextValue : selectedMinute ?? 0
|
||||
|
||||
onChange(formatTime(nextHour, nextMinute))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col divide-y sm:h-[300px] sm:flex-row sm:divide-x sm:divide-y-0', className)}>
|
||||
<ScrollArea className="w-64 sm:w-auto">
|
||||
<div className="flex p-2 sm:flex-col">
|
||||
{hours.map((hour) => (
|
||||
<Button
|
||||
key={hour}
|
||||
type="button"
|
||||
size="icon"
|
||||
variant={selectedHour === hour ? 'default' : 'ghost'}
|
||||
className="aspect-square shrink-0 sm:w-full"
|
||||
disabled={disabled}
|
||||
onClick={() => handleTimeChange('hour', hour)}
|
||||
>
|
||||
{hour}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||
</ScrollArea>
|
||||
|
||||
<ScrollArea className="w-64 sm:w-auto">
|
||||
<div className="flex p-2 sm:flex-col">
|
||||
{minutes.map((minute) => (
|
||||
<Button
|
||||
key={minute}
|
||||
type="button"
|
||||
size="icon"
|
||||
variant={selectedMinute === minute ? 'default' : 'ghost'}
|
||||
className="aspect-square shrink-0 sm:w-full"
|
||||
disabled={disabled}
|
||||
onClick={() => handleTimeChange('minute', minute)}
|
||||
>
|
||||
{String(minute).padStart(2, '0')}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KriTimePicker
|
||||
@@ -1,17 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export function LoadingOverlay({ force = false }: { force?: boolean }) {
|
||||
const isLoading = useAtomValue(loadingAtom);
|
||||
|
||||
if (!force && !isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[9999] bg-black/70 flex items-center justify-center">
|
||||
{/* 심플 로딩 인디케이터 */}
|
||||
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MultiSelectContent } from './MultiSelectContent'
|
||||
import { MultiSelectTrigger } from './MultiSelectTrigger'
|
||||
import type { MultiSelectOption, MultiSelectProps, MultiSelectRef } from './types'
|
||||
import { arraysEqual, deduplicateOptions, flattenOptions } from './utils'
|
||||
import { useResponsiveSettings } from './use-responsive-settings'
|
||||
|
||||
function MultiSelectInner<T>(
|
||||
{
|
||||
options: rawOptions,
|
||||
onValueChange,
|
||||
onOptionChange,
|
||||
onInfoChange,
|
||||
defaultValue = [],
|
||||
stickySelectedOptions = [],
|
||||
onStickySelectedOptionsChange,
|
||||
placeholder = 'Select options',
|
||||
maxCount = 3,
|
||||
maxSelected,
|
||||
selectionMode = 'multiple',
|
||||
modalPopover = false,
|
||||
variant = 'default',
|
||||
className,
|
||||
spanClassName,
|
||||
badgeClassName,
|
||||
hideSelectAll = false,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
emptyIndicator = '검색 결과가 없습니다.',
|
||||
autoSize = false,
|
||||
singleLine = false,
|
||||
popoverClassName,
|
||||
disabled = false,
|
||||
responsive,
|
||||
minWidth,
|
||||
maxWidth,
|
||||
deduplicateOptions: shouldDeduplicate = false,
|
||||
resetOnDefaultValueChange = true,
|
||||
closeOnSelect = false,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
style,
|
||||
...buttonProps
|
||||
}: MultiSelectProps<T>,
|
||||
ref: React.ForwardedRef<MultiSelectRef>,
|
||||
) {
|
||||
const [selectedValues, setSelectedValues] = React.useState<string[]>(defaultValue)
|
||||
const [searchValue, setSearchValue] = React.useState(defaultSearchValue)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const buttonRef = React.useRef<HTMLButtonElement>(null)
|
||||
const [triggerWidth, setTriggerWidth] = React.useState<number>()
|
||||
|
||||
const options = React.useMemo(
|
||||
() => (shouldDeduplicate ? deduplicateOptions(rawOptions) : rawOptions),
|
||||
[rawOptions, shouldDeduplicate],
|
||||
)
|
||||
const flatOptions = React.useMemo(() => flattenOptions(options), [options])
|
||||
const responsiveSettings = useResponsiveSettings(responsive, maxCount)
|
||||
|
||||
const optionMap = React.useMemo(() => {
|
||||
const map = new Map<string, MultiSelectOption<T>>()
|
||||
for (const option of stickySelectedOptions) map.set(option.value, option)
|
||||
for (const option of flatOptions) map.set(option.value, option)
|
||||
return map
|
||||
}, [flatOptions, stickySelectedOptions])
|
||||
|
||||
const selectedOptions = React.useMemo(
|
||||
() => selectedValues.map((value) => optionMap.get(value) ?? { value, label: value }),
|
||||
[optionMap, selectedValues],
|
||||
)
|
||||
|
||||
const emit = React.useCallback(
|
||||
(next: string[]) => {
|
||||
setSelectedValues(next)
|
||||
onValueChange(next)
|
||||
const nextOptions = next.map((value) => optionMap.get(value) ?? { value, label: value })
|
||||
onOptionChange?.(nextOptions)
|
||||
onInfoChange?.(
|
||||
nextOptions.flatMap((option) => (option.info === undefined ? [] : [option.info])),
|
||||
)
|
||||
},
|
||||
[onInfoChange, onOptionChange, onValueChange, optionMap],
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!resetOnDefaultValueChange || arraysEqual(defaultValue, selectedValues)) return
|
||||
setSelectedValues(defaultValue)
|
||||
}, [defaultValue, resetOnDefaultValueChange, selectedValues])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!onStickySelectedOptionsChange) return
|
||||
const refreshed = selectedValues
|
||||
.map((value) => optionMap.get(value))
|
||||
.filter((option): option is MultiSelectOption<T> => Boolean(option))
|
||||
onStickySelectedOptionsChange(refreshed)
|
||||
}, [onStickySelectedOptionsChange, optionMap, selectedValues])
|
||||
|
||||
React.useEffect(() => {
|
||||
const element = buttonRef.current
|
||||
if (!element || !('ResizeObserver' in window)) return
|
||||
const update = () => setTriggerWidth(Math.round(element.getBoundingClientRect().width))
|
||||
update()
|
||||
const observer = new ResizeObserver(update)
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
React.useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
reset: () => {
|
||||
emit(defaultValue)
|
||||
setSearchValue(defaultSearchValue)
|
||||
setOpen(false)
|
||||
},
|
||||
getSelectedValues: () => selectedValues,
|
||||
setSelectedValues: emit,
|
||||
clear: () => emit([]),
|
||||
focus: () => buttonRef.current?.focus(),
|
||||
}),
|
||||
[defaultSearchValue, defaultValue, emit, selectedValues],
|
||||
)
|
||||
|
||||
const toggleOption = React.useCallback(
|
||||
(option: MultiSelectOption<T>) => {
|
||||
if (option.disabled) return
|
||||
const selected = selectedValues.includes(option.value)
|
||||
|
||||
if (selected) {
|
||||
if (preventDeselect) return
|
||||
emit(selectedValues.filter((value) => value !== option.value))
|
||||
return
|
||||
}
|
||||
|
||||
if (selectionMode === 'single') {
|
||||
emit([option.value])
|
||||
if (closeOnSelect) setOpen(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (maxSelected !== undefined && selectedValues.length >= maxSelected) return
|
||||
emit([...selectedValues, option.value])
|
||||
if (closeOnSelect) setOpen(false)
|
||||
},
|
||||
[closeOnSelect, emit, maxSelected, preventDeselect, selectedValues, selectionMode],
|
||||
)
|
||||
|
||||
const toggleAll = React.useCallback(() => {
|
||||
const values = flatOptions.filter((option) => !option.disabled).map((option) => option.value)
|
||||
const allSelected = values.length > 0 && values.every((value) => selectedValues.includes(value))
|
||||
if (allSelected) {
|
||||
if (!preventDeselect) emit([])
|
||||
return
|
||||
}
|
||||
emit(maxSelected === undefined ? values : values.slice(0, maxSelected))
|
||||
}, [emit, flatOptions, maxSelected, preventDeselect, selectedValues])
|
||||
|
||||
const handleSearchChange = (value: string) => {
|
||||
setSearchValue(value)
|
||||
onSearchValueChange?.(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
||||
<PopoverTrigger asChild>
|
||||
<MultiSelectTrigger
|
||||
ref={buttonRef}
|
||||
selectedOptions={selectedOptions}
|
||||
placeholder={placeholder}
|
||||
maxCount={responsiveSettings.maxCount}
|
||||
compactMode={responsiveSettings.compactMode}
|
||||
hideIcons={responsiveSettings.hideIcons}
|
||||
singleLine={singleLine}
|
||||
preventDeselect={preventDeselect}
|
||||
variant={variant}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
onRemove={(value) => emit(selectedValues.filter((selected) => selected !== value))}
|
||||
onClear={() => emit([])}
|
||||
className={cn(autoSize && 'w-auto', className)}
|
||||
disabled={disabled}
|
||||
style={{ minWidth, maxWidth, ...style }}
|
||||
{...buttonProps}
|
||||
/>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className={cn('w-[var(--radix-popover-trigger-width)] min-w-64 p-0', popoverClassName)}
|
||||
style={{ width: triggerWidth ? `${triggerWidth}px` : undefined }}
|
||||
>
|
||||
<MultiSelectContent
|
||||
options={options}
|
||||
selectedValues={selectedValues}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
searchValue={searchValue}
|
||||
onSearchValueChange={handleSearchChange}
|
||||
hideSelectAll={hideSelectAll}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
selectionMode={selectionMode}
|
||||
emptyIndicator={emptyIndicator}
|
||||
onToggleOption={toggleOption}
|
||||
onToggleAll={toggleAll}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
const ForwardedMultiSelect = React.forwardRef(MultiSelectInner) as <T = unknown>(
|
||||
props: MultiSelectProps<T> & { ref?: React.ForwardedRef<MultiSelectRef> },
|
||||
) => React.ReactElement
|
||||
|
||||
export const MultiSelect = ForwardedMultiSelect
|
||||
169
src/components/common/multi-select/MultiSelectContent.tsx
Normal file
169
src/components/common/multi-select/MultiSelectContent.tsx
Normal file
@@ -0,0 +1,169 @@
|
||||
'use client'
|
||||
|
||||
import { CheckIcon } from 'lucide-react'
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from '@/components/ui/command'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
||||
import { isGroupedOptions } from './utils'
|
||||
|
||||
interface MultiSelectContentProps<T> {
|
||||
options: MultiSelectOptions<T>
|
||||
selectedValues: string[]
|
||||
searchable: boolean
|
||||
searchMode: 'filter' | 'inputOnly'
|
||||
searchValue: string
|
||||
onSearchValueChange: (value: string) => void
|
||||
hideSelectAll: boolean
|
||||
hideOptionCheck: boolean
|
||||
selectionMode: 'single' | 'multiple'
|
||||
emptyIndicator: React.ReactNode
|
||||
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||
onToggleAll: () => void
|
||||
}
|
||||
|
||||
function OptionItem<T>({
|
||||
option,
|
||||
selected,
|
||||
hideOptionCheck,
|
||||
onToggle,
|
||||
}: {
|
||||
option: MultiSelectOption<T>
|
||||
selected: boolean
|
||||
hideOptionCheck: boolean
|
||||
onToggle: () => void
|
||||
}) {
|
||||
const Icon = option.icon
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
value={`${option.label} ${option.value}`}
|
||||
disabled={option.disabled}
|
||||
onSelect={onToggle}
|
||||
className="flex items-center cursor-pointer"
|
||||
>
|
||||
{!hideOptionCheck ? (
|
||||
<span
|
||||
className={cn(
|
||||
'border-primary flex size-4 items-center justify-center rounded-sm border',
|
||||
selected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
) : null}
|
||||
{Icon ? <Icon className="size-4" style={{ color: option.style?.iconColor }} /> : null}
|
||||
<span className="truncate">{option.label}</span>
|
||||
</CommandItem>
|
||||
)
|
||||
}
|
||||
|
||||
function OptionsGroup<T>({
|
||||
group,
|
||||
selectedValues,
|
||||
hideOptionCheck,
|
||||
onToggleOption,
|
||||
}: {
|
||||
group: MultiSelectGroup<T>
|
||||
selectedValues: string[]
|
||||
hideOptionCheck: boolean
|
||||
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||
}) {
|
||||
return (
|
||||
<CommandGroup heading={group.heading}>
|
||||
{group.options.map((option) => (
|
||||
<OptionItem
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={selectedValues.includes(option.value)}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggle={() => onToggleOption(option)}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export function MultiSelectContent<T>({
|
||||
options,
|
||||
selectedValues,
|
||||
searchable,
|
||||
searchMode,
|
||||
searchValue,
|
||||
onSearchValueChange,
|
||||
hideSelectAll,
|
||||
hideOptionCheck,
|
||||
selectionMode,
|
||||
emptyIndicator,
|
||||
onToggleOption,
|
||||
onToggleAll,
|
||||
}: MultiSelectContentProps<T>) {
|
||||
const grouped = isGroupedOptions(options)
|
||||
const flatOptions = grouped ? options.flatMap((group) => group.options) : options
|
||||
const selectableOptions = flatOptions.filter((option) => !option.disabled)
|
||||
const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value))
|
||||
|
||||
return (
|
||||
<Command shouldFilter={searchMode === 'filter'}>
|
||||
{searchable ? (
|
||||
<CommandInput
|
||||
value={searchValue}
|
||||
onValueChange={onSearchValueChange}
|
||||
placeholder="검색..."
|
||||
/>
|
||||
) : null}
|
||||
<CommandList>
|
||||
<CommandEmpty>{emptyIndicator}</CommandEmpty>
|
||||
{selectionMode === 'multiple' && !hideSelectAll && selectableOptions.length > 0 ? (
|
||||
<>
|
||||
<CommandGroup>
|
||||
<CommandItem className="cursor-pointer" value="__kri_select_all__" onSelect={onToggleAll}>
|
||||
<span
|
||||
className={cn(
|
||||
'border-primary flex size-4 items-center justify-center rounded-sm border',
|
||||
allSelected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
전체 선택
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
<CommandSeparator />
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{grouped ? (
|
||||
options.map((group) => (
|
||||
<OptionsGroup
|
||||
key={group.heading}
|
||||
group={group}
|
||||
selectedValues={selectedValues}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggleOption={onToggleOption}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<CommandGroup>
|
||||
{options.map((option) => (
|
||||
<OptionItem
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={selectedValues.includes(option.value)}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggle={() => onToggleOption(option)}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)}
|
||||
</CommandList>
|
||||
</Command>
|
||||
)
|
||||
}
|
||||
143
src/components/common/multi-select/MultiSelectTrigger.tsx
Normal file
143
src/components/common/multi-select/MultiSelectTrigger.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { ChevronDown, XCircle, XIcon } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MultiSelectOption, MultiSelectVariant } from './types'
|
||||
import { getVariantClass } from './utils'
|
||||
|
||||
interface MultiSelectTriggerProps<T> extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onChange'> {
|
||||
selectedOptions: MultiSelectOption<T>[]
|
||||
placeholder: string
|
||||
maxCount: number
|
||||
singleLine: boolean
|
||||
compactMode: boolean
|
||||
hideIcons: boolean
|
||||
preventDeselect: boolean
|
||||
variant: MultiSelectVariant
|
||||
spanClassName?: string
|
||||
badgeClassName?: string
|
||||
onRemove: (value: string) => void
|
||||
onClear: () => void
|
||||
}
|
||||
|
||||
export const MultiSelectTrigger = React.forwardRef(function MultiSelectTriggerInner<T>(
|
||||
{
|
||||
selectedOptions,
|
||||
placeholder,
|
||||
maxCount,
|
||||
singleLine,
|
||||
compactMode,
|
||||
hideIcons,
|
||||
preventDeselect,
|
||||
variant,
|
||||
spanClassName,
|
||||
badgeClassName,
|
||||
className,
|
||||
disabled,
|
||||
onRemove,
|
||||
onClear,
|
||||
...buttonProps
|
||||
}: MultiSelectTriggerProps<T>,
|
||||
ref: React.ForwardedRef<HTMLButtonElement>,
|
||||
) {
|
||||
const visible = selectedOptions.slice(0, maxCount)
|
||||
const hiddenCount = Math.max(0, selectedOptions.length - visible.length)
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
type="button"
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-haspopup="listbox"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-auto min-h-9 w-full justify-between gap-2 px-3 py-1.5 font-normal',
|
||||
getVariantClass(variant),
|
||||
className,
|
||||
)}
|
||||
{...buttonProps}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'flex min-w-0 flex-1 items-center gap-1 text-left',
|
||||
singleLine ? 'overflow-x-auto whitespace-nowrap' : 'flex-wrap',
|
||||
spanClassName,
|
||||
)}
|
||||
>
|
||||
{selectedOptions.length === 0 ? (
|
||||
<span className="text-muted-foreground truncate">{placeholder}</span>
|
||||
) : compactMode ? (
|
||||
<span>{selectedOptions.length}개 선택</span>
|
||||
) : (
|
||||
<>
|
||||
{visible.map((option) => {
|
||||
const Icon = option.icon
|
||||
return (
|
||||
<Badge
|
||||
key={option.value}
|
||||
variant="secondary"
|
||||
className={cn('max-w-full gap-1', badgeClassName)}
|
||||
style={{ background: option.style?.gradient ?? option.style?.badgeColor }}
|
||||
>
|
||||
{!hideIcons && Icon ? <Icon className="size-3.5" /> : null}
|
||||
<span className="max-w-48 truncate">{option.label}</span>
|
||||
{!preventDeselect ? (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`${option.label} 선택 해제`}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onRemove(option.value)
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onRemove(option.value)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<XIcon className="size-3" />
|
||||
</span>
|
||||
) : null}
|
||||
</Badge>
|
||||
)
|
||||
})}
|
||||
{hiddenCount > 0 ? <Badge variant="secondary">+{hiddenCount}</Badge> : null}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
|
||||
<span className="flex shrink-0 items-center gap-1">
|
||||
{selectedOptions.length > 0 && !preventDeselect ? (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label="전체 선택 해제"
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onClear()
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onClear()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<XCircle className="text-muted-foreground size-4" />
|
||||
</span>
|
||||
) : null}
|
||||
<ChevronDown className="text-muted-foreground size-4" />
|
||||
</span>
|
||||
</Button>
|
||||
)
|
||||
}) as <T>(props: MultiSelectTriggerProps<T> & { ref?: React.ForwardedRef<HTMLButtonElement> }) => React.ReactElement
|
||||
13
src/components/common/multi-select/index.ts
Normal file
13
src/components/common/multi-select/index.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export { MultiSelect } from './MultiSelect'
|
||||
export type {
|
||||
AnimationConfig,
|
||||
MultiSelectGroup,
|
||||
MultiSelectOption,
|
||||
MultiSelectOptions,
|
||||
MultiSelectProps,
|
||||
MultiSelectRef,
|
||||
MultiSelectResponsiveConfig,
|
||||
MultiSelectResponsiveSettings,
|
||||
MultiSelectSelectionMode,
|
||||
MultiSelectVariant,
|
||||
} from './types'
|
||||
89
src/components/common/multi-select/types.ts
Normal file
89
src/components/common/multi-select/types.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import type * as React from 'react'
|
||||
|
||||
export interface AnimationConfig {
|
||||
badgeAnimation?: 'bounce' | 'pulse' | 'wiggle' | 'fade' | 'slide' | 'none'
|
||||
popoverAnimation?: 'scale' | 'slide' | 'fade' | 'flip' | 'none'
|
||||
optionHoverAnimation?: 'highlight' | 'scale' | 'glow' | 'none'
|
||||
duration?: number
|
||||
delay?: number
|
||||
}
|
||||
|
||||
export interface MultiSelectOption<T = unknown> {
|
||||
label: string
|
||||
value: string
|
||||
info?: T
|
||||
icon?: React.ComponentType<React.SVGProps<SVGSVGElement>>
|
||||
disabled?: boolean
|
||||
style?: {
|
||||
badgeColor?: string
|
||||
iconColor?: string
|
||||
gradient?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface MultiSelectGroup<T = unknown> {
|
||||
heading: string
|
||||
options: MultiSelectOption<T>[]
|
||||
}
|
||||
|
||||
export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[]
|
||||
export type MultiSelectSelectionMode = 'single' | 'multiple'
|
||||
export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted'
|
||||
|
||||
export interface MultiSelectResponsiveSettings {
|
||||
maxCount?: number
|
||||
hideIcons?: boolean
|
||||
compactMode?: boolean
|
||||
}
|
||||
|
||||
export interface MultiSelectResponsiveConfig {
|
||||
mobile?: MultiSelectResponsiveSettings
|
||||
tablet?: MultiSelectResponsiveSettings
|
||||
desktop?: MultiSelectResponsiveSettings
|
||||
}
|
||||
|
||||
export interface MultiSelectProps<T = unknown>
|
||||
extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'defaultValue' | 'onChange'> {
|
||||
options: MultiSelectOptions<T>
|
||||
onValueChange: (value: string[]) => void
|
||||
onOptionChange?: (selectedOptions: MultiSelectOption<T>[]) => void
|
||||
onInfoChange?: (infos: T[]) => void
|
||||
defaultValue?: string[]
|
||||
stickySelectedOptions?: MultiSelectOption<T>[]
|
||||
onStickySelectedOptionsChange?: (options: MultiSelectOption<T>[]) => void
|
||||
placeholder?: string
|
||||
animation?: number
|
||||
animationConfig?: AnimationConfig
|
||||
maxCount?: number
|
||||
maxSelected?: number
|
||||
selectionMode?: MultiSelectSelectionMode
|
||||
modalPopover?: boolean
|
||||
variant?: MultiSelectVariant
|
||||
spanClassName?: string
|
||||
badgeClassName?: string
|
||||
hideSelectAll?: boolean
|
||||
searchable?: boolean
|
||||
searchMode?: 'filter' | 'inputOnly'
|
||||
defaultSearchValue?: string
|
||||
onSearchValueChange?: (value: string) => void
|
||||
emptyIndicator?: React.ReactNode
|
||||
autoSize?: boolean
|
||||
singleLine?: boolean
|
||||
popoverClassName?: string
|
||||
responsive?: boolean | MultiSelectResponsiveConfig
|
||||
minWidth?: string
|
||||
maxWidth?: string
|
||||
deduplicateOptions?: boolean
|
||||
resetOnDefaultValueChange?: boolean
|
||||
closeOnSelect?: boolean
|
||||
preventDeselect?: boolean
|
||||
hideOptionCheck?: boolean
|
||||
}
|
||||
|
||||
export interface MultiSelectRef {
|
||||
reset: () => void
|
||||
getSelectedValues: () => string[]
|
||||
setSelectedValues: (values: string[]) => void
|
||||
clear: () => void
|
||||
focus: () => void
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import type { MultiSelectProps, MultiSelectResponsiveSettings } from './types'
|
||||
|
||||
export function useResponsiveSettings(
|
||||
responsive: MultiSelectProps['responsive'],
|
||||
defaultMaxCount: number,
|
||||
): Required<MultiSelectResponsiveSettings> {
|
||||
const [screen, setScreen] = React.useState<'mobile' | 'tablet' | 'desktop'>('desktop')
|
||||
|
||||
React.useEffect(() => {
|
||||
const update = () => {
|
||||
if (window.innerWidth < 640) setScreen('mobile')
|
||||
else if (window.innerWidth < 1024) setScreen('tablet')
|
||||
else setScreen('desktop')
|
||||
}
|
||||
|
||||
update()
|
||||
window.addEventListener('resize', update)
|
||||
return () => window.removeEventListener('resize', update)
|
||||
}, [])
|
||||
|
||||
if (!responsive) {
|
||||
return { maxCount: defaultMaxCount, hideIcons: false, compactMode: false }
|
||||
}
|
||||
|
||||
if (responsive === true) {
|
||||
const defaults = {
|
||||
mobile: { maxCount: 2, hideIcons: false, compactMode: true },
|
||||
tablet: { maxCount: 4, hideIcons: false, compactMode: false },
|
||||
desktop: { maxCount: 6, hideIcons: false, compactMode: false },
|
||||
}
|
||||
return defaults[screen]
|
||||
}
|
||||
|
||||
const current = responsive[screen]
|
||||
return {
|
||||
maxCount: current?.maxCount ?? defaultMaxCount,
|
||||
hideIcons: current?.hideIcons ?? false,
|
||||
compactMode: current?.compactMode ?? false,
|
||||
}
|
||||
}
|
||||
48
src/components/common/multi-select/utils.ts
Normal file
48
src/components/common/multi-select/utils.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
||||
|
||||
export function isGroupedOptions<T>(options: MultiSelectOptions<T>): options is MultiSelectGroup<T>[] {
|
||||
return options.length > 0 && 'heading' in options[0]
|
||||
}
|
||||
|
||||
export function flattenOptions<T>(options: MultiSelectOptions<T>): MultiSelectOption<T>[] {
|
||||
return isGroupedOptions(options) ? options.flatMap((group) => group.options) : options
|
||||
}
|
||||
|
||||
export function deduplicateOptions<T>(options: MultiSelectOptions<T>): MultiSelectOptions<T> {
|
||||
const seen = new Set<string>()
|
||||
|
||||
if (isGroupedOptions(options)) {
|
||||
return options.map((group) => ({
|
||||
...group,
|
||||
options: group.options.filter((option) => {
|
||||
if (seen.has(option.value)) return false
|
||||
seen.add(option.value)
|
||||
return true
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
return options.filter((option) => {
|
||||
if (seen.has(option.value)) return false
|
||||
seen.add(option.value)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
export function arraysEqual(left: string[], right: string[]): boolean {
|
||||
if (left.length !== right.length) return false
|
||||
return left.every((value, index) => value === right[index])
|
||||
}
|
||||
|
||||
export function getVariantClass(variant: 'default' | 'secondary' | 'destructive' | 'inverted'): string {
|
||||
switch (variant) {
|
||||
case 'secondary':
|
||||
return 'bg-secondary text-secondary-foreground'
|
||||
case 'destructive':
|
||||
return 'bg-destructive text-destructive-foreground'
|
||||
case 'inverted':
|
||||
return 'bg-foreground text-background'
|
||||
default:
|
||||
return 'bg-background text-foreground'
|
||||
}
|
||||
}
|
||||
@@ -1,224 +1,183 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
ChevronsLeftIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsRightIcon,
|
||||
ArrowUp,
|
||||
ArrowDown,
|
||||
ArrowUpDown
|
||||
} from 'lucide-react'
|
||||
|
||||
import type { PaginationState, SortingState, RowSelectionState } from '@tanstack/react-table'
|
||||
import {
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel,
|
||||
useReactTable
|
||||
} from '@tanstack/react-table'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { OnChangeFn, PaginationState, Row, RowSelectionState, SortingState } from '@tanstack/react-table'
|
||||
import { flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table'
|
||||
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from '@/components/ui/pagination'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
|
||||
import { usePagination } from './hooks/usePagination'
|
||||
import { DataTableProps, DataTableColumn } from './DataTable.type'
|
||||
|
||||
import { TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {usePreventClickOnDrag} from "@/components/data-table/hooks/usePreventClickOnDrag";
|
||||
import type { DataTableColumn, DataTableProps } from './DataTable.type'
|
||||
import { DataTablePagination } from './DataTablePagination'
|
||||
import { usePreventClickOnDrag } from './hooks/usePreventClickOnDrag'
|
||||
|
||||
export function DataTable<TData>({
|
||||
columns,
|
||||
data,
|
||||
getRowId,
|
||||
highlightRowIds,
|
||||
isClient = true,
|
||||
pageCount: serverPageCount,
|
||||
totalCount: serverTotalCount,
|
||||
onPaginationChange: onServerPaginationChange,
|
||||
onSortingChange: onServerSortingChange,
|
||||
selectMode = 'none',
|
||||
onRowClick,
|
||||
onRowSelectionChange,
|
||||
defaultPageSize = 10,
|
||||
pageSizeOptions = [5, 10, 25, 50],
|
||||
paginationItemsToDisplay = 5
|
||||
}: DataTableProps<TData>) {
|
||||
// Pagination state
|
||||
const [pagination, setPagination] = useState<PaginationState>({
|
||||
pageIndex: 0,
|
||||
pageSize: defaultPageSize
|
||||
})
|
||||
|
||||
// Sorting state
|
||||
export function DataTable<TData, TValue = unknown>({
|
||||
columns,
|
||||
data,
|
||||
getRowId,
|
||||
highlightRowIds,
|
||||
focusRowId,
|
||||
isClient = true,
|
||||
pageCount: serverPageCount,
|
||||
totalCount: serverTotalCount,
|
||||
pagination: externalPagination,
|
||||
onPaginationChange: onServerPaginationChange,
|
||||
onSortingChange: onServerSortingChange,
|
||||
selectMode = 'none',
|
||||
onRowClick,
|
||||
onRowDoubleClick,
|
||||
onRowSelectionChange,
|
||||
defaultPageSize = 10,
|
||||
pageSizeOptions = [5, 10, 25, 50],
|
||||
paginationItemsToDisplay = 5,
|
||||
emptyText = '데이터가 없습니다.',
|
||||
className,
|
||||
maxBodyHeight,
|
||||
}: Readonly<DataTableProps<TData, TValue>>) {
|
||||
const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
|
||||
const [sorting, setSorting] = useState<SortingState>([])
|
||||
|
||||
// Row selection state
|
||||
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const drag = usePreventClickOnDrag()
|
||||
const selectionEnabled = selectMode === 'single' || selectMode === 'multi'
|
||||
|
||||
const drag = usePreventClickOnDrag(6);
|
||||
const enhancedColumns = useMemo<DataTableColumn<TData, TValue>[]>(() => {
|
||||
if (!selectionEnabled) return columns
|
||||
|
||||
const isNotSelection = !['none', 'click-event'].includes(selectMode);
|
||||
const selectionColumn = {
|
||||
id: 'select',
|
||||
header: ({ table }) => selectMode === 'multi' ? (
|
||||
<Checkbox
|
||||
checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && 'indeterminate')}
|
||||
onCheckedChange={(value) => table.toggleAllPageRowsSelected(Boolean(value))}
|
||||
aria-label="전체 선택"
|
||||
/>
|
||||
) : null,
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
checked={row.getIsSelected()}
|
||||
onCheckedChange={(value) => {
|
||||
if (selectMode === 'single') table.resetRowSelection()
|
||||
row.toggleSelected(Boolean(value))
|
||||
}}
|
||||
aria-label="행 선택"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
/>
|
||||
),
|
||||
size: 28,
|
||||
enableSorting: false,
|
||||
} as DataTableColumn<TData, TValue>
|
||||
|
||||
return [selectionColumn, ...columns]
|
||||
}, [columns, selectMode, selectionEnabled])
|
||||
|
||||
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
|
||||
|
||||
// 서버 페이지네이션일 때 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (!isClient && onServerPaginationChange) {
|
||||
onServerPaginationChange(pagination)
|
||||
}
|
||||
}, [pagination, isClient, onServerPaginationChange])
|
||||
setRowSelection({})
|
||||
}, [pagination.pageIndex, pagination.pageSize, sorting])
|
||||
|
||||
// 서버 정렬일 때 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (!isClient && onServerSortingChange) {
|
||||
onServerSortingChange(sorting)
|
||||
}
|
||||
}, [sorting, isClient, onServerSortingChange])
|
||||
const handlePaginationChange = useCallback<OnChangeFn<PaginationState>>(
|
||||
(updater) => {
|
||||
if (isClient) {
|
||||
setInternalPagination(updater)
|
||||
return
|
||||
}
|
||||
|
||||
// Row selection 변경 시 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (isNotSelection && onRowSelectionChange) {
|
||||
const selectedRows = table
|
||||
.getSelectedRowModel()
|
||||
.rows.map(row => row.original)
|
||||
onRowSelectionChange(selectedRows)
|
||||
}
|
||||
}, [rowSelection, selectMode])
|
||||
if (onServerPaginationChange) {
|
||||
onServerPaginationChange(updater)
|
||||
return
|
||||
}
|
||||
|
||||
// selectMode에 따라 select column 추가
|
||||
const enhancedColumns: DataTableColumn<TData, any>[] = [
|
||||
...(isNotSelection
|
||||
? [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) =>
|
||||
selectMode === 'multi' ? (
|
||||
<Checkbox
|
||||
checked={
|
||||
table.getIsAllPageRowsSelected() ||
|
||||
(table.getIsSomePageRowsSelected() && 'indeterminate')
|
||||
}
|
||||
onCheckedChange={value => table.toggleAllPageRowsSelected(!!value)}
|
||||
aria-label='KriSelect all'
|
||||
/>
|
||||
) : null,
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
checked={row.getIsSelected()}
|
||||
onCheckedChange={value => {
|
||||
if (selectMode === 'single') {
|
||||
// single mode: 다른 것 모두 해제
|
||||
table.resetRowSelection()
|
||||
}
|
||||
row.toggleSelected(!!value)
|
||||
}}
|
||||
aria-label='KriSelect row'
|
||||
onClick={e => e.stopPropagation()} // row 클릭 이벤트 전파 방지
|
||||
/>
|
||||
),
|
||||
size: 28,
|
||||
enableSorting: false
|
||||
} as DataTableColumn<TData, any>
|
||||
]
|
||||
: []),
|
||||
...columns
|
||||
]
|
||||
|
||||
// Row 클릭 핸들러
|
||||
const handleRowClick = (row: any) => {
|
||||
switch (selectMode) {
|
||||
case 'none':
|
||||
return
|
||||
|
||||
case 'click-event':
|
||||
if (!onRowClick) return
|
||||
onRowClick(row.original)
|
||||
return
|
||||
|
||||
case 'single':
|
||||
table.resetRowSelection()
|
||||
row.toggleSelected(true)
|
||||
return
|
||||
|
||||
default: // 'multi' 등
|
||||
row.toggleSelected(!row.getIsSelected())
|
||||
return
|
||||
}
|
||||
}
|
||||
setInternalPagination(updater)
|
||||
},
|
||||
[isClient, onServerPaginationChange],
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns: enhancedColumns,
|
||||
pageCount: isClient ? undefined : serverPageCount,
|
||||
state: {
|
||||
sorting,
|
||||
pagination,
|
||||
rowSelection
|
||||
},
|
||||
enableRowSelection: isNotSelection,
|
||||
state: { sorting, pagination, rowSelection },
|
||||
enableRowSelection: selectionEnabled,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onPaginationChange: setPagination,
|
||||
onPaginationChange: handlePaginationChange,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
|
||||
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined,
|
||||
manualPagination: !isClient,
|
||||
manualSorting: !isClient,
|
||||
enableSortingRemoval: false,
|
||||
...(getRowId && { getRowId }), //있으면만 적용
|
||||
...(getRowId ? { getRowId } : {}),
|
||||
})
|
||||
|
||||
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
|
||||
currentPage: table.getState().pagination.pageIndex + 1,
|
||||
totalPages: table.getPageCount(),
|
||||
paginationItemsToDisplay
|
||||
})
|
||||
useEffect(() => {
|
||||
if (!isClient) onServerSortingChange?.(sorting)
|
||||
}, [isClient, onServerSortingChange, sorting])
|
||||
|
||||
const totalCount = isClient ? data.length : (serverTotalCount || 0)
|
||||
useEffect(() => {
|
||||
if (!selectionEnabled) return
|
||||
onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original))
|
||||
}, [onRowSelectionChange, rowSelection, selectionEnabled, table])
|
||||
|
||||
useEffect(() => {
|
||||
if (!focusRowId) return
|
||||
const target = containerRef.current?.querySelector<HTMLElement>(`[data-row-id="${CSS.escape(focusRowId)}"]`)
|
||||
target?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}, [focusRowId, data])
|
||||
|
||||
const handleRowClick = (row: Row<TData>) => {
|
||||
if (selectMode === 'none') return
|
||||
if (selectMode === 'click-event') {
|
||||
onRowClick?.(row.original)
|
||||
return
|
||||
}
|
||||
if (selectMode === 'single') {
|
||||
table.resetRowSelection()
|
||||
row.toggleSelected(true)
|
||||
onRowClick?.(row.original)
|
||||
return
|
||||
}
|
||||
row.toggleSelected(!row.getIsSelected())
|
||||
onRowClick?.(row.original)
|
||||
}
|
||||
|
||||
const handleRowDoubleClick = (row: Row<TData>) => {
|
||||
onRowDoubleClick?.(row.original)
|
||||
}
|
||||
|
||||
const totalCount = isClient ? data.length : (serverTotalCount ?? 0)
|
||||
|
||||
return (
|
||||
<div className='w-full space-y-4'>
|
||||
<div className='rounded-md border'>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<TableRow key={headerGroup.id} className='hover:bg-transparent'>
|
||||
{headerGroup.headers.map(header => {
|
||||
<div className={cn('w-full space-y-4', className)}>
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn('relative w-full overflow-x-auto rounded-md border', maxBodyHeight && 'overflow-y-auto')}
|
||||
style={maxBodyHeight ? { maxHeight: maxBodyHeight } : undefined}
|
||||
>
|
||||
<table className="w-full caption-bottom text-sm">
|
||||
<TableHeader className={cn(maxBodyHeight && 'sticky top-0 z-10 bg-background')}>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id} className="hover:bg-transparent">
|
||||
{headerGroup.headers.map((header) => {
|
||||
const column = header.column
|
||||
const canSort = column.getCanSort()
|
||||
const sorted = column.getIsSorted() as false | 'asc' | 'desc'
|
||||
const headerContent = header.isPlaceholder
|
||||
? null
|
||||
: flexRender(column.columnDef.header, header.getContext())
|
||||
const sorted = column.getIsSorted()
|
||||
const content = header.isPlaceholder ? null : flexRender(column.columnDef.header, header.getContext())
|
||||
|
||||
return (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
className={cn(
|
||||
'content-text-lg font-semibold text-gray-900',
|
||||
column.id === 'actions' && 'w-[140px] text-center'
|
||||
)}
|
||||
className={cn('text-base font-semibold text-foreground', column.id === 'actions' && 'w-[140px] text-center')}
|
||||
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
|
||||
>
|
||||
{header.isPlaceholder ? null : canSort ? (
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
className='px-0 font-semibold content-text-lg flex items-center gap-1'
|
||||
onClick={column.getToggleSortingHandler()}
|
||||
>
|
||||
<span>{headerContent}</span>
|
||||
{sorted === 'asc' && <ArrowUp className='w-3 h-3' />}
|
||||
{sorted === 'desc' && <ArrowDown className='w-3 h-3' />}
|
||||
{!sorted && <ArrowUpDown className='w-3 h-3 text-muted-foreground' />}
|
||||
{!header.isPlaceholder && column.getCanSort() ? (
|
||||
<Button type="button" variant="ghost" className="flex gap-1 px-0 text-base font-semibold" onClick={column.getToggleSortingHandler()}>
|
||||
<span>{content}</span>
|
||||
{sorted === 'asc' ? <ArrowUp className="size-3" /> : sorted === 'desc' ? <ArrowDown className="size-3" /> : <ArrowUpDown className="text-muted-foreground size-3" />}
|
||||
</Button>
|
||||
) : (
|
||||
headerContent
|
||||
)}
|
||||
) : content}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
@@ -226,160 +185,41 @@ export function DataTable<TData>({
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map(row => {
|
||||
const shouldHighlight = highlightRowIds && highlightRowIds.includes(row.id)
|
||||
return (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && 'selected'}
|
||||
onPointerDown={drag.onPointerDown}
|
||||
onPointerMove={drag.onPointerMove}
|
||||
onPointerUp={drag.onPointerUp}
|
||||
onPointerCancel={drag.onPointerCancel}
|
||||
onClick={drag.wrapClick(() => handleRowClick(row))}
|
||||
className={cn(
|
||||
'content-text-base',
|
||||
'[&>td]:py-0 [&>td]:px-2',
|
||||
selectMode !== 'none' && 'cursor-pointer',
|
||||
'data-[state=selected]:bg-slate-100 data-[state=selected]:font-semibold',
|
||||
shouldHighlight && 'bg-emerald-50',
|
||||
)}
|
||||
>
|
||||
{row.getVisibleCells().map(cell => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)})
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={enhancedColumns.length} className='h-24 text-center'>
|
||||
데이터가 없습니다.
|
||||
</TableCell>
|
||||
{table.getRowModel().rows.length ? table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-row-id={row.id}
|
||||
data-state={row.getIsSelected() ? 'selected' : undefined}
|
||||
onPointerDown={drag.onPointerDown}
|
||||
onPointerMove={drag.onPointerMove}
|
||||
onPointerUp={drag.onPointerUp}
|
||||
onPointerCancel={drag.onPointerCancel}
|
||||
onClick={drag.wrapClick(() => handleRowClick(row))}
|
||||
onDoubleClick={onRowDoubleClick ? () => handleRowDoubleClick(row) : undefined}
|
||||
className={cn(
|
||||
'text-base [&>td]:px-2 [&>td]:py-1',
|
||||
(selectMode !== 'none' || onRowDoubleClick) && 'cursor-pointer',
|
||||
'data-[state=selected]:bg-muted data-[state=selected]:font-semibold',
|
||||
highlightRowIds?.includes(row.id) && 'bg-emerald-50',
|
||||
row.id === focusRowId && 'bg-accent',
|
||||
)}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
|
||||
</TableRow>
|
||||
)) : (
|
||||
<TableRow><TableCell colSpan={enhancedColumns.length} className="h-24 text-center">{emptyText}</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className='flex items-center justify-between gap-3 max-sm:flex-col p-2 pt-0'>
|
||||
<p className='text-muted-foreground flex-1 text-sm whitespace-nowrap' aria-live='polite'>
|
||||
Page <span className='text-foreground'>{table.getState().pagination.pageIndex + 1}</span> of{' '}
|
||||
<span className='text-foreground'>{table.getPageCount()}</span>
|
||||
{!isClient && totalCount > 0 && (
|
||||
<span className='ml-2'>
|
||||
(총 <span className='text-foreground'>{totalCount}</span>건)
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div className='grow'>
|
||||
<Pagination>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.firstPage()}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
aria-label='Go to first page'
|
||||
>
|
||||
<ChevronsLeftIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.previousPage()}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
aria-label='Go to previous page'
|
||||
>
|
||||
<ChevronLeftIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
|
||||
{showLeftEllipsis && (
|
||||
<PaginationItem>
|
||||
<PaginationEllipsis />
|
||||
</PaginationItem>
|
||||
)}
|
||||
|
||||
{pages.map(page => {
|
||||
const isActive = page === table.getState().pagination.pageIndex + 1
|
||||
|
||||
return (
|
||||
<PaginationItem key={page}>
|
||||
<Button
|
||||
size='icon'
|
||||
variant={isActive ? 'default' : 'ghost'}
|
||||
onClick={() => table.setPageIndex(page - 1)}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
>
|
||||
{page}
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
)
|
||||
})}
|
||||
|
||||
{showRightEllipsis && (
|
||||
<PaginationItem>
|
||||
<PaginationEllipsis />
|
||||
</PaginationItem>
|
||||
)}
|
||||
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.nextPage()}
|
||||
disabled={!table.getCanNextPage()}
|
||||
aria-label='Go to next page'
|
||||
>
|
||||
<ChevronRightIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.lastPage()}
|
||||
disabled={!table.getCanNextPage()}
|
||||
aria-label='Go to last page'
|
||||
>
|
||||
<ChevronsRightIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
|
||||
<div className='flex flex-1 justify-end'>
|
||||
<Select
|
||||
value={table.getState().pagination.pageSize.toString()}
|
||||
onValueChange={value => {
|
||||
table.setPageSize(Number(value))
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id='results-per-page' className='w-fit whitespace-nowrap' aria-label='Results per page'>
|
||||
<SelectValue placeholder='페이지당 개수' />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{pageSizeOptions.map(size => (
|
||||
<SelectItem key={size} value={size.toString()}>
|
||||
{size} / page
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<DataTablePagination
|
||||
table={table}
|
||||
isClient={isClient}
|
||||
totalCount={totalCount}
|
||||
pageSizeOptions={pageSizeOptions}
|
||||
paginationItemsToDisplay={paginationItemsToDisplay}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table'
|
||||
import type { ColumnDef, PaginationState, SortingState, Updater } from '@tanstack/react-table'
|
||||
|
||||
export type SelectMode = 'none' | 'click-event' | 'single' | 'multi'
|
||||
|
||||
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue> & {
|
||||
enableSorting?: boolean // 정렬 가능 여부 (기본값: false)
|
||||
}
|
||||
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue>
|
||||
|
||||
export interface ServerPaginationParams {
|
||||
pageIndex: number
|
||||
@@ -18,30 +15,26 @@ export interface ServerPaginationResponse<TData> {
|
||||
pageCount: number
|
||||
}
|
||||
|
||||
export interface DataTableProps<TData> {
|
||||
// 필수 props
|
||||
columns: DataTableColumn<TData, any>[]
|
||||
export interface DataTableProps<TData, TValue = unknown> {
|
||||
columns: DataTableColumn<TData, TValue>[]
|
||||
data: TData[]
|
||||
getRowId?: (row: TData, index: number) => string //id 지정
|
||||
getRowId?: (row: TData, index: number) => string
|
||||
highlightRowIds?: string[]
|
||||
// 페이지네이션 모드
|
||||
isClient?: boolean // true: 클라이언트, false: 서버 (기본값: true)
|
||||
|
||||
// 서버 페이지네이션 (isClient=false일 때 필요)
|
||||
focusRowId?: string
|
||||
isClient?: boolean
|
||||
pageCount?: number
|
||||
totalCount?: number
|
||||
onPaginationChange?: (pagination: PaginationState) => void
|
||||
pagination?: PaginationState
|
||||
onPaginationChange?: (updater: Updater<PaginationState>) => void
|
||||
onSortingChange?: (sorting: SortingState) => void
|
||||
|
||||
// 선택 모드
|
||||
selectMode?: SelectMode // 'none' | 'click-event' | 'single' | 'multi' (기본값: 'none')
|
||||
onRowClick?: (selectedRows: TData) => void
|
||||
onRowSelectionChange?: (selectedRows: TData[]) => void
|
||||
|
||||
// 페이지네이션 설정
|
||||
selectMode?: SelectMode
|
||||
onRowClick?: (row: TData) => void
|
||||
onRowDoubleClick?: (row: TData) => void
|
||||
onRowSelectionChange?: (rows: TData[]) => void
|
||||
defaultPageSize?: number
|
||||
pageSizeOptions?: number[]
|
||||
|
||||
// 기타 설정
|
||||
paginationItemsToDisplay?: number
|
||||
}
|
||||
emptyText?: string
|
||||
className?: string
|
||||
maxBodyHeight?: string
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user