diff --git a/src/app/(pages)/(main)/assign/list/page.tsx b/src/app/(pages)/(main)/assign/list/page.tsx index 91ce3e7..e2cdd41 100644 --- a/src/app/(pages)/(main)/assign/list/page.tsx +++ b/src/app/(pages)/(main)/assign/list/page.tsx @@ -1,6 +1,8 @@ 'use client' import { useEffect, useMemo, useState } from 'react' +import { useAtom } from 'jotai' +import { listJobOpenRequestAtom } from '@/store/jotai/list-job' import { useMounted } from '@kri/common/hooks' import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter' import { useAuth } from '@/hooks/useAuth' @@ -13,7 +15,10 @@ import { AssignTargetList, useAssignTargetRows } from '@/components/assign/Assig import { ListSearchTable } from '@/components/list/ListSearchTable' import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project' import { useListHeaderQuery } from '@/query/list' -import { useResetListAssignMutation, useUpsertListAssignMutation } from '@/query/assign' +import { ListJobPageQueryContext, useSubmitListJob } from '@/query/list-job' +import { ListJobGatePanel } from '@/components/list/ListJobGate' +import { ListJobRefreshNotice } from '@/components/list/ListJobRefreshNotice' +import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor' import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst' import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list' import type { ResultCode } from '@/types/project' @@ -55,8 +60,13 @@ const ListAssignPage = () => { const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled) const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled) const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled) - const upsertListAssignMutation = useUpsertListAssignMutation(prjctIdx) - const resetListAssignMutation = useResetListAssignMutation(prjctIdx) + const assignMutation = useSubmitListJob(prjctIdx) + const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_ASSIGN', enabled, { + hasSelection: !!selectedAssignId, + isSubmitting: assignMutation.isPending, + }) + const { gate: assignGate, dataRevision } = pageMonitor + const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom) const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: effectiveAssignType }) const resultCodeArray = useMemo(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]) @@ -122,7 +132,15 @@ const ListAssignPage = () => { const hasNoAppliedFilter = () => filterSummary.length === 0 && assignFilterIds.length === 0 + useEffect(() => { + if (enabled && openRequest && !openRequest.opened && openRequest.jobType === 'LIST_ASSIGN' + && openRequest.userId === auth.user?.userId && openRequest.prjctIdx === prjctIdx) { + setOpenRequest({ ...openRequest, opened: true }) + } + }, [enabled, openRequest, auth.user?.userId, prjctIdx, setOpenRequest]) + const handleAssign = async () => { + if (assignGate.submitBlocked || assignMutation.isPending) return if (!selectedAssignId) { alert('배정할 대상을 선택해주세요.') return @@ -131,33 +149,38 @@ const ListAssignPage = () => { return } - await upsertListAssignMutation.mutateAsync({ - assignId: selectedAssignId, - request: { + await assignMutation.mutateAsync({ + jobType: 'LIST_ASSIGN', + path: `mutations/assign/${encodeURIComponent(selectedAssignId)}`, + body: { assignType: effectiveAssignType, transferResve: effectiveAssignType === ListHeaderAssignConst.OUTSOURCE? false : transferResve, listFilter: currentListFilter, }, }) - alert('배정되었습니다.') } const handleResetAssign = async () => { + if (assignGate.submitBlocked || assignMutation.isPending) return if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) { return } if (!confirm('정말 배정을 초기화 하시겠습니까?')) return - await resetListAssignMutation.mutateAsync({ + await assignMutation.mutateAsync({ + jobType: 'LIST_ASSIGN', + path: 'mutations/assign-reset', + body: { assignType: effectiveAssignType, listFilter: currentListFilter, + }, }) - alert('배정이 초기화 되었습니다.') } if (!mounted || !selectedProject) return return ( +
@@ -180,8 +203,11 @@ const ListAssignPage = () => { />
-
+
+ + { 예약 이관 )} - - @@ -230,6 +256,7 @@ const ListAssignPage = () => { />
+ ) } diff --git a/src/app/(pages)/(main)/list/manage/page.tsx b/src/app/(pages)/(main)/list/manage/page.tsx index 2455e9a..870d52d 100644 --- a/src/app/(pages)/(main)/list/manage/page.tsx +++ b/src/app/(pages)/(main)/list/manage/page.tsx @@ -1,6 +1,9 @@ 'use client' import { useEffect, useMemo, useRef, useState } from 'react' +import { useAtom } from 'jotai' +import { toast } from 'sonner' +import { listJobOpenRequestAtom } from '@/store/jotai/list-job' import type { PaginationState } from '@tanstack/react-table' import { useQueryClient } from '@tanstack/react-query' import { useRouter } from 'next/navigation' @@ -11,21 +14,23 @@ 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 { ListManageActions, type ListManageActionKey } 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 { ListJobPageQueryContext, useMyActiveListJobs, useSubmitListJob } from '@/query/list-job' +import { ListJobGatePanel } from '@/components/list/ListJobGate' +import { ListJobRefreshNotice } from '@/components/list/ListJobRefreshNotice' +import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor' +import { useTrackedListJobs } from '@/store/list-job-tracker' +import { isListPageActionBlocked } from '@/utils/listJobAvailability' +import type { ListJobType } from '@/types/list-job' +import { LIST_DOWNLOAD_JOB_TYPE, LIST_JOB_VIEW, MESSAGE_JOB_TYPE } from '@/const/listJobConst' import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project' import type { ListTableRow } from '@/components/table-column/ListTableColumn' import { @@ -39,8 +44,8 @@ import { type ListFilterTarget, type listHeader, type ListSearchUiState, - ListResetMode, - type ListResetScope, + type ListResetRequest, + type ListResetSelection, type ListUploadRequest, } from '@/types/list' import { type ResultCode, ResultCodeType } from '@/types/project' @@ -50,7 +55,7 @@ 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 { downloadFile } from '@kri/common/browser' import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst"; import { isInternalManager, isManager } from "@/utils/userRole"; import { applyListAccessFilter } from "@/utils/listAccess"; @@ -84,6 +89,7 @@ const ListManagePage = () => { const { auth } = useAuth() const { showDialog } = useDialog() const { selectedProject, isSelectedProjectHydrated } = useSelectedProject() + const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom) const [downloadMode, setDownloadMode] = useState('list') const [messageSendMode, setMessageSendMode] = useState('email') @@ -110,19 +116,56 @@ const ListManagePage = () => { const canManageList = isManager(userRole); // 리스트 초기화/헤더 관리/업로드는 내부 관리자 전용 — 외주사 계정에는 노출되면 안 됨. const isInternal = isInternalManager(userRole); + const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_RESET', enabled, { hasSelection: selectedRows.length > 0 }) + const { gate: pageGate, dataRevision } = pageMonitor + const trackedJobs = useTrackedListJobs() + + useEffect(() => { + if (!mounted || !restoreResolved || !enabled || !openRequest || openRequest.opened + || openRequest.userId !== userId || openRequest.prjctIdx !== prjctIdx) return + const view = LIST_JOB_VIEW[openRequest.jobType] + if (view.path !== '/list/manage' || !view.dialogId) return + if (!canManageList || (!isInternal && (openRequest.jobType === 'LIST_UPLOAD' || openRequest.jobType === 'LIST_RESET'))) { + toast.error('해당 작업 화면을 열 권한이 없습니다.') + setOpenRequest(null) + return + } + if (view.downloadMode) setDownloadMode(view.downloadMode) + if (view.messageMode) setMessageSendMode(view.messageMode) + showDialog(view.dialogId) + setOpenRequest({ ...openRequest, opened: true }) + }, [mounted, restoreResolved, enabled, openRequest, userId, prjctIdx, canManageList, isInternal, setOpenRequest, showDialog]) 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 submitJob = useSubmitListJob(prjctIdx) + // 전역 ListJobWatcher가 갱신하는 동일 쿼리를 구독하고 별도 폴링은 만들지 않는다. + const myActiveJobsQuery = useMyActiveListJobs(prjctIdx, false) + const myActiveJobTypes = new Set((myActiveJobsQuery.data ?? []).map((job) => job.jobType)) + const inspectableJobTypes = new Set([ + ...trackedJobs.filter(job => job.userId === userId && job.prjctIdx === prjctIdx).map(job => job.jobType), + ...myActiveJobTypes, + ...(pageGate.availability?.blockers.filter(blocker => blocker.mine && blocker.jobKey).map(blocker => blocker.jobType) ?? []), + ]) + const isActionDisabled = (jobType: ListJobType) => !inspectableJobTypes.has(jobType) && isListPageActionBlocked( + pageGate.status === 'unsupported' ? undefined : pageGate.availability, + jobType, + pageGate.status === 'checking' || pageGate.status === 'error', + ) + const actionJobTypes: Record = { + reset: 'LIST_RESET', upload: 'LIST_UPLOAD', ...LIST_DOWNLOAD_JOB_TYPE, ...MESSAGE_JOB_TYPE, + } + const disabledActions = new Set((Object.keys(actionJobTypes) as ListManageActionKey[]).filter(action => isActionDisabled(actionJobTypes[action]))) + const runningActions = new Set([ + ...(myActiveJobTypes.has('LIST_RESET') ? ['reset' as const] : []), + ...(myActiveJobTypes.has('LIST_UPLOAD') ? ['upload' as const] : []), + ...(Object.keys(LIST_DOWNLOAD_JOB_TYPE) as ListDownloadMode[]).filter((mode) => myActiveJobTypes.has(LIST_DOWNLOAD_JOB_TYPE[mode])), + ...(Object.keys(MESSAGE_JOB_TYPE) as MessageSendMode[]).filter((mode) => myActiveJobTypes.has(MESSAGE_JOB_TYPE[mode])), + ]) 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]) @@ -140,7 +183,6 @@ const ListManagePage = () => { removeLastListVisit() } setRestoreResolved(true) - // eslint-disable-next-line react-hooks/exhaustive-deps }, [mounted, isSelectedProjectHydrated, restoreResolved]) useEffect(() => { @@ -222,28 +264,16 @@ const ListManagePage = () => { 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 handleResetConfirm = async (payload: { target: ListFilterTarget; selection: ListResetSelection }) => { + const body: ListResetRequest = { + ...payload.selection, + listFilter: buildTargetFilter(payload.target), + } + await submitJob.mutateAsync({ jobType: 'LIST_RESET', path: 'reset', body }) } 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() + await submitJob.mutateAsync({ jobType: 'LIST_UPLOAD', path: 'upload', file, body: request }) } const handleDownloadTemplate = async () => { @@ -262,45 +292,47 @@ const ListManagePage = () => { const handleDownloadConfirm = async (payload: ListDownloadPayload) => { const listFilter = buildTargetFilter(payload.target) + const jobType = LIST_DOWNLOAD_JOB_TYPE[payload.mode] if (payload.mode === 'list') { - const buffer = await downloadListMutation.mutateAsync({ listFilter, includeResult: payload.includeResult }) - downloadArrayBuffer(buffer, `${prjctName} list.xlsx`) + await submitJob.mutateAsync({ jobType, path: `downloads/list?includeResult=${payload.includeResult}`, body: listFilter }) return } if (payload.mode === 'list-change-history') { - const buffer = await downloadListUpdateHistoryMutation.mutateAsync(listFilter) - downloadArrayBuffer(buffer, `${prjctName} update-history.xlsx`) + await submitJob.mutateAsync({ jobType, path: 'downloads/update-history', body: listFilter }) return } if (payload.mode === 'upload-file') { - const buffer = await downloadListItemFileMutation.mutateAsync(listFilter) - downloadArrayBuffer(buffer, `${prjctName} upload-files.zip`, 'application/zip') + await submitJob.mutateAsync({ jobType, path: 'downloads/item-files', body: listFilter }) return } - const buffer = await downloadListEventHistoryMutation.mutateAsync({ - includeResult: payload.includeResult, + await submitJob.mutateAsync({ jobType, path: `downloads/event-history?includeResult=${payload.includeResult}`, body: { listFilter, resultCodeTypes: [ResultCodeType.CONTACT, ResultCodeType.INTERVIEW, ResultCodeType.SURVEY], searchBase: payload.contactHistoryType === 'latest' ? ListEventHistoryBase.LATEST : ListEventHistoryBase.ALL, historyOrder: payload.historyOrder ?? ListEventHistoryOrder.DESC, dateRange: toDateTimeRange(payload.contactHistoryDateFrom, payload.contactHistoryDateTo), - }) - downloadArrayBuffer(buffer, `${prjctName} contact-history.xlsx`) + } }) } if (!mounted || !restoreResolved) return return ( +
+ + 0} /> {canManageList && ( showDialog('listResetDialog')} - onHeaderManage={() => showDialog('listHeaderManageDialog')} + onHeaderManage={() => { if (!pageGate.submitBlocked) showDialog('listHeaderManageDialog') }} onUpload={() => showDialog('listUploadDialog')} onDownload={openDownloadDialog} onMessageSend={openMessageDialog} @@ -320,6 +352,8 @@ const ListManagePage = () => { listHeaders={headerManageRows} fieldInterviewEnabled={selectedProject?.ff !== false} enableBatchEdit={canManageList} + batchEditDisabled={isActionDisabled('LIST_UPDATE')} + dataRevision={dataRevision} selectMode={canManageList ? 'multi' : 'click-event'} refreshKey={listRefreshKey} onCurrentFilterChange={setCurrentListFilter} @@ -342,11 +376,15 @@ const ListManagePage = () => { {isInternal && ( <> { }} headerRows={headerManageRows} /> - + )} {canManageList && ( <> { )}
+
) } diff --git a/src/app/(pages)/(main)/page.tsx b/src/app/(pages)/(main)/page.tsx index 82ea20f..3965c22 100644 --- a/src/app/(pages)/(main)/page.tsx +++ b/src/app/(pages)/(main)/page.tsx @@ -31,7 +31,6 @@ import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} import {useGroupCodeListQuery} from "@/query/intranet"; import {PROJECT_STATUS_LABEL} from "@/const/projectConst"; import {isInternalManager, isManager} from "@/utils/userRole"; -import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst"; const MainPage = () => { const router = useRouter(); diff --git a/src/app/(pages)/(main)/progress/message/page.tsx b/src/app/(pages)/(main)/progress/message/page.tsx index 99bbbe1..f1dac67 100644 --- a/src/app/(pages)/(main)/progress/message/page.tsx +++ b/src/app/(pages)/(main)/progress/message/page.tsx @@ -29,6 +29,7 @@ type SummaryRow = { successCount: number; failCount: number; standByCount: number; + canceledCount: number; }; const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) => @@ -45,6 +46,7 @@ const buildRows = (data: SendResultSummaryResponse[]): SummaryRow[] => successCount: sum(matched, "successCount"), failCount: sum(matched, "failCount"), standByCount: sum(matched, "standByCount"), + canceledCount: sum(matched, "canceledCount"), }; }); @@ -81,6 +83,7 @@ const MessageProgressPage = () => { successCount: rows.reduce((acc, row) => acc + row.successCount, 0), failCount: rows.reduce((acc, row) => acc + row.failCount, 0), standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0), + canceledCount: rows.reduce((acc, row) => acc + row.canceledCount, 0), }), [rows], ); @@ -104,6 +107,7 @@ const MessageProgressPage = () => { 성공 실패 발송중 + 취소 @@ -116,6 +120,7 @@ const MessageProgressPage = () => { {caseUnit(row.successCount)} {caseUnit(row.failCount)} {caseUnit(row.standByCount)} + {caseUnit(row.canceledCount)} ))} @@ -125,6 +130,7 @@ const MessageProgressPage = () => { {caseUnit(total.successCount)} {caseUnit(total.failCount)} {caseUnit(total.standByCount)} + {caseUnit(total.canceledCount)} diff --git a/src/app/(pages)/(main)/project/info/page.tsx b/src/app/(pages)/(main)/project/info/page.tsx index b66c873..563ee58 100644 --- a/src/app/(pages)/(main)/project/info/page.tsx +++ b/src/app/(pages)/(main)/project/info/page.tsx @@ -444,7 +444,7 @@ const ProjectInfoPage = () => { const updateMutation = useUpdateProjectMutation(prjctIdx); const deleteMutation = useDeleteProjectMutation(prjctIdx); - const uploadScenarioMutation = useUploadScenarioImageMutation(prjctIdx, projectInfo.prjctCd); + const uploadScenarioMutation = useUploadScenarioImageMutation(projectInfo.prjctCd); const [resultCodeArray, setResultCodeArray] = useState([]); const [assignCmpnIdArray, setAssignCmpnIdArray] = useState([]); diff --git a/src/app/(pages)/redirect/[slug]/page.tsx b/src/app/(pages)/redirect/[slug]/page.tsx index fdcf88b..5f82422 100644 --- a/src/app/(pages)/redirect/[slug]/page.tsx +++ b/src/app/(pages)/redirect/[slug]/page.tsx @@ -14,10 +14,8 @@ const toRedirectSlug = (slug: string): RedirectSlug | null => { const redirectPage = async ({ params, - searchParams, }: redirectPageProps) => { const { slug } = await params; - const sp = searchParams ? await searchParams : undefined; const redirectSlug = toRedirectSlug(slug); if (!redirectSlug) notFound(); diff --git a/src/app/api/assign/[[...slug]]/route.ts b/src/app/api/assign/[[...slug]]/route.ts index a4bc663..eeb47ab 100644 --- a/src/app/api/assign/[[...slug]]/route.ts +++ b/src/app/api/assign/[[...slug]]/route.ts @@ -64,37 +64,6 @@ export const PUT = async (req: NextRequest, context: RouteContext) => { return new NextResponse(null, { status: 204 }); } - if (action === "list" && slug.length === 3) { - const body = await req.json().catch(() => null); - if (!body) { - return NextResponse.json( - { message: "요청 바디가 없습니다." }, - { status: 400 } - ); - } - - const result = await contactApi.put(`/assign/list/${slug[1]}/${slug[2]}`, body); - return NextResponse.json(result, { status: 200 }); - } - - return NextResponse.json({ message: "Not found" }, { status: 404 }); - } catch (error: unknown) { - return errorToResponse(error); - } -}; - -export const DELETE = async (req: NextRequest, context: RouteContext) => { - try { - const { slug = [] } = await context.params; - const [action] = slug; - const contactApi = await createContactApi(); - - if (action === "list" && slug[1] === "reset" && slug.length === 3) { - const body = await req.json().catch(() => null); - const result = await contactApi.del(`/assign/list/reset/${slug[2]}`, { json: body }); - return NextResponse.json(result, { status: 200 }); - } - return NextResponse.json({ message: "Not found" }, { status: 404 }); } catch (error: unknown) { return errorToResponse(error); diff --git a/src/app/api/list-hist/[[...slug]]/route.ts b/src/app/api/list-hist/[[...slug]]/route.ts index 3aed8c5..a9d8e3c 100644 --- a/src/app/api/list-hist/[[...slug]]/route.ts +++ b/src/app/api/list-hist/[[...slug]]/route.ts @@ -4,7 +4,7 @@ import {createContactApi} from "@/lib/http-server"; import {errorToResponse} from "@kri/common/http"; import type {ListEventHistory, ListUpdateHistory} from "@/types/list"; -export const GET = async (req: NextRequest, context: RouteContext) => { +export const GET = async (_req: NextRequest, context: RouteContext) => { try { const { slug = [] } = await context.params; const [action] = slug; @@ -30,7 +30,7 @@ export const GET = async (req: NextRequest, context: RouteContext) => { } }; -export const DELETE = async (req: NextRequest, context: RouteContext) => { +export const DELETE = async (_req: NextRequest, context: RouteContext) => { try { const { slug = [] } = await context.params; const [action] = slug; diff --git a/src/app/api/list-jobs/[[...slug]]/route.ts b/src/app/api/list-jobs/[[...slug]]/route.ts new file mode 100644 index 0000000..e355418 --- /dev/null +++ b/src/app/api/list-jobs/[[...slug]]/route.ts @@ -0,0 +1,59 @@ +import { NextRequest, NextResponse } from 'next/server' +import { cookies } from 'next/headers' +import { errorToResponse } from '@kri/common/http' +import { createContactApi } from '@/lib/http-server' +import { serverEnv } from '@/lib/env.server' +import { CookieKeys } from '@/store/cookie/cookie-keys' +import type { RouteContext } from '@/types/common' + +const project = '[1-9][0-9]*' +const key = '[a-f0-9]{32}' +const getPath = new RegExp(`^${project}/(?:availability|upload-reset-active|my-active|${key}(?:/(?:sid-failures|range-failures|validation-errors|source-file|files/[0-9]+|message-report/(?:batches|preparation-failures)))?)$`) +const postPath = new RegExp(`^${project}/(?:upload|reset|${key}/cancel|mutations/(?:update|assign-reset|assign/[^/]+)|downloads/(?:list|event-history|update-history|item-files)|messages/(?:email|sms|kko))$`) + +// The shared HTTP client decodes binary bodies. Forward file bodies as streams instead. +async function forwardFile(req: NextRequest, path: string) { + const token = (await cookies()).get(CookieKeys.AuthToken)?.value + if (!token) return NextResponse.json({ message: '로그인이 필요합니다.' }, { status: 401 }) + const headers = new Headers({ Authorization: `Bearer ${token}` }) + if (req.method === 'POST') { + const type = req.headers.get('content-type') + if (!type?.startsWith('multipart/form-data;')) return NextResponse.json({ message: '파일 요청 형식이 올바르지 않습니다.' }, { status: 400 }) + headers.set('Content-Type', type) + } + const options: RequestInit & { duplex?: 'half' } = { + method: req.method, headers, cache: 'no-store', redirect: 'error', + signal: AbortSignal.any([req.signal, AbortSignal.timeout(300_000)]), + ...(req.method === 'POST' ? { body: req.body, duplex: 'half' as const } : {}), + } + const upstream = await fetch(`${serverEnv.API_CONTACT_SERVER.replace(/\/$/, '')}/list/jobs/${path}`, options) + const responseHeaders = new Headers({ 'Cache-Control': 'no-store' }) + for (const name of ['Content-Type', 'Content-Disposition', 'Content-Length']) { + const value = upstream.headers.get(name) + if (value) responseHeaders.set(name, value) + } + return new NextResponse(upstream.body, { status: upstream.status, headers: responseHeaders }) +} + +async function proxy(req: NextRequest, context: RouteContext) { + try { + const { slug = [] } = await context.params + const path = slug.map(encodeURIComponent).join('/') + if (!(req.method === 'GET' ? getPath : postPath).test(path)) return NextResponse.json({ message: '지원하지 않는 작업 경로입니다.' }, { status: 404 }) + if (/\/(source-file|files\/[0-9]+|upload)$/.test(path)) return await forwardFile(req, path) + const query = new URLSearchParams() + for (const name of ['offset', 'limit', 'includeResult', 'jobType']) { + const value = req.nextUrl.searchParams.get(name) + if (value !== null) query.set(name, value) + } + const url = `/list/jobs/${path}${query.size ? `?${query}` : ''}` + const api = await createContactApi() + const value = req.method === 'GET' + ? await api.get(url, { cache: 'no-store' }) + : await api.post(url, await req.json().catch(() => undefined)) + return NextResponse.json(value, { headers: { 'Cache-Control': 'no-store' } }) + } catch (error: unknown) { return errorToResponse(error) } +} + +export const GET = proxy +export const POST = proxy diff --git a/src/app/api/list/[[...slug]]/route.ts b/src/app/api/list/[[...slug]]/route.ts index ac88603..5ad6614 100644 --- a/src/app/api/list/[[...slug]]/route.ts +++ b/src/app/api/list/[[...slug]]/route.ts @@ -4,13 +4,12 @@ import {RouteContext} from "@/types/common"; import {createContactApi} from "@/lib/http-server"; import {errorToResponse} from "@kri/common/http"; import {listHeader, ListSearchRequest, ListSearchWithFullResult} from "@/types/list"; -import {LIST_EXCEL_TIMEOUT_MS} from "@/const/listConst"; const excelHeaders = { "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }; -export const GET = async (req: NextRequest, context: RouteContext) => { +export const GET = async (_req: NextRequest, context: RouteContext) => { try { const {slug = []} = await context.params; const [action] = slug; @@ -101,52 +100,6 @@ export const POST = async (req: NextRequest, context: RouteContext) => { return new NextResponse(null, { status: 204 }); } - if (action === "excel-upload") { - const form = await req.formData(); - const result = await contactApi.postForm(`/list/excel/upload/${slug[1]}`, form, { - timeoutMs: LIST_EXCEL_TIMEOUT_MS, - }); - return NextResponse.json(result, { status: 200 }); - } - - if (action === "excel-download") { - const body = await req.json().catch(() => null); - const includeResult = req.nextUrl.searchParams.get("includeResult") !== "false"; - const result = await contactApi.post( - `/list/excel/download/${slug[1]}?includeResult=${includeResult}`, - body, - { expectBinary: true, timeoutMs: LIST_EXCEL_TIMEOUT_MS }, - ); - return new NextResponse(result, { status: 200, headers: excelHeaders }); - } - - if (action === "excel-download-update") { - const body = await req.json().catch(() => null); - const result = await contactApi.post(`/list/excel/download/update/${slug[1]}`, body, { - expectBinary: true, - }); - return new NextResponse(result, { status: 200, headers: excelHeaders }); - } - - if (action === "event-history-download") { - const body = await req.json().catch(() => null); - const includeResult = req.nextUrl.searchParams.get("includeResult") !== "false"; - const result = await contactApi.post( - `/list-hist/excel/download/event/${slug[1]}?includeResult=${includeResult}`, - body, - { expectBinary: true, timeoutMs: LIST_EXCEL_TIMEOUT_MS }, - ); - return new NextResponse(result, { status: 200, headers: excelHeaders }); - } - - if (action === "item-file-download") { - const body = await req.json().catch(() => null); - const result = await contactApi.post(`/list/item-file/download/${slug[1]}`, body, { - expectBinary: true, - }); - return new NextResponse(result, { status: 200, headers: { "Content-Type": "application/zip" } }); - } - if (action === "upload-history-file") { const result = await contactApi.post( `/list/excel/upload-history/file/${slug[1]}/${slug[2]}`, @@ -184,15 +137,3 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => { return errorToResponse(error); } }; - -export const DELETE = async (req: NextRequest, context: RouteContext) => { - try { - const { slug = [] } = await context.params; - const body = await req.json().catch(() => null); - const contactApi = await createContactApi(); - const result = await contactApi.del(`/list/${slug[0]}`, { json: body }); - return NextResponse.json(result, { status: 200 }); - } catch (error: unknown) { - return errorToResponse(error); - } -}; diff --git a/src/app/api/logout/[[...slug]]/route.ts b/src/app/api/logout/[[...slug]]/route.ts index 1007f59..43a8067 100644 --- a/src/app/api/logout/[[...slug]]/route.ts +++ b/src/app/api/logout/[[...slug]]/route.ts @@ -6,7 +6,7 @@ import {RouteContext} from "@/types/common"; import {CookieKeys} from "@/store/cookie/cookie-keys"; export async function POST( - req: NextRequest, + _req: NextRequest, context: RouteContext ) { try { diff --git a/src/app/api/message-send/[[...slug]]/route.ts b/src/app/api/message-send/[[...slug]]/route.ts index 44b3380..5a795c3 100644 --- a/src/app/api/message-send/[[...slug]]/route.ts +++ b/src/app/api/message-send/[[...slug]]/route.ts @@ -2,18 +2,48 @@ import {NextRequest, NextResponse} from "next/server"; import {RouteContext} from "@/types/common"; import {createContactApi} from "@/lib/http-server"; import {errorToResponse} from "@kri/common/http"; -import type {BulkSendResult} from "@kri/common/noti-hub"; +import type {SendCancelResponse} from "@kri/common/noti-hub"; import type {MessageSendChannel, SendSingleResponse} from "@/types/message"; const isChannel = (value: string): value is MessageSendChannel => value === "sms" || value === "email" || value === "kko"; +const BULK_SEND_KEY_MAX_LENGTH = 32; + +const readCancelBody = (body: unknown, target: string): Record | null => { + if (!body || typeof body !== "object") return null; + if (target === "single") { + const sendIdx = (body as {sendIdx?: unknown}).sendIdx; + return typeof sendIdx === "number" && Number.isSafeInteger(sendIdx) && sendIdx > 0 ? {sendIdx} : null; + } + if (target === "bulk") { + const bulkSendKey = (body as {bulkSendKey?: unknown}).bulkSendKey; + return typeof bulkSendKey === "string" && bulkSendKey.trim() !== "" && bulkSendKey.length <= BULK_SEND_KEY_MAX_LENGTH + ? {bulkSendKey} + : null; + } + return null; +}; + export const POST = async (req: NextRequest, context: RouteContext) => { try { const {slug = []} = await context.params; const [channel, action, prjctIdx] = slug; const contactApi = await createContactApi(); + // 예약 취소 (POST /message-send/cancel/{single|bulk}). 채널 구분 없이 공통 API를 사용한다. + if (channel === "cancel") { + if (action !== "single" && action !== "bulk") { + return NextResponse.json({message: "Not found"}, {status: 404}); + } + const cancelBody = readCancelBody(await req.json().catch(() => null), action); + if (!cancelBody) { + return NextResponse.json({message: "취소 요청 값이 올바르지 않습니다."}, {status: 400}); + } + const result = await contactApi.post(`/message-send/cancel/${action}`, cancelBody); + return NextResponse.json(result, {status: 200}); + } + if (!isChannel(channel) || !prjctIdx) { return NextResponse.json({message: "Not found"}, {status: 404}); } @@ -28,11 +58,6 @@ export const POST = async (req: NextRequest, context: RouteContext) => { return NextResponse.json(result, {status: 200}); } - if (action === "bulk") { - const result = await contactApi.post(`/message-send/${channel}/bulk/${prjctIdx}`, body); - return NextResponse.json(result, {status: 200}); - } - return NextResponse.json({message: "Not found"}, {status: 404}); } catch (error: unknown) { return errorToResponse(error); diff --git a/src/app/api/message-template/[[...slug]]/route.ts b/src/app/api/message-template/[[...slug]]/route.ts index 171c005..4198d64 100644 --- a/src/app/api/message-template/[[...slug]]/route.ts +++ b/src/app/api/message-template/[[...slug]]/route.ts @@ -70,7 +70,6 @@ export const GET = async (req: NextRequest, context: RouteContext) => { export const PUT = async (req: NextRequest, context: RouteContext) => { try{ - const { searchParams } = new URL(req.url); const {slug = []} = await context.params; const [action] = slug; const contactApi = await createContactApi(); @@ -117,7 +116,6 @@ export const PUT = async (req: NextRequest, context: RouteContext) => { export const PATCH = async (req: NextRequest, context: RouteContext) => { try{ - const { searchParams } = new URL(req.url); const {slug = []} = await context.params; const [action] = slug; const contactApi = await createContactApi(); diff --git a/src/app/api/project/[[...slug]]/route.ts b/src/app/api/project/[[...slug]]/route.ts index 3950d19..8941420 100644 --- a/src/app/api/project/[[...slug]]/route.ts +++ b/src/app/api/project/[[...slug]]/route.ts @@ -1,5 +1,5 @@ import {NextRequest, NextResponse} from "next/server"; -import {createContactApi, createIntranetApi} from "@/lib/http-server"; +import {createContactApi} from "@/lib/http-server"; import {errorToResponse} from "@kri/common/http"; import type {PageResponse} from "@kri/common"; import {RouteContext} from "@/types/common"; @@ -172,10 +172,9 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => { } }; -export const DELETE = async (req: NextRequest, context: RouteContext) => { +export const DELETE = async (_req: NextRequest, context: RouteContext) => { try { const {slug = []} = await context.params; - const [action] = slug; const contactApi = await createContactApi(); if(slug.length === 1){ diff --git a/src/app/api/reserve/[[...slug]]/route.ts b/src/app/api/reserve/[[...slug]]/route.ts index a2d4fa2..a7203c8 100644 --- a/src/app/api/reserve/[[...slug]]/route.ts +++ b/src/app/api/reserve/[[...slug]]/route.ts @@ -48,7 +48,7 @@ export const GET = async (req: NextRequest, context: RouteContext) => { } }; -export const PUT = async (req: NextRequest, context: RouteContext) => { +export const PUT = async (req: NextRequest) => { try { const body = await req.json().catch(() => null); if (!body) { diff --git a/src/app/api/result-code/[[...slug]]/route.ts b/src/app/api/result-code/[[...slug]]/route.ts index bb91632..f1fd480 100644 --- a/src/app/api/result-code/[[...slug]]/route.ts +++ b/src/app/api/result-code/[[...slug]]/route.ts @@ -1,14 +1,12 @@ import {NextRequest, NextResponse} from "next/server"; import {RouteContext} from "@/types/common"; import {createContactApi} from "@/lib/http-server"; -import {ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project"; +import {ResultCode} from "@/types/project"; import {errorToResponse} from "@kri/common/http"; -export const GET = async (req: NextRequest, context: RouteContext) => { +export const GET = async (_req: NextRequest, context: RouteContext) => { try { - const { searchParams } = new URL(req.url); const {slug = []} = await context.params; - const [action] = slug; const contactApi = await createContactApi(); if(slug.length === 1){ diff --git a/src/app/api/role/[[...slug]]/route.ts b/src/app/api/role/[[...slug]]/route.ts index daec883..af59c7c 100644 --- a/src/app/api/role/[[...slug]]/route.ts +++ b/src/app/api/role/[[...slug]]/route.ts @@ -4,7 +4,7 @@ import {RoleInfo} from "@/types/role"; import {errorToResponse} from "@kri/common/http"; import {RouteContext} from "@/types/common"; -export const GET = async (req: NextRequest, context: RouteContext) => { +export const GET = async (_req: NextRequest, context: RouteContext) => { try { const { slug = [] } = await context.params; const [action] = slug; diff --git a/src/app/api/user/[[...slug]]/route.ts b/src/app/api/user/[[...slug]]/route.ts index f4d3f87..e452ca0 100644 --- a/src/app/api/user/[[...slug]]/route.ts +++ b/src/app/api/user/[[...slug]]/route.ts @@ -149,7 +149,7 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => { } }; -export const DELETE = async (req: NextRequest, context: RouteContext) => { +export const DELETE = async (_req: NextRequest, context: RouteContext) => { try { const { slug = [] } = await context.params; const [userId] = slug ?? []; diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 156cf5b..11490c7 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -2,7 +2,7 @@ import type { Metadata } from "next"; import {Geist, Geist_Mono} from "next/font/google"; import { AppProvider } from "@/components/providers/AppProvider"; import "./globals.css"; -import {Toaster} from "sonner"; +import {Toaster} from "@/components/ui/sonner"; const geistSans = Geist({ variable: "--font-geist-sans", diff --git a/src/components/app-shell/AppMainLayout.tsx b/src/components/app-shell/AppMainLayout.tsx index 32aa52d..49d38c9 100644 --- a/src/components/app-shell/AppMainLayout.tsx +++ b/src/components/app-shell/AppMainLayout.tsx @@ -17,6 +17,7 @@ import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data" import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types"; import { cn } from "@/lib/utils"; import { FONT_SIZE } from "@/const/commonConst"; +import { ListJobWatcher } from "@/components/list/ListJobWatcher"; type AppMainLayoutProps = { children: ReactNode; @@ -235,6 +236,7 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo } > {children} + {mounted && auth.user && } ); diff --git a/src/components/data-table/DataTable.tsx b/src/components/data-table/DataTable.tsx index bbf206a..db0335d 100644 --- a/src/components/data-table/DataTable.tsx +++ b/src/components/data-table/DataTable.tsx @@ -121,7 +121,7 @@ export function DataTable({ [topPinnedRows, data, bottomPinnedRows], ) - const internalGetRowId = useCallback((row: TData, index: number) => { + const internalGetRowId = useCallback((_row: TData, index: number) => { if (index < topPinnedRows.length) return `__top-pinned-${index}` if (index >= topPinnedRows.length + data.length) { return `__bottom-pinned-${index - topPinnedRows.length - data.length}` diff --git a/src/components/dialog/ListBatchEditDialog.tsx b/src/components/dialog/ListBatchEditDialog.tsx index f0c7aaa..323dfbc 100644 --- a/src/components/dialog/ListBatchEditDialog.tsx +++ b/src/components/dialog/ListBatchEditDialog.tsx @@ -15,6 +15,7 @@ import { import { KriSingleSelect } from '@/components/common/KriAutoComplete' import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption' import { useDialog } from '@/hooks/useDialog' +import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate' import type { DialogId } from '@/store/jotai/dialog' import type { FilterValueOption, ListFilterTarget } from '@/types/list' import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project' @@ -47,6 +48,7 @@ export type BatchEditPayload = { } export type ListBatchEditDialogProps = { + prjctIdx: number dialogId?: DialogId open?: boolean onOpenChange?: (open: boolean) => void @@ -75,6 +77,7 @@ const resultCodeGroups: { type: Exclude; ] const ListBatchEditDialog = ({ + prjctIdx, dialogId = 'listBatchEditDialog', open, onOpenChange, @@ -98,6 +101,7 @@ const ListBatchEditDialog = ({ const rowInputRefs = useRef>(new Map()) const resolvedOpen = open ?? isDialogOpen(dialogId) + const gate = useListJobGate({ prjctIdx, jobType: 'LIST_UPDATE', active: resolvedOpen }) const defaultHeaderId = headerOptions[0]?.id ?? 0 const isFileHeader = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.listHderTy === ListHeaderConst.FILE @@ -168,6 +172,7 @@ const ListBatchEditDialog = ({ } const handleConfirm = async () => { + if (gate.submitBlocked || submitting) return setInvalidRowId(null) if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return @@ -203,7 +208,6 @@ const ListBatchEditDialog = ({ setSubmitting(true) try { await onConfirm({ rows: normalized, resultCodes: resultCodeSelections, surveyResultCodes, target }) - handleOpenChange(false) } finally { setSubmitting(false) } @@ -214,19 +218,23 @@ const ListBatchEditDialog = ({ open={resolvedOpen} onOpenChange={handleOpenChange} title={일괄 수정} - contentClassName="sm:max-w-[900px]" + contentClassName="sm:max-w-[900px] max-h-[90vh] overflow-y-auto" bodyClassName="space-y-4" footer={ <> - + {!gate.hasCurrentJob && ( + + )} } > + + {!gate.hasCurrentJob && <>

적용 대상

행 추가 + } ) } diff --git a/src/components/dialog/ListDownloadDialog.tsx b/src/components/dialog/ListDownloadDialog.tsx index 1d380b5..35a53af 100644 --- a/src/components/dialog/ListDownloadDialog.tsx +++ b/src/components/dialog/ListDownloadDialog.tsx @@ -8,6 +8,8 @@ import { Checkbox } from '@/components/ui/checkbox' import { Label } from '@/components/ui/label' import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group' import { useDialog } from '@/hooks/useDialog' +import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate' +import { LIST_DOWNLOAD_JOB_TYPE } from '@/const/listJobConst' import type { DialogId } from '@/store/jotai/dialog' import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption' import KriDateRangePicker from '@/components/common/KriDateRangePicker' @@ -20,6 +22,7 @@ import { } from '@/types/list' export type ListDownloadDialogProps = { + prjctIdx: number dialogId?: DialogId open?: boolean onOpenChange?: (open: boolean) => void @@ -37,6 +40,7 @@ const titleMap: Record = { } const ListDownloadDialog = ({ + prjctIdx, dialogId = 'listDownloadDialog', open, onOpenChange, @@ -55,6 +59,7 @@ const ListDownloadDialog = ({ const [submitting, setSubmitting] = useState(false) const resolvedOpen = open ?? isDialogOpen(dialogId) + const gate = useListJobGate({ prjctIdx, jobType: LIST_DOWNLOAD_JOB_TYPE[mode], active: resolvedOpen }) const handleOpenChange = (nextOpen: boolean) => { onOpenChange?.(nextOpen) @@ -66,6 +71,7 @@ const ListDownloadDialog = ({ } const handleDownload = async () => { + if (gate.submitBlocked || submitting) return if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return if (mode === 'contact-history') { @@ -93,7 +99,6 @@ const ListDownloadDialog = ({ contactHistoryType: mode === 'contact-history' ? contactHistoryType : undefined, historyOrder: mode === 'contact-history' ? historyOrder : undefined, }) - handleOpenChange(false) } finally { setSubmitting(false) } @@ -104,20 +109,24 @@ const ListDownloadDialog = ({ open={resolvedOpen} onOpenChange={handleOpenChange} title={{titleMap[mode]}} - contentClassName="sm:max-w-[560px]" + contentClassName="sm:max-w-[560px] max-h-[90vh] overflow-y-auto" bodyClassName="space-y-4" footer={ <> - + {!gate.hasCurrentJob && ( + + )} } > + + {!gate.hasCurrentJob && <> {mode === 'contact-history' ? (

조회 기간

@@ -189,6 +198,7 @@ const ListDownloadDialog = ({
) : null} + } ) } diff --git a/src/components/dialog/ListHeaderManageDialog.tsx b/src/components/dialog/ListHeaderManageDialog.tsx index 388640d..c3b1882 100644 --- a/src/components/dialog/ListHeaderManageDialog.tsx +++ b/src/components/dialog/ListHeaderManageDialog.tsx @@ -38,6 +38,7 @@ export type ListHeaderManageDialogProps = { prjctIdx: number rows: listHeader[] onConfirm: (rows: listHeader[]) => void | Promise + saveDisabled?: boolean } type ListHeaderRowProps = { @@ -179,6 +180,7 @@ const ListHeaderManageDialog = ({ prjctIdx, rows, onConfirm, + saveDisabled = false, }: ListHeaderManageDialogProps) => { const { isDialogOpen, showDialog, hideDialog } = useDialog() const [localRows, setLocalRows] = useState([]) @@ -299,6 +301,7 @@ const ListHeaderManageDialog = ({ } const handleConfirm = async () => { + if (saveDisabled || submitting) return const names = localRows.map((row) => row.listHderNm.trim()) const duplicateNames = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))] if (duplicateNames.length > 0) { @@ -354,12 +357,13 @@ const ListHeaderManageDialog = ({ - } > + {saveDisabled &&

리스트 작업이 진행 중이거나 작업 상태를 확인할 수 없어 헤더를 저장할 수 없습니다.

}
⚠️ 헤더명이 수정 되거나 헤더가 삭제되면 KON또는 KON-KIWI의 리스트 관련 하드코딩에 영향이 있을 수 있습니다. diff --git a/src/components/dialog/ListResetDialog.tsx b/src/components/dialog/ListResetDialog.tsx index a8d6691..19d52a5 100644 --- a/src/components/dialog/ListResetDialog.tsx +++ b/src/components/dialog/ListResetDialog.tsx @@ -3,23 +3,44 @@ import { useState } from 'react' import { KriDialog } from '@/components/common/KriDialog' import { Button } from '@/components/ui/button' +import { Checkbox } from '@/components/ui/checkbox' import { Label } from '@/components/ui/label' -import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group' import { useDialog } from '@/hooks/useDialog' +import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate' import type { DialogId } from '@/store/jotai/dialog' import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption' -import type { ListFilterTarget, ListResetScope } from '@/types/list' +import type { ListFilterTarget, ListResetSelection } from '@/types/list' +import type { ProjectSurvey } from '@/types/project' export type ListResetDialogProps = { + prjctIdx: number + /** 프로젝트에 연동된 설문 목록. undefined면 아직 불러오지 못한 상태로 보고 초기화를 막는다. */ + surveys?: ProjectSurvey[] dialogId?: DialogId open?: boolean onOpenChange?: (open: boolean) => void selectedSids: string[] filterSummary?: string[] - onConfirm: (payload: { target: ListFilterTarget; scope: ListResetScope }) => void | Promise + onConfirm: (payload: { target: ListFilterTarget; selection: ListResetSelection }) => void | Promise +} + +type ResetSurveyOption = { prjctSurveyIdx: number; surveyName: string } + +const toResetSurveyOptions = (surveys: ProjectSurvey[]): ResetSurveyOption[] => { + const seen = new Set() + return [...surveys] + .sort((a, b) => a.surveyOrder - b.surveyOrder) + .flatMap((survey) => { + const id = survey.prjctSurveyIdx + if (id == null || seen.has(id)) return [] + seen.add(id) + return [{ prjctSurveyIdx: id, surveyName: survey.surveyName }] + }) } const ListResetDialog = ({ + prjctIdx, + surveys, dialogId = 'listResetDialog', open, onOpenChange, @@ -29,10 +50,38 @@ const ListResetDialog = ({ }: ListResetDialogProps) => { const { isDialogOpen, showDialog, hideDialog } = useDialog() const [target, setTarget] = useState('selected') - const [scope, setScope] = useState('result-and-history') + const [resetList, setResetList] = useState(false) + const [resetContactHistory, setResetContactHistory] = useState(false) + const [resetInterviewHistory, setResetInterviewHistory] = useState(false) + const [selectedSurveyIds, setSelectedSurveyIds] = useState([]) const [submitting, setSubmitting] = useState(false) const resolvedOpen = open ?? isDialogOpen(dialogId) + const gate = useListJobGate({ prjctIdx, jobType: 'LIST_RESET', active: resolvedOpen }) + + const surveysReady = surveys !== undefined + const surveyOptions = toResetSurveyOptions(surveys ?? []) + const allSurveyIds = surveyOptions.map((survey) => survey.prjctSurveyIdx) + // 설문 목록이 다시 조회되어 빠진 설문이 있으면 요청에서 제외한다. + const checkedSurveyIds = allSurveyIds.filter((id) => selectedSurveyIds.includes(id)) + const hasSelection = resetList || resetContactHistory || resetInterviewHistory || checkedSurveyIds.length > 0 + + // 리스트 초기화는 모든 이력을 포함해야 하므로 이력을 전부 선택하고 잠근다. + // 해제 시에는 잠금 중 화면에 보이던 전체 선택 상태를 그대로 유지한다(잠금 중 로드된 설문 포함). + const handleResetListChange = (checked: boolean) => { + setResetList(checked) + setResetContactHistory(true) + setResetInterviewHistory(true) + setSelectedSurveyIds(allSurveyIds) + } + + const handleSurveyChange = (id: number, checked: boolean) => { + setSelectedSurveyIds((prev) => (checked ? [...prev.filter((v) => v !== id), id] : prev.filter((v) => v !== id))) + } + + const buildSelection = (): ListResetSelection => resetList + ? { resetList: true, resetContactHistory: true, resetInterviewHistory: true, resetSurveyIds: allSurveyIds } + : { resetList: false, resetContactHistory, resetInterviewHistory, resetSurveyIds: checkedSurveyIds } const handleOpenChange = (nextOpen: boolean) => { onOpenChange?.(nextOpen) @@ -43,14 +92,33 @@ const ListResetDialog = ({ hideDialog(dialogId) } + // '새 작업'(완료 확인)을 누르면 이전 작업의 대상·범위를 이어 쓰지 않도록 초기값으로 되돌린다. + const gatePanel = { + ...gate, + acknowledge: () => { + gate.acknowledge() + setTarget('selected') + setResetList(false) + setResetContactHistory(false) + setResetInterviewHistory(false) + setSelectedSurveyIds([]) + }, + } + + // 전체 대상은 선택 시점에도 한 번 확인한다. 취소하면 기존 대상을 유지한다. + const handleTargetChange = (next: ListFilterTarget) => { + if (next === 'all' && target !== 'all' && !confirm('전체 대상을 선택하면 프로젝트의 모든 리스트가 초기화 대상이 됩니다. 선택하시겠습니까?')) return + setTarget(next) + } + const handleConfirm = async () => { + if (gate.submitBlocked || submitting || !surveysReady || !hasSelection) return if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return if (target === 'all' && !confirm('전체 리스트가 초기화 됩니다. 진행하시겠습니까?')) return setSubmitting(true) try { - await onConfirm({ target, scope }) - handleOpenChange(false) + await onConfirm({ target, selection: buildSelection() }) } finally { setSubmitting(false) } @@ -61,24 +129,33 @@ const ListResetDialog = ({ open={resolvedOpen} onOpenChange={handleOpenChange} title={리스트 초기화} - contentClassName="sm:max-w-[700px]" + contentClassName="sm:max-w-[700px] max-h-[90vh] overflow-y-auto" bodyClassName="space-y-6 py-2" footer={ <> - + {!gate.hasCurrentJob && ( + + )} } > + + {!gate.hasCurrentJob && <>

초기화 대상

setTarget(v)} + onValueChange={handleTargetChange} idPrefix="list-reset-target" selectedSids={selectedSids} filterSummary={filterSummary} @@ -87,17 +164,65 @@ const ListResetDialog = ({

초기화 범위

- setScope(v as ListResetScope)} className="space-y-2"> -
- - +
+
+
+ handleResetListChange(checked === true)} + /> + +
+
+ setResetContactHistory(checked === true)} + /> + +
+
+ setResetInterviewHistory(checked === true)} + /> + +
-
- - -
- + {(!surveysReady || surveyOptions.length > 0) && ( +
+

설문 상태이력

+ {!surveysReady &&

설문 목록을 불러오는 중입니다.

} +
+ {surveyOptions.map((survey) => { + const id = `list-reset-scope-survey-${survey.prjctSurveyIdx}` + return ( +
+ handleSurveyChange(survey.prjctSurveyIdx, checked === true)} + /> + +
+ ) + })} +
+
+ )} +
+
    +
  • 선택한 이력은 해당 유형의 이력과 최신 상태가 함께 초기화되며, 선택하지 않은 이력은 유지됩니다.
  • +
  • 리스트를 선택하면 리스트와 모든 이력이 함께 초기화됩니다.
  • +
  • 설문 상태이력 초기화는 외부 설문 시스템의 실제 응답 데이터를 삭제하지 않습니다.
  • +
+ } ) } diff --git a/src/components/dialog/ListUploadDialog.tsx b/src/components/dialog/ListUploadDialog.tsx index 9efb84e..701ff48 100644 --- a/src/components/dialog/ListUploadDialog.tsx +++ b/src/components/dialog/ListUploadDialog.tsx @@ -6,10 +6,9 @@ import { KriDialog } from '@/components/common/KriDialog' import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' import { Label } from '@/components/ui/label' -// eslint-disable-next-line @typescript-eslint/no-unused-vars -import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group' import { KriSelect, KriSelectItem } from '@/components/common/KriSelect' import { useDialog } from '@/hooks/useDialog' +import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate' import { useLoading } from '@/hooks/useLoading' import type { DialogId } from '@/store/jotai/dialog' import { formatKst } from '@kri/common' @@ -22,6 +21,7 @@ export type ValidationOption = { } export type ListUploadDialogProps = { + prjctIdx: number dialogId?: DialogId open?: boolean onOpenChange?: (open: boolean) => void @@ -32,10 +32,12 @@ export type ListUploadDialogProps = { headerRows?: listHeader[] } -const ACCEPT_EXTENSIONS = ['.xlsx', '.xls', '.csv'] +const ACCEPT_EXTENSIONS = ['.xlsx'] +// 전체 초기화 후 등록(RESET_AND_INSERT)은 위험성 때문에 사용하지 않는다. const FIXED_UPLOAD_MODE = ListUploadMode.ADD_AND_CHANGE const ListUploadDialog = ({ + prjctIdx, dialogId = 'listUploadDialog', open, onOpenChange, @@ -52,8 +54,6 @@ const ListUploadDialog = ({ const [selectedFile, setSelectedFile] = useState(null) const [excelHeaders, setExcelHeaders] = useState([]) const [otherHeaderTypeMap, setOtherHeaderTypeMap] = useState>({}) - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const [uploadMode, setUploadMode] = useState(ListUploadMode.ADD_AND_CHANGE) const [submitting, setSubmitting] = useState(false) const [historyExpanded, setHistoryExpanded] = useState(false) const [validation, setValidation] = useState({ @@ -62,6 +62,7 @@ const ListUploadDialog = ({ }) const resolvedOpen = open ?? isDialogOpen(dialogId) + const gate = useListJobGate({ prjctIdx, jobType: 'LIST_UPLOAD', active: resolvedOpen }) const normalizedHistory = useMemo( () => @@ -94,7 +95,6 @@ const ListUploadDialog = ({ setSelectedFile(null) setExcelHeaders([]) setOtherHeaderTypeMap({}) - setUploadMode(ListUploadMode.ADD_AND_CHANGE) setSubmitting(false) setHistoryExpanded(false) setValidation({ @@ -137,7 +137,7 @@ const ListUploadDialog = ({ const { read, utils } = await import('xlsx') const buffer = await file.arrayBuffer() - const workbook = read(buffer, { type: 'array' }) + const workbook = read(buffer, { type: 'array', sheetRows: 1, sheets: 0 }) const firstSheet = workbook.SheetNames[0] if (!firstSheet) return [] const rows = utils.sheet_to_json<(string | number | null)[]>(workbook.Sheets[firstSheet], { header: 1, raw: false }) @@ -151,10 +151,11 @@ const ListUploadDialog = ({ const lower = file.name.toLowerCase() const valid = ACCEPT_EXTENSIONS.some((ext) => lower.endsWith(ext)) if (!valid) { - alert('엑셀 또는 CSV 파일만 업로드 가능합니다. (.xlsx, .xls, .csv)') + alert('XLSX 파일만 업로드 가능합니다. (.xlsx)') return } + if (file.size > 100 * 1024 * 1024) { alert('100MB 이하의 파일을 선택해 주세요.'); return } setSelectedFile(file) void withLoadingAsync(async () => { try { @@ -168,6 +169,7 @@ const ListUploadDialog = ({ } const handleSubmit = async () => { + if (gate.submitBlocked || submitting) return if (!selectedFile) { alert('업로드할 파일을 선택해 주세요.') return @@ -177,7 +179,7 @@ const ListUploadDialog = ({ try { const specificHeader = Object.fromEntries( Object.entries(otherHeaderTypeMap) - .map(([index, value]) => [String(Number(index) + 1), value]) + .map(([index, value]) => [String(Math.max(101, ...orderedHeaderRows.map(row => row.listHderId + 1)) + Number(index) - baseHeaderRows.length), value]) .filter(([, value]) => value !== ListHeaderConst.TEXT), ) @@ -187,8 +189,6 @@ const ListUploadDialog = ({ checkDuplicatePhone: validation.checkPhoneDuplicate, ...(Object.keys(specificHeader).length > 0 ? { specificHeader } : {}), }) - resetState() - handleOpenChange(false) } catch (e) { console.error(e) } finally { @@ -256,44 +256,23 @@ const ListUploadDialog = ({ open={resolvedOpen} onOpenChange={handleDialogOpenChange} title={리스트 업로드} - contentClassName="w-[min(960px,95vw)] max-w-[95vw] sm:max-w-[min(960px,95vw)] overflow-hidden" - bodyClassName="min-w-0 space-y-6 py-2" + contentClassName="w-[min(960px,95vw)] max-w-[95vw] sm:max-w-[min(960px,95vw)] max-h-[90vh] grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden" + bodyClassName="min-w-0 space-y-6 overflow-y-auto py-2" footer={ <> - + {!gate.hasCurrentJob && ( + + )} } > - { - /* -
- - setUploadMode(Number(value) as ListUploadMode)} - className="flex flex-wrap items-center gap-6" - > -
- - -
-
- - -
-
-
- */ - } + + {!gate.hasCurrentJob && <>
@@ -425,6 +404,7 @@ const ListUploadDialog = ({
)}
+ } ) } diff --git a/src/components/dialog/MessageHistoryDialog.tsx b/src/components/dialog/MessageHistoryDialog.tsx index 616043d..088b134 100644 --- a/src/components/dialog/MessageHistoryDialog.tsx +++ b/src/components/dialog/MessageHistoryDialog.tsx @@ -8,13 +8,15 @@ import type { DataTableColumn } from '@/components/data-table/DataTable.type' import { useDialog } from '@/hooks/useDialog' import { useSelectedProject } from '@/hooks/useSelectedProject' import { useBulkSendDetailExcelMutation, useBulkSendDetailQuery, useBulkSendListQuery } from '@/query/message' -import { MessageType } from '@kri/common/noti-hub' +import { isSendCancelable, MessageType } from '@kri/common/noti-hub' import { MESSAGE_TYPE_LABEL } from '@/const/messageTemplateConst' import { downloadBase64File, XLSX_MIME_TYPE } from '@kri/common/browser' import { formatKst } from '@kri/common' import type { PaginationState } from '@tanstack/react-table' import type { DialogId } from '@/store/jotai/dialog' import type { BulkSendInfo, SendResultInfo } from '@kri/common/noti-hub' +import type { SendCancelRequest } from '@/types/message' +import { useSendCancel } from '@/hooks/useSendCancel' import {clientEnv} from "@/lib/env.client"; import { formatKoreanPhoneNumber } from "@/utils/phone"; @@ -32,7 +34,40 @@ const tabLabelMap: Record = { kko: '알림톡', } -const historyColumns: DataTableColumn[] = [ +// 취소 일시가 없으면 빈 칸으로 둔다. +const formatCancelDt = (cancelDt: string | undefined) => (cancelDt ? formatKst(cancelDt, 'dateTime') : null) + +// 버튼만 셀 가운데에 둔다. 취소 일시는 다른 컬럼과 같은 기본 정렬을 따른다. +const CancelButton = ({ disabled, onClick }: { disabled: boolean; onClick: () => void }) => ( +
+ +
+) + +type CancelColumnOptions = { + /** false(면접원)이면 취소 버튼 대신 취소 일시(없으면 빈 칸)를 표시한다. */ + canCancel: boolean + onCancel: (request: SendCancelRequest) => void + cancelPending: boolean +} + +// 버튼은 서버의 cancelable로만 판단한다(값이 없는 구버전 응답은 취소 불가). 최종 결과는 취소 API 응답 건수로 안내한다. +const canCancelDetail = (row: SendResultInfo) => isSendCancelable(row) && !!row.sendIdx + +// 취소 컬럼에는 취소 가능하면 버튼, 아니면 취소 일시(없으면 빈 칸) 중 하나만 표시한다. +const buildHistoryColumns = ({ canCancel, onCancel, cancelPending }: CancelColumnOptions): DataTableColumn[] => [ { id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') }, { id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') }, { id: 'resve', header: '구분', accessorFn: (row) => (row.resve ? '예약' : '즉시') }, @@ -40,16 +75,44 @@ const historyColumns: DataTableColumn[] = [ { id: 'sendCnt', header: '발송수', accessorFn: (row) => row.sendCnt.toLocaleString() }, { id: 'succesCnt', header: '성공', accessorFn: (row) => row.succesCnt.toLocaleString() }, { id: 'failCnt', header: '실패', accessorFn: (row) => row.failCnt.toLocaleString() }, + { + id: 'cancelDt', + header: '취소 일시', + accessorFn: (row) => row.cancelDt ?? '', + cell: ({ row }) => + canCancel && isSendCancelable(row.original) ? ( + onCancel({ type: 'bulk', bulkSendKey: row.original.bulkSendKey })} + /> + ) : ( + formatCancelDt(row.original.cancelDt) + ), + }, { id: 'completeDt', header: '완료 일시', accessorFn: (row) => (row.completeDt ? formatKst(row.completeDt, 'dateTime') : '-') }, { id: 'regUser', header: '등록자', accessorFn: (row) => row.regUser ?? '-' }, ] -const detailColumns: DataTableColumn[] = [ +const buildDetailColumns = ({ canCancel, onCancel, cancelPending }: CancelColumnOptions): DataTableColumn[] => [ { id: 'sendTy', header: '유형', accessorFn: (row) => MESSAGE_TYPE_LABEL[row.sendTy] ?? String(row.sendTy) }, { id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || (row.destTel ? formatKoreanPhoneNumber(row.destTel) : '') || '-' }, { id: 'destNm', header: '수신자명', accessorFn: (row) => row.destNm ?? '-' }, { id: 'sendFrom', header: '발신지', accessorFn: (row) => row.sendEml || (row.sendTel ? formatKoreanPhoneNumber(row.sendTel) : '') || '-' }, { id: 'resultViewLabel', header: '결과', accessorFn: (row) => row.resultViewLabel || row.resultLabel || String(row.resultCode) }, + { + // 개별 건의 현재 취소 상태는 결과 컬럼(resultCode 라벨)으로 표시한다. + id: 'cancelDt', + header: '취소 일시', + accessorFn: (row) => row.cancelDt ?? '', + cell: ({ row }) => { + const { sendIdx, cancelDt } = row.original + return canCancel && canCancelDetail(row.original) && sendIdx ? ( + onCancel({ type: 'single', sendIdx })} /> + ) : ( + formatCancelDt(cancelDt) + ) + }, + }, { id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') }, { id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') }, ] @@ -92,6 +155,9 @@ const MessageHistoryDialog = ({ enabled && !!selectedKey, ) const detailExcelMutation = useBulkSendDetailExcelMutation() + const { canCancel, cancel, isPending: cancelPending } = useSendCancel() + const historyColumns = buildHistoryColumns({ canCancel, onCancel: cancel, cancelPending }) + const detailColumns = buildDetailColumns({ canCancel, onCancel: cancel, cancelPending }) const handleOpenChange = (nextOpen: boolean) => { onOpenChange?.(nextOpen) @@ -130,7 +196,7 @@ const MessageHistoryDialog = ({ title={발송 이력} contentClassName="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto" closeLabel="닫기" - bodyClassName="space-y-4" + bodyClassName="min-w-0 space-y-4" >
- + {!gate.hasCurrentJob && ( + + )} } > + + {!gate.hasCurrentJob && <>
@@ -319,6 +324,7 @@ const MessageSendDialog = ({
+ } ) } diff --git a/src/components/kri-editor/KriEditorHtmlOnly.tsx b/src/components/kri-editor/KriEditorHtmlOnly.tsx index 0e4c845..edecbd2 100644 --- a/src/components/kri-editor/KriEditorHtmlOnly.tsx +++ b/src/components/kri-editor/KriEditorHtmlOnly.tsx @@ -65,7 +65,6 @@ export function KriEditorHtmlOnly({ React.useEffect(() => { applyExternalValue(value || '') // 최초 마운트 시 1회만 실행 — 이후 value 변경은 아래 effect가 처리한다. - // eslint-disable-next-line react-hooks/exhaustive-deps }, []) React.useEffect(() => { diff --git a/src/components/list-contact/ListContactEventPanel.tsx b/src/components/list-contact/ListContactEventPanel.tsx index 8758f51..70384ea 100644 --- a/src/components/list-contact/ListContactEventPanel.tsx +++ b/src/components/list-contact/ListContactEventPanel.tsx @@ -10,9 +10,10 @@ import { useAddListEventMutation, useDeleteListEventMutation, useListEventHistor import { useSendResultBySidQuery } from '@/query/message' import { useInternalInfoQuery } from '@/query/internal' import { clientEnv } from '@/lib/env.client' -import { ChannelType } from '@kri/common/noti-hub' +import { ChannelType, isSendCancelable } from '@kri/common/noti-hub' import { MESSAGE_TYPE_LABEL } from '@/const/messageTemplateConst' import type { SendResultInfo } from '@kri/common/noti-hub' +import { useSendCancel } from '@/hooks/useSendCancel' import { formatKst } from '@kri/common' import { type ResultCode, ResultCodeType } from '@/types/project' import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst' @@ -240,6 +241,8 @@ const ContactEventSection = ({ } const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results: SendResultInfo[] }) => { + const { canCancel: canCancelSend, cancel, isPending: cancelPending } = useSendCancel() + if (isLoading) { return
불러오는 중...
} @@ -257,17 +260,38 @@ const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results: 수신처 결과 발송일시 + {canCancelSend ? 예약 취소 : null} - {results.map((item) => ( - - {MESSAGE_TYPE_LABEL[item.sendTy] ?? String(item.sendTy)} - {item.destEml || item.destTel || '-'} - {item.resultViewLabel || item.resultLabel || item.resultCode} - {formatKst(item.sendDt, 'dateHourMin')} - - ))} + {results.map((item) => { + const { sendIdx } = item + // 버튼은 서버의 cancelable로만 판단한다(값이 없는 구버전 응답은 취소 불가). 최종 결과는 취소 API 응답 건수로 안내한다. + const canCancel = isSendCancelable(item) && !!sendIdx + return ( + + {MESSAGE_TYPE_LABEL[item.sendTy] ?? String(item.sendTy)} + {item.destEml || item.destTel || '-'} + {item.resultViewLabel || item.resultLabel || item.resultCode} + {formatKst(item.sendDt, 'dateHourMin')} + {canCancelSend ? ( + + {canCancel && sendIdx ? ( + + ) : null} + + ) : null} + + ) + })}
diff --git a/src/components/list-contact/ListContactInfoPanel.tsx b/src/components/list-contact/ListContactInfoPanel.tsx index 5d19a38..6dff3fe 100644 --- a/src/components/list-contact/ListContactInfoPanel.tsx +++ b/src/components/list-contact/ListContactInfoPanel.tsx @@ -1,6 +1,6 @@ 'use client' -import { useEffect, useRef, useState, type ReactNode } from 'react' +import { useRef, useState, type ReactNode } from 'react' import { Mail, MessageCircle, MessageSquare, Paperclip, Phone, QrCode } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' @@ -78,7 +78,7 @@ const FieldRow = ({ label, editable, children }: { label: string; editable?: boo