blob: 211624910bdb2b1ba93eb0417b4f204bca7eeac7 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
// app/hooks/use-document-polling.ts
"use client"
import { pullDocumentStatusFromSHI } from "@/lib/vendor-document-list/plant/document-stages-service"
import { useEffect, useState } from "react"
import { toast } from "sonner"
interface UseDocumentPollingProps {
contractId: number
autoStart?: boolean
onUpdate?: () => void
}
export function useDocumentPolling({
contractId,
autoStart = true,
onUpdate
}: UseDocumentPollingProps) {
const [isPolling, setIsPolling] = useState(false)
const [lastPolledAt, setLastPolledAt] = useState<Date | null>(null)
const [pollingStatus, setPollingStatus] = useState<'idle' | 'polling' | 'success' | 'error'>('idle')
// 폴링 함수
const pollDocuments = async (showToast = true) => {
setIsPolling(true)
setPollingStatus('polling')
try {
const result = await pullDocumentStatusFromSHI(contractId)
if (result.success) {
setPollingStatus('success')
setLastPolledAt(new Date())
if (showToast) {
if (result.updatedCount > 0) {
toast.success(result.message)
} else {
toast.info("모든 문서가 최신 상태입니다.")
}
}
// 업데이트 콜백 실행
if (result.updatedCount > 0 && onUpdate) {
onUpdate()
}
} else {
setPollingStatus('error')
if (showToast) {
toast.error(result.message)
}
}
} catch (error) {
setPollingStatus('error')
if (showToast) {
toast.error("동기화 중 오류가 발생했습니다.")
}
} finally {
setIsPolling(false)
}
}
// 페이지 로드 시 자동 폴링
useEffect(() => {
if (autoStart && contractId) {
pollDocuments(false) // 초기 로드 시에는 토스트 메시지 표시 안 함
}
}, [contractId])
return {
isPolling,
lastPolledAt,
pollingStatus,
pollDocuments
}
}
|