159 lines
9.6 KiB
TypeScript
159 lines
9.6 KiB
TypeScript
'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'
|
|
// 재조회 중에는 직전 결과를 유지한다. 같은 쿼리를 페이지가 주기적으로 재조회하므로 isFetching을 '확인 중'으로
|
|
// 보면 그때마다 다이얼로그가 깜빡인다. 접수 직전에는 useSubmitListJob이 다시 확인한다.
|
|
: !availability.data ? '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>
|
|
)
|
|
}
|