Files
contact-front/src/components/dialog/ListBatchEditDialog.tsx

407 lines
15 KiB
TypeScript

'use client'
import { useEffect, useRef, useState } from 'react'
import { Plus, X } from 'lucide-react'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
import type { FilterValueOption, ListFilterTarget } from '@/types/list'
import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
import { ListHeaderConst, LIST_BATCH_EDIT_FILE_DELETE_VALUE } from '@/const/listConst'
import { COMMON_TEXT_REGEX } from '@/const/validationConst'
import { validateValue } from '@/utils/validation'
import { formatKoreanPhoneNumber } from '@/utils/phone'
export type BatchEditOption = {
id: number
label: string
listHderTy: number
valueOptions?: FilterValueOption[]
}
export type BatchEditRow = {
id: string
headerId: number
value: string
}
export type BatchEditResultCodes = Partial<Record<Exclude<ResultCodeType, ResultCodeType.SURVEY>, number>>
export type BatchEditSurveyResultCodes = Record<number, number>
export type BatchEditPayload = {
rows: BatchEditRow[]
resultCodes: BatchEditResultCodes
surveyResultCodes: { prjctSurveyIdx: number; resultCd: number }[]
target: ListFilterTarget
}
export type ListBatchEditDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
headerOptions: BatchEditOption[]
resultCodes: ResultCode[]
surveys: ProjectSurvey[]
selectedSids: string[]
filterSummary?: string[]
initialRows?: BatchEditRow[]
initialResultCodes?: BatchEditResultCodes
initialSurveyResultCodes?: BatchEditSurveyResultCodes
onConfirm: (payload: BatchEditPayload) => void | Promise<void>
}
const createRow = (headerId: number, value = ''): BatchEditRow => ({
id: crypto.randomUUID(),
headerId,
value,
})
const NO_CHANGE = '__no_change__'
const resultCodeGroups: { type: Exclude<ResultCodeType, ResultCodeType.SURVEY>; label: string }[] = [
{ type: ResultCodeType.CONTACT, label: '컨택 결과' },
{ type: ResultCodeType.INTERVIEW, label: '면접 결과' },
]
const ListBatchEditDialog = ({
dialogId = 'listBatchEditDialog',
open,
onOpenChange,
headerOptions,
resultCodes,
surveys,
selectedSids,
filterSummary,
initialRows = [],
initialResultCodes = {},
initialSurveyResultCodes = {},
onConfirm,
}: ListBatchEditDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [rows, setRows] = useState<BatchEditRow[]>([])
const [resultCodeSelections, setResultCodeSelections] = useState<BatchEditResultCodes>({})
const [surveyResultSelections, setSurveyResultSelections] = useState<BatchEditSurveyResultCodes>({})
const [target, setTarget] = useState<ListFilterTarget>('filtered')
const [submitting, setSubmitting] = useState(false)
const [invalidRowId, setInvalidRowId] = useState<string | null>(null)
const rowInputRefs = useRef<Map<string, HTMLInputElement>>(new Map())
const resolvedOpen = open ?? isDialogOpen(dialogId)
const defaultHeaderId = headerOptions[0]?.id ?? 0
const isFileHeader = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.listHderTy === ListHeaderConst.FILE
const isTelHeader = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.listHderTy === ListHeaderConst.TEL_NUM
useEffect(() => {
if (!resolvedOpen) return
if (initialRows.length > 0) {
setRows(initialRows.map((row) => ({ ...row })))
} else {
setRows([])
}
setResultCodeSelections({ ...initialResultCodes })
setSurveyResultSelections({ ...initialSurveyResultCodes })
setTarget('filtered')
setInvalidRowId(null)
}, [resolvedOpen, initialRows, initialResultCodes, initialSurveyResultCodes])
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
const handleAddRow = () => {
if (defaultHeaderId <= 0) return
setRows((prev) => [...prev, createRow(defaultHeaderId, isFileHeader(defaultHeaderId) ? LIST_BATCH_EDIT_FILE_DELETE_VALUE : '')])
}
const handleRemoveRow = (id: string) => {
setRows((prev) => prev.filter((row) => row.id !== id))
}
const handleChangeHeader = (id: string, headerId: number) => {
const value = isFileHeader(headerId) ? LIST_BATCH_EDIT_FILE_DELETE_VALUE : ''
setRows((prev) => prev.map((row) => (row.id === id ? { ...row, headerId, value } : row)))
}
const getValueOptions = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.valueOptions
const handleChangeValue = (id: string, value: string) => {
setRows((prev) => prev.map((row) => (row.id === id ? { ...row, value } : row)))
}
const handleChangeResultCode = (type: Exclude<ResultCodeType, ResultCodeType.SURVEY>, value: string) => {
setResultCodeSelections((prev) => {
if (value === NO_CHANGE) {
const next = { ...prev }
delete next[type]
return next
}
return { ...prev, [type]: Number(value) }
})
}
const handleChangeSurveyResultCode = (prjctSurveyIdx: number, value: string) => {
setSurveyResultSelections((prev) => {
if (value === NO_CHANGE) {
const next = { ...prev }
delete next[prjctSurveyIdx]
return next
}
return { ...prev, [prjctSurveyIdx]: Number(value) }
})
}
const handleConfirm = async () => {
setInvalidRowId(null)
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
const normalized = rows.filter((row) => row.headerId > 0 && row.value.trim().length > 0)
const surveyResultCodes = Object.entries(surveyResultSelections).map(([prjctSurveyIdx, resultCd]) => ({
prjctSurveyIdx: Number(prjctSurveyIdx),
resultCd,
}))
const hasResultCodeChange = Object.keys(resultCodeSelections).length > 0 || surveyResultCodes.length > 0
if (normalized.length === 0 && !hasResultCodeChange) {
alert('일괄 수정할 항목을 입력해주세요.')
return
}
// 직접 값을 타이핑하는 행(선택형/파일 삭제가 아닌 행)만 형식을 검증한다.
for (const row of normalized) {
const isFreeTextRow = !isFileHeader(row.headerId) && getValueOptions(row.headerId) === undefined
if (!isFreeTextRow) continue
const valueCheck = validateValue(row.value, {
maxLength: 2048,
pattern: COMMON_TEXT_REGEX,
patternMessage: '수정 값에 허용되지 않는 문자가 포함되어 있습니다.',
})
if (!valueCheck.valid) {
alert(valueCheck.message)
setInvalidRowId(row.id)
rowInputRefs.current.get(row.id)?.focus()
return
}
}
setSubmitting(true)
try {
await onConfirm({ rows: normalized, resultCodes: resultCodeSelections, surveyResultCodes, target })
handleOpenChange(false)
} finally {
setSubmitting(false)
}
}
return (
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">일괄 수정</span>}
contentClassName="sm:max-w-[900px]"
bodyClassName="space-y-4"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
적용
</Button>
</>
}
>
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">적용 대상</p>
<ApplyFilterOption
value={target}
onValueChange={setTarget}
idPrefix="batch-edit-target"
selectedSids={selectedSids}
filterSummary={filterSummary}
/>
</div>
<div className="rounded-md border p-4 space-y-3">
<p className="font-semibold text-sm">결과값 수정</p>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
{resultCodeGroups.map((group) => (
<div key={group.type} className="space-y-1">
<p className="text-sm text-muted-foreground">{group.label}</p>
<Select
value={
resultCodeSelections[group.type] !== undefined
? String(resultCodeSelections[group.type])
: NO_CHANGE
}
onValueChange={(v) => handleChangeResultCode(group.type, v)}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="변경 안함" />
</SelectTrigger>
<SelectContent>
<SelectItem value={NO_CHANGE}>변경 안함</SelectItem>
{resultCodes
.filter((code) => code.resultCdTy === group.type && code.resultCd !== 0)
.map((code) => (
<SelectItem key={code.resultCdUUID} value={String(code.resultCd)}>
{code.resultCdLbl}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
))}
</div>
</div>
{surveys.length > 0 ? (
<div className="rounded-md border p-4 space-y-3">
<p className="font-semibold text-sm">설문별 결과 수정</p>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
{surveys.map((survey) => (
<div key={survey.prjctSurveyIdx} className="space-y-1">
<p className="text-sm text-muted-foreground">{survey.surveyName}</p>
<Select
value={
survey.prjctSurveyIdx != null && surveyResultSelections[survey.prjctSurveyIdx] !== undefined
? String(surveyResultSelections[survey.prjctSurveyIdx])
: NO_CHANGE
}
onValueChange={(v) => survey.prjctSurveyIdx != null && handleChangeSurveyResultCode(survey.prjctSurveyIdx, v)}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="변경 안함" />
</SelectTrigger>
<SelectContent>
<SelectItem value={NO_CHANGE}>변경 안함</SelectItem>
{resultCodes
.filter((code) => code.resultCdTy === ResultCodeType.SURVEY && code.resultCd !== 0)
.map((code) => (
<SelectItem key={code.resultCdUUID} value={String(code.resultCd)}>
{code.resultCdLbl}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
))}
</div>
</div>
) : null}
<p className="font-semibold text-sm">항목값 수정</p>
<div className="rounded-md border overflow-hidden">
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[1fr_2fr_64px] items-center text-sm font-semibold">
<span>헤더</span>
<span>수정 값</span>
<span />
</div>
<div className="max-h-72 overflow-auto">
{rows.map((row) => {
const valueOptions = getValueOptions(row.headerId)
const isFile = isFileHeader(row.headerId)
return (
<div
key={row.id}
className="h-12 px-4 border-b last:border-b-0 grid grid-cols-[1fr_2fr_64px] items-center gap-2"
>
<Select
value={String(row.headerId)}
onValueChange={(v) => handleChangeHeader(row.id, Number(v))}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="헤더 선택" />
</SelectTrigger>
<SelectContent>
{headerOptions.map((option) => (
<SelectItem key={option.id} value={String(option.id)}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
{isFile ? (
<p className="text-sm font-bold text-red-600">파일 삭제</p>
) : valueOptions !== undefined ? (
<KriSingleSelect
items={valueOptions}
value={row.value}
onChange={(value) => handleChangeValue(row.id, value)}
getValue={(item) => item.value}
getLabel={(item) => item.label}
placeholder="값 선택"
heightClassName="h-9"
widthClassName="w-full"
className="w-full"
/>
) : isTelHeader(row.headerId) ? (
<Input
ref={(el) => {
if (el) rowInputRefs.current.set(row.id, el)
else rowInputRefs.current.delete(row.id)
}}
value={formatKoreanPhoneNumber(row.value)}
onChange={(e) => handleChangeValue(row.id, e.target.value.replace(/\D/g, ''))}
placeholder="수정할 값을 입력해주세요"
aria-invalid={invalidRowId === row.id}
/>
) : (
<Input
ref={(el) => {
if (el) rowInputRefs.current.set(row.id, el)
else rowInputRefs.current.delete(row.id)
}}
value={row.value}
onChange={(e) => handleChangeValue(row.id, e.target.value)}
placeholder="수정할 값을 입력해주세요"
aria-invalid={invalidRowId === row.id}
/>
)}
<div className="flex justify-center">
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => handleRemoveRow(row.id)}
aria-label="행 제거"
>
<X className="w-4 h-4" />
</Button>
</div>
</div>
)
})}
</div>
</div>
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
<Plus className="w-4 h-4" />
행 추가
</Button>
</KriDialog>
)
}
export default ListBatchEditDialog