261019_01_ENH: 리스트 비동기 작업 동시 실행 제한 및 진행 상태 UI 개선, 미사용 참조 정리
This commit is contained in:
@@ -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<ResultCode[]>(() => 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 <LoadingOverlayAdapter force />
|
||||
|
||||
return (
|
||||
<ListJobPageQueryContext.Provider value="LIST_ASSIGN">
|
||||
<div className="flex gap-4 text-sm">
|
||||
<div className="w-72 shrink-0 space-y-2">
|
||||
<Tabs value={String(effectiveAssignType)} onValueChange={handleTabChange}>
|
||||
@@ -180,8 +198,10 @@ const ListAssignPage = () => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<ListJobGatePanel gate={assignGate} />
|
||||
<ListSearchTable
|
||||
dataRevision={dataRevision}
|
||||
prjctIdx={prjctIdx}
|
||||
enabled={enabled}
|
||||
userRole={userRole}
|
||||
@@ -219,10 +239,10 @@ const ListAssignPage = () => {
|
||||
예약 이관
|
||||
</label>
|
||||
)}
|
||||
<Button type="button" onClick={handleAssign}>
|
||||
<Button type="button" onClick={handleAssign} disabled={assignMutation.isPending || assignGate.submitBlocked}>
|
||||
배정
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={handleResetAssign}>
|
||||
<Button type="button" variant="outline" onClick={handleResetAssign} disabled={assignMutation.isPending || assignGate.submitBlocked}>
|
||||
배정 초기화
|
||||
</Button>
|
||||
</>
|
||||
@@ -230,6 +250,7 @@ const ListAssignPage = () => {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</ListJobPageQueryContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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<ListDownloadMode>('list')
|
||||
const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('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<string>((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<ListManageActionKey, ListJobType> = {
|
||||
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<ListManageActionKey>([
|
||||
...(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<ResultCode[]>(() => 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 <LoadingOverlayAdapter force />
|
||||
|
||||
return (
|
||||
<ListJobPageQueryContext.Provider value="LIST_RESET">
|
||||
<div className="space-y-6 text-sm">
|
||||
<ListJobGatePanel gate={pageGate} showCurrentJob={false} />
|
||||
{canManageList && (
|
||||
<ListManageActions
|
||||
showAdminActions={isInternal}
|
||||
runningActions={runningActions}
|
||||
disabledActions={disabledActions}
|
||||
headerManageDisabled={pageGate.submitBlocked}
|
||||
onReset={() => 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 && (
|
||||
<>
|
||||
<ListResetDialog
|
||||
prjctIdx={prjctIdx}
|
||||
selectedSids={selectedSidSet}
|
||||
filterSummary={filterSummary}
|
||||
onConfirm={handleResetConfirm}
|
||||
/>
|
||||
<ListUploadDialog
|
||||
prjctIdx={prjctIdx}
|
||||
onUpload={handleUploadConfirm}
|
||||
onDownloadTemplate={handleDownloadTemplate}
|
||||
uploadHistory={uploadHistoryQuery.data ?? []}
|
||||
@@ -356,13 +388,14 @@ const ListManagePage = () => {
|
||||
}}
|
||||
headerRows={headerManageRows}
|
||||
/>
|
||||
<ListHeaderManageDialog prjctIdx={prjctIdx} rows={headerManageRows} onConfirm={handleHeaderManageConfirm} />
|
||||
<ListHeaderManageDialog prjctIdx={prjctIdx} rows={headerManageRows} onConfirm={handleHeaderManageConfirm} saveDisabled={pageGate.submitBlocked} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{canManageList && (
|
||||
<>
|
||||
<ListDownloadDialog
|
||||
prjctIdx={prjctIdx}
|
||||
mode={downloadMode}
|
||||
selectedSids={selectedSidSet}
|
||||
filterSummary={filterSummary}
|
||||
@@ -380,6 +413,7 @@ const ListManagePage = () => {
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</ListJobPageQueryContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<ResultCode[]>([]);
|
||||
const [assignCmpnIdArray, setAssignCmpnIdArray] = useState<string[]>([]);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<number>(`/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<number>(`/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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
59
src/app/api/list-jobs/[[...slug]]/route.ts
Normal file
59
src/app/api/list-jobs/[[...slug]]/route.ts
Normal file
@@ -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
|
||||
@@ -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<ArrayBuffer>(
|
||||
`/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<ArrayBuffer>(`/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<ArrayBuffer>(
|
||||
`/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<ArrayBuffer>(`/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<ArrayBuffer>(
|
||||
`/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<number>(`/list/${slug[0]}`, { json: body });
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<BulkSendResult>(`/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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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){
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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){
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 ?? [];
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 && <ListJobWatcher userId={auth.user.userId} prjctIdx={selectedProject?.prjctIdx ?? 0} />}
|
||||
<ReserveSearchDialog />
|
||||
</KriMainLayout>
|
||||
);
|
||||
|
||||
@@ -121,7 +121,7 @@ export function DataTable<TData, TValue = unknown>({
|
||||
[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}`
|
||||
|
||||
@@ -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<ResultCodeType, ResultCodeType.SURVEY>;
|
||||
]
|
||||
|
||||
const ListBatchEditDialog = ({
|
||||
prjctIdx,
|
||||
dialogId = 'listBatchEditDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
@@ -98,6 +101,7 @@ const ListBatchEditDialog = ({
|
||||
const rowInputRefs = useRef<Map<string, HTMLInputElement>>(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={<span className="text-2xl font-bold">일괄 수정</span>}
|
||||
contentClassName="sm:max-w-[900px]"
|
||||
contentClassName="sm:max-w-[900px] max-h-[90vh] overflow-y-auto"
|
||||
bodyClassName="space-y-4"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
적용
|
||||
{gate.hasCurrentJob ? '닫기' : '취소'}
|
||||
</Button>
|
||||
{!gate.hasCurrentJob && (
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting || gate.submitBlocked}>
|
||||
적용
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
|
||||
{!gate.hasCurrentJob && <>
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">적용 대상</p>
|
||||
<ApplyFilterOption
|
||||
@@ -399,6 +407,7 @@ const ListBatchEditDialog = ({
|
||||
<Plus className="w-4 h-4" />
|
||||
행 추가
|
||||
</Button>
|
||||
</>}
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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<ListDownloadMode, string> = {
|
||||
}
|
||||
|
||||
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={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
|
||||
contentClassName="sm:max-w-[560px]"
|
||||
contentClassName="sm:max-w-[560px] max-h-[90vh] overflow-y-auto"
|
||||
bodyClassName="space-y-4"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleDownload} disabled={submitting} className="gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
다운로드
|
||||
{gate.hasCurrentJob ? '닫기' : '취소'}
|
||||
</Button>
|
||||
{!gate.hasCurrentJob && (
|
||||
<Button type="button" onClick={handleDownload} disabled={submitting || gate.submitBlocked} className="gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
다운로드
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
|
||||
{!gate.hasCurrentJob && <>
|
||||
{mode === 'contact-history' ? (
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">조회 기간</p>
|
||||
@@ -189,6 +198,7 @@ const ListDownloadDialog = ({
|
||||
</RadioGroup>
|
||||
</div>
|
||||
) : null}
|
||||
</>}
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ export type ListHeaderManageDialogProps = {
|
||||
prjctIdx: number
|
||||
rows: listHeader[]
|
||||
onConfirm: (rows: listHeader[]) => void | Promise<void>
|
||||
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<listHeader[]>([])
|
||||
@@ -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 = ({
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting || saveDisabled}>
|
||||
저장
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{saveDisabled && <p role="alert" className="mb-2 text-sm text-amber-800">리스트 작업이 진행 중이거나 작업 상태를 확인할 수 없어 헤더를 저장할 수 없습니다.</p>}
|
||||
|
||||
<div className="flex justify-between mb-2">
|
||||
<span className="text-base text-red-600 font-semibold">⚠️ 헤더명이 수정 되거나 헤더가 삭제되면 KON또는 KON-KIWI의 리스트 관련 하드코딩에 영향이 있을 수 있습니다.</span>
|
||||
|
||||
@@ -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={<span className="text-2xl font-bold">리스트 초기화</span>}
|
||||
contentClassName="sm:max-w-[700px]"
|
||||
contentClassName="sm:max-w-[700px] max-h-[90vh] overflow-y-auto"
|
||||
bodyClassName="space-y-6 py-2"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" onClick={handleConfirm} disabled={submitting}>
|
||||
초기화
|
||||
{gate.hasCurrentJob ? '닫기' : '취소'}
|
||||
</Button>
|
||||
{!gate.hasCurrentJob && (
|
||||
<Button type="button" variant="destructive" onClick={handleConfirm} disabled={submitting || gate.submitBlocked}>
|
||||
초기화
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
|
||||
{!gate.hasCurrentJob && <>
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold text-red-600">초기화 대상</p>
|
||||
<ApplyFilterOption
|
||||
@@ -98,6 +106,7 @@ const ListResetDialog = ({
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</>}
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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<File | null>(null)
|
||||
const [excelHeaders, setExcelHeaders] = useState<string[]>([])
|
||||
const [otherHeaderTypeMap, setOtherHeaderTypeMap] = useState<Record<number, ListHeaderType>>({})
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [uploadMode, setUploadMode] = useState<ListUploadMode>(ListUploadMode.ADD_AND_CHANGE)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [historyExpanded, setHistoryExpanded] = useState(false)
|
||||
const [validation, setValidation] = useState<ValidationOption>({
|
||||
@@ -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={<span className="text-2xl font-bold">리스트 업로드</span>}
|
||||
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={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleDialogOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting || hasHeaderMismatch}>
|
||||
{submitting ? '업로드 중...' : '업로드'}
|
||||
{gate.hasCurrentJob ? '닫기' : '취소'}
|
||||
</Button>
|
||||
{!gate.hasCurrentJob && (
|
||||
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting || hasHeaderMismatch || gate.submitBlocked}>
|
||||
{submitting ? '업로드 중...' : '업로드'}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{
|
||||
/*
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">업로드 방식</Label>
|
||||
<RadioGroup
|
||||
value={String(uploadMode)}
|
||||
onValueChange={(value) => setUploadMode(Number(value) as ListUploadMode)}
|
||||
className="flex flex-wrap items-center gap-6"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value={String(ListUploadMode.CHANGE)} id="list-upload-mode-change" />
|
||||
<Label htmlFor="list-upload-mode-change" className="cursor-pointer">
|
||||
전체 교체
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value={String(ListUploadMode.ADD)} id="list-upload-mode-add" />
|
||||
<Label htmlFor="list-upload-mode-add" className="cursor-pointer">
|
||||
추가
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
*/
|
||||
}
|
||||
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
|
||||
{!gate.hasCurrentJob && <>
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">업로드 파일</Label>
|
||||
<div className="min-w-0 flex items-center gap-2">
|
||||
@@ -425,6 +404,7 @@ const ListUploadDialog = ({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>}
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
|
||||
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={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
{submitting ? '발송 중...' : '발송'}
|
||||
{gate.hasCurrentJob ? '닫기' : '취소'}
|
||||
</Button>
|
||||
{!gate.hasCurrentJob && (
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting || gate.submitBlocked}>
|
||||
{submitting ? '발송 중...' : '발송'}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" className="lg:col-span-2" />
|
||||
{!gate.hasCurrentJob && <>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">템플릿을 선택해 주세요</Label>
|
||||
@@ -319,6 +324,7 @@ const MessageSendDialog = ({
|
||||
</div>
|
||||
|
||||
<MessageSendPreview chnnlTy={chnnlTy} template={selectedTemplate} />
|
||||
</>}
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -65,7 +65,6 @@ export function KriEditorHtmlOnly({
|
||||
React.useEffect(() => {
|
||||
applyExternalValue(value || '')
|
||||
// 최초 마운트 시 1회만 실행 — 이후 value 변경은 아래 effect가 처리한다.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
React.useEffect(() => {
|
||||
|
||||
@@ -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'
|
||||
|
||||
156
src/components/list/ListJobGate.tsx
Normal file
156
src/components/list/ListJobGate.tsx
Normal file
@@ -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<typeof useListJobGate>
|
||||
|
||||
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 (
|
||||
<div className={`${className} space-y-3`}>
|
||||
{showCurrentJob && gate.detailPending && <p role="status" className="text-sm text-muted-foreground">현재 작업 상태를 조회하는 중입니다.</p>}
|
||||
{showCurrentJob && gate.detailError && <div role="alert" className="text-sm space-y-2">
|
||||
<p>{gate.detailNotFound ? '작업을 찾을 수 없습니다. 보관 기간이 지났거나 접근할 수 없는 작업입니다.' : '현재 작업 상태를 불러오지 못했습니다.'}</p>
|
||||
<Button type="button" variant="outline" size="sm" onClick={gate.detailNotFound ? gate.acknowledge : gate.refetchDetail}>{gate.detailNotFound ? '확인' : '다시 조회'}</Button>
|
||||
</div>}
|
||||
{showCurrentJob && job && (
|
||||
<section className="rounded-md border p-3 space-y-2" aria-label="내 현재 작업">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="font-semibold">내 현재 작업 · {listJobLabel(job.jobType, job.operation)}</p>
|
||||
{gate.finishedJob && <Button type="button" size="sm" onClick={gate.acknowledge}>{acknowledgeLabel}</Button>}
|
||||
</div>
|
||||
<ListJobProgress prjctIdx={gate.prjctIdx} job={job} />
|
||||
</section>
|
||||
)}
|
||||
{status === 'checking' && <p role="status" className="text-sm text-muted-foreground">작업 가능 여부를 확인하는 중입니다.</p>}
|
||||
{status === 'error' && (
|
||||
<p role="alert" className="text-sm text-red-600">
|
||||
작업 가능 여부를 확인하지 못했습니다.{' '}
|
||||
<Button type="button" variant="outline" size="sm" onClick={gate.refetch}>다시 조회</Button>
|
||||
</p>
|
||||
)}
|
||||
{description && (
|
||||
<div role="alert" className="rounded-md border border-amber-300 bg-amber-50 p-3 space-y-2 text-sm">
|
||||
<p className="font-medium text-amber-800">{description.message}</p>
|
||||
{listedBlockers.length > 0 && (
|
||||
<ul className="space-y-1">
|
||||
{listedBlockers.map((blocker, index) => (
|
||||
<li key={`${blocker.requestUserId}-${blocker.regDt}-${index}`}>
|
||||
{blockerJobLabel(blocker)} · {blocker.mine ? '나' : blockerUserLabel(blocker)} · {blockerPhaseLabel(blocker)} · 접수 {blocker.regDt.replace('T', ' ').slice(0, 19)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{description.omittedCount > 0 && <p className="text-muted-foreground">외 {description.omittedCount.toLocaleString()}건은 표시하지 않았습니다.</p>}
|
||||
</div>
|
||||
)}
|
||||
{status === 'blocked' && uploadResetJob && !uploadResetDetailShown && (
|
||||
<div role="status" className="text-sm text-muted-foreground space-y-1">
|
||||
<p>{listJobLabel(uploadResetJob.jobType)} 처리 {uploadResetJob.processedSidCnt.toLocaleString()}
|
||||
{uploadResetJob.totalSidCnt === null ? '건 · 전체 집계 중' : ` / ${uploadResetJob.totalSidCnt.toLocaleString()}건`}</p>
|
||||
{uploadResetJob.totalSidCnt !== null && uploadResetJob.totalSidCnt > 0 && <progress className="w-full" aria-label={`${listJobLabel(uploadResetJob.jobType)} 진행률`} max={uploadResetJob.totalSidCnt} value={Math.min(uploadResetJob.totalSidCnt, uploadResetJob.processedSidCnt)} />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
195
src/components/list/ListJobProgress.tsx
Normal file
195
src/components/list/ListJobProgress.tsx
Normal file
@@ -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<JobDetailPath, readonly (readonly [string, string])[]> = {
|
||||
'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<string, string> = {
|
||||
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 <progress aria-label="SID 처리 진행률" className="w-full" max={total} value={Math.min(total, processed)} />
|
||||
}
|
||||
|
||||
function Progress({ job }: { job: ListJob }) {
|
||||
const p = job.progress ?? {}
|
||||
if (job.jobType.endsWith('_BULK')) return (
|
||||
<div className="text-sm space-y-1">
|
||||
<p>수신처 {n(p.preparedRecipientCnt)} · 접수 {n(p.acceptedRecipientCnt)} · 실패 {n(p.failedRecipientCnt)} · 접수 여부 불명 {n(p.unknownRecipientCnt)}</p>
|
||||
<p>발송 준비 실패 SID {n(p.preparationFailedSidCnt)} · 처리 수신처 {n(p.processedRecipientCnt)} / {n(p.preparedRecipientCnt)}</p>
|
||||
<p className="text-muted-foreground">발송 요청의 접수 결과입니다. 실제 전달 결과는 발송 이력에서 확인하세요. 접수 여부 불명 건은 재발송 전에 확인해야 합니다.</p>
|
||||
</div>
|
||||
)
|
||||
if (job.jobType.endsWith('_DOWNLOAD')) return <p className="text-sm">파일 처리 대상 {n(p.processedSidCnt)} · 작성 행 {n(p.writtenRowCnt)} · 작성 파일 {n(p.writtenFileCnt)}</p>
|
||||
return (
|
||||
<div className="text-sm space-y-1">
|
||||
<p>전체 {job.totalSidCnt === null ? '집계 중' : n(job.totalSidCnt)} · 반영 완료 {n(job.completedSidCnt)} · SID 실패 {n(job.failedSidCnt)} · 완료 구간 {n(job.completedChunkCnt)}</p>
|
||||
{typeof p.deleteTotalSidCnt === 'number' && <p>기존 데이터 삭제 {n(p.deleteCompletedSidCnt)} / {n(p.deleteTotalSidCnt)} · 삭제 실패 구간 {n(p.deleteFailedRangeCnt)}</p>}
|
||||
{typeof p.insertTotalSidCnt === 'number' && <p>신규 등록 {n(p.insertCompletedSidCnt)} / {n(p.insertTotalSidCnt)} · 등록 실패 구간 {n(p.insertFailedRangeCnt)}</p>}
|
||||
<SidProgress total={job.totalSidCnt} processed={job.processedSidCnt} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function JobDetailItem({ path, item }: { path: JobDetailPath; item: Record<string, unknown> }) {
|
||||
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 (
|
||||
<div className="space-y-1 break-words">
|
||||
<p>{fields.join(' · ') || '표시할 상세 정보가 없습니다.'}</p>
|
||||
{sids.length > 0 && <details><summary className="cursor-pointer">대상 SID {sids.length.toLocaleString()}건</summary><p className="break-all">{sids.join(', ')}</p></details>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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<ListJobFailurePage> => {
|
||||
const value = await nextApi.get<unknown>(`/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 (
|
||||
<section className="rounded border p-3 space-y-3" aria-label="작업 상세 내역">
|
||||
{sections.length > 1 ? <label className="flex gap-2 items-center text-sm">조회 항목
|
||||
<select className="rounded border p-2" value={section.path} onChange={event => {
|
||||
const next = sections.find(item => item.path === event.target.value)
|
||||
if (next) { setSelectedPath(next.path); setOffset(0) }
|
||||
}}>
|
||||
{sections.map(item => <option key={item.path} value={item.path}>{item.label}</option>)}
|
||||
</select>
|
||||
</label> : <p className="text-sm font-medium">{section.label}</p>}
|
||||
{failures.isPending && <p role="status" className="text-sm">상세 내역을 조회하는 중입니다.</p>}
|
||||
{failures.isError && <div role="alert" className="text-sm space-y-2">
|
||||
<p>상세 내역을 불러오지 못했습니다.</p>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => void failures.refetch()}>다시 조회</Button>
|
||||
</div>}
|
||||
{!failures.isError && failures.data && <>
|
||||
<p className="text-sm">전체 {failures.data.total.toLocaleString()}건</p>
|
||||
{failures.data.items.length === 0 ? <p className="text-sm text-muted-foreground">조회된 내역이 없습니다.</p> : <ul className="max-h-60 overflow-auto text-sm space-y-2">
|
||||
{failures.data.items.map((item, index) => <li key={offset + index} className="border-b pb-1"><JobDetailItem path={section.path} item={item} /></li>)}
|
||||
</ul>}
|
||||
{failures.data.total > 100 && <div className="flex gap-2">
|
||||
<Button type="button" variant="outline" disabled={offset === 0 || failures.isFetching} onClick={() => setOffset(Math.max(0, offset - 100))}>이전 100건</Button>
|
||||
<Button type="button" variant="outline" disabled={offset + 100 >= failures.data.total || failures.isFetching} onClick={() => setOffset(offset + 100)}>다음 100건</Button>
|
||||
</div>}
|
||||
</>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
export function ListJobProgress({ prjctIdx, job }: { prjctIdx: number; job: ListJob }) {
|
||||
const qc = useQueryClient()
|
||||
const [detailJobKey, setDetailJobKey] = useState<string | null>(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 (
|
||||
<div className="space-y-3">
|
||||
{active && <p className="text-sm text-muted-foreground">창을 닫아도 작업은 계속되며, 완료 시 알림을 드립니다.</p>}
|
||||
<p><strong>{statusText}</strong> · 단계: {stageLabel(job.jobStage)} · 접수 {job.regDt.replace('T', ' ').slice(0, 19)}</p>
|
||||
<Progress job={job} />
|
||||
{job.jobStatus !== 'SUCCEEDED' && !active && <p className="text-sm text-red-600">{job.errorMessage || (job.cancelReason === 'USER_REQUEST' ? '사용자 요청으로 중단됐습니다.' : '처리가 종료됐습니다.')} {job.jobStage === 'VALIDATION_FAILED' ? '파일 검증 단계에서 중단되어 리스트 데이터는 변경되지 않았습니다.' : '이미 반영된 내용이 있을 수 있으니 확인 후 다시 요청하세요.'}</p>}
|
||||
{job.jobStatus === 'FAILED' && job.failedChunkNo != null && <p className="text-sm text-red-600">실패한 처리 구간: {n(job.failedChunkNo)}번째</p>}
|
||||
{(job.resultFiles.length > 0 || job.jobType === 'LIST_UPLOAD') && <div className="flex flex-wrap gap-3 text-sm">
|
||||
{job.resultFiles.map(file => file.ready
|
||||
? <a className="underline" key={file.index} href={`${clientEnv.API_BASE}/list-jobs/${prjctIdx}/${job.jobKey}/files/${file.index}`} download={file.fileName} target="_blank" rel="noopener noreferrer">{file.fileName} 다운로드</a>
|
||||
: <span key={file.index}>{file.fileName}: 다운로드 완료 또는 보관기간 종료</span>)}
|
||||
{job.jobType === 'LIST_UPLOAD' && <a className="underline" href={`${clientEnv.API_BASE}/list-jobs/${prjctIdx}/${job.jobKey}/source-file`} download target="_blank" rel="noopener noreferrer">업로드 원본</a>}
|
||||
</div>}
|
||||
{job.resultFiles.length > 0 && <p className="text-sm text-muted-foreground">파일은 다운로드 후 또는 보관 기간 만료 시 삭제됩니다.</p>}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{active && <Button variant="outline" disabled={cancel.isPending || job.jobStatus === 'CANCEL_REQUESTED'} onClick={() => {
|
||||
if (confirm('작업을 중단할까요? 이미 반영된 구간은 유지됩니다.')) cancel.mutate()
|
||||
}}>중단 요청</Button>}
|
||||
{sections.length > 0 && <Button type="button" variant="outline" onClick={() => setDetailJobKey(detailOpen ? null : job.jobKey)}>{detailLabel} {detailOpen ? '닫기' : '보기'}</Button>}
|
||||
</div>
|
||||
{detailOpen && sections.length > 0 && <JobFailures key={`${job.jobKey}-${sections.map(section => section.path).join('|')}`} prjctIdx={prjctIdx} job={job} sections={sections} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
115
src/components/list/ListJobWatcher.tsx
Normal file
115
src/components/list/ListJobWatcher.tsx
Normal file
@@ -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<string, unknown>
|
||||
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<unknown>(`/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
|
||||
}
|
||||
@@ -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<ListManageActionKey>
|
||||
disabledActions?: ReadonlySet<ListManageActionKey>
|
||||
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)
|
||||
? <Loader2 className="w-4 h-4 animate-spin" aria-label="진행 중" />
|
||||
: <Icon className="w-4 h-4" />
|
||||
|
||||
return (
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex flex-1 items-center gap-2 flex-wrap">
|
||||
{showAdminActions && (
|
||||
<>
|
||||
<Button variant="destructive" className="text-base gap-2" onClick={onReset}>
|
||||
<RotateCcw className="w-4 h-4" />
|
||||
<Button variant="destructive" className="text-base gap-2" onClick={onReset} disabled={disabledActions?.has('reset')}>
|
||||
{icon('reset', RotateCcw)}
|
||||
리스트 초기화
|
||||
</Button>
|
||||
<Button className="text-base" onClick={onHeaderManage}>
|
||||
<Button className="text-base" onClick={onHeaderManage} disabled={headerManageDisabled}>
|
||||
헤더 관리
|
||||
</Button>
|
||||
<Button className="text-base gap-2" onClick={onUpload}>
|
||||
<Upload className="w-4 h-4" />
|
||||
<Button className="text-base gap-2" onClick={onUpload} disabled={disabledActions?.has('upload')}>
|
||||
{icon('upload', Upload)}
|
||||
리스트 업로드
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list')}>
|
||||
<Download className="w-4 h-4" />
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list')} disabled={disabledActions?.has('list')}>
|
||||
{icon('list', Download)}
|
||||
리스트
|
||||
</Button>
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('contact-history')}>
|
||||
<Download className="w-4 h-4" />
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('contact-history')} disabled={disabledActions?.has('contact-history')}>
|
||||
{icon('contact-history', Download)}
|
||||
컨택 이력
|
||||
</Button>
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list-change-history')}>
|
||||
<Download className="w-4 h-4" />
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list-change-history')} disabled={disabledActions?.has('list-change-history')}>
|
||||
{icon('list-change-history', Download)}
|
||||
리스트 변경 이력
|
||||
</Button>
|
||||
<Button className="text-base gap-2" onClick={() => onDownload('upload-file')}>
|
||||
<Download className="w-4 h-4" />
|
||||
<Button className="text-base gap-2" onClick={() => onDownload('upload-file')} disabled={disabledActions?.has('upload-file')}>
|
||||
{icon('upload-file', Download)}
|
||||
업로드 파일(.zip)
|
||||
</Button>
|
||||
</div>
|
||||
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('email')}>
|
||||
<Mail className="w-4 h-4" />
|
||||
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('email')} disabled={disabledActions?.has('email')}>
|
||||
{icon('email', Mail)}
|
||||
이메일 발송
|
||||
</Button>
|
||||
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('sms')}>
|
||||
<MessageSquareMore className="w-4 h-4" />
|
||||
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('sms')} disabled={disabledActions?.has('sms')}>
|
||||
{icon('sms', MessageSquareMore)}
|
||||
문자 발송
|
||||
</Button>
|
||||
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('kko')}>
|
||||
<MessageCircle className="w-4 h-4" />
|
||||
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('kko')} disabled={disabledActions?.has('kko')}>
|
||||
{icon('kko', MessageCircle)}
|
||||
알림톡 발송
|
||||
</Button>
|
||||
<Button className="text-base gap-2" onClick={onMessageHistory}>
|
||||
|
||||
@@ -15,7 +15,8 @@ import ListBatchEditDialog, { type BatchEditPayload, type BatchEditResultCodes,
|
||||
import ListFilterDialog, { operatorLabel } from '@/components/dialog/ListFilterDialog'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useListSearchQuery, useUpdateListMutation } from '@/query/list'
|
||||
import { useListSearchQuery } from '@/query/list'
|
||||
import { useSubmitListJob } from '@/query/list-job'
|
||||
import { getListColumns, LIST_IS_USE_LABEL, type ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||
import { useAssignTargetRows } from '@/components/assign/AssignTargetList'
|
||||
import { ListHeaderAssignConst, ListHeaderConst } from '@/const/listConst'
|
||||
@@ -56,6 +57,8 @@ export type ListSearchTableProps = {
|
||||
listHeaders: listHeader[]
|
||||
fieldInterviewEnabled?: boolean
|
||||
enableBatchEdit?: boolean
|
||||
batchEditDisabled?: boolean
|
||||
dataRevision?: number
|
||||
refreshKey?: number
|
||||
selectMode?: SelectMode
|
||||
filterActions?: ReactNode
|
||||
@@ -184,6 +187,8 @@ export function ListSearchTable({
|
||||
listHeaders,
|
||||
fieldInterviewEnabled = true,
|
||||
enableBatchEdit = false,
|
||||
batchEditDisabled = false,
|
||||
dataRevision = 0,
|
||||
refreshKey = 0,
|
||||
selectMode = 'multi',
|
||||
filterActions,
|
||||
@@ -228,7 +233,7 @@ export function ListSearchTable({
|
||||
[selectedRows],
|
||||
)
|
||||
|
||||
const updateListMutation = useUpdateListMutation(prjctIdx)
|
||||
const updateListMutation = useSubmitListJob(prjctIdx)
|
||||
|
||||
const outsourceTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: ListHeaderAssignConst.OUTSOURCE })
|
||||
const contactTargetRows = useAssignTargetRows({
|
||||
@@ -530,6 +535,17 @@ export function ListSearchTable({
|
||||
const totalCount = listSearchQuery.data?.totalElements ?? 0
|
||||
const pageCount = listSearchQuery.data?.totalPages ?? 0
|
||||
|
||||
useEffect(() => {
|
||||
if (!dataRevision) return
|
||||
handleRowSelectionChange([])
|
||||
}, [dataRevision, handleRowSelectionChange])
|
||||
|
||||
useEffect(() => {
|
||||
if (!listSearchQuery.isSuccess || listSearchQuery.isFetching || listSearchQuery.isPlaceholderData) return
|
||||
const lastPage = Math.max(0, pageCount - 1)
|
||||
if (pagination.pageIndex > lastPage) setPagination(previous => ({ ...previous, pageIndex: lastPage }))
|
||||
}, [listSearchQuery.isSuccess, listSearchQuery.isFetching, listSearchQuery.isPlaceholderData, pageCount, pagination.pageIndex])
|
||||
|
||||
const headerOptions = useMemo(
|
||||
() =>
|
||||
accessibleListHeaders
|
||||
@@ -625,12 +641,15 @@ export function ListSearchTable({
|
||||
setBatchSurveyResultCodes(Object.fromEntries(surveyResultCodes.map((item) => [item.prjctSurveyIdx, item.resultCd])))
|
||||
const updateContents = Object.fromEntries(rows.map((row) => [String(row.headerId), row.value]))
|
||||
await updateListMutation.mutateAsync({
|
||||
jobType: 'LIST_UPDATE',
|
||||
path: 'mutations/update',
|
||||
body: {
|
||||
updateContents,
|
||||
updateResultCodes: resultCodeSelections,
|
||||
updateSurveyResultCodes: surveyResultCodes,
|
||||
listFilter: buildTargetFilter(target),
|
||||
},
|
||||
})
|
||||
await listSearchQuery.refetch()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -836,7 +855,7 @@ export function ListSearchTable({
|
||||
</Button>
|
||||
{filterActions}
|
||||
{enableBatchEdit ? (
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listBatchEditDialog')}>
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listBatchEditDialog')} disabled={batchEditDisabled}>
|
||||
<PencilLine className="w-4 h-4" />
|
||||
일괄 수정
|
||||
</Button>
|
||||
@@ -848,6 +867,7 @@ export function ListSearchTable({
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<DataTable<ListTableRow>
|
||||
key={dataRevision}
|
||||
columns={columns}
|
||||
data={viewList}
|
||||
getRowId={(row) => String(row.sid)}
|
||||
@@ -871,6 +891,7 @@ export function ListSearchTable({
|
||||
<ListFilterDialog headerOptions={filterHeaderOptions} initialRows={filterRows} onConfirm={handleFilterConfirm} />
|
||||
{enableBatchEdit ? (
|
||||
<ListBatchEditDialog
|
||||
prjctIdx={prjctIdx}
|
||||
headerOptions={headerOptions}
|
||||
resultCodes={resultCodes}
|
||||
surveys={surveys}
|
||||
|
||||
74
src/const/listJobConst.ts
Normal file
74
src/const/listJobConst.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import type { ListDownloadMode } from '@/types/list'
|
||||
import type { MessageSendChannel } from '@/types/message'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import { isListJobType, type ListJobOperation, type ListJobType } from '@/types/list-job'
|
||||
|
||||
export const LIST_JOB_TYPE_LABEL: Record<ListJobType, string> = {
|
||||
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<ListJobOperation, string> = {
|
||||
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<string, string> = {
|
||||
QUEUED: '대기', RUNNING: '진행 중', CANCEL_REQUESTED: '중단 요청 중', SUCCEEDED: '완료',
|
||||
FAILED: '실패', CANCELLED: '중단', REJECTED: '접수 거절',
|
||||
}
|
||||
|
||||
export const LIST_JOB_STAGE_LABEL: Record<string, string> = {
|
||||
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<ListDownloadMode, ListJobType> = {
|
||||
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<MessageSendChannel, ListJobType> = {
|
||||
email: 'EMAIL_BULK',
|
||||
sms: 'SMS_BULK',
|
||||
kko: 'KKO_BULK',
|
||||
}
|
||||
|
||||
export const LIST_JOB_VIEW: Record<ListJobType, {
|
||||
path: '/list/manage' | '/assign/list'
|
||||
dialogId?: DialogId
|
||||
downloadMode?: ListDownloadMode
|
||||
messageMode?: MessageSendChannel
|
||||
}> = {
|
||||
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' },
|
||||
}
|
||||
37
src/hooks/useListJobPageMonitor.ts
Normal file
37
src/hooks/useListJobPageMonitor.ts
Normal file
@@ -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 }
|
||||
}
|
||||
@@ -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<typeof useQueryClient>, 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<number>(`/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<number>(`/assign/list/reset/${prjctIdx}`, { json: request }),
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
qc.invalidateQueries({ queryKey: ["list", "search-filter"] }),
|
||||
invalidateAssignSummaries(qc, prjctIdx),
|
||||
]);
|
||||
},
|
||||
});
|
||||
}
|
||||
152
src/query/list-job.ts
Normal file
152
src/query/list-job.ts
Normal file
@@ -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<ListJobType | null>(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 },
|
||||
})
|
||||
}
|
||||
@@ -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<ExcelUploadResult>(`/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<number>(`/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<ArrayBuffer>(`/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<ArrayBuffer>(`/list/excel-download-update/${prjctIdx}`, listFilter, { expectBinary: true }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadListEventHistoryMutation(prjctIdx: number) {
|
||||
return useMutation({
|
||||
mutationFn: ({ includeResult, ...request }: ListEventHistDownloadRequest & { includeResult: boolean }) =>
|
||||
nextApi.post<ArrayBuffer>(`/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<ArrayBuffer>(`/list/item-file-download/${prjctIdx}`, listFilter, { expectBinary: true }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadUploadHistoryFileMutation(prjctIdx: number) {
|
||||
return useMutation({
|
||||
mutationFn: (listUploadLogId: string) =>
|
||||
|
||||
@@ -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<BulkSendResult>(`/message-send/${channel}/bulk/${prjctIdx}`, req),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* SID 단위 발송 결과 목록 조회 (GET /message-report/send-result/{sid}/{prjctCd}/{reqstSvc})
|
||||
*/
|
||||
|
||||
@@ -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<string> => {
|
||||
const formData = new FormData();
|
||||
|
||||
15
src/store/jotai/list-job.ts
Normal file
15
src/store/jotai/list-job.ts
Normal file
@@ -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<ListJobOpenRequest | null>(null);
|
||||
97
src/store/list-job-tracker.ts
Normal file
97
src/store/list-job-tracker.ts
Normal file
@@ -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<string, unknown>
|
||||
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<unknown>(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<TrackedListJob, 'userId' | 'prjctIdx' | 'jobType' | 'jobKey'>) => {
|
||||
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)
|
||||
@@ -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<StorageKey, "local" | "session"> = {
|
||||
[StorageKeys.ItrntUserList]: "session",
|
||||
[StorageKeys.LastListVisit]: "session",
|
||||
[StorageKeys.CtiState]: "local",
|
||||
[StorageKeys.ListJobs]: "local",
|
||||
};
|
||||
|
||||
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];
|
||||
|
||||
156
src/types/list-job.ts
Normal file
156
src/types/list-job.ts
Normal file
@@ -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<string, unknown> | 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<string, unknown>[] }
|
||||
|
||||
/** 새 작업 접수를 막고 있는 작업. 타인 작업이면 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<string, unknown>
|
||||
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<string, unknown>).items)) {
|
||||
throw new Error('작업 목록 응답이 올바르지 않습니다.')
|
||||
}
|
||||
return ((value as Record<string, unknown>).items as unknown[]).map(parseListJob)
|
||||
}
|
||||
|
||||
export function parseUploadResetActive(value: unknown): UploadResetActive {
|
||||
if (!value || typeof value !== 'object') throw new Error('진행 상태 응답이 올바르지 않습니다.')
|
||||
const body = value as Record<string, unknown>
|
||||
if (typeof body.active !== 'boolean') throw new Error('진행 상태 응답이 올바르지 않습니다.')
|
||||
if (body.job === null) return { active: body.active, job: null }
|
||||
const job = body.job as Record<string, unknown> | 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<string, unknown>
|
||||
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<string, unknown>
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -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 ||
|
||||
|
||||
52
src/utils/listJobAvailability.ts
Normal file
52
src/utils/listJobAvailability.ts
Normal file
@@ -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 }
|
||||
}
|
||||
Reference in New Issue
Block a user