diff --git a/src/app/(pages)/(main)/assign/list/page.tsx b/src/app/(pages)/(main)/assign/list/page.tsx index 91ce3e7..c1700b8 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,9 @@ 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 { 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 +59,9 @@ 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 { gate: assignGate, dataRevision } = useListJobPageMonitor(prjctIdx, 'LIST_ASSIGN', enabled) + const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom) const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: effectiveAssignType }) const resultCodeArray = useMemo(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]) @@ -122,7 +127,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 +144,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 +198,10 @@ const ListAssignPage = () => { />
-
+
+ { 예약 이관 )} - - @@ -230,6 +250,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..4d1e2de 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,22 @@ 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 { 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 { @@ -50,7 +54,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 +88,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 +115,55 @@ const ListManagePage = () => { const canManageList = isManager(userRole); // 리스트 초기화/헤더 관리/업로드는 내부 관리자 전용 — 외주사 계정에는 노출되면 안 됨. const isInternal = isInternalManager(userRole); + const { gate: pageGate, dataRevision } = useListJobPageMonitor(prjctIdx, 'LIST_RESET', enabled) + 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 +181,6 @@ const ListManagePage = () => { removeLastListVisit() } setRestoreResolved(true) - // eslint-disable-next-line react-hooks/exhaustive-deps }, [mounted, isSelectedProjectHydrated, restoreResolved]) useEffect(() => { @@ -223,27 +263,14 @@ const ListManagePage = () => { } const handleResetConfirm = async (payload: { target: ListFilterTarget; scope: ListResetScope }) => { - const listFilter = buildTargetFilter(payload.target) - const resetCount = await resetListMutation.mutateAsync({ + await submitJob.mutateAsync({ jobType: 'LIST_RESET', path: 'reset', body: { resetMode: payload.scope === 'result-and-history' ? ListResetMode.HIST : ListResetMode.ALL, - listFilter, - }) - alert(`${resetCount}건 삭제 되었습니다.`) - refreshList() + listFilter: buildTargetFilter(payload.target), + } }) } 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 +289,46 @@ 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 ( +
+ {canManageList && ( showDialog('listResetDialog')} - onHeaderManage={() => showDialog('listHeaderManageDialog')} + onHeaderManage={() => { if (!pageGate.submitBlocked) showDialog('listHeaderManageDialog') }} onUpload={() => showDialog('listUploadDialog')} onDownload={openDownloadDialog} onMessageSend={openMessageDialog} @@ -320,6 +348,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 +372,13 @@ 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)/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..fd21ddd 100644 --- a/src/app/api/message-send/[[...slug]]/route.ts +++ b/src/app/api/message-send/[[...slug]]/route.ts @@ -2,7 +2,6 @@ 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 {MessageSendChannel, SendSingleResponse} from "@/types/message"; const isChannel = (value: string): value is MessageSendChannel => @@ -28,11 +27,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..e98da77 100644 --- a/src/components/dialog/ListResetDialog.tsx +++ b/src/components/dialog/ListResetDialog.tsx @@ -6,11 +6,13 @@ import { Button } from '@/components/ui/button' 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' export type ListResetDialogProps = { + prjctIdx: number dialogId?: DialogId open?: boolean onOpenChange?: (open: boolean) => void @@ -20,6 +22,7 @@ export type ListResetDialogProps = { } const ListResetDialog = ({ + prjctIdx, dialogId = 'listResetDialog', open, onOpenChange, @@ -33,6 +36,7 @@ const ListResetDialog = ({ const [submitting, setSubmitting] = useState(false) const resolvedOpen = open ?? isDialogOpen(dialogId) + const gate = useListJobGate({ prjctIdx, jobType: 'LIST_RESET', active: resolvedOpen }) const handleOpenChange = (nextOpen: boolean) => { onOpenChange?.(nextOpen) @@ -44,13 +48,13 @@ const ListResetDialog = ({ } const handleConfirm = async () => { + if (gate.submitBlocked || submitting) return if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return if (target === 'all' && !confirm('전체 리스트가 초기화 됩니다. 진행하시겠습니까?')) return setSubmitting(true) try { await onConfirm({ target, scope }) - handleOpenChange(false) } finally { setSubmitting(false) } @@ -61,19 +65,23 @@ 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 && <>

초기화 대상

+ } ) } 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/MessageSendDialog.tsx b/src/components/dialog/MessageSendDialog.tsx index 9617e9d..7a4b9d6 100644 --- a/src/components/dialog/MessageSendDialog.tsx +++ b/src/components/dialog/MessageSendDialog.tsx @@ -11,7 +11,6 @@ import { useDialog } from '@/hooks/useDialog' import { useSelectedProject } from '@/hooks/useSelectedProject' import { useMainTemplateIdxQuery, - useSendBulkMessageMutation, useTemplateListQuery, useTemplateQuery, } from '@/query/message' @@ -23,6 +22,9 @@ import type { ListTableRow } from '@/components/table-column/ListTableColumn' import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption' import MessageSendPreview from '@/components/message-template/MessageSendPreview' import type { MessageSendChannel, TemplateSummaryWithPurpose } from '@/types/message' +import { useSubmitListJob } from '@/query/list-job' +import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate' +import { MESSAGE_JOB_TYPE } from '@/const/listJobConst' import { MESSAGE_CHANNEL_TYPE, TEMPLATE_PURPOSE } from '@/const/messageTemplateConst' export type MessageSendMode = MessageSendChannel @@ -71,6 +73,7 @@ const MessageSendDialog = ({ const resolvedOpen = open ?? isDialogOpen(dialogId) const prjctIdx = selectedProject?.prjctIdx ?? 0 + const gate = useListJobGate({ prjctIdx, jobType: MESSAGE_JOB_TYPE[mode], active: resolvedOpen }) const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? '' const enabled = resolvedOpen && !!selectedProject && prjctIdx > 0 @@ -98,7 +101,7 @@ const MessageSendDialog = ({ [listHeaders, headerType], ) - const sendBulkMessageMutation = useSendBulkMessageMutation(mode, prjctIdx) + const sendBulkMessageMutation = useSubmitListJob(prjctIdx) const mainTemplateAppliedRef = useRef(false) @@ -158,6 +161,7 @@ const MessageSendDialog = ({ } const handleConfirm = async () => { + if (gate.submitBlocked || submitting) return if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return if (!selectedTemplate || !templateIdx) { alert('템플릿을 선택해 주세요.') @@ -187,21 +191,18 @@ const MessageSendDialog = ({ setSubmitting(true) try { - const res = await sendBulkMessageMutation.mutateAsync({ + await sendBulkMessageMutation.mutateAsync({ + jobType: MESSAGE_JOB_TYPE[mode], + path: `messages/${mode}`, + body: { tmplatIdx: templateIdx, resve: scheduleType === 'reserve', sendDt: scheduleType === 'reserve' ? toReserveSendDt(reserveAt) : undefined, listFilter, destHeaderIds: [targetHeaderId], + }, }) - - if (res.failCount > 0) { - alert(`대상 ${res.targetCount}건 중 ${res.acceptCount}건 접수, ${res.failCount}건 실패했습니다.`) - } else { - alert(`대상 ${res.targetCount}건 발송 요청이 완료되었습니다.`) - } onSent?.() - handleOpenChange(false) } catch (e) { console.error(e) } finally { @@ -214,19 +215,23 @@ const MessageSendDialog = ({ open={resolvedOpen} onOpenChange={handleOpenChange} title={{titleMap[mode]}} - contentClassName="sm:max-w-[1100px] max-h-[90vh] overflow-y-auto" - bodyClassName="grid grid-cols-1 lg:grid-cols-2 gap-6" + contentClassName={gate.hasCurrentJob ? "sm:max-w-[700px] max-h-[90vh] overflow-y-auto" : "sm:max-w-[1100px] max-h-[90vh] overflow-y-auto"} + bodyClassName={gate.hasCurrentJob ? "space-y-4" : "grid grid-cols-1 lg:grid-cols-2 gap-6"} footer={ <> - + {!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/ListContactInfoPanel.tsx b/src/components/list-contact/ListContactInfoPanel.tsx index 5d19a38..03f4b68 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' diff --git a/src/components/list/ListJobGate.tsx b/src/components/list/ListJobGate.tsx new file mode 100644 index 0000000..d55542c --- /dev/null +++ b/src/components/list/ListJobGate.tsx @@ -0,0 +1,156 @@ +'use client' + +import { useEffect } from 'react' +import { useAtom } from 'jotai' +import { HttpError } from '@kri/common/http' +import { Button } from '@/components/ui/button' +import { ListJobProgress } from '@/components/list/ListJobProgress' +import { useAuth } from '@/hooks/useAuth' +import { isAvailabilityUnsupported, useListJob, useListJobAvailability, useUploadResetActive } from '@/query/list-job' +import { findTrackedListJob, trackListJob, untrackListJob, useTrackedListJobs } from '@/store/list-job-tracker' +import { listJobLabel } from '@/const/listJobConst' +import { blockerJobLabel, blockerPhaseLabel, blockerUserLabel, describeListJobAvailability } from '@/utils/listJobAvailability' +import { isActiveListJob, type ListJobType } from '@/types/list-job' +import { listJobOpenRequestAtom } from '@/store/jotai/list-job' + +export type ListJobGateStatus = 'idle' | 'checking' | 'allowed' | 'blocked' | 'error' | 'unsupported' + +/** + * 작업 다이얼로그(또는 배정 버튼 영역)에서 쓰는 접수 가능 여부와 내 현재 작업 상태. + * - availability: 다이얼로그는 차단 중 3초, 페이지는 평상시 10초·차단 중 3초 조회한다. + * - 내 현재 작업: localStorage 기록(사용자·프로젝트·jobType)의 작업 상세를 보여준다. + * requestLabel은 같은 jobType 안에서 이름이 갈리는 경우(배정/배정 초기화)에 넘긴다. + */ +export function useListJobGate({ prjctIdx, jobType, active, requestLabel, pollWhileIdle = false }: { + prjctIdx: number + jobType: ListJobType + active: boolean + requestLabel?: string + pollWhileIdle?: boolean +}) { + const { auth } = useAuth() + const userId = auth.user?.userId + const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom) + const requestMatches = openRequest?.userId === userId && openRequest?.prjctIdx === prjctIdx && openRequest?.jobType === jobType + const availability = useListJobAvailability(prjctIdx, jobType, active, pollWhileIdle) + const uploadResetBlockers = availability.isSuccess && !availability.data.allowed + ? availability.data.blockers.filter(blocker => blocker.blockingPhase === 'ACTIVE' && (blocker.jobType === 'LIST_UPLOAD' || blocker.jobType === 'LIST_RESET')) + : [] + const uploadResetActive = useUploadResetActive(prjctIdx, active && uploadResetBlockers.length > 0) + const uploadResetJob = uploadResetActive.isSuccess && uploadResetActive.data.active + && uploadResetBlockers.some(blocker => blocker.jobType === uploadResetActive.data.job?.jobType) + ? uploadResetActive.data.job : null + const tracked = findTrackedListJob(useTrackedListJobs(), userId ?? '', prjctIdx, jobType) + const jobKey = requestMatches ? openRequest.jobKey : tracked?.jobKey ?? null + const detail = useListJob(prjctIdx, jobKey, active) + const job = detail.data?.jobKey === jobKey ? detail.data : undefined + const finishedJob = job && !isActiveListJob(job.jobStatus) ? job : undefined + const detailNotFound = detail.error instanceof HttpError && detail.error.status === 404 + + useEffect(() => { + if (!active && requestMatches && openRequest.opened) setOpenRequest(null) + }, [active, openRequest, requestMatches, setOpenRequest]) + + // 다른 탭·기기에서 접수한 내 작업이면 기록을 채워 진행 상태를 보여준다. + useEffect(() => { + const mine = availability.data?.blockers.find(blocker => + blocker.mine && blocker.jobKey && blocker.jobType === jobType && blocker.blockingPhase === 'ACTIVE') + if (mine?.jobKey && userId) trackListJob({ userId, prjctIdx, jobType, jobKey: mine.jobKey }) + }, [availability.data, jobType, prjctIdx, userId]) + + const status: ListJobGateStatus = !active ? 'idle' + : isAvailabilityUnsupported(availability.error) ? 'unsupported' + : availability.isError ? 'error' + : !availability.data || (!pollWhileIdle && availability.isFetching && availability.data.allowed) ? 'checking' + : availability.data.allowed ? 'allowed' : 'blocked' + + return { + prjctIdx, + jobType, + requestLabel: requestLabel ?? listJobLabel(jobType), + status, + availability: availability.data, + availabilityUpdatedAt: availability.dataUpdatedAt, + availabilitySucceeded: availability.isSuccess, + refetch: () => void availability.refetch(), + job, + hasCurrentJob: !!jobKey, + detailPending: active && !!jobKey && detail.isPending, + detailError: active && !!jobKey && detail.isError, + detailNotFound, + refetchDetail: () => void detail.refetch(), + uploadResetJob, + finishedJob, + // 확인 중·조회 실패·차단이면 실행 버튼을 막는다. 404(미배포)는 서버 판단에 맡긴다. + submitBlocked: status === 'checking' || status === 'error' || status === 'blocked' || (!!job && isActiveListJob(job.jobStatus)), + /** 완료 상태를 본 뒤 닫거나 확인을 누르면 기록을 지운다. 진행 중이면 유지한다. */ + acknowledge: () => { + if (!finishedJob && !detailNotFound) return + if (jobKey) untrackListJob(jobKey) + if (requestMatches) setOpenRequest(null) + }, + } +} + +export type ListJobGate = ReturnType + +export function ListJobGatePanel({ gate, className = '', showCurrentJob = true, acknowledgeLabel = '확인' }: { gate: ListJobGate; className?: string; showCurrentJob?: boolean; acknowledgeLabel?: string }) { + const { status, availability, job, uploadResetJob } = gate + // 내 현재 작업으로 이미 보여주는 항목은 차단 목록에서 뺀다. + const listedBlockers = availability?.blockers.filter(blocker => !(showCurrentJob && blocker.mine && blocker.jobKey && blocker.jobKey === job?.jobKey)) ?? [] + const remainingBlockerCount = availability ? Math.max(0, availability.blockerCount - (availability.blockers.length - listedBlockers.length)) : 0 + const description = status === 'blocked' && availability && remainingBlockerCount > 0 + ? describeListJobAvailability({ ...availability, blockers: listedBlockers, blockerCount: remainingBlockerCount }, gate.jobType, gate.requestLabel) + : null + const uploadResetDetailShown = showCurrentJob && uploadResetJob?.mine && !!uploadResetJob.jobKey && job?.jobKey === uploadResetJob.jobKey + + if (!(showCurrentJob && (job || gate.detailPending || gate.detailError)) && status !== 'checking' && status !== 'error' && !description) return null + + return ( +
+ {showCurrentJob && gate.detailPending &&

현재 작업 상태를 조회하는 중입니다.

} + {showCurrentJob && gate.detailError &&
+

{gate.detailNotFound ? '작업을 찾을 수 없습니다. 보관 기간이 지났거나 접근할 수 없는 작업입니다.' : '현재 작업 상태를 불러오지 못했습니다.'}

+ +
} + {showCurrentJob && job && ( +
+
+

내 현재 작업 · {listJobLabel(job.jobType, job.operation)}

+ {gate.finishedJob && } +
+ +
+ )} + {status === 'checking' &&

작업 가능 여부를 확인하는 중입니다.

} + {status === 'error' && ( +

+ 작업 가능 여부를 확인하지 못했습니다.{' '} + +

+ )} + {description && ( +
+

{description.message}

+ {listedBlockers.length > 0 && ( +
    + {listedBlockers.map((blocker, index) => ( +
  • + {blockerJobLabel(blocker)} · {blocker.mine ? '나' : blockerUserLabel(blocker)} · {blockerPhaseLabel(blocker)} · 접수 {blocker.regDt.replace('T', ' ').slice(0, 19)} +
  • + ))} +
+ )} + {description.omittedCount > 0 &&

외 {description.omittedCount.toLocaleString()}건은 표시하지 않았습니다.

} +
+ )} + {status === 'blocked' && uploadResetJob && !uploadResetDetailShown && ( +
+

{listJobLabel(uploadResetJob.jobType)} 처리 {uploadResetJob.processedSidCnt.toLocaleString()} + {uploadResetJob.totalSidCnt === null ? '건 · 전체 집계 중' : ` / ${uploadResetJob.totalSidCnt.toLocaleString()}건`}

+ {uploadResetJob.totalSidCnt !== null && uploadResetJob.totalSidCnt > 0 && } +
+ )} +
+ ) +} diff --git a/src/components/list/ListJobProgress.tsx b/src/components/list/ListJobProgress.tsx new file mode 100644 index 0000000..00e848a --- /dev/null +++ b/src/components/list/ListJobProgress.tsx @@ -0,0 +1,195 @@ +'use client' + +import { useState } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { Button } from '@/components/ui/button' +import { nextApi } from '@/lib/http-client' +import { useAuth } from '@/hooks/useAuth' +import { clientEnv } from '@/lib/env.client' +import { LIST_JOB_STAGE_LABEL, LIST_JOB_STATUS_LABEL, listJobLabel } from '@/const/listJobConst' +import { isActiveListJob, type ListJob, type ListJobFailurePage } from '@/types/list-job' + +type JobDetailPath = 'validation-errors' | 'sid-failures' | 'range-failures' | 'message-report/batches' | 'message-report/preparation-failures' +type JobDetailSection = { path: JobDetailPath; label: string } + +function getDetailSections(job: ListJob): JobDetailSection[] { + const p = job.progress ?? {} + const positive = (value: unknown) => typeof value === 'number' && value > 0 + if (job.jobType === 'LIST_UPLOAD') { + const sections: JobDetailSection[] = [] + if (positive(p.validationErrorCnt) || job.jobStage === 'VALIDATION_FAILED' || job.errorCode === 'LIST_UPLOAD_VALIDATION_FAILED') { + sections.push({ path: 'validation-errors', label: '파일 검증 오류' }) + } + if (positive(p.deleteFailedRangeCnt) || positive(p.insertFailedRangeCnt) || job.errorCode === 'PARTIAL_RANGE_FAILURE') { + sections.push({ path: 'range-failures', label: '구간 실패' }) + } + return sections + } + if (['LIST_RESET', 'LIST_UPDATE', 'LIST_ASSIGN'].includes(job.jobType)) { + return job.failedSidCnt > 0 ? [{ path: 'sid-failures', label: '실패한 리스트' }] : [] + } + if (['EMAIL_BULK', 'SMS_BULK', 'KKO_BULK'].includes(job.jobType)) { + const sections: JobDetailSection[] = [] + if (positive(p.recordedBatchCnt)) sections.push({ path: 'message-report/batches', label: '발송 접수 결과' }) + if (positive(p.preparationFailedSidCnt)) sections.push({ path: 'message-report/preparation-failures', label: '발송 준비 실패' }) + return sections + } + return [] +} + +const DETAIL_FIELDS: Record = { + 'validation-errors': [['rowNumber', '행'], ['sid', 'SID'], ['fieldName', '항목'], ['errorMessage', '사유']], + 'sid-failures': [['sid', 'SID'], ['code', '사유'], ['chunkNo', '처리 구간']], + 'range-failures': [['stage', '단계'], ['attempt', '처리 순번'], ['code', '사유']], + 'message-report/batches': [ + ['batchNo', '접수 묶음'], ['status', '접수 상태'], ['targetRecipientCnt', '대상 수신처'], + ['acceptedRecipientCnt', '접수'], ['failedRecipientCnt', '실패'], ['unknownRecipientCnt', '접수 여부 불명'], + ], + 'message-report/preparation-failures': [['code', '사유']], +} +const DETAIL_VALUE_LABEL: Record = { + LIST_NOT_FOUND: '대상 리스트가 삭제되었거나 존재하지 않습니다.', + RANGE_EXECUTION_FAILED: '구간 처리 실패', TARGET_READ_FAILED: '대상 리스트 조회 실패', + ROW_PREPARATION_FAILED: '발송 내용 준비 실패', NO_DESTINATION: '수신처 없음', INVALID_DESTINATION: '수신처 형식 오류', + ACCEPTED: '접수 완료', PARTIAL: '일부 접수', REJECTED: '접수 거절', UNKNOWN: '접수 여부 불명', + INVALID_RESPONSE: '접수 응답 확인 불가', BULK_CREATION_FAILED: '발송 작업 생성 실패', CANCELLED_BEFORE_SEND: '발송 요청 전 중단', +} +const n = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString() : '-' +const text = (value: unknown) => typeof value === 'string' || typeof value === 'number' ? String(value).slice(0, 500) : '' +const stageLabel = (jobStage: string) => LIST_JOB_STAGE_LABEL[jobStage] ?? '처리 중' + +function SidProgress({ total, processed }: { total: number | null; processed: number }) { + if (total === null || total <= 0) return null + return +} + +function Progress({ job }: { job: ListJob }) { + const p = job.progress ?? {} + if (job.jobType.endsWith('_BULK')) return ( +
+

수신처 {n(p.preparedRecipientCnt)} · 접수 {n(p.acceptedRecipientCnt)} · 실패 {n(p.failedRecipientCnt)} · 접수 여부 불명 {n(p.unknownRecipientCnt)}

+

발송 준비 실패 SID {n(p.preparationFailedSidCnt)} · 처리 수신처 {n(p.processedRecipientCnt)} / {n(p.preparedRecipientCnt)}

+

발송 요청의 접수 결과입니다. 실제 전달 결과는 발송 이력에서 확인하세요. 접수 여부 불명 건은 재발송 전에 확인해야 합니다.

+
+ ) + if (job.jobType.endsWith('_DOWNLOAD')) return

파일 처리 대상 {n(p.processedSidCnt)} · 작성 행 {n(p.writtenRowCnt)} · 작성 파일 {n(p.writtenFileCnt)}

+ return ( +
+

전체 {job.totalSidCnt === null ? '집계 중' : n(job.totalSidCnt)} · 반영 완료 {n(job.completedSidCnt)} · SID 실패 {n(job.failedSidCnt)} · 완료 구간 {n(job.completedChunkCnt)}

+ {typeof p.deleteTotalSidCnt === 'number' &&

기존 데이터 삭제 {n(p.deleteCompletedSidCnt)} / {n(p.deleteTotalSidCnt)} · 삭제 실패 구간 {n(p.deleteFailedRangeCnt)}

} + {typeof p.insertTotalSidCnt === 'number' &&

신규 등록 {n(p.insertCompletedSidCnt)} / {n(p.insertTotalSidCnt)} · 등록 실패 구간 {n(p.insertFailedRangeCnt)}

} + +
+ ) +} + +function JobDetailItem({ path, item }: { path: JobDetailPath; item: Record }) { + const sids = Array.isArray(item.sids) ? item.sids.filter((sid): sid is string => typeof sid === 'string') : [] + const fields = DETAIL_FIELDS[path].flatMap(([field, label]) => { + const value = text(item[field]) + if (!value) return [] + const displayed = field === 'stage' ? stageLabel(value) + : field === 'code' || field === 'status' ? DETAIL_VALUE_LABEL[value] ?? value : value + return [`${label}: ${displayed}`] + }) + return ( +
+

{fields.join(' · ') || '표시할 상세 정보가 없습니다.'}

+ {sids.length > 0 &&
대상 SID {sids.length.toLocaleString()}건

{sids.join(', ')}

} +
+ ) +} + +function JobFailures({ prjctIdx, job, sections }: { prjctIdx: number; job: ListJob; sections: JobDetailSection[] }) { + const { auth } = useAuth() + const [selectedPath, setSelectedPath] = useState(sections[0].path) + const section = sections.find(item => item.path === selectedPath) ?? sections[0] + const [offset, setOffset] = useState(0) + const failures = useQuery({ + queryKey: ['listJobFailures', auth.user?.userId, prjctIdx, job.jobKey, section.path, offset, job.jobStatus], + queryFn: async (): Promise => { + const value = await nextApi.get(`/list-jobs/${prjctIdx}/${job.jobKey}/${section.path}?offset=${offset}&limit=100`, { skipResponseErrorHandler: true }) + if (!value || typeof value !== 'object' || !('total' in value) || typeof value.total !== 'number' + || !Number.isInteger(value.total) || value.total < 0 + || !('items' in value) || !Array.isArray(value.items) || !value.items.every(item => item && typeof item === 'object' && !Array.isArray(item))) throw new Error('상세 내역 응답이 올바르지 않습니다.') + return { total: value.total, offset, items: value.items } + }, + refetchInterval: query => isActiveListJob(job.jobStatus) && query.state.status === 'success' ? 3000 : false, + retry: false, + meta: { ignoreGlobalLoading: true }, + }) + return ( +
+ {sections.length > 1 ? :

{section.label}

} + {failures.isPending &&

상세 내역을 조회하는 중입니다.

} + {failures.isError &&
+

상세 내역을 불러오지 못했습니다.

+ +
} + {!failures.isError && failures.data && <> +

전체 {failures.data.total.toLocaleString()}건

+ {failures.data.items.length === 0 ?

조회된 내역이 없습니다.

:
    + {failures.data.items.map((item, index) =>
  • )} +
} + {failures.data.total > 100 &&
+ + +
} + } +
+ ) +} + +export function ListJobProgress({ prjctIdx, job }: { prjctIdx: number; job: ListJob }) { + const qc = useQueryClient() + const [detailJobKey, setDetailJobKey] = useState(null) + const detailOpen = detailJobKey === job.jobKey + const sections = getDetailSections(job) + const detailLabel = job.jobType === 'LIST_UPLOAD' ? '업로드 오류' : job.jobType.endsWith('_BULK') ? '발송 접수 내역' : '실패한 리스트' + const active = isActiveListJob(job.jobStatus) + const cancel = useMutation({ + mutationFn: () => nextApi.post(`/list-jobs/${prjctIdx}/${job.jobKey}/cancel`), + retry: false, + onSuccess: () => { + toast.info('중단을 요청했습니다. 이미 반영된 내용은 유지됩니다.') + for (const key of [['listJob'], ['listJobAvailability'], ['listJobMyActive'], ['listJobUploadResetActive']]) { + void qc.invalidateQueries({ queryKey: key }) + } + }, + }) + // 배정 작업은 진행 중일 때 operation에 따라 "배정 중"/"배정 초기화 중"으로 표시한다. + const statusText = job.jobType === 'LIST_ASSIGN' && job.operation && job.jobStatus === 'RUNNING' + ? `${listJobLabel(job.jobType, job.operation)} 중` + : LIST_JOB_STATUS_LABEL[job.jobStatus] + return ( +
+ {active &&

창을 닫아도 작업은 계속되며, 완료 시 알림을 드립니다.

} +

{statusText} · 단계: {stageLabel(job.jobStage)} · 접수 {job.regDt.replace('T', ' ').slice(0, 19)}

+ + {job.jobStatus !== 'SUCCEEDED' && !active &&

{job.errorMessage || (job.cancelReason === 'USER_REQUEST' ? '사용자 요청으로 중단됐습니다.' : '처리가 종료됐습니다.')} {job.jobStage === 'VALIDATION_FAILED' ? '파일 검증 단계에서 중단되어 리스트 데이터는 변경되지 않았습니다.' : '이미 반영된 내용이 있을 수 있으니 확인 후 다시 요청하세요.'}

} + {job.jobStatus === 'FAILED' && job.failedChunkNo != null &&

실패한 처리 구간: {n(job.failedChunkNo)}번째

} + {(job.resultFiles.length > 0 || job.jobType === 'LIST_UPLOAD') &&
+ {job.resultFiles.map(file => file.ready + ? {file.fileName} 다운로드 + : {file.fileName}: 다운로드 완료 또는 보관기간 종료)} + {job.jobType === 'LIST_UPLOAD' && 업로드 원본} +
} + {job.resultFiles.length > 0 &&

파일은 다운로드 후 또는 보관 기간 만료 시 삭제됩니다.

} +
+ {active && } + {sections.length > 0 && } +
+ {detailOpen && sections.length > 0 && section.path).join('|')}`} prjctIdx={prjctIdx} job={job} sections={sections} />} +
+ ) +} diff --git a/src/components/list/ListJobWatcher.tsx b/src/components/list/ListJobWatcher.tsx new file mode 100644 index 0000000..21c2de1 --- /dev/null +++ b/src/components/list/ListJobWatcher.tsx @@ -0,0 +1,115 @@ +'use client' + +import { useEffect } from 'react' +import { usePathname, useRouter } from 'next/navigation' +import { useAtom } from 'jotai' +import { useQueries, useQueryClient } from '@tanstack/react-query' +import { HttpError } from '@kri/common/http' +import { toast } from 'sonner' +import { nextApi } from '@/lib/http-client' +import { listJobKeys, useMyActiveListJobs } from '@/query/list-job' +import { listJobOpenRequestAtom } from '@/store/jotai/list-job' +import { useSelectedProject } from '@/hooks/useSelectedProject' +import { useDialog } from '@/hooks/useDialog' +import type { SelectedProject } from '@/store/jotai/project' +import { markListJobNotified, trackListJob, untrackListJob, useTrackedListJobs } from '@/store/list-job-tracker' +import { LIST_JOB_VIEW, listJobLabel } from '@/const/listJobConst' +import { isActiveListJob, isListJobType, parseListJob, type ListJob } from '@/types/list-job' + +function isProjectSelection(value: unknown, projectId: number): value is SelectedProject { + if (!value || typeof value !== 'object') return false + const project = value as Record + return project.prjctIdx === projectId && typeof project.ff === 'boolean' + && ['prjctCd', 'prjctName', 'itrntPrjctCd', 'ownerDept', 'ownerFw'].every(key => typeof project[key] === 'string') +} + +/** + * 화면 없이 동작하는 전역 감시. + * - 현재 프로젝트의 진행 중인 내 작업을 서버에서 가져와 기록이 없으면 채운다(다른 탭·기기 보완). + * - 기록된 작업이 끝나면 완료 toast를 1회 띄우고 관련 데이터를 갱신한다. + */ +export function ListJobWatcher({ userId, prjctIdx }: { userId: string; prjctIdx: number }) { + const qc = useQueryClient() + const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom) + const { selectedProject, setSelectedProject } = useSelectedProject() + const router = useRouter() + const pathname = usePathname() + const { hideAll } = useDialog() + const trackedJobs = useTrackedListJobs().filter(job => job.userId === userId) + const myActive = useMyActiveListJobs(prjctIdx, prjctIdx > 0) + + useEffect(() => { + if (!openRequest) return + if (openRequest.userId !== userId) { setOpenRequest(null); return } + if (openRequest.opened) { + if (selectedProject?.prjctIdx !== openRequest.prjctIdx || pathname !== LIST_JOB_VIEW[openRequest.jobType].path) setOpenRequest(null) + return + } + if (selectedProject?.prjctIdx === openRequest.prjctIdx) { + const path = LIST_JOB_VIEW[openRequest.jobType].path + if (pathname !== path) router.push(path) + return + } + let cancelled = false + void (async () => { + try { + const value = await nextApi.get(`/project/info/${openRequest.prjctIdx}`, { skipResponseErrorHandler: true }) + if (cancelled) return + if (!isProjectSelection(value, openRequest.prjctIdx)) throw new Error('Invalid project selection') + setSelectedProject({ + prjctIdx: value.prjctIdx, prjctCd: value.prjctCd, prjctName: value.prjctName, + itrntPrjctCd: value.itrntPrjctCd, ownerDept: value.ownerDept, ownerFw: value.ownerFw, ff: value.ff, + }) + } catch { + if (cancelled) return + toast.error('작업의 프로젝트를 열 수 없습니다. 접근 권한과 프로젝트 상태를 확인해 주세요.') + setOpenRequest(null) + } + })() + return () => { cancelled = true } + }, [openRequest, pathname, router, selectedProject?.prjctIdx, setOpenRequest, setSelectedProject, userId]) + + useEffect(() => { + for (const job of myActive.data ?? []) { + if (isListJobType(job.jobType)) trackListJob({ userId, prjctIdx, jobType: job.jobType, jobKey: job.jobKey }) + } + }, [myActive.data, prjctIdx, userId]) + + const details = useQueries({ + queries: trackedJobs.map(job => ({ + queryKey: listJobKeys.detail(userId, job.prjctIdx, job.jobKey), + queryFn: async () => parseListJob(await nextApi.get(`/list-jobs/${job.prjctIdx}/${job.jobKey}`, { skipResponseErrorHandler: true })), + refetchInterval: (query: { state: { data?: ListJob } }) => query.state.data && !isActiveListJob(query.state.data.jobStatus) ? false : 3000, + retry: false, + meta: { ignoreGlobalLoading: true }, + })), + }) + + useEffect(() => { + details.forEach((result, index) => { + const tracked = trackedJobs[index] + if (!tracked) return + if (result.error instanceof HttpError && result.error.status === 404) { + untrackListJob(tracked.jobKey) + return + } + const job = result.data + if (!job || isActiveListJob(job.jobStatus) || !markListJobNotified(tracked.jobKey)) return + // 일부 실패·중단이어도 앞 구간은 반영됐을 수 있으므로 항상 갱신한다. + for (const key of [['list'], ['assign'], ['project'], ['message-report'], ['listJobMyActive'], ['listJobUploadResetActive'], ['listJobAvailability']]) { + void qc.invalidateQueries({ queryKey: key }) + } + if (openRequest?.opened && openRequest.jobKey === tracked.jobKey) return + const label = listJobLabel(job.jobType, job.operation) + const open = { label: '보기', onClick: () => { + hideAll() + setOpenRequest({ userId, prjctIdx: tracked.prjctIdx, jobType: tracked.jobType, jobKey: tracked.jobKey, opened: false }) + } } + if (job.jobStatus === 'SUCCEEDED') toast.success(`${label} 작업이 완료됐습니다.`, { action: open }) + else if (job.jobStatus === 'CANCELLED') toast.info(`${label} 작업이 중단됐습니다.`, { action: open }) + else toast.error(`${label} 작업이 실패했습니다.`, { action: open }) + }) + }, [details, trackedJobs, openRequest, setOpenRequest, qc, userId, hideAll]) + + return null +} diff --git a/src/components/list/ListManageActions.tsx b/src/components/list/ListManageActions.tsx index 189d67b..8625e53 100644 --- a/src/components/list/ListManageActions.tsx +++ b/src/components/list/ListManageActions.tsx @@ -3,19 +3,27 @@ import { Download, FileClock, + Loader2, Mail, MessageCircle, MessageSquareMore, RotateCcw, Upload, + type LucideIcon, } from 'lucide-react' import { Button } from '@/components/ui/button' import type { ListDownloadMode } from '@/types/list' import type { MessageSendMode } from '@/components/dialog/MessageSendDialog' +export type ListManageActionKey = 'reset' | 'upload' | ListDownloadMode | MessageSendMode + export type ListManageActionsProps = { /** 리스트 초기화/헤더 관리/업로드처럼 내부 관리자 전용 버튼 노출 여부 (외주사 계정에는 숨겨야 함) */ showAdminActions: boolean + /** 비동기 작업이 진행 중인 버튼. 아이콘을 진행 표시로 바꾸고, 누르면 진행 다이얼로그가 열린다. */ + runningActions?: ReadonlySet + disabledActions?: ReadonlySet + headerManageDisabled?: boolean onReset: () => void onHeaderManage: () => void onUpload: () => void @@ -26,6 +34,9 @@ export type ListManageActionsProps = { export function ListManageActions({ showAdminActions, + runningActions, + disabledActions, + headerManageDisabled = false, onReset, onHeaderManage, onUpload, @@ -33,51 +44,56 @@ export function ListManageActions({ onMessageSend, onMessageHistory, }: ListManageActionsProps) { + const icon = (key: ListManageActionKey, Icon: LucideIcon) => + runningActions?.has(key) + ? + : + return (
{showAdminActions && ( <> - - - )} - - - -
- - - {filterActions} {enableBatchEdit ? ( - @@ -848,6 +867,7 @@ export function ListSearchTable({
+ key={dataRevision} columns={columns} data={viewList} getRowId={(row) => String(row.sid)} @@ -871,6 +891,7 @@ export function ListSearchTable({ {enableBatchEdit ? ( = { + LIST_UPLOAD: '리스트 업로드', + LIST_RESET: '리스트 초기화', + LIST_UPDATE: '리스트 일괄 수정', + LIST_ASSIGN: '배정 작업', + LIST_DOWNLOAD: '리스트 다운로드', + CONTACT_HISTORY_DOWNLOAD: '컨택 이력 다운로드', + UPDATE_HISTORY_DOWNLOAD: '리스트 수정 이력 다운로드', + ITEM_ZIP_DOWNLOAD: '첨부파일 ZIP 다운로드', + EMAIL_BULK: '이메일 일괄 발송', + SMS_BULK: '문자 일괄 발송', + KKO_BULK: '알림톡 일괄 발송', +} + +export const LIST_ASSIGN_OPERATION_LABEL: Record = { + ASSIGN: '배정', + RESET: '배정 초기화', +} + +/** 작업 표시 이름. LIST_ASSIGN은 operation(배정/배정 초기화)으로 구분한다. */ +export const listJobLabel = (jobType: string, operation?: ListJobOperation | null) => { + if (jobType === 'LIST_ASSIGN' && operation) return LIST_ASSIGN_OPERATION_LABEL[operation] + return isListJobType(jobType) ? LIST_JOB_TYPE_LABEL[jobType] : '리스트 작업' +} + +export const LIST_JOB_STATUS_LABEL: Record = { + QUEUED: '대기', RUNNING: '진행 중', CANCEL_REQUESTED: '중단 요청 중', SUCCEEDED: '완료', + FAILED: '실패', CANCELLED: '중단', REJECTED: '접수 거절', +} + +export const LIST_JOB_STAGE_LABEL: Record = { + ACCEPTED: '접수', VALIDATING: '파일 검증', VALIDATION_FAILED: '파일 검증 실패', + FREEZING_SIDS: '대상 확정', PROCESSING: '처리 중', INSERTING: '데이터 등록', + RESETTING: '기존 데이터 초기화', RESETTING_ALL: '기존 데이터 전체 초기화', + POST_PROCESSING: '후처리', COMPLETED: '처리 종료', GENERATING: '파일 생성', GENERATING_FILE: '파일 생성', + WRITING_FILE: '파일 저장', RESET_CHECK: '전체 초기화 확인', PREPARING: '발송 준비', SENDING: '발송 요청', +} + +export const LIST_DOWNLOAD_JOB_TYPE: Record = { + list: 'LIST_DOWNLOAD', + 'contact-history': 'CONTACT_HISTORY_DOWNLOAD', + 'list-change-history': 'UPDATE_HISTORY_DOWNLOAD', + 'upload-file': 'ITEM_ZIP_DOWNLOAD', +} + +export const MESSAGE_JOB_TYPE: Record = { + email: 'EMAIL_BULK', + sms: 'SMS_BULK', + kko: 'KKO_BULK', +} + +export const LIST_JOB_VIEW: Record = { + LIST_UPLOAD: { path: '/list/manage', dialogId: 'listUploadDialog' }, + LIST_RESET: { path: '/list/manage', dialogId: 'listResetDialog' }, + LIST_UPDATE: { path: '/list/manage', dialogId: 'listBatchEditDialog' }, + LIST_ASSIGN: { path: '/assign/list' }, + LIST_DOWNLOAD: { path: '/list/manage', dialogId: 'listDownloadDialog', downloadMode: 'list' }, + CONTACT_HISTORY_DOWNLOAD: { path: '/list/manage', dialogId: 'listDownloadDialog', downloadMode: 'contact-history' }, + UPDATE_HISTORY_DOWNLOAD: { path: '/list/manage', dialogId: 'listDownloadDialog', downloadMode: 'list-change-history' }, + ITEM_ZIP_DOWNLOAD: { path: '/list/manage', dialogId: 'listDownloadDialog', downloadMode: 'upload-file' }, + EMAIL_BULK: { path: '/list/manage', dialogId: 'messageSendDialog', messageMode: 'email' }, + SMS_BULK: { path: '/list/manage', dialogId: 'messageSendDialog', messageMode: 'sms' }, + KKO_BULK: { path: '/list/manage', dialogId: 'messageSendDialog', messageMode: 'kko' }, +} diff --git a/src/hooks/useListJobPageMonitor.ts b/src/hooks/useListJobPageMonitor.ts new file mode 100644 index 0000000..2862c0a --- /dev/null +++ b/src/hooks/useListJobPageMonitor.ts @@ -0,0 +1,37 @@ +'use client' + +import { useEffect, useRef, useState } from 'react' +import { useQueryClient } from '@tanstack/react-query' +import { useAuth } from '@/hooks/useAuth' +import { useListJobGate } from '@/components/list/ListJobGate' +import { listMutationBlockerIds } from '@/utils/listJobAvailability' +import type { ListJobType } from '@/types/list-job' + +/** 두 목록 화면의 공용 감시. 타인의 변경 작업도 종료 시 현재 프로젝트 데이터를 갱신한다. */ +export function useListJobPageMonitor(prjctIdx: number, jobType: ListJobType, active: boolean) { + const gate = useListJobGate({ prjctIdx, jobType, active, pollWhileIdle: true, requestLabel: jobType === 'LIST_ASSIGN' ? '배정' : '업로드·초기화·일괄 수정' }) + const qc = useQueryClient() + const { auth } = useAuth() + const userId = auth.user?.userId + const previous = useRef<{ scope: string; ids: string[] } | null>(null) + const [dataRevision, setDataRevision] = useState(0) + + useEffect(() => { + const scope = JSON.stringify([userId, prjctIdx]) + if (!active || !userId) { previous.current = null; return } + if (previous.current?.scope !== scope) previous.current = null + const availability = gate.availability + // 실패한 조회와 최대 20건에서 잘린 응답으로 작업 종료를 단정하지 않는다. + if (!gate.availabilitySucceeded || !availability || availability.blockerCount > availability.blockers.length) return + const ids = listMutationBlockerIds(availability) + const ended = previous.current?.ids.some(id => !ids.includes(id)) ?? false + previous.current = { scope, ids } + if (!ended) return + // 실패·중단이어도 이미 반영된 데이터가 있을 수 있다. + void qc.invalidateQueries({ predicate: query => + (query.queryKey[0] === 'list' || query.queryKey[0] === 'assign') && query.queryKey[2] === prjctIdx }) + setDataRevision(revision => revision + 1) + }, [active, userId, prjctIdx, gate.availability, gate.availabilitySucceeded, gate.availabilityUpdatedAt, qc]) + + return { gate, dataRevision } +} diff --git a/src/query/assign.ts b/src/query/assign.ts deleted file mode 100644 index 15f157d..0000000 --- a/src/query/assign.ts +++ /dev/null @@ -1,42 +0,0 @@ -"use client"; - -import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { nextApi } from "@/lib/http-client"; -import { qk } from "@/query/key/keys"; -import type { ListAssignRequest, ListAssignResetRequest } from "@/types/list"; - -const invalidateAssignSummaries = (qc: ReturnType, prjctIdx: number) => - Promise.all([ - qc.invalidateQueries({ queryKey: qk.projectAssignCmpnSummary(prjctIdx) }), - qc.invalidateQueries({ queryKey: ["assign", "prjct-fieldwork-summary", prjctIdx] }), - ]); - -export function useUpsertListAssignMutation(prjctIdx: number) { - const qc = useQueryClient(); - - return useMutation({ - mutationFn: ({ assignId, request }: { assignId: string; request: ListAssignRequest }) => - nextApi.put(`/assign/list/${prjctIdx}/${encodeURIComponent(assignId)}`, request), - onSuccess: async () => { - await Promise.all([ - qc.invalidateQueries({ queryKey: ["list", "search-filter"] }), - invalidateAssignSummaries(qc, prjctIdx), - ]); - }, - }); -} - -export function useResetListAssignMutation(prjctIdx: number) { - const qc = useQueryClient(); - - return useMutation({ - mutationFn: (request: ListAssignResetRequest) => - nextApi.del(`/assign/list/reset/${prjctIdx}`, { json: request }), - onSuccess: async () => { - await Promise.all([ - qc.invalidateQueries({ queryKey: ["list", "search-filter"] }), - invalidateAssignSummaries(qc, prjctIdx), - ]); - }, - }); -} diff --git a/src/query/list-job.ts b/src/query/list-job.ts new file mode 100644 index 0000000..21a737b --- /dev/null +++ b/src/query/list-job.ts @@ -0,0 +1,152 @@ +'use client' + +import { createContext, useContext } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useSetAtom } from 'jotai' +import { apiError, HttpError } from '@kri/common/http' +import { toast } from 'sonner' +import { nextApi } from '@/lib/http-client' +import { useAuth } from '@/hooks/useAuth' +import { trackListJob } from '@/store/list-job-tracker' +import { listJobOpenRequestAtom } from '@/store/jotai/list-job' +import { describeListJobAvailability } from '@/utils/listJobAvailability' +import { + parseListJob, + parseListJobAvailability, + parseMyActiveListJobs, + parseUploadResetActive, + type ListJobAvailability, + type ListJobType, +} from '@/types/list-job' + +export const listJobKeys = { + detail: (userId: string | undefined, prjctIdx: number, jobKey: string | null) => ['listJob', userId, prjctIdx, jobKey] as const, + myActive: (userId: string | undefined, prjctIdx: number) => ['listJobMyActive', userId, prjctIdx] as const, + uploadResetActive: (userId: string | undefined, prjctIdx: number) => ['listJobUploadResetActive', userId, prjctIdx] as const, + availability: (userId: string | undefined, prjctIdx: number, jobType: ListJobType) => ['listJobAvailability', userId, prjctIdx, jobType] as const, +} + +/** 페이지와 동일한 조회를 사용하는 다이얼로그는 별도 폴링을 만들지 않는다. */ +export const ListJobPageQueryContext = createContext(null) + +/** 접수 직전 재확인에서 다른 작업이 막고 있어 요청을 보내지 않은 경우. */ +class ListJobBlockedError extends Error {} + +const fetchAvailability = async (prjctIdx: number, jobType: ListJobType) => + parseListJobAvailability(await nextApi.get(`/list-jobs/${prjctIdx}/availability?jobType=${jobType}`, { skipResponseErrorHandler: true })) + +/** 신규 API 미배포·롤백 상태. 반복 호출하지 않고 사전 안내만 중단한다. */ +export const isAvailabilityUnsupported = (error: unknown) => error instanceof HttpError && error.status === 404 + +export function useSubmitListJob(prjctIdx: number) { + const qc = useQueryClient() + const { auth } = useAuth() + const setOpenRequest = useSetAtom(listJobOpenRequestAtom) + const userId = auth.user?.userId + const invalidate = () => { + void qc.invalidateQueries({ queryKey: ['listJobAvailability', userId, prjctIdx] }) + void qc.invalidateQueries({ queryKey: listJobKeys.myActive(userId, prjctIdx) }) + void qc.invalidateQueries({ queryKey: listJobKeys.uploadResetActive(userId, prjctIdx) }) + } + return useMutation({ + retry: false, + mutationFn: async ({ jobType, path, body, file }: { jobType: ListJobType; path: string; body?: unknown; file?: File }) => { + // 조회 결과는 예약이 아니므로 접수 직전에 다시 확인한다. 404(미배포)면 서버 판단에 맡긴다. + let availability: ListJobAvailability | null = null + try { + availability = await fetchAvailability(prjctIdx, jobType) + } catch (error) { + if (!isAvailabilityUnsupported(error)) throw new ListJobBlockedError('작업 가능 여부를 확인하지 못했습니다. 잠시 후 다시 시도해 주세요.') + } + if (availability && !availability.allowed) throw new ListJobBlockedError(describeListJobAvailability(availability, jobType).message) + + const url = `/list-jobs/${prjctIdx}/${path}` + const options = { skipResponseErrorHandler: true, timeoutMs: 120_000 } + let value: unknown + if (file) { + const form = new FormData() + form.append('file', file) + form.append('request', new Blob([JSON.stringify(body)], { type: 'application/json' })) + value = await nextApi.postForm(url, form, options) + } else value = await nextApi.post(url, body, options) + if (!value || typeof value !== 'object' || !('jobKey' in value) + || typeof value.jobKey !== 'string' || !/^[a-f0-9]{32}$/.test(value.jobKey)) throw new Error('접수 응답을 확인할 수 없습니다.') + return { jobKey: value.jobKey } + }, + onSuccess: ({ jobKey }, { jobType }) => { + setOpenRequest(previous => previous && previous.userId === userId && previous.prjctIdx === prjctIdx && previous.jobType === jobType ? null : previous) + if (userId) trackListJob({ userId, prjctIdx, jobType, jobKey }) + invalidate() + }, + onError: (error) => { + invalidate() + if (error instanceof ListJobBlockedError) { + toast.error(error.message) + return + } + const { code, message } = apiError(error) + // 충돌 메시지에는 거절 당시 요청자와 작업이 들어 있으므로 서버 detail을 그대로 보여준다. + if (code === 'LIST_JOB_PROJECT_CONFLICT' || code === 'LIST_JOB_USER_BUSY') toast.error(message) + else if (code === 'LIST_JOB_CAPACITY') toast.error('작업 대기 용량이 가득 찼습니다. 잠시 후 다시 시도해 주세요.') + else if (code === 'LIST_JOBS_UNAVAILABLE') toast.error('작업 접수를 준비 중입니다. 잠시 후 다시 시도해 주세요.') + else toast.error('작업 접수를 확인하지 못했습니다. 다시 요청하기 전에 진행 중인 작업이 있는지 확인해 주세요.') + }, + meta: { ignoreGlobalLoading: true }, + }) +} + +export function useListJob(prjctIdx: number, jobKey: string | null, enabled: boolean) { + const { auth } = useAuth() + return useQuery({ + queryKey: listJobKeys.detail(auth.user?.userId, prjctIdx, jobKey), + queryFn: async () => parseListJob(await nextApi.get(`/list-jobs/${prjctIdx}/${jobKey}`, { skipResponseErrorHandler: true })), + enabled: enabled && !!jobKey && !!auth.user, + retry: false, + meta: { ignoreGlobalLoading: true }, + }) +} + +export function useMyActiveListJobs(prjctIdx: number, enabled: boolean) { + const { auth } = useAuth() + return useQuery({ + queryKey: listJobKeys.myActive(auth.user?.userId, prjctIdx), + queryFn: async () => parseMyActiveListJobs(await nextApi.get(`/list-jobs/${prjctIdx}/my-active`, { skipResponseErrorHandler: true })), + enabled: enabled && prjctIdx > 0 && !!auth.user, + refetchInterval: 5000, + retry: false, + meta: { ignoreGlobalLoading: true }, + }) +} + +export function useUploadResetActive(prjctIdx: number, enabled: boolean) { + const { auth } = useAuth() + const pageQuery = useContext(ListJobPageQueryContext) + return useQuery({ + queryKey: listJobKeys.uploadResetActive(auth.user?.userId, prjctIdx), + queryFn: async () => parseUploadResetActive(await nextApi.get(`/list-jobs/${prjctIdx}/upload-reset-active`, { skipResponseErrorHandler: true })), + enabled: enabled && prjctIdx > 0 && !!auth.user, + refetchInterval: pageQuery ? false : 3000, + retry: false, + meta: { ignoreGlobalLoading: true }, + }) +} + +/** 페이지는 평상시 10초·차단 중 3초, 다이얼로그는 차단 중에만 3초 조회한다. */ +export function useListJobAvailability(prjctIdx: number, jobType: ListJobType, enabled: boolean, pollWhileIdle = false) { + const { auth } = useAuth() + const pageQuery = useContext(ListJobPageQueryContext) + const qc = useQueryClient() + const queryKey = listJobKeys.availability(auth.user?.userId, prjctIdx, jobType) + return useQuery({ + queryKey, + queryFn: () => fetchAvailability(prjctIdx, jobType), + enabled: enabled && prjctIdx > 0 && !!auth.user && !isAvailabilityUnsupported(qc.getQueryState(queryKey)?.error), + refetchInterval: query => { + if (query.state.status !== 'success' || (pageQuery === jobType && !pollWhileIdle)) return false + return query.state.data?.allowed === false ? 3000 : pollWhileIdle ? 10000 : false + }, + retry: false, + retryOnMount: false, + meta: { ignoreGlobalLoading: true }, + }) +} diff --git a/src/query/list.ts b/src/query/list.ts index bb582c8..80a76a4 100644 --- a/src/query/list.ts +++ b/src/query/list.ts @@ -3,22 +3,18 @@ import {qk} from "@/query/key/keys"; import {nextApi} from "@/lib/http-client"; import { listHeader, - ListEventHistDownloadRequest, ListEventHistory, ListEventInsertRequest, - ListFilter, ListReserve, ListReserveRequest, - ListResetRequest, ListSearchRequest, ListSearchWithFullResult, ListUpdateHistory, ListUpdateRequest, ListUploadHistory, - ListUploadRequest, } from "@/types/list"; -import type { ExcelUploadResult, PageResponse } from "@kri/common"; -import {LIST_EXCEL_TIMEOUT_MS, ListHeaderAssignConst} from "@/const/listConst"; +import type { PageResponse } from "@kri/common"; +import {ListHeaderAssignConst} from "@/const/listConst"; import {ResultCodeType} from "@/types/project"; export function useListHeaderQuery(prjctIdx: number, enabled: boolean) { @@ -187,28 +183,6 @@ export function useListUploadHistoryQuery(prjctIdx: number, enabled: boolean) { }); } -export function useUploadListExcelMutation(prjctIdx: number) { - const queryClient = useQueryClient(); - - return useMutation({ - mutationFn: ({ file, request }: { file: File; request: ListUploadRequest }) => { - const formData = new FormData(); - formData.append("file", file); - formData.append("request", new Blob([JSON.stringify(request)], { type: "application/json" })); - return nextApi.postForm(`/list/excel-upload/${prjctIdx}`, formData, { - timeoutMs: LIST_EXCEL_TIMEOUT_MS, - }); - }, - onSuccess: async () => { - await Promise.all([ - queryClient.invalidateQueries({ queryKey: qk.listHeader(prjctIdx) }), - queryClient.invalidateQueries({ queryKey: qk.listUploadHistory(prjctIdx) }), - queryClient.invalidateQueries({ queryKey: ["list", "search-filter"] }), - ]); - }, - }); -} - export function useUpdateListHeaderMutation(prjctIdx: number) { const queryClient = useQueryClient(); @@ -220,17 +194,6 @@ export function useUpdateListHeaderMutation(prjctIdx: number) { }); } -export function useResetListMutation(prjctIdx: number) { - const queryClient = useQueryClient(); - - return useMutation({ - mutationFn: (request: ListResetRequest) => nextApi.del(`/list/${prjctIdx}`, { json: request }), - onSuccess: async () => { - await queryClient.invalidateQueries({ queryKey: ["list"] }); - }, - }); -} - export function useUpdateListMutation(prjctIdx: number) { const queryClient = useQueryClient(); @@ -275,40 +238,6 @@ export function useDeleteListEventMutation(prjctIdx: number, sid: string) { }); } -export function useDownloadListMutation(prjctIdx: number) { - return useMutation({ - mutationFn: ({ listFilter, includeResult }: { listFilter: ListFilter; includeResult: boolean }) => - nextApi.post(`/list/excel-download/${prjctIdx}?includeResult=${includeResult}`, listFilter, { - expectBinary: true, - timeoutMs: LIST_EXCEL_TIMEOUT_MS, - }), - }); -} - -export function useDownloadListUpdateHistoryMutation(prjctIdx: number) { - return useMutation({ - mutationFn: (listFilter: ListFilter) => - nextApi.post(`/list/excel-download-update/${prjctIdx}`, listFilter, { expectBinary: true }), - }); -} - -export function useDownloadListEventHistoryMutation(prjctIdx: number) { - return useMutation({ - mutationFn: ({ includeResult, ...request }: ListEventHistDownloadRequest & { includeResult: boolean }) => - nextApi.post(`/list/event-history-download/${prjctIdx}?includeResult=${includeResult}`, request, { - expectBinary: true, - timeoutMs: LIST_EXCEL_TIMEOUT_MS, - }), - }); -} - -export function useDownloadListItemFileMutation(prjctIdx: number) { - return useMutation({ - mutationFn: (listFilter: ListFilter) => - nextApi.post(`/list/item-file-download/${prjctIdx}`, listFilter, { expectBinary: true }), - }); -} - export function useDownloadUploadHistoryFileMutation(prjctIdx: number) { return useMutation({ mutationFn: (listUploadLogId: string) => diff --git a/src/query/message.ts b/src/query/message.ts index 2e6b350..758023c 100644 --- a/src/query/message.ts +++ b/src/query/message.ts @@ -5,7 +5,6 @@ import { nextApi } from "@/lib/http-client"; import { qk } from "@/query/key/keys"; import type { BulkSendInfo, - BulkSendResult, ChannelType, KkoTemplateDetail, KkoTemplateListResponse, @@ -16,7 +15,6 @@ import type { import type { FileResponse, PageRequest, PageResponse } from "@kri/common"; import type { ProjectMainTemplateUpdateRequest } from "@/types/project"; import type { - MessageSendBulkRequest, MessageSendChannel, MessageSendSingleRequest, SendSingleResponse, @@ -268,16 +266,6 @@ export function useSendSingleMessageMutation(channel: MessageSendChannel, prjctI }); } -/** - * 대량 발송 (POST /message-send/{channel}/bulk/{prjctIdx}, contactServer 경유) - */ -export function useSendBulkMessageMutation(channel: MessageSendChannel, prjctIdx: number) { - return useMutation({ - mutationFn: (req: MessageSendBulkRequest) => - nextApi.post(`/message-send/${channel}/bulk/${prjctIdx}`, req), - }); -} - /** * SID 단위 발송 결과 목록 조회 (GET /message-report/send-result/{sid}/{prjctCd}/{reqstSvc}) */ diff --git a/src/query/project.ts b/src/query/project.ts index 54dc3f1..611bb27 100644 --- a/src/query/project.ts +++ b/src/query/project.ts @@ -273,7 +273,7 @@ export function useDeleteProjectMutation(prjctIdx: number) { /** * 시나리오 이미지 업로드 (엔드포인트 spelling은 너 서버 기준으로) */ -export function useUploadScenarioImageMutation(prjctIdx: number, prjctCd: string) { +export function useUploadScenarioImageMutation(prjctCd: string) { return useMutation({ mutationFn: async (file: File): Promise => { const formData = new FormData(); diff --git a/src/store/jotai/list-job.ts b/src/store/jotai/list-job.ts new file mode 100644 index 0000000..42b16fa --- /dev/null +++ b/src/store/jotai/list-job.ts @@ -0,0 +1,15 @@ +"use client"; + +import { atom } from "jotai"; +import type { ListJobType } from "@/types/list-job"; + +/** 완료 알림에서 원래 작업 화면을 열고, 해당 작업의 결과를 선택한다. */ +export type ListJobOpenRequest = { + userId: string; + prjctIdx: number; + jobType: ListJobType; + jobKey: string; + opened: boolean; +}; + +export const listJobOpenRequestAtom = atom(null); diff --git a/src/store/list-job-tracker.ts b/src/store/list-job-tracker.ts new file mode 100644 index 0000000..845de29 --- /dev/null +++ b/src/store/list-job-tracker.ts @@ -0,0 +1,97 @@ +'use client' + +import { useSyncExternalStore } from 'react' +import { getLocalStorage, setLocalStorage } from '@/store/storage/secure-storage' +import { StorageKeys } from '@/store/storage/storage-keys' +import { isListJobType, type ListJobType } from '@/types/list-job' + +/** + * 사용자가 요청한 "현재" 비동기 작업 기록. 사용자·프로젝트·jobType별로 1건만 유지한다. + * 완료 상태를 표시한 다이얼로그를 사용자가 닫으면(확인) 기록을 지운다. + */ +export type TrackedListJob = { + userId: string + prjctIdx: number + jobType: ListJobType + jobKey: string + savedAt: number + /** 완료 toast를 이미 띄웠는지. 새로고침 후 중복 알림을 막는다. */ + notified: boolean +} + +// 다른 브라우저에서 이미 확인했을 수 있어 오래된 기록은 버린다. +const TTL_MS = 24 * 60 * 60 * 1000 +const CHANGE_EVENT = 'kri:list-jobs-change' +const EMPTY: TrackedListJob[] = [] +let cache: TrackedListJob[] | null = null + +const isTrackedListJob = (value: unknown): value is TrackedListJob => { + if (!value || typeof value !== 'object') return false + const job = value as Record + return typeof job.userId === 'string' && job.userId.length > 0 + && typeof job.prjctIdx === 'number' && Number.isInteger(job.prjctIdx) && job.prjctIdx > 0 + && isListJobType(job.jobType) + && typeof job.jobKey === 'string' && /^[a-f0-9]{32}$/.test(job.jobKey) + && typeof job.savedAt === 'number' && typeof job.notified === 'boolean' +} + +const read = (): TrackedListJob[] => { + const stored = getLocalStorage(StorageKeys.ListJobs) + if (!Array.isArray(stored)) return EMPTY + const now = Date.now() + return stored.filter(isTrackedListJob).filter((job) => now - job.savedAt < TTL_MS) +} + +const write = (jobs: TrackedListJob[]) => { + setLocalStorage(StorageKeys.ListJobs, jobs) + cache = jobs + window.dispatchEvent(new Event(CHANGE_EVENT)) +} + +export const getTrackedListJobs = (): TrackedListJob[] => { + if (typeof window === 'undefined') return EMPTY + if (cache === null) cache = read() + return cache +} + +export const trackListJob = (entry: Pick) => { + const jobs = getTrackedListJobs() + if (jobs.some((job) => job.jobKey === entry.jobKey)) return + write([ + ...jobs.filter((job) => !(job.userId === entry.userId && job.prjctIdx === entry.prjctIdx && job.jobType === entry.jobType)), + { ...entry, savedAt: Date.now(), notified: false }, + ]) +} + +/** 아직 알리지 않은 기록이면 알림 처리하고 true를 반환한다. 중복 toast 방지용. */ +export const markListJobNotified = (jobKey: string) => { + const jobs = getTrackedListJobs() + if (!jobs.some((job) => job.jobKey === jobKey && !job.notified)) return false + write(jobs.map((job) => (job.jobKey === jobKey ? { ...job, notified: true } : job))) + return true +} + +export const untrackListJob = (jobKey: string) => { + const jobs = getTrackedListJobs() + if (!jobs.some((job) => job.jobKey === jobKey)) return + write(jobs.filter((job) => job.jobKey !== jobKey)) +} + +export const findTrackedListJob = (jobs: TrackedListJob[], userId: string, prjctIdx: number, jobType: ListJobType) => + jobs.find((job) => job.userId === userId && job.prjctIdx === prjctIdx && job.jobType === jobType) + +const subscribe = (onChange: () => void) => { + const handleStorage = (event: StorageEvent) => { + if (event.key !== null && event.key !== StorageKeys.ListJobs) return + cache = null + onChange() + } + window.addEventListener(CHANGE_EVENT, onChange) + window.addEventListener('storage', handleStorage) + return () => { + window.removeEventListener(CHANGE_EVENT, onChange) + window.removeEventListener('storage', handleStorage) + } +} + +export const useTrackedListJobs = () => useSyncExternalStore(subscribe, getTrackedListJobs, () => EMPTY) diff --git a/src/store/storage/storage-keys.ts b/src/store/storage/storage-keys.ts index fbd81e0..6db7f2d 100644 --- a/src/store/storage/storage-keys.ts +++ b/src/store/storage/storage-keys.ts @@ -4,6 +4,7 @@ export const StorageKeys = { ItrntUserList:"kri:itrntUserList", LastListVisit: "kri:lastListVisit", CtiState: "kri:ctiState", + ListJobs: "kri:listJobs", //SidebarCollapsed: "kri:sidebarCollapsed", // 필요하면 여기 계속 추가 } as const; @@ -14,6 +15,7 @@ export const StorageType: Record = { [StorageKeys.ItrntUserList]: "session", [StorageKeys.LastListVisit]: "session", [StorageKeys.CtiState]: "local", + [StorageKeys.ListJobs]: "local", }; export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys]; diff --git a/src/types/list-job.ts b/src/types/list-job.ts new file mode 100644 index 0000000..a613f5c --- /dev/null +++ b/src/types/list-job.ts @@ -0,0 +1,156 @@ +export type ListJobStatus = 'QUEUED' | 'RUNNING' | 'CANCEL_REQUESTED' | 'SUCCEEDED' | 'FAILED' | 'CANCELLED' | 'REJECTED' + +// 배정·배정 초기화는 LIST_ASSIGN 하나로 통합됐다. 두 명령은 operation(ASSIGN/RESET)으로만 구분한다. +export const LIST_JOB_TYPES = [ + 'LIST_UPLOAD', 'LIST_RESET', 'LIST_UPDATE', 'LIST_ASSIGN', + 'LIST_DOWNLOAD', 'CONTACT_HISTORY_DOWNLOAD', 'UPDATE_HISTORY_DOWNLOAD', 'ITEM_ZIP_DOWNLOAD', + 'EMAIL_BULK', 'SMS_BULK', 'KKO_BULK', +] as const + +export type ListJobType = (typeof LIST_JOB_TYPES)[number] + +export const isListJobType = (value: unknown): value is ListJobType => + typeof value === 'string' && (LIST_JOB_TYPES as readonly string[]).includes(value) + +/** LIST_ASSIGN 작업의 명령. 다른 jobType은 null이다. */ +export type ListJobOperation = 'ASSIGN' | 'RESET' + +const isOperationField = (value: unknown) => value === undefined || value === null || value === 'ASSIGN' || value === 'RESET' + +export type ListJob = { + jobKey: string + jobType: string + operation?: ListJobOperation | null + jobStatus: ListJobStatus + jobStage: string + totalSidCnt: number | null + completedSidCnt: number + completedChunkCnt: number + failedSidCnt: number + processedSidCnt: number + remainingSidCnt: number | null + progress: Record | null + failedChunkNo?: number | null + errorCode: string | null + errorMessage: string | null + cancelReason: string | null + regDt: string + startedDt: string | null + finishedDt: string | null + resultFiles: { index: number; type: string; fileName: string; sizeBytes: number; ready: boolean }[] +} + +/** 프로젝트에서 진행 중인 업로드·초기화. 다른 사용자 작업이면 jobKey는 null이다. */ +export type UploadResetActiveJob = { + jobType: 'LIST_UPLOAD' | 'LIST_RESET' + jobStatus: ListJobStatus + jobStage: string + totalSidCnt: number | null + processedSidCnt: number + mine: boolean + jobKey: string | null +} +export type UploadResetActive = { active: boolean; job: UploadResetActiveJob | null } +export type ListJobFailurePage = { total: number; offset: number; items: Record[] } + +/** 새 작업 접수를 막고 있는 작업. 타인 작업이면 jobKey는 null이다. */ +export type ListJobBlocker = { + jobType: string + operation: ListJobOperation | null + jobStatus: ListJobStatus + blockingPhase: 'ACTIVE' | 'FINALIZING' + requestUserId: string + requestUserName: string | null + mine: boolean + jobKey: string | null + regDt: string +} + +export type ListJobAvailability = { + requestedJobType: string + allowed: boolean + reasonCode: string | null + blockerCount: number + blockers: ListJobBlocker[] +} + +export const isActiveListJob = (status: ListJobStatus) => + status === 'QUEUED' || status === 'RUNNING' || status === 'CANCEL_REQUESTED' + +const statuses: string[] = ['QUEUED', 'RUNNING', 'CANCEL_REQUESTED', 'SUCCEEDED', 'FAILED', 'CANCELLED', 'REJECTED'] +const isJobKeyOrNull = (value: unknown) => value === null || (typeof value === 'string' && /^[a-f0-9]{32}$/.test(value)) + +export function parseListJob(value: unknown): ListJob { + if (!value || typeof value !== 'object') throw new Error('작업 응답이 올바르지 않습니다.') + const job = value as Record + if (typeof job.jobKey !== 'string' || !/^[a-f0-9]{32}$/.test(job.jobKey) + || typeof job.jobType !== 'string' || typeof job.jobStage !== 'string' + || typeof job.jobStatus !== 'string' || !statuses.includes(job.jobStatus) + || !isOperationField(job.operation) + || !(job.failedChunkNo === undefined || job.failedChunkNo === null + || (typeof job.failedChunkNo === 'number' && Number.isInteger(job.failedChunkNo) && job.failedChunkNo > 0)) + || !['completedSidCnt', 'completedChunkCnt', 'failedSidCnt', 'processedSidCnt'].every(key => typeof job[key] === 'number') + || !(job.totalSidCnt === null || typeof job.totalSidCnt === 'number') + || !Array.isArray(job.resultFiles) + || !job.resultFiles.every(file => file && typeof file === 'object' + && typeof file.index === 'number' && typeof file.fileName === 'string' + && typeof file.sizeBytes === 'number' && typeof file.ready === 'boolean')) { + throw new Error('작업 응답이 올바르지 않습니다.') + } + return value as ListJob +} + +export function parseMyActiveListJobs(value: unknown): ListJob[] { + if (!value || typeof value !== 'object' || !Array.isArray((value as Record).items)) { + throw new Error('작업 목록 응답이 올바르지 않습니다.') + } + return ((value as Record).items as unknown[]).map(parseListJob) +} + +export function parseUploadResetActive(value: unknown): UploadResetActive { + if (!value || typeof value !== 'object') throw new Error('진행 상태 응답이 올바르지 않습니다.') + const body = value as Record + if (typeof body.active !== 'boolean') throw new Error('진행 상태 응답이 올바르지 않습니다.') + if (body.job === null) return { active: body.active, job: null } + const job = body.job as Record | undefined + if (!job || typeof job !== 'object' + || (job.jobType !== 'LIST_UPLOAD' && job.jobType !== 'LIST_RESET') + || typeof job.jobStatus !== 'string' || !statuses.includes(job.jobStatus) + || typeof job.jobStage !== 'string' || typeof job.processedSidCnt !== 'number' || typeof job.mine !== 'boolean' + || !(job.totalSidCnt === null || typeof job.totalSidCnt === 'number') + || !isJobKeyOrNull(job.jobKey)) { + throw new Error('진행 상태 응답이 올바르지 않습니다.') + } + return { active: body.active, job: job as UploadResetActiveJob } +} + +const isBlocker = (value: unknown): value is ListJobBlocker => { + if (!value || typeof value !== 'object') return false + const blocker = value as Record + return typeof blocker.jobType === 'string' + && (blocker.operation === null || blocker.operation === 'ASSIGN' || blocker.operation === 'RESET') + && typeof blocker.jobStatus === 'string' && statuses.includes(blocker.jobStatus) + && (blocker.blockingPhase === 'ACTIVE' || blocker.blockingPhase === 'FINALIZING') + && typeof blocker.requestUserId === 'string' + && (blocker.requestUserName === null || typeof blocker.requestUserName === 'string') + && typeof blocker.mine === 'boolean' + && isJobKeyOrNull(blocker.jobKey) + && typeof blocker.regDt === 'string' +} + +export function parseListJobAvailability(value: unknown): ListJobAvailability { + if (!value || typeof value !== 'object') throw new Error('작업 가능 여부 응답이 올바르지 않습니다.') + const body = value as Record + if (typeof body.requestedJobType !== 'string' || typeof body.allowed !== 'boolean' + || !(body.reasonCode === null || typeof body.reasonCode === 'string') + || typeof body.blockerCount !== 'number' || !Array.isArray(body.blockers) || !body.blockers.every(isBlocker)) { + throw new Error('작업 가능 여부 응답이 올바르지 않습니다.') + } + return { + requestedJobType: body.requestedJobType, + allowed: body.allowed, + reasonCode: body.reasonCode, + blockerCount: body.blockerCount, + blockers: body.blockers, + } +} diff --git a/src/utils/listAccess.ts b/src/utils/listAccess.ts index 20bb8f0..3b78ec1 100644 --- a/src/utils/listAccess.ts +++ b/src/utils/listAccess.ts @@ -1,7 +1,7 @@ import { ListHeaderAssignConst, ListHeaderConst } from "@/const/listConst"; import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from "@/const/userConst"; import { ListIsUse, type ListFilter, type listHeader, type ListHeaderAssignType } from "@/types/list"; -import {isExternalManager, isFieldWorkUser, isInternalManager, isManager} from "@/utils/userRole"; +import {isExternalManager, isFieldWorkUser, isManager} from "@/utils/userRole"; export const isAssignHeaderType = (value: number): value is ListHeaderAssignType => value === ListHeaderAssignConst.OUTSOURCE || diff --git a/src/utils/listJobAvailability.ts b/src/utils/listJobAvailability.ts new file mode 100644 index 0000000..e9125d7 --- /dev/null +++ b/src/utils/listJobAvailability.ts @@ -0,0 +1,52 @@ +import { listJobLabel } from '@/const/listJobConst' +import type { ListJobAvailability, ListJobBlocker, ListJobType } from '@/types/list-job' + +const MUTATION_JOB_TYPES = new Set(['LIST_UPLOAD', 'LIST_RESET', 'LIST_UPDATE', 'LIST_ASSIGN']) + +/** FINALIZING도 같은 작업으로 유지하고, 성공한 후속 조회에서 사라졌을 때 종료로 판단한다. */ +export const listMutationBlockerIds = (availability: ListJobAvailability) => availability.blockers + .filter(blocker => MUTATION_JOB_TYPES.has(blocker.jobType)) + .map(blocker => JSON.stringify([blocker.jobType, blocker.operation, blocker.requestUserId, blocker.regDt])) + +export function isListPageActionBlocked(availability: ListJobAvailability | undefined, jobType: ListJobType, unavailable: boolean) { + if (unavailable) return true + if (!availability) return false // availability 미배포(404)는 실제 접수 시 서버 판단에 맡긴다. + if (availability.allowed) return false + if (MUTATION_JOB_TYPES.has(jobType)) return true + return availability.blockers.some(blocker => MUTATION_JOB_TYPES.has(blocker.jobType) || (blocker.mine && blocker.jobType === jobType)) +} + +/** 요청자 표시: 이름(ID), 이름이 없으면 ID */ +export const blockerUserLabel = (blocker: ListJobBlocker) => + blocker.requestUserName ? `${blocker.requestUserName}(${blocker.requestUserId})` : blocker.requestUserId + +export const blockerPhaseLabel = (blocker: ListJobBlocker) => { + if (blocker.blockingPhase === 'FINALIZING') return '마무리 중' + if (blocker.jobStatus === 'QUEUED') return '대기 중' + if (blocker.jobStatus === 'CANCEL_REQUESTED') return '취소 처리 중' + if (blocker.jobStatus === 'RUNNING') return '진행 중' + return '종료 처리 중' +} + +export const blockerJobLabel = (blocker: ListJobBlocker) => listJobLabel(blocker.jobType, blocker.operation) + +/** + * 차단 안내 문구. 조사(을/를, 이/가)가 작업 이름에 따라 달라지지 않도록 '작업'을 붙여 표현한다. + * requestLabel은 요청하려는 작업 이름이며, 배정처럼 operation으로 이름이 갈리는 경우 호출부가 넘긴다. + */ +export function describeListJobAvailability(availability: ListJobAvailability, jobType: ListJobType, requestLabel = listJobLabel(jobType)) { + const { blockers, blockerCount } = availability + const omittedCount = Math.max(0, blockerCount - blockers.length) + const first = blockers[0] + if (!first) return { message: `지금은 ${requestLabel} 작업을 시작할 수 없습니다. 잠시 후 다시 시도해 주세요.`, omittedCount } + + if (availability.reasonCode === 'LIST_JOB_USER_BUSY') { + return { message: `이미 요청한 ${blockerJobLabel(first)} 작업이 진행 중입니다. 종료 후 다시 시도해 주세요.`, omittedCount } + } + + const who = first.mine ? '내가 요청한' : `${blockerUserLabel(first)}님의` + const message = blockerCount > 1 + ? `${who} ${blockerJobLabel(first)} 작업 외 ${blockerCount - 1}개 작업으로 ${requestLabel} 작업을 시작할 수 없습니다. 작업 종료 후 다시 시도해 주세요.` + : `${who} ${blockerJobLabel(first)} 작업이 ${blockerPhaseLabel(first)}이어서 ${requestLabel} 작업을 시작할 수 없습니다. 작업 종료 후 다시 시도해 주세요.` + return { message, omittedCount } +}