'use client' import { useMemo, useState } from 'react' import { PaginationState, SortingState } from '@tanstack/react-table' import { Download, FileClock, Funnel, Mail, MessageSquareMore, PencilLine, RotateCcw, Upload, } from 'lucide-react' import { Input } from '@/components/ui/input' import { Button } from '@/components/ui/button' import { DataTable } from '@/components/data-table/DataTable' import type { DataTableColumn } from '@/components/data-table/DataTable.type' import { KriMultiSelect } from '@/components/common/KriAutoComplete' import { LoadingOverlay } from '@/components/common/LoadingOverlay' import { useMounted } from "@kri/common/hooks"; import { useAuth } from '@/hooks/useAuth' import { useDialog } from '@/hooks/useDialog' import { useSelectedProject } from '@/hooks/useSelectedProject' import { useDownloadListEventHistoryMutation, useDownloadListExcelTemplateMutation, useDownloadListItemFileMutation, useDownloadListMutation, useDownloadListUpdateHistoryMutation, useDownloadUploadHistoryFileMutation, useListHeaderQuery, useListSearchQuery, useListUploadHistoryQuery, useResetListMutation, useUpdateListHeaderMutation, useUpdateListMutation, useUploadListExcelMutation, } from '@/query/list' import { useResultCodesQuery } from '@/query/project' import { getListColumns, ListTableRow } from '@/components/table-column/ListTableColumn' import { createEmptyListFilter, FilterRow, ListEventHistoryBase, ListDownloadMode, ListDownloadPayload, listHeader, ListFilterMatchType, ListFilterOperator, ListFilterTarget, ListOtherItemFilterCondition, ListResetMode, ListResetScope, ListSearchRequest, ListUploadRequest, } from '@/types/list' import { ResultCode, ResultCodeType } from '@/types/project' import ListResetDialog from '@/components/dialog/ListResetDialog' import ListUploadDialog from '@/components/dialog/ListUploadDialog' import ListHeaderManageDialog from '@/components/dialog/ListHeaderManageDialog' import ListBatchEditDialog, { BatchEditRow } from '@/components/dialog/ListBatchEditDialog' import ListFilterDialog from '@/components/dialog/ListFilterDialog' import ListDownloadDialog from '@/components/dialog/ListDownloadDialog' import MessageSendDialog, { MessageSendMode, MessageSendPayload, MessageTemplateOption, } from '@/components/dialog/MessageSendDialog' import MessageHistoryDialog, { MessageHistoryRow } from '@/components/dialog/MessageHistoryDialog' import { downloadBase64File, downloadFile, XLSX_MIME_TYPE } from '@kri/common/browser' const messageTemplateMock: MessageTemplateOption[] = [ { id: 'sms-1', name: '[SMS] Contact Notice', title: 'Survey Request', body: 'Please participate in the survey.', }, { id: 'email-1', name: '[EMAIL] Contact Notice', title: 'Survey Participation Guide', body: 'Please click the link and complete the survey.', }, ] const messageHistoryMock: MessageHistoryRow[] = [ { id: 1, type: 'sms', title: 'Survey Request', templateName: 'SMS Template A', sendInfo: '010-xxxx-xxxx', targetHeader: 'Phone Number', targetCount: 405, successCount: 405, failCount: 0, createdAt: '03.06 14:37', sendAt: '03.06 14:30 (Reserve)', status: 'Done', templatePreview: 'Please participate in the survey.', targetPreview: ['010-1234-5678', '010-1234-1111'], successPreview: ['sid 1: success', 'sid 2: success'], failPreview: [], }, { id: 2, type: 'email', title: 'Survey Answer Request', templateName: 'EMAIL Template A', sendInfo: 'info@kric.com', targetHeader: 'Email', targetCount: 405, successCount: 395, failCount: 10, createdAt: '03.06 14:37', sendAt: '03.06 14:47 (Instant)', status: 'Requested', templatePreview: 'Please click the link and complete the survey.', targetPreview: ['aa@kric.com', 'bb@kric.com'], successPreview: ['sid 3: success', 'sid 4: success'], failPreview: ['sid 5: bounce', 'sid 6: invalid'], }, ] const toSidSet = (value: string) => value .split(',') .map((item) => item.trim()) .filter((item) => item.length > 0) const toFilterCondition = (row: FilterRow, usesListValue: boolean): Omit => { const values = usesListValue ? row.multiValues : [row.textValue.trim()] if (row.operator === 'eq') { return { operator: ListFilterOperator.POSITIVE, matchType: ListFilterMatchType.EXACT, values } } if (row.operator === 'neq') { return { operator: ListFilterOperator.NEGATIVE, matchType: ListFilterMatchType.EXACT, values } } if (row.operator === 'contains') { return { operator: ListFilterOperator.POSITIVE, matchType: ListFilterMatchType.CONTAINS, values } } return { operator: ListFilterOperator.NEGATIVE, matchType: ListFilterMatchType.CONTAINS, values } } const toDateTimeRange = (from?: string, to?: string) => { if (!from || !to) return undefined return { startDate: `${from}T00:00:00`, endDate: `${to}T23:59:59`, } } const downloadArrayBuffer = (buffer: ArrayBuffer, filename: string, type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') => { downloadFile(new Blob([buffer], { type }), filename) } const ListManagePage = () => { const mounted = useMounted() const { auth } = useAuth() const { showDialog } = useDialog() const { selectedProject } = useSelectedProject() const [searchText, setSearchText] = useState('') const [searchContactResult, setSearchContactResult] = useState([]) const [searchInterviewResult, setSearchInterviewResult] = useState([]) const [searchSurveyResult, setSearchSurveyResult] = useState([]) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 10 }) const [sorting, setSorting] = useState([]) const [downloadMode, setDownloadMode] = useState('list') const [messageSendMode, setMessageSendMode] = useState('email') const [filterRows, setFilterRows] = useState([]) const [batchRows, setBatchRows] = useState([]) const [selectedRows, setSelectedRows] = useState([]) const userRole = auth?.user?.userRole ?? 9000 const prjctName = selectedProject?.prjctName ?? ''; const prjctIdx = selectedProject?.prjctIdx ?? 0 const enabled = mounted && prjctIdx > 0 const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled) const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled) const uploadHistoryQuery = useListUploadHistoryQuery(prjctIdx, enabled) const downloadListExcelTemplateMutation = useDownloadListExcelTemplateMutation() const uploadListExcelMutation = useUploadListExcelMutation(prjctIdx) const updateListHeaderMutation = useUpdateListHeaderMutation(prjctIdx) const resetListMutation = useResetListMutation(prjctIdx) const updateListMutation = useUpdateListMutation(prjctIdx) const downloadListMutation = useDownloadListMutation(prjctIdx) const downloadListUpdateHistoryMutation = useDownloadListUpdateHistoryMutation(prjctIdx) const downloadListEventHistoryMutation = useDownloadListEventHistoryMutation(prjctIdx) const downloadListItemFileMutation = useDownloadListItemFileMutation(prjctIdx) const downloadUploadHistoryFileMutation = useDownloadUploadHistoryFileMutation(prjctIdx) const resultCodeArray = useMemo(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]) const listSearchRequest = useMemo(() => { const sort = sorting?.[0] ?? { id: 'sid', desc: false as const } const listFilter = createEmptyListFilter() listFilter.sidSet = toSidSet(searchText) listFilter.memoConditions = [] listFilter.otherItemConditions = filterRows .map((row) => { const usesListValue = (listHeaderQuery.data ?? []).some( (header) => header.listHderId === row.headerId && (header.filterContents?.length ?? 0) > 0, ) return { listHderId: row.headerId, ...toFilterCondition(row, usesListValue), } }) .filter((item) => item.values.some((value) => value.trim().length > 0)) return { listFilter, pageRequest: { pageIndex: pagination.pageIndex, pageSize: pagination.pageSize, sortBy: sort.id, sortDir: sort.desc ? 'desc' : 'asc', }, } }, [filterRows, listHeaderQuery.data, pagination.pageIndex, pagination.pageSize, searchText, sorting]) const listSearchQuery = useListSearchQuery(prjctIdx, listSearchRequest, enabled) const columns = useMemo[]>(() => { if (!listHeaderQuery.data) return [] return getListColumns(listHeaderQuery.data, resultCodeArray, userRole) }, [listHeaderQuery.data, resultCodeArray, userRole]) const viewList = useMemo( () => (listSearchQuery.data?.content ?? []).map((row) => ({ ...row, ...row.itemList })), [listSearchQuery.data], ) const selectedSidSet = useMemo( () => selectedRows .map((row) => row.sid) .filter((sid): sid is string | number => typeof sid === 'string' || typeof sid === 'number') .map(String), [selectedRows], ) const buildTargetFilter = (target: ListFilterTarget) => { if (target === 'all') return createEmptyListFilter() if (target === 'selected') { return { ...createEmptyListFilter(), sidSet: selectedSidSet, } } return listSearchRequest.listFilter } const totalCount = listSearchQuery.data?.totalElements ?? 0 const pageCount = listSearchQuery.data?.totalPages ?? 0 const headerOptions = useMemo( () => (listHeaderQuery.data ?? []).map((header) => ({ id: header.listHderId, label: header.listHderNm, })), [listHeaderQuery.data], ) const headerManageRows = useMemo(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]) const filterHeaderOptions = useMemo( () => (listHeaderQuery.data ?? []) .filter((header) => header.useFilter) .map((header) => ({ id: header.listHderId, label: header.listHderNm, values: header.filterContents ?? [], })), [listHeaderQuery.data], ) const messageTargetHeaders = useMemo(() => { const matched = headerOptions.filter((header) => /email|phone|tel/i.test(header.label)) return matched.length > 0 ? matched : headerOptions.slice(0, 1) }, [headerOptions]) const handleSearchClick = () => { setPagination((prev) => ({ ...prev, pageIndex: 0 })) } const openDownloadDialog = (mode: ListDownloadMode) => { setDownloadMode(mode) showDialog('listDownloadDialog') } const openMessageDialog = (mode: MessageSendMode) => { setMessageSendMode(mode) showDialog('messageSendDialog') } const handleResetConfirm = async (payload: { target: ListFilterTarget; scope: ListResetScope }) => { const listFilter = buildTargetFilter(payload.target) await resetListMutation.mutateAsync({ resetMode: payload.scope === 'result-and-history' ? ListResetMode.HIST : ListResetMode.ALL, listFilter, }) await listSearchQuery.refetch() } const handleUploadConfirm = async (file: File, request: ListUploadRequest) => { const res = await uploadListExcelMutation.mutateAsync({ file, request }) if (res.hasErrorFile && res.errorFileBase64) { alert("업로드 중 오류가 발생하여 오류 파일을 다운로드합니다."); downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx", XLSX_MIME_TYPE); } else{ alert(`${res.successCount}개의 리스트를 업로드했습니다.`); } await listSearchQuery.refetch() } const handleDownloadTemplate = async () => { if (!prjctIdx) { alert("프로젝트를 선택해주세요.") return } const buffer = await downloadListExcelTemplateMutation.mutateAsync(prjctIdx) downloadArrayBuffer(buffer, `${prjctName} list-upload-template.xlsx`) } const handleHeaderManageConfirm = async (rows: listHeader[]) => { await updateListHeaderMutation.mutateAsync(rows) } const handleFilterConfirm = async (rows: FilterRow[]) => { setFilterRows(rows) } const handleBatchConfirm = async (rows: BatchEditRow[]) => { setBatchRows(rows) const updateContents = Object.fromEntries(rows.map((row) => [String(row.headerId), row.value])) await updateListMutation.mutateAsync({ updateContents, listFilter: buildTargetFilter('filtered'), }) await listSearchQuery.refetch() } const handleDownloadConfirm = async (payload: ListDownloadPayload) => { const listFilter = buildTargetFilter(payload.target) if (payload.mode === 'list') { const buffer = await downloadListMutation.mutateAsync(listFilter) downloadArrayBuffer(buffer, `${prjctName} list.xlsx`) return } if (payload.mode === 'list-change-history') { const buffer = await downloadListUpdateHistoryMutation.mutateAsync(listFilter) downloadArrayBuffer(buffer, `${prjctName} update-history.xlsx`) return } if (payload.mode === 'upload-file') { const buffer = await downloadListItemFileMutation.mutateAsync(listFilter) downloadArrayBuffer(buffer, `${prjctName} upload-files.zip`, 'application/zip') return } const buffer = await downloadListEventHistoryMutation.mutateAsync({ listFilter, resultCodeTypes: [ResultCodeType.CONTACT, ResultCodeType.INTERVIEW, ResultCodeType.SURVEY], searchBase: payload.contactHistoryType === 'latest' ? ListEventHistoryBase.LATEST : ListEventHistoryBase.ALL, dateRange: toDateTimeRange(payload.contactHistoryDateFrom, payload.contactHistoryDateTo), }) downloadArrayBuffer(buffer, `${prjctName} contact-history.xlsx`) } const handleMessageSendConfirm = async (payload: MessageSendPayload) => { void payload alert('Message send action callback placeholder.') } if (!mounted) return return (
setSearchText(e.target.value)} /> item.resultCdTy === ResultCodeType.CONTACT)} value={searchContactResult} onChange={setSearchContactResult} getValue={(item) => String(item.resultCd)} getLabel={(item) => item.resultCdLbl} placeholder="컨택 결과" widthClassName="w-70" heightClassName="h-9" /> item.resultCdTy === ResultCodeType.INTERVIEW)} value={searchInterviewResult} onChange={setSearchInterviewResult} getValue={(item) => String(item.resultCd)} getLabel={(item) => item.resultCdLbl} placeholder="면접 결과" widthClassName="w-70" heightClassName="h-9" /> item.resultCdTy === ResultCodeType.SURVEY)} value={searchSurveyResult} onChange={setSearchSurveyResult} getValue={(item) => String(item.resultCd)} getLabel={(item) => item.resultCdLbl} placeholder="설문 결과" widthClassName="w-70" heightClassName="h-9" />
columns={columns} data={viewList} getRowId={(row) => String(row.sid)} isClient={false} pageCount={pageCount} totalCount={totalCount} onPaginationChange={setPagination} onSortingChange={setSorting} selectMode="multi" onRowSelectionChange={setSelectedRows} pageSizeOptions={[10, 20, 30, 50]} />
{ const buffer = await downloadUploadHistoryFileMutation.mutateAsync(item.listUploadLogId) downloadArrayBuffer(buffer, item.fileName) }} headerRows={headerManageRows} /> [row.headerId, row.multiValues]))} initialRows={batchRows} onConfirm={handleBatchConfirm} />
) } export default ListManagePage