'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, number>> export type BatchEditSurveyResultCodes = Record 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 } const createRow = (headerId: number, value = ''): BatchEditRow => ({ id: crypto.randomUUID(), headerId, value, }) const NO_CHANGE = '__no_change__' const resultCodeGroups: { type: Exclude; 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([]) const [resultCodeSelections, setResultCodeSelections] = useState({}) const [surveyResultSelections, setSurveyResultSelections] = useState({}) const [target, setTarget] = useState('filtered') const [submitting, setSubmitting] = useState(false) const [invalidRowId, setInvalidRowId] = useState(null) const rowInputRefs = useRef>(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, 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 ( 일괄 수정} contentClassName="sm:max-w-[900px]" bodyClassName="space-y-4" footer={ <> } >

적용 대상

결과값 수정

{resultCodeGroups.map((group) => (

{group.label}

))}
{surveys.length > 0 ? (

설문별 결과 수정

{surveys.map((survey) => (

{survey.surveyName}

))}
) : null}

항목값 수정

헤더 수정 값
{rows.map((row) => { const valueOptions = getValueOptions(row.headerId) const isFile = isFileHeader(row.headerId) return (
{isFile ? (

파일 삭제

) : valueOptions !== undefined ? ( 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) ? ( { 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} /> ) : ( { 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} /> )}
) })}
) } export default ListBatchEditDialog