develop #24
@@ -270,6 +270,7 @@ When implementing or changing frontend UI, use this order:
|
|||||||
### Installation and Ownership
|
### Installation and Ownership
|
||||||
|
|
||||||
- Inspect the registry item and its dependencies before installation. Use the shadcn CLI with the approved registry endpoint under `https://ui-registry.kric.com/r/` instead of copying files from `dist/r` manually.
|
- Inspect the registry item and its dependencies before installation. Use the shadcn CLI with the approved registry endpoint under `https://ui-registry.kric.com/r/` instead of copying files from `dist/r` manually.
|
||||||
|
- `kri-data-table` uses the TanStack Table v8 API. Keep `@tanstack/react-table` within the supported `^8.21.3` range and do not upgrade it to v9 until KriUiRegistry provides an explicitly migrated component contract.
|
||||||
- Respect the consumer project's component aliases, target paths, package manager, styling system, React version, and existing design tokens.
|
- Respect the consumer project's component aliases, target paths, package manager, styling system, React version, and existing design tokens.
|
||||||
- The shadcn workflow copies component source into the consumer repository. After installation, treat that copy as project-owned code; do not assume registry updates propagate automatically.
|
- The shadcn workflow copies component source into the consumer repository. After installation, treat that copy as project-owned code; do not assume registry updates propagate automatically.
|
||||||
- Do not overwrite an existing project component without reviewing the diff and confirming that local behavior and accessibility are preserved.
|
- Do not overwrite an existing project component without reviewing the diff and confirming that local behavior and accessibility are preserved.
|
||||||
|
|||||||
30
package-lock.json
generated
30
package-lock.json
generated
@@ -25,6 +25,7 @@
|
|||||||
"@tanstack/react-query": "^5.90.21",
|
"@tanstack/react-query": "^5.90.21",
|
||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"@tiptap/extension-color": "^3.13.0",
|
"@tiptap/extension-color": "^3.13.0",
|
||||||
|
"@tiptap/extension-font-family": "^3.13.0",
|
||||||
"@tiptap/extension-highlight": "^3.13.0",
|
"@tiptap/extension-highlight": "^3.13.0",
|
||||||
"@tiptap/extension-image": "^3.13.0",
|
"@tiptap/extension-image": "^3.13.0",
|
||||||
"@tiptap/extension-link": "^3.13.0",
|
"@tiptap/extension-link": "^3.13.0",
|
||||||
@@ -48,6 +49,7 @@
|
|||||||
"lucide-react": "^0.553.0",
|
"lucide-react": "^0.553.0",
|
||||||
"next": "^16.0.7",
|
"next": "^16.0.7",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
|
"prettier": "^3.9.6",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
"radix-ui": "^1.6.1",
|
"radix-ui": "^1.6.1",
|
||||||
"react": "^19.2.1",
|
"react": "^19.2.1",
|
||||||
@@ -3305,6 +3307,19 @@
|
|||||||
"@tiptap/pm": "^3.12.0"
|
"@tiptap/pm": "^3.12.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tiptap/extension-font-family": {
|
||||||
|
"version": "3.13.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-font-family/-/extension-font-family-3.13.0.tgz",
|
||||||
|
"integrity": "sha512-ZJ+P7qYK4dIRjncRibeYT1HI2P/blUe8/CWcmKJmp1e1DE9m6Q+jdllehNCr7a30yZzFxn9yJPJPDmHi5D3c0w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/ueberdosis"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tiptap/extension-text-style": "^3.13.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@tiptap/extension-gapcursor": {
|
"node_modules/@tiptap/extension-gapcursor": {
|
||||||
"version": "3.12.0",
|
"version": "3.12.0",
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-gapcursor/-/extension-gapcursor-3.12.0.tgz",
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-gapcursor/-/extension-gapcursor-3.12.0.tgz",
|
||||||
@@ -7758,6 +7773,21 @@
|
|||||||
"node": ">= 0.8.0"
|
"node": ">= 0.8.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/prettier": {
|
||||||
|
"version": "3.9.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.6.tgz",
|
||||||
|
"integrity": "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"prettier": "bin/prettier.cjs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/prop-types": {
|
"node_modules/prop-types": {
|
||||||
"version": "15.8.1",
|
"version": "15.8.1",
|
||||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||||
|
|||||||
@@ -26,6 +26,7 @@
|
|||||||
"@tanstack/react-query": "^5.90.21",
|
"@tanstack/react-query": "^5.90.21",
|
||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"@tiptap/extension-color": "^3.13.0",
|
"@tiptap/extension-color": "^3.13.0",
|
||||||
|
"@tiptap/extension-font-family": "^3.13.0",
|
||||||
"@tiptap/extension-highlight": "^3.13.0",
|
"@tiptap/extension-highlight": "^3.13.0",
|
||||||
"@tiptap/extension-image": "^3.13.0",
|
"@tiptap/extension-image": "^3.13.0",
|
||||||
"@tiptap/extension-link": "^3.13.0",
|
"@tiptap/extension-link": "^3.13.0",
|
||||||
@@ -49,6 +50,7 @@
|
|||||||
"lucide-react": "^0.553.0",
|
"lucide-react": "^0.553.0",
|
||||||
"next": "^16.0.7",
|
"next": "^16.0.7",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
|
"prettier": "^3.9.6",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
"radix-ui": "^1.6.1",
|
"radix-ui": "^1.6.1",
|
||||||
"react": "^19.2.1",
|
"react": "^19.2.1",
|
||||||
|
|||||||
@@ -17,11 +17,12 @@ import { useResetListAssignMutation, useUpsertListAssignMutation } from '@/query
|
|||||||
import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst'
|
import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst'
|
||||||
import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list'
|
import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list'
|
||||||
import type { ResultCode } from '@/types/project'
|
import type { ResultCode } from '@/types/project'
|
||||||
|
import { isExternalManager } from '@/utils/userRole'
|
||||||
|
|
||||||
const ASSIGN_TAB_TYPES: ListHeaderAssignType[] = [
|
const ASSIGN_TAB_TYPES: ListHeaderAssignType[] = [
|
||||||
ListHeaderAssignConst.OUTSOURCE,
|
|
||||||
ListHeaderAssignConst.CONTACT_INTERVIEWER,
|
ListHeaderAssignConst.CONTACT_INTERVIEWER,
|
||||||
ListHeaderAssignConst.FIELD_INTERVIEWER,
|
ListHeaderAssignConst.FIELD_INTERVIEWER,
|
||||||
|
ListHeaderAssignConst.OUTSOURCE,
|
||||||
]
|
]
|
||||||
|
|
||||||
const ASSIGNED_SENTINEL = '__ASSIGNED__'
|
const ASSIGNED_SENTINEL = '__ASSIGNED__'
|
||||||
@@ -36,8 +37,15 @@ const ListAssignPage = () => {
|
|||||||
const prjctIdx = selectedProject?.prjctIdx ?? 0
|
const prjctIdx = selectedProject?.prjctIdx ?? 0
|
||||||
const enabled = mounted && prjctIdx > 0
|
const enabled = mounted && prjctIdx > 0
|
||||||
const userRole = auth?.user?.userRole ?? 0
|
const userRole = auth?.user?.userRole ?? 0
|
||||||
|
const isExternalUser = isExternalManager(userRole)
|
||||||
|
|
||||||
const [assignType, setAssignType] = useState<ListHeaderAssignType>(ListHeaderAssignConst.OUTSOURCE)
|
const [assignType, setAssignType] = useState<ListHeaderAssignType>(ListHeaderAssignConst.CONTACT_INTERVIEWER)
|
||||||
|
const effectiveAssignType =
|
||||||
|
selectedProject?.ff === false && assignType === ListHeaderAssignConst.FIELD_INTERVIEWER
|
||||||
|
? ListHeaderAssignConst.CONTACT_INTERVIEWER
|
||||||
|
: isExternalUser && assignType === ListHeaderAssignConst.OUTSOURCE
|
||||||
|
? ListHeaderAssignConst.CONTACT_INTERVIEWER
|
||||||
|
: assignType
|
||||||
const [selectedAssignId, setSelectedAssignId] = useState<string | undefined>(undefined)
|
const [selectedAssignId, setSelectedAssignId] = useState<string | undefined>(undefined)
|
||||||
const [assignFilterIds, setAssignFilterIds] = useState<string[]>([])
|
const [assignFilterIds, setAssignFilterIds] = useState<string[]>([])
|
||||||
const [transferResve, setTransferResve] = useState(false)
|
const [transferResve, setTransferResve] = useState(false)
|
||||||
@@ -49,22 +57,40 @@ const ListAssignPage = () => {
|
|||||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||||
const upsertListAssignMutation = useUpsertListAssignMutation(prjctIdx)
|
const upsertListAssignMutation = useUpsertListAssignMutation(prjctIdx)
|
||||||
const resetListAssignMutation = useResetListAssignMutation(prjctIdx)
|
const resetListAssignMutation = useResetListAssignMutation(prjctIdx)
|
||||||
const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType })
|
const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: effectiveAssignType })
|
||||||
|
|
||||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
||||||
const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data])
|
const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data])
|
||||||
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||||
|
const assignTabTypes = useMemo(
|
||||||
|
() =>
|
||||||
|
ASSIGN_TAB_TYPES.filter((type) => {
|
||||||
|
if (type === ListHeaderAssignConst.FIELD_INTERVIEWER && selectedProject?.ff === false) return false
|
||||||
|
if (type === ListHeaderAssignConst.OUTSOURCE && isExternalUser) return false
|
||||||
|
return true
|
||||||
|
}),
|
||||||
|
[selectedProject?.ff, isExternalUser],
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (selectedProject?.ff === false && assignType === ListHeaderAssignConst.FIELD_INTERVIEWER) {
|
||||||
|
setAssignType(ListHeaderAssignConst.CONTACT_INTERVIEWER)
|
||||||
|
setSelectedAssignId(undefined)
|
||||||
|
setAssignFilterIds([])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (isExternalUser && assignType === ListHeaderAssignConst.OUTSOURCE) {
|
||||||
|
setAssignType(ListHeaderAssignConst.CONTACT_INTERVIEWER)
|
||||||
|
setSelectedAssignId(undefined)
|
||||||
|
setAssignFilterIds([])
|
||||||
|
}
|
||||||
|
}, [assignType, selectedProject?.ff, isExternalUser])
|
||||||
|
|
||||||
const handleTabChange = (value: string) => {
|
const handleTabChange = (value: string) => {
|
||||||
setAssignType(Number(value) as ListHeaderAssignType)
|
setAssignType(Number(value) as ListHeaderAssignType)
|
||||||
setSelectedAssignId(undefined)
|
setSelectedAssignId(undefined)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 좌측 테이블 선택값이 바뀌면 결과 필터 multiselect도 그 값으로 맞춘다.
|
|
||||||
useEffect(() => {
|
|
||||||
setAssignFilterIds(selectedAssignId ? [selectedAssignId] : [])
|
|
||||||
}, [selectedAssignId])
|
|
||||||
|
|
||||||
// "배정됨"/"배정되지 않음"은 실제 대상 선택과 동시에 선택될 수 없다: 새로 클릭된 쪽만 남긴다.
|
// "배정됨"/"배정되지 않음"은 실제 대상 선택과 동시에 선택될 수 없다: 새로 클릭된 쪽만 남긴다.
|
||||||
const handleAssignFilterChange = (next: string[]) => {
|
const handleAssignFilterChange = (next: string[]) => {
|
||||||
const addedSentinel = next.find((value) => isAssignFilterSentinel(value) && !assignFilterIds.includes(value))
|
const addedSentinel = next.find((value) => isAssignFilterSentinel(value) && !assignFilterIds.includes(value))
|
||||||
@@ -86,13 +112,13 @@ const ListAssignPage = () => {
|
|||||||
|
|
||||||
const externalAssignFilter = useMemo(() => {
|
const externalAssignFilter = useMemo(() => {
|
||||||
if (assignFilterIds[0] === ASSIGNED_SENTINEL) {
|
if (assignFilterIds[0] === ASSIGNED_SENTINEL) {
|
||||||
return { type: assignType, values: [] as string[], condition: 'assigned' as const }
|
return { type: effectiveAssignType, values: [] as string[], condition: 'assigned' as const }
|
||||||
}
|
}
|
||||||
if (assignFilterIds[0] === UNASSIGNED_SENTINEL) {
|
if (assignFilterIds[0] === UNASSIGNED_SENTINEL) {
|
||||||
return { type: assignType, values: [] as string[], condition: 'unassigned' as const }
|
return { type: effectiveAssignType, values: [] as string[], condition: 'unassigned' as const }
|
||||||
}
|
}
|
||||||
return { type: assignType, values: assignFilterIds }
|
return { type: effectiveAssignType, values: assignFilterIds }
|
||||||
}, [assignType, assignFilterIds])
|
}, [effectiveAssignType, assignFilterIds])
|
||||||
|
|
||||||
const hasNoAppliedFilter = () => filterSummary.length === 0 && assignFilterIds.length === 0
|
const hasNoAppliedFilter = () => filterSummary.length === 0 && assignFilterIds.length === 0
|
||||||
|
|
||||||
@@ -108,8 +134,8 @@ const ListAssignPage = () => {
|
|||||||
await upsertListAssignMutation.mutateAsync({
|
await upsertListAssignMutation.mutateAsync({
|
||||||
assignId: selectedAssignId,
|
assignId: selectedAssignId,
|
||||||
request: {
|
request: {
|
||||||
assignType,
|
assignType: effectiveAssignType,
|
||||||
transferResve: assignType === ListHeaderAssignConst.OUTSOURCE? false : transferResve,
|
transferResve: effectiveAssignType === ListHeaderAssignConst.OUTSOURCE? false : transferResve,
|
||||||
listFilter: currentListFilter,
|
listFilter: currentListFilter,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -123,7 +149,7 @@ const ListAssignPage = () => {
|
|||||||
if (!confirm('정말 배정을 초기화 하시겠습니까?')) return
|
if (!confirm('정말 배정을 초기화 하시겠습니까?')) return
|
||||||
|
|
||||||
await resetListAssignMutation.mutateAsync({
|
await resetListAssignMutation.mutateAsync({
|
||||||
assignType,
|
assignType: effectiveAssignType,
|
||||||
listFilter: currentListFilter,
|
listFilter: currentListFilter,
|
||||||
})
|
})
|
||||||
alert('배정이 초기화 되었습니다.')
|
alert('배정이 초기화 되었습니다.')
|
||||||
@@ -134,9 +160,9 @@ const ListAssignPage = () => {
|
|||||||
return (
|
return (
|
||||||
<div className="flex gap-4 text-sm">
|
<div className="flex gap-4 text-sm">
|
||||||
<div className="w-72 shrink-0 space-y-2">
|
<div className="w-72 shrink-0 space-y-2">
|
||||||
<Tabs value={String(assignType)} onValueChange={handleTabChange}>
|
<Tabs value={String(effectiveAssignType)} onValueChange={handleTabChange}>
|
||||||
<TabsList className="grid w-full grid-cols-3">
|
<TabsList className={`grid w-full ${assignTabTypes.length === 2 ? 'grid-cols-2' : assignTabTypes.length === 1 ? 'grid-cols-1' : 'grid-cols-3'}`}>
|
||||||
{ASSIGN_TAB_TYPES.map((type) => (
|
{assignTabTypes.map((type) => (
|
||||||
<TabsTrigger key={type} value={String(type)}>
|
<TabsTrigger key={type} value={String(type)}>
|
||||||
{LIST_HEADER_TYPE_LABEL[type]}
|
{LIST_HEADER_TYPE_LABEL[type]}
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
@@ -147,7 +173,8 @@ const ListAssignPage = () => {
|
|||||||
<AssignTargetList
|
<AssignTargetList
|
||||||
prjctIdx={prjctIdx}
|
prjctIdx={prjctIdx}
|
||||||
enabled={enabled}
|
enabled={enabled}
|
||||||
assignType={assignType}
|
assignType={effectiveAssignType}
|
||||||
|
userRole={userRole}
|
||||||
selectedId={selectedAssignId}
|
selectedId={selectedAssignId}
|
||||||
onSelect={setSelectedAssignId}
|
onSelect={setSelectedAssignId}
|
||||||
/>
|
/>
|
||||||
@@ -163,10 +190,11 @@ const ListAssignPage = () => {
|
|||||||
resultCodes={resultCodeArray}
|
resultCodes={resultCodeArray}
|
||||||
surveys={surveyArray}
|
surveys={surveyArray}
|
||||||
listHeaders={listHeaders}
|
listHeaders={listHeaders}
|
||||||
|
fieldInterviewEnabled={selectedProject.ff !== false}
|
||||||
selectMode="none"
|
selectMode="none"
|
||||||
onCurrentFilterChange={setCurrentListFilter}
|
onCurrentFilterChange={setCurrentListFilter}
|
||||||
onFilterSummaryChange={setFilterSummary}
|
onFilterSummaryChange={setFilterSummary}
|
||||||
excludeFilterHeaderTypes={[assignType]}
|
excludeFilterHeaderTypes={[effectiveAssignType]}
|
||||||
externalAssignFilter={externalAssignFilter}
|
externalAssignFilter={externalAssignFilter}
|
||||||
filterActions={
|
filterActions={
|
||||||
<KriMultiSelect
|
<KriMultiSelect
|
||||||
@@ -175,14 +203,14 @@ const ListAssignPage = () => {
|
|||||||
onChange={handleAssignFilterChange}
|
onChange={handleAssignFilterChange}
|
||||||
getValue={(item) => item.id}
|
getValue={(item) => item.id}
|
||||||
getLabel={(item) => item.name}
|
getLabel={(item) => item.name}
|
||||||
placeholder={`${LIST_HEADER_TYPE_LABEL[assignType]} 필터`}
|
placeholder={`${LIST_HEADER_TYPE_LABEL[effectiveAssignType]} 필터`}
|
||||||
widthClassName="w-56"
|
widthClassName="w-56"
|
||||||
heightClassName="h-9"
|
heightClassName="h-9"
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
rightActions={
|
rightActions={
|
||||||
<>
|
<>
|
||||||
{assignType === ListHeaderAssignConst.CONTACT_INTERVIEWER && (
|
{effectiveAssignType === ListHeaderAssignConst.CONTACT_INTERVIEWER && (
|
||||||
<label className="flex items-center gap-2 text-base cursor-pointer">
|
<label className="flex items-center gap-2 text-base cursor-pointer">
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={transferResve}
|
checked={transferResve}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { UserInfo } from "@/types/user";
|
|||||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||||
import { KriSelect, KriSelectItem } from "@/components/common/KriSelect";
|
import { KriSelect, KriSelectItem } from "@/components/common/KriSelect";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
|
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from "@/const/userConst";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
useFieldworkUsersQuery,
|
useFieldworkUsersQuery,
|
||||||
@@ -61,8 +61,9 @@ const ProjectAssignPage = () => {
|
|||||||
const roles = roleQuery.data ?? [];
|
const roles = roleQuery.data ?? [];
|
||||||
return roles
|
return roles
|
||||||
.filter(r => isFieldWorkUser(r.roleCd))
|
.filter(r => isFieldWorkUser(r.roleCd))
|
||||||
|
.filter(r => selectedProject?.ff !== false || r.roleCd !== FIELD_INTERVIEWER_ROLE)
|
||||||
.map(r => ({ value: String(r.roleCd), label: r.roleNm }));
|
.map(r => ({ value: String(r.roleCd), label: r.roleNm }));
|
||||||
}, [roleQuery.data]);
|
}, [roleQuery.data, selectedProject?.ff]);
|
||||||
|
|
||||||
const [companyFilter, setCompanyFilter] = useState<string>('');
|
const [companyFilter, setCompanyFilter] = useState<string>('');
|
||||||
const [roleFilter, setRoleFilter] = useState<KriSelectItem | undefined>(undefined);
|
const [roleFilter, setRoleFilter] = useState<KriSelectItem | undefined>(undefined);
|
||||||
@@ -233,8 +234,8 @@ const ProjectAssignPage = () => {
|
|||||||
}, [auth.user?.userCmpn, companyArray, companyFilter]);
|
}, [auth.user?.userCmpn, companyArray, companyFilter]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (roleFilter) return;
|
|
||||||
if (roleArray.length === 0) return;
|
if (roleArray.length === 0) return;
|
||||||
|
if (roleFilter && roleArray.some(role => role.value === roleFilter.value)) return;
|
||||||
|
|
||||||
const contactRole = roleArray.find(r => r.value === String(CONTACT_INTERVIEWER_ROLE));
|
const contactRole = roleArray.find(r => r.value === String(CONTACT_INTERVIEWER_ROLE));
|
||||||
setRoleFilter(contactRole ?? roleArray[0]);
|
setRoleFilter(contactRole ?? roleArray[0]);
|
||||||
|
|||||||
@@ -2,19 +2,17 @@
|
|||||||
|
|
||||||
import { Suspense, useEffect, useMemo, useState } from "react";
|
import { Suspense, useEffect, useMemo, useState } from "react";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { ArrowLeft, CalendarClock, RefreshCw } from "lucide-react";
|
import { ArrowLeft, RefreshCw } from "lucide-react";
|
||||||
import { useMounted } from "@kri/common/hooks";
|
import { useMounted } from "@kri/common/hooks";
|
||||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { useDialog } from "@/hooks/useDialog";
|
|
||||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||||
import { useListDetailQuery, useListHeaderQuery, useListReserveByUserQuery, useUpdateListMutation } from "@/query/list";
|
import { useListDetailQuery, useListHeaderQuery, useUpdateListMutation } from "@/query/list";
|
||||||
import { useProjectInfoQuery, useResultCodesQuery } from "@/query/project";
|
import { useProjectInfoQuery, useResultCodesQuery } from "@/query/project";
|
||||||
import ListContactInfoPanel, { buildInitialValues } from "@/components/list-contact/ListContactInfoPanel";
|
import ListContactInfoPanel, { buildInitialValues } from "@/components/list-contact/ListContactInfoPanel";
|
||||||
import ListContactEventPanel from "@/components/list-contact/ListContactEventPanel";
|
import ListContactEventPanel from "@/components/list-contact/ListContactEventPanel";
|
||||||
import ListUpdateHistoryPanel from "@/components/list-contact/ListUpdateHistoryPanel";
|
import ListUpdateHistoryPanel from "@/components/list-contact/ListUpdateHistoryPanel";
|
||||||
import ReservationListDialog from "@/components/dialog/ReservationListDialog";
|
|
||||||
import { createEmptyListFilter, type listHeader } from "@/types/list";
|
import { createEmptyListFilter, type listHeader } from "@/types/list";
|
||||||
import type { ResultCode } from "@/types/project";
|
import type { ResultCode } from "@/types/project";
|
||||||
import { isManager } from "@/utils/userRole";
|
import { isManager } from "@/utils/userRole";
|
||||||
@@ -31,7 +29,6 @@ const ListContactPageContent = () => {
|
|||||||
const mounted = useMounted();
|
const mounted = useMounted();
|
||||||
const { auth } = useAuth();
|
const { auth } = useAuth();
|
||||||
const { selectedProject } = useSelectedProject();
|
const { selectedProject } = useSelectedProject();
|
||||||
const { isDialogOpen, showDialog } = useDialog();
|
|
||||||
|
|
||||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||||
const prjctCd = selectedProject?.prjctCd ?? "";
|
const prjctCd = selectedProject?.prjctCd ?? "";
|
||||||
@@ -116,9 +113,6 @@ const ListContactPageContent = () => {
|
|||||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, queriesEnabled);
|
const resultCodesQuery = useResultCodesQuery(prjctIdx, queriesEnabled);
|
||||||
const updateListMutation = useUpdateListMutation(prjctIdx);
|
const updateListMutation = useUpdateListMutation(prjctIdx);
|
||||||
|
|
||||||
const reservationDialogOpen = isDialogOpen('reservationListDialog');
|
|
||||||
const reserveByUserQuery = useListReserveByUserQuery(prjctIdx, userId, reservationDialogOpen);
|
|
||||||
|
|
||||||
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]);
|
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]);
|
||||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]);
|
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]);
|
||||||
|
|
||||||
@@ -139,14 +133,6 @@ const ListContactPageContent = () => {
|
|||||||
router.push("/list/manage");
|
router.push("/list/manage");
|
||||||
}, [sid, router]);
|
}, [sid, router]);
|
||||||
|
|
||||||
const handleNavigateToSid = (nextSid: string) => {
|
|
||||||
if(shouldBlockNavigation){
|
|
||||||
alert("통화 중에는 이동할 수 없습니다.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
router.push(`/list/contact?sid=${encodeURIComponent(nextSid)}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleGoToListManage = () => {
|
const handleGoToListManage = () => {
|
||||||
if(shouldBlockNavigation){
|
if(shouldBlockNavigation){
|
||||||
alert("통화 중에는 이동할 수 없습니다.");
|
alert("통화 중에는 이동할 수 없습니다.");
|
||||||
@@ -159,6 +145,11 @@ const ListContactPageContent = () => {
|
|||||||
setFormValues((prev) => ({ ...prev, [listHderId]: value }));
|
setFormValues((prev) => ({ ...prev, [listHderId]: value }));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleCancelEdit = () => {
|
||||||
|
setFormValues(initialFormValues);
|
||||||
|
setIsEditing(false);
|
||||||
|
};
|
||||||
|
|
||||||
const handleToggleEdit = async () => {
|
const handleToggleEdit = async () => {
|
||||||
if (!isEditing) {
|
if (!isEditing) {
|
||||||
setIsEditing(true);
|
setIsEditing(true);
|
||||||
@@ -201,10 +192,11 @@ const ListContactPageContent = () => {
|
|||||||
<RefreshCw className={`h-4 w-4 ${listDetailQuery.isFetching ? "animate-spin" : ""}`} />
|
<RefreshCw className={`h-4 w-4 ${listDetailQuery.isFetching ? "animate-spin" : ""}`} />
|
||||||
</Button>
|
</Button>
|
||||||
<div className="ml-auto flex items-center gap-2">
|
<div className="ml-auto flex items-center gap-2">
|
||||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('reservationListDialog')}>
|
{isEditing ? (
|
||||||
<CalendarClock className="h-4 w-4" />
|
<Button type="button" variant="outline" disabled={updateListMutation.isPending} onClick={handleCancelEdit}>
|
||||||
예약리스트 조회
|
취소
|
||||||
</Button>
|
</Button>
|
||||||
|
) : null}
|
||||||
<Button type="button" disabled={updateListMutation.isPending} onClick={handleToggleEdit}>
|
<Button type="button" disabled={updateListMutation.isPending} onClick={handleToggleEdit}>
|
||||||
{isEditing ? '저장' : '수정'}
|
{isEditing ? '저장' : '수정'}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -248,8 +240,6 @@ const ListContactPageContent = () => {
|
|||||||
detail={listDetailQuery.data}
|
detail={listDetailQuery.data}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ReservationListDialog reservations={reserveByUserQuery.data ?? []} onSelectReservation={handleNavigateToSid} />
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,6 +68,7 @@ const downloadArrayBuffer = (buffer: ArrayBuffer, filename: string, type = 'appl
|
|||||||
const createEmptySearchUiState = (): ListSearchUiState => ({
|
const createEmptySearchUiState = (): ListSearchUiState => ({
|
||||||
searchText: '',
|
searchText: '',
|
||||||
searchContactResult: [],
|
searchContactResult: [],
|
||||||
|
searchContactDateRange: { from: '', to: '' },
|
||||||
searchInterviewResult: [],
|
searchInterviewResult: [],
|
||||||
surveyResultSelections: {},
|
surveyResultSelections: {},
|
||||||
filterRows: [],
|
filterRows: [],
|
||||||
@@ -284,7 +285,9 @@ const ListManagePage = () => {
|
|||||||
resultCodes={resultCodeArray}
|
resultCodes={resultCodeArray}
|
||||||
surveys={surveyArray}
|
surveys={surveyArray}
|
||||||
listHeaders={headerManageRows}
|
listHeaders={headerManageRows}
|
||||||
|
fieldInterviewEnabled={selectedProject?.ff !== false}
|
||||||
enableBatchEdit={canManageList}
|
enableBatchEdit={canManageList}
|
||||||
|
selectMode={canManageList ? 'multi' : 'click-event'}
|
||||||
refreshKey={listRefreshKey}
|
refreshKey={listRefreshKey}
|
||||||
onCurrentFilterChange={setCurrentListFilter}
|
onCurrentFilterChange={setCurrentListFilter}
|
||||||
onFilterSummaryChange={setFilterSummary}
|
onFilterSummaryChange={setFilterSummary}
|
||||||
|
|||||||
@@ -26,7 +26,8 @@ import {useRouter} from "next/navigation";
|
|||||||
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
|
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
|
||||||
import {useGroupCodeListQuery} from "@/query/intranet";
|
import {useGroupCodeListQuery} from "@/query/intranet";
|
||||||
import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
||||||
import {isManager} from "@/utils/userRole";
|
import {isInternalManager, isManager} from "@/utils/userRole";
|
||||||
|
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
|
||||||
|
|
||||||
const MainPage = () => {
|
const MainPage = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -41,7 +42,6 @@ const MainPage = () => {
|
|||||||
const [sorting, setSorting] = useState<SortingState>([]);
|
const [sorting, setSorting] = useState<SortingState>([]);
|
||||||
const [query, setQuery] = useState<ProjectListQuery>();
|
const [query, setQuery] = useState<ProjectListQuery>();
|
||||||
|
|
||||||
|
|
||||||
const statusArray: MultiSelectOption[] = useMemo(() => {
|
const statusArray: MultiSelectOption[] = useMemo(() => {
|
||||||
return (Object.values(ProjectStatus).filter((v) => typeof v === "number") as number[])
|
return (Object.values(ProjectStatus).filter((v) => typeof v === "number") as number[])
|
||||||
.sort((a, b) => a - b)
|
.sort((a, b) => a - b)
|
||||||
@@ -100,9 +100,9 @@ const MainPage = () => {
|
|||||||
const [searchDept, setSearchDept] = useState<string[]>([]);
|
const [searchDept, setSearchDept] = useState<string[]>([]);
|
||||||
const [searchFw, setSearchFw] = useState<string[]>([]);
|
const [searchFw, setSearchFw] = useState<string[]>([]);
|
||||||
|
|
||||||
const columns = getProjectColumns(users, groupCodeLabelMap);
|
|
||||||
const userId = auth.user?.userId ?? "";
|
const userId = auth.user?.userId ?? "";
|
||||||
const userRole = auth.user?.userRole;
|
const userRole = auth.user?.userRole;
|
||||||
|
const isInternal = isInternalManager(userRole);
|
||||||
|
|
||||||
const handleSearchClick = () => {
|
const handleSearchClick = () => {
|
||||||
const searchStatusCode:ProjectStatus[] = searchStatus
|
const searchStatusCode:ProjectStatus[] = searchStatus
|
||||||
@@ -123,9 +123,7 @@ const MainPage = () => {
|
|||||||
showDialog('projectCreateDialog');
|
showDialog('projectCreateDialog');
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleSubmit = async (data: ProjectCreateRequest): Promise<void> => {
|
const navigateWithProject = (projectInfo: ProjectInfo, path: string) => {
|
||||||
const projectInfo = await createMutation.mutateAsync(data);
|
|
||||||
|
|
||||||
setSelectedProject({
|
setSelectedProject({
|
||||||
prjctIdx: projectInfo.prjctIdx,
|
prjctIdx: projectInfo.prjctIdx,
|
||||||
prjctCd: projectInfo.prjctCd,
|
prjctCd: projectInfo.prjctCd,
|
||||||
@@ -136,22 +134,19 @@ const MainPage = () => {
|
|||||||
ff: projectInfo.ff
|
ff: projectInfo.ff
|
||||||
} as SelectedProject);
|
} as SelectedProject);
|
||||||
|
|
||||||
router.push("/project/info");
|
router.push(path);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClick = (projectInfo:ProjectInfo) => {
|
const handleSubmit = async (data: ProjectCreateRequest): Promise<void> => {
|
||||||
setSelectedProject({
|
const projectInfo = await createMutation.mutateAsync(data);
|
||||||
prjctIdx: projectInfo.prjctIdx,
|
navigateWithProject(projectInfo, "/project/info");
|
||||||
prjctCd: projectInfo.prjctCd,
|
};
|
||||||
prjctName: projectInfo.prjctName,
|
|
||||||
itrntPrjctCd: projectInfo.itrntPrjctCd,
|
|
||||||
ownerDept: projectInfo.ownerDept,
|
|
||||||
ownerFw: projectInfo.ownerFw,
|
|
||||||
ff: projectInfo.ff
|
|
||||||
} as SelectedProject);
|
|
||||||
|
|
||||||
router.push(`/list/manage`);
|
const handleClick = (projectInfo: ProjectInfo) => navigateWithProject(projectInfo, "/list/manage");
|
||||||
}
|
|
||||||
|
const handleNavigateToInfo = (projectInfo: ProjectInfo) => navigateWithProject(projectInfo, "/project/info");
|
||||||
|
|
||||||
|
const columns = getProjectColumns(users, groupCodeLabelMap, isInternal ? handleNavigateToInfo : undefined);
|
||||||
|
|
||||||
if (!mounted || isLoading) return <LoadingOverlayAdapter force />;
|
if (!mounted || isLoading) return <LoadingOverlayAdapter force />;
|
||||||
|
|
||||||
@@ -211,11 +206,13 @@ const MainPage = () => {
|
|||||||
검색
|
검색
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
{isInternal && (
|
||||||
|
<Button
|
||||||
onClick={handleCreateClick}
|
onClick={handleCreateClick}
|
||||||
>
|
>
|
||||||
프로젝트 등록
|
프로젝트 등록
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||||
|
|||||||
@@ -49,28 +49,15 @@ const buildRows = (data: SendResultSummaryResponse[]): SummaryRow[] =>
|
|||||||
const moneyUnit = (value: number) => `${value.toLocaleString()}원`;
|
const moneyUnit = (value: number) => `${value.toLocaleString()}원`;
|
||||||
const caseUnit = (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 MessageProgressPage = () => {
|
||||||
const mounted = useMounted();
|
const mounted = useMounted();
|
||||||
const { selectedProject } = useSelectedProject();
|
const { selectedProject } = useSelectedProject();
|
||||||
|
|
||||||
const [dateRange, setDateRange] = useState(() => {
|
const [dateRange, setDateRange] = useState({ from: "", to: "" });
|
||||||
const now = new Date();
|
|
||||||
return { from: getFirstDayOfMonth(now), to: getLastDayOfMonth(now) };
|
|
||||||
});
|
|
||||||
|
|
||||||
const prjctCd = selectedProject?.prjctCd ?? "";
|
const prjctCd = selectedProject?.prjctCd ?? "";
|
||||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
|
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
|
||||||
const enabled = mounted && !!prjctCd && !!dateRange.from && !!dateRange.to;
|
const enabled = mounted && !!prjctCd;
|
||||||
|
|
||||||
const summaryQuery = useSendResultSummaryQuery(
|
const summaryQuery = useSendResultSummaryQuery(
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -333,7 +333,7 @@ const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onReg
|
|||||||
const ProjectInfoPage = () => {
|
const ProjectInfoPage = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const mounted = useMounted();
|
const mounted = useMounted();
|
||||||
const {selectedProject} = useSelectedProject();
|
const {selectedProject, setSelectedProject} = useSelectedProject();
|
||||||
const {isDialogOpen, showDialog, hideDialog} = useDialog();
|
const {isDialogOpen, showDialog, hideDialog} = useDialog();
|
||||||
const {users} = useItrntUserList();
|
const {users} = useItrntUserList();
|
||||||
const {auth} = useAuth();
|
const {auth} = useAuth();
|
||||||
@@ -544,6 +544,16 @@ const ProjectInfoPage = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await updateMutation.mutateAsync(requestUpdateProject);
|
await updateMutation.mutateAsync(requestUpdateProject);
|
||||||
|
const savedProjectInfo = requestUpdateProject.projectInfo;
|
||||||
|
setSelectedProject({
|
||||||
|
prjctIdx: savedProjectInfo.prjctIdx,
|
||||||
|
prjctCd: savedProjectInfo.prjctCd,
|
||||||
|
prjctName: savedProjectInfo.prjctName,
|
||||||
|
itrntPrjctCd: savedProjectInfo.itrntPrjctCd,
|
||||||
|
ownerDept: savedProjectInfo.ownerDept,
|
||||||
|
ownerFw: savedProjectInfo.ownerFw,
|
||||||
|
ff: savedProjectInfo.ff,
|
||||||
|
});
|
||||||
initialProjectInfoRef.current = projectInfo;
|
initialProjectInfoRef.current = projectInfo;
|
||||||
alert("저장되었습니다.");
|
alert("저장되었습니다.");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import {RouteContext} from "@/types/common";
|
import {RouteContext} from "@/types/common";
|
||||||
import {createContactApi} from "@/lib/http-server";
|
import {createContactApi} from "@/lib/http-server";
|
||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
|
import type {ProjectCompanyAssignSummary, ProjectFieldworkAssignSummary} from "@/types/list";
|
||||||
|
|
||||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
@@ -19,6 +20,25 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
|||||||
return NextResponse.json(result, { status: 200 });
|
return NextResponse.json(result, { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (action === "prjct-cmpn-summary" && slug.length === 2) {
|
||||||
|
const result = await contactApi.get<ProjectCompanyAssignSummary>(`/assign/prjct-cmpn-summary/${slug[1]}`);
|
||||||
|
return NextResponse.json(result, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (action === "prjct-fieldwork-summary" && slug.length === 2) {
|
||||||
|
const assignType = req.nextUrl.searchParams.get("assignType");
|
||||||
|
const cmpnIds = req.nextUrl.searchParams.get("cmpnIds");
|
||||||
|
if (!assignType) {
|
||||||
|
return NextResponse.json({ message: "assignType이 필요합니다." }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const query = `?assignType=${assignType}${cmpnIds ? `&cmpnIds=${encodeURIComponent(cmpnIds)}` : ""}`;
|
||||||
|
const result = await contactApi.get<ProjectFieldworkAssignSummary>(
|
||||||
|
`/assign/prjct-fieldwork-summary/${slug[1]}${query}`,
|
||||||
|
);
|
||||||
|
return NextResponse.json(result, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
return errorToResponse(error);
|
return errorToResponse(error);
|
||||||
|
|||||||
@@ -30,6 +30,23 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
||||||
|
try {
|
||||||
|
const { slug = [] } = await context.params;
|
||||||
|
const [action] = slug;
|
||||||
|
const contactApi = await createContactApi();
|
||||||
|
|
||||||
|
if (action === "event" && slug.length === 2) {
|
||||||
|
await contactApi.del(`/list-hist/event/${slug[1]}`);
|
||||||
|
return new NextResponse(null, { status: 204 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return errorToResponse(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
|
|||||||
@@ -17,11 +17,31 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
|||||||
return NextResponse.json(result, { status: 200 });
|
return NextResponse.json(result, { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (action === "user" && slug.length === 3 && slug[2] === "search") {
|
||||||
|
const fromDt = req.nextUrl.searchParams.get("fromDt");
|
||||||
|
const toDt = req.nextUrl.searchParams.get("toDt");
|
||||||
|
if (!fromDt || !toDt) {
|
||||||
|
return NextResponse.json({ message: "fromDt, toDt가 필요합니다." }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await contactApi.get<ListReserve[]>(
|
||||||
|
`/reserve/user/${encodeURIComponent(slug[1])}/search?fromDt=${fromDt}&toDt=${toDt}`,
|
||||||
|
);
|
||||||
|
return NextResponse.json(result, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
if (action === "user" && slug.length === 3) {
|
if (action === "user" && slug.length === 3) {
|
||||||
const result = await contactApi.get<ListReserve[]>(`/reserve/${slug[1]}/user/${slug[2]}`);
|
const result = await contactApi.get<ListReserve[]>(`/reserve/${slug[1]}/user/${slug[2]}`);
|
||||||
return NextResponse.json(result, { status: 200 });
|
return NextResponse.json(result, { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (action === "user" && slug.length === 2) {
|
||||||
|
const requestPast = req.nextUrl.searchParams.get("requestPast");
|
||||||
|
const query = requestPast !== null ? `?requestPast=${requestPast}` : "";
|
||||||
|
const result = await contactApi.get<ListReserve[]>(`/reserve/user/${encodeURIComponent(slug[1])}${query}`);
|
||||||
|
return NextResponse.json(result, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
return errorToResponse(error);
|
return errorToResponse(error);
|
||||||
|
|||||||
@@ -251,3 +251,4 @@
|
|||||||
.ProseMirror [data-resize-container][data-resize-state="resizing"] {
|
.ProseMirror [data-resize-container][data-resize-state="resizing"] {
|
||||||
outline: 1px dashed #0ea5e9;
|
outline: 1px dashed #0ea5e9;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { LogOut, ZoomIn, ZoomOut } from "lucide-react";
|
import { CalendarClock, LogOut, ZoomIn, ZoomOut } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { KriHeader } from "@/components/layout/KriHeader";
|
import { KriHeader } from "@/components/layout/KriHeader";
|
||||||
import type { TopMenuItem } from "@/config/menu.types";
|
import type { TopMenuItem } from "@/config/menu.types";
|
||||||
@@ -21,6 +21,7 @@ interface AppHeaderProps {
|
|||||||
onNavigate: (path: string) => void;
|
onNavigate: (path: string) => void;
|
||||||
decreaseFontSize: () => void;
|
decreaseFontSize: () => void;
|
||||||
increaseFontSize: () => void;
|
increaseFontSize: () => void;
|
||||||
|
onOpenReserveSearch: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AppHeader({
|
export function AppHeader({
|
||||||
@@ -37,6 +38,7 @@ export function AppHeader({
|
|||||||
onNavigate,
|
onNavigate,
|
||||||
decreaseFontSize,
|
decreaseFontSize,
|
||||||
increaseFontSize,
|
increaseFontSize,
|
||||||
|
onOpenReserveSearch,
|
||||||
}: AppHeaderProps) {
|
}: AppHeaderProps) {
|
||||||
return (
|
return (
|
||||||
<KriHeader
|
<KriHeader
|
||||||
@@ -77,6 +79,9 @@ export function AppHeader({
|
|||||||
<ZoomIn className="h-4 w-4" />
|
<ZoomIn className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
<Button variant="ghost" size="icon-lg" onClick={onOpenReserveSearch} title="예약 내역 조회">
|
||||||
|
<CalendarClock className="size-6" />
|
||||||
|
</Button>
|
||||||
<span className="hidden text-sm text-gray-600 sm:inline">{userInfo?.userName || ""}</span>
|
<span className="hidden text-sm text-gray-600 sm:inline">{userInfo?.userName || ""}</span>
|
||||||
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
|
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
|
||||||
<LogOut className="h-4 w-4" />
|
<LogOut className="h-4 w-4" />
|
||||||
|
|||||||
@@ -7,9 +7,11 @@ import { getCurrentPositionMeta } from "@kri/common/browser";
|
|||||||
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
||||||
import { AppHeader } from "@/components/app-shell/AppHeader";
|
import { AppHeader } from "@/components/app-shell/AppHeader";
|
||||||
import { AppSidebar } from "@/components/app-shell/AppSidebar";
|
import { AppSidebar } from "@/components/app-shell/AppSidebar";
|
||||||
|
import ReserveSearchDialog from "@/components/dialog/ReserveSearchDialog";
|
||||||
import { useFontSize } from "@/hooks/useFontSize";
|
import { useFontSize } from "@/hooks/useFontSize";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||||
|
import { useDialog } from "@/hooks/useDialog";
|
||||||
import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data";
|
import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data";
|
||||||
import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types";
|
import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@@ -103,6 +105,7 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
|
|||||||
|
|
||||||
const { auth } = useAuth();
|
const { auth } = useAuth();
|
||||||
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject();
|
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject();
|
||||||
|
const { showDialog } = useDialog();
|
||||||
const [menuOpen, setMenuOpen] = useState(true);
|
const [menuOpen, setMenuOpen] = useState(true);
|
||||||
const [fontSize, setFontSize] = useFontSize(initialFontSize, { hydrateFromCookie: false });
|
const [fontSize, setFontSize] = useFontSize(initialFontSize, { hydrateFromCookie: false });
|
||||||
const userRole = auth.user?.userRole;
|
const userRole = auth.user?.userRole;
|
||||||
@@ -207,6 +210,7 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
|
|||||||
onNavigate={movePage}
|
onNavigate={movePage}
|
||||||
decreaseFontSize={decreaseFontSize}
|
decreaseFontSize={decreaseFontSize}
|
||||||
increaseFontSize={increaseFontSize}
|
increaseFontSize={increaseFontSize}
|
||||||
|
onOpenReserveSearch={() => showDialog("reserveSearchDialog")}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
sidebar={
|
sidebar={
|
||||||
@@ -224,6 +228,7 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
<ReserveSearchDialog />
|
||||||
</KriMainLayout>
|
</KriMainLayout>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,25 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useMemo } from 'react'
|
import { useMemo, useState } from 'react'
|
||||||
import { useCmpnListQuery } from '@/query/cmpn'
|
import { useCmpnListQuery } from '@/query/cmpn'
|
||||||
import { useFieldworkUsersQuery } from '@/query/user'
|
import { useFieldworkUsersQuery } from '@/query/user'
|
||||||
import { useAssignedCmpnIdsQuery, useAssignedFieldworkIdsQuery } from '@/query/project'
|
import {
|
||||||
|
useAssignedCmpnIdsQuery,
|
||||||
|
useAssignedCmpnSummaryQuery,
|
||||||
|
useAssignedFieldworkIdsQuery,
|
||||||
|
useAssignedFieldworkSummaryQuery,
|
||||||
|
} from '@/query/project'
|
||||||
|
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||||
import { ListHeaderAssignConst } from '@/const/listConst'
|
import { ListHeaderAssignConst } from '@/const/listConst'
|
||||||
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
|
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
|
||||||
|
import { isInternalManager } from '@/utils/userRole'
|
||||||
import type { ListHeaderAssignType } from '@/types/list'
|
import type { ListHeaderAssignType } from '@/types/list'
|
||||||
|
|
||||||
export type AssignTargetListProps = {
|
export type AssignTargetListProps = {
|
||||||
prjctIdx: number
|
prjctIdx: number
|
||||||
enabled: boolean
|
enabled: boolean
|
||||||
assignType: ListHeaderAssignType
|
assignType: ListHeaderAssignType
|
||||||
|
userRole: number
|
||||||
selectedId?: string
|
selectedId?: string
|
||||||
onSelect: (id: string) => void
|
onSelect: (id: string) => void
|
||||||
}
|
}
|
||||||
@@ -61,36 +69,127 @@ export function useAssignTargetRows({ prjctIdx, enabled, assignType }: UseAssign
|
|||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AssignTargetList({ prjctIdx, enabled, assignType, selectedId, onSelect }: AssignTargetListProps) {
|
type AssignSummaryRow = {
|
||||||
const rows = useAssignTargetRows({ prjctIdx, enabled, assignType })
|
id: string
|
||||||
|
name: string
|
||||||
|
assignedCount: number
|
||||||
|
cmpn?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AssignTargetList({
|
||||||
|
prjctIdx,
|
||||||
|
enabled,
|
||||||
|
assignType,
|
||||||
|
userRole,
|
||||||
|
selectedId,
|
||||||
|
onSelect
|
||||||
|
}: AssignTargetListProps) {
|
||||||
|
const isOutsource = assignType === ListHeaderAssignConst.OUTSOURCE
|
||||||
|
const canFilterByCmpn = !isOutsource && isInternalManager(userRole)
|
||||||
|
const showCmpnColumn = canFilterByCmpn
|
||||||
|
const [cmpnIds, setCmpnIds] = useState<string[]>([])
|
||||||
|
|
||||||
|
const cmpnListQuery = useCmpnListQuery()
|
||||||
|
const cmpnSummaryQuery = useAssignedCmpnSummaryQuery(prjctIdx, enabled && isOutsource)
|
||||||
|
const fieldworkSummaryQuery = useAssignedFieldworkSummaryQuery(
|
||||||
|
prjctIdx,
|
||||||
|
assignType,
|
||||||
|
cmpnIds,
|
||||||
|
enabled && !isOutsource,
|
||||||
|
)
|
||||||
|
|
||||||
|
const summary = isOutsource ? cmpnSummaryQuery.data : fieldworkSummaryQuery.data
|
||||||
|
const isLoading = isOutsource ? cmpnSummaryQuery.isLoading : fieldworkSummaryQuery.isLoading
|
||||||
|
|
||||||
|
const cmpnAliasById = useMemo(
|
||||||
|
() => new Map((cmpnListQuery.data ?? []).map((cmpn) => [cmpn.cmpnId, cmpn.cmpnAlias || cmpn.cmpnId])),
|
||||||
|
[cmpnListQuery.data],
|
||||||
|
)
|
||||||
|
|
||||||
|
const rows = useMemo<AssignSummaryRow[]>(() => {
|
||||||
|
if (isOutsource) {
|
||||||
|
return (cmpnSummaryQuery.data?.assignees ?? []).map((item) => ({
|
||||||
|
id: item.cmpnId,
|
||||||
|
name: item.cmpnAlias || item.cmpnId,
|
||||||
|
assignedCount: item.assignedCount,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
return (fieldworkSummaryQuery.data?.assignees ?? []).map((item) => ({
|
||||||
|
id: item.userId,
|
||||||
|
name: item.userName,
|
||||||
|
assignedCount: item.assignedCount,
|
||||||
|
cmpn: cmpnAliasById.get(item.userCmpn) ?? item.userCmpn,
|
||||||
|
}))
|
||||||
|
}, [isOutsource, cmpnSummaryQuery.data, fieldworkSummaryQuery.data, cmpnAliasById])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
<div className="flex h-[78vh] flex-col border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||||
<div className="h-[78vh] overflow-y-auto">
|
{canFilterByCmpn ? (
|
||||||
|
<div className="shrink-0 border-b border-gray-200 p-2">
|
||||||
|
<KriMultiSelect
|
||||||
|
items={cmpnListQuery.data ?? []}
|
||||||
|
value={cmpnIds}
|
||||||
|
onChange={setCmpnIds}
|
||||||
|
getValue={(item) => item.cmpnId}
|
||||||
|
getLabel={(item) => item.cmpnAlias || item.cmpnId}
|
||||||
|
placeholder="외주사 선택(전체)"
|
||||||
|
widthClassName="w-full"
|
||||||
|
heightClassName="h-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{summary ? (
|
||||||
|
<div className="shrink-0 border-b border-gray-200 bg-gray-50 px-3 py-1 text-lg font-semibold text-gray-700">
|
||||||
|
전체 {summary.totalCount}건 · 미배정 {summary.unassignedCount}건
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto">
|
||||||
<table className="w-full table-fixed">
|
<table className="w-full table-fixed">
|
||||||
<colgroup>
|
<colgroup>
|
||||||
<col className="w-28" />
|
<col className="w-20" />
|
||||||
<col />
|
<col />
|
||||||
|
{showCmpnColumn ? <col className="w-20" /> : null}
|
||||||
|
<col className="w-14" />
|
||||||
</colgroup>
|
</colgroup>
|
||||||
<thead className="bg-primary text-white sticky top-0">
|
<thead className="bg-primary text-white sticky top-0">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="p-2 text-left text-base font-medium">ID</th>
|
<th className="p-2 text-left text-base font-medium">ID</th>
|
||||||
<th className="p-2 text-left text-base font-medium">이름</th>
|
<th className="p-2 text-left text-base font-medium">이름</th>
|
||||||
|
{showCmpnColumn ? <th className="p-2 text-left text-base font-medium">회사</th> : null}
|
||||||
|
<th className="p-2 text-right text-base font-medium">배정</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{rows.map((row) => (
|
{isLoading ? (
|
||||||
<tr
|
<tr>
|
||||||
key={row.id}
|
<td colSpan={showCmpnColumn ? 4 : 3} className="p-4 text-center text-sm text-muted-foreground">
|
||||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
불러오는 중...
|
||||||
selectedId === row.id ? 'bg-accent' : ''
|
</td>
|
||||||
}`}
|
|
||||||
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>
|
</tr>
|
||||||
))}
|
) : rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={showCmpnColumn ? 4 : 3} className="p-4 text-center text-sm text-muted-foreground">
|
||||||
|
대상이 없습니다.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
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>
|
||||||
|
{showCmpnColumn ? <td className="p-2 text-base truncate">{row.cmpn}</td> : null}
|
||||||
|
<td className="p-2 text-base text-right">{row.assignedCount}</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -17,6 +17,11 @@ export type KriDateTimePickerProps = {
|
|||||||
contentClassName?: string
|
contentClassName?: string
|
||||||
disabled?: boolean
|
disabled?: boolean
|
||||||
modalPopover?: boolean
|
modalPopover?: boolean
|
||||||
|
startHour?: number
|
||||||
|
endHour?: number
|
||||||
|
minuteStep?: number
|
||||||
|
hourLabel?: string
|
||||||
|
minuteLabel?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const parseDateTime = (value: string): { date: Date | undefined; time: string } => {
|
const parseDateTime = (value: string): { date: Date | undefined; time: string } => {
|
||||||
@@ -59,15 +64,20 @@ const toDisplayText = (date: Date | undefined, time: string, placeholder: string
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function KriDateTimePicker({
|
export function KriDateTimePicker({
|
||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
placeholder = '날짜/시간 선택',
|
placeholder = '날짜/시간 선택',
|
||||||
className,
|
className,
|
||||||
triggerClassName,
|
triggerClassName,
|
||||||
contentClassName,
|
contentClassName,
|
||||||
disabled = false,
|
disabled = false,
|
||||||
modalPopover = true,
|
modalPopover = true,
|
||||||
}: KriDateTimePickerProps) {
|
startHour,
|
||||||
|
endHour,
|
||||||
|
minuteStep,
|
||||||
|
hourLabel,
|
||||||
|
minuteLabel,
|
||||||
|
}: KriDateTimePickerProps) {
|
||||||
const [open, setOpen] = React.useState(false)
|
const [open, setOpen] = React.useState(false)
|
||||||
const { date, time } = parseDateTime(value)
|
const { date, time } = parseDateTime(value)
|
||||||
const hasValue = date !== undefined
|
const hasValue = date !== undefined
|
||||||
@@ -83,53 +93,59 @@ export function KriDateTimePicker({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn('relative', className)}>
|
<div className={cn('relative', className)}>
|
||||||
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
className={cn(
|
className={cn(
|
||||||
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
|
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
|
||||||
!hasValue && 'text-muted-foreground',
|
!hasValue && 'text-muted-foreground',
|
||||||
triggerClassName,
|
triggerClassName,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||||
<span className="truncate">{toDisplayText(date, time, placeholder)}</span>
|
<span className="truncate">{toDisplayText(date, time, placeholder)}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
|
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
|
||||||
<div className="sm:flex">
|
<div className="sm:flex">
|
||||||
<Calendar
|
<Calendar
|
||||||
mode="single"
|
mode="single"
|
||||||
selected={date}
|
selected={date}
|
||||||
onSelect={handleDateSelect}
|
onSelect={handleDateSelect}
|
||||||
/>
|
autoFocus
|
||||||
<KriTimePicker
|
/>
|
||||||
value={time || '00:00'}
|
<KriTimePicker
|
||||||
onChange={handleTimeChange}
|
value={time || '00:00'}
|
||||||
disabled={!date}
|
onChange={handleTimeChange}
|
||||||
/>
|
disabled={!date}
|
||||||
</div>
|
startHour={startHour}
|
||||||
</PopoverContent>
|
endHour={endHour}
|
||||||
</Popover>
|
minuteStep={minuteStep}
|
||||||
|
hourLabel={hourLabel}
|
||||||
|
minuteLabel={minuteLabel}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
{hasValue && !disabled ? (
|
{hasValue && !disabled ? (
|
||||||
<button
|
<button
|
||||||
type="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"
|
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) => {
|
onClick={(event) => {
|
||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
onChange('')
|
onChange('')
|
||||||
}}
|
}}
|
||||||
aria-label="날짜/시간 초기화"
|
aria-label="날짜/시간 초기화"
|
||||||
>
|
>
|
||||||
<X className="h-3.5 w-3.5" />
|
<X className="h-3.5 w-3.5" />
|
||||||
</button>
|
</button>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,10 +9,10 @@ import { cn } from '@/lib/utils'
|
|||||||
import { KRI_PW_REGEX, ONLY_ALLOWED_PW_REGEX } from '@/const/validationConst'
|
import { KRI_PW_REGEX, ONLY_ALLOWED_PW_REGEX } from '@/const/validationConst'
|
||||||
|
|
||||||
const requirements = [
|
const requirements = [
|
||||||
{ test: (value: string) => /[A-Za-z]/.test(value), text: '영문 1개 이상' },
|
//{ test: (value: string) => /[A-Za-z]/.test(value), text: '영문 1개 이상' },
|
||||||
{ test: (value: string) => /\d/.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.length >= 1 && value.length <= 20, text: '1~20자' },
|
||||||
{ test: (value: string) => !value || ONLY_ALLOWED_PW_REGEX.test(value), text: '허용 문자만 사용' },
|
{ test: (value: string) => !value || KRI_PW_REGEX.test(value), text: '영문, 숫자, 허용된 특수문자를 사용하여 1~20자로 입력해야 합니다.' },
|
||||||
]
|
]
|
||||||
|
|
||||||
export type KriPasswordRef = {
|
export type KriPasswordRef = {
|
||||||
@@ -55,12 +55,13 @@ export const KriPassword = forwardRef<KriPasswordRef, KriPasswordProps>(function
|
|||||||
const score = checks.filter((item) => item.met).length
|
const score = checks.filter((item) => item.met).length
|
||||||
|
|
||||||
const statusText = useMemo(() => {
|
const statusText = useMemo(() => {
|
||||||
if (!value) return '비밀번호를 입력하세요'
|
if (!value) return '비밀번호를 입력하세요.'
|
||||||
if (!hasOnlyAllowedChars) return '허용되지 않는 문자가 포함되어 있어요'
|
if (!hasOnlyAllowedChars) return '허용되지 않는 문자가 포함되어 있습니다.'
|
||||||
return isValid ? '사용 가능한 비밀번호입니다' : '영문과 숫자를 포함한 8~20자로 입력하세요'
|
return isValid ? '사용 가능한 비밀번호입니다' : '영문, 숫자, 허용된 특수문자를 사용하여 1~20자로 입력해야 합니다.'
|
||||||
}, [hasOnlyAllowedChars, isValid, value])
|
}, [hasOnlyAllowedChars, isValid, value])
|
||||||
|
|
||||||
const barClass = score <= 1 ? 'bg-destructive' : score === 2 ? 'bg-orange-500' : score === 3 ? 'bg-yellow-400' : 'bg-green-500'
|
//const barClass = score <= 1 ? 'bg-destructive' : score === 2 ? 'bg-orange-500' : score === 3 ? 'bg-yellow-400' : 'bg-green-500'
|
||||||
|
const barClass = 'bg-green-500'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn('w-full space-y-2', className)}>
|
<div className={cn('w-full space-y-2', className)}>
|
||||||
|
|||||||
@@ -9,6 +9,10 @@ export type KriTimePickerProps = {
|
|||||||
onChange: (value: string) => void
|
onChange: (value: string) => void
|
||||||
disabled?: boolean
|
disabled?: boolean
|
||||||
minuteStep?: number
|
minuteStep?: number
|
||||||
|
startHour?: number
|
||||||
|
endHour?: number
|
||||||
|
hourLabel?: string
|
||||||
|
minuteLabel?: string
|
||||||
className?: string
|
className?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,72 +31,97 @@ const formatTime = (hour: number, minute: number) => {
|
|||||||
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
|
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const normalizeHour = (hour: number, fallback: number) => {
|
||||||
|
return Number.isFinite(hour) ? Math.min(23, Math.max(0, Math.trunc(hour))) : fallback
|
||||||
|
}
|
||||||
|
|
||||||
export function KriTimePicker({
|
export function KriTimePicker({
|
||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
disabled = false,
|
disabled = false,
|
||||||
minuteStep = 5,
|
minuteStep = 5,
|
||||||
className,
|
startHour = 0,
|
||||||
}: KriTimePickerProps) {
|
endHour = 23,
|
||||||
|
hourLabel = '시',
|
||||||
|
minuteLabel = '분',
|
||||||
|
className,
|
||||||
|
}: KriTimePickerProps) {
|
||||||
const { hour: selectedHour, minute: selectedMinute } = parseTime(value)
|
const { hour: selectedHour, minute: selectedMinute } = parseTime(value)
|
||||||
const normalizedMinuteStep = Number.isFinite(minuteStep) && minuteStep > 0
|
const normalizedMinuteStep = Number.isFinite(minuteStep) && minuteStep > 0
|
||||||
? Math.min(Math.floor(minuteStep), 60)
|
? Math.min(Math.floor(minuteStep), 60)
|
||||||
: 5
|
: 5
|
||||||
const hours = Array.from({ length: 24 }, (_, index) => index)
|
|
||||||
|
const clampedStartHour = normalizeHour(startHour, 0)
|
||||||
|
const clampedEndHour = normalizeHour(endHour, 23)
|
||||||
|
// startHour > endHour로 잘못 지정된 경우, 두 값을 뒤바꿔 유효한 범위로 되돌린다.
|
||||||
|
const [normalizedStartHour, normalizedEndHour] = clampedStartHour > clampedEndHour
|
||||||
|
? [clampedEndHour, clampedStartHour]
|
||||||
|
: [clampedStartHour, clampedEndHour]
|
||||||
|
|
||||||
|
const hours = Array.from(
|
||||||
|
{ length: normalizedEndHour - normalizedStartHour + 1 },
|
||||||
|
(_, index) => normalizedStartHour + index,
|
||||||
|
)
|
||||||
const minutes = Array.from(
|
const minutes = Array.from(
|
||||||
{ length: Math.ceil(60 / normalizedMinuteStep) },
|
{ length: Math.ceil(60 / normalizedMinuteStep) },
|
||||||
(_, index) => index * normalizedMinuteStep,
|
(_, index) => index * normalizedMinuteStep,
|
||||||
).filter((minute) => minute < 60)
|
).filter((minute) => minute < 60)
|
||||||
|
|
||||||
const handleTimeChange = (type: 'hour' | 'minute', nextValue: number) => {
|
const handleTimeChange = (type: 'hour' | 'minute', nextValue: number) => {
|
||||||
if (disabled) return
|
if (disabled) return
|
||||||
|
|
||||||
const nextHour = type === 'hour' ? nextValue : selectedHour ?? 0
|
const nextHour = type === 'hour' ? nextValue : selectedHour ?? normalizedStartHour
|
||||||
const nextMinute = type === 'minute' ? nextValue : selectedMinute ?? 0
|
const nextMinute = type === 'minute' ? nextValue : selectedMinute ?? 0
|
||||||
|
|
||||||
onChange(formatTime(nextHour, nextMinute))
|
onChange(formatTime(nextHour, nextMinute))
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn('flex flex-col divide-y sm:h-[300px] sm:flex-row sm:divide-x sm:divide-y-0', className)}>
|
<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 flex-col">
|
||||||
|
<div className="mt-1 p-1 align-middle text-center text-base border-b">{hourLabel}</div>
|
||||||
|
<ScrollArea className="w-64 sm:w-auto sm:min-h-0 sm:flex-1">
|
||||||
<div className="flex p-2 sm:flex-col">
|
<div className="flex p-2 sm:flex-col">
|
||||||
{hours.map((hour) => (
|
{hours.map((hour) => (
|
||||||
<Button
|
<Button
|
||||||
key={hour}
|
key={hour}
|
||||||
type="button"
|
type="button"
|
||||||
size="icon"
|
size="icon"
|
||||||
variant={selectedHour === hour ? 'default' : 'ghost'}
|
variant={selectedHour === hour ? 'default' : 'ghost'}
|
||||||
className="aspect-square shrink-0 sm:w-full"
|
className="aspect-square shrink-0 sm:w-full"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onClick={() => handleTimeChange('hour', hour)}
|
onClick={() => handleTimeChange('hour', hour)}
|
||||||
>
|
>
|
||||||
{hour}
|
{hour}
|
||||||
</Button>
|
</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>
|
</div>
|
||||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<div className="mt-1 p-1 align-middle text-center text-base border-b">{minuteLabel}</div>
|
||||||
|
<ScrollArea className="w-64 sm:w-auto sm:min-h-0 sm:flex-1">
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import { Plus, X } from 'lucide-react'
|
|
||||||
import { KriDialog } from '@/components/common/KriDialog'
|
import { KriDialog } from '@/components/common/KriDialog'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
@@ -33,12 +32,13 @@ export const operatorLabel: Record<FilterOperator, string> = {
|
|||||||
notContains: '포함하지 않음',
|
notContains: '포함하지 않음',
|
||||||
empty: '값 없음',
|
empty: '값 없음',
|
||||||
notEmpty: '값 있음',
|
notEmpty: '값 있음',
|
||||||
|
none: '필터 없음',
|
||||||
}
|
}
|
||||||
|
|
||||||
const createFilterRow = (headerId: number, headerOptions: FilterHeaderOption[]): FilterRow => ({
|
const createFilterRow = (headerId: number, headerOptions: FilterHeaderOption[]): FilterRow => ({
|
||||||
id: crypto.randomUUID(),
|
id: crypto.randomUUID(),
|
||||||
headerId,
|
headerId,
|
||||||
operator: headerOptions.find((option) => option.id === headerId)?.allowedOperators[0] ?? 'eq',
|
operator: headerOptions.find((option) => option.id === headerId)?.defaultOperator ?? 'eq',
|
||||||
textValue: '',
|
textValue: '',
|
||||||
multiValues: [],
|
multiValues: [],
|
||||||
})
|
})
|
||||||
@@ -56,18 +56,17 @@ const ListFilterDialog = ({
|
|||||||
const [submitting, setSubmitting] = useState(false)
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
|
||||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||||
const defaultHeaderId = headerOptions.find((option) => !option.disabled)?.id ?? 0
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!resolvedOpen) return
|
if (!resolvedOpen) return
|
||||||
if (initialRows.length > 0) {
|
const initialByHeaderId = new Map(initialRows.map((row) => [row.headerId, row]))
|
||||||
setRows(initialRows.map((row) => ({ ...row })))
|
setRows(
|
||||||
return
|
headerOptions.map((option) => {
|
||||||
}
|
const existing = initialByHeaderId.get(option.id)
|
||||||
if (defaultHeaderId > 0) {
|
return existing ? { ...existing } : createFilterRow(option.id, headerOptions)
|
||||||
setRows([createFilterRow(defaultHeaderId, headerOptions)])
|
}),
|
||||||
}
|
)
|
||||||
}, [resolvedOpen, initialRows, defaultHeaderId, headerOptions])
|
}, [resolvedOpen, initialRows, headerOptions])
|
||||||
|
|
||||||
const handleOpenChange = (nextOpen: boolean) => {
|
const handleOpenChange = (nextOpen: boolean) => {
|
||||||
onOpenChange?.(nextOpen)
|
onOpenChange?.(nextOpen)
|
||||||
@@ -78,17 +77,8 @@ const ListFilterDialog = ({
|
|||||||
hideDialog(dialogId)
|
hideDialog(dialogId)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleAddRow = () => {
|
const handleChangeRow = (headerId: number, updater: (row: FilterRow) => FilterRow) => {
|
||||||
if (defaultHeaderId <= 0) return
|
setRows((prev) => prev.map((row) => (row.headerId === headerId ? updater(row) : row)))
|
||||||
setRows((prev) => [...prev, createFilterRow(defaultHeaderId, headerOptions)])
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleRemoveRow = (id: string) => {
|
|
||||||
setRows((prev) => prev.filter((row) => row.id !== id))
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleChangeRow = (id: string, updater: (row: FilterRow) => FilterRow) => {
|
|
||||||
setRows((prev) => prev.map((row) => (row.id === id ? updater(row) : row)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const getHeaderOption = (headerId: number) => headerOptions.find((item) => item.id === headerId)
|
const getHeaderOption = (headerId: number) => headerOptions.find((item) => item.id === headerId)
|
||||||
@@ -108,6 +98,7 @@ const ListFilterDialog = ({
|
|||||||
rows
|
rows
|
||||||
.map((row) => {
|
.map((row) => {
|
||||||
if (isDisabledHeader(row.headerId)) return null
|
if (isDisabledHeader(row.headerId)) return null
|
||||||
|
if (row.operator === 'none') return null
|
||||||
if (row.operator === 'empty' || row.operator === 'notEmpty') return row
|
if (row.operator === 'empty' || row.operator === 'notEmpty') return row
|
||||||
if (isListValueHeader(row.headerId)) return row.multiValues.length > 0 ? row : null
|
if (isListValueHeader(row.headerId)) return row.multiValues.length > 0 ? row : null
|
||||||
return row.textValue.trim().length > 0 ? row : null
|
return row.textValue.trim().length > 0 ? row : null
|
||||||
@@ -117,13 +108,6 @@ const ListFilterDialog = ({
|
|||||||
)
|
)
|
||||||
|
|
||||||
const handleConfirm = async () => {
|
const handleConfirm = async () => {
|
||||||
// rows가 아예 없으면 "필터를 전부 지우겠다"는 의도이므로 그대로 통과시킨다.
|
|
||||||
// rows는 있는데 값을 안 채워 serializedRows가 비면, 실수로 방치된 조건일 가능성이 높아 알려준다.
|
|
||||||
if (rows.length > 0 && serializedRows.length === 0) {
|
|
||||||
alert('필터 조건을 입력해주세요.')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
setSubmitting(true)
|
setSubmitting(true)
|
||||||
try {
|
try {
|
||||||
await onConfirm(serializedRows)
|
await onConfirm(serializedRows)
|
||||||
@@ -151,61 +135,33 @@ const ListFilterDialog = ({
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<div className="overflow-hidden rounded-md border">
|
<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">
|
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr] items-center border-b bg-muted px-4 text-sm font-semibold">
|
||||||
<span>헤더</span>
|
<span>헤더</span>
|
||||||
<span>비교 연산자</span>
|
<span>비교 연산자</span>
|
||||||
<span>값</span>
|
<span>값</span>
|
||||||
<span />
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="max-h-80 overflow-auto">
|
<div className="max-h-170 overflow-auto">
|
||||||
{rows.map((row) => {
|
{rows.map((row) => {
|
||||||
const valueOptions = getValueOptions(row.headerId)
|
const valueOptions = getValueOptions(row.headerId)
|
||||||
const listMode = isListValueHeader(row.headerId)
|
const listMode = isListValueHeader(row.headerId)
|
||||||
const disabled = isDisabledHeader(row.headerId)
|
const disabled = isDisabledHeader(row.headerId)
|
||||||
const rowAllowedOperators = getAllowedOperators(row.headerId)
|
const rowAllowedOperators = getAllowedOperators(row.headerId)
|
||||||
const isEmptyOperator = row.operator === 'empty' || row.operator === 'notEmpty'
|
const isValuelessOperator = row.operator === 'empty' || row.operator === 'notEmpty' || row.operator === 'none'
|
||||||
|
const headerLabel = getHeaderOption(row.headerId)?.label ?? String(row.headerId)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={row.id}
|
key={row.headerId}
|
||||||
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"
|
className="grid min-h-12 grid-cols-[1fr_140px_1.4fr] items-center gap-2 border-b px-4 py-2 last:border-b-0"
|
||||||
>
|
>
|
||||||
<Select
|
<span className={disabled ? 'text-sm text-muted-foreground' : 'text-sm'}>{headerLabel}</span>
|
||||||
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
|
<Select
|
||||||
value={row.operator}
|
value={row.operator}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onValueChange={(value) =>
|
onValueChange={(value) =>
|
||||||
handleChangeRow(row.id, (current) => ({
|
handleChangeRow(row.headerId, (current) => ({
|
||||||
...current,
|
...current,
|
||||||
operator: value as FilterOperator,
|
operator: value as FilterOperator,
|
||||||
}))
|
}))
|
||||||
@@ -223,7 +179,7 @@ const ListFilterDialog = ({
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
|
||||||
{isEmptyOperator ? (
|
{isValuelessOperator ? (
|
||||||
<Input placeholder="값을 입력할 필요 없음" value="" disabled />
|
<Input placeholder="값을 입력할 필요 없음" value="" disabled />
|
||||||
) : listMode ? (
|
) : listMode ? (
|
||||||
<KriMultiSelect
|
<KriMultiSelect
|
||||||
@@ -231,7 +187,7 @@ const ListFilterDialog = ({
|
|||||||
value={row.multiValues}
|
value={row.multiValues}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onChange={(values) =>
|
onChange={(values) =>
|
||||||
handleChangeRow(row.id, (current) => ({
|
handleChangeRow(row.headerId, (current) => ({
|
||||||
...current,
|
...current,
|
||||||
multiValues: values,
|
multiValues: values,
|
||||||
}))
|
}))
|
||||||
@@ -252,36 +208,18 @@ const ListFilterDialog = ({
|
|||||||
value={row.textValue}
|
value={row.textValue}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
handleChangeRow(row.id, (current) => ({
|
handleChangeRow(row.headerId, (current) => ({
|
||||||
...current,
|
...current,
|
||||||
textValue: event.target.value,
|
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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2" disabled={defaultHeaderId <= 0}>
|
|
||||||
<Plus className="h-4 w-4" />
|
|
||||||
조건 추가
|
|
||||||
</Button>
|
|
||||||
</KriDialog>
|
</KriDialog>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,6 +49,8 @@ type ListHeaderRowProps = {
|
|||||||
onDelete: (id: number) => void
|
onDelete: (id: number) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const COMMON_GRADE_ORDER_START = 101
|
||||||
|
|
||||||
const isCommonGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.COMMON
|
const isCommonGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.COMMON
|
||||||
const isImmutableGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.IMMUTABLE
|
const isImmutableGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.IMMUTABLE
|
||||||
|
|
||||||
@@ -328,11 +330,12 @@ const ListHeaderManageDialog = ({
|
|||||||
|
|
||||||
setSubmitting(true)
|
setSubmitting(true)
|
||||||
try {
|
try {
|
||||||
const orderedRows = localRows.map((row, index) => ({
|
let defaultOrder = 0
|
||||||
...row,
|
let commonOrder = COMMON_GRADE_ORDER_START - 1
|
||||||
prjctIdx: row.prjctIdx ?? prjctIdx,
|
const orderedRows = localRows.map((row) => {
|
||||||
listHderOrder: index + 1,
|
const listHderOrder = isCommonGrade(row.listHderGrad) ? (commonOrder += 1) : (defaultOrder += 1)
|
||||||
}))
|
return { ...row, prjctIdx: row.prjctIdx ?? prjctIdx, listHderOrder }
|
||||||
|
})
|
||||||
await onConfirm(orderedRows)
|
await onConfirm(orderedRows)
|
||||||
handleOpenChange(false)
|
handleOpenChange(false)
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -1,91 +0,0 @@
|
|||||||
'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()): string | 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: string) => {
|
|
||||||
onSelectReservation(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
|
|
||||||
150
src/components/dialog/ReserveSearchDialog.tsx
Normal file
150
src/components/dialog/ReserveSearchDialog.tsx
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { formatKst } from '@kri/common'
|
||||||
|
import { KriDialog } from '@/components/common/KriDialog'
|
||||||
|
import { KriDateRangePicker, type KriDateRange } from '@/components/common/KriDateRangePicker'
|
||||||
|
import { useDialog } from '@/hooks/useDialog'
|
||||||
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
|
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||||
|
import { useCtiCallPhase } from '@/hooks/useCtiCallPhase'
|
||||||
|
import { CTI_CALL_PHASE } from '@/const/ctiConst'
|
||||||
|
import { useReserveSearchQuery } from '@/query/reserve'
|
||||||
|
import { nextApi } from '@/lib/http-client'
|
||||||
|
import { qk } from '@/query/key/keys'
|
||||||
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
|
import type { SelectedProject } from '@/store/jotai/project'
|
||||||
|
import type { ProjectInfo } from '@/types/project'
|
||||||
|
|
||||||
|
export type ReserveSearchDialogProps = {
|
||||||
|
dialogId?: DialogId
|
||||||
|
open?: boolean
|
||||||
|
onOpenChange?: (open: boolean) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const toDateInput = (date: Date) => {
|
||||||
|
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 todayRange = (): KriDateRange => {
|
||||||
|
const today = toDateInput(new Date())
|
||||||
|
return { from: today, to: today }
|
||||||
|
}
|
||||||
|
|
||||||
|
const ReserveSearchDialog = ({
|
||||||
|
dialogId = 'reserveSearchDialog',
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
}: ReserveSearchDialogProps) => {
|
||||||
|
const router = useRouter()
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||||
|
const { auth } = useAuth()
|
||||||
|
const { setSelectedProject } = useSelectedProject()
|
||||||
|
const ctiCallPhase = useCtiCallPhase()
|
||||||
|
const shouldBlockNavigation = CTI_CALL_PHASE.includes(ctiCallPhase)
|
||||||
|
|
||||||
|
const [range, setRange] = useState<KriDateRange>(todayRange)
|
||||||
|
const [navigatingSid, setNavigatingSid] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||||
|
const userId = auth.user?.userId ?? ''
|
||||||
|
const enabled = resolvedOpen && !!userId && !!range.from && !!range.to
|
||||||
|
|
||||||
|
const reserveSearchQuery = useReserveSearchQuery(userId, range.from, range.to, enabled)
|
||||||
|
const reservations = reserveSearchQuery.data ?? []
|
||||||
|
|
||||||
|
const handleOpenChange = (nextOpen: boolean) => {
|
||||||
|
onOpenChange?.(nextOpen)
|
||||||
|
if (nextOpen) {
|
||||||
|
showDialog(dialogId)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hideDialog(dialogId)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRowClick = async (prjctIdx: number, sid: string) => {
|
||||||
|
if (shouldBlockNavigation) {
|
||||||
|
alert('통화 중에는 이동할 수 없습니다.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setNavigatingSid(sid)
|
||||||
|
try {
|
||||||
|
const projectInfo = await queryClient.fetchQuery({
|
||||||
|
queryKey: qk.projectInfo(prjctIdx),
|
||||||
|
queryFn: () => nextApi.get<ProjectInfo>(`/project/info/${prjctIdx}`),
|
||||||
|
})
|
||||||
|
|
||||||
|
setSelectedProject({
|
||||||
|
prjctIdx: projectInfo.prjctIdx,
|
||||||
|
prjctCd: projectInfo.prjctCd,
|
||||||
|
prjctName: projectInfo.prjctName,
|
||||||
|
itrntPrjctCd: projectInfo.itrntPrjctCd,
|
||||||
|
ownerDept: projectInfo.ownerDept,
|
||||||
|
ownerFw: projectInfo.ownerFw,
|
||||||
|
ff: projectInfo.ff,
|
||||||
|
} as SelectedProject)
|
||||||
|
|
||||||
|
handleOpenChange(false)
|
||||||
|
router.push(`/list/contact?sid=${encodeURIComponent(sid)}`)
|
||||||
|
} finally {
|
||||||
|
setNavigatingSid(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<KriDialog
|
||||||
|
open={resolvedOpen}
|
||||||
|
onOpenChange={handleOpenChange}
|
||||||
|
title={<span className="text-xl">예약 내역 조회</span>}
|
||||||
|
contentClassName="sm:max-w-[860px]"
|
||||||
|
showDefaultFooter
|
||||||
|
>
|
||||||
|
<div className="space-y-3">
|
||||||
|
<KriDateRangePicker value={range} onChange={setRange} className="w-full" />
|
||||||
|
|
||||||
|
<div className="max-h-80 overflow-auto rounded-md border">
|
||||||
|
{reserveSearchQuery.isLoading ? (
|
||||||
|
<div className="p-6 text-center text-sm text-muted-foreground">불러오는 중...</div>
|
||||||
|
) : 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">프로젝트</th>
|
||||||
|
<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"
|
||||||
|
onClick={() => handleRowClick(item.prjctIdx, item.sid)}
|
||||||
|
>
|
||||||
|
<td className="p-2">{item.prjctName}</td>
|
||||||
|
<td className="p-2">{item.sid}</td>
|
||||||
|
<td className="p-2">
|
||||||
|
{formatKst(item.resveDt, 'dateHourMin')}
|
||||||
|
{navigatingSid === item.sid ? ' (이동 중...)' : ''}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</KriDialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ReserveSearchDialog
|
||||||
@@ -18,6 +18,7 @@ import { ChannelType, type TemplateSms, type TemplateSummary } from '@kri/common
|
|||||||
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
|
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
|
||||||
import { KriEditor } from '@/components/kri-editor'
|
import { KriEditor } from '@/components/kri-editor'
|
||||||
import { getNearestFutureDateTime } from '@/lib/datetime'
|
import { getNearestFutureDateTime } from '@/lib/datetime'
|
||||||
|
import { escapeHtml, substituteVariables } from '@/lib/variableSubstitution'
|
||||||
import type { DialogId } from '@/store/jotai/dialog'
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
import type { MessageSendChannel, TemplateEmailWithAttachments } from '@/types/message'
|
import type { MessageSendChannel, TemplateEmailWithAttachments } from '@/types/message'
|
||||||
import TemplateAttachmentList from '@/components/message-template/TemplateAttachmentList'
|
import TemplateAttachmentList from '@/components/message-template/TemplateAttachmentList'
|
||||||
@@ -36,6 +37,7 @@ export type SingleMessageSendDialogProps = {
|
|||||||
itrntPrjctCd: string
|
itrntPrjctCd: string
|
||||||
sid: string
|
sid: string
|
||||||
destHeaderId: number
|
destHeaderId: number
|
||||||
|
variableValues?: Record<string, string>
|
||||||
onSent?: () => void
|
onSent?: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,6 +50,7 @@ const SingleMessageSendDialog = ({
|
|||||||
itrntPrjctCd,
|
itrntPrjctCd,
|
||||||
sid,
|
sid,
|
||||||
destHeaderId,
|
destHeaderId,
|
||||||
|
variableValues,
|
||||||
onSent,
|
onSent,
|
||||||
}: SingleMessageSendDialogProps) => {
|
}: SingleMessageSendDialogProps) => {
|
||||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||||
@@ -68,6 +71,9 @@ const SingleMessageSendDialog = ({
|
|||||||
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
|
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
|
||||||
const mainTemplateIdx = mainTemplateQuery.data ?? null
|
const mainTemplateIdx = mainTemplateQuery.data ?? null
|
||||||
|
|
||||||
|
const previewValues = variableValues ?? {}
|
||||||
|
const resolvedTitle = selectedTemplate ? substituteVariables(selectedTemplate.tmplatTitle ?? '', previewValues) : ''
|
||||||
|
|
||||||
const sendSingleMutation = useSendSingleMessageMutation(channel, prjctIdx)
|
const sendSingleMutation = useSendSingleMessageMutation(channel, prjctIdx)
|
||||||
|
|
||||||
const mainTemplateAppliedRef = useRef(false)
|
const mainTemplateAppliedRef = useRef(false)
|
||||||
@@ -199,26 +205,33 @@ const SingleMessageSendDialog = ({
|
|||||||
{selectedTemplate && (
|
{selectedTemplate && (
|
||||||
<>
|
<>
|
||||||
{chnnlTy !== ChannelType.SMS && (
|
{chnnlTy !== ChannelType.SMS && (
|
||||||
<div className="rounded border p-2 text-sm font-semibold">{`제목: ${selectedTemplate.tmplatTitle}` || '(제목 없음)'}</div>
|
<div className="rounded border p-2 text-sm font-semibold">{resolvedTitle ? `제목: ${resolvedTitle}` : '(제목 없음)'}</div>
|
||||||
)}
|
)}
|
||||||
{chnnlTy === ChannelType.SMS ? (
|
{chnnlTy === ChannelType.SMS ? (
|
||||||
<div className="flex flex-col items-center">
|
<div className="flex flex-col items-center">
|
||||||
<KriEditor
|
<KriEditor
|
||||||
mode="sms"
|
mode="sms"
|
||||||
value={(selectedTemplate as TemplateSms).tmplatBody ?? ''}
|
value={substituteVariables((selectedTemplate as TemplateSms).tmplatBody ?? '', previewValues)}
|
||||||
onChange={() => {}}
|
onChange={() => {}}
|
||||||
isSmsReadOnly
|
isSmsReadOnly
|
||||||
placeholder="문자 내용을 입력해 주세요"
|
placeholder="문자 내용을 입력해 주세요"
|
||||||
className="max-w-80 mx-0"
|
className="max-w-80 mx-0"
|
||||||
debounceMs={600}
|
debounceMs={600}
|
||||||
smsTitle={(selectedTemplate as TemplateSms).tmplatTitle}
|
smsTitle={resolvedTitle}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<div
|
<div
|
||||||
className="rounded-md border bg-muted/30 p-3 text-sm"
|
className="rounded-md border bg-muted/30 p-3 text-sm"
|
||||||
dangerouslySetInnerHTML={{ __html: sanitizeHtmlForPreview(selectedTemplate.tmplatBody || '(내용 없음)') }}
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: sanitizeHtmlForPreview(
|
||||||
|
substituteVariables(
|
||||||
|
selectedTemplate.tmplatBody || '(내용 없음)',
|
||||||
|
Object.fromEntries(Object.entries(previewValues).map(([key, val]) => [key, escapeHtml(val)])),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
<TemplateAttachmentList
|
<TemplateAttachmentList
|
||||||
tmplatIdx={selectedTemplate.tmplatIdx}
|
tmplatIdx={selectedTemplate.tmplatIdx}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { compressImage } from './utils/imageCompression'
|
|||||||
import { useDebouncedChange } from './hooks/useDebouncedChange'
|
import { useDebouncedChange } from './hooks/useDebouncedChange'
|
||||||
import { sanitizeHtmlForPreview } from './utils/sanitizeHtml'
|
import { sanitizeHtmlForPreview } from './utils/sanitizeHtml'
|
||||||
import { preserveEmptyParagraphs } from './utils/emptyParagraph'
|
import { preserveEmptyParagraphs } from './utils/emptyParagraph'
|
||||||
|
import { formatHtmlSource } from './utils/formatHtml'
|
||||||
import { useTextareaInsert } from './hooks/useTextareaInsert'
|
import { useTextareaInsert } from './hooks/useTextareaInsert'
|
||||||
|
|
||||||
type HtmlOnlyProps = Omit<KriEditorProps, 'mode'> & { mode: 'html' }
|
type HtmlOnlyProps = Omit<KriEditorProps, 'mode'> & { mode: 'html' }
|
||||||
@@ -47,12 +48,31 @@ export function KriEditorHtmlOnly({
|
|||||||
else scheduleChange(next)
|
else scheduleChange(next)
|
||||||
}, [flushChange, scheduleChange])
|
}, [flushChange, scheduleChange])
|
||||||
|
|
||||||
|
// 사용자가 타이핑한 값이 아니라 외부에서 새로 세팅된 데이터일 때만(최초 마운트 포함)
|
||||||
|
// prettier로 포맷팅해서 반영한다 — 편집 중(commitHtml 경로)에는 절대 재포맷하지 않는다.
|
||||||
|
const applyExternalValue = React.useCallback((next: string) => {
|
||||||
|
setHtml(next)
|
||||||
|
latestHtmlRef.current = next
|
||||||
|
formatHtmlSource(next)
|
||||||
|
.then((formatted) => {
|
||||||
|
if (latestHtmlRef.current !== next) return // 그 사이 값이 또 바뀌었으면 건너뜀
|
||||||
|
setHtml(formatted)
|
||||||
|
latestHtmlRef.current = formatted
|
||||||
|
})
|
||||||
|
.catch(() => {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
applyExternalValue(value || '')
|
||||||
|
// 최초 마운트 시 1회만 실행 — 이후 value 변경은 아래 effect가 처리한다.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [])
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if ((value || '') !== latestHtmlRef.current) {
|
if ((value || '') !== latestHtmlRef.current) {
|
||||||
setHtml(value || '')
|
applyExternalValue(value || '')
|
||||||
latestHtmlRef.current = value || ''
|
|
||||||
}
|
}
|
||||||
}, [value])
|
}, [value, applyExternalValue])
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
onEditorReady?.(textareaRef.current)
|
onEditorReady?.(textareaRef.current)
|
||||||
@@ -122,7 +142,20 @@ export function KriEditorHtmlOnly({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const previewHtml = React.useMemo(() => sanitizeHtmlForPreview(preserveEmptyParagraphs(html)), [html])
|
const handleFormatHtml = React.useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const formatted = await formatHtmlSource(latestHtmlRef.current)
|
||||||
|
commitHtml(formatted)
|
||||||
|
} catch (error) {
|
||||||
|
toast.error('HTML 정렬에 실패했습니다.')
|
||||||
|
console.error(error)
|
||||||
|
}
|
||||||
|
}, [commitHtml])
|
||||||
|
|
||||||
|
const previewHtml = React.useMemo(
|
||||||
|
() => sanitizeHtmlForPreview(preserveEmptyParagraphs(html)),
|
||||||
|
[html],
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn('rounded-md border bg-background', className)}>
|
<div className={cn('rounded-md border bg-background', className)}>
|
||||||
@@ -130,11 +163,16 @@ export function KriEditorHtmlOnly({
|
|||||||
<div className="flex flex-col gap-2 px-3 py-2">
|
<div className="flex flex-col gap-2 px-3 py-2">
|
||||||
<div className="text-muted-foreground flex items-center justify-between text-xs">
|
<div className="text-muted-foreground flex items-center justify-between text-xs">
|
||||||
<span>HTML 모드</span>
|
<span>HTML 모드</span>
|
||||||
{onImageUpload ? (
|
<div className="flex items-center gap-2">
|
||||||
<button type="button" onClick={() => fileRef.current?.click()} className="rounded border px-2 py-1 hover:bg-muted">
|
<button type="button" onClick={handleFormatHtml} className="rounded border px-2 py-1 hover:bg-muted">
|
||||||
이미지 업로드
|
정렬
|
||||||
</button>
|
</button>
|
||||||
) : null}
|
{onImageUpload ? (
|
||||||
|
<button type="button" onClick={() => fileRef.current?.click()} className="rounded border px-2 py-1 hover:bg-muted">
|
||||||
|
이미지 업로드
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<textarea
|
<textarea
|
||||||
ref={textareaRef}
|
ref={textareaRef}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { EditorContent, useEditor, type Editor } from "@tiptap/react";
|
|||||||
import StarterKit from "@tiptap/starter-kit";
|
import StarterKit from "@tiptap/starter-kit";
|
||||||
import Underline from "@tiptap/extension-underline";
|
import Underline from "@tiptap/extension-underline";
|
||||||
import { TextStyle } from "@tiptap/extension-text-style";
|
import { TextStyle } from "@tiptap/extension-text-style";
|
||||||
|
import FontFamily from "@tiptap/extension-font-family";
|
||||||
import Color from "@tiptap/extension-color";
|
import Color from "@tiptap/extension-color";
|
||||||
import Highlight from "@tiptap/extension-highlight";
|
import Highlight from "@tiptap/extension-highlight";
|
||||||
import TiptapImage from "@tiptap/extension-image";
|
import TiptapImage from "@tiptap/extension-image";
|
||||||
@@ -27,6 +28,8 @@ import { Div } from "./extensions/div";
|
|||||||
import { compressImage } from "./utils/imageCompression";
|
import { compressImage } from "./utils/imageCompression";
|
||||||
import { sanitizeHtml } from "./utils/sanitizeHtml";
|
import { sanitizeHtml } from "./utils/sanitizeHtml";
|
||||||
import { preserveEmptyParagraphs } from "./utils/emptyParagraph";
|
import { preserveEmptyParagraphs } from "./utils/emptyParagraph";
|
||||||
|
import { DEFAULT_FONT_FAMILY_OPTIONS } from "./utils/fontFamilyOptions";
|
||||||
|
import { formatHtmlSource } from "./utils/formatHtml";
|
||||||
import { applyLinkPreviewClass, KRI_EDITOR_LINK_CLASS } from "./utils/linkPreview";
|
import { applyLinkPreviewClass, KRI_EDITOR_LINK_CLASS } from "./utils/linkPreview";
|
||||||
import { Toolbar } from "./toolbar/Toolbar";
|
import { Toolbar } from "./toolbar/Toolbar";
|
||||||
import { useDebouncedChange } from "./hooks/useDebouncedChange";
|
import { useDebouncedChange } from "./hooks/useDebouncedChange";
|
||||||
@@ -35,9 +38,10 @@ import { useTextareaInsert } from "./hooks/useTextareaInsert";
|
|||||||
type ViewMode = "wysiwyg" | "html";
|
type ViewMode = "wysiwyg" | "html";
|
||||||
|
|
||||||
function getToolbarState(editor: Editor): ToolbarState {
|
function getToolbarState(editor: Editor): ToolbarState {
|
||||||
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; color?: string | null };
|
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; fontFamily?: string | null; color?: string | null };
|
||||||
const hl = editor.getAttributes("highlight") as { color?: string | null };
|
const hl = editor.getAttributes("highlight") as { color?: string | null };
|
||||||
|
|
||||||
|
const fontFamily = (ts?.fontFamily ?? null) as string | null;
|
||||||
const fontSize = (ts?.fontSize ?? "16px") as string;
|
const fontSize = (ts?.fontSize ?? "16px") as string;
|
||||||
const textColor = (ts?.color ?? null) as string | null;
|
const textColor = (ts?.color ?? null) as string | null;
|
||||||
const highlightColor = (hl?.color ?? null) as string | null;
|
const highlightColor = (hl?.color ?? null) as string | null;
|
||||||
@@ -48,6 +52,7 @@ function getToolbarState(editor: Editor): ToolbarState {
|
|||||||
"left";
|
"left";
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
fontFamily,
|
||||||
fontSize,
|
fontSize,
|
||||||
textColor,
|
textColor,
|
||||||
highlightColor,
|
highlightColor,
|
||||||
@@ -89,6 +94,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
allowBase64 = false,
|
allowBase64 = false,
|
||||||
sanitizeHtml: sanitizeHtmlOpt = true,
|
sanitizeHtml: sanitizeHtmlOpt = true,
|
||||||
toolbar = {},
|
toolbar = {},
|
||||||
|
fontFamilyOptions = DEFAULT_FONT_FAMILY_OPTIONS,
|
||||||
editorExtensions = [],
|
editorExtensions = [],
|
||||||
allowedCustomHtml,
|
allowedCustomHtml,
|
||||||
transformPreviewHtml,
|
transformPreviewHtml,
|
||||||
@@ -122,6 +128,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
const selectionRef = useRef<{ from: number; to: number } | null>(null);
|
const selectionRef = useRef<{ from: number; to: number } | null>(null);
|
||||||
|
|
||||||
const [tb, setTb] = useState<ToolbarState>({
|
const [tb, setTb] = useState<ToolbarState>({
|
||||||
|
fontFamily: null,
|
||||||
fontSize: "16px",
|
fontSize: "16px",
|
||||||
textColor: null,
|
textColor: null,
|
||||||
highlightColor: null,
|
highlightColor: null,
|
||||||
@@ -150,6 +157,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
Underline,
|
Underline,
|
||||||
TextStyle,
|
TextStyle,
|
||||||
FontSize,
|
FontSize,
|
||||||
|
FontFamily,
|
||||||
Color,
|
Color,
|
||||||
Highlight.configure({ multicolor: true }),
|
Highlight.configure({ multicolor: true }),
|
||||||
Div,
|
Div,
|
||||||
@@ -276,6 +284,19 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
[editor, restoreSelection]
|
[editor, restoreSelection]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const setFontFamily = useCallback(
|
||||||
|
(value: string) => {
|
||||||
|
if (!editor) return;
|
||||||
|
restoreSelection();
|
||||||
|
if (!value) {
|
||||||
|
editor.chain().focus().unsetFontFamily().run();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
editor.chain().focus().setFontFamily(value).run();
|
||||||
|
},
|
||||||
|
[editor, restoreSelection]
|
||||||
|
);
|
||||||
|
|
||||||
const setTextColor = useCallback(
|
const setTextColor = useCallback(
|
||||||
(hex: string) => {
|
(hex: string) => {
|
||||||
if (!editor) return;
|
if (!editor) return;
|
||||||
@@ -436,8 +457,20 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
if (!editor) return;
|
if (!editor) return;
|
||||||
|
|
||||||
if (viewRef.current === "wysiwyg") {
|
if (viewRef.current === "wysiwyg") {
|
||||||
htmlDraftRef.current = editor.getHTML();
|
const raw = editor.getHTML();
|
||||||
|
htmlDraftRef.current = raw;
|
||||||
setView("html");
|
setView("html");
|
||||||
|
|
||||||
|
// WYSIWYG에서 막 넘어온, 사용자가 직접 타이핑하지 않은 HTML이므로
|
||||||
|
// 화면 표시용으로만 정렬한다(onChange는 호출하지 않음 — 저장값은 그대로 유지).
|
||||||
|
formatHtmlSource(raw)
|
||||||
|
.then((formatted) => {
|
||||||
|
if (viewRef.current !== "html" || htmlDraftRef.current !== raw) return;
|
||||||
|
htmlDraftRef.current = formatted;
|
||||||
|
if (htmlTextareaRef.current) htmlTextareaRef.current.value = formatted;
|
||||||
|
setPreviewSource(formatted);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -449,6 +482,19 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
setView("wysiwyg");
|
setView("wysiwyg");
|
||||||
}, [allowedCustomHtml, editor, flushChange, sanitizeHtmlOpt]);
|
}, [allowedCustomHtml, editor, flushChange, sanitizeHtmlOpt]);
|
||||||
|
|
||||||
|
const formatHtmlView = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const formatted = await formatHtmlSource(htmlDraftRef.current);
|
||||||
|
htmlDraftRef.current = formatted;
|
||||||
|
if (htmlTextareaRef.current) htmlTextareaRef.current.value = formatted;
|
||||||
|
setPreviewSource(formatted);
|
||||||
|
scheduleChange(preserveEmptyParagraphs(formatted));
|
||||||
|
} catch (err) {
|
||||||
|
toast.error("HTML 정렬에 실패했습니다.");
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
}, [scheduleChange]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!editor) return;
|
if (!editor) return;
|
||||||
|
|
||||||
@@ -595,6 +641,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
showHtmlToggle={showHtmlToggle}
|
showHtmlToggle={showHtmlToggle}
|
||||||
isHtmlView={view === "html"}
|
isHtmlView={view === "html"}
|
||||||
onToggleHtmlView={onToggleHtmlView}
|
onToggleHtmlView={onToggleHtmlView}
|
||||||
|
onFormatHtml={formatHtmlView}
|
||||||
|
fontFamilyOptions={fontFamilyOptions}
|
||||||
|
onSetFontFamily={setFontFamily}
|
||||||
onSetFontSize={setFontSize}
|
onSetFontSize={setFontSize}
|
||||||
onSetTextColor={setTextColor}
|
onSetTextColor={setTextColor}
|
||||||
onUnsetTextColor={unsetTextColor}
|
onUnsetTextColor={unsetTextColor}
|
||||||
@@ -639,7 +688,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
<div className={cn("border-t p-3", previewClassName)}>
|
<div className={cn("border-t p-3", previewClassName)}>
|
||||||
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
||||||
<div className="rounded-md border bg-muted/30 p-3">
|
<div className="rounded-md border bg-muted/30 p-3">
|
||||||
<div className="kri-editor-preview" dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
|
|||||||
export { KriEditorSms } from './KriEditorSms'
|
export { KriEditorSms } from './KriEditorSms'
|
||||||
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
|
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
|
||||||
export { ToolbarButton as KriEditorToolbarButton } from './toolbar/ToolbarButton'
|
export { ToolbarButton as KriEditorToolbarButton } from './toolbar/ToolbarButton'
|
||||||
|
export { DEFAULT_FONT_FAMILY_OPTIONS } from './utils/fontFamilyOptions'
|
||||||
export type {
|
export type {
|
||||||
KriEditorAllowedHtml,
|
KriEditorAllowedHtml,
|
||||||
KriEditorCommand,
|
KriEditorCommand,
|
||||||
|
KriEditorFontFamilyOption,
|
||||||
KriEditorMode,
|
KriEditorMode,
|
||||||
KriEditorProps,
|
KriEditorProps,
|
||||||
KriEditorToolbarConfig,
|
KriEditorToolbarConfig,
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
Code2,
|
Code2,
|
||||||
Highlighter,
|
Highlighter,
|
||||||
Image as ImageIcon,
|
Image as ImageIcon,
|
||||||
|
IndentIncrease,
|
||||||
Italic,
|
Italic,
|
||||||
Link2,
|
Link2,
|
||||||
List,
|
List,
|
||||||
@@ -25,7 +26,7 @@ import { Input } from '@/components/ui/input'
|
|||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||||
import { Separator } from '@/components/ui/separator'
|
import { Separator } from '@/components/ui/separator'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import type { KriEditorToolbarConfig, KriEditorToolbarFeature, ToolbarState } from '../types'
|
import type { KriEditorFontFamilyOption, KriEditorToolbarConfig, KriEditorToolbarFeature, ToolbarState } from '../types'
|
||||||
import { ToolbarButton } from './ToolbarButton'
|
import { ToolbarButton } from './ToolbarButton'
|
||||||
|
|
||||||
interface ToolbarProps {
|
interface ToolbarProps {
|
||||||
@@ -38,6 +39,9 @@ interface ToolbarProps {
|
|||||||
showHtmlToggle: boolean
|
showHtmlToggle: boolean
|
||||||
isHtmlView: boolean
|
isHtmlView: boolean
|
||||||
onToggleHtmlView: () => void
|
onToggleHtmlView: () => void
|
||||||
|
onFormatHtml: () => void
|
||||||
|
fontFamilyOptions: KriEditorFontFamilyOption[]
|
||||||
|
onSetFontFamily: (value: string) => void
|
||||||
onSetFontSize: (value: string) => void
|
onSetFontSize: (value: string) => void
|
||||||
onSetTextColor: (value: string) => void
|
onSetTextColor: (value: string) => void
|
||||||
onUnsetTextColor: () => void
|
onUnsetTextColor: () => void
|
||||||
@@ -74,6 +78,9 @@ export function Toolbar({
|
|||||||
showHtmlToggle,
|
showHtmlToggle,
|
||||||
isHtmlView,
|
isHtmlView,
|
||||||
onToggleHtmlView,
|
onToggleHtmlView,
|
||||||
|
onFormatHtml,
|
||||||
|
fontFamilyOptions,
|
||||||
|
onSetFontFamily,
|
||||||
onSetFontSize,
|
onSetFontSize,
|
||||||
onSetTextColor,
|
onSetTextColor,
|
||||||
onUnsetTextColor,
|
onUnsetTextColor,
|
||||||
@@ -89,6 +96,7 @@ export function Toolbar({
|
|||||||
customContent,
|
customContent,
|
||||||
}: ToolbarProps) {
|
}: ToolbarProps) {
|
||||||
const enabled = (feature: KriEditorToolbarFeature) => config?.[feature] !== false
|
const enabled = (feature: KriEditorToolbarFeature) => config?.[feature] !== false
|
||||||
|
const showFontControls = enabled('fontFamily') || enabled('fontSize')
|
||||||
const showTextStyle = enabled('bold') || enabled('italic') || enabled('underline') || enabled('strike')
|
const showTextStyle = enabled('bold') || enabled('italic') || enabled('underline') || enabled('strike')
|
||||||
const showColors = enabled('textColor') || enabled('highlight')
|
const showColors = enabled('textColor') || enabled('highlight')
|
||||||
const showLists = enabled('bulletList') || enabled('orderedList')
|
const showLists = enabled('bulletList') || enabled('orderedList')
|
||||||
@@ -108,6 +116,19 @@ export function Toolbar({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn('flex items-center gap-1 overflow-x-auto whitespace-nowrap px-2 py-1', className)}>
|
<div className={cn('flex items-center gap-1 overflow-x-auto whitespace-nowrap px-2 py-1', className)}>
|
||||||
|
{enabled('fontFamily') ? (
|
||||||
|
<select
|
||||||
|
className="h-8 w-[150px] rounded-md border bg-background px-2 text-sm"
|
||||||
|
value={state.fontFamily ?? ''}
|
||||||
|
onChange={(event) => onSetFontFamily(event.target.value)}
|
||||||
|
title="글꼴"
|
||||||
|
>
|
||||||
|
{fontFamilyOptions.map((option) => (
|
||||||
|
<option key={option.value} value={option.value}>{option.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{enabled('fontSize') ? (
|
{enabled('fontSize') ? (
|
||||||
<select
|
<select
|
||||||
className="h-8 w-[72px] rounded-md border bg-background px-2 text-sm"
|
className="h-8 w-[72px] rounded-md border bg-background px-2 text-sm"
|
||||||
@@ -121,7 +142,7 @@ export function Toolbar({
|
|||||||
</select>
|
</select>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{enabled('fontSize') && showTextStyle ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
{showFontControls && showTextStyle ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||||
|
|
||||||
{enabled('bold') ? (
|
{enabled('bold') ? (
|
||||||
<ToolbarButton active={state.isBold} disabled={!editor.can().chain().focus().toggleBold().run()} onClick={() => editor.chain().focus().toggleBold().run()} title="굵게">
|
<ToolbarButton active={state.isBold} disabled={!editor.can().chain().focus().toggleBold().run()} onClick={() => editor.chain().focus().toggleBold().run()} title="굵게">
|
||||||
@@ -278,6 +299,9 @@ export function Toolbar({
|
|||||||
<>
|
<>
|
||||||
<Separator orientation="vertical" className="mx-1 h-6" />
|
<Separator orientation="vertical" className="mx-1 h-6" />
|
||||||
<ToolbarButton active={isHtmlView} title={isHtmlView ? 'WYSIWYG로 전환' : 'HTML 편집'} onClick={onToggleHtmlView}><Code2 className="size-4" /></ToolbarButton>
|
<ToolbarButton active={isHtmlView} title={isHtmlView ? 'WYSIWYG로 전환' : 'HTML 편집'} onClick={onToggleHtmlView}><Code2 className="size-4" /></ToolbarButton>
|
||||||
|
{isHtmlView ? (
|
||||||
|
<ToolbarButton title="HTML 정렬" onClick={onFormatHtml}><IndentIncrease className="size-4" /></ToolbarButton>
|
||||||
|
) : null}
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
{customContent ? (
|
{customContent ? (
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms'
|
|||||||
export type KriEditorUploadResult = string | { url: string }
|
export type KriEditorUploadResult = string | { url: string }
|
||||||
|
|
||||||
export type KriEditorToolbarFeature =
|
export type KriEditorToolbarFeature =
|
||||||
|
| 'fontFamily'
|
||||||
| 'fontSize'
|
| 'fontSize'
|
||||||
| 'bold'
|
| 'bold'
|
||||||
| 'italic'
|
| 'italic'
|
||||||
@@ -39,6 +40,11 @@ export type KriEditorAllowedHtml = {
|
|||||||
attributes?: string[]
|
attributes?: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type KriEditorFontFamilyOption = {
|
||||||
|
label: string
|
||||||
|
value: string
|
||||||
|
}
|
||||||
|
|
||||||
export type KriEditorProps = {
|
export type KriEditorProps = {
|
||||||
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
|
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
|
||||||
onCommandReady?: (command: KriEditorCommand | null) => void
|
onCommandReady?: (command: KriEditorCommand | null) => void
|
||||||
@@ -69,14 +75,15 @@ export type KriEditorProps = {
|
|||||||
smsMaxBytes?: number
|
smsMaxBytes?: number
|
||||||
lmsMaxBytes?: number
|
lmsMaxBytes?: number
|
||||||
toolbar?: KriEditorToolbarConfig | false
|
toolbar?: KriEditorToolbarConfig | false
|
||||||
|
fontFamilyOptions?: KriEditorFontFamilyOption[]
|
||||||
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
|
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
|
||||||
editorExtensions?: Extensions
|
editorExtensions?: Extensions
|
||||||
allowedCustomHtml?: KriEditorAllowedHtml
|
allowedCustomHtml?: KriEditorAllowedHtml
|
||||||
/** 미리보기 패널에 표시할 HTML을 sanitize 이후 추가로 가공하고 싶을 때 사용 (예: 커스텀 태그를 대체 이미지로 치환) */
|
|
||||||
transformPreviewHtml?: (html: string) => string
|
transformPreviewHtml?: (html: string) => string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ToolbarState = {
|
export type ToolbarState = {
|
||||||
|
fontFamily: string | null
|
||||||
fontSize: string
|
fontSize: string
|
||||||
textColor: string | null
|
textColor: string | null
|
||||||
highlightColor: string | null
|
highlightColor: string | null
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
const EMPTY_PARAGRAPH_PATTERN = /<p((?:\s+[^>]*)?)>\s*<\/p>/gi;
|
const EMPTY_PARAGRAPH_PATTERN = /<p((?:\s+[^>]*)?)>\s*<\/p>/gi;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 내용이 전혀 없는 <p></p>는 CSS margin이 collapse되어 이메일 클라이언트 등
|
* TipTap이 빈 줄을 <p></p>로 직렬화하면 이메일 클라이언트에서 margin collapse로 사라진다.
|
||||||
* 우리 앱 밖에서는 높이 0으로 붙어버린다. 를 채워 실제 콘텐츠로 줄 높이를 보장한다.
|
* 눈에 보이지 않는 콘텐츠( )를 채워 실제 발송 HTML에서도 빈 줄이 유지되게 한다.
|
||||||
*/
|
*/
|
||||||
export function preserveEmptyParagraphs(html: string): string {
|
export function preserveEmptyParagraphs(html: string): string {
|
||||||
return html.replace(EMPTY_PARAGRAPH_PATTERN, (_match, attrs: string) => `<p${attrs}> </p>`);
|
return html.replace(EMPTY_PARAGRAPH_PATTERN, (_match, attrs: string) => `<p${attrs}> </p>`);
|
||||||
|
|||||||
29
src/components/kri-editor/utils/fontFamilyOptions.ts
Normal file
29
src/components/kri-editor/utils/fontFamilyOptions.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import type { KriEditorFontFamilyOption } from "../types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OS/이메일 클라이언트에 기본 설치돼 있어 별도 @font-face 로딩 없이 바로 렌더링되는 웹 세이프 폰트 목록.
|
||||||
|
* "자동"은 fontFamily 속성을 제거(unset)해 상위 스타일을 상속한다.
|
||||||
|
*/
|
||||||
|
export const DEFAULT_FONT_FAMILY_OPTIONS: KriEditorFontFamilyOption[] = [
|
||||||
|
{ label: "없음", value: "" },
|
||||||
|
{ label: "맑은 고딕", value: "'Malgun Gothic', sans-serif" },
|
||||||
|
{ label: "돋움", value: "Dotum, sans-serif" },
|
||||||
|
{ label: "굴림", value: "Gulim, sans-serif" },
|
||||||
|
{ label: "바탕", value: "Batang, serif" },
|
||||||
|
{ label: "궁서", value: "Gungsuh, serif" },
|
||||||
|
{ label: "Apple SD 고딕", value: "'Apple SD Gothic Neo', sans-serif" },
|
||||||
|
{ label: "Arial", value: "Arial, Helvetica, sans-serif" },
|
||||||
|
{ label: "Helvetica", value: "Helvetica, Arial, sans-serif" },
|
||||||
|
{ label: "Verdana", value: "Verdana, Geneva, sans-serif" },
|
||||||
|
{ label: "Tahoma", value: "Tahoma, Geneva, sans-serif" },
|
||||||
|
{ label: "Trebuchet MS", value: "'Trebuchet MS', Helvetica, sans-serif" },
|
||||||
|
{ label: "Century Gothic", value: "'Century Gothic', sans-serif" },
|
||||||
|
{ label: "Georgia", value: "Georgia, 'Times New Roman', serif" },
|
||||||
|
{ label: "Times New Roman", value: "'Times New Roman', Times, serif" },
|
||||||
|
{ label: "Palatino Linotype", value: "'Palatino Linotype', 'Book Antiqua', Palatino, serif" },
|
||||||
|
{ label: "Garamond", value: "Garamond, serif" },
|
||||||
|
{ label: "Courier New", value: "'Courier New', Courier, monospace" },
|
||||||
|
{ label: "Lucida Console", value: "'Lucida Console', Monaco, monospace" },
|
||||||
|
{ label: "Comic Sans MS", value: "'Comic Sans MS', cursive" },
|
||||||
|
{ label: "Impact", value: "Impact, Charcoal, sans-serif" },
|
||||||
|
];
|
||||||
16
src/components/kri-editor/utils/formatHtml.ts
Normal file
16
src/components/kri-editor/utils/formatHtml.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
export async function formatHtmlSource(html: string): Promise<string> {
|
||||||
|
if (!html.trim()) return html;
|
||||||
|
|
||||||
|
const [{ format }, htmlPlugin] = await Promise.all([
|
||||||
|
import("prettier/standalone"),
|
||||||
|
import("prettier/plugins/html"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return format(html, {
|
||||||
|
parser: "html",
|
||||||
|
plugins: [htmlPlugin],
|
||||||
|
printWidth: 100,
|
||||||
|
// 인라인 요소(span/a/mark 등) 사이 공백은 실제 렌더링에 영향을 주므로 보존한다.
|
||||||
|
htmlWhitespaceSensitivity: "css",
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,12 +1,21 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import DOMPurify from "dompurify";
|
import DOMPurify, { type DOMPurify as DOMPurifyInstance } from "dompurify";
|
||||||
|
|
||||||
export type SanitizeHtmlOptions = {
|
export type SanitizeHtmlOptions = {
|
||||||
tags?: string[];
|
tags?: string[];
|
||||||
attributes?: string[];
|
attributes?: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Next.js SSR(Node) 환경에서는 dompurify가 window에 바인딩된 인스턴스가 아니라
|
||||||
|
// (window: Window) => DOMPurify 형태의 factory만 노출한다. window가 없으면
|
||||||
|
// factory를 호출할 방법이 없으므로, 여기서 안전하게 null로 폴백한다.
|
||||||
|
function resolvePurifier(): DOMPurifyInstance | null {
|
||||||
|
if (typeof window === "undefined") return null;
|
||||||
|
if (typeof DOMPurify.sanitize === "function") return DOMPurify;
|
||||||
|
return DOMPurify(window);
|
||||||
|
}
|
||||||
|
|
||||||
export function sanitizeHtml(
|
export function sanitizeHtml(
|
||||||
input: string,
|
input: string,
|
||||||
options?: SanitizeHtmlOptions,
|
options?: SanitizeHtmlOptions,
|
||||||
@@ -15,14 +24,16 @@ export function sanitizeHtml(
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
// DOMPurify는 window/document가 있어야 동작한다. Next.js는 "use client" 컴포넌트도
|
const purifier = resolvePurifier();
|
||||||
// 최초 HTML을 만들 때 서버에서 한 번 실행하므로, SSR 단계에서는 sanitize를 건너뛴다.
|
|
||||||
// (이 값은 하이드레이션 후 클라이언트에서 다시 렌더링되며 정상적으로 sanitize된다.)
|
if (!purifier) {
|
||||||
if (typeof window === "undefined") {
|
// DOM이 없어 실제 sanitize를 수행할 수 없는 환경(SSR 등)에서는
|
||||||
return input;
|
// 검증되지 않은 HTML을 그대로 노출하지 않도록 태그를 모두 제거한 텍스트만 반환한다.
|
||||||
|
// 브라우저에서 하이드레이션된 이후 재계산될 때 실제 sanitize 결과로 대체된다.
|
||||||
|
return input.replace(/<[^>]*>/g, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
return DOMPurify.sanitize(
|
return purifier.sanitize(
|
||||||
input,
|
input,
|
||||||
{
|
{
|
||||||
USE_PROFILES: {
|
USE_PROFILES: {
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { RefreshCw } from 'lucide-react'
|
import { RefreshCw, Trash2 } from 'lucide-react'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||||
import { KriDateTimePicker } from '@/components/common/KriDateTimePicker'
|
import { KriDateTimePicker } from '@/components/common/KriDateTimePicker'
|
||||||
import CollapsibleHistorySection from '@/components/list-contact/CollapsibleHistorySection'
|
import CollapsibleHistorySection from '@/components/list-contact/CollapsibleHistorySection'
|
||||||
import { useAddListEventMutation, useListEventHistoryQuery, useReserveMutation } from '@/query/list'
|
import { useAddListEventMutation, useDeleteListEventMutation, useListEventHistoryQuery, useReserveMutation } from '@/query/list'
|
||||||
import { useSendResultBySidQuery } from '@/query/message'
|
import { useSendResultBySidQuery } from '@/query/message'
|
||||||
import { useInternalInfoQuery } from '@/query/internal'
|
import { useInternalInfoQuery } from '@/query/internal'
|
||||||
import { clientEnv } from '@/lib/env.client'
|
import { clientEnv } from '@/lib/env.client'
|
||||||
@@ -22,21 +22,9 @@ import { useCtiLastCallHistId } from '@/hooks/useCtiLastCallHistId'
|
|||||||
import { getCurrentPositionMeta } from '@kri/common/browser'
|
import { getCurrentPositionMeta } from '@kri/common/browser'
|
||||||
import type { listHeader, ListSearchWithFullResult } from '@/types/list'
|
import type { listHeader, ListSearchWithFullResult } from '@/types/list'
|
||||||
import { buildListContactVariableValues } from '@/components/list-contact/listContactVariables'
|
import { buildListContactVariableValues } from '@/components/list-contact/listContactVariables'
|
||||||
import { substituteVariables } from '@/lib/surveyUrl'
|
import { escapeHtml, substituteVariables } from '@/lib/variableSubstitution'
|
||||||
import { sanitizeHtml } from '@/components/kri-editor/utils/sanitizeHtml'
|
import { sanitizeHtml } from '@/components/kri-editor/utils/sanitizeHtml'
|
||||||
|
import { isInternalManager } from '@/utils/userRole'
|
||||||
const escapeHtml = (value: string) =>
|
|
||||||
value.replace(
|
|
||||||
/[&<>"']/g,
|
|
||||||
(character) =>
|
|
||||||
({
|
|
||||||
'&': '&',
|
|
||||||
'<': '<',
|
|
||||||
'>': '>',
|
|
||||||
'"': '"',
|
|
||||||
"'": ''',
|
|
||||||
})[character] ?? character,
|
|
||||||
)
|
|
||||||
|
|
||||||
const RefreshIconButton = ({ onRefresh, isFetching }: { onRefresh: () => void; isFetching: boolean }) => (
|
const RefreshIconButton = ({ onRefresh, isFetching }: { onRefresh: () => void; isFetching: boolean }) => (
|
||||||
<Button
|
<Button
|
||||||
@@ -64,6 +52,7 @@ type ContactEventSectionProps = {
|
|||||||
showInput?: boolean
|
showInput?: boolean
|
||||||
submitting: boolean
|
submitting: boolean
|
||||||
onSubmit: (resultCd: number, memo: string, resveDt: string, listCallHistIdx: number | null) => Promise<void>
|
onSubmit: (resultCd: number, memo: string, resveDt: string, listCallHistIdx: number | null) => Promise<void>
|
||||||
|
canDelete: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const EventHistoryList = ({
|
const EventHistoryList = ({
|
||||||
@@ -71,11 +60,17 @@ const EventHistoryList = ({
|
|||||||
history,
|
history,
|
||||||
resultCodeType,
|
resultCodeType,
|
||||||
resultCodes,
|
resultCodes,
|
||||||
|
canDelete = false,
|
||||||
|
onDelete,
|
||||||
|
isDeleting = false,
|
||||||
}: {
|
}: {
|
||||||
isLoading: boolean
|
isLoading: boolean
|
||||||
history: ReturnType<typeof useListEventHistoryQuery>['data']
|
history: ReturnType<typeof useListEventHistoryQuery>['data']
|
||||||
resultCodeType: ResultCodeType
|
resultCodeType: ResultCodeType
|
||||||
resultCodes: ResultCode[]
|
resultCodes: ResultCode[]
|
||||||
|
canDelete?: boolean
|
||||||
|
onDelete?: (listEventHistIdx: number) => void
|
||||||
|
isDeleting?: boolean
|
||||||
}) => {
|
}) => {
|
||||||
const filteredHistory = (history ?? [])
|
const filteredHistory = (history ?? [])
|
||||||
.filter((item) => item.eventTy === resultCodeType)
|
.filter((item) => item.eventTy === resultCodeType)
|
||||||
@@ -85,6 +80,11 @@ const EventHistoryList = ({
|
|||||||
resultCodes.find((code) => code.resultCdTy === resultCodeType && code.resultCd === resultCd)?.resultCdLbl ??
|
resultCodes.find((code) => code.resultCdTy === resultCodeType && code.resultCd === resultCd)?.resultCdLbl ??
|
||||||
String(resultCd)
|
String(resultCd)
|
||||||
|
|
||||||
|
const handleDelete = (listEventHistIdx: number) => {
|
||||||
|
if (!confirm('이력을 삭제하시겠습니까?')) return
|
||||||
|
onDelete?.(listEventHistIdx)
|
||||||
|
}
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
|
return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
|
||||||
}
|
}
|
||||||
@@ -102,6 +102,7 @@ const EventHistoryList = ({
|
|||||||
<th className="p-2 text-left">메모</th>
|
<th className="p-2 text-left">메모</th>
|
||||||
<th className="p-2 text-left">등록자</th>
|
<th className="p-2 text-left">등록자</th>
|
||||||
<th className="p-2 text-left">일시</th>
|
<th className="p-2 text-left">일시</th>
|
||||||
|
{canDelete ? <th className="p-2 text-left">삭제</th> : null}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@@ -113,6 +114,20 @@ const EventHistoryList = ({
|
|||||||
<td className="p-2">{item.memo || '-'}</td>
|
<td className="p-2">{item.memo || '-'}</td>
|
||||||
<td className="p-2">{item.regUser}</td>
|
<td className="p-2">{item.regUser}</td>
|
||||||
<td className="p-2">{formatKst(item.regDt, 'dateHourMin')}</td>
|
<td className="p-2">{formatKst(item.regDt, 'dateHourMin')}</td>
|
||||||
|
{canDelete ? (
|
||||||
|
<td className="p-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon-sm"
|
||||||
|
aria-label="이력 삭제"
|
||||||
|
disabled={isDeleting}
|
||||||
|
onClick={() => handleDelete(item.listEventHistIdx)}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</td>
|
||||||
|
) : null}
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -131,6 +146,7 @@ const ContactEventSection = ({
|
|||||||
showInput = true,
|
showInput = true,
|
||||||
submitting,
|
submitting,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
|
canDelete,
|
||||||
}: ContactEventSectionProps) => {
|
}: ContactEventSectionProps) => {
|
||||||
const [resultCd, setResultCd] = useState('')
|
const [resultCd, setResultCd] = useState('')
|
||||||
const [memo, setMemo] = useState('')
|
const [memo, setMemo] = useState('')
|
||||||
@@ -143,6 +159,7 @@ const ContactEventSection = ({
|
|||||||
const historyQuery = useListEventHistoryQuery(prjctIdx, sid, true)
|
const historyQuery = useListEventHistoryQuery(prjctIdx, sid, true)
|
||||||
const ctiLastCallHistId = useCtiLastCallHistId(prjctIdx, sid)
|
const ctiLastCallHistId = useCtiLastCallHistId(prjctIdx, sid)
|
||||||
const listCallHistIdx = isContactType ? ctiLastCallHistId : null
|
const listCallHistIdx = isContactType ? ctiLastCallHistId : null
|
||||||
|
const deleteEventMutation = useDeleteListEventMutation(prjctIdx, sid)
|
||||||
|
|
||||||
const handleResultCdChange = (next: string) => {
|
const handleResultCdChange = (next: string) => {
|
||||||
setResultCd(next)
|
setResultCd(next)
|
||||||
@@ -192,7 +209,7 @@ const ContactEventSection = ({
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
{showReservation && isReservationSelected ? (
|
{showReservation && isReservationSelected ? (
|
||||||
<KriDateTimePicker value={resveDt} onChange={setResveDt} placeholder="예약 날짜/시간" />
|
<KriDateTimePicker value={resveDt} onChange={setResveDt} startHour={9} endHour={20} placeholder="예약 날짜/시간" />
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<Button type="button" className="w-full" disabled={submitting} onClick={handleAdd}>
|
<Button type="button" className="w-full" disabled={submitting} onClick={handleAdd}>
|
||||||
@@ -203,10 +220,19 @@ const ContactEventSection = ({
|
|||||||
|
|
||||||
<CollapsibleHistorySection
|
<CollapsibleHistorySection
|
||||||
title={`${title}(최근순)`}
|
title={`${title}(최근순)`}
|
||||||
|
defaultOpen
|
||||||
showDivider={showInput}
|
showDivider={showInput}
|
||||||
headerExtra={<RefreshIconButton onRefresh={() => historyQuery.refetch()} isFetching={historyQuery.isFetching} />}
|
headerExtra={<RefreshIconButton onRefresh={() => historyQuery.refetch()} isFetching={historyQuery.isFetching} />}
|
||||||
>
|
>
|
||||||
<EventHistoryList isLoading={historyQuery.isLoading} history={historyQuery.data} resultCodeType={resultCodeType} resultCodes={resultCodes} />
|
<EventHistoryList
|
||||||
|
isLoading={historyQuery.isLoading}
|
||||||
|
history={historyQuery.data}
|
||||||
|
resultCodeType={resultCodeType}
|
||||||
|
resultCodes={resultCodes}
|
||||||
|
canDelete={canDelete}
|
||||||
|
isDeleting={deleteEventMutation.isPending}
|
||||||
|
onDelete={(listEventHistIdx) => deleteEventMutation.mutate(listEventHistIdx)}
|
||||||
|
/>
|
||||||
</CollapsibleHistorySection>
|
</CollapsibleHistorySection>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -261,6 +287,7 @@ const SendResultHistory = ({ sid, prjctCd }: { sid: string; prjctCd: string }) =
|
|||||||
<div className="space-y-2 rounded-lg border bg-white p-4">
|
<div className="space-y-2 rounded-lg border bg-white p-4">
|
||||||
<CollapsibleHistorySection
|
<CollapsibleHistorySection
|
||||||
title="발송 현황(최근순)"
|
title="발송 현황(최근순)"
|
||||||
|
defaultOpen
|
||||||
showDivider={false}
|
showDivider={false}
|
||||||
headerExtra={
|
headerExtra={
|
||||||
<div className="flex items-center gap-1">
|
<div className="flex items-center gap-1">
|
||||||
@@ -322,6 +349,7 @@ const ListContactEventPanel = ({
|
|||||||
const internalInfoQuery = useInternalInfoQuery()
|
const internalInfoQuery = useInternalInfoQuery()
|
||||||
const showContactInput = userRole !== FIELD_INTERVIEWER_ROLE
|
const showContactInput = userRole !== FIELD_INTERVIEWER_ROLE
|
||||||
const showInterviewInput = userRole !== CONTACT_INTERVIEWER_ROLE
|
const showInterviewInput = userRole !== CONTACT_INTERVIEWER_ROLE
|
||||||
|
const canDeleteEvent = isInternalManager(userRole)
|
||||||
const contactSenarioValues = Object.fromEntries(
|
const contactSenarioValues = Object.fromEntries(
|
||||||
Object.entries(buildListContactVariableValues(listHeaders, detail, sid)).map(([key, value]) => [
|
Object.entries(buildListContactVariableValues(listHeaders, detail, sid)).map(([key, value]) => [
|
||||||
key,
|
key,
|
||||||
@@ -369,13 +397,14 @@ const ListContactEventPanel = ({
|
|||||||
showInput={showContactInput}
|
showInput={showContactInput}
|
||||||
submitting={addListEventMutation.isPending || reserveMutation.isPending}
|
submitting={addListEventMutation.isPending || reserveMutation.isPending}
|
||||||
onSubmit={handleAddEvent(ResultCodeType.CONTACT)}
|
onSubmit={handleAddEvent(ResultCodeType.CONTACT)}
|
||||||
|
canDelete={canDeleteEvent}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<SendResultHistory sid={sid} prjctCd={prjctCd} />
|
<SendResultHistory sid={sid} prjctCd={prjctCd} />
|
||||||
|
|
||||||
{useFF &&
|
{useFF &&
|
||||||
<ContactEventSection
|
<ContactEventSection
|
||||||
title="인터뷰 요원 확인사항"
|
title="면접 확인사항"
|
||||||
prjctIdx={prjctIdx}
|
prjctIdx={prjctIdx}
|
||||||
sid={sid}
|
sid={sid}
|
||||||
resultCodeType={ResultCodeType.INTERVIEW}
|
resultCodeType={ResultCodeType.INTERVIEW}
|
||||||
@@ -383,6 +412,7 @@ const ListContactEventPanel = ({
|
|||||||
showInput={showInterviewInput}
|
showInput={showInterviewInput}
|
||||||
submitting={addListEventMutation.isPending}
|
submitting={addListEventMutation.isPending}
|
||||||
onSubmit={handleAddEvent(ResultCodeType.INTERVIEW)}
|
onSubmit={handleAddEvent(ResultCodeType.INTERVIEW)}
|
||||||
|
canDelete={canDeleteEvent}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import type { MessageSendChannel } from '@/types/message'
|
|||||||
import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
|
import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
|
||||||
import { formatKst } from '@kri/common'
|
import { formatKst } from '@kri/common'
|
||||||
import { isListFieldEditableForContact, isListFieldVisibleForContact } from '@/utils/listAccess'
|
import { isListFieldEditableForContact, isListFieldVisibleForContact } from '@/utils/listAccess'
|
||||||
import { substituteVariables } from '@/lib/surveyUrl'
|
import { substituteVariables } from '@/lib/variableSubstitution'
|
||||||
import { formatKoreanPhoneNumber } from '@/utils/phone'
|
import { formatKoreanPhoneNumber } from '@/utils/phone'
|
||||||
import SurveyQrDialog from '@/components/dialog/SurveyQrDialog'
|
import SurveyQrDialog from '@/components/dialog/SurveyQrDialog'
|
||||||
import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog'
|
import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog'
|
||||||
@@ -56,7 +56,7 @@ export const buildInitialValues = (listHeaders: listHeader[], detail?: ListSearc
|
|||||||
return values
|
return values
|
||||||
}
|
}
|
||||||
|
|
||||||
const disabledContrastClass = 'disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60'
|
const disabledContrastClass = 'bg-white disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60'
|
||||||
|
|
||||||
const getCallButtonLabel = (isDialing: boolean, isOnCall: boolean) => {
|
const getCallButtonLabel = (isDialing: boolean, isOnCall: boolean) => {
|
||||||
if (isDialing) return '거는 중'
|
if (isDialing) return '거는 중'
|
||||||
@@ -70,9 +70,16 @@ const getCallButtonTitle = (isCtiReady: boolean, isDialing: boolean) => {
|
|||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
const FieldRow = ({ label, children }: { label: string; children: ReactNode }) => (
|
const FieldRow = ({ label, editable, children }: { label: string; editable?: boolean; children: ReactNode }) => (
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Label className="w-24 shrink-0 text-sm font-bold text-foreground">{label}</Label>
|
<Label
|
||||||
|
className={cn(
|
||||||
|
'w-24 shrink-0 rounded-md px-2 py-2.5 text-sm font-bold text-foreground',
|
||||||
|
editable && 'bg-blue-100 text-black',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</Label>
|
||||||
<div className="min-w-0 flex-1">{children}</div>
|
<div className="min-w-0 flex-1">{children}</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -167,7 +174,7 @@ const ListContactInfoPanel = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4 rounded-lg border bg-white p-4">
|
<div className="space-y-2 rounded-lg border bg-white p-4">
|
||||||
<h2 className="text-lg font-bold">리스트 정보</h2>
|
<h2 className="text-lg font-bold">리스트 정보</h2>
|
||||||
<input type="file" ref={fileInputRef} className="hidden" onChange={handleFileSelected} />
|
<input type="file" ref={fileInputRef} className="hidden" onChange={handleFileSelected} />
|
||||||
{visibleHeaders.map((header) => {
|
{visibleHeaders.map((header) => {
|
||||||
@@ -180,7 +187,7 @@ const ListContactInfoPanel = ({
|
|||||||
|
|
||||||
if (header.listHderTy === ListHeaderConst.MEMO) {
|
if (header.listHderTy === ListHeaderConst.MEMO) {
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
||||||
<textarea
|
<textarea
|
||||||
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 ${disabledContrastClass}`}
|
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 ${disabledContrastClass}`}
|
||||||
value={value}
|
value={value}
|
||||||
@@ -193,7 +200,7 @@ const ListContactInfoPanel = ({
|
|||||||
|
|
||||||
if (header.listHderTy === ListHeaderConst.TEL_NUM) {
|
if (header.listHderTy === ListHeaderConst.TEL_NUM) {
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Input
|
<Input
|
||||||
value={formatKoreanPhoneNumber(value)}
|
value={formatKoreanPhoneNumber(value)}
|
||||||
@@ -234,7 +241,7 @@ const ListContactInfoPanel = ({
|
|||||||
|
|
||||||
if (header.listHderTy === ListHeaderConst.EMAIL) {
|
if (header.listHderTy === ListHeaderConst.EMAIL) {
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Input
|
<Input
|
||||||
value={value}
|
value={value}
|
||||||
@@ -259,7 +266,7 @@ const ListContactInfoPanel = ({
|
|||||||
|
|
||||||
if (header.listHderTy === ListHeaderConst.FILE) {
|
if (header.listHderTy === ListHeaderConst.FILE) {
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="min-w-0 flex-1 truncate text-sm">
|
<div className="min-w-0 flex-1 truncate text-sm">
|
||||||
{value ? (
|
{value ? (
|
||||||
@@ -300,7 +307,7 @@ const ListContactInfoPanel = ({
|
|||||||
|
|
||||||
if (header.listHderTy === ListHeaderConst.CONTENT_ITEM && (header.filterContents?.length ?? 0) > 0) {
|
if (header.listHderTy === ListHeaderConst.CONTENT_ITEM && (header.filterContents?.length ?? 0) > 0) {
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
||||||
<KriSingleSelect
|
<KriSingleSelect
|
||||||
items={header.filterContents ?? []}
|
items={header.filterContents ?? []}
|
||||||
value={value}
|
value={value}
|
||||||
@@ -317,7 +324,7 @@ const ListContactInfoPanel = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
||||||
<Input
|
<Input
|
||||||
value={value}
|
value={value}
|
||||||
disabled={!editable}
|
disabled={!editable}
|
||||||
@@ -365,6 +372,7 @@ const ListContactInfoPanel = ({
|
|||||||
itrntPrjctCd={itrntPrjctCd}
|
itrntPrjctCd={itrntPrjctCd}
|
||||||
sid={sid}
|
sid={sid}
|
||||||
destHeaderId={sendTarget?.headerId ?? 0}
|
destHeaderId={sendTarget?.headerId ?? 0}
|
||||||
|
variableValues={surveyUrlValues}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ const ListUpdateHistoryPanel = ({ prjctIdx, sid, listHeaders }: ListUpdateHistor
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2 rounded-lg border bg-white p-4">
|
<div className="space-y-2 rounded-lg border bg-white p-4">
|
||||||
<CollapsibleHistorySection title="수정 이력" showDivider={false}>
|
<CollapsibleHistorySection title="수정 이력" defaultOpen showDivider={false}>
|
||||||
{historyQuery.isLoading ? (
|
{historyQuery.isLoading ? (
|
||||||
<div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
|
<div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
|
||||||
) : history.length === 0 ? (
|
) : history.length === 0 ? (
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
import { useCallback, useEffect, useMemo, useState, type ClipboardEvent, type ReactNode } from 'react'
|
||||||
import type { PaginationState, SortingState } from '@tanstack/react-table'
|
import type { PaginationState, SortingState } from '@tanstack/react-table'
|
||||||
import { Funnel, PencilLine } from 'lucide-react'
|
import { Funnel, PencilLine } from 'lucide-react'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
@@ -8,6 +8,7 @@ import { Input } from '@/components/ui/input'
|
|||||||
import { DataTable } from '@/components/data-table/DataTable'
|
import { DataTable } from '@/components/data-table/DataTable'
|
||||||
import type { DataTableColumn, SelectMode } from '@/components/data-table/DataTable.type'
|
import type { DataTableColumn, SelectMode } from '@/components/data-table/DataTable.type'
|
||||||
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||||
|
import KriDateRangePicker, { type KriDateRange } from '@/components/common/KriDateRangePicker'
|
||||||
import ListBatchEditDialog, { type BatchEditPayload, type BatchEditResultCodes, type BatchEditRow, type BatchEditSurveyResultCodes } from '@/components/dialog/ListBatchEditDialog'
|
import ListBatchEditDialog, { type BatchEditPayload, type BatchEditResultCodes, type BatchEditRow, type BatchEditSurveyResultCodes } from '@/components/dialog/ListBatchEditDialog'
|
||||||
import ListFilterDialog, { operatorLabel } from '@/components/dialog/ListFilterDialog'
|
import ListFilterDialog, { operatorLabel } from '@/components/dialog/ListFilterDialog'
|
||||||
import { useDialog } from '@/hooks/useDialog'
|
import { useDialog } from '@/hooks/useDialog'
|
||||||
@@ -50,6 +51,7 @@ export type ListSearchTableProps = {
|
|||||||
resultCodes: ResultCode[]
|
resultCodes: ResultCode[]
|
||||||
surveys: ProjectSurvey[]
|
surveys: ProjectSurvey[]
|
||||||
listHeaders: listHeader[]
|
listHeaders: listHeader[]
|
||||||
|
fieldInterviewEnabled?: boolean
|
||||||
enableBatchEdit?: boolean
|
enableBatchEdit?: boolean
|
||||||
refreshKey?: number
|
refreshKey?: number
|
||||||
selectMode?: SelectMode
|
selectMode?: SelectMode
|
||||||
@@ -77,6 +79,8 @@ const toSidSet = (value: string) =>
|
|||||||
.map((item) => item.trim())
|
.map((item) => item.trim())
|
||||||
.filter((item) => item.length > 0)
|
.filter((item) => item.length > 0)
|
||||||
|
|
||||||
|
const deduplicateSidInput = (value: string) => [...new Set(toSidSet(value))].join(',')
|
||||||
|
|
||||||
const sanitizeSidInput = (value: string) => {
|
const sanitizeSidInput = (value: string) => {
|
||||||
let result = ''
|
let result = ''
|
||||||
let lastChar: 'digit' | 'comma' | 'tilde' | null = null
|
let lastChar: 'digit' | 'comma' | 'tilde' | null = null
|
||||||
@@ -131,7 +135,7 @@ const toFilterCondition = (row: FilterRow, usesListValue: boolean): Omit<ListOth
|
|||||||
const TEXT_LIKE_OPERATORS: FilterOperator[] = ['eq', 'neq', 'contains', 'notContains', 'empty', 'notEmpty']
|
const TEXT_LIKE_OPERATORS: FilterOperator[] = ['eq', 'neq', 'contains', 'notContains', 'empty', 'notEmpty']
|
||||||
const ASSIGN_LIKE_OPERATORS: FilterOperator[] = ['eq', 'neq', 'empty', 'notEmpty']
|
const ASSIGN_LIKE_OPERATORS: FilterOperator[] = ['eq', 'neq', 'empty', 'notEmpty']
|
||||||
const IS_USE_OPERATORS: FilterOperator[] = ['eq', 'neq']
|
const IS_USE_OPERATORS: FilterOperator[] = ['eq', 'neq']
|
||||||
const FILE_OPERATORS: FilterOperator[] = ['empty', 'notEmpty']
|
const FILE_OPERATORS: FilterOperator[] = ['none', 'empty', 'notEmpty']
|
||||||
|
|
||||||
const getAllowedOperators = (listHderTy: number): FilterOperator[] => {
|
const getAllowedOperators = (listHderTy: number): FilterOperator[] => {
|
||||||
if (listHderTy === ListHeaderConst.IS_USE) return IS_USE_OPERATORS
|
if (listHderTy === ListHeaderConst.IS_USE) return IS_USE_OPERATORS
|
||||||
@@ -140,6 +144,13 @@ const getAllowedOperators = (listHderTy: number): FilterOperator[] => {
|
|||||||
return TEXT_LIKE_OPERATORS
|
return TEXT_LIKE_OPERATORS
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getDefaultOperator = (listHderTy: number): FilterOperator => {
|
||||||
|
if (listHderTy === ListHeaderConst.FILE) return 'none'
|
||||||
|
if (listHderTy === ListHeaderConst.IS_USE) return 'eq'
|
||||||
|
if (isAssignHeaderType(listHderTy) || listHderTy === ListHeaderConst.CONTENT_ITEM) return 'eq'
|
||||||
|
return 'contains'
|
||||||
|
}
|
||||||
|
|
||||||
const IS_USE_VALUE_OPTIONS: FilterValueOption[] = Object.entries(LIST_IS_USE_LABEL).map(([value, label]) => ({
|
const IS_USE_VALUE_OPTIONS: FilterValueOption[] = Object.entries(LIST_IS_USE_LABEL).map(([value, label]) => ({
|
||||||
value,
|
value,
|
||||||
label,
|
label,
|
||||||
@@ -154,6 +165,7 @@ export function ListSearchTable({
|
|||||||
resultCodes,
|
resultCodes,
|
||||||
surveys,
|
surveys,
|
||||||
listHeaders,
|
listHeaders,
|
||||||
|
fieldInterviewEnabled = true,
|
||||||
enableBatchEdit = false,
|
enableBatchEdit = false,
|
||||||
refreshKey = 0,
|
refreshKey = 0,
|
||||||
selectMode = 'multi',
|
selectMode = 'multi',
|
||||||
@@ -176,6 +188,9 @@ export function ListSearchTable({
|
|||||||
const { showDialog } = useDialog()
|
const { showDialog } = useDialog()
|
||||||
const [searchText, setSearchText] = useState(initialSearchState?.searchText ?? '')
|
const [searchText, setSearchText] = useState(initialSearchState?.searchText ?? '')
|
||||||
const [searchContactResult, setSearchContactResult] = useState<string[]>(initialSearchState?.searchContactResult ?? [])
|
const [searchContactResult, setSearchContactResult] = useState<string[]>(initialSearchState?.searchContactResult ?? [])
|
||||||
|
const [searchContactDateRange, setSearchContactDateRange] = useState<KriDateRange>(
|
||||||
|
initialSearchState?.searchContactDateRange ?? { from: '', to: '' },
|
||||||
|
)
|
||||||
const [searchInterviewResult, setSearchInterviewResult] = useState<string[]>(initialSearchState?.searchInterviewResult ?? [])
|
const [searchInterviewResult, setSearchInterviewResult] = useState<string[]>(initialSearchState?.searchInterviewResult ?? [])
|
||||||
const [surveyResultSelections, setSurveyResultSelections] = useState<SurveyResultSelections>(initialSearchState?.surveyResultSelections ?? {})
|
const [surveyResultSelections, setSurveyResultSelections] = useState<SurveyResultSelections>(initialSearchState?.surveyResultSelections ?? {})
|
||||||
const [pagination, setPagination] = useState<PaginationState>(initialPagination ?? { pageIndex: 0, pageSize: 25 })
|
const [pagination, setPagination] = useState<PaginationState>(initialPagination ?? { pageIndex: 0, pageSize: 25 })
|
||||||
@@ -198,7 +213,11 @@ export function ListSearchTable({
|
|||||||
enabled,
|
enabled,
|
||||||
assignType: ListHeaderAssignConst.CONTACT_INTERVIEWER,
|
assignType: ListHeaderAssignConst.CONTACT_INTERVIEWER,
|
||||||
})
|
})
|
||||||
const fieldTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: ListHeaderAssignConst.FIELD_INTERVIEWER })
|
const fieldTargetRows = useAssignTargetRows({
|
||||||
|
prjctIdx,
|
||||||
|
enabled: enabled && fieldInterviewEnabled,
|
||||||
|
assignType: ListHeaderAssignConst.FIELD_INTERVIEWER,
|
||||||
|
})
|
||||||
|
|
||||||
const getValueOptionsForHeader = useCallback(
|
const getValueOptionsForHeader = useCallback(
|
||||||
(header: listHeader): FilterValueOption[] | undefined => {
|
(header: listHeader): FilterValueOption[] | undefined => {
|
||||||
@@ -220,20 +239,28 @@ export function ListSearchTable({
|
|||||||
[contactTargetRows, fieldTargetRows, outsourceTargetRows],
|
[contactTargetRows, fieldTargetRows, outsourceTargetRows],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const availableListHeaders = useMemo(
|
||||||
|
() =>
|
||||||
|
fieldInterviewEnabled
|
||||||
|
? listHeaders
|
||||||
|
: listHeaders.filter((header) => header.listHderTy !== ListHeaderConst.FIELD_INTERVIEWER),
|
||||||
|
[fieldInterviewEnabled, listHeaders],
|
||||||
|
)
|
||||||
|
|
||||||
const accessibleListHeaders = useMemo(
|
const accessibleListHeaders = useMemo(
|
||||||
() => listHeaders.filter((header) => isListHeaderVisibleByAccess(header, userRole)),
|
() => availableListHeaders.filter((header) => isListHeaderVisibleByAccess(header, userRole)),
|
||||||
[listHeaders, userRole],
|
[availableListHeaders, userRole],
|
||||||
)
|
)
|
||||||
|
|
||||||
const accessibleFilterHeaders = useMemo(
|
const accessibleFilterHeaders = useMemo(
|
||||||
() =>
|
() =>
|
||||||
listHeaders.filter(
|
availableListHeaders.filter(
|
||||||
(header) =>
|
(header) =>
|
||||||
header.listHderTy !== ListHeaderConst.SID &&
|
header.listHderTy !== ListHeaderConst.SID &&
|
||||||
isListFilterVisibleByAccess(header, userRole) &&
|
isListFilterVisibleByAccess(header, userRole) &&
|
||||||
!excludeFilterHeaderTypes?.includes(header.listHderTy),
|
!excludeFilterHeaderTypes?.includes(header.listHderTy),
|
||||||
),
|
),
|
||||||
[listHeaders, userRole, excludeFilterHeaderTypes],
|
[availableListHeaders, userRole, excludeFilterHeaderTypes],
|
||||||
)
|
)
|
||||||
|
|
||||||
const accessibleFilterHeaderById = useMemo(
|
const accessibleFilterHeaderById = useMemo(
|
||||||
@@ -250,7 +277,7 @@ export function ListSearchTable({
|
|||||||
listFilter.memoConditions = []
|
listFilter.memoConditions = []
|
||||||
listFilter.resultCodeMap = {
|
listFilter.resultCodeMap = {
|
||||||
[ResultCodeType.CONTACT]: searchContactResult.map(Number),
|
[ResultCodeType.CONTACT]: searchContactResult.map(Number),
|
||||||
[ResultCodeType.INTERVIEW]: searchInterviewResult.map(Number),
|
[ResultCodeType.INTERVIEW]: fieldInterviewEnabled ? searchInterviewResult.map(Number) : [],
|
||||||
}
|
}
|
||||||
listFilter.surveyResultConditions = Object.entries(surveyResultSelections)
|
listFilter.surveyResultConditions = Object.entries(surveyResultSelections)
|
||||||
.filter(([, codes]) => codes.length > 0)
|
.filter(([, codes]) => codes.length > 0)
|
||||||
@@ -259,9 +286,20 @@ export function ListSearchTable({
|
|||||||
resultCodes: codes.map(Number),
|
resultCodes: codes.map(Number),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
if (searchContactDateRange.from || searchContactDateRange.to) {
|
||||||
|
listFilter.lastEventDateRange = [
|
||||||
|
{
|
||||||
|
resultCodeType: ResultCodeType.CONTACT,
|
||||||
|
startDate: searchContactDateRange.from ? `${searchContactDateRange.from}T00:00:00` : undefined,
|
||||||
|
endDate: searchContactDateRange.to ? `${searchContactDateRange.to}T23:59:59` : undefined,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
filterRows.forEach((row) => {
|
filterRows.forEach((row) => {
|
||||||
const header = accessibleFilterHeaderById.get(row.headerId)
|
const header = accessibleFilterHeaderById.get(row.headerId)
|
||||||
if (!header || lockedListFilterHeaderTypes.has(header.listHderTy)) return
|
if (!header || lockedListFilterHeaderTypes.has(header.listHderTy)) return
|
||||||
|
if (row.operator === 'none') return
|
||||||
|
|
||||||
const isEmptyOperator = row.operator === 'empty' || row.operator === 'notEmpty'
|
const isEmptyOperator = row.operator === 'empty' || row.operator === 'notEmpty'
|
||||||
const usesListValue = getValueOptionsForHeader(header) !== undefined
|
const usesListValue = getValueOptionsForHeader(header) !== undefined
|
||||||
@@ -322,12 +360,14 @@ export function ListSearchTable({
|
|||||||
}, [
|
}, [
|
||||||
accessibleFilterHeaderById,
|
accessibleFilterHeaderById,
|
||||||
externalAssignFilter,
|
externalAssignFilter,
|
||||||
|
fieldInterviewEnabled,
|
||||||
filterRows,
|
filterRows,
|
||||||
getValueOptionsForHeader,
|
getValueOptionsForHeader,
|
||||||
lockedListFilterHeaderTypes,
|
lockedListFilterHeaderTypes,
|
||||||
pagination.pageIndex,
|
pagination.pageIndex,
|
||||||
pagination.pageSize,
|
pagination.pageSize,
|
||||||
searchContactResult,
|
searchContactResult,
|
||||||
|
searchContactDateRange,
|
||||||
searchInterviewResult,
|
searchInterviewResult,
|
||||||
surveyResultSelections,
|
surveyResultSelections,
|
||||||
searchText,
|
searchText,
|
||||||
@@ -361,13 +401,19 @@ export function ListSearchTable({
|
|||||||
|
|
||||||
const resultSummaryGroups: { label: string; type: ResultCodeType; values: string[] }[] = [
|
const resultSummaryGroups: { label: string; type: ResultCodeType; values: string[] }[] = [
|
||||||
{ label: '컨택 결과', type: ResultCodeType.CONTACT, values: searchContactResult },
|
{ label: '컨택 결과', type: ResultCodeType.CONTACT, values: searchContactResult },
|
||||||
{ label: '면접 결과', type: ResultCodeType.INTERVIEW, values: searchInterviewResult },
|
...(fieldInterviewEnabled
|
||||||
|
? [{ label: '면접 결과', type: ResultCodeType.INTERVIEW, values: searchInterviewResult }]
|
||||||
|
: []),
|
||||||
]
|
]
|
||||||
resultSummaryGroups.forEach(({ label, type, values }) => {
|
resultSummaryGroups.forEach(({ label, type, values }) => {
|
||||||
if (values.length === 0) return
|
if (values.length === 0) return
|
||||||
lines.push(`${label}: ${values.map((value) => resultCodeLabel(type, value)).join(', ')}`)
|
lines.push(`${label}: ${values.map((value) => resultCodeLabel(type, value)).join(', ')}`)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if (searchContactDateRange.from || searchContactDateRange.to) {
|
||||||
|
lines.push(`컨택 일자: ${searchContactDateRange.from || ''} ~ ${searchContactDateRange.to || ''}`)
|
||||||
|
}
|
||||||
|
|
||||||
surveys.forEach((survey) => {
|
surveys.forEach((survey) => {
|
||||||
if (survey.prjctSurveyIdx == null) return
|
if (survey.prjctSurveyIdx == null) return
|
||||||
const codes = surveyResultSelections[survey.prjctSurveyIdx] ?? []
|
const codes = surveyResultSelections[survey.prjctSurveyIdx] ?? []
|
||||||
@@ -402,9 +448,11 @@ export function ListSearchTable({
|
|||||||
}, [
|
}, [
|
||||||
accessibleFilterHeaderById,
|
accessibleFilterHeaderById,
|
||||||
filterRows,
|
filterRows,
|
||||||
|
fieldInterviewEnabled,
|
||||||
getValueOptionsForHeader,
|
getValueOptionsForHeader,
|
||||||
lockedListFilterHeaderTypes,
|
lockedListFilterHeaderTypes,
|
||||||
resultCodeLabel,
|
resultCodeLabel,
|
||||||
|
searchContactDateRange,
|
||||||
searchContactResult,
|
searchContactResult,
|
||||||
searchInterviewResult,
|
searchInterviewResult,
|
||||||
surveys,
|
surveys,
|
||||||
@@ -444,9 +492,12 @@ export function ListSearchTable({
|
|||||||
)
|
)
|
||||||
|
|
||||||
const columns = useMemo<DataTableColumn<ListTableRow, unknown>[]>(() => {
|
const columns = useMemo<DataTableColumn<ListTableRow, unknown>[]>(() => {
|
||||||
if (!listHeaders.length) return []
|
if (!availableListHeaders.length) return []
|
||||||
return getListColumns(listHeaders, resultCodes, userRole, surveys)
|
const listColumns = getListColumns(availableListHeaders, resultCodes, userRole, surveys)
|
||||||
}, [listHeaders, resultCodes, userRole, surveys])
|
return fieldInterviewEnabled
|
||||||
|
? listColumns
|
||||||
|
: listColumns.filter((column) => column.id !== 'result-interview')
|
||||||
|
}, [availableListHeaders, fieldInterviewEnabled, resultCodes, surveys, userRole])
|
||||||
|
|
||||||
const viewList = useMemo<ListTableRow[]>(
|
const viewList = useMemo<ListTableRow[]>(
|
||||||
() => (listSearchQuery.data?.content ?? []).map((row) => ({ ...row, ...row.itemList })),
|
() => (listSearchQuery.data?.content ?? []).map((row) => ({ ...row, ...row.itemList })),
|
||||||
@@ -475,6 +526,7 @@ export function ListSearchTable({
|
|||||||
id: header.listHderId,
|
id: header.listHderId,
|
||||||
label: header.listHderNm,
|
label: header.listHderNm,
|
||||||
allowedOperators: getAllowedOperators(header.listHderTy),
|
allowedOperators: getAllowedOperators(header.listHderTy),
|
||||||
|
defaultOperator: getDefaultOperator(header.listHderTy),
|
||||||
valueOptions: getValueOptionsForHeader(header),
|
valueOptions: getValueOptionsForHeader(header),
|
||||||
disabled: lockedListFilterHeaderTypes.has(header.listHderTy),
|
disabled: lockedListFilterHeaderTypes.has(header.listHderTy),
|
||||||
})),
|
})),
|
||||||
@@ -485,6 +537,17 @@ export function ListSearchTable({
|
|||||||
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleSidPaste = (e: ClipboardEvent<HTMLInputElement>) => {
|
||||||
|
const pastedText = e.clipboardData.getData('text')
|
||||||
|
const normalizedText = pastedText.replace(/\t|\r\n|\r|\n/g, ',')
|
||||||
|
|
||||||
|
e.preventDefault()
|
||||||
|
const selectionStart = e.currentTarget.selectionStart ?? searchText.length
|
||||||
|
const selectionEnd = e.currentTarget.selectionEnd ?? selectionStart
|
||||||
|
const nextValue = `${searchText.slice(0, selectionStart)}${normalizedText}${searchText.slice(selectionEnd)}`
|
||||||
|
setSearchText(deduplicateSidInput(sanitizeSidInput(nextValue)))
|
||||||
|
}
|
||||||
|
|
||||||
const handleFilterConfirm = async (rows: FilterRow[]) => {
|
const handleFilterConfirm = async (rows: FilterRow[]) => {
|
||||||
setFilterRows(rows)
|
setFilterRows(rows)
|
||||||
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
||||||
@@ -522,6 +585,7 @@ export function ListSearchTable({
|
|||||||
onSearchStateChange?.({
|
onSearchStateChange?.({
|
||||||
searchText,
|
searchText,
|
||||||
searchContactResult,
|
searchContactResult,
|
||||||
|
searchContactDateRange,
|
||||||
searchInterviewResult,
|
searchInterviewResult,
|
||||||
surveyResultSelections,
|
surveyResultSelections,
|
||||||
filterRows,
|
filterRows,
|
||||||
@@ -530,6 +594,7 @@ export function ListSearchTable({
|
|||||||
}, [
|
}, [
|
||||||
searchText,
|
searchText,
|
||||||
searchContactResult,
|
searchContactResult,
|
||||||
|
searchContactDateRange,
|
||||||
searchInterviewResult,
|
searchInterviewResult,
|
||||||
surveyResultSelections,
|
surveyResultSelections,
|
||||||
filterRows,
|
filterRows,
|
||||||
@@ -559,12 +624,13 @@ export function ListSearchTable({
|
|||||||
return (
|
return (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
<Input
|
<Input
|
||||||
placeholder="SID 검색"
|
placeholder="SID 검색"
|
||||||
className="h-9 bg-white flex-1 min-w-0 max-w-xs"
|
className="h-9 bg-white flex-1 min-w-0 max-w-xs"
|
||||||
value={searchText}
|
value={searchText}
|
||||||
onChange={(e) => setSearchText(sanitizeSidInput(e.target.value))}
|
onChange={(e) => setSearchText(sanitizeSidInput(e.target.value))}
|
||||||
|
onPaste={handleSidPaste}
|
||||||
/>
|
/>
|
||||||
<div className="flex-1 min-w-0 max-w-xs">
|
<div className="flex-1 min-w-0 max-w-xs">
|
||||||
<KriMultiSelect
|
<KriMultiSelect
|
||||||
@@ -578,18 +644,29 @@ export function ListSearchTable({
|
|||||||
heightClassName="h-9"
|
heightClassName="h-9"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-w-0 max-w-xs">
|
<KriDateRangePicker
|
||||||
<KriMultiSelect
|
value={searchContactDateRange}
|
||||||
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.INTERVIEW)}
|
onChange={(range) => {
|
||||||
value={searchInterviewResult}
|
setSearchContactDateRange(range)
|
||||||
onChange={setSearchInterviewResult}
|
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
||||||
getValue={(item) => String(item.resultCd)}
|
}}
|
||||||
getLabel={(item) => item.resultCdLbl}
|
placeholder="컨택 일자"
|
||||||
placeholder="면접 결과"
|
className="flex-1 min-w-[240px] max-w-xs"
|
||||||
widthClassName="w-full"
|
/>
|
||||||
heightClassName="h-9"
|
{fieldInterviewEnabled ? (
|
||||||
/>
|
<div className="flex-1 min-w-0 max-w-xs">
|
||||||
</div>
|
<KriMultiSelect
|
||||||
|
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.INTERVIEW)}
|
||||||
|
value={searchInterviewResult}
|
||||||
|
onChange={setSearchInterviewResult}
|
||||||
|
getValue={(item) => String(item.resultCd)}
|
||||||
|
getLabel={(item) => item.resultCdLbl}
|
||||||
|
placeholder="면접 결과"
|
||||||
|
widthClassName="w-full"
|
||||||
|
heightClassName="h-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{surveys.length > 0 ? (
|
{surveys.length > 0 ? (
|
||||||
|
|||||||
@@ -535,7 +535,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
|||||||
{!isSms && (
|
{!isSms && (
|
||||||
<KriEditor
|
<KriEditor
|
||||||
//mode="both"
|
//mode="both"
|
||||||
mode="wysiwyg"
|
mode="both"
|
||||||
showPreview={true}
|
showPreview={true}
|
||||||
value={normalizeQrCodeForEditor(selectedTemplate.tmplatBody) || "<p></p>"}
|
value={normalizeQrCodeForEditor(selectedTemplate.tmplatBody) || "<p></p>"}
|
||||||
onChange={(html: string) => setTemplateBody(html)}
|
onChange={(html: string) => setTemplateBody(html)}
|
||||||
@@ -549,6 +549,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
|||||||
toolbar={{ strike: false, table: false, bulletList: false, orderedList: false }}
|
toolbar={{ strike: false, table: false, bulletList: false, orderedList: false }}
|
||||||
editorExtensions={MESSAGE_EDITOR_EXTENSIONS}
|
editorExtensions={MESSAGE_EDITOR_EXTENSIONS}
|
||||||
allowedCustomHtml={QR_CODE_ALLOWED_HTML}
|
allowedCustomHtml={QR_CODE_ALLOWED_HTML}
|
||||||
|
previewClassName="kri-editor-preview"
|
||||||
transformPreviewHtml={renderQrCodePreviewHtml}
|
transformPreviewHtml={renderQrCodePreviewHtml}
|
||||||
renderToolbarEnd={({editor}) => (
|
renderToolbarEnd={({editor}) => (
|
||||||
<QrCodeToolbar editor={editor} surveys={surveys} />
|
<QrCodeToolbar editor={editor} surveys={surveys} />
|
||||||
|
|||||||
@@ -14,22 +14,13 @@ import { useCmpnListQuery } from "@/query/cmpn";
|
|||||||
import { useResultCodesQuery } from "@/query/project";
|
import { useResultCodesQuery } from "@/query/project";
|
||||||
import { useDateProgressQuery, useLastDateProgressQuery, useUserProgressQuery } from "@/query/progress";
|
import { useDateProgressQuery, useLastDateProgressQuery, useUserProgressQuery } from "@/query/progress";
|
||||||
import type { ProgressEventTypeValue } from "@/types/progress";
|
import type { ProgressEventTypeValue } from "@/types/progress";
|
||||||
import type { ResultCodeType } from "@/types/project";
|
import { ResultCodeType } from "@/types/project";
|
||||||
|
import { RESULT_CODE_UNUSED } from "@/const/projectConst";
|
||||||
import { UserProgressTable } from "./UserProgressTable";
|
import { UserProgressTable } from "./UserProgressTable";
|
||||||
import { DateProgressSection } from "./DateProgressSection";
|
import { DateProgressSection } from "./DateProgressSection";
|
||||||
import { buildResultCodeColumns } from "./resultCodeColumns";
|
import { buildResultCodeColumns } from "./resultCodeColumns";
|
||||||
import { isExternalManager, isFieldWorkUser, isInternalManager } from "@/utils/userRole";
|
import { isExternalManager, isFieldWorkUser, isInternalManager } from "@/utils/userRole";
|
||||||
|
|
||||||
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);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ProgressPageContentProps = {
|
export type ProgressPageContentProps = {
|
||||||
eventTy: ProgressEventTypeValue;
|
eventTy: ProgressEventTypeValue;
|
||||||
resultCdTy: ResultCodeType;
|
resultCdTy: ResultCodeType;
|
||||||
@@ -44,10 +35,7 @@ export function ProgressPageContent({ eventTy, resultCdTy, pageTitle, domainLabe
|
|||||||
const { selectedProject } = useSelectedProject();
|
const { selectedProject } = useSelectedProject();
|
||||||
const { users, isLoading: usersLoading } = useItrntUserList();
|
const { users, isLoading: usersLoading } = useItrntUserList();
|
||||||
|
|
||||||
const [dateRange, setDateRange] = useState(() => {
|
const [dateRange, setDateRange] = useState({ from: "", to: "" });
|
||||||
const now = new Date();
|
|
||||||
return { from: getFirstDayOfMonth(now), to: getLastDayOfMonth(now) };
|
|
||||||
});
|
|
||||||
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
|
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
|
||||||
const [selectedCmpnId, setSelectedCmpnId] = useState("ALL");
|
const [selectedCmpnId, setSelectedCmpnId] = useState("ALL");
|
||||||
|
|
||||||
@@ -57,13 +45,20 @@ export function ProgressPageContent({ eventTy, resultCdTy, pageTitle, domainLabe
|
|||||||
const showCmpnSelect = isInternalManager(userRole);
|
const showCmpnSelect = isInternalManager(userRole);
|
||||||
|
|
||||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||||
const enabled = mounted && !usersLoading && prjctIdx > 0 && !!dateRange.from && !!dateRange.to;
|
const enabled = mounted && !usersLoading && prjctIdx > 0;
|
||||||
|
|
||||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled);
|
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled);
|
||||||
const resultCodeColumns = useMemo(
|
const resultCodeColumns = useMemo(
|
||||||
() => buildResultCodeColumns(resultCodesQuery.data ?? [], resultCdTy),
|
() => buildResultCodeColumns(resultCodesQuery.data ?? [], resultCdTy),
|
||||||
[resultCodesQuery.data, resultCdTy],
|
[resultCodesQuery.data, resultCdTy],
|
||||||
);
|
);
|
||||||
|
const dateResultCodeColumns = useMemo(
|
||||||
|
() =>
|
||||||
|
resultCdTy === ResultCodeType.CONTACT
|
||||||
|
? resultCodeColumns.filter(({ resultCd }) => resultCd !== RESULT_CODE_UNUSED)
|
||||||
|
: resultCodeColumns,
|
||||||
|
[resultCdTy, resultCodeColumns],
|
||||||
|
);
|
||||||
|
|
||||||
const userNameMap = useMemo(() => {
|
const userNameMap = useMemo(() => {
|
||||||
const map: Record<string, string> = {};
|
const map: Record<string, string> = {};
|
||||||
@@ -157,14 +152,14 @@ export function ProgressPageContent({ eventTy, resultCdTy, pageTitle, domainLabe
|
|||||||
title={`일자별 ${domainLabel} 현황(전체)`}
|
title={`일자별 ${domainLabel} 현황(전체)`}
|
||||||
subtitle={`일자별 입력된 ${domainLabel} 진행 현황을 전체 결과를 기준으로 집계하는 현황입니다.`}
|
subtitle={`일자별 입력된 ${domainLabel} 진행 현황을 전체 결과를 기준으로 집계하는 현황입니다.`}
|
||||||
rows={dateProgressQuery.data ?? []}
|
rows={dateProgressQuery.data ?? []}
|
||||||
resultCodeColumns={resultCodeColumns}
|
resultCodeColumns={dateResultCodeColumns}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<DateProgressSection
|
<DateProgressSection
|
||||||
title={`일자별 ${domainLabel} 현황(마지막 기준)`}
|
title={`일자별 ${domainLabel} 현황(마지막 기준)`}
|
||||||
subtitle={`일자별 입력된 ${domainLabel} 진행 현황을 최고 결과를 기준으로 집계하는 현황입니다.`}
|
subtitle={`일자별 입력된 ${domainLabel} 진행 현황을 최고 결과를 기준으로 집계하는 현황입니다.`}
|
||||||
rows={lastDateProgressQuery.data ?? []}
|
rows={lastDateProgressQuery.data ?? []}
|
||||||
resultCodeColumns={resultCodeColumns}
|
resultCodeColumns={dateResultCodeColumns}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ export type UserProgressTableProps = {
|
|||||||
|
|
||||||
const pct = (count: number, total: number) => (total > 0 ? `(${((count / total) * 100).toFixed(1)})` : '(0.0)')
|
const pct = (count: number, total: number) => (total > 0 ? `(${((count / total) * 100).toFixed(1)})` : '(0.0)')
|
||||||
|
|
||||||
|
const getUserLabel = (userId: string | undefined, userNameMap: Record<string, string>) => {
|
||||||
|
if (userId === 'UNASSIGNED') return '미배정'
|
||||||
|
return userNameMap[userId ?? ''] ?? userId ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
export function UserProgressTable({
|
export function UserProgressTable({
|
||||||
rows,
|
rows,
|
||||||
resultCodeColumns,
|
resultCodeColumns,
|
||||||
@@ -38,10 +43,10 @@ export function UserProgressTable({
|
|||||||
{
|
{
|
||||||
id: 'userId',
|
id: 'userId',
|
||||||
header: '담당자',
|
header: '담당자',
|
||||||
accessorFn: (row) => userNameMap[row.userId ?? ''] ?? row.userId ?? '',
|
accessorFn: (row) => getUserLabel(row.userId, userNameMap),
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
{row.getIsPinned() ? 'Total' : (userNameMap[row.original.userId ?? ''] ?? row.original.userId ?? '')}
|
{row.getIsPinned() ? 'Total' : getUserLabel(row.original.userId, userNameMap)}
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdap
|
|||||||
import { QueryProvider } from "@kri/common/query";
|
import { QueryProvider } from "@kri/common/query";
|
||||||
import { QueryLoadingSync } from "./QueryLoadingSync";
|
import { QueryLoadingSync } from "./QueryLoadingSync";
|
||||||
import { CtiConnectionSync } from "./CtiConnectionSync";
|
import { CtiConnectionSync } from "./CtiConnectionSync";
|
||||||
|
import { ReserveNotificationSync } from "./ReserveNotificationSync";
|
||||||
|
|
||||||
export function AppProvider({ children }: { children: React.ReactNode }) {
|
export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
@@ -23,6 +24,7 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
|
|||||||
>
|
>
|
||||||
<QueryLoadingSync />
|
<QueryLoadingSync />
|
||||||
<CtiConnectionSync />
|
<CtiConnectionSync />
|
||||||
|
<ReserveNotificationSync />
|
||||||
<LoadingOverlayAdapter />
|
<LoadingOverlayAdapter />
|
||||||
{children}
|
{children}
|
||||||
</QueryProvider>
|
</QueryProvider>
|
||||||
|
|||||||
8
src/components/providers/ReserveNotificationSync.tsx
Normal file
8
src/components/providers/ReserveNotificationSync.tsx
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useReserveNotification } from "@/hooks/useReserveNotification";
|
||||||
|
|
||||||
|
export function ReserveNotificationSync() {
|
||||||
|
useReserveNotification();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -24,7 +24,7 @@ const getResultColumns = (resultCodeArray: ResultCode[], surveys: ProjectSurvey[
|
|||||||
|
|
||||||
const formatResult = (
|
const formatResult = (
|
||||||
result?: ListResultBase,
|
result?: ListResultBase,
|
||||||
options?: { resultType?: ResultCodeType; showCount?: boolean },
|
options?: { resultType?: ResultCodeType; showCount?: boolean; showDate?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const lastResultCd = result?.lastResultCd;
|
const lastResultCd = result?.lastResultCd;
|
||||||
if (lastResultCd === undefined) return "";
|
if (lastResultCd === undefined) return "";
|
||||||
@@ -33,6 +33,7 @@ const getResultColumns = (resultCodeArray: ResultCode[], surveys: ProjectSurvey[
|
|||||||
options?.resultType !== undefined ? labelByTypeCode.get(`${options.resultType}:${lastResultCd}`) ?? "" : "";
|
options?.resultType !== undefined ? labelByTypeCode.get(`${options.resultType}:${lastResultCd}`) ?? "" : "";
|
||||||
const label = result?.lastResultViewLabel || fallbackLabel;
|
const label = result?.lastResultViewLabel || fallbackLabel;
|
||||||
const showCount = options?.showCount ?? true;
|
const showCount = options?.showCount ?? true;
|
||||||
|
const showDate = options?.showDate ?? true;
|
||||||
const count = result?.attemptCount ?? 0;
|
const count = result?.attemptCount ?? 0;
|
||||||
const resultText = showCount ? `${lastResultCd}. ${label} (${count}회)` : `${lastResultCd}. ${label}`;
|
const resultText = showCount ? `${lastResultCd}. ${label} (${count}회)` : `${lastResultCd}. ${label}`;
|
||||||
const dt = result?.lastResultDt ? formatKst(result.lastResultDt, "dateHourMin") : "";
|
const dt = result?.lastResultDt ? formatKst(result.lastResultDt, "dateHourMin") : "";
|
||||||
@@ -40,7 +41,7 @@ const getResultColumns = (resultCodeArray: ResultCode[], surveys: ProjectSurvey[
|
|||||||
return (
|
return (
|
||||||
<div className="leading-tight">
|
<div className="leading-tight">
|
||||||
<div>{resultText}</div>
|
<div>{resultText}</div>
|
||||||
{dt && <div>({dt})</div>}
|
{showDate && dt && <div>({dt})</div>}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -65,7 +66,20 @@ const getResultColumns = (resultCodeArray: ResultCode[], surveys: ProjectSurvey[
|
|||||||
header: "컨택 결과",
|
header: "컨택 결과",
|
||||||
accessorFn: (row) => (row.contactResult as ListContactResult | undefined)?.lastResultCd ?? null,
|
accessorFn: (row) => (row.contactResult as ListContactResult | undefined)?.lastResultCd ?? null,
|
||||||
cell: ({ row }) =>
|
cell: ({ row }) =>
|
||||||
formatResult(row.original.contactResult as ListContactResult | undefined, { resultType: ResultCodeType.CONTACT }),
|
formatResult(row.original.contactResult as ListContactResult | undefined, {
|
||||||
|
resultType: ResultCodeType.CONTACT,
|
||||||
|
showDate: false,
|
||||||
|
}),
|
||||||
|
enableSorting: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "result-date-contact",
|
||||||
|
header: "컨택 일자",
|
||||||
|
accessorFn: (row) => (row.contactResult as ListContactResult | undefined)?.lastResultDt ?? null,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const lastResultDt = (row.original.contactResult as ListContactResult | undefined)?.lastResultDt;
|
||||||
|
return lastResultDt ? formatKst(lastResultDt, "dateHourMin") : "";
|
||||||
|
},
|
||||||
enableSorting: true,
|
enableSorting: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -108,9 +122,10 @@ const getResultColumns = (resultCodeArray: ResultCode[], surveys: ProjectSurvey[
|
|||||||
|
|
||||||
const resultColumnOrder = new Map([
|
const resultColumnOrder = new Map([
|
||||||
["result-contact", 0],
|
["result-contact", 0],
|
||||||
["result-interview", 1],
|
["result-date-contact", 1],
|
||||||
["mailSendResult", 3],
|
["result-interview", 2],
|
||||||
["smsSendResult", 4],
|
["mailSendResult", 4],
|
||||||
|
["smsSendResult", 5],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return columns.sort((a, b) => (resultColumnOrder.get(a.id ?? "") ?? 2) - (resultColumnOrder.get(b.id ?? "") ?? 2));
|
return columns.sort((a, b) => (resultColumnOrder.get(a.id ?? "") ?? 2) - (resultColumnOrder.get(b.id ?? "") ?? 2));
|
||||||
|
|||||||
@@ -5,62 +5,81 @@ import { formatKst } from "@kri/common";
|
|||||||
import {cn} from "@/lib/utils";
|
import {cn} from "@/lib/utils";
|
||||||
import {PROJECT_STATUS_CLASS, PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
import {PROJECT_STATUS_CLASS, PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
||||||
import {ItrntUserInfo} from "@/types/user";
|
import {ItrntUserInfo} from "@/types/user";
|
||||||
|
import type {MouseEvent} from "react";
|
||||||
|
|
||||||
export const getProjectColumns = (
|
export const getProjectColumns = (
|
||||||
users:ItrntUserInfo[],
|
users:ItrntUserInfo[],
|
||||||
groupCodeLabelMap: Map<string, string> = new Map(),
|
groupCodeLabelMap: Map<string, string> = new Map(),
|
||||||
): ColumnDef<ProjectInfo>[] => [
|
onNavigateToInfo?: (projectInfo: ProjectInfo) => void,
|
||||||
{
|
): ColumnDef<ProjectInfo>[] => {
|
||||||
accessorKey: "prjctIdx",
|
// 진행 상태/담당 그룹/담당 실사/등록일 셀은 행 클릭(list/manage)과 분기해 project/info로 이동시킨다.
|
||||||
header: "No",
|
const handleInfoCellClick = (e: MouseEvent, projectInfo: ProjectInfo) => {
|
||||||
enableSorting: true,
|
if (!onNavigateToInfo) return;
|
||||||
},
|
e.stopPropagation();
|
||||||
{
|
onNavigateToInfo(projectInfo);
|
||||||
accessorKey: "prjctCd",
|
};
|
||||||
header: "프로젝트 코드",
|
// DataTable의 body row td 패딩(px-2 py-1)만큼 음수 마진/확장으로 채워서, 클릭 영역을 셀 패딩까지 포함한 전체로 넓힌다.
|
||||||
enableSorting: true,
|
const infoCellClass = "flex h-[calc(100%+0.5rem)] w-[calc(100%+1rem)] -mx-2 -my-1 items-center px-2 cursor-pointer";
|
||||||
meta: {
|
|
||||||
maxWidth: 180
|
return [
|
||||||
|
{
|
||||||
|
accessorKey: "prjctIdx",
|
||||||
|
header: "No",
|
||||||
|
enableSorting: true,
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
{
|
accessorKey: "prjctCd",
|
||||||
accessorKey: "prjctName",
|
header: "프로젝트 코드",
|
||||||
header: "프로젝트 명",
|
enableSorting: true,
|
||||||
enableSorting: true,
|
meta: {
|
||||||
meta: {
|
maxWidth: 180
|
||||||
maxWidth: 1000
|
},
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
{
|
accessorKey: "prjctName",
|
||||||
accessorKey: "prjctStatus",
|
header: "프로젝트 명",
|
||||||
header: "진행 상태",
|
enableSorting: true,
|
||||||
cell: ({row}) => (
|
meta: {
|
||||||
<Badge className={cn("w-15 h-7 my-1.5", PROJECT_STATUS_CLASS[row.original.prjctStatus])}>
|
maxWidth: 1000
|
||||||
{PROJECT_STATUS_LABEL[row.original.prjctStatus]}
|
},
|
||||||
</Badge>
|
},
|
||||||
) ,
|
{
|
||||||
enableSorting: true,
|
accessorKey: "prjctStatus",
|
||||||
},
|
header: "진행 상태",
|
||||||
{
|
cell: ({row}) => (
|
||||||
accessorKey: "ownerDept",
|
<div className={infoCellClass} onClick={(e) => handleInfoCellClick(e, row.original)}>
|
||||||
header: "담당 그룹",
|
<Badge className={cn("w-15 h-7 my-1.5", PROJECT_STATUS_CLASS[row.original.prjctStatus])}>
|
||||||
enableSorting: true,
|
{PROJECT_STATUS_LABEL[row.original.prjctStatus]}
|
||||||
cell: ({row}) => (
|
</Badge>
|
||||||
groupCodeLabelMap.get(row.original.ownerDept) ?? row.original.ownerDept
|
</div>
|
||||||
),
|
) ,
|
||||||
},
|
enableSorting: true,
|
||||||
{
|
},
|
||||||
accessorKey: "ownerFw",
|
{
|
||||||
header: "담당 실사",
|
accessorKey: "ownerDept",
|
||||||
enableSorting: true,
|
header: "담당 그룹",
|
||||||
cell: ({row}) => (
|
enableSorting: true,
|
||||||
users.find(u => u.userId === row.original.ownerFw)?.userNm ?? ""
|
cell: ({row}) => (
|
||||||
) ,
|
<div className={infoCellClass} onClick={(e) => handleInfoCellClick(e, row.original)}>
|
||||||
},
|
{groupCodeLabelMap.get(row.original.ownerDept) ?? row.original.ownerDept}
|
||||||
{
|
</div>
|
||||||
accessorKey: "regDt",
|
),
|
||||||
header: "등록일",
|
},
|
||||||
cell: ({row}) => (formatKst(row.original.regDt ?? "", "date")),
|
{
|
||||||
enableSorting: true,
|
accessorKey: "ownerFw",
|
||||||
}
|
header: "담당 실사",
|
||||||
];
|
enableSorting: true,
|
||||||
|
cell: ({row}) => (
|
||||||
|
<div className={infoCellClass} onClick={(e) => handleInfoCellClick(e, row.original)}>
|
||||||
|
{users.find(u => u.userId === row.original.ownerFw)?.userNm ?? ""}
|
||||||
|
</div>
|
||||||
|
) ,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "regDt",
|
||||||
|
header: "등록일",
|
||||||
|
cell: ({row}) => (formatKst(row.original.regDt ?? "", "date")),
|
||||||
|
enableSorting: true,
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|||||||
@@ -14,4 +14,5 @@ export const ALLOWED_PW_SPECIALS_TEXT = `~ ! @ # $ % ^ & * ( ) _ + - = { } [ ] :
|
|||||||
// 비밀번호에 허용된 문자만 사용했는지
|
// 비밀번호에 허용된 문자만 사용했는지
|
||||||
export const ONLY_ALLOWED_PW_REGEX = /^[A-Za-z\d~!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]+$/
|
export const ONLY_ALLOWED_PW_REGEX = /^[A-Za-z\d~!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]+$/
|
||||||
// 영문 1개 이상 + 숫자 1개 이상 포함, 8~20자, 허용된 문자만 사용
|
// 영문 1개 이상 + 숫자 1개 이상 포함, 8~20자, 허용된 문자만 사용
|
||||||
export const KRI_PW_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]{8,20}$/
|
//export const KRI_PW_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]{1,20}$/
|
||||||
|
export const KRI_PW_REGEX = /^[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]{1,20}$/
|
||||||
|
|||||||
85
src/hooks/useReserveNotification.tsx
Normal file
85
src/hooks/useReserveNotification.tsx
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { X } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
|
import { useDialog } from "@/hooks/useDialog";
|
||||||
|
import { fetchReserveNotifications } from "@/query/reserve";
|
||||||
|
|
||||||
|
const FIVE_MINUTES_MS = 5 * 60_000;
|
||||||
|
const RESERVE_NOTIFICATION_TOAST_ID = "reserve-notification";
|
||||||
|
|
||||||
|
// 예약은 5분 단위로만 등록되므로, 5분 정각(0,5,10,...)에 맞춰 조회해야 창을 놓치지 않는다.
|
||||||
|
const msUntilNextFiveMinuteMark = (now: Date) => {
|
||||||
|
const next = new Date(now);
|
||||||
|
const minutesToNext = 5 - (now.getMinutes() % 5);
|
||||||
|
next.setMinutes(now.getMinutes() + minutesToNext, 0, 0);
|
||||||
|
return next.getTime() - now.getTime();
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useReserveNotification() {
|
||||||
|
const { auth } = useAuth();
|
||||||
|
const { showDialog } = useDialog();
|
||||||
|
const userId = auth.user?.userId ?? "";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!userId) return;
|
||||||
|
|
||||||
|
let intervalId: ReturnType<typeof setInterval> | undefined;
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
|
const showNotification = () => {
|
||||||
|
toast.custom(
|
||||||
|
(id) => (
|
||||||
|
<div
|
||||||
|
className="flex w-[360px] cursor-pointer items-start justify-between gap-3 rounded-lg border border-amber-500 bg-amber-100 p-4 text-amber-900 shadow-md"
|
||||||
|
onClick={() => {
|
||||||
|
toast.dismiss(id);
|
||||||
|
showDialog("reserveSearchDialog");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span className="text-base font-bold">5분 이내에 예약된 내용이 있습니다.</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="닫기"
|
||||||
|
className="shrink-0 cursor-pointer rounded-full p-1 text-amber-900/70 hover:bg-amber-200 hover:text-amber-900"
|
||||||
|
onClick={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
toast.dismiss(id);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<X className="size-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
{ id: RESERVE_NOTIFICATION_TOAST_ID, duration: Infinity },
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const poll = async (requestPast: boolean) => {
|
||||||
|
try {
|
||||||
|
const reservations = await fetchReserveNotifications(userId, requestPast);
|
||||||
|
if (cancelled || reservations.length === 0) return;
|
||||||
|
|
||||||
|
showNotification();
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[reserve-notification] 예약 알림 조회 실패", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
void poll(true);
|
||||||
|
|
||||||
|
const alignTimeoutId = setTimeout(() => {
|
||||||
|
if (cancelled) return;
|
||||||
|
void poll(false);
|
||||||
|
intervalId = setInterval(() => void poll(false), FIVE_MINUTES_MS);
|
||||||
|
}, msUntilNextFiveMinuteMark(new Date()));
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
clearTimeout(alignTimeoutId);
|
||||||
|
if (intervalId) clearInterval(intervalId);
|
||||||
|
};
|
||||||
|
}, [userId, showDialog]);
|
||||||
|
}
|
||||||
@@ -2,3 +2,16 @@
|
|||||||
// 값이 없는 토큰은 빈 문자열로 치환한다.
|
// 값이 없는 토큰은 빈 문자열로 치환한다.
|
||||||
export const substituteVariables = (contents: string, values: Record<string, string>) =>
|
export const substituteVariables = (contents: string, values: Record<string, string>) =>
|
||||||
contents.replace(/\[\$([^\]]+)\]/g, (_, key: string) => values[key] ?? "");
|
contents.replace(/\[\$([^\]]+)\]/g, (_, key: string) => values[key] ?? "");
|
||||||
|
|
||||||
|
export const escapeHtml = (value: string) =>
|
||||||
|
value.replace(
|
||||||
|
/[&<>"']/g,
|
||||||
|
(character) =>
|
||||||
|
({
|
||||||
|
'&': '&',
|
||||||
|
'<': '<',
|
||||||
|
'>': '>',
|
||||||
|
'"': '"',
|
||||||
|
"'": ''',
|
||||||
|
})[character] ?? character,
|
||||||
|
);
|
||||||
@@ -2,15 +2,27 @@
|
|||||||
|
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { nextApi } from "@/lib/http-client";
|
import { nextApi } from "@/lib/http-client";
|
||||||
|
import { qk } from "@/query/key/keys";
|
||||||
import type { ListAssignRequest, ListAssignResetRequest } from "@/types/list";
|
import type { ListAssignRequest, ListAssignResetRequest } from "@/types/list";
|
||||||
|
|
||||||
|
const invalidateAssignSummaries = (qc: ReturnType<typeof useQueryClient>, prjctIdx: number) =>
|
||||||
|
Promise.all([
|
||||||
|
qc.invalidateQueries({ queryKey: qk.projectAssignCmpnSummary(prjctIdx) }),
|
||||||
|
qc.invalidateQueries({ queryKey: ["assign", "prjct-fieldwork-summary", prjctIdx] }),
|
||||||
|
]);
|
||||||
|
|
||||||
export function useUpsertListAssignMutation(prjctIdx: number) {
|
export function useUpsertListAssignMutation(prjctIdx: number) {
|
||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: ({ assignId, request }: { assignId: string; request: ListAssignRequest }) =>
|
mutationFn: ({ assignId, request }: { assignId: string; request: ListAssignRequest }) =>
|
||||||
nextApi.put<number>(`/assign/list/${prjctIdx}/${encodeURIComponent(assignId)}`, request),
|
nextApi.put<number>(`/assign/list/${prjctIdx}/${encodeURIComponent(assignId)}`, request),
|
||||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["list", "search-filter"] }),
|
onSuccess: async () => {
|
||||||
|
await Promise.all([
|
||||||
|
qc.invalidateQueries({ queryKey: ["list", "search-filter"] }),
|
||||||
|
invalidateAssignSummaries(qc, prjctIdx),
|
||||||
|
]);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -20,6 +32,11 @@ export function useResetListAssignMutation(prjctIdx: number) {
|
|||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (request: ListAssignResetRequest) =>
|
mutationFn: (request: ListAssignResetRequest) =>
|
||||||
nextApi.del<number>(`/assign/list/reset/${prjctIdx}`, { json: request }),
|
nextApi.del<number>(`/assign/list/reset/${prjctIdx}`, { json: request }),
|
||||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["list", "search-filter"] }),
|
onSuccess: async () => {
|
||||||
|
await Promise.all([
|
||||||
|
qc.invalidateQueries({ queryKey: ["list", "search-filter"] }),
|
||||||
|
invalidateAssignSummaries(qc, prjctIdx),
|
||||||
|
]);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ export const qk = {
|
|||||||
/********** 배정 관련 **********/
|
/********** 배정 관련 **********/
|
||||||
projectAssignFieldwork: (prjctIdx: number) => ["assign", "prjct-fieldwork", prjctIdx] as const,
|
projectAssignFieldwork: (prjctIdx: number) => ["assign", "prjct-fieldwork", prjctIdx] as const,
|
||||||
projectAssignCmpn: (prjctIdx: number) => ["assign", "prjct-cmpn", prjctIdx] as const,
|
projectAssignCmpn: (prjctIdx: number) => ["assign", "prjct-cmpn", prjctIdx] as const,
|
||||||
|
projectAssignCmpnSummary: (prjctIdx: number) => ["assign", "prjct-cmpn-summary", prjctIdx] as const,
|
||||||
|
projectAssignFieldworkSummary: (prjctIdx: number, assignType: number, cmpnIds: string[]) =>
|
||||||
|
["assign", "prjct-fieldwork-summary", prjctIdx, assignType, [...cmpnIds].sort()] as const,
|
||||||
/********** 배정 관련 **********/
|
/********** 배정 관련 **********/
|
||||||
|
|
||||||
/********** KON, KIWI 프로젝트 관련 KART에서 받아옴 **********/
|
/********** KON, KIWI 프로젝트 관련 KART에서 받아옴 **********/
|
||||||
@@ -58,9 +61,13 @@ export const qk = {
|
|||||||
listEventHistory: (prjctIdx: number, sid: string) => ["list", "event-history", prjctIdx, sid] as const,
|
listEventHistory: (prjctIdx: number, sid: string) => ["list", "event-history", prjctIdx, sid] as const,
|
||||||
listUpdateHistory: (prjctIdx: number, sid: string) => ["list", "update-history", prjctIdx, sid] as const,
|
listUpdateHistory: (prjctIdx: number, sid: string) => ["list", "update-history", prjctIdx, sid] as const,
|
||||||
listReserveBySid: (prjctIdx: number, sid: string) => ["list", "reserve", "sid", prjctIdx, sid] as const,
|
listReserveBySid: (prjctIdx: number, sid: string) => ["list", "reserve", "sid", prjctIdx, sid] as const,
|
||||||
listReserveByUser: (prjctIdx: number, userId: string) => ["list", "reserve", "user", prjctIdx, userId] as const,
|
|
||||||
/********** 리스트 관련 **********/
|
/********** 리스트 관련 **********/
|
||||||
|
|
||||||
|
/********** 예약 알림 관련 **********/
|
||||||
|
reserveSearch: (userId: string, fromDt: string, toDt: string) =>
|
||||||
|
["reserve", "search", userId, fromDt, toDt] as const,
|
||||||
|
/********** 예약 알림 관련 **********/
|
||||||
|
|
||||||
/********** 템플릿 및 발송 관련 **********/
|
/********** 템플릿 및 발송 관련 **********/
|
||||||
mainTemplate: (prjctIdx: number, chnnlTy: ChannelType) =>
|
mainTemplate: (prjctIdx: number, chnnlTy: ChannelType) =>
|
||||||
["project", "main-template", prjctIdx, chnnlTy] as const,
|
["project", "main-template", prjctIdx, chnnlTy] as const,
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ const serializeListSearchRequest = (request: ListSearchRequest) => ({
|
|||||||
[ResultCodeType.INTERVIEW]: [],
|
[ResultCodeType.INTERVIEW]: [],
|
||||||
},
|
},
|
||||||
surveyResultConditions: request.listFilter.surveyResultConditions ?? [],
|
surveyResultConditions: request.listFilter.surveyResultConditions ?? [],
|
||||||
|
...(request.listFilter.lastEventDateRange?.length
|
||||||
|
? { lastEventDateRange: request.listFilter.lastEventDateRange }
|
||||||
|
: {}),
|
||||||
memoConditions: request.listFilter.memoConditions ?? [],
|
memoConditions: request.listFilter.memoConditions ?? [],
|
||||||
otherItemConditions: request.listFilter.otherItemConditions ?? [],
|
otherItemConditions: request.listFilter.otherItemConditions ?? [],
|
||||||
},
|
},
|
||||||
@@ -122,26 +125,15 @@ export function useListReserveBySidQuery(prjctIdx: number, sid: string, enabled:
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useListReserveByUserQuery(prjctIdx: number, userId: string, enabled: boolean) {
|
|
||||||
return useQuery({
|
|
||||||
queryKey: qk.listReserveByUser(prjctIdx, userId),
|
|
||||||
queryFn: () => nextApi.get<ListReserve[]>(`/reserve/user/${prjctIdx}/${userId}`),
|
|
||||||
enabled,
|
|
||||||
staleTime: 0,
|
|
||||||
refetchOnMount: "always",
|
|
||||||
meta: { ignoreGlobalLoading: true },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useReserveMutation(prjctIdx: number, sid: string) {
|
export function useReserveMutation(prjctIdx: number, sid: string) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (request: ListReserveRequest) => nextApi.put<ListReserve>(`/reserve`, request),
|
mutationFn: (request: ListReserveRequest) => nextApi.put<ListReserve>(`/reserve`, request),
|
||||||
onSuccess: async (_result, request) => {
|
onSuccess: async () => {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
queryClient.invalidateQueries({ queryKey: qk.listReserveBySid(prjctIdx, sid) }),
|
queryClient.invalidateQueries({ queryKey: qk.listReserveBySid(prjctIdx, sid) }),
|
||||||
queryClient.invalidateQueries({ queryKey: qk.listReserveByUser(prjctIdx, request.userId) }),
|
queryClient.invalidateQueries({ queryKey: ["reserve", "search"] }),
|
||||||
]);
|
]);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -260,6 +252,20 @@ export function useAddListEventMutation(prjctIdx: number, sid: string) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useDeleteListEventMutation(prjctIdx: number, sid: string) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (listEventHistIdx: number) => nextApi.del<void>(`/list-hist/event/${listEventHistIdx}`),
|
||||||
|
onSuccess: async () => {
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({ queryKey: qk.listDetail(prjctIdx, sid) }),
|
||||||
|
queryClient.invalidateQueries({ queryKey: qk.listEventHistory(prjctIdx, sid) }),
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function useDownloadListMutation(prjctIdx: number) {
|
export function useDownloadListMutation(prjctIdx: number) {
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (listFilter: ListFilter) =>
|
mutationFn: (listFilter: ListFilter) =>
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import type {
|
|||||||
ProjectListRequest,
|
ProjectListRequest,
|
||||||
ProjectOwnerResponse, ProjectUpdateRequest, ResultCode
|
ProjectOwnerResponse, ProjectUpdateRequest, ResultCode
|
||||||
} from "@/types/project";
|
} from "@/types/project";
|
||||||
|
import type { ListHeaderAssignType, ProjectCompanyAssignSummary, ProjectFieldworkAssignSummary } from "@/types/list";
|
||||||
import type { PageRequest, PageResponse } from "@kri/common";
|
import type { PageRequest, PageResponse } from "@kri/common";
|
||||||
|
|
||||||
export function useProjectOwnerListQuery(enabled: boolean = true) {
|
export function useProjectOwnerListQuery(enabled: boolean = true) {
|
||||||
@@ -166,6 +167,41 @@ export function useAssignedFieldworkIdsQuery(prjctIdx: number, enabled: boolean)
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 프로젝트의 외주사별 배정 현황(총 개수/미배정 개수/외주사별 배정 개수)
|
||||||
|
*/
|
||||||
|
export function useAssignedCmpnSummaryQuery(prjctIdx: number, enabled: boolean) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: qk.projectAssignCmpnSummary(prjctIdx),
|
||||||
|
queryFn: () => nextApi.get<ProjectCompanyAssignSummary>(`/assign/prjct-cmpn-summary/${prjctIdx}`),
|
||||||
|
enabled,
|
||||||
|
staleTime: 0,
|
||||||
|
refetchOnMount: "always",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 프로젝트의 컨택원/면접원별 배정 현황(총 개수/미배정 개수/사람별 배정 개수)
|
||||||
|
* cmpnIds를 지정하면 해당 외주사 소속 인원 범위로 카운트가 재계산된다(외주사 계정은 서버에서 본인 회사로 강제됨).
|
||||||
|
*/
|
||||||
|
export function useAssignedFieldworkSummaryQuery(
|
||||||
|
prjctIdx: number,
|
||||||
|
assignType: ListHeaderAssignType,
|
||||||
|
cmpnIds: string[],
|
||||||
|
enabled: boolean,
|
||||||
|
) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: qk.projectAssignFieldworkSummary(prjctIdx, assignType, cmpnIds),
|
||||||
|
queryFn: () => {
|
||||||
|
const query = `?assignType=${assignType}${cmpnIds.length > 0 ? `&cmpnIds=${cmpnIds.join(",")}` : ""}`;
|
||||||
|
return nextApi.get<ProjectFieldworkAssignSummary>(`/assign/prjct-fieldwork-summary/${prjctIdx}${query}`);
|
||||||
|
},
|
||||||
|
enabled,
|
||||||
|
staleTime: 0,
|
||||||
|
refetchOnMount: "always",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function useCreateProjectMutation() {
|
export function useCreateProjectMutation() {
|
||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
|
|
||||||
|
|||||||
30
src/query/reserve.ts
Normal file
30
src/query/reserve.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { nextApi } from "@/lib/http-client";
|
||||||
|
import { qk } from "@/query/key/keys";
|
||||||
|
import type { ListReserve } from "@/types/list";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 헤더의 예약 조회 다이얼로그용: 전체 프로젝트 대상, 날짜 range로 조회.
|
||||||
|
*/
|
||||||
|
export function useReserveSearchQuery(userId: string, fromDt: string, toDt: string, enabled: boolean) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: qk.reserveSearch(userId, fromDt, toDt),
|
||||||
|
queryFn: () =>
|
||||||
|
nextApi.get<ListReserve[]>(`/reserve/user/${encodeURIComponent(userId)}/search?fromDt=${fromDt}&toDt=${toDt}`),
|
||||||
|
enabled,
|
||||||
|
staleTime: 0,
|
||||||
|
refetchOnMount: "always",
|
||||||
|
meta: { ignoreGlobalLoading: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 5분 정각 폴링용: react-query 캐시 없이 그때그때 호출한다(useReserveNotification 훅 전용).
|
||||||
|
*/
|
||||||
|
export function fetchReserveNotifications(userId: string, requestPast: boolean) {
|
||||||
|
return nextApi.get<ListReserve[]>(
|
||||||
|
`/reserve/user/${encodeURIComponent(userId)}?requestPast=${requestPast}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -15,5 +15,5 @@ export type DialogId =
|
|||||||
| "messageSendDialog"
|
| "messageSendDialog"
|
||||||
| "messageHistoryDialog"
|
| "messageHistoryDialog"
|
||||||
| "surveyQrDialog"
|
| "surveyQrDialog"
|
||||||
| "reservationListDialog"
|
| "reserveSearchDialog"
|
||||||
| "singleMessageSendDialog";
|
| "singleMessageSendDialog";
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ export enum ListEventHistoryBase {
|
|||||||
LATEST = 2,
|
LATEST = 2,
|
||||||
}
|
}
|
||||||
|
|
||||||
export type FilterOperator = 'eq' | 'neq' | 'contains' | 'notContains' | 'empty' | 'notEmpty';
|
export type FilterOperator = 'eq' | 'neq' | 'contains' | 'notContains' | 'empty' | 'notEmpty' | 'none';
|
||||||
|
|
||||||
export type FilterValueOption = {
|
export type FilterValueOption = {
|
||||||
value: string;
|
value: string;
|
||||||
@@ -57,6 +57,7 @@ export type FilterHeaderOption = {
|
|||||||
id: number;
|
id: number;
|
||||||
label: string;
|
label: string;
|
||||||
allowedOperators: FilterOperator[];
|
allowedOperators: FilterOperator[];
|
||||||
|
defaultOperator: FilterOperator;
|
||||||
valueOptions?: FilterValueOption[];
|
valueOptions?: FilterValueOption[];
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
};
|
};
|
||||||
@@ -120,6 +121,13 @@ export type SurveyResultCondition = {
|
|||||||
resultCodes: number[];
|
resultCodes: number[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export interface LastEventDateRange {
|
||||||
|
resultCodeType: 21 | 22 | 91;
|
||||||
|
prjctSurveyIdx?: number | null;
|
||||||
|
startDate?: string | null;
|
||||||
|
endDate?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export type ListFilter = {
|
export type ListFilter = {
|
||||||
sidSet: string[];
|
sidSet: string[];
|
||||||
listUseSet: ListIsUse[];
|
listUseSet: ListIsUse[];
|
||||||
@@ -128,6 +136,7 @@ export type ListFilter = {
|
|||||||
assignConditions: ListAssignFilterCondition[];
|
assignConditions: ListAssignFilterCondition[];
|
||||||
resultCodeMap: Record<Exclude<ResultCodeType, ResultCodeType.SURVEY>, number[]>;
|
resultCodeMap: Record<Exclude<ResultCodeType, ResultCodeType.SURVEY>, number[]>;
|
||||||
surveyResultConditions: SurveyResultCondition[];
|
surveyResultConditions: SurveyResultCondition[];
|
||||||
|
lastEventDateRange?: LastEventDateRange[];
|
||||||
memoConditions: ListFilterCondition[];
|
memoConditions: ListFilterCondition[];
|
||||||
otherItemConditions: ListOtherItemFilterCondition[];
|
otherItemConditions: ListOtherItemFilterCondition[];
|
||||||
};
|
};
|
||||||
@@ -160,6 +169,7 @@ export type SurveyResultSelections = Record<number, string[]>;
|
|||||||
export type ListSearchUiState = {
|
export type ListSearchUiState = {
|
||||||
searchText: string;
|
searchText: string;
|
||||||
searchContactResult: string[];
|
searchContactResult: string[];
|
||||||
|
searchContactDateRange: { from: string; to: string };
|
||||||
searchInterviewResult: string[];
|
searchInterviewResult: string[];
|
||||||
surveyResultSelections: SurveyResultSelections;
|
surveyResultSelections: SurveyResultSelections;
|
||||||
filterRows: FilterRow[];
|
filterRows: FilterRow[];
|
||||||
@@ -252,6 +262,7 @@ export type ListUpdateHistory = {
|
|||||||
export type ListReserve = {
|
export type ListReserve = {
|
||||||
listResveIdx: number;
|
listResveIdx: number;
|
||||||
prjctIdx: number;
|
prjctIdx: number;
|
||||||
|
prjctName: string;
|
||||||
sid: string;
|
sid: string;
|
||||||
memo?: string;
|
memo?: string;
|
||||||
cnfirm: boolean;
|
cnfirm: boolean;
|
||||||
@@ -310,6 +321,31 @@ export type ListAssignResetRequest = {
|
|||||||
listFilter: ListFilter;
|
listFilter: ListFilter;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type CompanyAssignSummaryItem = {
|
||||||
|
cmpnId: string;
|
||||||
|
cmpnAlias: string;
|
||||||
|
assignedCount: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ProjectCompanyAssignSummary = {
|
||||||
|
totalCount: number;
|
||||||
|
unassignedCount: number;
|
||||||
|
assignees: CompanyAssignSummaryItem[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type FieldworkAssignSummaryItem = {
|
||||||
|
userId: string;
|
||||||
|
userName: string;
|
||||||
|
userCmpn: string;
|
||||||
|
assignedCount: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ProjectFieldworkAssignSummary = {
|
||||||
|
totalCount: number;
|
||||||
|
unassignedCount: number;
|
||||||
|
assignees: FieldworkAssignSummaryItem[];
|
||||||
|
};
|
||||||
|
|
||||||
export type ListResetRequest = {
|
export type ListResetRequest = {
|
||||||
resetMode: ListResetMode;
|
resetMode: ListResetMode;
|
||||||
listFilter: ListFilter;
|
listFilter: ListFilter;
|
||||||
|
|||||||
Reference in New Issue
Block a user