261019_01_ENH: 리스트 비동기 작업 동시 실행 제한 및 진행 상태 UI 개선, 미사용 참조 정리
This commit is contained in:
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}
|
||||
|
||||
Reference in New Issue
Block a user