develop #3
5
.env
5
.env
@@ -1 +1,4 @@
|
||||
NEXT_PUBLIC_STORE_KEY = 4b6f7265615265736561726368-496e7465726e6174696f6e616c-49545465616d
|
||||
NEXT_PUBLIC_STORE_KEY = 4b6f7265615265736561726368-496e7465726e6174696f6e616c-49545465616d
|
||||
NEXT_PUBLIC_REQUEST_SVC = kri-contact
|
||||
NEXT_PUBLIC_API_INTERNAL=https://intranet.kric.com
|
||||
NEXT_PUBLIC_CTI_WS_URL=wss://teracall.kric.com:2302
|
||||
@@ -1,10 +1,9 @@
|
||||
NEXT_PUBLIC_ENV=dev
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:4000/api
|
||||
NEXT_PUBLIC_API_INTERNAL=https://intranet.kric.com
|
||||
|
||||
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
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
NEXT_PUBLIC_ENV=local
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:4000/api
|
||||
NEXT_PUBLIC_API_INTERNAL=https://intranet.kric.com
|
||||
|
||||
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
|
||||
@@ -1,10 +1,9 @@
|
||||
NEXT_PUBLIC_ENV=prod
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:4000/api
|
||||
NEXT_PUBLIC_API_INTERNAL=https://intranet.kric.com
|
||||
|
||||
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
21
.idea/claudeCodeEditorTabs.xml
generated
Normal file
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ClaudeCodeEditorTabs">
|
||||
<option name="activeSessionId" value="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>
|
||||
1771
package-lock.json
generated
1771
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -12,7 +12,7 @@
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@kri/common": "^0.12.0",
|
||||
"@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",
|
||||
@@ -41,12 +41,18 @@
|
||||
"@tiptap/starter-kit": "^3.12.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"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",
|
||||
"xlsx": "^0.18.5"
|
||||
@@ -54,6 +60,7 @@
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"babel-plugin-react-compiler": "1.0.0",
|
||||
|
||||
@@ -1,8 +1,196 @@
|
||||
const ListAssignPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
'use client'
|
||||
|
||||
return (<div>This is List Assign Page</div>)
|
||||
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;
|
||||
export default ListAssignPage
|
||||
|
||||
@@ -13,18 +13,21 @@ 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, DEFAULT_COMPANY_NAME, FW_USER_ROLE} from "@/const/userConst";
|
||||
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
|
||||
|
||||
import {
|
||||
useFieldworkUsersQuery, useOutsourceUsersQuery,
|
||||
useFieldworkUsersQuery,
|
||||
useRoleListQuery,
|
||||
} from "@/query/user";
|
||||
import { useCmpnListQuery } from "@/query/cmpn";
|
||||
|
||||
import {
|
||||
useAssignedCmpnIdsQuery,
|
||||
useAssignedFieldworkIdsQuery,
|
||||
useSaveAssignedFieldworkMutation,
|
||||
useProjectTopQuery, useAssignedOutsourceIdsQuery,
|
||||
useProjectTopQuery,
|
||||
} from "@/query/project";
|
||||
import { isFieldWorkUser } from "@/utils/userRole";
|
||||
|
||||
const ProjectAssignPage = () => {
|
||||
const mounted = useMounted();
|
||||
@@ -34,9 +37,9 @@ const ProjectAssignPage = () => {
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0;
|
||||
|
||||
const companyQuery = useOutsourceUsersQuery(enabled);
|
||||
const companyQuery = useCmpnListQuery();
|
||||
const fwUsersQuery = useFieldworkUsersQuery(enabled);
|
||||
const assignedCompanyQuery = useAssignedOutsourceIdsQuery(prjctIdx, enabled);
|
||||
const assignedCmpnIdsQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled);
|
||||
const assignedIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled);
|
||||
const saveAssignMutation = useSaveAssignedFieldworkMutation(prjctIdx);
|
||||
|
||||
@@ -48,18 +51,14 @@ const ProjectAssignPage = () => {
|
||||
const projectArray = projectTopQuery.data ?? [];
|
||||
const companyArray = useMemo(() => {
|
||||
const companies = companyQuery.data ?? [];
|
||||
const assigned = assignedCompanyQuery.data ?? [];
|
||||
const assignedCompanies = companies
|
||||
.filter(c => !assigned.includes(c.userCmpn))
|
||||
.map(c => c.userCmpn);
|
||||
|
||||
return [DEFAULT_COMPANY_NAME, ...assignedCompanies];
|
||||
}, [companyQuery.data, assignedCompanyQuery.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]);
|
||||
|
||||
@@ -219,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]);
|
||||
|
||||
@@ -269,6 +277,8 @@ const ProjectAssignPage = () => {
|
||||
items={companyArray}
|
||||
value={companyFilter}
|
||||
onChange={handleCompanyChange}
|
||||
getValue={(item) => item.cmpnId}
|
||||
getLabel={(item) => item.cmpnAlias || item.cmpnId}
|
||||
placeholder="회사 선택"
|
||||
className="w-56 h-9"
|
||||
useAll={false}
|
||||
@@ -293,7 +303,7 @@ 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-2 bg-black text-white rounded-lg text-lg mb-2 h-13 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">
|
||||
@@ -308,7 +318,7 @@ const ProjectAssignPage = () => {
|
||||
|
||||
<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-2 text-left w-12">
|
||||
<Checkbox
|
||||
@@ -353,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 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>
|
||||
@@ -369,7 +379,7 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<div className="p-2 bg-black text-white rounded-lg text-lg mb-2 h-13">
|
||||
<div className="p-2 bg-primary text-white rounded-lg text-lg mb-2 h-13">
|
||||
<KriSingleSelect<ProjectInfo>
|
||||
items={projectArray}
|
||||
value={String(sourceProject?.prjctIdx ?? "")}
|
||||
@@ -401,7 +411,7 @@ const ProjectAssignPage = () => {
|
||||
|
||||
<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-2 text-left w-12">
|
||||
<Checkbox
|
||||
@@ -446,7 +456,7 @@ const ProjectAssignPage = () => {
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
className="bg-black hover:bg-gray-800 px-12 h-9 text-base font-medium"
|
||||
className=" px-12 h-9 text-base font-medium"
|
||||
>
|
||||
저장
|
||||
</Button>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
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";
|
||||
@@ -31,8 +31,8 @@ export default async function MainLayoutWrapper({
|
||||
}
|
||||
|
||||
return (
|
||||
<MainLayout initialFontSize={initialFontSize}>
|
||||
<AppMainLayout initialFontSize={initialFontSize}>
|
||||
{children}
|
||||
</MainLayout>
|
||||
</AppMainLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,166 @@
|
||||
const ListContactPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
'use client'
|
||||
|
||||
return (<div>This is List Contact Page</div>)
|
||||
import { Suspense, useEffect, useMemo, useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { ArrowLeft, CalendarClock } from "lucide-react";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useDialog } from "@/hooks/useDialog";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useListDetailQuery, useListHeaderQuery, useListReserveByUserQuery, useUpdateListMutation } from "@/query/list";
|
||||
import { useProjectInfoQuery, useResultCodesQuery } from "@/query/project";
|
||||
import ListContactInfoPanel, { buildInitialValues } from "@/components/list-contact/ListContactInfoPanel";
|
||||
import ListContactEventPanel from "@/components/list-contact/ListContactEventPanel";
|
||||
import ListUpdateHistoryPanel from "@/components/list-contact/ListUpdateHistoryPanel";
|
||||
import ReservationListDialog from "@/components/dialog/ReservationListDialog";
|
||||
import { createEmptyListFilter, type listHeader } from "@/types/list";
|
||||
import type { ResultCode } from "@/types/project";
|
||||
import { isManager } from "@/utils/userRole";
|
||||
|
||||
const ListContactPageContent = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const sid = searchParams.get("sid") ?? "";
|
||||
|
||||
const mounted = useMounted();
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
const { isDialogOpen, showDialog } = useDialog();
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const prjctCd = selectedProject?.prjctCd ?? "";
|
||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
|
||||
const userId = auth?.user?.userId ?? "";
|
||||
const userRole = auth?.user?.userRole ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0 && !!sid;
|
||||
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, mounted && prjctIdx > 0);
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, mounted && prjctIdx > 0);
|
||||
const listDetailQuery = useListDetailQuery(prjctIdx, sid, enabled);
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, mounted && prjctIdx > 0);
|
||||
const updateListMutation = useUpdateListMutation(prjctIdx);
|
||||
|
||||
const reservationDialogOpen = isDialogOpen('reservationListDialog');
|
||||
const reserveByUserQuery = useListReserveByUserQuery(prjctIdx, userId, reservationDialogOpen);
|
||||
|
||||
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]);
|
||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]);
|
||||
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const initialFormValues = useMemo(
|
||||
() => buildInitialValues(listHeaders, listDetailQuery.data),
|
||||
[listHeaders, listDetailQuery.data],
|
||||
);
|
||||
const [formValues, setFormValues] = useState<Record<number, string>>(initialFormValues);
|
||||
|
||||
useEffect(() => {
|
||||
setFormValues(initialFormValues);
|
||||
}, [initialFormValues]);
|
||||
|
||||
useEffect(() => {
|
||||
if (sid) return;
|
||||
alert("sid가 없으면 진행할 수 없습니다.");
|
||||
router.back();
|
||||
}, [sid, router]);
|
||||
|
||||
const handleNavigateToSid = (nextSid: string) => {
|
||||
router.push(`/list/contact?sid=${encodeURIComponent(nextSid)}`);
|
||||
};
|
||||
|
||||
const handleGoToListManage = () => {
|
||||
router.push("/list/manage");
|
||||
};
|
||||
|
||||
const handleFieldChange = (listHderId: number, value: string) => {
|
||||
setFormValues((prev) => ({ ...prev, [listHderId]: value }));
|
||||
};
|
||||
|
||||
const handleToggleEdit = async () => {
|
||||
if (!isEditing) {
|
||||
setIsEditing(true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await updateListMutation.mutateAsync({
|
||||
updateContents: Object.fromEntries(Object.entries(formValues)),
|
||||
listFilter: { ...createEmptyListFilter(), sidSet: [sid] },
|
||||
});
|
||||
alert("저장되었습니다.");
|
||||
setIsEditing(false);
|
||||
listDetailQuery.refetch();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert("저장 중 오류가 발생했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
if (!sid) return null;
|
||||
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<div className="flex items-center gap-3 w-1/2 pr-5">
|
||||
<Button type="button" variant="outline" size="icon" onClick={handleGoToListManage} aria-label="목록으로">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold tracking-tight">컨택 진행</h1>
|
||||
<span className="text-2xl font-bold tracking-tight">SID: {sid}</span>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('reservationListDialog')}>
|
||||
<CalendarClock className="h-4 w-4" />
|
||||
예약리스트 조회
|
||||
</Button>
|
||||
<Button type="button" disabled={updateListMutation.isPending} onClick={handleToggleEdit}>
|
||||
{isEditing ? '저장' : '수정'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
|
||||
<div className="h-[80vh] space-y-4 overflow-y-auto">
|
||||
<ListContactInfoPanel
|
||||
prjctIdx={prjctIdx}
|
||||
sid={sid}
|
||||
itrntPrjctCd={itrntPrjctCd}
|
||||
userRole={userRole}
|
||||
isEditing={isEditing}
|
||||
listHeaders={listHeaders}
|
||||
detail={listDetailQuery.data}
|
||||
surveyUrl={projectInfoQuery.data?.surveyUrl}
|
||||
formValues={formValues}
|
||||
onFieldChange={handleFieldChange}
|
||||
onSaved={() => listDetailQuery.refetch()}
|
||||
/>
|
||||
|
||||
{isManager(userRole) ? (
|
||||
<ListUpdateHistoryPanel prjctIdx={prjctIdx} sid={sid} listHeaders={listHeaders} />
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<ListContactEventPanel
|
||||
prjctIdx={prjctIdx}
|
||||
sid={sid}
|
||||
prjctCd={prjctCd}
|
||||
userId={userId}
|
||||
userRole={userRole}
|
||||
resultCodes={resultCodeArray}
|
||||
useContactSenario={projectInfoQuery.data?.useContactSenario ?? false}
|
||||
contactSenario={projectInfoQuery.data?.contactSenario}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ReservationListDialog reservations={reserveByUserQuery.data ?? []} onSelectReservation={handleNavigateToSid} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListContactPage;
|
||||
const ListContactPage = () => (
|
||||
<Suspense fallback={null}>
|
||||
<ListContactPageContent />
|
||||
</Suspense>
|
||||
);
|
||||
|
||||
export default ListContactPage;
|
||||
|
||||
@@ -1,27 +1,17 @@
|
||||
'use client'
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { PaginationState, SortingState } from '@tanstack/react-table'
|
||||
import {
|
||||
Download,
|
||||
FileClock,
|
||||
Funnel,
|
||||
Mail,
|
||||
MessageSquareMore,
|
||||
PencilLine,
|
||||
RotateCcw,
|
||||
Upload,
|
||||
} from 'lucide-react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DataTable } from '@/components/data-table/DataTable'
|
||||
import type { DataTableColumn } from '@/components/data-table/DataTable.type'
|
||||
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||
import { LoadingOverlay } from '@/components/common/LoadingOverlay'
|
||||
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,
|
||||
@@ -30,120 +20,37 @@ import {
|
||||
useDownloadListUpdateHistoryMutation,
|
||||
useDownloadUploadHistoryFileMutation,
|
||||
useListHeaderQuery,
|
||||
useListSearchQuery,
|
||||
useListUploadHistoryQuery,
|
||||
useResetListMutation,
|
||||
useUpdateListHeaderMutation,
|
||||
useUpdateListMutation,
|
||||
useUploadListExcelMutation,
|
||||
} from '@/query/list'
|
||||
import { useResultCodesQuery } from '@/query/project'
|
||||
import { getListColumns, ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||
import {
|
||||
createEmptyListFilter,
|
||||
FilterRow,
|
||||
ListEventHistoryBase,
|
||||
ListDownloadMode,
|
||||
ListDownloadPayload,
|
||||
listHeader,
|
||||
ListFilterMatchType,
|
||||
ListFilterOperator,
|
||||
ListFilterTarget,
|
||||
ListOtherItemFilterCondition,
|
||||
type LastListVisit,
|
||||
type ListDownloadMode,
|
||||
type ListDownloadPayload,
|
||||
type ListFilter,
|
||||
type ListFilterTarget,
|
||||
type listHeader,
|
||||
ListResetMode,
|
||||
ListResetScope,
|
||||
ListSearchRequest,
|
||||
ListUploadRequest,
|
||||
type ListResetScope,
|
||||
type ListUploadRequest,
|
||||
} from '@/types/list'
|
||||
import { ResultCode, ResultCodeType } from '@/types/project'
|
||||
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 ListBatchEditDialog, { BatchEditRow } from '@/components/dialog/ListBatchEditDialog'
|
||||
import ListFilterDialog from '@/components/dialog/ListFilterDialog'
|
||||
import ListDownloadDialog from '@/components/dialog/ListDownloadDialog'
|
||||
import MessageSendDialog, {
|
||||
MessageSendMode,
|
||||
MessageSendPayload,
|
||||
MessageTemplateOption,
|
||||
} from '@/components/dialog/MessageSendDialog'
|
||||
import MessageHistoryDialog, { MessageHistoryRow } from '@/components/dialog/MessageHistoryDialog'
|
||||
import MessageSendDialog, { type MessageSendMode } from '@/components/dialog/MessageSendDialog'
|
||||
import MessageHistoryDialog from '@/components/dialog/MessageHistoryDialog'
|
||||
import { downloadBase64File, downloadFile, XLSX_MIME_TYPE } from '@kri/common/browser'
|
||||
|
||||
const messageTemplateMock: MessageTemplateOption[] = [
|
||||
{
|
||||
id: 'sms-1',
|
||||
name: '[SMS] Contact Notice',
|
||||
title: 'Survey Request',
|
||||
body: 'Please participate in the survey.',
|
||||
},
|
||||
{
|
||||
id: 'email-1',
|
||||
name: '[EMAIL] Contact Notice',
|
||||
title: 'Survey Participation Guide',
|
||||
body: 'Please click the link and complete the survey.',
|
||||
},
|
||||
]
|
||||
|
||||
const messageHistoryMock: MessageHistoryRow[] = [
|
||||
{
|
||||
id: 1,
|
||||
type: 'sms',
|
||||
title: 'Survey Request',
|
||||
templateName: 'SMS Template A',
|
||||
sendInfo: '010-xxxx-xxxx',
|
||||
targetHeader: 'Phone Number',
|
||||
targetCount: 405,
|
||||
successCount: 405,
|
||||
failCount: 0,
|
||||
createdAt: '03.06 14:37',
|
||||
sendAt: '03.06 14:30 (Reserve)',
|
||||
status: 'Done',
|
||||
templatePreview: 'Please participate in the survey.',
|
||||
targetPreview: ['010-1234-5678', '010-1234-1111'],
|
||||
successPreview: ['sid 1: success', 'sid 2: success'],
|
||||
failPreview: [],
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
type: 'email',
|
||||
title: 'Survey Answer Request',
|
||||
templateName: 'EMAIL Template A',
|
||||
sendInfo: 'info@kric.com',
|
||||
targetHeader: 'Email',
|
||||
targetCount: 405,
|
||||
successCount: 395,
|
||||
failCount: 10,
|
||||
createdAt: '03.06 14:37',
|
||||
sendAt: '03.06 14:47 (Instant)',
|
||||
status: 'Requested',
|
||||
templatePreview: 'Please click the link and complete the survey.',
|
||||
targetPreview: ['aa@kric.com', 'bb@kric.com'],
|
||||
successPreview: ['sid 3: success', 'sid 4: success'],
|
||||
failPreview: ['sid 5: bounce', 'sid 6: invalid'],
|
||||
},
|
||||
]
|
||||
|
||||
const toSidSet = (value: string) =>
|
||||
value
|
||||
.split(',')
|
||||
.map((item) => item.trim())
|
||||
.filter((item) => item.length > 0)
|
||||
|
||||
const toFilterCondition = (row: FilterRow, usesListValue: boolean): Omit<ListOtherItemFilterCondition, 'listHderId'> => {
|
||||
const values = usesListValue ? row.multiValues : [row.textValue.trim()]
|
||||
|
||||
if (row.operator === 'eq') {
|
||||
return { operator: ListFilterOperator.POSITIVE, matchType: ListFilterMatchType.EXACT, values }
|
||||
}
|
||||
if (row.operator === 'neq') {
|
||||
return { operator: ListFilterOperator.NEGATIVE, matchType: ListFilterMatchType.EXACT, values }
|
||||
}
|
||||
if (row.operator === 'contains') {
|
||||
return { operator: ListFilterOperator.POSITIVE, matchType: ListFilterMatchType.CONTAINS, values }
|
||||
}
|
||||
return { operator: ListFilterOperator.NEGATIVE, matchType: ListFilterMatchType.CONTAINS, values }
|
||||
}
|
||||
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
|
||||
@@ -158,28 +65,32 @@ const downloadArrayBuffer = (buffer: ArrayBuffer, filename: string, type = 'appl
|
||||
}
|
||||
|
||||
const ListManagePage = () => {
|
||||
const router = useRouter()
|
||||
const mounted = useMounted()
|
||||
const { auth } = useAuth()
|
||||
const { showDialog } = useDialog()
|
||||
const { selectedProject } = useSelectedProject()
|
||||
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const [searchContactResult, setSearchContactResult] = useState<string[]>([])
|
||||
const [searchInterviewResult, setSearchInterviewResult] = useState<string[]>([])
|
||||
const [searchSurveyResult, setSearchSurveyResult] = useState<string[]>([])
|
||||
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 })
|
||||
const [sorting, setSorting] = useState<SortingState>([])
|
||||
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject()
|
||||
|
||||
const [downloadMode, setDownloadMode] = useState<ListDownloadMode>('list')
|
||||
const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('email')
|
||||
const [filterRows, setFilterRows] = useState<FilterRow[]>([])
|
||||
const [batchRows, setBatchRows] = useState<BatchEditRow[]>([])
|
||||
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 userRole = auth?.user?.userRole ?? 9000
|
||||
const prjctName = selectedProject?.prjctName ?? '';
|
||||
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)
|
||||
@@ -188,7 +99,6 @@ const ListManagePage = () => {
|
||||
const uploadListExcelMutation = useUploadListExcelMutation(prjctIdx)
|
||||
const updateListHeaderMutation = useUpdateListHeaderMutation(prjctIdx)
|
||||
const resetListMutation = useResetListMutation(prjctIdx)
|
||||
const updateListMutation = useUpdateListMutation(prjctIdx)
|
||||
const downloadListMutation = useDownloadListMutation(prjctIdx)
|
||||
const downloadListUpdateHistoryMutation = useDownloadListUpdateHistoryMutation(prjctIdx)
|
||||
const downloadListEventHistoryMutation = useDownloadListEventHistoryMutation(prjctIdx)
|
||||
@@ -196,47 +106,23 @@ const ListManagePage = () => {
|
||||
const downloadUploadHistoryFileMutation = useDownloadUploadHistoryFileMutation(prjctIdx)
|
||||
|
||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
||||
const headerManageRows = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||
|
||||
const listSearchRequest = useMemo<ListSearchRequest>(() => {
|
||||
const sort = sorting?.[0] ?? { id: 'sid', desc: false as const }
|
||||
const listFilter = createEmptyListFilter()
|
||||
listFilter.sidSet = toSidSet(searchText)
|
||||
listFilter.memoConditions = []
|
||||
listFilter.otherItemConditions = filterRows
|
||||
.map((row) => {
|
||||
const usesListValue = (listHeaderQuery.data ?? []).some(
|
||||
(header) => header.listHderId === row.headerId && (header.filterContents?.length ?? 0) > 0,
|
||||
)
|
||||
|
||||
return {
|
||||
listHderId: row.headerId,
|
||||
...toFilterCondition(row, usesListValue),
|
||||
}
|
||||
})
|
||||
.filter((item) => item.values.some((value) => value.trim().length > 0))
|
||||
|
||||
return {
|
||||
listFilter,
|
||||
pageRequest: {
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
sortBy: sort.id,
|
||||
sortDir: sort.desc ? 'desc' : 'asc',
|
||||
},
|
||||
// 컨택 진행 화면에서 돌아왔을 때 1회만 복원하고, 재방문 시 다시 나타나지 않도록 즉시 지운다.
|
||||
// ListSearchTable이 첫 마운트될 때 초기 페이지네이션 값이 확정돼 있어야 하므로(useState는 이후 prop
|
||||
// 변경을 반영하지 않음), selectedProject 하이드레이션이 끝나기 전에는 ListSearchTable을 아예 그리지 않는다.
|
||||
useEffect(() => {
|
||||
if (!mounted || !isSelectedProjectHydrated || restoreResolved) return
|
||||
const stored = getLastListVisit()
|
||||
if (stored) {
|
||||
setRestoredVisit(stored)
|
||||
removeLastListVisit()
|
||||
}
|
||||
}, [filterRows, listHeaderQuery.data, pagination.pageIndex, pagination.pageSize, searchText, sorting])
|
||||
setRestoreResolved(true)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [mounted, isSelectedProjectHydrated, restoreResolved])
|
||||
|
||||
const listSearchQuery = useListSearchQuery(prjctIdx, listSearchRequest, enabled)
|
||||
|
||||
const columns = useMemo<DataTableColumn<ListTableRow, unknown>[]>(() => {
|
||||
if (!listHeaderQuery.data) return []
|
||||
return getListColumns(listHeaderQuery.data, resultCodeArray, userRole)
|
||||
}, [listHeaderQuery.data, resultCodeArray, userRole])
|
||||
|
||||
const viewList = useMemo<ListTableRow[]>(
|
||||
() => (listSearchQuery.data?.content ?? []).map((row) => ({ ...row, ...row.itemList })),
|
||||
[listSearchQuery.data],
|
||||
)
|
||||
const restoredForThisProject = restoredVisit?.prjctIdx === prjctIdx ? restoredVisit : undefined
|
||||
|
||||
const selectedSidSet = useMemo(
|
||||
() =>
|
||||
@@ -247,50 +133,30 @@ const ListManagePage = () => {
|
||||
[selectedRows],
|
||||
)
|
||||
|
||||
const buildTargetFilter = (target: ListFilterTarget) => {
|
||||
if (target === 'all') return createEmptyListFilter()
|
||||
if (target === 'selected') {
|
||||
return {
|
||||
...createEmptyListFilter(),
|
||||
sidSet: selectedSidSet,
|
||||
}
|
||||
}
|
||||
return listSearchRequest.listFilter
|
||||
const refreshList = () => {
|
||||
setListRefreshKey((prev) => prev + 1)
|
||||
}
|
||||
|
||||
const totalCount = listSearchQuery.data?.totalElements ?? 0
|
||||
const pageCount = listSearchQuery.data?.totalPages ?? 0
|
||||
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 headerOptions = useMemo(
|
||||
() =>
|
||||
(listHeaderQuery.data ?? []).map((header) => ({
|
||||
id: header.listHderId,
|
||||
label: header.listHderNm,
|
||||
})),
|
||||
[listHeaderQuery.data],
|
||||
)
|
||||
|
||||
const headerManageRows = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||
|
||||
const filterHeaderOptions = useMemo(
|
||||
() =>
|
||||
(listHeaderQuery.data ?? [])
|
||||
.filter((header) => header.useFilter)
|
||||
.map((header) => ({
|
||||
id: header.listHderId,
|
||||
label: header.listHderNm,
|
||||
values: header.filterContents ?? [],
|
||||
})),
|
||||
[listHeaderQuery.data],
|
||||
)
|
||||
|
||||
const messageTargetHeaders = useMemo(() => {
|
||||
const matched = headerOptions.filter((header) => /email|phone|tel/i.test(header.label))
|
||||
return matched.length > 0 ? matched : headerOptions.slice(0, 1)
|
||||
}, [headerOptions])
|
||||
|
||||
const handleSearchClick = () => {
|
||||
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
||||
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) => {
|
||||
@@ -309,7 +175,7 @@ const ListManagePage = () => {
|
||||
resetMode: payload.scope === 'result-and-history' ? ListResetMode.HIST : ListResetMode.ALL,
|
||||
listFilter,
|
||||
})
|
||||
await listSearchQuery.refetch()
|
||||
refreshList()
|
||||
}
|
||||
|
||||
const handleUploadConfirm = async (file: File, request: ListUploadRequest) => {
|
||||
@@ -323,7 +189,7 @@ const ListManagePage = () => {
|
||||
alert(`${res.successCount}개의 리스트를 업로드했습니다.`);
|
||||
}
|
||||
|
||||
await listSearchQuery.refetch()
|
||||
refreshList()
|
||||
}
|
||||
|
||||
const handleDownloadTemplate = async () => {
|
||||
@@ -340,20 +206,6 @@ const ListManagePage = () => {
|
||||
await updateListHeaderMutation.mutateAsync(rows)
|
||||
}
|
||||
|
||||
const handleFilterConfirm = async (rows: FilterRow[]) => {
|
||||
setFilterRows(rows)
|
||||
}
|
||||
|
||||
const handleBatchConfirm = async (rows: BatchEditRow[]) => {
|
||||
setBatchRows(rows)
|
||||
const updateContents = Object.fromEntries(rows.map((row) => [String(row.headerId), row.value]))
|
||||
await updateListMutation.mutateAsync({
|
||||
updateContents,
|
||||
listFilter: buildTargetFilter('filtered'),
|
||||
})
|
||||
await listSearchQuery.refetch()
|
||||
}
|
||||
|
||||
const handleDownloadConfirm = async (payload: ListDownloadPayload) => {
|
||||
const listFilter = buildTargetFilter(payload.target)
|
||||
|
||||
@@ -384,160 +236,69 @@ const ListManagePage = () => {
|
||||
downloadArrayBuffer(buffer, `${prjctName} contact-history.xlsx`)
|
||||
}
|
||||
|
||||
const handleMessageSendConfirm = async (payload: MessageSendPayload) => {
|
||||
void payload
|
||||
alert('Message send action callback placeholder.')
|
||||
}
|
||||
|
||||
if (!mounted) return <LoadingOverlay force />
|
||||
if (!mounted || !restoreResolved) return <LoadingOverlayAdapter force />
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex flex-1 items-center gap-2 flex-wrap">
|
||||
<Button variant="destructive" className="text-base gap-2" onClick={() => showDialog('listResetDialog')}>
|
||||
<RotateCcw className="w-4 h-4" />
|
||||
리스트 초기화
|
||||
</Button>
|
||||
<Button className="text-base" onClick={() => showDialog('listHeaderManageDialog')}>
|
||||
헤더 관리
|
||||
</Button>
|
||||
<Button className="text-base gap-2" onClick={() => showDialog('listUploadDialog')}>
|
||||
<Upload className="w-4 h-4" />
|
||||
리스트 업로드
|
||||
</Button>
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => openDownloadDialog('list')}>
|
||||
<Download className="w-4 h-4" />
|
||||
리스트
|
||||
</Button>
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => openDownloadDialog('contact-history')}>
|
||||
<Download className="w-4 h-4" />
|
||||
컨택 이력
|
||||
</Button>
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => openDownloadDialog('list-change-history')}>
|
||||
<Download className="w-4 h-4" />
|
||||
리스트 변경 이력
|
||||
</Button>
|
||||
<Button className="text-base gap-2" onClick={() => openDownloadDialog('upload-file')}>
|
||||
<Download className="w-4 h-4" />
|
||||
업로드 파일(.zip)
|
||||
</Button>
|
||||
</div>
|
||||
<Button className="text-base bg-blue gap-2" onClick={() => openMessageDialog('email')}>
|
||||
<Mail className="w-4 h-4" />
|
||||
이메일 발송
|
||||
</Button>
|
||||
<Button className="text-base bg-blue gap-2" onClick={() => openMessageDialog('sms')}>
|
||||
<MessageSquareMore className="w-4 h-4" />
|
||||
문자 발송
|
||||
</Button>
|
||||
<Button className="text-base gap-2" onClick={() => showDialog('messageHistoryDialog')}>
|
||||
<FileClock className="w-4 h-4" />
|
||||
발송 이력
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Input
|
||||
placeholder="Search SID"
|
||||
className="w-100 h-9 bg-white"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
/>
|
||||
<KriMultiSelect
|
||||
items={resultCodeArray.filter((item) => item.resultCdTy === ResultCodeType.CONTACT)}
|
||||
value={searchContactResult}
|
||||
onChange={setSearchContactResult}
|
||||
getValue={(item) => String(item.resultCd)}
|
||||
getLabel={(item) => item.resultCdLbl}
|
||||
placeholder="컨택 결과"
|
||||
widthClassName="w-70"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
<KriMultiSelect
|
||||
items={resultCodeArray.filter((item) => item.resultCdTy === ResultCodeType.INTERVIEW)}
|
||||
value={searchInterviewResult}
|
||||
onChange={setSearchInterviewResult}
|
||||
getValue={(item) => String(item.resultCd)}
|
||||
getLabel={(item) => item.resultCdLbl}
|
||||
placeholder="면접 결과"
|
||||
widthClassName="w-70"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
<KriMultiSelect
|
||||
items={resultCodeArray.filter((item) => item.resultCdTy === ResultCodeType.SURVEY)}
|
||||
value={searchSurveyResult}
|
||||
onChange={setSearchSurveyResult}
|
||||
getValue={(item) => String(item.resultCd)}
|
||||
getLabel={(item) => item.resultCdLbl}
|
||||
placeholder="설문 결과"
|
||||
widthClassName="w-70"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
<Button className="text-lg" onClick={handleSearchClick}>
|
||||
검색
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listFilterDialog')}>
|
||||
<Funnel className="w-4 h-4" />
|
||||
필터
|
||||
</Button>
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listBatchEditDialog')}>
|
||||
<PencilLine className="w-4 h-4" />
|
||||
일괄 수정
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<DataTable<ListTableRow>
|
||||
columns={columns}
|
||||
data={viewList}
|
||||
getRowId={(row) => String(row.sid)}
|
||||
isClient={false}
|
||||
pageCount={pageCount}
|
||||
totalCount={totalCount}
|
||||
onPaginationChange={setPagination}
|
||||
onSortingChange={setSorting}
|
||||
selectMode="multi"
|
||||
onRowSelectionChange={setSelectedRows}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
{canManageList && (
|
||||
<ListManageActions
|
||||
onReset={() => showDialog('listResetDialog')}
|
||||
onHeaderManage={() => showDialog('listHeaderManageDialog')}
|
||||
onUpload={() => showDialog('listUploadDialog')}
|
||||
onDownload={openDownloadDialog}
|
||||
onMessageSend={openMessageDialog}
|
||||
onMessageHistory={() => showDialog('messageHistoryDialog')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<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}
|
||||
<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}
|
||||
/>
|
||||
<ListHeaderManageDialog rows={headerManageRows} onConfirm={handleHeaderManageConfirm} />
|
||||
<ListFilterDialog headerOptions={filterHeaderOptions} initialRows={filterRows} onConfirm={handleFilterConfirm} />
|
||||
<ListBatchEditDialog
|
||||
headerOptions={headerOptions}
|
||||
appliedFilters={Object.fromEntries(filterRows.map((row) => [row.headerId, row.multiValues]))}
|
||||
initialRows={batchRows}
|
||||
onConfirm={handleBatchConfirm}
|
||||
/>
|
||||
<ListDownloadDialog mode={downloadMode} onDownload={handleDownloadConfirm} />
|
||||
<MessageSendDialog
|
||||
mode={messageSendMode}
|
||||
templateOptions={messageTemplateMock}
|
||||
targetHeaderOptions={messageTargetHeaders}
|
||||
defaultSenderEmail="info@kric.com"
|
||||
defaultSenderName="코리아리서치"
|
||||
defaultSenderNumber="02-0000-0000"
|
||||
onConfirm={handleMessageSendConfirm}
|
||||
/>
|
||||
<MessageHistoryDialog rows={messageHistoryMock} />
|
||||
|
||||
{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>
|
||||
)
|
||||
}
|
||||
|
||||
99
src/app/(pages)/(main)/manage/cmpn/page.tsx
Normal file
99
src/app/(pages)/(main)/manage/cmpn/page.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { DataTable } from "@/components/data-table/DataTable";
|
||||
import { getCmpnColumns } from "@/components/table-column/CmpnTableColumn";
|
||||
import CmpnUpsertDialog from "@/components/dialog/CmpnUpsertDialog";
|
||||
import { useDialog } from "@/hooks/useDialog";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import type { CmpnInfoSaveRequest } from "@/types/cmpn";
|
||||
import {
|
||||
useCheckCmpnIdDuplicateMutation,
|
||||
useCmpnDetailQuery,
|
||||
useCmpnListQuery,
|
||||
useUpsertCmpnMutation,
|
||||
} from "@/query/cmpn";
|
||||
|
||||
const CmpnManagePage = () => {
|
||||
const { showDialog } = useDialog();
|
||||
const mounted = useMounted();
|
||||
|
||||
const cmpnListQuery = useCmpnListQuery();
|
||||
const checkDupMutation = useCheckCmpnIdDuplicateMutation();
|
||||
const upsertMutation = useUpsertCmpnMutation();
|
||||
|
||||
const [editCmpnId, setEditCmpnId] = useState<string | null>(null);
|
||||
const [dialogMode, setDialogMode] = useState<'create' | 'edit'>('create');
|
||||
const cmpnDetailQuery = useCmpnDetailQuery(editCmpnId ?? "", !!editCmpnId);
|
||||
|
||||
const cmpnList = cmpnListQuery.data ?? [];
|
||||
|
||||
const handleCreateClick = () => {
|
||||
setDialogMode("create");
|
||||
setEditCmpnId(null);
|
||||
showDialog("cmpnUpsertDialog");
|
||||
};
|
||||
|
||||
const handleEdit = (cmpnId: string) => {
|
||||
setDialogMode("edit");
|
||||
setEditCmpnId(cmpnId);
|
||||
showDialog("cmpnUpsertDialog");
|
||||
};
|
||||
|
||||
const handleCheckDuplicate = (cmpnId: string) => {
|
||||
return checkDupMutation.mutateAsync(cmpnId);
|
||||
};
|
||||
|
||||
const handleSubmit = async (data: CmpnInfoSaveRequest): Promise<void> => {
|
||||
await upsertMutation.mutateAsync({ mode: dialogMode, data });
|
||||
|
||||
if (dialogMode === "create") {
|
||||
alert("등록되었습니다.");
|
||||
} else {
|
||||
alert("수정되었습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
const columns = getCmpnColumns({
|
||||
onEdit: handleEdit,
|
||||
});
|
||||
|
||||
if (!mounted) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText={"회사 관리"} />
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleCreateClick}>
|
||||
회사 등록
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={cmpnList}
|
||||
isClient={true}
|
||||
selectMode="single"
|
||||
defaultPageSize={10}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.cmpnId}
|
||||
maxBodyHeight="71vh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<CmpnUpsertDialog
|
||||
mode={dialogMode}
|
||||
initialData={dialogMode === "edit" ? (cmpnDetailQuery.data ?? undefined) : undefined}
|
||||
onSubmit={handleSubmit}
|
||||
onCheckDuplicate={handleCheckDuplicate}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CmpnManagePage;
|
||||
@@ -3,7 +3,7 @@
|
||||
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";
|
||||
@@ -13,14 +13,13 @@ import {useDialog} from "@/hooks/useDialog";
|
||||
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 type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {DEFAULT_COMPANY_NAME, EXTERNAL_USER_ROLE} from "@/const/userConst";
|
||||
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,
|
||||
@@ -29,6 +28,8 @@ import {
|
||||
useUploadUsersExcelMutation,
|
||||
useDownloadUserExcelTemplateMutation,
|
||||
} from "@/query/user";
|
||||
import { useCmpnListQuery } from "@/query/cmpn";
|
||||
import { isInternalManager } from "@/utils/userRole";
|
||||
|
||||
const UserManagePage = () => {
|
||||
const { showDialog } = useDialog();
|
||||
@@ -36,7 +37,7 @@ const UserManagePage = () => {
|
||||
|
||||
const { auth } = useAuth();
|
||||
const roleQuery = useRoleListQuery();
|
||||
const cmpnQuery = useUserCompaniesQuery();
|
||||
const cmpnQuery = useCmpnListQuery();
|
||||
const usersQuery = useUsersQuery();
|
||||
|
||||
const checkDupMutation = useCheckUserIdDuplicateMutation();
|
||||
@@ -151,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 text-sm">
|
||||
<BodyTitle titleText={"User management"}/>
|
||||
<AppPageTitle titleText={"사용자 관리"}/>
|
||||
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
<Input
|
||||
placeholder="면접원 ID 또는 면접원 이름"
|
||||
placeholder="사용자 ID 또는 사용자 이름"
|
||||
className="w-70 h-9 bg-white"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
@@ -181,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"
|
||||
@@ -198,17 +201,16 @@ const UserManagePage = () => {
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
className="text-lg"
|
||||
onClick={handleCreateClick}
|
||||
>
|
||||
면접원 등록
|
||||
사용자 등록
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => showDialog('userUploadDialog')}
|
||||
className="gap-2 bg-excel text-lg"
|
||||
className="gap-2 bg-excel"
|
||||
>
|
||||
<Upload className="w-4 h-4" />
|
||||
면접원 일괄 등록
|
||||
사용자 일괄 등록
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -221,6 +223,7 @@ const UserManagePage = () => {
|
||||
defaultPageSize={10}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.userId} // row.id = userId
|
||||
maxBodyHeight="71vh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {MessageType, TemplateEmail} from "@/types/messageTemplate";
|
||||
import { MessageType, type TemplateEmail } from "@kri/common/noti-hub";
|
||||
import MessageTemplate from "@/components/message-template/MessageTemplate";
|
||||
|
||||
const EmailTemplatePage = () => {
|
||||
@@ -21,4 +21,4 @@ const EmailTemplatePage = () => {
|
||||
)
|
||||
}
|
||||
|
||||
export default EmailTemplatePage;
|
||||
export default EmailTemplatePage;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import {MessageType, TemplateSms} from "@/types/messageTemplate";
|
||||
import { MessageType, type TemplateSms } from "@kri/common/noti-hub";
|
||||
import MessageTemplate from "@/components/message-template/MessageTemplate";
|
||||
|
||||
const SmsTemplatePage = () => {
|
||||
@@ -23,4 +23,4 @@ const SmsTemplatePage = () => {
|
||||
)
|
||||
}
|
||||
|
||||
export default SmsTemplatePage;
|
||||
export default SmsTemplatePage;
|
||||
|
||||
@@ -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,7 +12,7 @@ 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";
|
||||
@@ -20,12 +20,12 @@ import {useAuth} from "@/hooks/useAuth";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {SelectedProject} from "@/store/jotai/project";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {FW_USER_ROLE} from "@/const/userConst";
|
||||
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
|
||||
@@ -141,11 +141,11 @@ const MainPage = () => {
|
||||
router.push(`/list/manage`);
|
||||
}
|
||||
|
||||
if (!mounted || isLoading) return <LoadingOverlay force />;
|
||||
if (!mounted || isLoading) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<BodyTitle titleText={"프로젝트"}/>
|
||||
<AppPageTitle titleText={"프로젝트"}/>
|
||||
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
@@ -161,7 +161,7 @@ const MainPage = () => {
|
||||
}}
|
||||
/>
|
||||
{
|
||||
userRole < FW_USER_ROLE &&
|
||||
isManager(userRole) &&
|
||||
<KriMultiSelect
|
||||
items={statusArray}
|
||||
value={searchStatus}
|
||||
@@ -192,14 +192,12 @@ const MainPage = () => {
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
<Button
|
||||
className="text-lg"
|
||||
onClick={handleSearchClick}
|
||||
>
|
||||
검색
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
className="text-lg"
|
||||
onClick={handleCreateClick}
|
||||
>
|
||||
프로젝트 등록
|
||||
@@ -213,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>
|
||||
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
const ContactProgressPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
'use client'
|
||||
|
||||
return (<div>This is Contact Progress Page</div>)
|
||||
}
|
||||
import { ProgressPageContent } from "@/components/progress/ProgressPageContent";
|
||||
import { ProgressEventType } from "@/types/progress";
|
||||
import { ResultCodeType } from "@/types/project";
|
||||
|
||||
export default ContactProgressPage;
|
||||
const ContactProgressPage = () => (
|
||||
<ProgressPageContent
|
||||
eventTy={ProgressEventType.CONTACT}
|
||||
resultCdTy={ResultCodeType.CONTACT}
|
||||
pageTitle="컨택 현황"
|
||||
domainLabel="컨택"
|
||||
personLabel="컨택인력"
|
||||
/>
|
||||
);
|
||||
|
||||
export default ContactProgressPage;
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
const FieldworkProgressPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
|
||||
return (<div>This is Fieldwork Progress Page</div>)
|
||||
}
|
||||
|
||||
export default FieldworkProgressPage;
|
||||
17
src/app/(pages)/(main)/progress/interview/page.tsx
Normal file
17
src/app/(pages)/(main)/progress/interview/page.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
'use client'
|
||||
|
||||
import { ProgressPageContent } from "@/components/progress/ProgressPageContent";
|
||||
import { ProgressEventType } from "@/types/progress";
|
||||
import { ResultCodeType } from "@/types/project";
|
||||
|
||||
const InterviewProgressPage = () => (
|
||||
<ProgressPageContent
|
||||
eventTy={ProgressEventType.INTERVIEW}
|
||||
resultCdTy={ResultCodeType.INTERVIEW}
|
||||
pageTitle="면접 현황"
|
||||
domainLabel="면접"
|
||||
personLabel="면접원"
|
||||
/>
|
||||
);
|
||||
|
||||
export default InterviewProgressPage;
|
||||
@@ -1,8 +1,151 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import KriDateRangePicker from "@/components/common/KriDateRangePicker";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useSendResultSummaryQuery } from "@/query/message";
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
import { MessageType } from "@kri/common/noti-hub";
|
||||
import type { SendResultSummaryResponse } from "@kri/common/noti-hub";
|
||||
|
||||
const SEND_TYPE_ORDER = [MessageType.SMS, MessageType.LMS_MMS, MessageType.EMAIL] as const;
|
||||
|
||||
const SEND_TYPE_LABEL: Record<number, string> = {
|
||||
[MessageType.SMS]: "단문",
|
||||
[MessageType.LMS_MMS]: "장문",
|
||||
[MessageType.EMAIL]: "메일",
|
||||
};
|
||||
|
||||
type SummaryRow = {
|
||||
sendTy: number;
|
||||
price: number;
|
||||
totalCount: number;
|
||||
cost: number;
|
||||
successCount: number;
|
||||
failCount: number;
|
||||
standByCount: number;
|
||||
};
|
||||
|
||||
const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) =>
|
||||
list.reduce((acc, item) => acc + (item[field] as number | undefined ?? 0), 0);
|
||||
|
||||
const buildRows = (data: SendResultSummaryResponse[]): SummaryRow[] =>
|
||||
SEND_TYPE_ORDER.map((sendTy) => {
|
||||
const matched = data.filter((item) => item.sendTy === sendTy);
|
||||
return {
|
||||
sendTy,
|
||||
price: matched[0]?.price ?? 0,
|
||||
totalCount: sum(matched, "totalCount"),
|
||||
cost: sum(matched, "cost"),
|
||||
successCount: sum(matched, "successCount"),
|
||||
failCount: sum(matched, "failCount"),
|
||||
standByCount: sum(matched, "standByCount"),
|
||||
};
|
||||
});
|
||||
|
||||
const moneyUnit = (value: number) => `${value.toLocaleString()}원`;
|
||||
const caseUnit = (value: number) => `${value.toLocaleString()}건`;
|
||||
|
||||
const getFirstDayOfMonth = (date: Date) => {
|
||||
const d = new Date(date.getFullYear(), date.getMonth(), 1);
|
||||
return d.toISOString().slice(0, 10);
|
||||
};
|
||||
|
||||
const getLastDayOfMonth = (date: Date) => {
|
||||
const d = new Date(date.getFullYear(), date.getMonth() + 1, 0);
|
||||
return d.toISOString().slice(0, 10);
|
||||
};
|
||||
|
||||
const MessageProgressPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
const mounted = useMounted();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
|
||||
return (<div>This is Message Progress Page</div>)
|
||||
}
|
||||
const [dateRange, setDateRange] = useState(() => {
|
||||
const now = new Date();
|
||||
return { from: getFirstDayOfMonth(now), to: getLastDayOfMonth(now) };
|
||||
});
|
||||
|
||||
export default MessageProgressPage;
|
||||
const prjctCd = selectedProject?.prjctCd ?? "";
|
||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
|
||||
const enabled = mounted && !!prjctCd && !!dateRange.from && !!dateRange.to;
|
||||
|
||||
const summaryQuery = useSendResultSummaryQuery(
|
||||
{
|
||||
reqstSvc: clientEnv.REQUEST_SVC,
|
||||
itrntPrjctCd,
|
||||
prjctCd,
|
||||
sendStartDt: dateRange.from ? `${dateRange.from}T00:00:00` : undefined,
|
||||
sendEndDt: dateRange.to ? `${dateRange.to}T23:59:59` : undefined,
|
||||
},
|
||||
enabled,
|
||||
);
|
||||
|
||||
const rows = useMemo(() => buildRows(summaryQuery.data ?? []), [summaryQuery.data]);
|
||||
|
||||
const total = useMemo(
|
||||
() => ({
|
||||
totalCount: rows.reduce((acc, row) => acc + row.totalCount, 0),
|
||||
cost: rows.reduce((acc, row) => acc + row.cost, 0),
|
||||
successCount: rows.reduce((acc, row) => acc + row.successCount, 0),
|
||||
failCount: rows.reduce((acc, row) => acc + row.failCount, 0),
|
||||
standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0),
|
||||
}),
|
||||
[rows],
|
||||
);
|
||||
|
||||
if (!mounted) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="발송 현황" />
|
||||
|
||||
<KriDateRangePicker value={dateRange} onChange={setDateRange} className="w-80" />
|
||||
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-blue-50">
|
||||
<tr>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">유형</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">단가</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">대상수</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">비용</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">성공</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">실패</th>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">발송중</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.sendTy} className="border-b last:border-b-0">
|
||||
<td className="h-10 px-3 text-center">{SEND_TYPE_LABEL[row.sendTy]}</td>
|
||||
<td className="h-10 px-3 text-center">{moneyUnit(row.price)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(row.totalCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{moneyUnit(row.cost)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(row.successCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(row.failCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(row.standByCount)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr className="bg-gray-50 font-semibold">
|
||||
<td className="h-10 px-3 text-center" colSpan={2}>합계</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(total.totalCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{moneyUnit(total.cost)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(total.successCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(total.failCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(total.standByCount)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
※ 보낸 내역을 토대로 계산된 값으로 실제 정산 금액과 차이가 발생할 수 있습니다.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MessageProgressPage;
|
||||
|
||||
68
src/app/(pages)/(main)/progress/survey/page.tsx
Normal file
68
src/app/(pages)/(main)/progress/survey/page.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useProjectInfoQuery, useSurveyRedirectUrlQuery } from "@/query/project";
|
||||
import { SurveyType } from "@/types/project";
|
||||
|
||||
const SurveyProgressPage = () => {
|
||||
const mounted = useMounted();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
const openedRef = useRef(false);
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0;
|
||||
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
|
||||
const projectInfo = projectInfoQuery.data;
|
||||
const surveyTy = projectInfo?.surveyTy ?? SurveyType.NONE;
|
||||
|
||||
const isKonKiwi = surveyTy === SurveyType.KON || surveyTy === SurveyType.KIWI;
|
||||
const isKiwi = surveyTy === SurveyType.KIWI ? 1 : 0;
|
||||
const pkey = projectInfo?.surveyPrjctCd ?? "";
|
||||
|
||||
const redirectUrlEnabled = enabled && !!projectInfo && isKonKiwi && !!pkey;
|
||||
const redirectUrlQuery = useSurveyRedirectUrlQuery(isKiwi, pkey, redirectUrlEnabled);
|
||||
|
||||
const targetUrl = isKonKiwi
|
||||
? (redirectUrlQuery.data ?? null)
|
||||
: surveyTy === SurveyType.EXTERNAL
|
||||
? (projectInfo?.surveyDashboardUrl || null)
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (openedRef.current || !targetUrl) return;
|
||||
openedRef.current = true;
|
||||
window.open(targetUrl, "_blank");
|
||||
}, [targetUrl]);
|
||||
|
||||
const isLoading = !mounted || projectInfoQuery.isLoading || (redirectUrlEnabled && redirectUrlQuery.isLoading);
|
||||
|
||||
if (isLoading) return <LoadingOverlayAdapter force />;
|
||||
|
||||
if (targetUrl) {
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="설문 현황" />
|
||||
<p>
|
||||
새 창에서 열립니다. 열리지 않았다면{" "}
|
||||
<a href={targetUrl} target="_blank" rel="noreferrer" className="text-blue-600 underline">
|
||||
여기
|
||||
</a>
|
||||
를 클릭해 주세요.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="연결 가능한 현황이 없습니다." />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SurveyProgressPage;
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import {useEffect, useState, useCallback, useRef, 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'
|
||||
@@ -12,7 +12,7 @@ import {KriMultiSelect, KriSingleSelect} from '@/components/common/KriAutoComple
|
||||
import {useDialog} from '@/hooks/useDialog'
|
||||
import ResultCodeDialog from '@/components/dialog/ResultCodeDialog'
|
||||
import { useDebouncedValue, useMounted } from "@kri/common/hooks";
|
||||
import {LoadingOverlay} from '@/components/common/LoadingOverlay'
|
||||
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
||||
import {
|
||||
ProjectInfo, ProjectUpdateRequest, ResultCode,
|
||||
ProjectStatus, ResultCodeType, SurveyType
|
||||
@@ -23,7 +23,7 @@ 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";
|
||||
@@ -33,12 +33,12 @@ 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,
|
||||
@@ -51,6 +51,7 @@ const defaultProjectInfo: ProjectInfo = {
|
||||
surveyTy: SurveyType.NONE,
|
||||
surveyPrjctCd: '',
|
||||
surveyUrl: '',
|
||||
surveyDashboardUrl: '',
|
||||
ff: false,
|
||||
useContactSenario: false,
|
||||
contactSenario: '',
|
||||
@@ -61,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: {
|
||||
@@ -94,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;
|
||||
@@ -107,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 &&
|
||||
@@ -129,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 ?? [];
|
||||
@@ -162,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]
|
||||
);
|
||||
@@ -192,10 +194,11 @@ const ProjectInfoPage = () => {
|
||||
const requestUpdateProject: ProjectUpdateRequest = {
|
||||
projectInfo: projectInfo,
|
||||
resultCodeList: updateCodeArray,
|
||||
assignUserIdList: outsourceUserArray,
|
||||
assignCmpnIdList: assignCmpnIdArray,
|
||||
}
|
||||
|
||||
await updateMutation.mutateAsync(requestUpdateProject);
|
||||
initialProjectInfoRef.current = projectInfo;
|
||||
alert("저장되었습니다.");
|
||||
}
|
||||
|
||||
@@ -213,6 +216,7 @@ const ProjectInfoPage = () => {
|
||||
useEffect(() => {
|
||||
if (projectInfoQuery.data) {
|
||||
setProjectInfo(projectInfoQuery.data);
|
||||
initialProjectInfoRef.current = projectInfoQuery.data;
|
||||
}
|
||||
}, [projectInfoQuery.data]);
|
||||
|
||||
@@ -223,36 +227,61 @@ 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">
|
||||
@@ -335,9 +364,9 @@ const ProjectInfoPage = () => {
|
||||
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
|
||||
<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}
|
||||
@@ -352,7 +381,7 @@ const ProjectInfoPage = () => {
|
||||
|
||||
<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) => {
|
||||
@@ -374,7 +403,7 @@ const ProjectInfoPage = () => {
|
||||
<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"}
|
||||
@@ -397,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">
|
||||
@@ -490,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="컨택 시나리오를 작성해 주세요"
|
||||
|
||||
@@ -4,45 +4,31 @@ 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, { Suspense, useEffect, useRef, useState } from "react";
|
||||
import {useRouter, useSearchParams} from "next/navigation";
|
||||
import { useStorage } from "@/hooks/useStorage"
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
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";
|
||||
import {useInternalInfoQuery} from "@/query/internal";
|
||||
|
||||
const LoginPageContent = () => {
|
||||
const LoginPage = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const typeParam = searchParams.get("type") ?? "";
|
||||
|
||||
const loginMutation = useLoginMutation();
|
||||
const internalInfoQuery = useInternalInfoQuery();
|
||||
// TODO: 받은 데이터 확인
|
||||
console.log(internalInfoQuery.data);
|
||||
|
||||
const { get: getSeatNumberStorage } = 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("Please enter ID.");
|
||||
if (!userPw) return alert("Please enter password.");
|
||||
if (loginType === "call" && !seatNum) return alert("Please enter seat number.");
|
||||
|
||||
setError(null);
|
||||
try {
|
||||
await loginMutation.mutateAsync({ userId, userPw, seatNum, loginType });
|
||||
await loginMutation.mutateAsync({ userId, userPw });
|
||||
} catch (e) {
|
||||
const err = apiError(e, {
|
||||
fallbackMessage: "Login failed.",
|
||||
@@ -59,18 +45,6 @@ const LoginPageContent = () => {
|
||||
}
|
||||
}, [loginMutation.isSuccess, router]);
|
||||
|
||||
// URL 쿼리 파라미터에서 type 수신
|
||||
useEffect(() => {
|
||||
setLoginType(typeParam);
|
||||
|
||||
if (typeParam === "call") {
|
||||
setSeatNum(getSeatNumberStorage() ?? "");
|
||||
} else {
|
||||
setSeatNum("");
|
||||
}
|
||||
|
||||
}, [typeParam]);
|
||||
|
||||
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
@@ -79,19 +53,6 @@ const LoginPageContent = () => {
|
||||
};
|
||||
|
||||
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();
|
||||
@@ -118,13 +79,13 @@ const LoginPageContent = () => {
|
||||
<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="Enter ID"
|
||||
placeholder="ID"
|
||||
value={userId}
|
||||
onChange={(e) => setUserId(e.currentTarget.value)}
|
||||
onKeyDown={handleIdKeyDown}
|
||||
@@ -132,14 +93,14 @@ const LoginPageContent = () => {
|
||||
</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="Enter password"
|
||||
placeholder="password"
|
||||
value={userPw}
|
||||
onChange={(e) => setUserPw(e.currentTarget.value)}
|
||||
onKeyDown={handlePwKeyDown}
|
||||
@@ -147,24 +108,6 @@ const LoginPageContent = () => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{loginType === "call"?
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">자리번호 (면접원)</label>
|
||||
<Input
|
||||
id="seatNum"
|
||||
name="seatNum"
|
||||
type="text"
|
||||
placeholder="Enter seat number"
|
||||
value={seatNum}
|
||||
onChange={(e) => setSeatNum(e.currentTarget.value)}
|
||||
onKeyDown={handleSeatNumberKeyDown}
|
||||
ref={seatNumberInputRef}
|
||||
/>
|
||||
</div>
|
||||
:
|
||||
null
|
||||
}
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-500">
|
||||
{error}
|
||||
@@ -189,10 +132,4 @@ const LoginPageContent = () => {
|
||||
);
|
||||
}
|
||||
|
||||
const LoginPage = () => (
|
||||
<Suspense fallback={null}>
|
||||
<LoginPageContent />
|
||||
</Suspense>
|
||||
);
|
||||
|
||||
export default LoginPage;
|
||||
|
||||
@@ -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");
|
||||
})();
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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,10 +40,41 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.put(`/assign/prjct-fieldwork/${slug[1]}`, body);
|
||||
await contactApi.put(`/assign/${action}/${slug[1]}`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (action === "list" && slug.length === 3) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await contactApi.put<number>(`/assign/list/${slug[1]}/${slug[2]}`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "list" && slug[1] === "reset" && slug.length === 3) {
|
||||
const body = await req.json().catch(() => null);
|
||||
const result = await contactApi.del<number>(`/assign/list/reset/${slug[2]}`, { json: body });
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
|
||||
93
src/app/api/cmpn/[[...slug]]/route.ts
Normal file
93
src/app/api/cmpn/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createContactApi } from "@/lib/http-server";
|
||||
import type { CmpnInfo } from "@/types/cmpn";
|
||||
import type { DataVerification } from "@kri/common";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "check-cmpn-id") {
|
||||
const cmpnId = req.nextUrl.searchParams.get("cmpnId") ?? "";
|
||||
if (!cmpnId) {
|
||||
return NextResponse.json(
|
||||
{ message: "cmpnId 파라미터가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await contactApi.get<DataVerification>("/cmpn/check-cmpn-id", {
|
||||
query: { cmpnId },
|
||||
});
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (slug.length === 1) {
|
||||
const result = await contactApi.get<CmpnInfo>(`/cmpn/${encodeURIComponent(action)}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (!action) {
|
||||
const result = await contactApi.get<CmpnInfo[]>("/cmpn");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (!action) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.put("/cmpn", body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (!action) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.patch("/cmpn", body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -21,6 +21,22 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "survey-redirect-url" && slug.length === 3){
|
||||
const [, isKiwi, pkey] = slug;
|
||||
|
||||
const skey = await kartApi.get<string>(`/encrypt/pkey`, {
|
||||
headers: { pkey, iskiwi: isKiwi },
|
||||
});
|
||||
|
||||
const shortUrl = await kartApi.post<string>(
|
||||
`/uri/short`,
|
||||
{ realURI: "/Report/Current", mode: "U" },
|
||||
{ headers: { skey } },
|
||||
);
|
||||
|
||||
return NextResponse.json(shortUrl, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
|
||||
25
src/app/api/list-call-hist/[[...slug]]/route.ts
Normal file
25
src/app/api/list-call-hist/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [prjctIdx, sid] = slug;
|
||||
if (!prjctIdx || !sid) {
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ message: "요청 바디가 없습니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const contactApi = await createContactApi();
|
||||
const result = await contactApi.put(`/list-call-hist/${prjctIdx}/${sid}`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
52
src/app/api/list-hist/[[...slug]]/route.ts
Normal file
52
src/app/api/list-hist/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {ListEventHistory, ListUpdateHistory} from "@/types/list";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "event" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListEventHistory[]>(`/list-hist/event/${slug[1]}/${slug[2]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "update" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListUpdateHistory[]>(`/list-hist/update/${slug[1]}/${slug[2]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "event") {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.put(`/list-hist/event`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -27,6 +27,11 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
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);
|
||||
@@ -76,6 +81,12 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {LoginRequest, LoginUser} from "@/types/auth";
|
||||
import type { LoginRequest, LoginUser } from "@kri/common";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
82
src/app/api/message-report/[[...slug]]/route.ts
Normal file
82
src/app/api/message-report/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createNotihubApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {FileResponse, PageRequest, PageResponse} from "@kri/common";
|
||||
import type {BulkSendInfo, SendResultSummaryRequest, SendResultSummaryResponse} from "@kri/common/noti-hub";
|
||||
import type {SendResultInfo} from "@/types/message";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, sendTy, reqstSvc, prjctCd] = slug;
|
||||
const notihubApi = await createNotihubApi();
|
||||
|
||||
if (action === "bulk-list" && sendTy && reqstSvc && prjctCd) {
|
||||
const result = await notihubApi.get<BulkSendInfo[]>(
|
||||
`/report/bulk-list/${sendTy}/${reqstSvc}/${prjctCd}`,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
if (action === "send-result" && slug.length >= 4) {
|
||||
const [, sid, prjctCdParam, reqstSvcParam] = slug;
|
||||
const channelTy = req.nextUrl.searchParams.get("channelTy");
|
||||
const query = channelTy ? `?channelTy=${channelTy}` : "";
|
||||
const result = await notihubApi.get<SendResultInfo[]>(
|
||||
`/report/send-result/${sid}/${prjctCdParam}/${reqstSvcParam}${query}`,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, bulkSendKey] = slug;
|
||||
const notihubApi = await createNotihubApi();
|
||||
|
||||
if (action === "bulk-detail" && bulkSendKey) {
|
||||
const body: PageRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
const result = await notihubApi.post<PageResponse<SendResultInfo>>(
|
||||
`/report/bulk-detail/${bulkSendKey}`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
if (action === "bulk-detail-excel" && bulkSendKey) {
|
||||
const result = await notihubApi.post<FileResponse>(
|
||||
`/report/bulk-detail/excel/${bulkSendKey}`,
|
||||
undefined,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
if (action === "send-result-summary") {
|
||||
const body: SendResultSummaryRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
const result = await notihubApi.post<SendResultSummaryResponse[]>(
|
||||
`/report/send-result-summary`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
53
src/app/api/message-send/[[...slug]]/route.ts
Normal file
53
src/app/api/message-send/[[...slug]]/route.ts
Normal 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);
|
||||
}
|
||||
};
|
||||
@@ -2,7 +2,7 @@
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createNotihubApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import {Template, TemplateSummary} from "@/types/messageTemplate";
|
||||
import type { Template, TemplateSummary } from "@kri/common/noti-hub";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try{
|
||||
|
||||
38
src/app/api/message/[[...slug]]/route.ts
Normal file
38
src/app/api/message/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {MessageBulkSendResponse} from "@/types/message";
|
||||
|
||||
const isChannel = (value: string): value is "sms" | "email" => value === "sms" || value === "email";
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [channel, action, prjctIdx] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (!isChannel(channel) || !prjctIdx) {
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
if (action === "single") {
|
||||
await contactApi.post(`/message/${channel}/single/${prjctIdx}`, body);
|
||||
return new NextResponse(null, {status: 204});
|
||||
}
|
||||
|
||||
if (action === "bulk") {
|
||||
const result = await contactApi.post<MessageBulkSendResponse>(`/message/${channel}/bulk/${prjctIdx}`, body);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
39
src/app/api/progress/[[...slug]]/route.ts
Normal file
39
src/app/api/progress/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {ProgressDateResponse, ProgressSearchRequest, ProgressUserResponse} from "@/types/progress";
|
||||
|
||||
const ACTION_PATH: Record<string, string> = {
|
||||
"user": "/progress/user",
|
||||
"last-date": "/progress/last-date",
|
||||
"date": "/progress/date",
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, prjctIdx, eventTy] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
const basePath = ACTION_PATH[action];
|
||||
if (!basePath || !prjctIdx || !eventTy) {
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
}
|
||||
|
||||
const body: ProgressSearchRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
if (action === "user") {
|
||||
const result = await contactApi.post<ProgressUserResponse[]>(`${basePath}/${prjctIdx}/${eventTy}`, body);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
const result = await contactApi.post<ProgressDateResponse[]>(`${basePath}/${prjctIdx}/${eventTy}`, body);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
42
src/app/api/reserve/[[...slug]]/route.ts
Normal file
42
src/app/api/reserve/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {ListReserve} from "@/types/list";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "sid" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListReserve[]>(`/reserve/${slug[1]}/sid/${slug[2]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "user" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListReserve[]>(`/reserve/${slug[1]}/user/${slug[2]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ message: "요청 바디가 없습니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const contactApi = await createContactApi();
|
||||
const result = await contactApi.put<ListReserve>(`/reserve`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,8 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createContactApi } from "@/lib/http-server";
|
||||
import {ExcelUploadResult, UserInfo} from "@/types/user";
|
||||
import {DataVerification, RouteContext} from "@/types/common";
|
||||
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) => {
|
||||
@@ -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 });
|
||||
|
||||
@@ -9,19 +9,19 @@
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
/* --content-font-size 배율 기반 font-size 스케일 (기본 text-* 유틸을 그대로 대체) */
|
||||
--font-size-xs: calc(var(--content-font-size) * 0.75);
|
||||
--font-size-sm: calc(var(--content-font-size) * 0.875);
|
||||
--font-size-base: var(--content-font-size);
|
||||
--font-size-lg: calc(var(--content-font-size) * 1.125);
|
||||
--font-size-xl: calc(var(--content-font-size) * 1.25);
|
||||
--font-size-2xl: calc(var(--content-font-size) * 1.5);
|
||||
--font-size-3xl: calc(var(--content-font-size) * 1.875);
|
||||
--font-size-4xl: calc(var(--content-font-size) * 2.25);
|
||||
--font-size-5xl: calc(var(--content-font-size) * 3);
|
||||
--font-size-6xl: calc(var(--content-font-size) * 3.75);
|
||||
--font-size-7xl: calc(var(--content-font-size) * 4.5);
|
||||
--font-size-8xl: calc(var(--content-font-size) * 6);
|
||||
--font-size-9xl: calc(var(--content-font-size) * 8);
|
||||
--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);
|
||||
@@ -65,13 +65,13 @@
|
||||
--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: 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.97 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);
|
||||
@@ -100,14 +100,14 @@
|
||||
--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);
|
||||
--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.269 0 0);
|
||||
--accent-foreground: oklch(0.985 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%);
|
||||
@@ -128,10 +128,10 @@
|
||||
}
|
||||
|
||||
.bg-excel {
|
||||
background-color: var(--color-green-600);
|
||||
background-color: #217346;
|
||||
}
|
||||
.bg-excel:hover {
|
||||
background-color: var(--color-green-700);
|
||||
background-color: #185c37;
|
||||
}
|
||||
|
||||
.bg-blue {
|
||||
|
||||
87
src/components/app-shell/AppHeader.tsx
Normal file
87
src/components/app-shell/AppHeader.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import { LogOut, ZoomIn, ZoomOut } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { KriHeader } from "@/components/layout/KriHeader";
|
||||
import type { TopMenuItem } from "@/config/menu.types";
|
||||
import type { LoginUser } from "@kri/common";
|
||||
|
||||
interface AppHeaderProps {
|
||||
isMain: boolean;
|
||||
menuOpen: boolean;
|
||||
activeTopId: string;
|
||||
topMenus: TopMenuItem[];
|
||||
isViewProjectTitle: boolean;
|
||||
projectName?: string;
|
||||
userInfo?: LoginUser;
|
||||
fontSize: number;
|
||||
onToggleMenu: () => void;
|
||||
onNavigate: (path: string) => void;
|
||||
decreaseFontSize: () => void;
|
||||
increaseFontSize: () => void;
|
||||
}
|
||||
|
||||
export function AppHeader({
|
||||
isMain,
|
||||
menuOpen,
|
||||
activeTopId,
|
||||
topMenus,
|
||||
isViewProjectTitle,
|
||||
projectName,
|
||||
userInfo,
|
||||
fontSize,
|
||||
onToggleMenu,
|
||||
onNavigate,
|
||||
decreaseFontSize,
|
||||
increaseFontSize,
|
||||
}: AppHeaderProps) {
|
||||
return (
|
||||
<KriHeader
|
||||
logo={
|
||||
<div className="flex h-10 w-20 items-center justify-center">
|
||||
<Image
|
||||
src="/kri_logo.png"
|
||||
alt="KRI 로고"
|
||||
width={120}
|
||||
height={40}
|
||||
className="object-contain"
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
homePath="/"
|
||||
menus={topMenus}
|
||||
activeMenuId={activeTopId}
|
||||
menuOpen={menuOpen}
|
||||
showMenuButton={!isMain}
|
||||
onToggleMenu={onToggleMenu}
|
||||
onNavigate={(path) => onNavigate(path)}
|
||||
className="border-gray-200 bg-white"
|
||||
innerClassName="h-16 px-4"
|
||||
center={
|
||||
isViewProjectTitle && projectName ? (
|
||||
<h1 className="ml-3 text-2xl font-bold">{projectName}</h1>
|
||||
) : null
|
||||
}
|
||||
right={
|
||||
<>
|
||||
<div className="flex items-center gap-1 border-r pr-4">
|
||||
<Button variant="ghost" size="icon" onClick={decreaseFontSize} title="폰트 작게">
|
||||
<ZoomOut className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="min-w-[3rem] text-center text-xs text-gray-500">{fontSize}px</span>
|
||||
<Button variant="ghost" size="icon" onClick={increaseFontSize} title="폰트 크게">
|
||||
<ZoomIn className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<span className="hidden text-sm text-gray-600 sm:inline">{userInfo?.userName || ""}</span>
|
||||
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
|
||||
<LogOut className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">로그아웃</span>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
219
src/components/app-shell/AppMainLayout.tsx
Normal file
219
src/components/app-shell/AppMainLayout.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
10
src/components/app-shell/AppPageTitle.tsx
Normal file
10
src/components/app-shell/AppPageTitle.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { KriPageTitle } from "@/components/layout/KriPageTitle";
|
||||
|
||||
interface AppPageTitleProps {
|
||||
titleText: string;
|
||||
}
|
||||
|
||||
export default function AppPageTitle({ titleText }: AppPageTitleProps) {
|
||||
return <KriPageTitle title={titleText} />;
|
||||
}
|
||||
|
||||
50
src/components/app-shell/AppSidebar.tsx
Normal file
50
src/components/app-shell/AppSidebar.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import { KriSidebar } from "@/components/layout/KriSidebar";
|
||||
import { AppSidebarProjectSearch } from "@/components/app-shell/AppSidebarProjectSearch";
|
||||
import type { SideMenuItem } from "@/config/menu.types";
|
||||
|
||||
interface AppSidebarProps {
|
||||
isProjectMenu: boolean;
|
||||
sideMenus: SideMenuItem[];
|
||||
isOpen: boolean;
|
||||
pathname: string;
|
||||
openMenus: Record<string, boolean>;
|
||||
onOpenMenusChange: (openMenus: Record<string, boolean>) => void;
|
||||
onNavigate: (path: string) => void;
|
||||
}
|
||||
|
||||
export function AppSidebar({
|
||||
isProjectMenu,
|
||||
sideMenus,
|
||||
isOpen,
|
||||
pathname,
|
||||
openMenus,
|
||||
onOpenMenusChange,
|
||||
onNavigate,
|
||||
}: AppSidebarProps) {
|
||||
const openItemIds = Object.entries(openMenus)
|
||||
.filter(([, open]) => open)
|
||||
.map(([id]) => id);
|
||||
|
||||
return (
|
||||
<KriSidebar
|
||||
items={sideMenus}
|
||||
isOpen={isOpen}
|
||||
pathname={pathname}
|
||||
header={isProjectMenu ? <AppSidebarProjectSearch /> : null}
|
||||
openItemIds={openItemIds}
|
||||
onOpenItemIdsChange={(ids) => {
|
||||
onOpenMenusChange(
|
||||
sideMenus.reduce<Record<string, boolean>>((acc, item) => {
|
||||
acc[item.id] = ids.includes(item.id);
|
||||
return acc;
|
||||
}, {}),
|
||||
);
|
||||
}}
|
||||
onNavigate={(path) => onNavigate(path)}
|
||||
className="border-gray-200 bg-white"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,17 +6,20 @@ 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;
|
||||
@@ -36,7 +39,6 @@ export const SidebarProjectSearch = () =>{
|
||||
searchMode="inputOnly"
|
||||
onSearchValueChange={setSearchKeyword}
|
||||
placeholder="프로젝트 검색..."
|
||||
spanClassName="text-sm"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
preventDeselect
|
||||
15
src/components/app-shell/LoadingOverlayAdapter.tsx
Normal file
15
src/components/app-shell/LoadingOverlayAdapter.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import { KriLoadingOverlay, type KriLoadingOverlayProps } from "@/components/common/KriLoadingOverlay";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export type LoadingOverlayAdapterProps = Omit<KriLoadingOverlayProps, "open"> & {
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
export function LoadingOverlayAdapter({ force = false, ...props }: LoadingOverlayAdapterProps) {
|
||||
const open = useAtomValue(loadingAtom);
|
||||
|
||||
return <KriLoadingOverlay open={force || open} {...props} />;
|
||||
}
|
||||
6
src/components/app-shell/index.ts
Normal file
6
src/components/app-shell/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export { AppHeader } from "./AppHeader";
|
||||
export { AppSidebar } from "./AppSidebar";
|
||||
export { LoadingOverlayAdapter } from "./LoadingOverlayAdapter";
|
||||
export { default as AppMainLayout } from "./AppMainLayout";
|
||||
export { default as AppPageTitle } from "./AppPageTitle";
|
||||
|
||||
101
src/components/assign/AssignTargetList.tsx
Normal file
101
src/components/assign/AssignTargetList.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import { useCmpnListQuery } from '@/query/cmpn'
|
||||
import { useFieldworkUsersQuery } from '@/query/user'
|
||||
import { useAssignedCmpnIdsQuery, useAssignedFieldworkIdsQuery } from '@/query/project'
|
||||
import { ListHeaderAssignConst } from '@/const/listConst'
|
||||
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
|
||||
import type { ListHeaderAssignType } from '@/types/list'
|
||||
|
||||
export type AssignTargetListProps = {
|
||||
prjctIdx: number
|
||||
enabled: boolean
|
||||
assignType: ListHeaderAssignType
|
||||
selectedId?: string
|
||||
onSelect: (id: string) => void
|
||||
}
|
||||
|
||||
export type AssignTargetRow = {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export type UseAssignTargetRowsArgs = {
|
||||
prjctIdx: number
|
||||
enabled: boolean
|
||||
assignType: ListHeaderAssignType
|
||||
}
|
||||
|
||||
export function useAssignTargetRows({ prjctIdx, enabled, assignType }: UseAssignTargetRowsArgs): AssignTargetRow[] {
|
||||
const isOutsource = assignType === ListHeaderAssignConst.OUTSOURCE
|
||||
|
||||
const assignedCmpnIdsQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled && isOutsource)
|
||||
const cmpnListQuery = useCmpnListQuery()
|
||||
|
||||
const assignedFieldworkIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled && !isOutsource)
|
||||
const fieldworkUsersQuery = useFieldworkUsersQuery(enabled && !isOutsource)
|
||||
|
||||
return useMemo<AssignTargetRow[]>(() => {
|
||||
if (isOutsource) {
|
||||
const assignedIds = new Set(assignedCmpnIdsQuery.data ?? [])
|
||||
return (cmpnListQuery.data ?? [])
|
||||
.filter((cmpn) => assignedIds.has(cmpn.cmpnId))
|
||||
.map((cmpn) => ({ id: cmpn.cmpnId, name: cmpn.cmpnAlias || cmpn.cmpnId }))
|
||||
}
|
||||
|
||||
const targetRole =
|
||||
assignType === ListHeaderAssignConst.CONTACT_INTERVIEWER ? CONTACT_INTERVIEWER_ROLE : FIELD_INTERVIEWER_ROLE
|
||||
const assignedIds = new Set(assignedFieldworkIdsQuery.data ?? [])
|
||||
|
||||
return (fieldworkUsersQuery.data ?? [])
|
||||
.filter((user) => assignedIds.has(user.userId) && user.userRole === targetRole)
|
||||
.map((user) => ({ id: user.userId, name: user.userName }))
|
||||
}, [
|
||||
assignType,
|
||||
isOutsource,
|
||||
assignedCmpnIdsQuery.data,
|
||||
cmpnListQuery.data,
|
||||
assignedFieldworkIdsQuery.data,
|
||||
fieldworkUsersQuery.data,
|
||||
])
|
||||
}
|
||||
|
||||
export function AssignTargetList({ prjctIdx, enabled, assignType, selectedId, onSelect }: AssignTargetListProps) {
|
||||
const rows = useAssignTargetRows({ prjctIdx, enabled, assignType })
|
||||
|
||||
return (
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||
<div className="h-[78vh] overflow-y-auto">
|
||||
<table className="w-full table-fixed">
|
||||
<colgroup>
|
||||
<col className="w-28" />
|
||||
<col />
|
||||
</colgroup>
|
||||
<thead className="bg-primary text-white sticky top-0">
|
||||
<tr>
|
||||
<th className="p-2 text-left text-base font-medium">ID</th>
|
||||
<th className="p-2 text-left text-base font-medium">이름</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
selectedId === row.id ? 'bg-accent' : ''
|
||||
}`}
|
||||
onClick={() => onSelect(row.id)}
|
||||
>
|
||||
<td className="p-2 text-base truncate">{row.id}</td>
|
||||
<td className="p-2 text-base truncate">{row.name}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default AssignTargetList
|
||||
147
src/components/chart/BaseEChart.tsx
Normal file
147
src/components/chart/BaseEChart.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import type { ComponentType, CSSProperties } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { CHART_HEIGHTS } from './chart.config'
|
||||
import { useResizeKey } from './useResizeKey'
|
||||
|
||||
type EChartsSeries = NonNullable<EChartsOption['series']>
|
||||
type ReactEChartsProps = {
|
||||
option: EChartsOption
|
||||
className?: string
|
||||
style?: CSSProperties
|
||||
notMerge?: boolean
|
||||
lazyUpdate?: boolean
|
||||
onEvents?: Record<string, (params: unknown) => void>
|
||||
}
|
||||
|
||||
export type BaseEChartProps = {
|
||||
option: EChartsOption
|
||||
height?: number | string
|
||||
className?: string
|
||||
contentClassName?: string
|
||||
chartClassName?: string
|
||||
style?: CSSProperties
|
||||
contentStyle?: CSSProperties
|
||||
chartStyle?: CSSProperties
|
||||
notMerge?: boolean
|
||||
lazyUpdate?: boolean
|
||||
onEvents?: Record<string, (params: unknown) => void>
|
||||
resizeDebounceMs?: number
|
||||
normalizeValues?: boolean
|
||||
decimalPlaces?: number
|
||||
}
|
||||
|
||||
const roundNumber = (value: number, decimalPlaces: number) => {
|
||||
const factor = 10 ** decimalPlaces
|
||||
return Math.round((value + Number.EPSILON) * factor) / factor
|
||||
}
|
||||
|
||||
const normalizeDataValue = (value: unknown, decimalPlaces: number): unknown => {
|
||||
if (typeof value === 'number') {
|
||||
return roundNumber(value, decimalPlaces)
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => normalizeDataValue(item, decimalPlaces))
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object' && 'value' in value) {
|
||||
const dataItem = value as Record<string, unknown>
|
||||
|
||||
return {
|
||||
...dataItem,
|
||||
value: normalizeDataValue(dataItem.value, decimalPlaces),
|
||||
}
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const normalizeSeries = (
|
||||
series: EChartsOption['series'] | undefined,
|
||||
decimalPlaces: number,
|
||||
): EChartsOption['series'] => {
|
||||
if (!series) return series
|
||||
|
||||
const normalizeOne = (seriesOption: EChartsSeries): EChartsSeries => {
|
||||
const candidate = seriesOption as Record<string, unknown>
|
||||
const data = candidate.data
|
||||
|
||||
if (!Array.isArray(data)) {
|
||||
return seriesOption
|
||||
}
|
||||
|
||||
return {
|
||||
...candidate,
|
||||
data: data.map((value) => normalizeDataValue(value, decimalPlaces)),
|
||||
} as EChartsSeries
|
||||
}
|
||||
|
||||
return (Array.isArray(series) ? series.map((item) => normalizeOne(item as EChartsSeries)) : normalizeOne(series)) as EChartsOption['series']
|
||||
}
|
||||
|
||||
export function BaseEChart({
|
||||
option,
|
||||
height = CHART_HEIGHTS.DEFAULT,
|
||||
className,
|
||||
contentClassName,
|
||||
chartClassName,
|
||||
style,
|
||||
contentStyle,
|
||||
chartStyle,
|
||||
notMerge = true,
|
||||
lazyUpdate = false,
|
||||
onEvents,
|
||||
resizeDebounceMs = 150,
|
||||
normalizeValues = true,
|
||||
decimalPlaces = 2,
|
||||
}: BaseEChartProps) {
|
||||
const resizeKey = useResizeKey(resizeDebounceMs)
|
||||
const [ReactECharts, setReactECharts] = useState<ComponentType<ReactEChartsProps> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
void import('echarts-for-react').then((module) => {
|
||||
if (!cancelled) {
|
||||
setReactECharts(() => module.default as ComponentType<ReactEChartsProps>)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const normalizedOption = useMemo<EChartsOption>(() => {
|
||||
if (!normalizeValues) return option
|
||||
|
||||
return {
|
||||
...option,
|
||||
series: normalizeSeries(option.series, decimalPlaces),
|
||||
}
|
||||
}, [decimalPlaces, normalizeValues, option])
|
||||
|
||||
return (
|
||||
<div className={className} style={{ display: 'flex', flexDirection: 'column', height, ...style }}>
|
||||
<div className={contentClassName} style={{ flex: 1, minHeight: 0, ...contentStyle }}>
|
||||
{ReactECharts ? (
|
||||
<ReactECharts
|
||||
key={resizeKey}
|
||||
option={normalizedOption}
|
||||
className={chartClassName}
|
||||
style={{ width: '100%', height: '100%', ...chartStyle }}
|
||||
notMerge={notMerge}
|
||||
lazyUpdate={lazyUpdate}
|
||||
onEvents={onEvents}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default BaseEChart
|
||||
59
src/components/chart/KriBarChart.tsx
Normal file
59
src/components/chart/KriBarChart.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriCartesianChartProps } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriBarChartProps = KriCartesianChartProps & {
|
||||
isHorizontal?: boolean
|
||||
barWidth?: number | string
|
||||
barMaxWidth?: number | string
|
||||
}
|
||||
|
||||
export function KriBarChart({
|
||||
categories,
|
||||
series,
|
||||
isHorizontal = false,
|
||||
barWidth,
|
||||
barMaxWidth,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriBarChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const categoryAxis = { type: 'category', data: categories }
|
||||
const valueAxis = { type: 'value' }
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption(isHorizontal ? valueAxis : categoryAxis, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption(isHorizontal ? categoryAxis : valueAxis, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'bar',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
...(barWidth ? { barWidth } : {}),
|
||||
...(barMaxWidth ? { barMaxWidth } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [barMaxWidth, barWidth, categories, grid, isHorizontal, legend, option, series, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriBarChart
|
||||
|
||||
58
src/components/chart/KriLineChart.tsx
Normal file
58
src/components/chart/KriLineChart.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriCartesianChartProps } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriLineChartProps = KriCartesianChartProps & {
|
||||
smooth?: boolean
|
||||
area?: boolean
|
||||
showSymbol?: boolean
|
||||
}
|
||||
|
||||
export function KriLineChart({
|
||||
categories,
|
||||
series,
|
||||
smooth = false,
|
||||
area = false,
|
||||
showSymbol = true,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriLineChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'axis' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption({ type: 'category', data: categories, boundaryGap: false }, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption({ type: 'value' }, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'line',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
smooth,
|
||||
showSymbol,
|
||||
...(area ? { areaStyle: {} } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [area, categories, grid, legend, option, series, showSymbol, smooth, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriLineChart
|
||||
|
||||
50
src/components/chart/KriPieChart.tsx
Normal file
50
src/components/chart/KriPieChart.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriChartBaseProps, KriPieChartSeries } from './chart.types'
|
||||
import { defaultLegend, mergeChartOptions } from './chart.utils'
|
||||
|
||||
export type KriPieChartProps = KriChartBaseProps & {
|
||||
series: KriPieChartSeries[]
|
||||
}
|
||||
|
||||
const getPieCenter = (index: number, count: number) => {
|
||||
if (count === 1) return ['50%', '55%']
|
||||
|
||||
return [`${((index + 0.5) / count) * 100}%`, '55%']
|
||||
}
|
||||
|
||||
export function KriPieChart({
|
||||
series,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriPieChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'item' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
series: series.map((item, index) => ({
|
||||
type: 'pie',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
radius: item.radius ?? (series.length > 1 ? ['32%', '52%'] : '65%'),
|
||||
center: item.center ?? getPieCenter(index, series.length),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [legend, option, series, title, tooltip])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriPieChart
|
||||
|
||||
55
src/components/chart/KriRadarChart.tsx
Normal file
55
src/components/chart/KriRadarChart.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriChartBaseProps, KriRadarChartSeries, KriRadarDataItem, KriRadarIndicator } from './chart.types'
|
||||
import { defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriRadarChartProps = KriChartBaseProps & {
|
||||
indicators: KriRadarIndicator[]
|
||||
series: KriRadarChartSeries[]
|
||||
radar?: EChartsOption['radar']
|
||||
}
|
||||
|
||||
const normalizeRadarData = (series: KriRadarChartSeries): KriRadarDataItem[] => {
|
||||
if (series.data.every((value) => typeof value === 'number')) {
|
||||
return [{ name: series.name, value: series.data as number[] }]
|
||||
}
|
||||
|
||||
return series.data as KriRadarDataItem[]
|
||||
}
|
||||
|
||||
export function KriRadarChart({
|
||||
indicators,
|
||||
series,
|
||||
radar,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriRadarChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'item' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
radar: mergeObjectOption({ indicator: indicators }, radar) as EChartsOption['radar'],
|
||||
series: series.map((item) => ({
|
||||
type: 'radar',
|
||||
name: item.name,
|
||||
data: normalizeRadarData(item),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [indicators, legend, option, radar, series, title, tooltip])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriRadarChart
|
||||
|
||||
55
src/components/chart/KriScatterChart.tsx
Normal file
55
src/components/chart/KriScatterChart.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriChartBaseProps, KriScatterChartSeries } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriScatterChartProps = KriChartBaseProps & {
|
||||
series: KriScatterChartSeries[]
|
||||
grid?: EChartsOption['grid']
|
||||
xAxis?: EChartsOption['xAxis']
|
||||
yAxis?: EChartsOption['yAxis']
|
||||
symbolSize?: number | ((value: unknown, params: unknown) => number)
|
||||
}
|
||||
|
||||
export function KriScatterChart({
|
||||
series,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
symbolSize,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriScatterChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'item' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption({ type: 'value' }, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption({ type: 'value' }, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'scatter',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
...(symbolSize ? { symbolSize } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [grid, legend, option, series, symbolSize, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriScatterChart
|
||||
|
||||
62
src/components/chart/KriStackedBarChart.tsx
Normal file
62
src/components/chart/KriStackedBarChart.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriCartesianChartProps } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriStackedBarChartProps = KriCartesianChartProps & {
|
||||
isHorizontal?: boolean
|
||||
stackName?: string
|
||||
barWidth?: number | string
|
||||
barMaxWidth?: number | string
|
||||
}
|
||||
|
||||
export function KriStackedBarChart({
|
||||
categories,
|
||||
series,
|
||||
isHorizontal = false,
|
||||
stackName = 'total',
|
||||
barWidth,
|
||||
barMaxWidth,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriStackedBarChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const categoryAxis = { type: 'category', data: categories }
|
||||
const valueAxis = { type: 'value' }
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption(isHorizontal ? valueAxis : categoryAxis, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption(isHorizontal ? categoryAxis : valueAxis, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'bar',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
stack: item.stack ?? stackName,
|
||||
...(barWidth ? { barWidth } : {}),
|
||||
...(barMaxWidth ? { barMaxWidth } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [barMaxWidth, barWidth, categories, grid, isHorizontal, legend, option, series, stackName, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriStackedBarChart
|
||||
|
||||
6
src/components/chart/chart.config.ts
Normal file
6
src/components/chart/chart.config.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export const CHART_HEIGHTS = {
|
||||
DEFAULT: 320,
|
||||
SMALL: 240,
|
||||
LARGE: 420,
|
||||
} as const
|
||||
|
||||
71
src/components/chart/chart.types.ts
Normal file
71
src/components/chart/chart.types.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import type { BaseEChartProps } from './BaseEChart'
|
||||
|
||||
export type KriChartBaseProps = Omit<BaseEChartProps, 'option'> & {
|
||||
option?: EChartsOption
|
||||
title?: EChartsOption['title']
|
||||
legend?: EChartsOption['legend']
|
||||
tooltip?: EChartsOption['tooltip']
|
||||
}
|
||||
|
||||
export type KriCategoryValue = string | number
|
||||
|
||||
export type KriCategoryChartSeries = {
|
||||
name: string
|
||||
data: unknown[]
|
||||
color?: string
|
||||
stack?: string
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type KriCartesianChartProps = KriChartBaseProps & {
|
||||
categories: KriCategoryValue[]
|
||||
series: KriCategoryChartSeries[]
|
||||
grid?: EChartsOption['grid']
|
||||
xAxis?: EChartsOption['xAxis']
|
||||
yAxis?: EChartsOption['yAxis']
|
||||
}
|
||||
|
||||
export type KriNamedChartData = {
|
||||
name: string
|
||||
value: unknown
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type KriPieChartSeries = {
|
||||
name?: string
|
||||
data: KriNamedChartData[]
|
||||
radius?: string | number | Array<string | number>
|
||||
center?: Array<string | number>
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type KriRadarIndicator = {
|
||||
name: string
|
||||
max?: number
|
||||
min?: number
|
||||
color?: string
|
||||
}
|
||||
|
||||
export type KriRadarDataItem = {
|
||||
name?: string
|
||||
value: number[]
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type KriRadarChartSeries = {
|
||||
name: string
|
||||
data: number[] | KriRadarDataItem[]
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type KriScatterDataItem = [number, number] | [string, number] | KriNamedChartData
|
||||
|
||||
export type KriScatterChartSeries = {
|
||||
name: string
|
||||
data: KriScatterDataItem[]
|
||||
color?: string
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
34
src/components/chart/chart.utils.ts
Normal file
34
src/components/chart/chart.utils.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
export const mergeChartOptions = (generated: EChartsOption, option?: EChartsOption): EChartsOption => {
|
||||
if (!option) return generated
|
||||
|
||||
return {
|
||||
...generated,
|
||||
...option,
|
||||
series: option.series ?? generated.series,
|
||||
}
|
||||
}
|
||||
|
||||
export const mergeObjectOption = <TOption>(defaults: Record<string, unknown>, option?: TOption): TOption | Record<string, unknown> => {
|
||||
if (!option) return defaults
|
||||
if (Array.isArray(option)) return option
|
||||
if (typeof option === 'object') return { ...defaults, ...(option as Record<string, unknown>) }
|
||||
|
||||
return option
|
||||
}
|
||||
|
||||
export const defaultLegend = (seriesCount: number): EChartsOption['legend'] | undefined => {
|
||||
return seriesCount > 1 ? { top: 0 } : undefined
|
||||
}
|
||||
|
||||
export const defaultGrid = (seriesCount: number): EChartsOption['grid'] => {
|
||||
return {
|
||||
top: seriesCount > 1 ? 44 : 24,
|
||||
right: 24,
|
||||
bottom: 24,
|
||||
left: 24,
|
||||
containLabel: true,
|
||||
}
|
||||
}
|
||||
|
||||
29
src/components/chart/index.ts
Normal file
29
src/components/chart/index.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export { BaseEChart, default } from './BaseEChart'
|
||||
export type { BaseEChartProps } from './BaseEChart'
|
||||
export { KriBarChart } from './KriBarChart'
|
||||
export type { KriBarChartProps } from './KriBarChart'
|
||||
export { KriLineChart } from './KriLineChart'
|
||||
export type { KriLineChartProps } from './KriLineChart'
|
||||
export { KriPieChart } from './KriPieChart'
|
||||
export type { KriPieChartProps } from './KriPieChart'
|
||||
export { KriRadarChart } from './KriRadarChart'
|
||||
export type { KriRadarChartProps } from './KriRadarChart'
|
||||
export { KriScatterChart } from './KriScatterChart'
|
||||
export type { KriScatterChartProps } from './KriScatterChart'
|
||||
export { KriStackedBarChart } from './KriStackedBarChart'
|
||||
export type { KriStackedBarChartProps } from './KriStackedBarChart'
|
||||
export { CHART_HEIGHTS } from './chart.config'
|
||||
export type {
|
||||
KriCartesianChartProps,
|
||||
KriCategoryChartSeries,
|
||||
KriCategoryValue,
|
||||
KriChartBaseProps,
|
||||
KriNamedChartData,
|
||||
KriPieChartSeries,
|
||||
KriRadarChartSeries,
|
||||
KriRadarDataItem,
|
||||
KriRadarIndicator,
|
||||
KriScatterChartSeries,
|
||||
KriScatterDataItem,
|
||||
} from './chart.types'
|
||||
export { useResizeKey } from './useResizeKey'
|
||||
31
src/components/chart/useResizeKey.ts
Normal file
31
src/components/chart/useResizeKey.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
export function useResizeKey(delay = 150) {
|
||||
const [resizeKey, setResizeKey] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return
|
||||
|
||||
let timer: 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
|
||||
}
|
||||
|
||||
@@ -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 = "text-lg",
|
||||
badgeClassName = "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 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 = "text-lg",
|
||||
badgeClassName = "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 text-lg", className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
preventDeselect={preventDeselect}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
hideSelectAll
|
||||
autoSize
|
||||
singleLine
|
||||
closeOnSelect
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
/>
|
||||
</div>
|
||||
<div className={cn('flex-none', widthClassName, heightClassName)}>
|
||||
<MultiSelect<T>
|
||||
ref={ref}
|
||||
options={options}
|
||||
defaultValue={value ? [value] : []}
|
||||
onValueChange={(next) => {
|
||||
const selected = next[0] ?? ''
|
||||
if (selected === clearValue) {
|
||||
ref.current?.clear()
|
||||
onChange('')
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
return
|
||||
}
|
||||
onChange(selected)
|
||||
}}
|
||||
onOptionChange={(next) => {
|
||||
const option = next[0] ?? null
|
||||
if (option?.value === clearValue) {
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
return
|
||||
}
|
||||
onOptionChange?.(option)
|
||||
onItemChange?.(option?.info ?? null)
|
||||
}}
|
||||
selectionMode="single"
|
||||
maxCount={1}
|
||||
maxSelected={1}
|
||||
placeholder={placeholder}
|
||||
className={cn('bg-background text-base', !widthClassName && 'w-auto', className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
preventDeselect={preventDeselect}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
hideSelectAll
|
||||
singleLine
|
||||
closeOnSelect
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
disabled={disabled}
|
||||
title={showSelectedTooltip ? selectedLabel ?? value : undefined}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
82
src/components/common/KriDatePicker.tsx
Normal file
82
src/components/common/KriDatePicker.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
"use client";
|
||||
|
||||
import {CalendarIcon, X} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Calendar} from "@/components/ui/calendar";
|
||||
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
|
||||
import {cn} from "@/lib/utils";
|
||||
|
||||
const parseDate = (value: string) => {
|
||||
if (!value) return undefined
|
||||
|
||||
const [year, month, day] = value.split('-').map(Number)
|
||||
if (!year || !month || !day) return undefined
|
||||
|
||||
const date = new Date(year, month - 1, day)
|
||||
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return date
|
||||
}
|
||||
|
||||
const formatDate = (date: Date | undefined) => {
|
||||
if (!date) return ''
|
||||
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
export function KriDatePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "날짜 선택",
|
||||
className,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
const selected = parseDate(value);
|
||||
|
||||
return (
|
||||
<div className={cn("relative", className)}>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={cn("h-9 w-full justify-start bg-white pr-8 text-left font-normal", !value && "text-muted-foreground")}
|
||||
>
|
||||
<CalendarIcon className="h-4 w-4" />
|
||||
{selected ? formatDate(selected) : placeholder}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={selected}
|
||||
onSelect={(date) => onChange(date ? formatDate(date) : "")}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{value && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onChange("");
|
||||
}}
|
||||
aria-label="날짜 초기화"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
'use client'
|
||||
|
||||
import { useRef } from 'react'
|
||||
import { CalendarDays, X } from 'lucide-react'
|
||||
import { CalendarIcon, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Calendar } from '@/components/ui/calendar'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -13,7 +11,7 @@ export type KriDateRange = {
|
||||
to: string
|
||||
}
|
||||
|
||||
type KriDateRangePickerProps = {
|
||||
export type KriDateRangePickerProps = {
|
||||
value: KriDateRange
|
||||
onChange: (value: KriDateRange) => void
|
||||
placeholder?: string
|
||||
@@ -23,97 +21,101 @@ type KriDateRangePickerProps = {
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function KriDateRangePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '조회 기간 선택',
|
||||
className,
|
||||
triggerClassName,
|
||||
contentClassName,
|
||||
disabled = false,
|
||||
}: KriDateRangePickerProps) {
|
||||
const toInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const parseDate = (value: string) => {
|
||||
if (!value) return undefined
|
||||
|
||||
const displayText = value.from && value.to
|
||||
? `${value.from} ~ ${value.to}`
|
||||
: value.from
|
||||
? `${value.from} ~`
|
||||
: value.to
|
||||
? `~ ${value.to}`
|
||||
: placeholder
|
||||
const [year, month, day] = value.split('-').map(Number)
|
||||
if (!year || !month || !day) return undefined
|
||||
|
||||
const hasValue = value.from.length > 0 || value.to.length > 0
|
||||
const invalidRange = value.from.length > 0 && value.to.length > 0 && value.from > value.to
|
||||
|
||||
const focusAndOpenToDate = () => {
|
||||
const input = toInputRef.current
|
||||
if (!input) return
|
||||
|
||||
input.focus()
|
||||
const inputWithPicker = input as HTMLInputElement & { showPicker?: () => void }
|
||||
inputWithPicker.showPicker?.()
|
||||
if (!inputWithPicker.showPicker) {
|
||||
input.click()
|
||||
}
|
||||
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('flex items-center gap-2', className)}>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn('justify-start min-w-[260px] font-normal', triggerClassName)}
|
||||
>
|
||||
<CalendarDays className="w-4 h-4" />
|
||||
<span className="truncate">{displayText}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className={cn('w-[360px] space-y-3', contentClassName)}>
|
||||
<Label className="font-semibold">조회 기간</Label>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="date"
|
||||
value={value.from}
|
||||
onChange={(e) => {
|
||||
const nextFrom = e.target.value
|
||||
onChange({ ...value, from: nextFrom })
|
||||
if (nextFrom) {
|
||||
requestAnimationFrame(() => {
|
||||
focusAndOpenToDate()
|
||||
<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),
|
||||
})
|
||||
}
|
||||
}}
|
||||
}}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">~</span>
|
||||
<Input
|
||||
ref={toInputRef}
|
||||
type="date"
|
||||
value={value.to}
|
||||
onChange={(e) => onChange({ ...value, to: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{invalidRange && (
|
||||
<p className="text-xs text-red-600">조회 시작일은 종료일보다 이후일 수 없습니다.</p>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => onChange({ from: '', to: '' })}
|
||||
disabled={disabled || !hasValue}
|
||||
aria-label="조회 기간 초기화"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{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>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
136
src/components/common/KriDateTimePicker.tsx
Normal file
136
src/components/common/KriDateTimePicker.tsx
Normal file
@@ -0,0 +1,136 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { CalendarIcon, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Calendar } from '@/components/ui/calendar'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { KriTimePicker } from '@/components/common/KriTimePicker'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type KriDateTimePickerProps = {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder?: string
|
||||
className?: string
|
||||
triggerClassName?: string
|
||||
contentClassName?: string
|
||||
disabled?: boolean
|
||||
modalPopover?: boolean
|
||||
}
|
||||
|
||||
const parseDateTime = (value: string): { date: Date | undefined; time: string } => {
|
||||
if (!value) return { date: undefined, time: '' }
|
||||
|
||||
const [datePart, timePart = ''] = value.split('T')
|
||||
const [year, month, day] = datePart.split('-').map(Number)
|
||||
if (!year || !month || !day) return { date: undefined, time: timePart }
|
||||
|
||||
const date = new Date(year, month - 1, day)
|
||||
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
||||
return { date: undefined, time: timePart }
|
||||
}
|
||||
|
||||
return { date, time: timePart }
|
||||
}
|
||||
|
||||
const formatDate = (date: Date | undefined) => {
|
||||
if (!date) return ''
|
||||
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
const toValue = (date: Date | undefined, time: string): string => {
|
||||
const dateText = formatDate(date)
|
||||
if (!dateText) return ''
|
||||
|
||||
return `${dateText}T${time || '00:00'}`
|
||||
}
|
||||
|
||||
const toDisplayText = (date: Date | undefined, time: string, placeholder: string) => {
|
||||
const dateText = formatDate(date)
|
||||
if (!dateText) return placeholder
|
||||
|
||||
return `${dateText} ${time || '00:00'}`
|
||||
}
|
||||
|
||||
export function KriDateTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '날짜/시간 선택',
|
||||
className,
|
||||
triggerClassName,
|
||||
contentClassName,
|
||||
disabled = false,
|
||||
modalPopover = true,
|
||||
}: KriDateTimePickerProps) {
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const { date, time } = parseDateTime(value)
|
||||
const hasValue = date !== undefined
|
||||
|
||||
const handleDateSelect = (nextDate: Date | undefined) => {
|
||||
if (!nextDate) return
|
||||
onChange(toValue(nextDate, time || '00:00'))
|
||||
}
|
||||
|
||||
const handleTimeChange = (nextTime: string) => {
|
||||
if (!date) return
|
||||
onChange(toValue(date, nextTime))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('relative', className)}>
|
||||
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
|
||||
!hasValue && 'text-muted-foreground',
|
||||
triggerClassName,
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
<span className="truncate">{toDisplayText(date, time, placeholder)}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
|
||||
<div className="sm:flex">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={date}
|
||||
onSelect={handleDateSelect}
|
||||
/>
|
||||
<KriTimePicker
|
||||
value={time || '00:00'}
|
||||
onChange={handleTimeChange}
|
||||
disabled={!date}
|
||||
/>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{hasValue && !disabled ? (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onChange('')
|
||||
}}
|
||||
aria-label="날짜/시간 초기화"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KriDateTimePicker
|
||||
76
src/components/common/KriDialog.tsx
Normal file
76
src/components/common/KriDialog.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
26
src/components/common/KriLoadingOverlay.tsx
Normal file
26
src/components/common/KriLoadingOverlay.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export type KriSelectItem = {
|
||||
label: string
|
||||
}
|
||||
|
||||
type KriSelectProps<T> = {
|
||||
export type KriSelectProps<T> = {
|
||||
items: T[]
|
||||
value: string
|
||||
onChange?: (value: string) => void
|
||||
@@ -23,6 +23,7 @@ type KriSelectProps<T> = {
|
||||
getValue?: (item: T) => string
|
||||
getLabel?: (item: T) => string
|
||||
useAll?: boolean
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const HEIGHT_CLASS_VALUE: Record<string, CSSProperties['height']> = {
|
||||
@@ -41,12 +42,13 @@ export function KriSelect<T>({
|
||||
placeholder,
|
||||
className,
|
||||
heightClassName,
|
||||
triggerTextClassName = 'text-lg',
|
||||
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))
|
||||
@@ -57,10 +59,11 @@ export function KriSelect<T>({
|
||||
return (
|
||||
<Select
|
||||
value={value}
|
||||
onValueChange={(v) => {
|
||||
onChange?.(v)
|
||||
disabled={disabled}
|
||||
onValueChange={(selectedValue) => {
|
||||
onChange?.(selectedValue)
|
||||
|
||||
const selected = items.find((item) => extractValue(item) === v)
|
||||
const selected = items.find((item) => extractValue(item) === selectedValue)
|
||||
if (selected) {
|
||||
onChangeOption?.(selected)
|
||||
}
|
||||
@@ -75,16 +78,16 @@ export function KriSelect<T>({
|
||||
</SelectTrigger>
|
||||
<SelectContent className={contentClassName}>
|
||||
{useAll ? (
|
||||
<SelectItem key="ALL" value="ALL" className={itemClassName}>
|
||||
<SelectItem value="ALL" className={itemClassName}>
|
||||
전체
|
||||
</SelectItem>
|
||||
) : null}
|
||||
{items.map((item, idx) => {
|
||||
const v = extractValue(item)
|
||||
{items.map((item, index) => {
|
||||
const itemValue = extractValue(item)
|
||||
const label = extractLabel(item)
|
||||
|
||||
return (
|
||||
<SelectItem key={v ?? idx} value={v} className={itemClassName}>
|
||||
<SelectItem key={itemValue || index} value={itemValue} className={itemClassName}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
)
|
||||
|
||||
99
src/components/common/KriTimePicker.tsx
Normal file
99
src/components/common/KriTimePicker.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type KriTimePickerProps = {
|
||||
value?: string
|
||||
onChange: (value: string) => void
|
||||
disabled?: boolean
|
||||
minuteStep?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
const parseTime = (value: string | undefined) => {
|
||||
if (!value) return { hour: undefined, minute: undefined }
|
||||
|
||||
const [hour, minute] = value.split(':').map(Number)
|
||||
|
||||
return {
|
||||
hour: Number.isInteger(hour) && hour >= 0 && hour < 24 ? hour : undefined,
|
||||
minute: Number.isInteger(minute) && minute >= 0 && minute < 60 ? minute : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
const formatTime = (hour: number, minute: number) => {
|
||||
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export function KriTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
disabled = false,
|
||||
minuteStep = 5,
|
||||
className,
|
||||
}: KriTimePickerProps) {
|
||||
const { hour: selectedHour, minute: selectedMinute } = parseTime(value)
|
||||
const normalizedMinuteStep = Number.isFinite(minuteStep) && minuteStep > 0
|
||||
? Math.min(Math.floor(minuteStep), 60)
|
||||
: 5
|
||||
const hours = Array.from({ length: 24 }, (_, index) => index)
|
||||
const minutes = Array.from(
|
||||
{ length: Math.ceil(60 / normalizedMinuteStep) },
|
||||
(_, index) => index * normalizedMinuteStep,
|
||||
).filter((minute) => minute < 60)
|
||||
|
||||
const handleTimeChange = (type: 'hour' | 'minute', nextValue: number) => {
|
||||
if (disabled) return
|
||||
|
||||
const nextHour = type === 'hour' ? nextValue : selectedHour ?? 0
|
||||
const nextMinute = type === 'minute' ? nextValue : selectedMinute ?? 0
|
||||
|
||||
onChange(formatTime(nextHour, nextMinute))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col divide-y sm:h-[300px] sm:flex-row sm:divide-x sm:divide-y-0', className)}>
|
||||
<ScrollArea className="w-64 sm:w-auto">
|
||||
<div className="flex p-2 sm:flex-col">
|
||||
{hours.map((hour) => (
|
||||
<Button
|
||||
key={hour}
|
||||
type="button"
|
||||
size="icon"
|
||||
variant={selectedHour === hour ? 'default' : 'ghost'}
|
||||
className="aspect-square shrink-0 sm:w-full"
|
||||
disabled={disabled}
|
||||
onClick={() => handleTimeChange('hour', hour)}
|
||||
>
|
||||
{hour}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||
</ScrollArea>
|
||||
|
||||
<ScrollArea className="w-64 sm:w-auto">
|
||||
<div className="flex p-2 sm:flex-col">
|
||||
{minutes.map((minute) => (
|
||||
<Button
|
||||
key={minute}
|
||||
type="button"
|
||||
size="icon"
|
||||
variant={selectedMinute === minute ? 'default' : 'ghost'}
|
||||
className="aspect-square shrink-0 sm:w-full"
|
||||
disabled={disabled}
|
||||
onClick={() => handleTimeChange('minute', minute)}
|
||||
>
|
||||
{String(minute).padStart(2, '0')}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KriTimePicker
|
||||
@@ -1,17 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export function LoadingOverlay({ force = false }: { force?: boolean }) {
|
||||
const isLoading = useAtomValue(loadingAtom);
|
||||
|
||||
if (!force && !isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[9999] bg-black/70 flex items-center justify-center">
|
||||
{/* 심플 로딩 인디케이터 */}
|
||||
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MultiSelectContent } from './MultiSelectContent'
|
||||
import { MultiSelectTrigger } from './MultiSelectTrigger'
|
||||
import type { MultiSelectOption, MultiSelectProps, MultiSelectRef } from './types'
|
||||
import { arraysEqual, deduplicateOptions, flattenOptions } from './utils'
|
||||
import { useResponsiveSettings } from './use-responsive-settings'
|
||||
|
||||
function MultiSelectInner<T>(
|
||||
{
|
||||
options: rawOptions,
|
||||
onValueChange,
|
||||
onOptionChange,
|
||||
onInfoChange,
|
||||
defaultValue = [],
|
||||
stickySelectedOptions = [],
|
||||
onStickySelectedOptionsChange,
|
||||
placeholder = 'Select options',
|
||||
maxCount = 3,
|
||||
maxSelected,
|
||||
selectionMode = 'multiple',
|
||||
modalPopover = false,
|
||||
variant = 'default',
|
||||
className,
|
||||
spanClassName,
|
||||
badgeClassName,
|
||||
hideSelectAll = false,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
emptyIndicator = '검색 결과가 없습니다.',
|
||||
autoSize = false,
|
||||
singleLine = false,
|
||||
popoverClassName,
|
||||
disabled = false,
|
||||
responsive,
|
||||
minWidth,
|
||||
maxWidth,
|
||||
deduplicateOptions: shouldDeduplicate = false,
|
||||
resetOnDefaultValueChange = true,
|
||||
closeOnSelect = false,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
style,
|
||||
...buttonProps
|
||||
}: MultiSelectProps<T>,
|
||||
ref: React.ForwardedRef<MultiSelectRef>,
|
||||
) {
|
||||
const [selectedValues, setSelectedValues] = React.useState<string[]>(defaultValue)
|
||||
const [searchValue, setSearchValue] = React.useState(defaultSearchValue)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const buttonRef = React.useRef<HTMLButtonElement>(null)
|
||||
const [triggerWidth, setTriggerWidth] = React.useState<number>()
|
||||
|
||||
const options = React.useMemo(
|
||||
() => (shouldDeduplicate ? deduplicateOptions(rawOptions) : rawOptions),
|
||||
[rawOptions, shouldDeduplicate],
|
||||
)
|
||||
const flatOptions = React.useMemo(() => flattenOptions(options), [options])
|
||||
const responsiveSettings = useResponsiveSettings(responsive, maxCount)
|
||||
|
||||
const optionMap = React.useMemo(() => {
|
||||
const map = new Map<string, MultiSelectOption<T>>()
|
||||
for (const option of stickySelectedOptions) map.set(option.value, option)
|
||||
for (const option of flatOptions) map.set(option.value, option)
|
||||
return map
|
||||
}, [flatOptions, stickySelectedOptions])
|
||||
|
||||
const selectedOptions = React.useMemo(
|
||||
() => selectedValues.map((value) => optionMap.get(value) ?? { value, label: value }),
|
||||
[optionMap, selectedValues],
|
||||
)
|
||||
|
||||
const emit = React.useCallback(
|
||||
(next: string[]) => {
|
||||
setSelectedValues(next)
|
||||
onValueChange(next)
|
||||
const nextOptions = next.map((value) => optionMap.get(value) ?? { value, label: value })
|
||||
onOptionChange?.(nextOptions)
|
||||
onInfoChange?.(
|
||||
nextOptions.flatMap((option) => (option.info === undefined ? [] : [option.info])),
|
||||
)
|
||||
},
|
||||
[onInfoChange, onOptionChange, onValueChange, optionMap],
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!resetOnDefaultValueChange || arraysEqual(defaultValue, selectedValues)) return
|
||||
setSelectedValues(defaultValue)
|
||||
}, [defaultValue, resetOnDefaultValueChange, selectedValues])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!onStickySelectedOptionsChange) return
|
||||
const refreshed = selectedValues
|
||||
.map((value) => optionMap.get(value))
|
||||
.filter((option): option is MultiSelectOption<T> => Boolean(option))
|
||||
onStickySelectedOptionsChange(refreshed)
|
||||
}, [onStickySelectedOptionsChange, optionMap, selectedValues])
|
||||
|
||||
React.useEffect(() => {
|
||||
const element = buttonRef.current
|
||||
if (!element || !('ResizeObserver' in window)) return
|
||||
const update = () => setTriggerWidth(Math.round(element.getBoundingClientRect().width))
|
||||
update()
|
||||
const observer = new ResizeObserver(update)
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
React.useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
reset: () => {
|
||||
emit(defaultValue)
|
||||
setSearchValue(defaultSearchValue)
|
||||
setOpen(false)
|
||||
},
|
||||
getSelectedValues: () => selectedValues,
|
||||
setSelectedValues: emit,
|
||||
clear: () => emit([]),
|
||||
focus: () => buttonRef.current?.focus(),
|
||||
}),
|
||||
[defaultSearchValue, defaultValue, emit, selectedValues],
|
||||
)
|
||||
|
||||
const toggleOption = React.useCallback(
|
||||
(option: MultiSelectOption<T>) => {
|
||||
if (option.disabled) return
|
||||
const selected = selectedValues.includes(option.value)
|
||||
|
||||
if (selected) {
|
||||
if (preventDeselect) return
|
||||
emit(selectedValues.filter((value) => value !== option.value))
|
||||
return
|
||||
}
|
||||
|
||||
if (selectionMode === 'single') {
|
||||
emit([option.value])
|
||||
if (closeOnSelect) setOpen(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (maxSelected !== undefined && selectedValues.length >= maxSelected) return
|
||||
emit([...selectedValues, option.value])
|
||||
if (closeOnSelect) setOpen(false)
|
||||
},
|
||||
[closeOnSelect, emit, maxSelected, preventDeselect, selectedValues, selectionMode],
|
||||
)
|
||||
|
||||
const toggleAll = React.useCallback(() => {
|
||||
const values = flatOptions.filter((option) => !option.disabled).map((option) => option.value)
|
||||
const allSelected = values.length > 0 && values.every((value) => selectedValues.includes(value))
|
||||
if (allSelected) {
|
||||
if (!preventDeselect) emit([])
|
||||
return
|
||||
}
|
||||
emit(maxSelected === undefined ? values : values.slice(0, maxSelected))
|
||||
}, [emit, flatOptions, maxSelected, preventDeselect, selectedValues])
|
||||
|
||||
const handleSearchChange = (value: string) => {
|
||||
setSearchValue(value)
|
||||
onSearchValueChange?.(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
||||
<PopoverTrigger asChild>
|
||||
<MultiSelectTrigger
|
||||
ref={buttonRef}
|
||||
selectedOptions={selectedOptions}
|
||||
placeholder={placeholder}
|
||||
maxCount={responsiveSettings.maxCount}
|
||||
compactMode={responsiveSettings.compactMode}
|
||||
hideIcons={responsiveSettings.hideIcons}
|
||||
singleLine={singleLine}
|
||||
preventDeselect={preventDeselect}
|
||||
variant={variant}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
onRemove={(value) => emit(selectedValues.filter((selected) => selected !== value))}
|
||||
onClear={() => emit([])}
|
||||
className={cn(autoSize && 'w-auto', className)}
|
||||
disabled={disabled}
|
||||
style={{ minWidth, maxWidth, ...style }}
|
||||
{...buttonProps}
|
||||
/>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className={cn('w-[var(--radix-popover-trigger-width)] min-w-64 p-0', popoverClassName)}
|
||||
style={{ width: triggerWidth ? `${triggerWidth}px` : undefined }}
|
||||
>
|
||||
<MultiSelectContent
|
||||
options={options}
|
||||
selectedValues={selectedValues}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
searchValue={searchValue}
|
||||
onSearchValueChange={handleSearchChange}
|
||||
hideSelectAll={hideSelectAll}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
selectionMode={selectionMode}
|
||||
emptyIndicator={emptyIndicator}
|
||||
onToggleOption={toggleOption}
|
||||
onToggleAll={toggleAll}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
const ForwardedMultiSelect = React.forwardRef(MultiSelectInner) as <T = unknown>(
|
||||
props: MultiSelectProps<T> & { ref?: React.ForwardedRef<MultiSelectRef> },
|
||||
) => React.ReactElement
|
||||
|
||||
export const MultiSelect = ForwardedMultiSelect
|
||||
169
src/components/common/multi-select/MultiSelectContent.tsx
Normal file
169
src/components/common/multi-select/MultiSelectContent.tsx
Normal file
@@ -0,0 +1,169 @@
|
||||
'use client'
|
||||
|
||||
import { CheckIcon } from 'lucide-react'
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from '@/components/ui/command'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
||||
import { isGroupedOptions } from './utils'
|
||||
|
||||
interface MultiSelectContentProps<T> {
|
||||
options: MultiSelectOptions<T>
|
||||
selectedValues: string[]
|
||||
searchable: boolean
|
||||
searchMode: 'filter' | 'inputOnly'
|
||||
searchValue: string
|
||||
onSearchValueChange: (value: string) => void
|
||||
hideSelectAll: boolean
|
||||
hideOptionCheck: boolean
|
||||
selectionMode: 'single' | 'multiple'
|
||||
emptyIndicator: React.ReactNode
|
||||
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||
onToggleAll: () => void
|
||||
}
|
||||
|
||||
function OptionItem<T>({
|
||||
option,
|
||||
selected,
|
||||
hideOptionCheck,
|
||||
onToggle,
|
||||
}: {
|
||||
option: MultiSelectOption<T>
|
||||
selected: boolean
|
||||
hideOptionCheck: boolean
|
||||
onToggle: () => void
|
||||
}) {
|
||||
const Icon = option.icon
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
value={`${option.label} ${option.value}`}
|
||||
disabled={option.disabled}
|
||||
onSelect={onToggle}
|
||||
className="flex items-center cursor-pointer"
|
||||
>
|
||||
{!hideOptionCheck ? (
|
||||
<span
|
||||
className={cn(
|
||||
'border-primary flex size-4 items-center justify-center rounded-sm border',
|
||||
selected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
) : null}
|
||||
{Icon ? <Icon className="size-4" style={{ color: option.style?.iconColor }} /> : null}
|
||||
<span className="truncate">{option.label}</span>
|
||||
</CommandItem>
|
||||
)
|
||||
}
|
||||
|
||||
function OptionsGroup<T>({
|
||||
group,
|
||||
selectedValues,
|
||||
hideOptionCheck,
|
||||
onToggleOption,
|
||||
}: {
|
||||
group: MultiSelectGroup<T>
|
||||
selectedValues: string[]
|
||||
hideOptionCheck: boolean
|
||||
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||
}) {
|
||||
return (
|
||||
<CommandGroup heading={group.heading}>
|
||||
{group.options.map((option) => (
|
||||
<OptionItem
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={selectedValues.includes(option.value)}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggle={() => onToggleOption(option)}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export function MultiSelectContent<T>({
|
||||
options,
|
||||
selectedValues,
|
||||
searchable,
|
||||
searchMode,
|
||||
searchValue,
|
||||
onSearchValueChange,
|
||||
hideSelectAll,
|
||||
hideOptionCheck,
|
||||
selectionMode,
|
||||
emptyIndicator,
|
||||
onToggleOption,
|
||||
onToggleAll,
|
||||
}: MultiSelectContentProps<T>) {
|
||||
const grouped = isGroupedOptions(options)
|
||||
const flatOptions = grouped ? options.flatMap((group) => group.options) : options
|
||||
const selectableOptions = flatOptions.filter((option) => !option.disabled)
|
||||
const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value))
|
||||
|
||||
return (
|
||||
<Command shouldFilter={searchMode === 'filter'}>
|
||||
{searchable ? (
|
||||
<CommandInput
|
||||
value={searchValue}
|
||||
onValueChange={onSearchValueChange}
|
||||
placeholder="검색..."
|
||||
/>
|
||||
) : null}
|
||||
<CommandList>
|
||||
<CommandEmpty>{emptyIndicator}</CommandEmpty>
|
||||
{selectionMode === 'multiple' && !hideSelectAll && selectableOptions.length > 0 ? (
|
||||
<>
|
||||
<CommandGroup>
|
||||
<CommandItem className="cursor-pointer" value="__kri_select_all__" onSelect={onToggleAll}>
|
||||
<span
|
||||
className={cn(
|
||||
'border-primary flex size-4 items-center justify-center rounded-sm border',
|
||||
allSelected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
전체 선택
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
<CommandSeparator />
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{grouped ? (
|
||||
options.map((group) => (
|
||||
<OptionsGroup
|
||||
key={group.heading}
|
||||
group={group}
|
||||
selectedValues={selectedValues}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggleOption={onToggleOption}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<CommandGroup>
|
||||
{options.map((option) => (
|
||||
<OptionItem
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={selectedValues.includes(option.value)}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggle={() => onToggleOption(option)}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)}
|
||||
</CommandList>
|
||||
</Command>
|
||||
)
|
||||
}
|
||||
143
src/components/common/multi-select/MultiSelectTrigger.tsx
Normal file
143
src/components/common/multi-select/MultiSelectTrigger.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { ChevronDown, XCircle, XIcon } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MultiSelectOption, MultiSelectVariant } from './types'
|
||||
import { getVariantClass } from './utils'
|
||||
|
||||
interface MultiSelectTriggerProps<T> extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onChange'> {
|
||||
selectedOptions: MultiSelectOption<T>[]
|
||||
placeholder: string
|
||||
maxCount: number
|
||||
singleLine: boolean
|
||||
compactMode: boolean
|
||||
hideIcons: boolean
|
||||
preventDeselect: boolean
|
||||
variant: MultiSelectVariant
|
||||
spanClassName?: string
|
||||
badgeClassName?: string
|
||||
onRemove: (value: string) => void
|
||||
onClear: () => void
|
||||
}
|
||||
|
||||
export const MultiSelectTrigger = React.forwardRef(function MultiSelectTriggerInner<T>(
|
||||
{
|
||||
selectedOptions,
|
||||
placeholder,
|
||||
maxCount,
|
||||
singleLine,
|
||||
compactMode,
|
||||
hideIcons,
|
||||
preventDeselect,
|
||||
variant,
|
||||
spanClassName,
|
||||
badgeClassName,
|
||||
className,
|
||||
disabled,
|
||||
onRemove,
|
||||
onClear,
|
||||
...buttonProps
|
||||
}: MultiSelectTriggerProps<T>,
|
||||
ref: React.ForwardedRef<HTMLButtonElement>,
|
||||
) {
|
||||
const visible = selectedOptions.slice(0, maxCount)
|
||||
const hiddenCount = Math.max(0, selectedOptions.length - visible.length)
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
type="button"
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-haspopup="listbox"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-auto min-h-9 w-full justify-between gap-2 px-3 py-1.5 font-normal',
|
||||
getVariantClass(variant),
|
||||
className,
|
||||
)}
|
||||
{...buttonProps}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'flex min-w-0 flex-1 items-center gap-1 text-left',
|
||||
singleLine ? 'overflow-x-auto whitespace-nowrap' : 'flex-wrap',
|
||||
spanClassName,
|
||||
)}
|
||||
>
|
||||
{selectedOptions.length === 0 ? (
|
||||
<span className="text-muted-foreground truncate">{placeholder}</span>
|
||||
) : compactMode ? (
|
||||
<span>{selectedOptions.length}개 선택</span>
|
||||
) : (
|
||||
<>
|
||||
{visible.map((option) => {
|
||||
const Icon = option.icon
|
||||
return (
|
||||
<Badge
|
||||
key={option.value}
|
||||
variant="secondary"
|
||||
className={cn('max-w-full gap-1', badgeClassName)}
|
||||
style={{ background: option.style?.gradient ?? option.style?.badgeColor }}
|
||||
>
|
||||
{!hideIcons && Icon ? <Icon className="size-3.5" /> : null}
|
||||
<span className="max-w-48 truncate">{option.label}</span>
|
||||
{!preventDeselect ? (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`${option.label} 선택 해제`}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onRemove(option.value)
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onRemove(option.value)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<XIcon className="size-3" />
|
||||
</span>
|
||||
) : null}
|
||||
</Badge>
|
||||
)
|
||||
})}
|
||||
{hiddenCount > 0 ? <Badge variant="secondary">+{hiddenCount}</Badge> : null}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
|
||||
<span className="flex shrink-0 items-center gap-1">
|
||||
{selectedOptions.length > 0 && !preventDeselect ? (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label="전체 선택 해제"
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onClear()
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onClear()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<XCircle className="text-muted-foreground size-4" />
|
||||
</span>
|
||||
) : null}
|
||||
<ChevronDown className="text-muted-foreground size-4" />
|
||||
</span>
|
||||
</Button>
|
||||
)
|
||||
}) as <T>(props: MultiSelectTriggerProps<T> & { ref?: React.ForwardedRef<HTMLButtonElement> }) => React.ReactElement
|
||||
13
src/components/common/multi-select/index.ts
Normal file
13
src/components/common/multi-select/index.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export { MultiSelect } from './MultiSelect'
|
||||
export type {
|
||||
AnimationConfig,
|
||||
MultiSelectGroup,
|
||||
MultiSelectOption,
|
||||
MultiSelectOptions,
|
||||
MultiSelectProps,
|
||||
MultiSelectRef,
|
||||
MultiSelectResponsiveConfig,
|
||||
MultiSelectResponsiveSettings,
|
||||
MultiSelectSelectionMode,
|
||||
MultiSelectVariant,
|
||||
} from './types'
|
||||
89
src/components/common/multi-select/types.ts
Normal file
89
src/components/common/multi-select/types.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import type * as React from 'react'
|
||||
|
||||
export interface AnimationConfig {
|
||||
badgeAnimation?: 'bounce' | 'pulse' | 'wiggle' | 'fade' | 'slide' | 'none'
|
||||
popoverAnimation?: 'scale' | 'slide' | 'fade' | 'flip' | 'none'
|
||||
optionHoverAnimation?: 'highlight' | 'scale' | 'glow' | 'none'
|
||||
duration?: number
|
||||
delay?: number
|
||||
}
|
||||
|
||||
export interface MultiSelectOption<T = unknown> {
|
||||
label: string
|
||||
value: string
|
||||
info?: T
|
||||
icon?: React.ComponentType<React.SVGProps<SVGSVGElement>>
|
||||
disabled?: boolean
|
||||
style?: {
|
||||
badgeColor?: string
|
||||
iconColor?: string
|
||||
gradient?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface MultiSelectGroup<T = unknown> {
|
||||
heading: string
|
||||
options: MultiSelectOption<T>[]
|
||||
}
|
||||
|
||||
export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[]
|
||||
export type MultiSelectSelectionMode = 'single' | 'multiple'
|
||||
export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted'
|
||||
|
||||
export interface MultiSelectResponsiveSettings {
|
||||
maxCount?: number
|
||||
hideIcons?: boolean
|
||||
compactMode?: boolean
|
||||
}
|
||||
|
||||
export interface MultiSelectResponsiveConfig {
|
||||
mobile?: MultiSelectResponsiveSettings
|
||||
tablet?: MultiSelectResponsiveSettings
|
||||
desktop?: MultiSelectResponsiveSettings
|
||||
}
|
||||
|
||||
export interface MultiSelectProps<T = unknown>
|
||||
extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'defaultValue' | 'onChange'> {
|
||||
options: MultiSelectOptions<T>
|
||||
onValueChange: (value: string[]) => void
|
||||
onOptionChange?: (selectedOptions: MultiSelectOption<T>[]) => void
|
||||
onInfoChange?: (infos: T[]) => void
|
||||
defaultValue?: string[]
|
||||
stickySelectedOptions?: MultiSelectOption<T>[]
|
||||
onStickySelectedOptionsChange?: (options: MultiSelectOption<T>[]) => void
|
||||
placeholder?: string
|
||||
animation?: number
|
||||
animationConfig?: AnimationConfig
|
||||
maxCount?: number
|
||||
maxSelected?: number
|
||||
selectionMode?: MultiSelectSelectionMode
|
||||
modalPopover?: boolean
|
||||
variant?: MultiSelectVariant
|
||||
spanClassName?: string
|
||||
badgeClassName?: string
|
||||
hideSelectAll?: boolean
|
||||
searchable?: boolean
|
||||
searchMode?: 'filter' | 'inputOnly'
|
||||
defaultSearchValue?: string
|
||||
onSearchValueChange?: (value: string) => void
|
||||
emptyIndicator?: React.ReactNode
|
||||
autoSize?: boolean
|
||||
singleLine?: boolean
|
||||
popoverClassName?: string
|
||||
responsive?: boolean | MultiSelectResponsiveConfig
|
||||
minWidth?: string
|
||||
maxWidth?: string
|
||||
deduplicateOptions?: boolean
|
||||
resetOnDefaultValueChange?: boolean
|
||||
closeOnSelect?: boolean
|
||||
preventDeselect?: boolean
|
||||
hideOptionCheck?: boolean
|
||||
}
|
||||
|
||||
export interface MultiSelectRef {
|
||||
reset: () => void
|
||||
getSelectedValues: () => string[]
|
||||
setSelectedValues: (values: string[]) => void
|
||||
clear: () => void
|
||||
focus: () => void
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import type { MultiSelectProps, MultiSelectResponsiveSettings } from './types'
|
||||
|
||||
export function useResponsiveSettings(
|
||||
responsive: MultiSelectProps['responsive'],
|
||||
defaultMaxCount: number,
|
||||
): Required<MultiSelectResponsiveSettings> {
|
||||
const [screen, setScreen] = React.useState<'mobile' | 'tablet' | 'desktop'>('desktop')
|
||||
|
||||
React.useEffect(() => {
|
||||
const update = () => {
|
||||
if (window.innerWidth < 640) setScreen('mobile')
|
||||
else if (window.innerWidth < 1024) setScreen('tablet')
|
||||
else setScreen('desktop')
|
||||
}
|
||||
|
||||
update()
|
||||
window.addEventListener('resize', update)
|
||||
return () => window.removeEventListener('resize', update)
|
||||
}, [])
|
||||
|
||||
if (!responsive) {
|
||||
return { maxCount: defaultMaxCount, hideIcons: false, compactMode: false }
|
||||
}
|
||||
|
||||
if (responsive === true) {
|
||||
const defaults = {
|
||||
mobile: { maxCount: 2, hideIcons: false, compactMode: true },
|
||||
tablet: { maxCount: 4, hideIcons: false, compactMode: false },
|
||||
desktop: { maxCount: 6, hideIcons: false, compactMode: false },
|
||||
}
|
||||
return defaults[screen]
|
||||
}
|
||||
|
||||
const current = responsive[screen]
|
||||
return {
|
||||
maxCount: current?.maxCount ?? defaultMaxCount,
|
||||
hideIcons: current?.hideIcons ?? false,
|
||||
compactMode: current?.compactMode ?? false,
|
||||
}
|
||||
}
|
||||
48
src/components/common/multi-select/utils.ts
Normal file
48
src/components/common/multi-select/utils.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
||||
|
||||
export function isGroupedOptions<T>(options: MultiSelectOptions<T>): options is MultiSelectGroup<T>[] {
|
||||
return options.length > 0 && 'heading' in options[0]
|
||||
}
|
||||
|
||||
export function flattenOptions<T>(options: MultiSelectOptions<T>): MultiSelectOption<T>[] {
|
||||
return isGroupedOptions(options) ? options.flatMap((group) => group.options) : options
|
||||
}
|
||||
|
||||
export function deduplicateOptions<T>(options: MultiSelectOptions<T>): MultiSelectOptions<T> {
|
||||
const seen = new Set<string>()
|
||||
|
||||
if (isGroupedOptions(options)) {
|
||||
return options.map((group) => ({
|
||||
...group,
|
||||
options: group.options.filter((option) => {
|
||||
if (seen.has(option.value)) return false
|
||||
seen.add(option.value)
|
||||
return true
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
return options.filter((option) => {
|
||||
if (seen.has(option.value)) return false
|
||||
seen.add(option.value)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
export function arraysEqual(left: string[], right: string[]): boolean {
|
||||
if (left.length !== right.length) return false
|
||||
return left.every((value, index) => value === right[index])
|
||||
}
|
||||
|
||||
export function getVariantClass(variant: 'default' | 'secondary' | 'destructive' | 'inverted'): string {
|
||||
switch (variant) {
|
||||
case 'secondary':
|
||||
return 'bg-secondary text-secondary-foreground'
|
||||
case 'destructive':
|
||||
return 'bg-destructive text-destructive-foreground'
|
||||
case 'inverted':
|
||||
return 'bg-foreground text-background'
|
||||
default:
|
||||
return 'bg-background text-foreground'
|
||||
}
|
||||
}
|
||||
@@ -1,224 +1,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
|
||||
}: Readonly<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(
|
||||
'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 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(
|
||||
'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>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
98
src/components/data-table/DataTablePagination.tsx
Normal file
98
src/components/data-table/DataTablePagination.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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])
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
8
src/components/data-table/index.ts
Normal file
8
src/components/data-table/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export { DataTable } from './DataTable'
|
||||
export type {
|
||||
DataTableColumn,
|
||||
DataTableProps,
|
||||
SelectMode,
|
||||
ServerPaginationParams,
|
||||
ServerPaginationResponse,
|
||||
} from './DataTable.type'
|
||||
233
src/components/dialog/CmpnUpsertDialog.tsx
Normal file
233
src/components/dialog/CmpnUpsertDialog.tsx
Normal 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
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Plus, X } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
@@ -107,7 +107,7 @@ const ListBatchEditDialog = ({
|
||||
const handleConfirm = async () => {
|
||||
const normalized = rows.filter((row) => row.headerId > 0 && row.value.trim().length > 0)
|
||||
if (normalized.length === 0) {
|
||||
alert('일괄 수정할 항목을 입력해 주세요.')
|
||||
alert('일괄 수정할 항목을 입력해주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -121,87 +121,86 @@ const ListBatchEditDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[900px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">일괄 수정</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-md border px-4 py-3 text-sm">
|
||||
<p className="font-semibold mb-1">적용된 필터</p>
|
||||
<p className="text-muted-foreground">
|
||||
{filterSummary.length > 0 ? filterSummary : '적용된 필터가 없습니다.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<div className="h-11 px-4 border-b bg-muted/40 grid grid-cols-[1fr_2fr_64px] items-center text-sm font-semibold">
|
||||
<span>헤더</span>
|
||||
<span>수정 값</span>
|
||||
<span />
|
||||
</div>
|
||||
|
||||
<div className="max-h-72 overflow-auto">
|
||||
{rows.map((row) => (
|
||||
<div
|
||||
key={row.id}
|
||||
className="h-12 px-4 border-b last:border-b-0 grid grid-cols-[1fr_2fr_64px] items-center gap-2"
|
||||
>
|
||||
<Select
|
||||
value={String(row.headerId)}
|
||||
onValueChange={(v) => handleChangeHeader(row.id, Number(v))}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="헤더 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{headerOptions.map((option) => (
|
||||
<SelectItem key={option.id} value={String(option.id)}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Input
|
||||
value={row.value}
|
||||
onChange={(e) => handleChangeValue(row.id, e.target.value)}
|
||||
placeholder="수정할 값을 입력해 주세요"
|
||||
/>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleRemoveRow(row.id)}
|
||||
aria-label="행 제거"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
|
||||
<Plus className="w-4 h-4" />
|
||||
행 추가
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">일괄 수정</span>}
|
||||
contentClassName="sm:max-w-[900px]"
|
||||
bodyClassName="space-y-4"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
적용
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="rounded-md border px-4 py-3 text-sm">
|
||||
<p className="font-semibold mb-1">적용된 필터</p>
|
||||
<p className="text-muted-foreground">
|
||||
{filterSummary.length > 0 ? filterSummary : '적용된 필터가 없습니다.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[1fr_2fr_64px] items-center text-sm font-semibold">
|
||||
<span>헤더</span>
|
||||
<span>수정 값</span>
|
||||
<span />
|
||||
</div>
|
||||
|
||||
<div className="max-h-72 overflow-auto">
|
||||
{rows.map((row) => (
|
||||
<div
|
||||
key={row.id}
|
||||
className="h-12 px-4 border-b last:border-b-0 grid grid-cols-[1fr_2fr_64px] items-center gap-2"
|
||||
>
|
||||
<Select
|
||||
value={String(row.headerId)}
|
||||
onValueChange={(v) => handleChangeHeader(row.id, Number(v))}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="헤더 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{headerOptions.map((option) => (
|
||||
<SelectItem key={option.id} value={String(option.id)}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Input
|
||||
value={row.value}
|
||||
onChange={(e) => handleChangeValue(row.id, e.target.value)}
|
||||
placeholder="수정할 값을 입력해주세요"
|
||||
/>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleRemoveRow(row.id)}
|
||||
aria-label="행 제거"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
|
||||
<Plus className="w-4 h-4" />
|
||||
행 추가
|
||||
</Button>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -22,15 +22,15 @@ const ApplyFilterOption = ({ value, onValueChange, idPrefix }: ApplyFilterGroupP
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="selected" id={`${idPrefix}-selected`} />
|
||||
<Label htmlFor={`${idPrefix}-selected`}>선택 항목만</Label>
|
||||
<Label className="text-base" htmlFor={`${idPrefix}-selected`}>선택 항목만</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="filtered" id={`${idPrefix}-filtered`} />
|
||||
<Label htmlFor={`${idPrefix}-filtered`}>필터 적용 대상만</Label>
|
||||
<Label className="text-base" htmlFor={`${idPrefix}-filtered`}>필터 적용 대상만</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="all" id={`${idPrefix}-all`} />
|
||||
<Label htmlFor={`${idPrefix}-all`}>전체 대상</Label>
|
||||
<Label className="text-base" htmlFor={`${idPrefix}-all`}>전체 대상</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Download } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
@@ -57,7 +57,7 @@ const ListDownloadDialog = ({
|
||||
const hasFrom = contactHistoryDateFrom.length > 0
|
||||
const hasTo = contactHistoryDateTo.length > 0
|
||||
if (hasFrom !== hasTo) {
|
||||
alert('조회 기간은 시작일과 종료일을 모두 입력해 주세요.')
|
||||
alert('조회 기간은 시작일과 종료일을 모두 입력해주세요.')
|
||||
return
|
||||
}
|
||||
if (hasFrom && hasTo && contactHistoryDateFrom > contactHistoryDateTo) {
|
||||
@@ -83,51 +83,14 @@ const ListDownloadDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[560px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">{titleMap[mode]}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{mode === 'contact-history' ? (
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">조회 기간</p>
|
||||
<KriDateRangePicker
|
||||
value={{ from: contactHistoryDateFrom, to: contactHistoryDateTo }}
|
||||
onChange={(range) => {
|
||||
setContactHistoryDateFrom(range.from)
|
||||
setContactHistoryDateTo(range.to)
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">비워두면 전체 기간으로 다운로드됩니다.</p>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">다운로드 범위</p>
|
||||
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="download-scope-target" />
|
||||
</div>
|
||||
{mode === 'contact-history' ? (
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">이력 기준</p>
|
||||
<RadioGroup
|
||||
value={contactHistoryType}
|
||||
onValueChange={(v) => setContactHistoryType(v as ContactHistoryDownloadType)}
|
||||
className="flex items-center gap-6 flex-wrap"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="all" id="download-contact-history-all" />
|
||||
<Label htmlFor="download-contact-history-all">전체 이력</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="latest" id="download-contact-history-latest" />
|
||||
<Label htmlFor="download-contact-history-latest">마지막 이력만</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
|
||||
contentClassName="sm:max-w-[560px]"
|
||||
bodyClassName="space-y-4"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
@@ -135,9 +98,46 @@ const ListDownloadDialog = ({
|
||||
<Download className="w-4 h-4" />
|
||||
다운로드
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{mode === 'contact-history' ? (
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">조회 기간</p>
|
||||
<KriDateRangePicker
|
||||
value={{ from: contactHistoryDateFrom, to: contactHistoryDateTo }}
|
||||
onChange={(range) => {
|
||||
setContactHistoryDateFrom(range.from)
|
||||
setContactHistoryDateTo(range.to)
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">비워두면 전체 기간으로 다운로드합니다.</p>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">다운로드 범위</p>
|
||||
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="download-scope-target" />
|
||||
</div>
|
||||
{mode === 'contact-history' ? (
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">이력 기준</p>
|
||||
<RadioGroup
|
||||
value={contactHistoryType}
|
||||
onValueChange={(v) => setContactHistoryType(v as ContactHistoryDownloadType)}
|
||||
className="flex items-center gap-6 flex-wrap"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="all" id="download-contact-history-all" />
|
||||
<Label className="text-base" htmlFor="download-contact-history-all">전체 이력</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="latest" id="download-contact-history-latest" />
|
||||
<Label className="text-base" htmlFor="download-contact-history-latest">마지막 이력만</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
) : null}
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Plus, X } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { FilterHeaderOption, FilterOperator, FilterRow } from '@/types/list'
|
||||
import type { FilterHeaderOption, FilterOperator, FilterRow, FilterValueOption } from '@/types/list'
|
||||
|
||||
export type ListFilterDialogProps = {
|
||||
dialogId?: DialogId
|
||||
@@ -31,12 +31,14 @@ const operatorLabel: Record<FilterOperator, string> = {
|
||||
neq: '다름',
|
||||
contains: '포함',
|
||||
notContains: '포함하지 않음',
|
||||
empty: '값 없음',
|
||||
notEmpty: '값 있음',
|
||||
}
|
||||
|
||||
const createFilterRow = (headerId: number): FilterRow => ({
|
||||
const createFilterRow = (headerId: number, headerOptions: FilterHeaderOption[]): FilterRow => ({
|
||||
id: crypto.randomUUID(),
|
||||
headerId,
|
||||
operator: 'eq',
|
||||
operator: headerOptions.find((option) => option.id === headerId)?.allowedOperators[0] ?? 'eq',
|
||||
textValue: '',
|
||||
multiValues: [],
|
||||
})
|
||||
@@ -54,7 +56,7 @@ const ListFilterDialog = ({
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
const defaultHeaderId = headerOptions[0]?.id ?? 0
|
||||
const defaultHeaderId = headerOptions.find((option) => !option.disabled)?.id ?? 0
|
||||
|
||||
useEffect(() => {
|
||||
if (!resolvedOpen) return
|
||||
@@ -63,9 +65,9 @@ const ListFilterDialog = ({
|
||||
return
|
||||
}
|
||||
if (defaultHeaderId > 0) {
|
||||
setRows([createFilterRow(defaultHeaderId)])
|
||||
setRows([createFilterRow(defaultHeaderId, headerOptions)])
|
||||
}
|
||||
}, [resolvedOpen, initialRows, defaultHeaderId])
|
||||
}, [resolvedOpen, initialRows, defaultHeaderId, headerOptions])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
@@ -78,7 +80,7 @@ const ListFilterDialog = ({
|
||||
|
||||
const handleAddRow = () => {
|
||||
if (defaultHeaderId <= 0) return
|
||||
setRows((prev) => [...prev, createFilterRow(defaultHeaderId)])
|
||||
setRows((prev) => [...prev, createFilterRow(defaultHeaderId, headerOptions)])
|
||||
}
|
||||
|
||||
const handleRemoveRow = (id: string) => {
|
||||
@@ -89,16 +91,25 @@ const ListFilterDialog = ({
|
||||
setRows((prev) => prev.map((row) => (row.id === id ? updater(row) : row)))
|
||||
}
|
||||
|
||||
const getValueOptions = (headerId: number) => {
|
||||
return headerOptions.find((item) => item.id === headerId)?.values ?? []
|
||||
}
|
||||
const getHeaderOption = (headerId: number) => headerOptions.find((item) => item.id === headerId)
|
||||
|
||||
const getValueOptions = (headerId: number): FilterValueOption[] => getHeaderOption(headerId)?.valueOptions ?? []
|
||||
|
||||
// valueOptions가 undefined면 텍스트 입력 헤더, 빈 배열이면 "목록형인데 현재 선택 가능한 값이 없음"이므로 둘을 구분한다.
|
||||
const isListValueHeader = (headerId: number) => getHeaderOption(headerId)?.valueOptions !== undefined
|
||||
|
||||
const getAllowedOperators = (headerId: number): FilterOperator[] =>
|
||||
getHeaderOption(headerId)?.allowedOperators ?? ['eq', 'neq', 'contains', 'notContains', 'empty', 'notEmpty']
|
||||
|
||||
const isDisabledHeader = (headerId: number) => getHeaderOption(headerId)?.disabled === true
|
||||
|
||||
const serializedRows = useMemo(
|
||||
() =>
|
||||
rows
|
||||
.map((row) => {
|
||||
const hasValueOptions = getValueOptions(row.headerId).length > 0
|
||||
if (hasValueOptions) return row.multiValues.length > 0 ? row : null
|
||||
if (isDisabledHeader(row.headerId)) return null
|
||||
if (row.operator === 'empty' || row.operator === 'notEmpty') return row
|
||||
if (isListValueHeader(row.headerId)) return row.multiValues.length > 0 ? row : null
|
||||
return row.textValue.trim().length > 0 ? row : null
|
||||
})
|
||||
.filter((row): row is FilterRow => row !== null),
|
||||
@@ -107,7 +118,7 @@ const ListFilterDialog = ({
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (serializedRows.length === 0) {
|
||||
alert('필터 조건을 입력해 주세요.')
|
||||
alert('필터 조건을 입력해주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -121,141 +132,155 @@ const ListFilterDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[940px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">필터</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr_64px] items-center border-b bg-muted/40 px-4 text-sm font-semibold">
|
||||
<span>헤더</span>
|
||||
<span>비교 연산자</span>
|
||||
<span>값</span>
|
||||
<span />
|
||||
</div>
|
||||
|
||||
<div className="max-h-80 overflow-auto">
|
||||
{rows.map((row) => {
|
||||
const valueOptions = getValueOptions(row.headerId)
|
||||
const listMode = valueOptions.length > 0
|
||||
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className="grid min-h-12 grid-cols-[1fr_140px_1.4fr_64px] items-center gap-2 border-b px-4 py-2 last:border-b-0"
|
||||
>
|
||||
<Select
|
||||
value={String(row.headerId)}
|
||||
onValueChange={(value) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
headerId: Number(value),
|
||||
textValue: '',
|
||||
multiValues: [],
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="헤더 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{headerOptions.map((option) => (
|
||||
<SelectItem key={option.id} value={String(option.id)}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select
|
||||
value={row.operator}
|
||||
onValueChange={(value) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
operator: value as FilterOperator,
|
||||
textValue: '',
|
||||
multiValues: [],
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(Object.keys(operatorLabel) as FilterOperator[]).map((operator) => (
|
||||
<SelectItem key={operator} value={operator}>
|
||||
{operatorLabel[operator]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{listMode ? (
|
||||
<KriMultiSelect
|
||||
items={valueOptions}
|
||||
value={row.multiValues}
|
||||
onChange={(values) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
multiValues: values,
|
||||
}))
|
||||
}
|
||||
getValue={(item) => item}
|
||||
getLabel={(item) => item}
|
||||
placeholder="값 선택"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
className="w-full"
|
||||
spanClassName="text-sm"
|
||||
badgeClassName="text-xs"
|
||||
maxCount={2}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
placeholder="검색할 텍스트"
|
||||
value={row.textValue}
|
||||
onChange={(event) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
textValue: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleRemoveRow(row.id)}
|
||||
aria-label="조건 제거"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
조건 추가
|
||||
</Button>
|
||||
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">필터</span>}
|
||||
contentClassName="sm:max-w-[940px]"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
적용
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr_64px] items-center border-b bg-muted px-4 text-sm font-semibold">
|
||||
<span>헤더</span>
|
||||
<span>비교 연산자</span>
|
||||
<span>값</span>
|
||||
<span />
|
||||
</div>
|
||||
|
||||
<div className="max-h-80 overflow-auto">
|
||||
{rows.map((row) => {
|
||||
const valueOptions = getValueOptions(row.headerId)
|
||||
const listMode = isListValueHeader(row.headerId)
|
||||
const disabled = isDisabledHeader(row.headerId)
|
||||
const rowAllowedOperators = getAllowedOperators(row.headerId)
|
||||
const isEmptyOperator = row.operator === 'empty' || row.operator === 'notEmpty'
|
||||
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className="grid min-h-12 grid-cols-[1fr_140px_1.4fr_64px] items-center gap-2 border-b px-4 py-2 last:border-b-0"
|
||||
>
|
||||
<Select
|
||||
value={String(row.headerId)}
|
||||
disabled={disabled}
|
||||
onValueChange={(value) => {
|
||||
const nextHeaderId = Number(value)
|
||||
const nextAllowedOperators = getAllowedOperators(nextHeaderId)
|
||||
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
headerId: nextHeaderId,
|
||||
operator: nextAllowedOperators.includes(current.operator)
|
||||
? current.operator
|
||||
: nextAllowedOperators[0] ?? 'eq',
|
||||
textValue: '',
|
||||
multiValues: [],
|
||||
}))
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="헤더 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{headerOptions.map((option) => (
|
||||
<SelectItem key={option.id} value={String(option.id)} disabled={option.disabled}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select
|
||||
value={row.operator}
|
||||
disabled={disabled}
|
||||
onValueChange={(value) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
operator: value as FilterOperator,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{rowAllowedOperators.map((operator) => (
|
||||
<SelectItem key={operator} value={operator}>
|
||||
{operatorLabel[operator]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{isEmptyOperator ? (
|
||||
<Input placeholder="값을 입력할 필요 없음" value="" disabled />
|
||||
) : listMode ? (
|
||||
<KriMultiSelect
|
||||
items={valueOptions}
|
||||
value={row.multiValues}
|
||||
disabled={disabled}
|
||||
onChange={(values) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
multiValues: values,
|
||||
}))
|
||||
}
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="값 선택"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
className="w-full"
|
||||
spanClassName="text-sm"
|
||||
badgeClassName="text-xs"
|
||||
maxCount={2}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
placeholder="검색할 텍스트"
|
||||
value={row.textValue}
|
||||
disabled={disabled}
|
||||
onChange={(event) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
textValue: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
disabled={disabled}
|
||||
onClick={() => handleRemoveRow(row.id)}
|
||||
aria-label="조건 제거"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2" disabled={defaultHeaderId <= 0}>
|
||||
<Plus className="h-4 w-4" />
|
||||
조건 추가
|
||||
</Button>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
} from '@dnd-kit/sortable'
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
import { GripVertical, Plus, Trash2 } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -35,6 +35,7 @@ export type ListHeaderManageDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
prjctIdx: number
|
||||
rows: listHeader[]
|
||||
onConfirm: (rows: listHeader[]) => void | Promise<void>
|
||||
}
|
||||
@@ -76,7 +77,7 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
|
||||
style={style}
|
||||
className={cn(
|
||||
'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2',
|
||||
(activeId === row.listHderId || isDragging) && 'bg-muted/40',
|
||||
(activeId === row.listHderId || isDragging) && 'bg-muted',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center">
|
||||
@@ -173,6 +174,7 @@ const ListHeaderManageDialog = ({
|
||||
dialogId = 'listHeaderManageDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
prjctIdx,
|
||||
rows,
|
||||
onConfirm,
|
||||
}: ListHeaderManageDialogProps) => {
|
||||
@@ -275,6 +277,7 @@ const ListHeaderManageDialog = ({
|
||||
const newIndex = prev.filter((row) => row.listHderNm.startsWith('신규 헤더')).length + 1
|
||||
|
||||
const nextRow: listHeader = {
|
||||
prjctIdx,
|
||||
listHderId: nextId,
|
||||
listHderOrder: prev.length + 1,
|
||||
listHderGrad: ListHeaderGrade.COMMON,
|
||||
@@ -295,6 +298,7 @@ const ListHeaderManageDialog = ({
|
||||
try {
|
||||
const orderedRows = localRows.map((row, index) => ({
|
||||
...row,
|
||||
prjctIdx: row.prjctIdx ?? prjctIdx,
|
||||
listHderOrder: index + 1,
|
||||
}))
|
||||
await onConfirm(orderedRows)
|
||||
@@ -305,13 +309,24 @@ const ListHeaderManageDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[1200px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">리스트 헤더 관리</DialogTitle>
|
||||
</DialogHeader>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">리스트 헤더 관리</span>}
|
||||
contentClassName="sm:max-w-[1200px]"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
저장
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button type="button" className="gap-2 bg-blue" onClick={handleAddHeader} disabled={submitting}>
|
||||
<Plus className="w-4 h-4" />
|
||||
헤더 추가
|
||||
@@ -319,7 +334,7 @@ const ListHeaderManageDialog = ({
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<div className="h-11 px-4 border-b bg-muted/40 grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold">
|
||||
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold">
|
||||
<span>순서</span>
|
||||
<span>헤더명</span>
|
||||
<span>헤더 타입</span>
|
||||
@@ -355,16 +370,7 @@ const ListHeaderManageDialog = ({
|
||||
</DndContext>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
저장
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
@@ -50,47 +50,46 @@ const ListResetDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[700px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">리스트 초기화</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 py-2">
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold text-red-600">초기화 대상</p>
|
||||
<ApplyFilterOption
|
||||
value={target}
|
||||
onValueChange={(v) => setTarget(v)}
|
||||
idPrefix="list-reset-target"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold text-red-600">초기화 범위</p>
|
||||
<RadioGroup value={scope} onValueChange={(v) => setScope(v as ListResetScope)} className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="result-and-history" id="list-reset-scope-result-history" />
|
||||
<Label htmlFor="list-reset-scope-result-history">결과 + 이력 삭제</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="list-only" id="list-reset-scope-list-only" />
|
||||
<Label htmlFor="list-reset-scope-list-only">결과 + 이력 + 리스트 삭제</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">리스트 초기화</span>}
|
||||
contentClassName="sm:max-w-[700px]"
|
||||
bodyClassName="space-y-6 py-2"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" onClick={handleConfirm} disabled={submitting}>
|
||||
초기화
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold text-red-600">초기화 대상</p>
|
||||
<ApplyFilterOption
|
||||
value={target}
|
||||
onValueChange={(v) => setTarget(v)}
|
||||
idPrefix="list-reset-target"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold text-red-600">초기화 범위</p>
|
||||
<RadioGroup value={scope} onValueChange={(v) => setScope(v as ListResetScope)} className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="result-and-history" id="list-reset-scope-result-history" />
|
||||
<Label className="text-base" htmlFor="list-reset-scope-result-history">결과 + 이력 삭제</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="list-only" id="list-reset-scope-list-only" />
|
||||
<Label className="text-base" htmlFor="list-reset-scope-list-only">결과 + 이력 + 리스트 삭제</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import { ChevronDown, ChevronUp, Download, Upload, X } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Label } from '@/components/ui/label'
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import { KriSelect, KriSelectItem } from '@/components/common/KriSelect'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
@@ -32,6 +33,7 @@ export type ListUploadDialogProps = {
|
||||
}
|
||||
|
||||
const ACCEPT_EXTENSIONS = ['.xlsx', '.xls', '.csv']
|
||||
const FIXED_UPLOAD_MODE = ListUploadMode.ADD_AND_CHANGE
|
||||
|
||||
const ListUploadDialog = ({
|
||||
dialogId = 'listUploadDialog',
|
||||
@@ -50,7 +52,8 @@ const ListUploadDialog = ({
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [excelHeaders, setExcelHeaders] = useState<string[]>([])
|
||||
const [otherHeaderTypeMap, setOtherHeaderTypeMap] = useState<Record<number, ListHeaderType>>({})
|
||||
const [uploadMode, setUploadMode] = useState<ListUploadMode>(ListUploadMode.CHANGE)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [uploadMode, setUploadMode] = useState<ListUploadMode>(ListUploadMode.ADD_AND_CHANGE)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [historyExpanded, setHistoryExpanded] = useState(false)
|
||||
const [validation, setValidation] = useState<ValidationOption>({
|
||||
@@ -91,7 +94,7 @@ const ListUploadDialog = ({
|
||||
setSelectedFile(null)
|
||||
setExcelHeaders([])
|
||||
setOtherHeaderTypeMap({})
|
||||
setUploadMode(ListUploadMode.ADD)
|
||||
setUploadMode(ListUploadMode.ADD_AND_CHANGE)
|
||||
setSubmitting(false)
|
||||
setHistoryExpanded(false)
|
||||
setValidation({
|
||||
@@ -115,10 +118,19 @@ const ListUploadDialog = ({
|
||||
handleOpenChange(nextOpen)
|
||||
}
|
||||
|
||||
const decodeCsvText = (buffer: ArrayBuffer) => {
|
||||
// 한국 Windows 엑셀에서 저장한 CSV는 UTF-8이 아니라 EUC-KR(CP949)인 경우가 많다.
|
||||
try {
|
||||
return new TextDecoder('utf-8', { fatal: true }).decode(buffer)
|
||||
} catch {
|
||||
return new TextDecoder('euc-kr').decode(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
const extractHeaders = async (file: File) => {
|
||||
const lower = file.name.toLowerCase()
|
||||
if (lower.endsWith('.csv')) {
|
||||
const text = await file.text()
|
||||
const text = decodeCsvText(await file.arrayBuffer())
|
||||
const firstLine = text.split(/\r?\n/)[0] ?? ''
|
||||
return firstLine.split(',').map((s) => s.trim()).filter((s) => s.length > 0)
|
||||
}
|
||||
@@ -170,7 +182,7 @@ const ListUploadDialog = ({
|
||||
)
|
||||
|
||||
await onUpload(selectedFile, {
|
||||
uploadMode,
|
||||
uploadMode: FIXED_UPLOAD_MODE,
|
||||
checkDuplicateEmail: validation.checkEmailDuplicate,
|
||||
checkDuplicatePhone: validation.checkPhoneDuplicate,
|
||||
...(Object.keys(specificHeader).length > 0 ? { specificHeader } : {}),
|
||||
@@ -235,168 +247,167 @@ const ListUploadDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleDialogOpenChange}>
|
||||
<DialogContent className="overflow-hidden" style={{ width: 'min(960px, 95vw)', maxWidth: '95vw' }}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">리스트 업로드</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="min-w-0 space-y-6 py-2">
|
||||
{
|
||||
/*
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">업로드 방식</Label>
|
||||
<RadioGroup
|
||||
value={String(uploadMode)}
|
||||
onValueChange={(value) => setUploadMode(Number(value) as ListUploadMode)}
|
||||
className="flex flex-wrap items-center gap-6"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value={String(ListUploadMode.CHANGE)} id="list-upload-mode-change" />
|
||||
<Label htmlFor="list-upload-mode-change" className="cursor-pointer">
|
||||
전체 교체
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value={String(ListUploadMode.ADD)} id="list-upload-mode-add" />
|
||||
<Label htmlFor="list-upload-mode-add" className="cursor-pointer">
|
||||
추가
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
*/
|
||||
}
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">업로드 파일</Label>
|
||||
<div className="min-w-0 flex items-center gap-2">
|
||||
<Button type="button" className="shrink-0 bg-excel text-base" onClick={onDownloadTemplate}>
|
||||
<Download className="w-4 h-4" />
|
||||
양식 다운로드
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-w-0 flex-1 justify-start text-lg"
|
||||
disabled={submitting}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="w-4 h-4 shrink-0" />
|
||||
<span className="min-w-0 truncate">{selectedFile ? selectedFile.name : '업로드 파일을 선택해 주세요.'}</span>
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" size="icon-sm" disabled={!selectedFile || submitting} onClick={resetState} aria-label="선택 파일 제거">
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
<input ref={fileInputRef} type="file" accept={ACCEPT_EXTENSIONS.join(',')} className="hidden" onChange={handleSelectFile} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedFile && excelHeaders.length > 0 && compareRows.length > 0 && (
|
||||
<div className="min-w-0 space-y-3">
|
||||
<Label className="text-lg font-semibold">헤더 비교</Label>
|
||||
<div className="block w-full max-w-full overflow-x-scroll rounded-md border pb-1">
|
||||
<div className="w-max whitespace-nowrap">
|
||||
{headerCompareList.map(({ header, index, isMatched, isSettingRequired, serverHeader }) => {
|
||||
return (
|
||||
<div key={`${header}-${index}`} className="inline-block w-[125px] align-top border-r last:border-r-0">
|
||||
<div className="flex h-8 items-center truncate bg-slate-700 px-2.5 text-sm font-medium text-slate-50">
|
||||
{header || `컬럼${index + 1}`}
|
||||
</div>
|
||||
<div className="flex h-9 items-center border-t px-2">
|
||||
{renderHeaderTypeCell(serverHeader, isMatched, isSettingRequired, index)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">중복 검증</Label>
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="list-upload-email-dup"
|
||||
checked={validation.checkEmailDuplicate}
|
||||
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkEmailDuplicate: checked === true }))}
|
||||
/>
|
||||
<Label htmlFor="list-upload-email-dup" className="cursor-pointer">
|
||||
이메일 중복검증
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="list-upload-phone-dup"
|
||||
checked={validation.checkPhoneDuplicate}
|
||||
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkPhoneDuplicate: checked === true }))}
|
||||
/>
|
||||
<Label htmlFor="list-upload-phone-dup" className="cursor-pointer">
|
||||
전화번호 중복검증
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border">
|
||||
<button type="button" className="flex h-11 w-full items-center justify-between border-b px-4 text-left" onClick={() => setHistoryExpanded((prev) => !prev)}>
|
||||
<span className="text-lg font-semibold">업로드 이력({normalizedHistory.length} 회)</span>
|
||||
{historyExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
</button>
|
||||
{historyExpanded && (
|
||||
<div className="h-[160px] overflow-y-auto">
|
||||
<table className="w-full text-base">
|
||||
<thead className="sticky top-0 border-b bg-white">
|
||||
<tr>
|
||||
<th className="h-9 px-3 text-center">회차</th>
|
||||
<th className="h-9 px-3 text-center">파일명</th>
|
||||
<th className="h-9 px-3 text-center">사용자 ID</th>
|
||||
<th className="h-9 px-3 text-center">업로드 건수</th>
|
||||
<th className="h-9 px-3 text-center">업로드 일시</th>
|
||||
<th className="h-9 px-3 text-center">다운로드</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{normalizedHistory.length === 0 && (
|
||||
<tr>
|
||||
<td className="h-12 px-3 text-center text-muted-foreground" colSpan={6}>
|
||||
업로드 이력이 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{normalizedHistory.map((item) => (
|
||||
<tr key={item.listUploadLogId} className="border-b last:border-b-0">
|
||||
<td className="h-10 px-3 text-center">{item.wave}</td>
|
||||
<td className="h-10 px-3 text-center">{item.fileName}</td>
|
||||
<td className="h-10 px-3 text-center">{item.regUser}</td>
|
||||
<td className="h-10 px-3 text-center">{item.listCount.toLocaleString()}</td>
|
||||
<td className="h-10 px-3 text-center">{item.uploadAtLabel}</td>
|
||||
<td className="h-10 px-3 text-center">
|
||||
<Button type="button" size="sm" className="bg-excel" onClick={() => onDownloadHistory?.(item)}>
|
||||
<Download className="h-4 w-4" />
|
||||
다운로드
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
title={<span className="text-2xl font-bold">리스트 업로드</span>}
|
||||
contentClassName="w-[min(960px,95vw)] max-w-[95vw] sm:max-w-[min(960px,95vw)] overflow-hidden"
|
||||
bodyClassName="min-w-0 space-y-6 py-2"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleDialogOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting || hasHeaderMismatch}>
|
||||
{submitting ? '업로드 중...' : '업로드'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{
|
||||
/*
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">업로드 방식</Label>
|
||||
<RadioGroup
|
||||
value={String(uploadMode)}
|
||||
onValueChange={(value) => setUploadMode(Number(value) as ListUploadMode)}
|
||||
className="flex flex-wrap items-center gap-6"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value={String(ListUploadMode.CHANGE)} id="list-upload-mode-change" />
|
||||
<Label htmlFor="list-upload-mode-change" className="cursor-pointer">
|
||||
전체 교체
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value={String(ListUploadMode.ADD)} id="list-upload-mode-add" />
|
||||
<Label htmlFor="list-upload-mode-add" className="cursor-pointer">
|
||||
추가
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
*/
|
||||
}
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">업로드 파일</Label>
|
||||
<div className="min-w-0 flex items-center gap-2">
|
||||
<Button type="button" className="shrink-0 bg-excel text-base" onClick={onDownloadTemplate}>
|
||||
<Download className="w-4 h-4" />
|
||||
양식 다운로드
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-w-0 flex-1 justify-start text-lg"
|
||||
disabled={submitting}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="w-4 h-4 shrink-0" />
|
||||
<span className="min-w-0 truncate text-sm">{selectedFile ? selectedFile.name : '업로드 파일을 선택해 주세요.'}</span>
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" size="icon-sm" disabled={!selectedFile || submitting} onClick={resetState} aria-label="선택 파일 제거">
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
<input ref={fileInputRef} type="file" accept={ACCEPT_EXTENSIONS.join(',')} className="hidden" onChange={handleSelectFile} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedFile && excelHeaders.length > 0 && compareRows.length > 0 && (
|
||||
<div className="min-w-0 space-y-3">
|
||||
<Label className="text-lg font-semibold">헤더 비교</Label>
|
||||
<div className="block w-full max-w-full overflow-x-scroll rounded-md border pb-1">
|
||||
<div className="w-max whitespace-nowrap">
|
||||
{headerCompareList.map(({ header, index, isMatched, isSettingRequired, serverHeader }) => {
|
||||
return (
|
||||
<div key={`${header}-${index}`} className="inline-block w-[125px] align-top border-r last:border-r-0">
|
||||
<div className="flex h-8 items-center truncate bg-slate-700 px-2.5 text-sm font-medium text-slate-50">
|
||||
{header || `컬럼${index + 1}`}
|
||||
</div>
|
||||
<div className="flex h-9 items-center border-t px-2">
|
||||
{renderHeaderTypeCell(serverHeader, isMatched, isSettingRequired, index)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">중복 검증</Label>
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="list-upload-email-dup"
|
||||
checked={validation.checkEmailDuplicate}
|
||||
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkEmailDuplicate: checked === true }))}
|
||||
/>
|
||||
<Label htmlFor="list-upload-email-dup" className="cursor-pointer text-base">
|
||||
이메일 중복검증
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="list-upload-phone-dup"
|
||||
checked={validation.checkPhoneDuplicate}
|
||||
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkPhoneDuplicate: checked === true }))}
|
||||
/>
|
||||
<Label htmlFor="list-upload-phone-dup" className="cursor-pointer text-base">
|
||||
전화번호 중복검증
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border">
|
||||
<button type="button" className="flex h-11 w-full items-center justify-between border-b px-4 text-left" onClick={() => setHistoryExpanded((prev) => !prev)}>
|
||||
<span className="text-lg font-semibold">업로드 이력({normalizedHistory.length} 회)</span>
|
||||
{historyExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
</button>
|
||||
{historyExpanded && (
|
||||
<div className="h-[160px] overflow-y-auto">
|
||||
<table className="w-full text-base">
|
||||
<thead className="sticky top-0 border-b bg-white">
|
||||
<tr>
|
||||
<th className="h-9 px-3 text-center">회차</th>
|
||||
<th className="h-9 px-3 text-center">파일명</th>
|
||||
<th className="h-9 px-3 text-center">사용자 ID</th>
|
||||
<th className="h-9 px-3 text-center">업로드 건수</th>
|
||||
<th className="h-9 px-3 text-center">업로드 일시</th>
|
||||
<th className="h-9 px-3 text-center">다운로드</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{normalizedHistory.length === 0 && (
|
||||
<tr>
|
||||
<td className="h-12 px-3 text-center text-muted-foreground" colSpan={6}>
|
||||
업로드 이력이 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{normalizedHistory.map((item) => (
|
||||
<tr key={item.listUploadLogId} className="border-b last:border-b-0">
|
||||
<td className="h-10 px-3 text-center">{item.wave}</td>
|
||||
<td className="h-10 px-3 text-center">{item.fileName}</td>
|
||||
<td className="h-10 px-3 text-center">{item.regUser}</td>
|
||||
<td className="h-10 px-3 text-center">{item.listCount.toLocaleString()}</td>
|
||||
<td className="h-10 px-3 text-center">{item.uploadAtLabel}</td>
|
||||
<td className="h-10 px-3 text-center">
|
||||
<Button type="button" size="sm" className="bg-excel" onClick={() => onDownloadHistory?.(item)}>
|
||||
<Download className="h-4 w-4" />
|
||||
다운로드
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,39 +1,28 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DataTable } from '@/components/data-table/DataTable'
|
||||
import type { DataTableColumn } from '@/components/data-table/DataTable.type'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||
import { useBulkSendDetailExcelMutation, useBulkSendDetailQuery, useBulkSendListQuery } from '@/query/message'
|
||||
import { MessageType } from '@kri/common/noti-hub'
|
||||
import { downloadBase64File, XLSX_MIME_TYPE } from '@kri/common/browser'
|
||||
import { formatKst } from '@kri/common'
|
||||
import type { PaginationState } from '@tanstack/react-table'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { BulkSendInfo } from '@kri/common/noti-hub'
|
||||
import type { SendResultInfo } from '@/types/message'
|
||||
import {clientEnv} from "@/lib/env.client";
|
||||
|
||||
export type MessageHistoryType = 'sms' | 'email'
|
||||
export type MessageHistoryDetailType = 'template' | 'target' | 'success' | 'fail' | null
|
||||
|
||||
export type MessageHistoryRow = {
|
||||
id: number
|
||||
type: MessageHistoryType
|
||||
title: string
|
||||
templateName: string
|
||||
sendInfo: string
|
||||
targetHeader: string
|
||||
targetCount: number
|
||||
successCount: number
|
||||
failCount: number
|
||||
createdAt: string
|
||||
sendAt: string
|
||||
status: string
|
||||
templatePreview?: string
|
||||
targetPreview?: string[]
|
||||
successPreview?: string[]
|
||||
failPreview?: string[]
|
||||
}
|
||||
|
||||
export type MessageHistoryDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
rows: MessageHistoryRow[]
|
||||
onDownload?: (row: MessageHistoryRow, detailType: Exclude<MessageHistoryDetailType, null>) => void | Promise<void>
|
||||
}
|
||||
|
||||
const tabLabelMap: Record<MessageHistoryType, string> = {
|
||||
@@ -41,26 +30,64 @@ const tabLabelMap: Record<MessageHistoryType, string> = {
|
||||
email: '이메일',
|
||||
}
|
||||
|
||||
const historyColumns: DataTableColumn<BulkSendInfo>[] = [
|
||||
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
|
||||
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
|
||||
{ id: 'resve', header: '구분', accessorFn: (row) => (row.resve ? '예약' : '즉시') },
|
||||
{ id: 'trgtCnt', header: '대상수', accessorFn: (row) => row.trgtCnt.toLocaleString() },
|
||||
{ id: 'sendCnt', header: '발송수', accessorFn: (row) => row.sendCnt.toLocaleString() },
|
||||
{ id: 'succesCnt', header: '성공', accessorFn: (row) => row.succesCnt.toLocaleString() },
|
||||
{ id: 'failCnt', header: '실패', accessorFn: (row) => row.failCnt.toLocaleString() },
|
||||
{ id: 'completeDt', header: '완료 일시', accessorFn: (row) => (row.completeDt ? formatKst(row.completeDt, 'dateTime') : '-') },
|
||||
{ id: 'regUser', header: '등록자', accessorFn: (row) => row.regUser ?? '-' },
|
||||
]
|
||||
|
||||
const detailColumns: DataTableColumn<SendResultInfo>[] = [
|
||||
{ id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || row.destTel || '-' },
|
||||
{ id: 'destNm', header: '수신자명', accessorFn: (row) => row.destNm ?? '-' },
|
||||
{ id: 'sendFrom', header: '발신지', accessorFn: (row) => row.sendEml || row.sendTel || '-' },
|
||||
{ id: 'resultViewLabel', header: '결과', accessorFn: (row) => row.resultViewLabel || row.resultLabel || String(row.resultCode) },
|
||||
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
|
||||
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
|
||||
]
|
||||
|
||||
const MessageHistoryDialog = ({
|
||||
dialogId = 'messageHistoryDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
rows,
|
||||
onDownload,
|
||||
}: MessageHistoryDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const { selectedProject } = useSelectedProject()
|
||||
const [tab, setTab] = useState<MessageHistoryType>('sms')
|
||||
const [selectedId, setSelectedId] = useState<number | null>(null)
|
||||
const [detailType, setDetailType] = useState<MessageHistoryDetailType>(null)
|
||||
const [selectedKey, setSelectedKey] = useState<string | null>(null)
|
||||
const [detailPagination, setDetailPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 })
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
const prjctCd = selectedProject?.prjctCd ?? ''
|
||||
const enabled = resolvedOpen && !!prjctCd
|
||||
|
||||
const visibleRows = useMemo(() => rows.filter((row) => row.type === tab), [rows, tab])
|
||||
const emailListQuery = useBulkSendListQuery(MessageType.EMAIL, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'email')
|
||||
const smsListQuery = useBulkSendListQuery(MessageType.SMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
|
||||
const lmsListQuery = useBulkSendListQuery(MessageType.LMS_MMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
|
||||
|
||||
const selectedRow = useMemo(
|
||||
() => visibleRows.find((row) => row.id === selectedId) ?? null,
|
||||
[visibleRows, selectedId],
|
||||
const visibleRows = useMemo(() => {
|
||||
if (tab === 'email') return emailListQuery.data ?? []
|
||||
return [...(smsListQuery.data ?? []), ...(lmsListQuery.data ?? [])].sort((a, b) =>
|
||||
(b.regDt ?? '').localeCompare(a.regDt ?? ''),
|
||||
)
|
||||
}, [tab, emailListQuery.data, smsListQuery.data, lmsListQuery.data])
|
||||
|
||||
const detailQuery = useBulkSendDetailQuery(
|
||||
selectedKey ?? '',
|
||||
{
|
||||
pageIndex: detailPagination.pageIndex,
|
||||
pageSize: detailPagination.pageSize,
|
||||
sortBy: 'regDt',
|
||||
sortDir: 'desc',
|
||||
},
|
||||
enabled && !!selectedKey,
|
||||
)
|
||||
const detailExcelMutation = useBulkSendDetailExcelMutation()
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
@@ -69,142 +96,85 @@ const MessageHistoryDialog = ({
|
||||
return
|
||||
}
|
||||
hideDialog(dialogId)
|
||||
setSelectedId(null)
|
||||
setDetailType(null)
|
||||
setSelectedKey(null)
|
||||
}
|
||||
|
||||
const handlePickDetail = (rowId: number, nextType: Exclude<MessageHistoryDetailType, null>) => {
|
||||
setSelectedId(rowId)
|
||||
setDetailType(nextType)
|
||||
const handleSelectTab = (nextTab: MessageHistoryType) => {
|
||||
setTab(nextTab)
|
||||
setSelectedKey(null)
|
||||
}
|
||||
|
||||
const detailContent = useMemo(() => {
|
||||
if (!selectedRow || !detailType) return null
|
||||
if (detailType === 'template') return selectedRow.templatePreview ?? '(미리보기 데이터 없음)'
|
||||
if (detailType === 'target') return (selectedRow.targetPreview ?? []).join('\n')
|
||||
if (detailType === 'success') return (selectedRow.successPreview ?? []).join('\n')
|
||||
if (detailType === 'fail') return (selectedRow.failPreview ?? []).join('\n')
|
||||
return null
|
||||
}, [selectedRow, detailType])
|
||||
const handleSelectRow = (row: BulkSendInfo) => {
|
||||
setSelectedKey(row.bulkSendKey)
|
||||
setDetailPagination({ pageIndex: 0, pageSize: 10 })
|
||||
}
|
||||
|
||||
const handleDownloadDetail = async () => {
|
||||
if (!selectedKey) return
|
||||
const result = await detailExcelMutation.mutateAsync(selectedKey)
|
||||
if (!result.fileBase64) {
|
||||
alert('다운로드할 데이터가 없습니다.')
|
||||
return
|
||||
}
|
||||
downloadBase64File(result.fileBase64, result.fileName, XLSX_MIME_TYPE)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[1200px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">발송 이력</DialogTitle>
|
||||
</DialogHeader>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">발송 이력</span>}
|
||||
contentClassName="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto"
|
||||
closeLabel="닫기"
|
||||
bodyClassName="space-y-4"
|
||||
>
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => handleSelectTab('sms')}>
|
||||
{tabLabelMap.sms}
|
||||
</Button>
|
||||
<Button type="button" variant={tab === 'email' ? 'default' : 'outline'} onClick={() => handleSelectTab('email')}>
|
||||
{tabLabelMap.email}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => setTab('sms')}>
|
||||
{tabLabelMap.sms}
|
||||
</Button>
|
||||
<Button type="button" variant={tab === 'email' ? 'default' : 'outline'} onClick={() => setTab('email')}>
|
||||
{tabLabelMap.email}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<DataTable<BulkSendInfo>
|
||||
columns={historyColumns}
|
||||
data={visibleRows}
|
||||
getRowId={(row) => row.bulkSendKey}
|
||||
isClient
|
||||
selectMode="click-event"
|
||||
onRowClick={handleSelectRow}
|
||||
highlightRowIds={selectedKey ? [selectedKey] : []}
|
||||
emptyText="발송 이력이 없습니다."
|
||||
pageSizeOptions={[5, 10, 20]}
|
||||
defaultPageSize={5}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 xl:grid-cols-[1.7fr_1fr] gap-4">
|
||||
<div className="rounded-md border overflow-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 bg-white border-b">
|
||||
<tr>
|
||||
<th className="px-2 h-9 text-left">회차</th>
|
||||
<th className="px-2 h-9 text-left">제목</th>
|
||||
<th className="px-2 h-9 text-left">템플릿</th>
|
||||
<th className="px-2 h-9 text-left">발송 정보</th>
|
||||
<th className="px-2 h-9 text-left">타겟 헤더</th>
|
||||
<th className="px-2 h-9 text-right">대상수</th>
|
||||
<th className="px-2 h-9 text-right">성공</th>
|
||||
<th className="px-2 h-9 text-right">실패</th>
|
||||
<th className="px-2 h-9 text-left">등록 일시</th>
|
||||
<th className="px-2 h-9 text-left">발송 일시</th>
|
||||
<th className="px-2 h-9 text-left">상태</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{visibleRows.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={11} className="h-12 text-center text-muted-foreground">
|
||||
발송 이력이 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{visibleRows.map((row) => (
|
||||
<tr key={`${row.type}-${row.id}`} className="border-b last:border-b-0">
|
||||
<td className="px-2 h-10">{row.id}</td>
|
||||
<td className="px-2 h-10">{row.title}</td>
|
||||
<td className="px-2 h-10">
|
||||
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'template')}>
|
||||
{row.templateName}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-2 h-10">{row.sendInfo}</td>
|
||||
<td className="px-2 h-10">
|
||||
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'target')}>
|
||||
{row.targetHeader}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-2 h-10 text-right">{row.targetCount}</td>
|
||||
<td className="px-2 h-10 text-right">
|
||||
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'success')}>
|
||||
{row.successCount}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-2 h-10 text-right">
|
||||
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'fail')}>
|
||||
{row.failCount}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-2 h-10">{row.createdAt}</td>
|
||||
<td className="px-2 h-10">{row.sendAt}</td>
|
||||
<td className="px-2 h-10">{row.status}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-4 space-y-3 min-h-80">
|
||||
<p className="text-lg font-semibold">
|
||||
{detailType === null && '상세 이력'}
|
||||
{detailType === 'template' && '미리보기'}
|
||||
{detailType === 'target' && '수신 대상'}
|
||||
{detailType === 'success' && '성공 이력'}
|
||||
{detailType === 'fail' && '실패 이력'}
|
||||
</p>
|
||||
|
||||
{detailType === null && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
템플릿, 대상수, 성공, 실패 항목을 선택하면 상세 영역이 열립니다.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{detailType !== null && (
|
||||
<>
|
||||
<pre className="rounded border p-3 text-sm whitespace-pre-wrap min-h-56">{detailContent}</pre>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
if (!selectedRow || !detailType) return
|
||||
onDownload?.(selectedRow, detailType)
|
||||
}}
|
||||
disabled={!selectedRow || !detailType || !onDownload}
|
||||
>
|
||||
다운로드
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{selectedKey && (
|
||||
<div className="rounded-md border p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-lg font-semibold">상세 이력</p>
|
||||
<Button type="button" variant="outline" onClick={handleDownloadDetail} disabled={detailExcelMutation.isPending}>
|
||||
다운로드
|
||||
</Button>
|
||||
</div>
|
||||
<DataTable<SendResultInfo>
|
||||
columns={detailColumns}
|
||||
data={detailQuery.data?.content ?? []}
|
||||
getRowId={(row) => row.cmid}
|
||||
isClient={false}
|
||||
pageCount={detailQuery.data?.totalPages ?? 0}
|
||||
totalCount={detailQuery.data?.totalElements ?? 0}
|
||||
pagination={detailPagination}
|
||||
onPaginationChange={setDetailPagination}
|
||||
emptyText="상세 이력이 없습니다."
|
||||
pageSizeOptions={[10, 20, 30]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" onClick={() => handleOpenChange(false)}>
|
||||
닫기
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,60 +1,54 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useEffect, useMemo, useRef, 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 { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { KriDateTimePicker } from '@/components/common/KriDateTimePicker'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||
import { useListSearchQuery } from '@/query/list'
|
||||
import {
|
||||
useCreateBulkSendKeyMutation,
|
||||
useMainTemplateIdxQuery,
|
||||
useSendBulkMutation,
|
||||
useTemplateListQuery,
|
||||
useTemplateQuery,
|
||||
} from '@/query/message'
|
||||
import {ChannelType, type DestInfo, TemplateSms, type TemplateSummary} from '@kri/common/noti-hub'
|
||||
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { getNearestFutureDateTime } from '@/lib/datetime'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import { createEmptyListFilter, type ListFilter, type ListFilterTarget, type listHeader } from '@/types/list'
|
||||
import { ListHeaderConst } from '@/const/listConst'
|
||||
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||
import ApplyFilterOption from './ListDialogOption/ApplyFilterOption'
|
||||
import {KriEditor} from "@/components/kri-editor";
|
||||
import {clientEnv} from "@/lib/env.client";
|
||||
|
||||
export type MessageSendMode = 'email' | 'sms'
|
||||
export type ScheduleType = 'instant' | 'reserve'
|
||||
|
||||
export type MessageTemplateOption = {
|
||||
id: string
|
||||
name: string
|
||||
title: string
|
||||
body: string
|
||||
}
|
||||
const MAX_TARGET_COUNT = 5000
|
||||
|
||||
export type MessageSendHeaderOption = {
|
||||
id: number
|
||||
label: string
|
||||
}
|
||||
|
||||
export type MessageSendPayload = {
|
||||
mode: MessageSendMode
|
||||
templateId: string
|
||||
senderEmail: string
|
||||
senderName: string
|
||||
senderNumber: string
|
||||
title: string
|
||||
body: string
|
||||
scheduleType: ScheduleType
|
||||
reserveAt?: string
|
||||
targetHeaderId: number
|
||||
}
|
||||
const toTargetRow = (row: ListTableRow): { sid: string; itemList: Record<number, string> } => ({
|
||||
sid: String(row.sid ?? ''),
|
||||
itemList: (row.itemList as Record<number, string> | undefined) ?? {},
|
||||
})
|
||||
|
||||
export type MessageSendDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
mode: MessageSendMode
|
||||
templateOptions: MessageTemplateOption[]
|
||||
targetHeaderOptions: MessageSendHeaderOption[]
|
||||
defaultSenderEmail?: string
|
||||
defaultSenderName?: string
|
||||
defaultSenderNumber?: string
|
||||
onConfirm: (payload: MessageSendPayload) => void | Promise<void>
|
||||
listHeaders: listHeader[]
|
||||
currentFilter: ListFilter
|
||||
selectedRows: ListTableRow[]
|
||||
onSent?: () => void
|
||||
}
|
||||
|
||||
const titleMap: Record<MessageSendMode, string> = {
|
||||
@@ -67,45 +61,105 @@ const MessageSendDialog = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
mode,
|
||||
templateOptions,
|
||||
targetHeaderOptions,
|
||||
defaultSenderEmail = '',
|
||||
defaultSenderName = '',
|
||||
defaultSenderNumber = '',
|
||||
onConfirm,
|
||||
listHeaders,
|
||||
currentFilter,
|
||||
selectedRows,
|
||||
onSent,
|
||||
}: MessageSendDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const [templateId, setTemplateId] = useState('')
|
||||
const [title, setTitle] = useState('')
|
||||
const [body, setBody] = useState('')
|
||||
const [senderEmail, setSenderEmail] = useState(defaultSenderEmail)
|
||||
const [senderName, setSenderName] = useState(defaultSenderName)
|
||||
const [senderNumber, setSenderNumber] = useState(defaultSenderNumber)
|
||||
const [scheduleType, setScheduleType] = useState<ScheduleType>('instant')
|
||||
const { auth } = useAuth()
|
||||
const { selectedProject } = useSelectedProject()
|
||||
|
||||
const chnnlTy = mode === 'email' ? ChannelType.EMAIL : ChannelType.SMS
|
||||
|
||||
const [templateIdx, setTemplateIdx] = useState<number | null>(null)
|
||||
const [senderEmail, setSenderEmail] = useState('')
|
||||
const [senderName, setSenderName] = useState('')
|
||||
const [senderNumber, setSenderNumber] = useState('')
|
||||
const [scheduleType, setScheduleType] = useState<'instant' | 'reserve'>('instant')
|
||||
const [reserveAt, setReserveAt] = useState('')
|
||||
const [targetHeaderId, setTargetHeaderId] = useState<number>(targetHeaderOptions[0]?.id ?? 0)
|
||||
const [targetHeaderId, setTargetHeaderId] = useState<number | null>(null)
|
||||
const [target, setTarget] = useState<ListFilterTarget>('selected')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
|
||||
const selectedTemplate = useMemo(
|
||||
() => templateOptions.find((template) => template.id === templateId),
|
||||
[templateId, templateOptions],
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0
|
||||
const prjctCd = selectedProject?.prjctCd ?? ''
|
||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? ''
|
||||
const enabled = resolvedOpen && !!selectedProject && prjctIdx > 0
|
||||
|
||||
const templateListQuery = useTemplateListQuery(chnnlTy, itrntPrjctCd, enabled)
|
||||
const templateList: TemplateSummary[] = templateListQuery.data ?? []
|
||||
const templateDetailQuery = useTemplateQuery(templateIdx ?? 0, enabled && !!templateIdx)
|
||||
const selectedTemplate = templateDetailQuery.data ?? null
|
||||
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
|
||||
const mainTemplateIdx = mainTemplateQuery.data ?? null
|
||||
|
||||
const headerType = mode === 'email' ? ListHeaderConst.EMAIL : ListHeaderConst.TEL_NUM
|
||||
const targetHeaderOptions = useMemo(
|
||||
() => listHeaders.filter((header) => header.listHderTy === headerType),
|
||||
[listHeaders, headerType],
|
||||
)
|
||||
|
||||
// '전체'/'필터 적용 대상'은 현재 페이지에 보이는 행을 넘어설 수 있어 별도로 넓게 조회한다
|
||||
const bulkTargetFilter = target === 'all' ? createEmptyListFilter() : currentFilter
|
||||
const bulkTargetEnabled = enabled && target !== 'selected'
|
||||
const bulkTargetQuery = useListSearchQuery(
|
||||
prjctIdx,
|
||||
{
|
||||
listFilter: bulkTargetFilter,
|
||||
pageRequest: { pageIndex: 0, pageSize: MAX_TARGET_COUNT, sortBy: 'sid', sortDir: 'asc' },
|
||||
},
|
||||
bulkTargetEnabled,
|
||||
)
|
||||
|
||||
const targetRows = useMemo(() => {
|
||||
const rows = target === 'selected' ? selectedRows : (bulkTargetQuery.data?.content ?? [])
|
||||
return rows.map(toTargetRow)
|
||||
}, [target, selectedRows, bulkTargetQuery.data])
|
||||
|
||||
const targetTotalCount = target === 'selected' ? selectedRows.length : (bulkTargetQuery.data?.totalElements ?? 0)
|
||||
const isTargetTruncated = target !== 'selected' && targetTotalCount > MAX_TARGET_COUNT
|
||||
|
||||
const createBulkKeyMutation = useCreateBulkSendKeyMutation(mode)
|
||||
const sendBulkMutation = useSendBulkMutation(mode)
|
||||
|
||||
const mainTemplateAppliedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!resolvedOpen) return
|
||||
const firstTemplate = templateOptions[0]
|
||||
setTemplateId(firstTemplate?.id ?? '')
|
||||
setTitle(firstTemplate?.title ?? '')
|
||||
setBody(firstTemplate?.body ?? '')
|
||||
setTemplateIdx(null)
|
||||
setSenderEmail('')
|
||||
setSenderName('')
|
||||
setSenderNumber('')
|
||||
setScheduleType('instant')
|
||||
setReserveAt('')
|
||||
setTargetHeaderId(targetHeaderOptions[0]?.id ?? 0)
|
||||
setSenderEmail(defaultSenderEmail)
|
||||
setSenderName(defaultSenderName)
|
||||
setSenderNumber(defaultSenderNumber)
|
||||
}, [resolvedOpen, templateOptions, targetHeaderOptions, defaultSenderEmail, defaultSenderName, defaultSenderNumber])
|
||||
setTarget('selected')
|
||||
setTargetHeaderId(null)
|
||||
mainTemplateAppliedRef.current = false
|
||||
}, [resolvedOpen])
|
||||
|
||||
// 대표 템플릿이 있으면 최초 1회 자동 선택
|
||||
useEffect(() => {
|
||||
if (!enabled || mainTemplateAppliedRef.current || !mainTemplateQuery.isSuccess) return
|
||||
mainTemplateAppliedRef.current = true
|
||||
if (mainTemplateIdx) setTemplateIdx(mainTemplateIdx)
|
||||
}, [enabled, mainTemplateQuery.isSuccess, mainTemplateIdx])
|
||||
|
||||
// 템플릿 상세가 도착하면 발신 정보를 세팅한다 (발송 전 수정 가능)
|
||||
useEffect(() => {
|
||||
if (!selectedTemplate) return
|
||||
setSenderName(selectedTemplate.sendNm)
|
||||
if ('sendEml' in selectedTemplate) setSenderEmail(selectedTemplate.sendEml)
|
||||
if ('sendTel' in selectedTemplate) setSenderNumber(selectedTemplate.sendTel)
|
||||
}, [selectedTemplate])
|
||||
|
||||
useEffect(() => {
|
||||
if (targetHeaderId !== null) return
|
||||
const first = targetHeaderOptions[0]
|
||||
if (first) setTargetHeaderId(first.listHderId)
|
||||
}, [targetHeaderOptions, targetHeaderId])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
@@ -116,175 +170,235 @@ const MessageSendDialog = ({
|
||||
hideDialog(dialogId)
|
||||
}
|
||||
|
||||
const handleTemplateChange = (nextTemplateId: string) => {
|
||||
const template = templateOptions.find((item) => item.id === nextTemplateId)
|
||||
setTemplateId(nextTemplateId)
|
||||
if (!template) return
|
||||
setTitle(template.title)
|
||||
setBody(template.body)
|
||||
const handleScheduleTypeChange = (next: 'instant' | 'reserve') => {
|
||||
setScheduleType(next)
|
||||
if (next === 'reserve' && !reserveAt) {
|
||||
setReserveAt(getNearestFutureDateTime())
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectTemplate = (value: string) => {
|
||||
const idx = Number(value)
|
||||
setTemplateIdx(Number.isFinite(idx) && idx > 0 ? idx : null)
|
||||
}
|
||||
|
||||
const buildMsgParam = (itemList: Record<number, string>): Record<string, string> => {
|
||||
const param: Record<string, string> = {}
|
||||
listHeaders.forEach((header) => {
|
||||
const value = itemList[header.listHderId]
|
||||
if (value !== undefined) param[header.listHderNm] = value
|
||||
})
|
||||
return param
|
||||
}
|
||||
|
||||
const buildDestInfoList = (): DestInfo[] => {
|
||||
if (!targetHeaderId) return []
|
||||
return targetRows.map(({ sid, itemList }) => {
|
||||
const destValue = itemList[targetHeaderId] ?? ''
|
||||
return {
|
||||
sid,
|
||||
destEml: mode === 'email' ? destValue : undefined,
|
||||
destTel: mode === 'sms' ? destValue : undefined,
|
||||
msgParam: buildMsgParam(itemList),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!templateId) {
|
||||
if (!selectedTemplate || !templateIdx) {
|
||||
alert('템플릿을 선택해 주세요.')
|
||||
return
|
||||
}
|
||||
if (!title.trim() || !body.trim()) {
|
||||
alert('제목과 내용을 입력해 주세요.')
|
||||
if (!targetHeaderId) {
|
||||
alert(`수신 ${mode === 'email' ? '이메일' : '번호'} 헤더를 선택해 주세요.`)
|
||||
return
|
||||
}
|
||||
if (mode === 'email' && !senderEmail.trim()) {
|
||||
alert('발송자 메일을 입력해 주세요.')
|
||||
return
|
||||
}
|
||||
if (mode === 'sms' && !senderNumber.trim()) {
|
||||
alert('발송 번호를 입력해 주세요.')
|
||||
return
|
||||
}
|
||||
if (mode === 'email' && (!senderEmail.trim() || !senderName.trim())) {
|
||||
alert('발송자 정보를 입력해 주세요.')
|
||||
return
|
||||
}
|
||||
if (scheduleType === 'reserve' && !reserveAt) {
|
||||
alert('예약 발송 일시를 선택해 주세요.')
|
||||
return
|
||||
}
|
||||
if (isTargetTruncated) {
|
||||
alert(`수신 대상이 ${MAX_TARGET_COUNT}건을 초과합니다. 대상 범위를 좁혀 주세요.`)
|
||||
return
|
||||
}
|
||||
const destInfoList = buildDestInfoList()
|
||||
if (destInfoList.length === 0) {
|
||||
alert('수신 대상이 없습니다.')
|
||||
return
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await onConfirm({
|
||||
mode,
|
||||
templateId,
|
||||
senderEmail,
|
||||
senderName,
|
||||
senderNumber,
|
||||
title,
|
||||
body,
|
||||
scheduleType,
|
||||
reserveAt: scheduleType === 'reserve' ? reserveAt : undefined,
|
||||
targetHeaderId,
|
||||
const bulkSendKey = await createBulkKeyMutation.mutateAsync({
|
||||
reqstCmpn: auth.user?.userCmpn ?? '',
|
||||
reqstUser: auth.user?.userId ?? '',
|
||||
reqstSvc: clientEnv.REQUEST_SVC,
|
||||
prjctCd,
|
||||
tmplatIdx: templateIdx,
|
||||
resve: scheduleType === 'reserve',
|
||||
sendDt: scheduleType === 'reserve' ? new Date(reserveAt).toISOString() : undefined,
|
||||
trgtCnt: destInfoList.length,
|
||||
})
|
||||
|
||||
await sendBulkMutation.mutateAsync({
|
||||
sendEml: mode === 'email' ? senderEmail : undefined,
|
||||
sendTel: mode === 'sms' ? senderNumber : undefined,
|
||||
sendNm: senderName || undefined,
|
||||
bulkSendKey,
|
||||
destInfoList,
|
||||
})
|
||||
|
||||
alert('발송 요청이 완료되었습니다.')
|
||||
onSent?.()
|
||||
handleOpenChange(false)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert('발송 중 오류가 발생했습니다.')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[980px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">{titleMap[mode]}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-lg font-semibold">템플릿</Label>
|
||||
<Select value={templateId} onValueChange={handleTemplateChange}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="템플릿을 선택해 주세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{templateOptions.map((template) => (
|
||||
<SelectItem key={template.id} value={template.id}>
|
||||
{template.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{mode === 'email' ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label>발송자 메일</Label>
|
||||
<Input value={senderEmail} onChange={(e) => setSenderEmail(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>발송자 이름</Label>
|
||||
<Input value={senderName} onChange={(e) => setSenderName(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<Label>발송 번호</Label>
|
||||
<Input value={senderNumber} onChange={(e) => setSenderNumber(e.target.value)} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{mode === 'email' ? '메일 제목' : '문자 제목'}</Label>
|
||||
<Input value={title} onChange={(e) => setTitle(e.target.value)} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{mode === 'email' ? '메일 내용' : '문자 내용'}</Label>
|
||||
<textarea
|
||||
className="w-full min-h-36 rounded-md border px-3 py-2 text-sm resize-y"
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>수신 대상 헤더</Label>
|
||||
<Select value={String(targetHeaderId)} onValueChange={(v) => setTargetHeaderId(Number(v))}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{targetHeaderOptions.map((header) => (
|
||||
<SelectItem key={header.id} value={String(header.id)}>
|
||||
{header.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>발송 일시</Label>
|
||||
<RadioGroup
|
||||
value={scheduleType}
|
||||
onValueChange={(v) => setScheduleType(v as ScheduleType)}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="instant" id="message-send-instant" />
|
||||
<Label htmlFor="message-send-instant">즉시</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="reserve" id="message-send-reserve" />
|
||||
<Label htmlFor="message-send-reserve">예약</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
{scheduleType === 'reserve' && (
|
||||
<Input type="datetime-local" value={reserveAt} onChange={(e) => setReserveAt(e.target.value)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-4 space-y-2">
|
||||
<p className="text-lg font-semibold">미리보기</p>
|
||||
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
|
||||
{selectedTemplate && (
|
||||
<>
|
||||
<div className="rounded border p-2 text-sm font-semibold">{title || '(제목 없음)'}</div>
|
||||
<div className="rounded border p-3 text-sm whitespace-pre-wrap min-h-72">
|
||||
{body || '(내용 없음)'}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
|
||||
contentClassName="sm:max-w-[1100px] max-h-[90vh] overflow-y-auto"
|
||||
bodyClassName="grid grid-cols-1 lg:grid-cols-2 gap-6"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
발송
|
||||
{submitting ? '발송 중...' : '발송'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">템플릿을 선택해 주세요</Label>
|
||||
<KriSingleSelect
|
||||
items={templateList}
|
||||
value={String(templateIdx ?? '')}
|
||||
onChange={handleSelectTemplate}
|
||||
placeholder="템플릿을 선택해 주세요"
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
getLabel={(item) => item.tmplatNm}
|
||||
getValue={(item) => String(item.tmplatIdx)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{mode === 'email' ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">발송자 메일</Label>
|
||||
<Input value={senderEmail} onChange={(e) => setSenderEmail(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">발송자 이름</Label>
|
||||
<Input value={senderName} onChange={(e) => setSenderName(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">발송 번호</Label>
|
||||
<Input value={senderNumber} onChange={(e) => setSenderNumber(e.target.value)} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">발송 일시</Label>
|
||||
<RadioGroup
|
||||
value={scheduleType}
|
||||
onValueChange={(v) => handleScheduleTypeChange(v as 'instant' | 'reserve')}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-2 cursor-pointer">
|
||||
<RadioGroupItem value="instant" id="message-send-instant" />
|
||||
<Label htmlFor="message-send-instant">즉시</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 cursor-pointer">
|
||||
<RadioGroupItem value="reserve" id="message-send-reserve" />
|
||||
<Label htmlFor="message-send-reserve">예약</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
{scheduleType === 'reserve' && (
|
||||
<KriDateTimePicker value={reserveAt} onChange={setReserveAt} placeholder="예약 일시 선택" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">수신 {mode === 'email' ? '이메일' : '번호'} 헤더</Label>
|
||||
<KriSingleSelect
|
||||
items={targetHeaderOptions}
|
||||
value={String(targetHeaderId ?? '')}
|
||||
onChange={(value) => setTargetHeaderId(Number(value) || null)}
|
||||
placeholder={`수신 ${mode === 'email' ? '이메일' : '번호'}로 사용할 헤더를 선택해 주세요`}
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
getLabel={(item) => item.listHderNm}
|
||||
getValue={(item) => String(item.listHderId)}
|
||||
/>
|
||||
{targetHeaderOptions.length === 0 && (
|
||||
<p className="text-sm text-red-600">
|
||||
{mode === 'email' ? '이메일' : '전화번호'} 타입의 리스트 헤더가 없습니다. 헤더 관리에서 먼저 설정해 주세요.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 rounded-md border p-4">
|
||||
<Label className="text-base">수신 대상</Label>
|
||||
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="message-send-target" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
대상 {targetTotalCount.toLocaleString()}건
|
||||
{isTargetTruncated ? ` (최대 ${MAX_TARGET_COUNT.toLocaleString()}건까지만 발송 가능합니다)` : ''}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-4 space-y-2">
|
||||
<p className="text-lg font-semibold">미리보기</p>
|
||||
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
|
||||
{selectedTemplate && (
|
||||
<>
|
||||
{chnnlTy !== ChannelType.SMS && (
|
||||
<div className="rounded border p-2 text-lg font-semibold">{`제목: ${selectedTemplate.tmplatTitle}` || '(제목 없음)'}</div>
|
||||
)}
|
||||
{chnnlTy === ChannelType.SMS ? (
|
||||
<div className="flex flex-col items-center">
|
||||
<KriEditor
|
||||
mode="sms"
|
||||
value={(selectedTemplate as TemplateSms).tmplatBody ?? ""}
|
||||
onChange={() => {}}
|
||||
isSmsReadOnly
|
||||
placeholder="문자 내용을 입력해 주세요"
|
||||
className="max-w-80 mx-0"
|
||||
debounceMs={600}
|
||||
smsTitle={(selectedTemplate as TemplateSms).tmplatTitle}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={cn('rounded-md border bg-muted/30 p-3')}
|
||||
dangerouslySetInnerHTML={{ __html: sanitizeHtmlForPreview(selectedTemplate.tmplatBody || '(내용 없음)') }}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import {useState, useEffect, useMemo} from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from "@/components/ui/dialog";
|
||||
import { KriDialog } from "@/components/common/KriDialog";
|
||||
import {Label} from "@/components/ui/label";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {Button} from "@/components/ui/button";
|
||||
@@ -21,7 +14,7 @@ import {ProjectCreateRequest} from "@/types/project";
|
||||
import { useDebouncedValue } from "@kri/common/hooks";
|
||||
import {PROJECT_NAME_REGEX} from "@/const/projectConst";
|
||||
import {FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
import {useIntranetProjectListQuery} from "@/query/intranet";
|
||||
|
||||
@@ -165,15 +158,32 @@ const ProjectCreateDialog = ({
|
||||
}, [users]);
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px] text-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-xl">
|
||||
프로젝트 생성
|
||||
</DialogTitle>
|
||||
<DialogDescription>프로젝트 생성에 필요한 기본 정보를 입력해주세요.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-6 py-4">
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-xl">프로젝트 생성</span>}
|
||||
description="프로젝트 생성에 필요한 기본 정보를 입력해주세요."
|
||||
contentClassName="sm:max-w-[500px] text-sm"
|
||||
bodyClassName="grid gap-6 py-4"
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
생성
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-2">
|
||||
<Label>
|
||||
인트라넷 프로젝트<span className="text-red-500 ml-1">*</span>
|
||||
@@ -230,25 +240,7 @@ const ProjectCreateDialog = ({
|
||||
widthClassName="w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
생성
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</KriDialog>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
91
src/components/dialog/ReservationListDialog.tsx
Normal file
91
src/components/dialog/ReservationListDialog.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
'use client'
|
||||
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { ListReserve } from '@/types/list'
|
||||
import { formatKst } from '@kri/common'
|
||||
|
||||
export type ReservationListDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
reservations: ListReserve[]
|
||||
onSelectReservation: (sid: string) => void
|
||||
}
|
||||
|
||||
// 오늘과 가장 가까운(과거/미래 무관) 예약의 sid를 찾는다.
|
||||
export const findClosestReservationSid = (reservations: ListReserve[], now: Date = new Date()): number | null => {
|
||||
if (reservations.length === 0) return null
|
||||
|
||||
return reservations.reduce((closest, current) => {
|
||||
const closestDiff = Math.abs(new Date(closest.resveDt).getTime() - now.getTime())
|
||||
const currentDiff = Math.abs(new Date(current.resveDt).getTime() - now.getTime())
|
||||
return currentDiff < closestDiff ? current : closest
|
||||
}, reservations[0]).sid
|
||||
}
|
||||
|
||||
const ReservationListDialog = ({
|
||||
dialogId = 'reservationListDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
reservations,
|
||||
onSelectReservation,
|
||||
}: ReservationListDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
const closestSid = findClosestReservationSid(reservations)
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
if (nextOpen) {
|
||||
showDialog(dialogId)
|
||||
return
|
||||
}
|
||||
hideDialog(dialogId)
|
||||
}
|
||||
|
||||
const handleSelect = (sid: number) => {
|
||||
onSelectReservation(String(sid))
|
||||
handleOpenChange(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-xl">예약리스트 조회</span>}
|
||||
contentClassName="sm:max-w-[480px]"
|
||||
showDefaultFooter
|
||||
>
|
||||
<div className="max-h-80 overflow-auto rounded-md border">
|
||||
{reservations.length === 0 ? (
|
||||
<div className="p-6 text-center text-sm text-muted-foreground">예약된 리스트가 없습니다.</div>
|
||||
) : (
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 bg-muted">
|
||||
<tr>
|
||||
<th className="p-2 text-left">SID</th>
|
||||
<th className="p-2 text-left">예약 일시</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{reservations.map((item) => (
|
||||
<tr
|
||||
key={item.listResveIdx}
|
||||
className={`cursor-pointer border-t hover:bg-muted/50 ${item.sid === closestSid ? 'bg-accent' : ''}`}
|
||||
onClick={() => handleSelect(item.sid)}
|
||||
>
|
||||
<td className="p-2">{item.sid}</td>
|
||||
<td className="p-2">{formatKst(item.resveDt, 'dateHourMin')}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default ReservationListDialog
|
||||
@@ -1,13 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import {useEffect, useMemo, useState} from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {Trash2, Plus, Download} from 'lucide-react'
|
||||
@@ -77,6 +71,7 @@ const ResultCodeDialog = ({
|
||||
resultCdTy: resultCodeType,
|
||||
resultCd: lastCode + 1,
|
||||
resultCdLbl: '',
|
||||
isDefault: false,
|
||||
}
|
||||
])
|
||||
}
|
||||
@@ -220,23 +215,46 @@ const ResultCodeDialog = ({
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<KriDialog
|
||||
open={open ?? false}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) handleClose()
|
||||
}}
|
||||
title={<div className="text-2xl font-bold">결과 코드 설정</div>}
|
||||
contentClassName={[
|
||||
'overflow-hidden',
|
||||
'transition-all duration-200',
|
||||
importMode ? 'sm:max-w-6xl' : 'sm:max-w-3xl',
|
||||
'w-[calc(100vw-2rem)]',
|
||||
'max-h-[85vh]',
|
||||
'gap-2',
|
||||
].join(' ')}
|
||||
bodyClassName="min-h-0 p-0"
|
||||
footerClassName="px-6 py-4 border-t bg-white"
|
||||
footer={
|
||||
importMode ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={handleImportCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleImportApply} disabled={!importProject} className="gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
가져오기 적용
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
>
|
||||
{/* importMode일 때 더 넓게(그리고 애니메이션으로 부드럽게) */}
|
||||
<DialogContent
|
||||
className={[
|
||||
'p-0 overflow-hidden',
|
||||
'transition-all duration-200',
|
||||
importMode ? 'sm:max-w-6xl' : 'sm:max-w-3xl',
|
||||
'w-[calc(100vw-2rem)]',
|
||||
'max-h-[85vh]',
|
||||
'gap-2',
|
||||
].join(' ')}
|
||||
>
|
||||
<DialogHeader className="px-6 pt-6 pb-4 border-b">
|
||||
<DialogTitle className="flex items-center justify-between gap-3">
|
||||
<span>결과 코드 설정</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* 상단 버튼 영역 */}
|
||||
<div className="px-6 pt-1 pb-3 border-b bg-white flex justify-end">
|
||||
@@ -272,7 +290,7 @@ const ResultCodeDialog = ({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="px-6 pt-4 flex flex-wrap items-center gap-2">
|
||||
<div className="px-6 py-2 flex flex-wrap items-center gap-1">
|
||||
{RESULT_CODE_TYPE_OPTIONS
|
||||
.filter((opt) => opt.value !== ResultCodeType.SURVEY)
|
||||
.map((opt) => (
|
||||
@@ -315,7 +333,9 @@ const ResultCodeDialog = ({
|
||||
<tbody className="divide-y">
|
||||
{resultCodeArray
|
||||
.filter((rc) => rc.resultCdTy === resultCodeType)
|
||||
.map((code, index) => (
|
||||
.map((code, index) => {
|
||||
const isLocked = code.isDefault;
|
||||
return (
|
||||
<tr key={index} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-2 align-middle">
|
||||
<Input
|
||||
@@ -323,7 +343,7 @@ const ResultCodeDialog = ({
|
||||
onChange={(e) => handleCodeChange(code.resultCdUUID, 'resultCd', e.target.value)}
|
||||
onBlur={(e) => checkDuplicate(code.resultCdUUID, Number(e.target.value), e.target)}
|
||||
className="h-9"
|
||||
disabled={importMode}
|
||||
disabled={importMode || isLocked}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-4 py-2 align-middle">
|
||||
@@ -331,15 +351,15 @@ const ResultCodeDialog = ({
|
||||
value={code.resultCdLbl}
|
||||
onChange={(e) => handleCodeChange(code.resultCdUUID, 'resultCdLbl', e.target.value)}
|
||||
className="h-9"
|
||||
disabled={importMode}
|
||||
disabled={importMode || isLocked}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-2 py-2 align-middle">
|
||||
{!importMode && (
|
||||
{!importMode && !isLocked && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleDeleteCode(index)}
|
||||
onClick={() => handleDeleteCode(code.resultCd)}
|
||||
aria-label="delete"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 text-red-600" />
|
||||
@@ -347,7 +367,8 @@ const ResultCodeDialog = ({
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -398,30 +419,7 @@ const ResultCodeDialog = ({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="px-6 py-4 border-t bg-white">
|
||||
{importMode ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={handleImportCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleImportApply} disabled={!importProject} className="gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
가져오기 적용
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
230
src/components/dialog/SingleMessageSendDialog.tsx
Normal file
230
src/components/dialog/SingleMessageSendDialog.tsx
Normal file
@@ -0,0 +1,230 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { KriDateTimePicker } from '@/components/common/KriDateTimePicker'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import {
|
||||
useMainTemplateIdxQuery,
|
||||
useSendSingleMessageMutation,
|
||||
useTemplateListQuery,
|
||||
useTemplateQuery,
|
||||
} from '@/query/message'
|
||||
import { ChannelType, type TemplateSms, type TemplateSummary } from '@kri/common/noti-hub'
|
||||
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
|
||||
import { KriEditor } from '@/components/kri-editor'
|
||||
import { getNearestFutureDateTime } from '@/lib/datetime'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { MessageSendChannel } from '@/types/message'
|
||||
|
||||
const titleMap: Record<MessageSendChannel, string> = {
|
||||
email: '메일 발송',
|
||||
sms: '문자 발송',
|
||||
}
|
||||
|
||||
export type SingleMessageSendDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
channel: MessageSendChannel
|
||||
prjctIdx: number
|
||||
itrntPrjctCd: string
|
||||
sid: string
|
||||
destHeaderId: number
|
||||
onSent?: () => void
|
||||
}
|
||||
|
||||
const SingleMessageSendDialog = ({
|
||||
dialogId = 'singleMessageSendDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
channel,
|
||||
prjctIdx,
|
||||
itrntPrjctCd,
|
||||
sid,
|
||||
destHeaderId,
|
||||
onSent,
|
||||
}: SingleMessageSendDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
|
||||
const chnnlTy = channel === 'email' ? ChannelType.EMAIL : ChannelType.SMS
|
||||
|
||||
const [templateIdx, setTemplateIdx] = useState<number | null>(null)
|
||||
const [scheduleType, setScheduleType] = useState<'instant' | 'reserve'>('instant')
|
||||
const [reserveAt, setReserveAt] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const enabled = resolvedOpen && !!itrntPrjctCd
|
||||
const templateListQuery = useTemplateListQuery(chnnlTy, itrntPrjctCd, enabled)
|
||||
const templateList: TemplateSummary[] = templateListQuery.data ?? []
|
||||
const templateDetailQuery = useTemplateQuery(templateIdx ?? 0, enabled && !!templateIdx)
|
||||
const selectedTemplate = templateDetailQuery.data ?? null
|
||||
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
|
||||
const mainTemplateIdx = mainTemplateQuery.data ?? null
|
||||
|
||||
const sendSingleMutation = useSendSingleMessageMutation(channel, prjctIdx)
|
||||
|
||||
const mainTemplateAppliedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!resolvedOpen) return
|
||||
setTemplateIdx(null)
|
||||
setScheduleType('instant')
|
||||
setReserveAt('')
|
||||
mainTemplateAppliedRef.current = false
|
||||
}, [resolvedOpen])
|
||||
|
||||
// 대표 템플릿이 있으면 최초 1회 자동 선택
|
||||
useEffect(() => {
|
||||
if (!enabled || mainTemplateAppliedRef.current || !mainTemplateQuery.isSuccess) return
|
||||
mainTemplateAppliedRef.current = true
|
||||
if (mainTemplateIdx) setTemplateIdx(mainTemplateIdx)
|
||||
}, [enabled, mainTemplateQuery.isSuccess, mainTemplateIdx])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
if (nextOpen) {
|
||||
showDialog(dialogId)
|
||||
return
|
||||
}
|
||||
hideDialog(dialogId)
|
||||
}
|
||||
|
||||
const handleScheduleTypeChange = (next: 'instant' | 'reserve') => {
|
||||
setScheduleType(next)
|
||||
if (next === 'reserve' && !reserveAt) {
|
||||
setReserveAt(getNearestFutureDateTime())
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectTemplate = (value: string) => {
|
||||
const idx = Number(value)
|
||||
setTemplateIdx(Number.isFinite(idx) && idx > 0 ? idx : null)
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!templateIdx) {
|
||||
alert('템플릿을 선택해 주세요.')
|
||||
return
|
||||
}
|
||||
if (scheduleType === 'reserve' && !reserveAt) {
|
||||
alert('예약 발송 일시를 선택해 주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await sendSingleMutation.mutateAsync({
|
||||
tmplatIdx: templateIdx,
|
||||
resve: scheduleType === 'reserve',
|
||||
sendDt: scheduleType === 'reserve' ? new Date(reserveAt).toISOString() : undefined,
|
||||
sid: Number(sid),
|
||||
destHeaderIds: [destHeaderId],
|
||||
})
|
||||
|
||||
alert('발송 요청이 완료되었습니다.')
|
||||
onSent?.()
|
||||
handleOpenChange(false)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert('발송 중 오류가 발생했습니다.')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-xl font-bold">{titleMap[channel]}</span>}
|
||||
contentClassName="sm:max-w-[900px] max-h-[90vh] overflow-y-auto"
|
||||
bodyClassName="grid grid-cols-1 lg:grid-cols-2 gap-6"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
{submitting ? '발송 중...' : '발송'}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">템플릿을 선택해 주세요</Label>
|
||||
<KriSingleSelect
|
||||
items={templateList}
|
||||
value={String(templateIdx ?? '')}
|
||||
onChange={handleSelectTemplate}
|
||||
placeholder="템플릿을 선택해 주세요"
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
getLabel={(item) => item.tmplatNm}
|
||||
getValue={(item) => String(item.tmplatIdx)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">발송 일시</Label>
|
||||
<RadioGroup
|
||||
value={scheduleType}
|
||||
onValueChange={(v) => handleScheduleTypeChange(v as 'instant' | 'reserve')}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-2 cursor-pointer">
|
||||
<RadioGroupItem value="instant" id="single-send-instant" />
|
||||
<Label htmlFor="single-send-instant">즉시</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 cursor-pointer">
|
||||
<RadioGroupItem value="reserve" id="single-send-reserve" />
|
||||
<Label htmlFor="single-send-reserve">예약</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
{scheduleType === 'reserve' && (
|
||||
<KriDateTimePicker value={reserveAt} onChange={setReserveAt} placeholder="예약 일시 선택" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 rounded-md border p-4">
|
||||
<p className="text-sm font-semibold">미리보기</p>
|
||||
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
|
||||
{selectedTemplate && (
|
||||
<>
|
||||
{chnnlTy !== ChannelType.SMS && (
|
||||
<div className="rounded border p-2 text-sm font-semibold">{`제목: ${selectedTemplate.tmplatTitle}` || '(제목 없음)'}</div>
|
||||
)}
|
||||
{chnnlTy === ChannelType.SMS ? (
|
||||
<div className="flex flex-col items-center">
|
||||
<KriEditor
|
||||
mode="sms"
|
||||
value={(selectedTemplate as TemplateSms).tmplatBody ?? ''}
|
||||
onChange={() => {}}
|
||||
isSmsReadOnly
|
||||
placeholder="문자 내용을 입력해 주세요"
|
||||
className="max-w-80 mx-0"
|
||||
debounceMs={600}
|
||||
smsTitle={(selectedTemplate as TemplateSms).tmplatTitle}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="rounded-md border bg-muted/30 p-3 text-sm"
|
||||
dangerouslySetInnerHTML={{ __html: sanitizeHtmlForPreview(selectedTemplate.tmplatBody || '(내용 없음)') }}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default SingleMessageSendDialog
|
||||
69
src/components/dialog/SurveyQrDialog.tsx
Normal file
69
src/components/dialog/SurveyQrDialog.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { toDataURL } from 'qrcode'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
|
||||
export type SurveyQrDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
url: string
|
||||
}
|
||||
|
||||
const SurveyQrDialog = ({ dialogId = 'surveyQrDialog', open, onOpenChange, url }: SurveyQrDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null)
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
if (nextOpen) {
|
||||
showDialog(dialogId)
|
||||
return
|
||||
}
|
||||
hideDialog(dialogId)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!resolvedOpen || !url) {
|
||||
setQrDataUrl(null)
|
||||
return
|
||||
}
|
||||
|
||||
let cancelled = false
|
||||
toDataURL(url, { width: 240 }).then((dataUrl) => {
|
||||
if (!cancelled) setQrDataUrl(dataUrl)
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [resolvedOpen, url])
|
||||
|
||||
return (
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-xl">설문 QR코드</span>}
|
||||
contentClassName="sm:max-w-[360px]"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-3 py-4">
|
||||
{qrDataUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={qrDataUrl} alt="설문 QR코드" width={240} height={240} />
|
||||
) : (
|
||||
<div className="flex h-[240px] w-[240px] items-center justify-center text-sm text-muted-foreground">
|
||||
QR코드 생성 중...
|
||||
</div>
|
||||
)}
|
||||
<p className="break-all text-center text-xs text-muted-foreground">{url}</p>
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default SurveyQrDialog
|
||||
@@ -1,12 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useState, useRef } from 'react'
|
||||
import {Download, Upload, X} from 'lucide-react'
|
||||
@@ -117,13 +111,20 @@ const UserUploadDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleDialogOpenChange}>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className=" text-2xl font-bold">User upload</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 py-4">
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
title={<span className="text-2xl font-bold">User upload</span>}
|
||||
contentClassName="sm:max-w-[600px]"
|
||||
bodyClassName="space-y-6 py-4"
|
||||
footer={
|
||||
<div className="flex items-center justify-end w-full gap-2">
|
||||
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting}>
|
||||
확인
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
@@ -165,17 +166,7 @@ const UserUploadDialog = ({
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<div className="flex items-center justify-end w-full gap-2">
|
||||
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting}>
|
||||
확인
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user