'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(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 }, }) }