'use client' import { useEffect, useMemo, useState } from 'react' import type { PaginationState } from '@tanstack/react-table' import { useRouter } from 'next/navigation' import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter' import { useMounted } from "@kri/common/hooks"; import { useAuth } from '@/hooks/useAuth' import { useDialog } from '@/hooks/useDialog' import { useSelectedProject } from '@/hooks/useSelectedProject' import { useStorage } from '@/hooks/useStorage' import { StorageKeys } from '@/store/storage/storage-keys' import { ListManageActions } from '@/components/list/ListManageActions' import { ListSearchTable } from '@/components/list/ListSearchTable' import { useDownloadListEventHistoryMutation, useDownloadListExcelTemplateMutation, useDownloadListItemFileMutation, useDownloadListMutation, useDownloadListUpdateHistoryMutation, useDownloadUploadHistoryFileMutation, useListHeaderQuery, useListUploadHistoryQuery, useResetListMutation, useUpdateListHeaderMutation, useUploadListExcelMutation, } from '@/query/list' import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project' import type { ListTableRow } from '@/components/table-column/ListTableColumn' import { createEmptyListFilter, ListEventHistoryBase, type LastListVisit, type ListDownloadMode, type ListDownloadPayload, type ListFilter, type ListFilterTarget, type listHeader, type ListSearchUiState, ListResetMode, type ListResetScope, type ListUploadRequest, } from '@/types/list' import { type ResultCode, ResultCodeType } from '@/types/project' import ListResetDialog from '@/components/dialog/ListResetDialog' import ListUploadDialog from '@/components/dialog/ListUploadDialog' import ListHeaderManageDialog from '@/components/dialog/ListHeaderManageDialog' import ListDownloadDialog from '@/components/dialog/ListDownloadDialog' import MessageSendDialog, { type MessageSendMode } from '@/components/dialog/MessageSendDialog' import MessageHistoryDialog from '@/components/dialog/MessageHistoryDialog' import { downloadBase64File, downloadFile, XLSX_MIME_TYPE } from '@kri/common/browser' import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst"; import { isInternalManager, isManager } from "@/utils/userRole"; import { applyListAccessFilter } from "@/utils/listAccess"; 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 createEmptySearchUiState = (): ListSearchUiState => ({ searchText: '', searchContactResult: [], searchInterviewResult: [], surveyResultSelections: {}, filterRows: [], sorting: [], }) const ListManagePage = () => { const router = useRouter() const mounted = useMounted() const { auth } = useAuth() const { showDialog } = useDialog() const { selectedProject, isSelectedProjectHydrated } = useSelectedProject() const [downloadMode, setDownloadMode] = useState('list') const [messageSendMode, setMessageSendMode] = useState('email') const [selectedRows, setSelectedRows] = useState([]) const [currentListFilter, setCurrentListFilter] = useState(() => createEmptyListFilter()) const [filterSummary, setFilterSummary] = useState([]) const [searchUiState, setSearchUiState] = useState(createEmptySearchUiState) const [listRefreshKey, setListRefreshKey] = useState(0) const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 }) const [restoredVisit, setRestoredVisit] = useState(null) const [restoreResolved, setRestoreResolved] = useState(false) const { get: getLastListVisit, set: setLastListVisit, remove: removeLastListVisit } = useStorage( StorageKeys.LastListVisit, ) const userRole = auth?.user?.userRole ?? CONTACT_INTERVIEWER_ROLE const userId = auth?.user?.userId ?? '' const userCmpn = auth?.user?.userCmpn ?? '' const prjctName = selectedProject?.prjctName ?? '' const prjctIdx = selectedProject?.prjctIdx ?? 0 const enabled = mounted && prjctIdx > 0 const canManageList = isManager(userRole); // 리스트 초기화/헤더 관리/업로드는 내부 관리자 전용 — 외주사 계정에는 노출되면 안 됨. const isInternal = isInternalManager(userRole); const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled) const projectInfoQuery = useProjectInfoQuery(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 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 surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data]) const headerManageRows = useMemo(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]) // 컨택 진행 화면에서 돌아왔을 때 1회만 복원하고, 재방문 시 다시 나타나지 않도록 즉시 지운다. // ListSearchTable이 첫 마운트될 때 초기 페이지네이션 값이 확정돼 있어야 하므로(useState는 이후 prop // 변경을 반영하지 않음), selectedProject 하이드레이션이 끝나기 전에는 ListSearchTable을 아예 그리지 않는다. useEffect(() => { if (!mounted || !isSelectedProjectHydrated || restoreResolved) return const stored = getLastListVisit() if (stored) { setRestoredVisit(stored) removeLastListVisit() } setRestoreResolved(true) // eslint-disable-next-line react-hooks/exhaustive-deps }, [mounted, isSelectedProjectHydrated, restoreResolved]) const restoredForThisProject = restoredVisit?.prjctIdx === prjctIdx ? restoredVisit : undefined const selectedSidSet = useMemo( () => selectedRows .map((row) => row.sid) .filter((sid): sid is string | number => typeof sid === 'string' || typeof sid === 'number') .map(String), [selectedRows], ) const refreshList = () => { setListRefreshKey((prev) => prev + 1) } const buildTargetFilter = (target: ListFilterTarget) => { if (target === 'all') { return applyListAccessFilter(createEmptyListFilter(), { userRole, userId, userCmpn }) } if (target === 'selected') { return applyListAccessFilter( { ...createEmptyListFilter(), sidSet: selectedSidSet, }, { userRole, userId, userCmpn }, ) } return applyListAccessFilter(currentListFilter, { userRole, userId, userCmpn }) } const handleStartContact = (row: ListTableRow) => { const sid = String(row.sid ?? '') setLastListVisit({ prjctIdx, sid, pageIndex: pagination.pageIndex, pageSize: pagination.pageSize, ...searchUiState, }) router.push(`/list/contact?sid=${encodeURIComponent(sid)}`) } 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) const resetCount = await resetListMutation.mutateAsync({ resetMode: payload.scope === 'result-and-history' ? ListResetMode.HIST : ListResetMode.ALL, listFilter, }) alert(`${resetCount}건 삭제 되었습니다.`) refreshList() } 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}개의 리스트를 업로드했습니다.`); } refreshList() } 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 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`) } if (!mounted || !restoreResolved) return return (
{canManageList && ( showDialog('listResetDialog')} onHeaderManage={() => showDialog('listHeaderManageDialog')} onUpload={() => showDialog('listUploadDialog')} onDownload={openDownloadDialog} onMessageSend={openMessageDialog} onMessageHistory={() => showDialog('messageHistoryDialog')} /> )} {isInternal && ( <> { const buffer = await downloadUploadHistoryFileMutation.mutateAsync(item.listUploadLogId) downloadArrayBuffer(buffer, item.fileName) }} headerRows={headerManageRows} /> )} {canManageList && ( <> )}
) } export default ListManagePage