Files
contact-front/src/app/(pages)/(main)/list/manage/page.tsx
kric_jspark 081b53945a 260812_01_ENH: 배정·진행 현황 개선 및 예약/이벤트 이력 기능 추가
- 프로젝트별 외주사·필드워커 배정 현황 및 미배정 건수 UI 추가
- 현장 면접 진행 여부와 사용자 권한에 따른 배정 탭·필터·컬럼 노출 제어
- 컨택 마지막 이벤트 일자 필터·정렬 및 결과/일자 컬럼 분리
- 컨택·면접·발송 현황의 날짜 범위 선택 optional 처리
- 진행 현황의 미배정 표시 및 일자별 미사용 결과 제외
- 전역 예약 기간 조회·이동 및 5분 단위 예약 알림 추가
- 내부 관리자용 이벤트 이력 단건 삭제 기능 추가
- 리스트 필터 UI 및 일반 헤더 정렬 기준 개선
- 프로젝트 저장 시 선택 프로젝트 정보 동기화
2026-08-12 08:41:27 +09:00

353 lines
14 KiB
TypeScript

'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: [],
searchContactDateRange: { from: '', to: '' },
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<ListDownloadMode>('list')
const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('email')
const [selectedRows, setSelectedRows] = useState<ListTableRow[]>([])
const [currentListFilter, setCurrentListFilter] = useState<ListFilter>(() => createEmptyListFilter())
const [filterSummary, setFilterSummary] = useState<string[]>([])
const [searchUiState, setSearchUiState] = useState<ListSearchUiState>(createEmptySearchUiState)
const [listRefreshKey, setListRefreshKey] = useState(0)
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 25 })
const [restoredVisit, setRestoredVisit] = useState<LastListVisit | null>(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<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data])
const headerManageRows = useMemo<listHeader[]>(() => 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 <LoadingOverlayAdapter force />
return (
<div className="space-y-6 text-sm">
{canManageList && (
<ListManageActions
showAdminActions={isInternal}
onReset={() => showDialog('listResetDialog')}
onHeaderManage={() => showDialog('listHeaderManageDialog')}
onUpload={() => showDialog('listUploadDialog')}
onDownload={openDownloadDialog}
onMessageSend={openMessageDialog}
onMessageHistory={() => showDialog('messageHistoryDialog')}
/>
)}
<ListSearchTable
prjctIdx={prjctIdx}
enabled={enabled}
userRole={userRole}
userId={userId}
userCmpn={userCmpn}
resultCodes={resultCodeArray}
surveys={surveyArray}
listHeaders={headerManageRows}
fieldInterviewEnabled={selectedProject?.ff !== false}
enableBatchEdit={canManageList}
selectMode={canManageList ? 'multi' : 'click-event'}
refreshKey={listRefreshKey}
onCurrentFilterChange={setCurrentListFilter}
onFilterSummaryChange={setFilterSummary}
onSelectedRowsChange={setSelectedRows}
onRowClick={!canManageList ? handleStartContact : undefined}
onRowDoubleClick={canManageList ? handleStartContact : undefined}
initialPagination={
restoredForThisProject
? { pageIndex: restoredForThisProject.pageIndex, pageSize: restoredForThisProject.pageSize }
: undefined
}
onPaginationChange={setPagination}
initialSearchState={restoredForThisProject}
onSearchStateChange={setSearchUiState}
focusRowId={restoredForThisProject?.sid}
/>
{isInternal && (
<>
<ListResetDialog
selectedSids={selectedSidSet}
filterSummary={filterSummary}
onConfirm={handleResetConfirm}
/>
<ListUploadDialog
onUpload={handleUploadConfirm}
onDownloadTemplate={handleDownloadTemplate}
uploadHistory={uploadHistoryQuery.data ?? []}
onDownloadHistory={async (item) => {
const buffer = await downloadUploadHistoryFileMutation.mutateAsync(item.listUploadLogId)
downloadArrayBuffer(buffer, item.fileName)
}}
headerRows={headerManageRows}
/>
<ListHeaderManageDialog prjctIdx={prjctIdx} rows={headerManageRows} onConfirm={handleHeaderManageConfirm} />
</>
)}
{canManageList && (
<>
<ListDownloadDialog
mode={downloadMode}
selectedSids={selectedSidSet}
filterSummary={filterSummary}
onDownload={handleDownloadConfirm}
/>
<MessageSendDialog
mode={messageSendMode}
listHeaders={headerManageRows}
currentFilter={currentListFilter}
selectedRows={selectedRows}
filterSummary={filterSummary}
onSent={refreshList}
/>
<MessageHistoryDialog />
</>
)}
</div>
)
}
export default ListManagePage