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