261020_02_FIX: 짧은 비동기 작업 종료 시 리스트 및 배정 목록이 갱신되지 않는 오류 수정
This commit is contained in:
@@ -17,6 +17,7 @@ import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
|
||||
import { useListHeaderQuery } from '@/query/list'
|
||||
import { ListJobPageQueryContext, useSubmitListJob } from '@/query/list-job'
|
||||
import { ListJobGatePanel } from '@/components/list/ListJobGate'
|
||||
import { ListJobRefreshNotice } from '@/components/list/ListJobRefreshNotice'
|
||||
import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
|
||||
import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst'
|
||||
import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list'
|
||||
@@ -60,7 +61,11 @@ const ListAssignPage = () => {
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||
const assignMutation = useSubmitListJob(prjctIdx)
|
||||
const { gate: assignGate, dataRevision } = useListJobPageMonitor(prjctIdx, 'LIST_ASSIGN', enabled)
|
||||
const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_ASSIGN', enabled, {
|
||||
hasSelection: !!selectedAssignId,
|
||||
isSubmitting: assignMutation.isPending,
|
||||
})
|
||||
const { gate: assignGate, dataRevision } = pageMonitor
|
||||
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
|
||||
const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: effectiveAssignType })
|
||||
|
||||
@@ -200,6 +205,7 @@ const ListAssignPage = () => {
|
||||
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<ListJobGatePanel gate={assignGate} />
|
||||
<ListJobRefreshNotice monitor={pageMonitor} />
|
||||
<ListSearchTable
|
||||
dataRevision={dataRevision}
|
||||
prjctIdx={prjctIdx}
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
} from '@/query/list'
|
||||
import { ListJobPageQueryContext, useMyActiveListJobs, useSubmitListJob } from '@/query/list-job'
|
||||
import { ListJobGatePanel } from '@/components/list/ListJobGate'
|
||||
import { ListJobRefreshNotice } from '@/components/list/ListJobRefreshNotice'
|
||||
import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
|
||||
import { useTrackedListJobs } from '@/store/list-job-tracker'
|
||||
import { isListPageActionBlocked } from '@/utils/listJobAvailability'
|
||||
@@ -115,7 +116,8 @@ const ListManagePage = () => {
|
||||
const canManageList = isManager(userRole);
|
||||
// 리스트 초기화/헤더 관리/업로드는 내부 관리자 전용 — 외주사 계정에는 노출되면 안 됨.
|
||||
const isInternal = isInternalManager(userRole);
|
||||
const { gate: pageGate, dataRevision } = useListJobPageMonitor(prjctIdx, 'LIST_RESET', enabled)
|
||||
const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_RESET', enabled, { hasSelection: selectedRows.length > 0 })
|
||||
const { gate: pageGate, dataRevision } = pageMonitor
|
||||
const trackedJobs = useTrackedListJobs()
|
||||
|
||||
useEffect(() => {
|
||||
@@ -321,6 +323,7 @@ const ListManagePage = () => {
|
||||
<ListJobPageQueryContext.Provider value="LIST_RESET">
|
||||
<div className="space-y-6 text-sm">
|
||||
<ListJobGatePanel gate={pageGate} showCurrentJob={false} />
|
||||
<ListJobRefreshNotice monitor={pageMonitor} clearsSelection={selectedRows.length > 0} />
|
||||
{canManageList && (
|
||||
<ListManageActions
|
||||
showAdminActions={isInternal}
|
||||
|
||||
22
src/components/list/ListJobRefreshNotice.tsx
Normal file
22
src/components/list/ListJobRefreshNotice.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { ListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
|
||||
|
||||
export function ListJobRefreshNotice({ monitor, clearsSelection = false }: {
|
||||
monitor: ListJobPageMonitor
|
||||
clearsSelection?: boolean
|
||||
}) {
|
||||
if (!monitor.pendingRefresh) return null
|
||||
return (
|
||||
<div role="status" className="flex items-center justify-between gap-3 rounded-md border bg-muted/30 p-3 text-sm">
|
||||
<p>{monitor.refreshError ? '목록을 새로 불러오지 못했습니다. 다시 시도해 주세요.'
|
||||
: clearsSelection ? '목록이 변경되었습니다. 새로고침하면 선택한 행이 해제됩니다.'
|
||||
: '목록이 변경되었습니다. 작업을 마친 뒤 새로고침해 주세요.'}</p>
|
||||
<Button type="button" variant="outline" size="sm" disabled={monitor.refreshBlocked || monitor.refreshing}
|
||||
onClick={() => void monitor.refresh()}>
|
||||
{monitor.refreshing ? '새로고침 중…' : '새로고침'}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,37 +1,108 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useListJobGate } from '@/components/list/ListJobGate'
|
||||
import { listMutationBlockerIds } from '@/utils/listJobAvailability'
|
||||
import { observeListMutations } from '@/utils/listJobAvailability'
|
||||
import type { ListJobType } from '@/types/list-job'
|
||||
|
||||
/** 두 목록 화면의 공용 감시. 타인의 변경 작업도 종료 시 현재 프로젝트 데이터를 갱신한다. */
|
||||
export function useListJobPageMonitor(prjctIdx: number, jobType: ListJobType, active: boolean) {
|
||||
export function useListJobPageMonitor(prjctIdx: number, jobType: ListJobType, active: boolean,
|
||||
{ hasSelection = false, isSubmitting = false }: { hasSelection?: boolean; isSubmitting?: boolean } = {}) {
|
||||
const gate = useListJobGate({ prjctIdx, jobType, active, pollWhileIdle: true, requestLabel: jobType === 'LIST_ASSIGN' ? '배정' : '업로드·초기화·일괄 수정' })
|
||||
const qc = useQueryClient()
|
||||
const { auth } = useAuth()
|
||||
const { openDialogIds } = useDialog()
|
||||
const userId = auth.user?.userId
|
||||
const previous = useRef<{ scope: string; ids: string[] } | null>(null)
|
||||
const scope = JSON.stringify([userId, prjctIdx])
|
||||
const previous = useRef<{ scope: string; snapshot: ReturnType<typeof observeListMutations>['snapshot'] } | null>(null)
|
||||
const sequence = useRef(0)
|
||||
const generation = useRef(0)
|
||||
const [pendingChange, setPendingChange] = useState<{ scope: string; id: number } | null>(null)
|
||||
const inFlight = useRef<{ scope: string; id: number } | null>(null)
|
||||
const [refreshingScope, setRefreshingScope] = useState<string | null>(null)
|
||||
const [errorScope, setErrorScope] = useState<string | null>(null)
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
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
|
||||
if (!active || !userId) {
|
||||
generation.current += 1
|
||||
previous.current = null
|
||||
setPendingChange(null)
|
||||
setErrorScope(null)
|
||||
return
|
||||
}
|
||||
if (previous.current?.scope !== scope) {
|
||||
generation.current += 1
|
||||
previous.current = null
|
||||
setPendingChange(null)
|
||||
setErrorScope(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])
|
||||
if (!gate.availabilitySucceeded || !availability) return
|
||||
const observation = observeListMutations(previous.current?.snapshot, availability)
|
||||
previous.current = { scope, snapshot: observation.snapshot }
|
||||
if (!observation.changed) return
|
||||
sequence.current += 1
|
||||
setPendingChange({ scope, id: sequence.current })
|
||||
setErrorScope(null)
|
||||
}, [active, userId, scope, gate.availability, gate.availabilitySucceeded, gate.availabilityUpdatedAt])
|
||||
|
||||
return { gate, dataRevision }
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
const editing = (element: EventTarget | null) => element instanceof HTMLElement
|
||||
&& (element.matches('input, textarea, [contenteditable="true"], [role="combobox"]')
|
||||
|| !!element.closest('[role="listbox"]'))
|
||||
const focusIn = (event: FocusEvent) => setIsEditing(editing(event.target))
|
||||
const focusOut = (event: FocusEvent) => setIsEditing(editing(event.relatedTarget))
|
||||
setIsEditing(editing(document.activeElement))
|
||||
document.addEventListener('focusin', focusIn)
|
||||
document.addEventListener('focusout', focusOut)
|
||||
return () => {
|
||||
document.removeEventListener('focusin', focusIn)
|
||||
document.removeEventListener('focusout', focusOut)
|
||||
}
|
||||
}, [active])
|
||||
|
||||
const pendingRefresh = active && !!userId && pendingChange?.scope === scope
|
||||
const refreshing = refreshingScope === scope
|
||||
const refreshError = errorScope === scope
|
||||
const refreshBlocked = openDialogIds.length > 0 || isSubmitting
|
||||
|| !gate.availabilitySucceeded || gate.status !== 'allowed'
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (!pendingRefresh || !pendingChange || refreshBlocked || inFlight.current?.scope === scope) return
|
||||
const request = pendingChange
|
||||
const requestGeneration = generation.current
|
||||
inFlight.current = request
|
||||
setRefreshingScope(scope)
|
||||
setErrorScope(null)
|
||||
try {
|
||||
await qc.invalidateQueries({ predicate: query =>
|
||||
(query.queryKey[0] === 'list' || query.queryKey[0] === 'assign') && query.queryKey[2] === prjctIdx },
|
||||
{ throwOnError: true })
|
||||
if (previous.current?.scope !== scope || generation.current !== requestGeneration) return
|
||||
// 조회 중 새 변경이 감지됐다면 다음 갱신 대상으로 남긴다.
|
||||
setPendingChange(current => current === request ? null : current)
|
||||
setDataRevision(revision => revision + 1)
|
||||
} catch {
|
||||
if (previous.current?.scope === scope && generation.current === requestGeneration) setErrorScope(scope)
|
||||
} finally {
|
||||
if (inFlight.current === request) {
|
||||
inFlight.current = null
|
||||
setRefreshingScope(current => current === scope ? null : current)
|
||||
}
|
||||
}
|
||||
}, [pendingRefresh, pendingChange, refreshBlocked, scope, prjctIdx, qc])
|
||||
|
||||
useEffect(() => {
|
||||
if (pendingRefresh && !hasSelection && !isEditing && !refreshing && !refreshError) void refresh()
|
||||
}, [pendingRefresh, hasSelection, isEditing, refreshing, refreshError, refresh])
|
||||
|
||||
return { gate, dataRevision, pendingRefresh, refreshing, refreshError, refreshBlocked, refresh }
|
||||
}
|
||||
|
||||
export type ListJobPageMonitor = ReturnType<typeof useListJobPageMonitor>
|
||||
|
||||
@@ -66,12 +66,18 @@ export type ListJobBlocker = {
|
||||
regDt: string
|
||||
}
|
||||
|
||||
export type ListMutationCompletion = {
|
||||
finishedCount: number
|
||||
lastFinishedAt: string | null
|
||||
}
|
||||
|
||||
export type ListJobAvailability = {
|
||||
requestedJobType: string
|
||||
allowed: boolean
|
||||
reasonCode: string | null
|
||||
blockerCount: number
|
||||
blockers: ListJobBlocker[]
|
||||
mutationCompletion?: ListMutationCompletion
|
||||
}
|
||||
|
||||
export const isActiveListJob = (status: ListJobStatus) =>
|
||||
@@ -146,11 +152,31 @@ export function parseListJobAvailability(value: unknown): ListJobAvailability {
|
||||
|| typeof body.blockerCount !== 'number' || !Array.isArray(body.blockers) || !body.blockers.every(isBlocker)) {
|
||||
throw new Error('작업 가능 여부 응답이 올바르지 않습니다.')
|
||||
}
|
||||
const completion = body.mutationCompletion
|
||||
let mutationCompletion: ListMutationCompletion | undefined
|
||||
if (completion !== undefined) {
|
||||
if (!completion || typeof completion !== 'object'
|
||||
|| !('finishedCount' in completion) || typeof completion.finishedCount !== 'number'
|
||||
|| !Number.isSafeInteger(completion.finishedCount) || completion.finishedCount < 0
|
||||
|| !('lastFinishedAt' in completion)
|
||||
|| !(completion.lastFinishedAt === null || typeof completion.lastFinishedAt === 'string')
|
||||
|| !(completion.finishedCount === 0 ? completion.lastFinishedAt === null
|
||||
: typeof completion.lastFinishedAt === 'string'
|
||||
&& /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(completion.lastFinishedAt)
|
||||
&& !Number.isNaN(Date.parse(completion.lastFinishedAt)))) {
|
||||
throw new Error('작업 종료 요약 응답이 올바르지 않습니다.')
|
||||
}
|
||||
mutationCompletion = {
|
||||
finishedCount: completion.finishedCount,
|
||||
lastFinishedAt: completion.lastFinishedAt,
|
||||
}
|
||||
}
|
||||
return {
|
||||
requestedJobType: body.requestedJobType,
|
||||
allowed: body.allowed,
|
||||
reasonCode: body.reasonCode,
|
||||
blockerCount: body.blockerCount,
|
||||
blockers: body.blockers,
|
||||
...(mutationCompletion === undefined ? {} : { mutationCompletion }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { listJobLabel } from '@/const/listJobConst'
|
||||
import type { ListJobAvailability, ListJobBlocker, ListJobType } from '@/types/list-job'
|
||||
import type { ListJobAvailability, ListJobBlocker, ListJobType, ListMutationCompletion } from '@/types/list-job'
|
||||
|
||||
const MUTATION_JOB_TYPES = new Set(['LIST_UPLOAD', 'LIST_RESET', 'LIST_UPDATE', 'LIST_ASSIGN'])
|
||||
|
||||
@@ -8,6 +8,29 @@ export const listMutationBlockerIds = (availability: ListJobAvailability) => ava
|
||||
.filter(blocker => MUTATION_JOB_TYPES.has(blocker.jobType))
|
||||
.map(blocker => JSON.stringify([blocker.jobType, blocker.operation, blocker.requestUserId, blocker.regDt]))
|
||||
|
||||
type ListMutationSnapshot = {
|
||||
ids: string[] | null
|
||||
completion: ListMutationCompletion | undefined
|
||||
}
|
||||
|
||||
/** 요약은 짧은 작업도 감지한다. 구버전 서버에서는 기존 차단 목록의 종료 감지를 유지한다. */
|
||||
export function observeListMutations(previous: ListMutationSnapshot | undefined, availability: ListJobAvailability) {
|
||||
const ids = availability.blockerCount > availability.blockers.length ? null : listMutationBlockerIds(availability)
|
||||
const completion = availability.mutationCompletion
|
||||
const completionChanged = previous !== undefined && completion !== undefined
|
||||
&& (previous.completion === undefined
|
||||
|| previous.completion.finishedCount !== completion.finishedCount
|
||||
|| previous.completion.lastFinishedAt !== completion.lastFinishedAt)
|
||||
const ended = ids !== null && (previous?.ids?.some(id => !ids.includes(id)) ?? false)
|
||||
return {
|
||||
changed: completionChanged || ended,
|
||||
snapshot: {
|
||||
ids: ids ?? previous?.ids ?? null,
|
||||
completion: completion ?? previous?.completion,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function isListPageActionBlocked(availability: ListJobAvailability | undefined, jobType: ListJobType, unavailable: boolean) {
|
||||
if (unavailable) return true
|
||||
if (!availability) return false // availability 미배포(404)는 실제 접수 시 서버 판단에 맡긴다.
|
||||
|
||||
Reference in New Issue
Block a user