Merge pull request 'feature-list' (#2) from feature-list into develop

Reviewed-on: #2
This commit is contained in:
2026-07-14 11:37:51 +09:00
235 changed files with 15393 additions and 7041 deletions

5
.env
View File

@@ -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

View File

@@ -2,8 +2,8 @@ NEXT_PUBLIC_ENV=dev
NEXT_PUBLIC_API_BASE=http://localhost:4000/api
ENV=dev
CONTACT_SERVER=http://localhost:4001
API_CONTACT_SERVER=http://localhost:4001/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

View File

@@ -4,12 +4,7 @@ NEXT_PUBLIC_API_BASE=http://localhost:4000/api
ENV=local
CONTACT_SERVER=http://localhost:4001
API_CONTACT_SERVER=http://localhost:4001/api/v1
#API_NOTIHUB_SERVER=https://localhost:4011/api/v1
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
#API_INTRANET_SERVER=http://localhost:3031/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

View File

@@ -2,8 +2,8 @@ NEXT_PUBLIC_ENV=prod
NEXT_PUBLIC_API_BASE=http://localhost:4000/api
ENV=prod
CONTACT_SERVER=http://localhost:4001
API_CONTACT_SERVER=http://localhost:4001/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

21
.idea/claudeCodeEditorTabs.xml generated Normal file
View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ClaudeCodeEditorTabs">
<option name="activeSessionId" value="ce9acaee-3f3c-42ad-8c11-11ac85f2faf9" />
<option name="openSessionIds">
<list>
<option value="ce9acaee-3f3c-42ad-8c11-11ac85f2faf9" />
</list>
</option>
<option name="sessionPaths">
<map>
<entry key="ce9acaee-3f3c-42ad-8c11-11ac85f2faf9" value="/sessions/2b094ed0-8b05-4852-a909-78cee4b18687" />
</map>
</option>
<option name="sessionTitles">
<map>
<entry key="ce9acaee-3f3c-42ad-8c11-11ac85f2faf9" value="이 다이얼로그에서 미리보기는 우측으로 따로 빼야 할거 같아 y축 높이가 너무 길어" />
</map>
</option>
</component>
</project>

8
.idea/dictionaries/project.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<component name="ProjectDictionaryState">
<dictionary name="project">
<words>
<w>Hder</w>
<w>prjct</w>
</words>
</dictionary>
</component>

2
.npmrc Normal file
View 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}

View File

@@ -1,15 +1,16 @@
import type { NextConfig } from "next";
import { createEnv, createKriNextConfig, env } from "@kri/common/config";
const nextConfig: NextConfig = {
/* config options here */
output: "standalone",
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*`,
},
];
},
@@ -19,17 +20,17 @@ const nextConfig: NextConfig = {
{
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-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;

2123
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -9,6 +9,10 @@
"lint": "eslint"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@kri/common": "^0.16.0",
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
@@ -35,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",
"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",
"@tanstack/react-query-devtools": "^5.91.3",
"@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",

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View 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

View File

@@ -8,25 +8,26 @@ import { ChevronLeft, ChevronRight } from 'lucide-react'
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
import { ProjectInfo } from "@/types/project";
import { PROJECT_SEARCH_COUNT } from "@/const/projectConst";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import { useMounted } from "@/hooks/useMounted";
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_USER_ROLE, FW_USER_ROLE } from "@/const/userConst";
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
import {
useFieldworkUsersQuery,
useRoleListQuery,
useUserCompaniesQuery,
} 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();
@@ -36,23 +37,28 @@ const ProjectAssignPage = () => {
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 companyQuery = useUserCompaniesQuery();
const roleQuery = useRoleListQuery();
const [searchKeyword, setSearchKeyword] = useState("");
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
const projectTopQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, mounted);
const projectArray = projectTopQuery.data ?? [];
const companyArray = companyQuery.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 => r.roleCd >= FW_USER_ROLE)
.filter(r => isFieldWorkUser(r.roleCd))
.map(r => ({ value: String(r.roleCd), label: r.roleNm }));
}, [roleQuery.data]);
@@ -212,14 +218,23 @@ const ProjectAssignPage = () => {
useEffect(() => {
const cmpn = auth.user?.userCmpn ?? "";
if (cmpn) setCompanyFilter(cmpn);
}, [auth.user?.userCmpn]);
const hasAuthCmpn = companyArray.some((company) => company.cmpnId === cmpn);
if (cmpn && hasAuthCmpn) {
setCompanyFilter(cmpn);
return;
}
if (companyFilter && !companyArray.some((company) => company.cmpnId === companyFilter)) {
setCompanyFilter("");
}
}, [auth.user?.userCmpn, companyArray, companyFilter]);
useEffect(() => {
if (roleFilter) return;
if (roleArray.length === 0) return;
const contactRole = roleArray.find(r => r.value === String(CONTACT_USER_ROLE));
const contactRole = roleArray.find(r => r.value === String(CONTACT_INTERVIEWER_ROLE));
setRoleFilter(contactRole ?? roleArray[0]);
}, [roleArray, roleFilter]);
@@ -252,16 +267,18 @@ const ProjectAssignPage = () => {
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}
@@ -269,7 +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 || ""}
@@ -286,11 +303,11 @@ const ProjectAssignPage = () => {
<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">
<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}
@@ -299,18 +316,18 @@ 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">
<th className="p-2 text-left text-base font-medium">
배정된 {roleFilter?.label} ( {assignBase.length}명 )
</th>
</tr>
@@ -324,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>
@@ -346,7 +363,7 @@ const ProjectAssignPage = () => {
<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>
@@ -354,7 +371,7 @@ 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>
@@ -362,7 +379,7 @@ const ProjectAssignPage = () => {
</div>
<div className="min-w-0">
<div className="p-3 bg-black text-white rounded-lg content-text-lg mb-2 h-15">
<div className="p-2 bg-primary text-white rounded-lg text-lg mb-2 h-13">
<KriSingleSelect<ProjectInfo>
items={projectArray}
value={String(sourceProject?.prjctIdx ?? "")}
@@ -383,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}
@@ -392,18 +409,18 @@ 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">
<th className="p-2 text-left text-base font-medium">
배정 가능 {roleFilter?.label} ({ableBase.length}명 )
</th>
</tr>
@@ -417,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>
@@ -439,7 +456,7 @@ const ProjectAssignPage = () => {
<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>
@@ -449,4 +466,4 @@ const ProjectAssignPage = () => {
)
}
export default ProjectAssignPage;
export default ProjectAssignPage;

View File

@@ -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,
@@ -23,7 +23,7 @@ export default async function MainLayoutWrapper({
}) {
const cookieStore = await cookies();
const fontSize = cookieStore.get(CookieKeys.FontSize);
const accessToken = cookieStore.get("access_token")?.value;
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
const initialFontSize = parseFontSize(fontSize?.value);
if (!accessToken) {
@@ -31,8 +31,8 @@ export default async function MainLayoutWrapper({
}
return (
<MainLayout initialFontSize={initialFontSize}>
<AppMainLayout initialFontSize={initialFontSize}>
{children}
</MainLayout>
</AppMainLayout>
);
}
}

View File

@@ -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;

View File

@@ -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;

View File

@@ -1,25 +1,306 @@
"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,
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 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 [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 })
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)
await resetListMutation.mutateAsync({
resetMode: payload.scope === 'result-and-history' ? ListResetMode.HIST : ListResetMode.ALL,
listFilter,
})
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}
onSelectedRowsChange={setSelectedRows}
onRowClick={!canManageList ? handleStartContact : undefined}
onRowDoubleClick={canManageList ? handleStartContact : undefined}
initialPagination={
restoredForThisProject
? { pageIndex: restoredForThisProject.pageIndex, pageSize: restoredForThisProject.pageSize }
: undefined
}
onPaginationChange={setPagination}
focusRowId={restoredForThisProject?.sid}
/>
{canManageList && (
<>
<ListResetDialog 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} onDownload={handleDownloadConfirm} />
<MessageSendDialog
mode={messageSendMode}
listHeaders={headerManageRows}
currentFilter={currentListFilter}
selectedRows={selectedRows}
onSent={refreshList}
/>
<MessageHistoryDialog />
</>
)}
</div>
)
}
export default ListManagePage

View 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;

View File

@@ -1,25 +1,25 @@
'use client'
'use client'
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 "@/components/table-column/UserTableColumn";
import UserUpsertDialog from "@/components/dialog/UserUpsertDialog";
import {UserInfo, UserInfoSaveRequest} from "@/types/user";
import {UserInfoSaveRequest} from "@/types/user";
import UserUploadDialog from "@/components/dialog/UserUploadDialog";
import {useDialog} from "@/hooks/useDialog";
import {downloadBase64File, downloadFile} from "@/lib/utils";
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,
useUserCompaniesQuery,
useUsersQuery,
useUserDetailQuery,
useCheckUserIdDuplicateMutation,
@@ -28,6 +28,8 @@ import {
useUploadUsersExcelMutation,
useDownloadUserExcelTemplateMutation,
} from "@/query/user";
import { useCmpnListQuery } from "@/query/cmpn";
import { isInternalManager } from "@/utils/userRole";
const UserManagePage = () => {
const { showDialog } = useDialog();
@@ -35,7 +37,7 @@ const UserManagePage = () => {
const { auth } = useAuth();
const roleQuery = useRoleListQuery();
const cmpnQuery = useUserCompaniesQuery();
const cmpnQuery = useCmpnListQuery();
const usersQuery = useUsersQuery();
const checkDupMutation = useCheckUserIdDuplicateMutation();
@@ -100,9 +102,9 @@ const UserManagePage = () => {
await upsertMutation.mutateAsync({ mode: dialogMode, data });
if (dialogMode === "create") {
alert("등록 됐습니다.");
alert("등록되었습니다.");
} else {
alert("수정 됐습니다.");
alert("수정되었습니다.");
}
};
@@ -116,17 +118,18 @@ const UserManagePage = () => {
if (!confirm("정말 삭제하시겠습니까?")) return;
await deleteMutation.mutateAsync(userId);
alert("삭제 됐습니다.");
alert("삭제되었습니다.");
};
const uploadFile = async (file: File) => {
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{
alert(`${res.successCount}개의 계정을 생성했습니다.`);
alert(`${res.successCount}개의 계정이 생성되었습니다.`);
}
};
@@ -137,8 +140,8 @@ const UserManagePage = () => {
const blob = new Blob([buffer], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
downloadFile(blob, "사용자 업로드 양식.xlsx");
alert("다운로드 됐습니다.");
downloadFile(blob, "사용자_업로드_양식.xlsx");
alert("다운로드되었습니다.");
} else {
console.log("빈 파일입니다.");
}
@@ -149,26 +152,26 @@ const UserManagePage = () => {
onEdit: handleEdit,
onDelete: handleDelete
},
userRoleArray
userRoleArray,
userCmpnArray
);
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)}
@@ -179,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"
@@ -196,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>
@@ -218,6 +223,7 @@ const UserManagePage = () => {
defaultPageSize={10}
pageSizeOptions={[10, 20, 30, 50]}
getRowId={(row) => row.userId} // row.id = userId
maxBodyHeight="71vh"
/>
</div>
@@ -240,4 +246,4 @@ const UserManagePage = () => {
);
}
export default UserManagePage;
export default UserManagePage;

View File

@@ -1,6 +1,5 @@
import {MessageType, TemplateEmail} from "@/types/messageTemplate";
import { MessageType, type TemplateEmail } from "@kri/common/noti-hub";
import MessageTemplate from "@/components/message-template/MessageTemplate";
import BodyTitle from "@/components/layout/BodyTitle";
const EmailTemplatePage = () => {
@@ -16,10 +15,10 @@ const EmailTemplatePage = () => {
}
return (
<div className="space-y-6 content-text-sm">
<div className="space-y-6 text-sm">
<MessageTemplate pageTitle={"이메일 템플릿 관리"} defaultTemplate={defaultEmailTemplate}/>
</div>
)
}
export default EmailTemplatePage;
export default EmailTemplatePage;

View File

@@ -1,8 +1,7 @@
'use client'
import {MessageType, TemplateSms} from "@/types/messageTemplate";
import { MessageType, type TemplateSms } from "@kri/common/noti-hub";
import MessageTemplate from "@/components/message-template/MessageTemplate";
import BodyTitle from "@/components/layout/BodyTitle";
const SmsTemplatePage = () => {
@@ -18,10 +17,10 @@ const SmsTemplatePage = () => {
}
return (
<div className="space-y-6 content-text-sm">
<div className="space-y-6 text-sm">
<MessageTemplate pageTitle="문자 템플릿 관리" defaultTemplate={defaultSmsTemplate}/>
</div>
)
}
export default SmsTemplatePage;
export default SmsTemplatePage;

View File

@@ -1,6 +1,6 @@
'use client'
import {useMemo, useState} from "react";
import BodyTitle from "@/components/layout/BodyTitle";
import AppPageTitle from "@/components/app-shell/AppPageTitle";
import {Button} from "@/components/ui/button";
import {DataTable} from "@/components/data-table/DataTable";
import {getProjectColumns} from "@/components/table-column/ProjectTableColumn";
@@ -12,20 +12,20 @@ import {
} 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 ProjectCreateDialog from "@/components/dialog/ProjectCreateDialog";
import {useDialog} from "@/hooks/useDialog";
import {useAuth} from "@/hooks/useAuth";
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 { 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();
@@ -88,7 +88,7 @@ const MainPage = () => {
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
@@ -119,6 +119,8 @@ const MainPage = () => {
itrntPrjctCd: projectInfo.itrntPrjctCd,
ownerDept: projectInfo.ownerDept,
ownerFw: projectInfo.ownerFw,
surveyTy: projectInfo.surveyTy,
ff: projectInfo.ff
} as SelectedProject);
router.push("/project/info");
@@ -132,16 +134,18 @@ const MainPage = () => {
itrntPrjctCd: projectInfo.itrntPrjctCd,
ownerDept: projectInfo.ownerDept,
ownerFw: projectInfo.ownerFw,
surveyTy: projectInfo.surveyTy,
ff: projectInfo.ff
} as SelectedProject);
router.push(`/list/manage`);
}
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">
@@ -157,7 +161,7 @@ const MainPage = () => {
}}
/>
{
userRole < FW_USER_ROLE &&
isManager(userRole) &&
<KriMultiSelect
items={statusArray}
value={searchStatus}
@@ -188,14 +192,12 @@ const MainPage = () => {
heightClassName="h-9"
/>
<Button
className="content-text-lg"
onClick={handleSearchClick}
>
검색
</Button>
</div>
<Button
className="content-text-lg"
onClick={handleCreateClick}
>
프로젝트 등록
@@ -209,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>
@@ -227,4 +231,4 @@ const MainPage = () => {
)
}
export default MainPage;
export default MainPage;

View File

@@ -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;

View File

@@ -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;

View 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;

View File

@@ -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;

View 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;

View File

@@ -1,7 +1,7 @@
'use client'
import {useEffect, useState, useCallback, useRef, useMemo} from 'react'
import BodyTitle from '@/components/layout/BodyTitle'
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,8 +11,8 @@ 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 { useDebouncedValue, useMounted } from "@kri/common/hooks";
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
import {
ProjectInfo, ProjectUpdateRequest, ResultCode,
ProjectStatus, ResultCodeType, SurveyType
@@ -23,23 +23,22 @@ import {
SURVEY_TYPE_LABEL,
SURVEY_TYPE_ORDER,
} 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 {useSelectedProject} from "@/hooks/useSelectedProject";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {useAuth} from "@/hooks/useAuth";
import {KriEditor} from "@/components/kri-editor";
import {useRouter} from "next/navigation";
import {
useProjectInfoQuery,
useResultCodesQuery,
useAssignedOutsourceIdsQuery,
useAssignedCmpnIdsQuery,
useUpdateProjectMutation,
useDeleteProjectMutation,
useUploadScenarioImageMutation, useKartProjectListQuery,
} from "@/query/project";
import {useOutsourceUsersQuery} from "@/query/user";
import { useCmpnListQuery } from "@/query/cmpn";
const defaultProjectInfo: ProjectInfo = {
prjctIdx: 0,
@@ -52,6 +51,7 @@ const defaultProjectInfo: ProjectInfo = {
surveyTy: SurveyType.NONE,
surveyPrjctCd: '',
surveyUrl: '',
surveyDashboardUrl: '',
ff: false,
useContactSenario: false,
contactSenario: '',
@@ -62,7 +62,7 @@ const defaultProjectInfo: ProjectInfo = {
type ExternalTab = 'redirect' | 'api'
const baseUrl = 'https://kcont.kric.com'
const sidParam = 'sid=${$SID}'
const sidParam = 'sid=[$SID]'
const externalUrls = {
redirect: {
@@ -95,6 +95,7 @@ const ProjectInfoPage = () => {
const [externalTab, setExternalTab] = useState<ExternalTab>('redirect')
const sessionTempUrlsRef = useRef<Set<string>>(new Set());
const initialProjectInfoRef = useRef<ProjectInfo | null>(null);
const userTeam = auth.user?.userTeam ?? "";
const prjctIdx = selectedProject?.prjctIdx ?? 0;
@@ -108,8 +109,8 @@ const ProjectInfoPage = () => {
// 조회 쿼리들
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled);
const outsourceUsersQuery = useOutsourceUsersQuery(enabled);
const assignedOutsourceQuery = useAssignedOutsourceIdsQuery(prjctIdx, enabled);
const cmpnListQuery = useCmpnListQuery();
const assignedCmpnQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled);
const kartEnabled =
mounted &&
@@ -130,16 +131,16 @@ const ProjectInfoPage = () => {
const uploadScenarioMutation = useUploadScenarioImageMutation(prjctIdx, projectInfo.prjctCd);
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]);
const [outsourceUserArray, setOutsourceUserArray] = useState<string[]>([]);
const [assignCmpnIdArray, setAssignCmpnIdArray] = useState<string[]>([]);
const [changeResultCodeType, setChangeResultCodeType] = useState<ResultCodeType[]>([]);
const outsourceOptionArray: MultiSelectOption[] = useMemo(() => {
const arr = outsourceUsersQuery.data ?? [];
return arr.map((u) => ({
value: u.userId,
label: `${u.userCmpn} / ${u.userName}(${u.userId})`,
const cmpnOptionArray: MultiSelectOption[] = useMemo(() => {
const arr = cmpnListQuery.data ?? [];
return arr.filter((cmpn) => !cmpn.ownCmpn).map((cmpn) => ({
value: cmpn.cmpnId,
label: cmpn.cmpnAlias || cmpn.cmpnId,
}));
}, [outsourceUsersQuery.data]);
}, [cmpnListQuery.data]);
const surveyProjectArray = kartProjectListQuery.data ?? [];
@@ -163,15 +164,15 @@ const ProjectInfoPage = () => {
}
const handleImageUpload = useCallback(
async (file: File): Promise<{ url: string }> => {
async (file: File): Promise<string> => {
if (!projectInfo.prjctCd) {
alert("프로젝트 코드가 없습니다. 잠시 후 다시 시도해주세요.");
return {url: ""};
return "";
}
const url = await uploadScenarioMutation.mutateAsync(file);
sessionTempUrlsRef.current.add(url);
return {url};
return url;
},
[uploadScenarioMutation, projectInfo.prjctCd]
);
@@ -193,10 +194,11 @@ const ProjectInfoPage = () => {
const requestUpdateProject: ProjectUpdateRequest = {
projectInfo: projectInfo,
resultCodeList: updateCodeArray,
assignUserIdList: outsourceUserArray,
assignCmpnIdList: assignCmpnIdArray,
}
await updateMutation.mutateAsync(requestUpdateProject);
initialProjectInfoRef.current = projectInfo;
alert("저장되었습니다.");
}
@@ -214,6 +216,7 @@ const ProjectInfoPage = () => {
useEffect(() => {
if (projectInfoQuery.data) {
setProjectInfo(projectInfoQuery.data);
initialProjectInfoRef.current = projectInfoQuery.data;
}
}, [projectInfoQuery.data]);
@@ -224,49 +227,74 @@ const ProjectInfoPage = () => {
}, [resultCodesQuery.data]);
useEffect(() => {
if (assignedOutsourceQuery.data) {
setOutsourceUserArray(assignedOutsourceQuery.data);
if (assignedCmpnQuery.data) {
setAssignCmpnIdArray(assignedCmpnQuery.data);
}
}, [assignedOutsourceQuery.data]);
}, [assignedCmpnQuery.data]);
useEffect(() => {
if (projectInfo.surveyTy !== SurveyType.EXTERNAL) {
setExternalTab('redirect')
}
}, [projectInfo.surveyTy]);
if (projectInfo.surveyPrjctCd && internalSurvey.has(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]);
if (!mounted) return <LoadingOverlay force />
return next;
})
}
// 설문 연동(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;
setProjectInfo((prev) => ({
...prev,
surveyTy: nextSurveyTy,
surveyPrjctCd: backToInitial ? (initial!.surveyPrjctCd ?? '') : '',
surveyUrl: backToInitial ? (initial!.surveyUrl ?? '') : '',
surveyDashboardUrl: backToInitial ? (initial!.surveyDashboardUrl ?? '') : '',
}))
}
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)}
@@ -277,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>
@@ -286,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
@@ -305,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 || ''}
@@ -317,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 || ''}
@@ -334,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}
@@ -349,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) => {
@@ -361,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>
@@ -371,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"}
@@ -388,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)}
@@ -398,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">
@@ -412,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>
@@ -437,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>
@@ -463,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">
@@ -472,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>
@@ -483,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>
@@ -491,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="컨택 시나리오를 작성해 주세요"
@@ -512,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>

View File

@@ -1,48 +1,38 @@
"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 {useRouter, useSearchParams} from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
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 router = useRouter();
const searchParams = useSearchParams();
const typeParam = searchParams.get("type") ?? "";
const { auth } = useAuth();
const loginMutation = useLoginMutation();
const { get: getSeatNumberStorage, set: setSeatNumberStorage } = useStorage(StorageKeys.SeatNumber);
const [error, setError] = useState<string | null>(null);
const [userId, setUserId] = useState<string>("");
const [userPw, setUserPw] = useState<string>("");
const [seatNum, setSeatNum] = useState<string>("");
const [loginType, setLoginType] = useState<string>("");
const passwordInputRef = useRef<HTMLInputElement | null>(null);
const seatNumberInputRef = useRef<HTMLInputElement | null>(null);
const tryLogin = async () => {
if (!userId) return alert("아이디를 입력해 주세요");
if (!userPw) return alert("PW를 입력해 주세요");
if (loginType === "call" && !seatNum) return alert("자리번호를 입력해 주세요");
if (!userId) return alert("Please enter ID.");
if (!userPw) return alert("Please enter password.");
setError(null);
try {
await loginMutation.mutateAsync({ userId, userPw, seatNum, loginType });
await loginMutation.mutateAsync({ userId, userPw });
} catch (e) {
const err = apiError(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})`);
@@ -50,22 +40,10 @@ const LoginPage = () => {
}
useEffect(() => {
if(auth.user){
if (loginMutation.isSuccess) {
router.replace("/");
}
}, [auth.user]);
// URL 쿼리 파라미터에서 type 수신
useEffect(() => {
setLoginType(typeParam);
if (typeParam === "call") {
setSeatNum(getSeatNumberStorage() ?? "");
} else {
setSeatNum("");
}
}, [typeParam]);
}, [loginMutation.isSuccess, router]);
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
@@ -75,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();
@@ -103,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
@@ -114,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}
@@ -128,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}
@@ -143,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}
@@ -185,4 +132,4 @@ const LoginPage = () => {
);
}
export default LoginPage;
export default LoginPage;

View File

@@ -9,9 +9,8 @@ const LogoutPage = () => {
useEffect(() => {
(async () => {
const { loginType } = await logoutMutation.mutateAsync();
// 기존 로직 그대로: call 타입이면 쿼리 붙여서 이동
router.replace(loginType === "call" ? "/login?type=call" : "/login");
await logoutMutation.mutateAsync();
router.replace("/login");
})();
}, []);

View File

@@ -18,15 +18,8 @@ const redirectPage = async ({
}: redirectPageProps) => {
const { slug } = await params;
const sp = searchParams ? await searchParams : undefined;
//미들 웨어에서 처리
console.log(sp);
const redirectSlug = toRedirectSlug(slug);
console.log(redirectSlug);
if (!redirectSlug) notFound();
return (

View File

@@ -1,7 +1,7 @@
import {NextRequest, NextResponse} from "next/server";
import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/server-api";
import {errorToResponse} from "@/lib/http-util";
import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http";
export const GET = async (req: NextRequest, context: RouteContext) => {
try {
@@ -9,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 });
}
@@ -31,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(
@@ -40,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);
}
};

View 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);
}
};

View File

@@ -1,42 +1,94 @@
//외부 설문에 뎐동 되는 API
// External survey event API.
import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/server-api";
import {errorToResponse} from "@/lib/http-util";
import {getClientIp} from "@/lib/utils";
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";
export const POST = async (req: NextRequest, context: RouteContext) => {
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 } = new URL(req.url);
const {slug = []} = await context.params;
const [action] = slug;
const { searchParams } = req.nextUrl;
const { slug = [] } = await context.params;
const action = toExternalAction((slug[0] ?? "").toLowerCase());
console.log(slug)
const sid = (searchParams.get("sid") ?? "").trim();
const allowAction = ["start", "complete", "screen", "quota"]
if(slug.length === 1 && allowAction.includes(action.toLowerCase()) && sid.length > 0){
const contactApi = await createContactApi();
const pathname = req.nextUrl.pathname;
const h = req.headers;
const log = {
remoteAddr: h.get("x-orig-ip") || getClientIp(req),
uri: h.get("x-orig-uri") || pathname,
url: h.get("x-orig-url") || req.url,
userAgent: h.get("x-orig-user-agent") || h.get("user-agent"),
referer: h.get("x-orig-referer") || h.get("referer"),
origin: h.get("x-orig-origin") || h.get("origin"),
xForwardedFor: h.get("x-forwarded-for"),
forwarded: h.get("forwarded"),
};
//Todo 수정 필요
return new NextResponse(null, { status: 204 });
if (slug.length !== 1 || !action) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
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;

View File

@@ -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);
}
};
};

View File

@@ -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);
}
};
};

View 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);
}
};

View 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);
}
};

View 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);
}
};

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View 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);
}
};

View File

@@ -0,0 +1,53 @@
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 {BulkSendCreateRequest, BulkSendResponse, SendRequestBulk} from "@kri/common/noti-hub";
type MessageSendChannel = "sms" | "email";
const isSendChannel = (value: string): value is MessageSendChannel => value === "sms" || value === "email";
export const PUT = async (req: NextRequest, context: RouteContext) => {
try {
const {slug = []} = await context.params;
const [action, channel] = slug;
const notihubApi = await createNotihubApi();
if (action === "create-bulk" && channel && isSendChannel(channel)) {
const body: BulkSendCreateRequest | null = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
}
const result = await notihubApi.put<string>(`/send-${channel}/create/bulk`, body);
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, channel] = slug;
const notihubApi = await createNotihubApi();
if (action === "bulk" && channel && isSendChannel(channel)) {
const body: SendRequestBulk | null = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
}
const result = await notihubApi.post<BulkSendResponse>(`/send-${channel}/bulk`, body);
return NextResponse.json(result, {status: 200});
}
return NextResponse.json({message: "Not found"}, {status: 404});
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -1,8 +1,8 @@
import {NextRequest, NextResponse} from "next/server";
import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {createNotihubApi} from "@/lib/server-api";
import {errorToResponse} from "@/lib/http-util";
import {Template, TemplateSummary} from "@/types/messageTemplate";
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{
@@ -102,4 +102,4 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
} catch (error: unknown) {
return errorToResponse(error);
}
}
}

View 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);
}
};

View 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);
}
};

View File

@@ -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 {
@@ -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: "요청 바디가 없습니다." },
@@ -186,4 +187,4 @@ export const DELETE = async (req: NextRequest, context: RouteContext) => {
} catch (error: unknown) {
return errorToResponse(error);
}
};
};

View 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);
}
};

View File

@@ -1,8 +1,8 @@
import {NextRequest, NextResponse} from "next/server";
import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/server-api";
import {createContactApi} from "@/lib/http-server";
import {ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project";
import {errorToResponse} from "@/lib/http-util";
import {errorToResponse} from "@kri/common/http";
export const GET = async (req: NextRequest, context: RouteContext) => {
try {
@@ -20,4 +20,4 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
} catch (error: unknown) {
return errorToResponse(error);
}
};
};

View File

@@ -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);
}
};
};

View File

@@ -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
);

View File

@@ -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*******************************/

View 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>
</>
}
/>
);
}

View File

@@ -0,0 +1,219 @@
"use client";
import { ReactNode, useEffect, useMemo, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useMounted } from "@kri/common/hooks";
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]);
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>
);
}

View 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} />;
}

View 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"
/>
);
}

View File

@@ -1,23 +1,25 @@
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import { useDebouncedValue, useMounted } from "@kri/common/hooks";
import {useMemo, useState} from "react";
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
import {useSelectedProject} from "@/hooks/useSelectedProject";
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 enabled = mounted && !!selectedProject;
const topQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, enabled);
const projectArray = useMemo(() => topQuery.data ?? [] ,[topQuery.data]);
const projectArray = useMemo(() => {
const data = topQuery.data ?? [];
return selectedProject ? [selectedProject, ...data] : data;
}, [topQuery.data, selectedProject]);
const handleSelectProject = (info: SelectedProject | null) => {
if (!info) return;
@@ -37,7 +39,6 @@ export const SidebarProjectSearch = () =>{
searchMode="inputOnly"
onSearchValueChange={setSearchKeyword}
placeholder="프로젝트 검색..."
spanClassName="content-text-sm"
widthClassName="w-full"
heightClassName="h-9"
preventDeselect
@@ -47,4 +48,4 @@ export const SidebarProjectSearch = () =>{
getValue={(item) => String(item.prjctIdx)}
/>
);
}
}

View 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} />;
}

View 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";

View 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

View 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

View 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

View 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

View 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

View 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

View 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

View 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

View File

@@ -0,0 +1,6 @@
export const CHART_HEIGHTS = {
DEFAULT: 320,
SMALL: 240,
LARGE: 420,
} as const

View 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>
}

View 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,
}
}

View 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'

View 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: ReturnType<typeof window.setTimeout> | 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
}

View File

@@ -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>
)
}

View 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>
);
}

View 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

View 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

View File

@@ -0,0 +1,76 @@
'use client'
import type { ReactNode } from 'react'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { cn } from '@/lib/utils'
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 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}>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
{description ? <DialogDescription>{description}</DialogDescription> : null}
</DialogHeader>
<div className={cn('min-h-0', bodyClassName)}>{children}</div>
{renderFooter()}
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,26 @@
'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)}
>
<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>
)
}

View File

@@ -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>
)
}

View File

@@ -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>
)
}

View 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

View File

@@ -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>
);
}

View 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

View 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>
)
}

View 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

View File

@@ -0,0 +1,13 @@
export { MultiSelect } from './MultiSelect'
export type {
AnimationConfig,
MultiSelectGroup,
MultiSelectOption,
MultiSelectOptions,
MultiSelectProps,
MultiSelectRef,
MultiSelectResponsiveConfig,
MultiSelectResponsiveSettings,
MultiSelectSelectionMode,
MultiSelectVariant,
} from './types'

View 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
}

View File

@@ -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,
}
}

View 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'
}
}

View File

@@ -1,224 +1,179 @@
'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>
// 서버 페이지네이션일 때 부모에게 알림
useEffect(() => {
if (!isClient && onServerPaginationChange) {
onServerPaginationChange(pagination)
}
}, [pagination, isClient, onServerPaginationChange])
return [selectionColumn, ...columns]
}, [columns, selectMode, selectionEnabled])
// 서버 정렬일 때 부모에게 알림
useEffect(() => {
if (!isClient && onServerSortingChange) {
onServerSortingChange(sorting)
}
}, [sorting, isClient, onServerSortingChange])
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
// Row selection 변경 시 부모에게 알림
useEffect(() => {
if (isNotSelection && onRowSelectionChange) {
const selectedRows = table
.getSelectedRowModel()
.rows.map(row => row.original)
onRowSelectionChange(selectedRows)
}
}, [rowSelection, selectMode])
const handlePaginationChange = useCallback<OnChangeFn<PaginationState>>(
(updater) => {
if (isClient) {
setInternalPagination(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
]
if (onServerPaginationChange) {
onServerPaginationChange(updater)
return
}
// 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 +181,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-0',
(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>
)
}
}

View File

@@ -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
}

View File

@@ -0,0 +1,98 @@
'use client'
import type { Table } from '@tanstack/react-table'
import { ChevronLeftIcon, ChevronRightIcon, ChevronsLeftIcon, ChevronsRightIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from '@/components/ui/pagination'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { usePagination } from './hooks/usePagination'
interface DataTablePaginationProps<TData> {
table: Table<TData>
isClient: boolean
totalCount: number
pageSizeOptions: number[]
paginationItemsToDisplay: number
}
export function DataTablePagination<TData>({
table,
isClient,
totalCount,
pageSizeOptions,
paginationItemsToDisplay,
}: DataTablePaginationProps<TData>) {
'use no memo'
const currentPage = table.getState().pagination.pageIndex + 1
const pageCount = table.getPageCount()
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
currentPage,
totalPages: pageCount,
paginationItemsToDisplay,
})
return (
<div className="flex items-center justify-between gap-3 p-2 pt-0 max-sm:flex-col">
<p className="text-muted-foreground flex-1 whitespace-nowrap text-sm" aria-live="polite">
Page <span className="text-foreground">{currentPage}</span> of{' '}
<span className="text-foreground">{pageCount}</span>
{!isClient && totalCount > 0 ? (
<span className="ml-2">(총 <span className="text-foreground">{totalCount}</span>건)</span>
) : null}
</p>
<div className="grow">
<Pagination>
<PaginationContent>
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.firstPage()} disabled={!table.getCanPreviousPage()} aria-label="첫 페이지">
<ChevronsLeftIcon aria-hidden="true" />
</Button>
</PaginationItem>
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()} aria-label="이전 페이지">
<ChevronLeftIcon aria-hidden="true" />
</Button>
</PaginationItem>
{showLeftEllipsis ? <PaginationItem><PaginationEllipsis /></PaginationItem> : null}
{pages.map((page) => (
<PaginationItem key={page}>
<Button
size="icon"
variant={page === currentPage ? 'default' : 'ghost'}
onClick={() => table.setPageIndex(page - 1)}
aria-current={page === currentPage ? 'page' : undefined}
>
{page}
</Button>
</PaginationItem>
))}
{showRightEllipsis ? <PaginationItem><PaginationEllipsis /></PaginationItem> : null}
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.nextPage()} disabled={!table.getCanNextPage()} aria-label="다음 페이지">
<ChevronRightIcon aria-hidden="true" />
</Button>
</PaginationItem>
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.lastPage()} disabled={!table.getCanNextPage()} aria-label="마지막 페이지">
<ChevronsRightIcon aria-hidden="true" />
</Button>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
<div className="flex flex-1 justify-end">
<Select value={String(table.getState().pagination.pageSize)} onValueChange={(value) => table.setPageSize(Number(value))}>
<SelectTrigger className="w-fit whitespace-nowrap" aria-label="페이지당 개수">
<SelectValue placeholder="페이지당 개수" />
</SelectTrigger>
<SelectContent>
{pageSizeOptions.map((size) => <SelectItem key={size} value={String(size)}>{size} / page</SelectItem>)}
</SelectContent>
</Select>
</div>
</div>
)
}

View File

@@ -6,33 +6,25 @@ interface UsePaginationProps {
paginationItemsToDisplay?: number
}
export function usePagination({
currentPage,
totalPages,
paginationItemsToDisplay = 5
}: UsePaginationProps) {
const { pages, showLeftEllipsis, showRightEllipsis } = useMemo(() => {
const halfDisplay = Math.floor(paginationItemsToDisplay / 2)
let startPage = Math.max(1, currentPage - halfDisplay)
let endPage = Math.min(totalPages, currentPage + halfDisplay)
if (currentPage <= halfDisplay) {
endPage = Math.min(paginationItemsToDisplay, totalPages)
export function usePagination({ currentPage, totalPages, paginationItemsToDisplay = 5 }: UsePaginationProps) {
return useMemo(() => {
if (totalPages <= 0) {
return { pages: [] as number[], showLeftEllipsis: false, showRightEllipsis: false }
}
if (currentPage > totalPages - halfDisplay) {
startPage = Math.max(1, totalPages - paginationItemsToDisplay + 1)
}
const visibleCount = Math.max(1, paginationItemsToDisplay)
const half = Math.floor(visibleCount / 2)
let startPage = Math.max(1, currentPage - half)
let endPage = Math.min(totalPages, startPage + visibleCount - 1)
const pages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i)
if (endPage - startPage + 1 < visibleCount) {
startPage = Math.max(1, endPage - visibleCount + 1)
}
return {
pages,
pages: Array.from({ length: endPage - startPage + 1 }, (_, index) => startPage + index),
showLeftEllipsis: startPage > 1,
showRightEllipsis: endPage < totalPages
showRightEllipsis: endPage < totalPages,
}
}, [currentPage, totalPages, paginationItemsToDisplay])
return { pages, showLeftEllipsis, showRightEllipsis }
}
}, [currentPage, paginationItemsToDisplay, totalPages])
}

View File

@@ -1,48 +1,37 @@
import * as React from "react";
import * as React from 'react'
export const usePreventClickOnDrag = (thresholdPx = 6) => {
const s = React.useRef({ x: 0, y: 0, dragging: false });
export function usePreventClickOnDrag(thresholdPx = 6) {
const state = React.useRef({ x: 0, y: 0, dragging: false })
const onPointerDown = React.useCallback((e: React.PointerEvent) => {
// 좌클릭만
if (e.button !== 0) return;
s.current.x = e.clientX;
s.current.y = e.clientY;
s.current.dragging = false;
}, []);
const onPointerDown = React.useCallback((event: React.PointerEvent) => {
if (event.button !== 0) return
state.current = { x: event.clientX, y: event.clientY, dragging: false }
}, [])
const onPointerMove = React.useCallback(
(e: React.PointerEvent) => {
// 누르고 있을 때만
if (e.buttons === 0) return;
const dx = e.clientX - s.current.x;
const dy = e.clientY - s.current.y;
if (dx * dx + dy * dy >= thresholdPx * thresholdPx) {
s.current.dragging = true;
}
},
[thresholdPx]
);
const onPointerMove = React.useCallback((event: React.PointerEvent) => {
if (event.buttons === 0) return
const dx = event.clientX - state.current.x
const dy = event.clientY - state.current.y
if (dx * dx + dy * dy >= thresholdPx * thresholdPx) state.current.dragging = true
}, [thresholdPx])
const onPointerUp = React.useCallback(() => {
// click은 pointerup 다음에 발생하므로 "다음 tick"에 false로 복구
setTimeout(() => {
s.current.dragging = false;
}, 0);
}, []);
state.current.dragging = false
}, 0)
}, [])
const wrapClick =
(fn: () => void) =>
(e: React.MouseEvent) => {
if (s.current.dragging) {
e.preventDefault();
e.stopPropagation();
return;
}
fn();
};
const wrapClick = React.useCallback(
(callback: () => void) => (event: React.MouseEvent) => {
if (state.current.dragging) {
event.preventDefault()
event.stopPropagation()
return
}
callback()
},
[],
)
return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp, wrapClick };
}
return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp, wrapClick }
}

View File

@@ -0,0 +1,8 @@
export { DataTable } from './DataTable'
export type {
DataTableColumn,
DataTableProps,
SelectMode,
ServerPaginationParams,
ServerPaginationResponse,
} from './DataTable.type'

View File

@@ -0,0 +1,233 @@
'use client'
import { useEffect, useState } from 'react'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
import type { CmpnInfoSaveRequest } from '@/types/cmpn'
import type { DataVerification } from "@kri/common";
import { apiError, NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR } from "@kri/common/http";
export type CmpnUpsertDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
mode?: 'create' | 'edit'
initialData?: Partial<CmpnInfoSaveRequest>
onSubmit: (data: CmpnInfoSaveRequest) => void | Promise<void>
onCheckDuplicate?: (cmpnId: string) => DataVerification | Promise<DataVerification>
}
const createDefaultCmpnInfo = (): CmpnInfoSaveRequest => ({
cmpnId: '',
cmpnAlias: '',
cmpnTel: '',
ownCmpn: false,
memo: '',
})
const CmpnUpsertDialog = ({
dialogId = 'cmpnUpsertDialog',
open,
onOpenChange,
mode = 'create',
initialData,
onSubmit,
onCheckDuplicate,
}: CmpnUpsertDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog();
const [formData, setFormData] = useState<CmpnInfoSaveRequest>(createDefaultCmpnInfo);
const [isCheckedDuplicate, setIsCheckedDuplicate] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const resolvedOpen = open ?? isDialogOpen(dialogId);
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen);
if (nextOpen) {
showDialog(dialogId);
} else {
hideDialog(dialogId);
}
}
useEffect(() => {
if (initialData) {
setFormData({
...createDefaultCmpnInfo(),
...initialData,
});
if (mode === 'edit') {
setIsCheckedDuplicate(true);
}
} else {
setFormData(createDefaultCmpnInfo());
setIsCheckedDuplicate(false);
}
}, [initialData, mode, resolvedOpen]);
const handleInputChange = (field: keyof CmpnInfoSaveRequest, value: string) => {
setFormData((prev) => ({
...prev,
[field]: value,
}));
if (field === 'cmpnId' && mode === 'create') {
setIsCheckedDuplicate(false);
}
}
const handleCheckDuplicate = async () => {
const cmpnId = formData.cmpnId.trim();
if (!cmpnId) {
alert("회사 ID를 입력해주세요.");
return;
}
if (onCheckDuplicate) {
const result = await onCheckDuplicate(cmpnId);
if (!result.success) {
alert(result.errMessage);
setIsCheckedDuplicate(false);
} else {
alert("사용 가능한 회사 ID입니다.");
setIsCheckedDuplicate(true);
}
} else {
setIsCheckedDuplicate(true);
}
}
const handleSubmit = async () => {
if (!formData.cmpnId.trim()) {
alert("회사 ID를 입력해주세요.");
return;
}
if (mode === 'create' && !isCheckedDuplicate) {
alert("회사 ID 중복체크를 해주세요.");
return;
}
if (!formData.cmpnAlias.trim()) {
alert("별칭을 입력해주세요.");
return;
}
setIsSubmitting(true);
try {
await onSubmit({
...formData,
cmpnId: formData.cmpnId.trim(),
cmpnAlias: formData.cmpnAlias.trim(),
cmpnTel: formData.cmpnTel?.trim(),
ownCmpn: mode === 'create' ? false : formData.ownCmpn,
memo: formData.memo?.trim(),
});
handleOpenChange(false);
} catch (e) {
const err = apiError(e, {
fallbackMessage: "Save failed.",
});
console.error(err.status, err.code, err.message);
if (err.code !== NONE_HTTP_ERROR && err.code !== UNKNOWN_HTTP_ERROR) {
alert(err.message);
} else {
alert("저장에 실패했습니다.");
}
} finally {
setIsSubmitting(false);
}
}
return (
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-xl">{mode === 'create' ? '회사 등록' : '회사 수정'}</span>}
description="회사 정보를 입력해주세요."
contentClassName="sm:max-w-[500px] text-sm"
bodyClassName="grid gap-4 py-4"
footer={
<>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
>
취소
</Button>
<Button
type="submit"
onClick={handleSubmit}
disabled={isSubmitting}
>
{mode === 'create' ? "등록" : "수정"}
</Button>
</>
}
>
<div className="grid gap-2">
<Label htmlFor="cmpnId">
회사 ID<span className="text-red-500 ml-1">*</span>
</Label>
<div className="flex gap-2">
<Input
id="cmpnId"
placeholder="Enter company ID"
value={formData.cmpnId}
onChange={(e) => handleInputChange('cmpnId', e.target.value)}
disabled={mode === 'edit'}
/>
{mode === 'create' && (
<Button
variant="outline"
onClick={handleCheckDuplicate}
disabled={!formData.cmpnId.trim() || isCheckedDuplicate}
>
{isCheckedDuplicate ? "확인완료" : "중복체크"}
</Button>
)}
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="cmpnAlias">별칭</Label>
<Input
id="cmpnAlias"
placeholder="Enter alias"
value={formData.cmpnAlias ?? ''}
onChange={(e) => handleInputChange('cmpnAlias', e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="cmpnTel">전화번호</Label>
<Input
id="cmpnTel"
placeholder="Enter tel"
value={formData.cmpnTel ?? ''}
onChange={(e) => handleInputChange('cmpnTel', e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="memo">메모</Label>
<textarea
id="memo"
className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
rows={3}
placeholder="Enter memo"
value={formData.memo ?? ''}
onChange={(e) => handleInputChange('memo', e.target.value)}
/>
</div>
</KriDialog>
)
}
export default CmpnUpsertDialog

Some files were not shown because too many files have changed in this diff Show More