summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/ship/send-to-shi-button.tsx
blob: 61893da53a6d248bc545d64ab70aed3c57f9cf8c (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// components/sync/send-to-shi-button.tsx (다중 계약 버전)
"use client"

import * as React from "react"
import { Send, Loader2, CheckCircle, AlertTriangle, Settings } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Separator } from "@/components/ui/separator"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useSyncStatus, useTriggerSync } from "@/hooks/use-sync-status"
import type { EnhancedDocument } from "@/types/enhanced-documents"

interface SendToSHIButtonProps {
  documents?: EnhancedDocument[]
  onSyncComplete?: () => void
  projectType: "ship" | "plant"
}

interface ContractSyncStatus {
  contractId: number
  syncStatus: any
  isLoading: boolean
  error: any
}

export function SendToSHIButton({ 
  documents = [], 
  onSyncComplete,
  projectType
}: SendToSHIButtonProps) {
  const [isDialogOpen, setIsDialogOpen] = React.useState(false)
  const [syncProgress, setSyncProgress] = React.useState(0)
  const [currentSyncingContract, setCurrentSyncingContract] = React.useState<number | null>(null)

  const targetSystem = projectType === 'ship' ? "DOLCE" : "SWP"
  
  // documents에서 contractId 목록 추출
  const documentsContractIds = React.useMemo(() => {
    const uniqueIds = [...new Set(documents.map(doc => doc.contractId).filter(Boolean))]
    return uniqueIds.sort()
  }, [documents])

  // 각 contract별 동기화 상태 조회
  const contractStatuses = React.useMemo(() => {
    return documentsContractIds.map(contractId => {
      const { 
        syncStatus, 
        isLoading, 
        error,
        refetch 
      } = useSyncStatus(contractId, targetSystem)
      
      return {
        contractId,
        syncStatus,
        isLoading,
        error,
        refetch
      }
    })
  }, [documentsContractIds, targetSystem])

  const { 
    triggerSync, 
    isLoading: isSyncing, 
    error: syncError 
  } = useTriggerSync()

  // 전체 통계 계산
  const totalStats = React.useMemo(() => {
    let totalPending = 0
    let totalSynced = 0
    let totalFailed = 0
    let hasError = false
    let isLoading = false

    contractStatuses.forEach(({ syncStatus, error, isLoading: loading }) => {
      if (error) hasError = true
      if (loading) isLoading = true
      if (syncStatus) {
        totalPending += syncStatus.pendingChanges || 0
        totalSynced += syncStatus.syncedChanges || 0
        totalFailed += syncStatus.failedChanges || 0
      }
    })

    return {
      totalPending,
      totalSynced,
      totalFailed,
      hasError,
      isLoading,
      canSync: totalPending > 0 && !hasError
    }
  }, [contractStatuses])

  // 에러 상태 표시
  React.useEffect(() => {
    if (totalStats.hasError) {
      console.warn('Failed to load sync status for some contracts')
    }
  }, [totalStats.hasError])

  const handleSync = async () => {
    if (documentsContractIds.length === 0) return
    
    setSyncProgress(0)
    let successfulSyncs = 0
    let failedSyncs = 0
    let totalSuccessCount = 0
    let totalFailureCount = 0
    const errors: string[] = []
    
    try {
      const contractsToSync = contractStatuses.filter(
        ({ syncStatus, error }) => !error && syncStatus?.syncEnabled && syncStatus?.pendingChanges > 0
      )

      if (contractsToSync.length === 0) {
        toast.info('동기화할 변경사항이 없습니다.')
        setIsDialogOpen(false)
        return
      }

      // 각 contract별로 순차 동기화
      for (let i = 0; i < contractsToSync.length; i++) {
        const { contractId } = contractsToSync[i]
        setCurrentSyncingContract(contractId)
        
        try {
          const result = await triggerSync({ 
            contractId, 
            targetSystem 
          })
          
          if (result?.success) {
            successfulSyncs++
            totalSuccessCount += result.successCount || 0
          } else {
            failedSyncs++
            totalFailureCount += result?.failureCount || 0
            if (result?.errors?.[0]) {
              errors.push(`Contract ${contractId}: ${result.errors[0]}`)
            }
          }
        } catch (error) {
          failedSyncs++
          const errorMessage = error instanceof Error ? error.message : '알 수 없는 오류'
          errors.push(`Contract ${contractId}: ${errorMessage}`)
        }

        // 진행률 업데이트
        setSyncProgress(((i + 1) / contractsToSync.length) * 100)
      }

      setCurrentSyncingContract(null)
      
      setTimeout(() => {
        setSyncProgress(0)
        setIsDialogOpen(false)
        
        if (failedSyncs === 0) {
          toast.success(
            `모든 계약 동기화 완료: ${totalSuccessCount}건 성공`,
            {
              description: `${successfulSyncs}개 계약에서 ${totalSuccessCount}개 항목이 SHI 시스템으로 전송되었습니다.`
            }
          )
        } else if (successfulSyncs > 0) {
          toast.warning(
            `부분 동기화 완료: ${successfulSyncs}개 성공, ${failedSyncs}개 실패`,
            {
              description: errors[0] || '일부 계약 동기화에 실패했습니다.'
            }
          )
        } else {
          toast.error(
            `동기화 실패: ${failedSyncs}개 계약 모두 실패`,
            {
              description: errors[0] || '모든 계약 동기화에 실패했습니다.'
            }
          )
        }
        
        // 모든 contract 상태 갱신
        contractStatuses.forEach(({ refetch }) => refetch?.())
        onSyncComplete?.()
      }, 500)
      
    } catch (error) {
      setSyncProgress(0)
      setCurrentSyncingContract(null)
      
      toast.error('동기화 실패', {
        description: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.'
      })
    }
  }

  const getSyncStatusBadge = () => {
    if (totalStats.isLoading) {
      return <Badge variant="secondary">확인 중...</Badge>
    }

    if (totalStats.hasError) {
      return <Badge variant="destructive">오류</Badge>
    }

    if (documentsContractIds.length === 0) {
      return <Badge variant="secondary">계약 없음</Badge>
    }

    if (totalStats.totalPending > 0) {
      return (
        <Badge variant="destructive" className="gap-1">
          <AlertTriangle className="w-3 h-3" />
          {totalStats.totalPending}건 대기
        </Badge>
      )
    }

    if (totalStats.totalSynced > 0) {
      return (
        <Badge variant="default" className="gap-1 bg-green-500 hover:bg-green-600">
          <CheckCircle className="w-3 h-3" />
          동기화됨
        </Badge>
      )
    }

    return <Badge variant="secondary">변경사항 없음</Badge>
  }

  const refreshAllStatuses = () => {
    contractStatuses.forEach(({ refetch }) => refetch?.())
  }

  return (
    <>
      <Popover>
        <PopoverTrigger asChild>
          <div className="flex items-center gap-3">
            <Button
              variant="default"
              size="sm"
              className="flex items-center bg-blue-600 hover:bg-blue-700"
              disabled={isSyncing || totalStats.isLoading || documentsContractIds.length === 0}
            >
              {isSyncing ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Send className="w-4 h-4" />
              )}
              <span className="hidden sm:inline">Send to SHI</span>
              {totalStats.totalPending > 0 && (
                <Badge 
                  variant="destructive" 
                  className="h-5 w-5 p-0 text-xs flex items-center justify-center"
                >
                  {totalStats.totalPending}
                </Badge>
              )}
            </Button>
          </div>
        </PopoverTrigger>
        
        <PopoverContent className="w-96">
          <div className="space-y-4">
            <div className="space-y-2">
              <h4 className="font-medium">SHI 동기화 상태</h4>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">전체 상태</span>
                {getSyncStatusBadge()}
              </div>
              <div className="text-xs text-muted-foreground">
                {documentsContractIds.length}개 계약 대상
              </div>
            </div>

            {!totalStats.hasError && documentsContractIds.length > 0 && (
              <div className="space-y-3">
                <Separator />
                
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <div className="text-muted-foreground">대기 중</div>
                    <div className="font-medium">{totalStats.totalPending}건</div>
                  </div>
                  <div>
                    <div className="text-muted-foreground">동기화됨</div>
                    <div className="font-medium">{totalStats.totalSynced}건</div>
                  </div>
                  <div>
                    <div className="text-muted-foreground">실패</div>
                    <div className="font-medium text-red-600">{totalStats.totalFailed}건</div>
                  </div>
                </div>

                {/* 계약별 상세 상태 */}
                {contractStatuses.length > 1 && (
                  <div className="space-y-2">
                    <div className="text-sm font-medium">계약별 상태</div>
                    <ScrollArea className="h-32">
                      <div className="space-y-2">
                        {contractStatuses.map(({ contractId, syncStatus, isLoading, error }) => (
                          <div key={contractId} className="flex items-center justify-between text-xs p-2 rounded border">
                            <span>Contract {contractId}</span>
                            {isLoading ? (
                              <Badge variant="secondary" className="text-xs">로딩...</Badge>
                            ) : error ? (
                              <Badge variant="destructive" className="text-xs">오류</Badge>
                            ) : syncStatus?.pendingChanges > 0 ? (
                              <Badge variant="destructive" className="text-xs">
                                {syncStatus.pendingChanges}건 대기
                              </Badge>
                            ) : (
                              <Badge variant="secondary" className="text-xs">동기화됨</Badge>
                            )}
                          </div>
                        ))}
                      </div>
                    </ScrollArea>
                  </div>
                )}
              </div>
            )}

            {totalStats.hasError && (
              <div className="space-y-2">
                <Separator />
                <div className="text-sm text-red-600">
                  <div className="font-medium">연결 오류</div>
                  <div className="text-xs">일부 계약의 동기화 상태를 확인할 수 없습니다.</div>
                </div>
              </div>
            )}

            {documentsContractIds.length === 0 && (
              <div className="space-y-2">
                <Separator />
                <div className="text-sm text-muted-foreground">
                  <div className="font-medium">계약 정보 없음</div>
                  <div className="text-xs">동기화할 문서가 없습니다.</div>
                </div>
              </div>
            )}

            <Separator />

            <div className="flex gap-2">
              <Button
                onClick={() => setIsDialogOpen(true)}
                disabled={!totalStats.canSync || isSyncing}
                className="flex-1"
                size="sm"
              >
                {isSyncing ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    동기화 중...
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4 mr-2" />
                    지금 동기화
                  </>
                )}
              </Button>
              
              <Button
                variant="outline"
                size="sm"
                onClick={refreshAllStatuses}
                disabled={totalStats.isLoading}
              >
                {totalStats.isLoading ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Settings className="w-4 h-4" />
                )}
              </Button>
            </div>
          </div>
        </PopoverContent>
      </Popover>

      {/* 동기화 진행 다이얼로그 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>SHI 시스템으로 동기화</DialogTitle>
            <DialogDescription>
              {documentsContractIds.length}개 계약의 변경된 문서 데이터를 SHI 시스템으로 전송합니다.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {!totalStats.hasError && documentsContractIds.length > 0 && (
              <div className="rounded-lg border p-4 space-y-3">
                <div className="flex items-center justify-between text-sm">
                  <span>전송 대상</span>
                  <span className="font-medium">{totalStats.totalPending}건</span>
                </div>
                
                <div className="flex items-center justify-between text-sm">
                  <span>대상 계약</span>
                  <span className="font-medium">{documentsContractIds.length}개</span>
                </div>
                
                <div className="text-xs text-muted-foreground">
                  문서, 리비전, 첨부파일의 변경사항이 포함됩니다.
                </div>

                {isSyncing && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span>진행률</span>
                      <span>{Math.round(syncProgress)}%</span>
                    </div>
                    <Progress value={syncProgress} className="h-2" />
                    {currentSyncingContract && (
                      <div className="text-xs text-muted-foreground">
                        현재 처리 중: Contract {currentSyncingContract}
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}

            {totalStats.hasError && (
              <div className="rounded-lg border border-red-200 p-4">
                <div className="text-sm text-red-600">
                  일부 계약의 동기화 상태를 확인할 수 없습니다. 네트워크 연결을 확인해주세요.
                </div>
              </div>
            )}

            {documentsContractIds.length === 0 && (
              <div className="rounded-lg border border-yellow-200 p-4">
                <div className="text-sm text-yellow-700">
                  동기화할 계약이 없습니다. 문서를 선택해주세요.
                </div>
              </div>
            )}

            <div className="flex justify-end gap-2">
              <Button
                variant="outline"
                onClick={() => setIsDialogOpen(false)}
                disabled={isSyncing}
              >
                취소
              </Button>
              <Button
                onClick={handleSync}
                disabled={isSyncing || !totalStats.canSync}
              >
                {isSyncing ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    동기화 중...
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4 mr-2" />
                    동기화 시작
                  </>
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}