summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/ship/import-from-dolce-button.tsx
blob: d4728d22c96fa81169bd4e92798fbdb53c475d0b (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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
"use client"

import * as React from "react"
import { RefreshCw, Download, Loader2, CheckCircle, AlertTriangle } 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 { SimplifiedDocumentsView } from "@/db/schema"
import { ImportStatus } from "../import-service"
import { useSession } from "next-auth/react"
import { getContractIdsByVendor } from "../service" // 서버 액션 import

interface ImportFromDOLCEButtonProps {
  allDocuments: SimplifiedDocumentsView[] // contractId 대신 문서 배열
  onImportComplete?: () => void
}

export function ImportFromDOLCEButton({ 
  allDocuments, 
  onImportComplete 
}: ImportFromDOLCEButtonProps) {
  const [isDialogOpen, setIsDialogOpen] = React.useState(false)
  const [importProgress, setImportProgress] = React.useState(0)
  const [isImporting, setIsImporting] = React.useState(false)
  const [importStatusMap, setImportStatusMap] = React.useState<Map<number, ImportStatus>>(new Map())
  const [statusLoading, setStatusLoading] = React.useState(false)
  const [vendorContractIds, setVendorContractIds] = React.useState<number[]>([]) // 서버에서 가져온 contractIds
  const [loadingVendorContracts, setLoadingVendorContracts] = React.useState(false)
  const { data: session } = useSession()

  const vendorId = session?.user.companyId;

  // allDocuments에서 추출한 contractIds
  const documentsContractIds = React.useMemo(() => {
    const uniqueIds = [...new Set(allDocuments.map(doc => doc.contractId).filter(Boolean))]
    return uniqueIds.sort()
  }, [allDocuments])

  // 최종 사용할 contractIds (allDocuments가 있으면 문서에서, 없으면 vendor의 모든 contracts)
  const contractIds = React.useMemo(() => {
    if (documentsContractIds.length > 0) {
      return documentsContractIds
    }
    return vendorContractIds
  }, [documentsContractIds, vendorContractIds])

  console.log(contractIds, "contractIds")

  // vendorId로 contracts 가져오기
  React.useEffect(() => {
    const fetchVendorContracts = async () => {
      // allDocuments가 비어있고 vendorId가 있을 때만 실행
      if (allDocuments.length === 0 && vendorId) {
        setLoadingVendorContracts(true)
        try {
          const contractIds = await getContractIdsByVendor(vendorId)
          setVendorContractIds(contractIds)
        } catch (error) {
          console.error('Failed to fetch vendor contracts:', error)
          toast.error('계약 정보를 가져오는데 실패했습니다.')
        } finally {
          setLoadingVendorContracts(false)
        }
      }
    }

    fetchVendorContracts()
  }, [allDocuments.length, vendorId])

  // 주요 contractId (가장 많이 나타나는 것)
  const primaryContractId = React.useMemo(() => {
    if (contractIds.length === 1) return contractIds[0]
    
    if (allDocuments.length > 0) {
      const counts = allDocuments.reduce((acc, doc) => {
        const id = doc.contractId || 0
        acc[id] = (acc[id] || 0) + 1
        return acc
      }, {} as Record<number, number>)
      
      return Number(Object.entries(counts)
        .sort(([,a], [,b]) => b - a)[0]?.[0] || contractIds[0] || 0)
    }
    
    return contractIds[0] || 0
  }, [contractIds, allDocuments])

  // 모든 contractId에 대한 상태 조회
  const fetchAllImportStatus = async () => {
    if (contractIds.length === 0) return
    
    setStatusLoading(true)
    const statusMap = new Map<number, ImportStatus>()
    
    try {
      // 각 contractId별로 상태 조회
      const statusPromises = contractIds.map(async (contractId) => {
        try {
          const response = await fetch(`/api/sync/import/status?contractId=${contractId}&sourceSystem=DOLCE`)
          if (!response.ok) {
            const errorData = await response.json().catch(() => ({}))
            throw new Error(errorData.message || 'Failed to fetch import status')
          }
          
          const status = await response.json()
          if (status.error) {
            console.warn(`Status error for contract ${contractId}:`, status.error)
            return { contractId, status: null }
          }
          
          return { contractId, status }
        } catch (error) {
          console.error(`Failed to fetch status for contract ${contractId}:`, error)
          return { contractId, status: null }
        }
      })

      const results = await Promise.all(statusPromises)
      
      results.forEach(({ contractId, status }) => {
        if (status) {
          statusMap.set(contractId, status)
        }
      })
      
      setImportStatusMap(statusMap)
      
    } catch (error) {
      console.error('Failed to fetch import statuses:', error)
      toast.error('상태를 확인할 수 없습니다. 프로젝트 설정을 확인해주세요.')
    } finally {
      setStatusLoading(false)
    }
  }

  // 컴포넌트 마운트 시 상태 조회
  React.useEffect(() => {
    if (contractIds.length > 0) {
      fetchAllImportStatus()
    }
  }, [contractIds])

  // 주요 contractId의 상태
  const primaryImportStatus = importStatusMap.get(primaryContractId)

  // 전체 통계 계산
  const totalStats = React.useMemo(() => {
    const statuses = Array.from(importStatusMap.values())
    return statuses.reduce((acc, status) => ({
      availableDocuments: acc.availableDocuments + (status.availableDocuments || 0),
      newDocuments: acc.newDocuments + (status.newDocuments || 0),
      updatedDocuments: acc.updatedDocuments + (status.updatedDocuments || 0),
      importEnabled: acc.importEnabled || status.importEnabled
    }), {
      availableDocuments: 0,
      newDocuments: 0,
      updatedDocuments: 0,
      importEnabled: false
    })
  }, [importStatusMap])

  const handleImport = async () => {
    if (contractIds.length === 0) return
    
    setImportProgress(0)
    setIsImporting(true)
    
    try {
      // 진행률 시뮬레이션
      const progressInterval = setInterval(() => {
        setImportProgress(prev => Math.min(prev + 10, 85))
      }, 500)

      // 여러 contractId에 대해 순차적으로 가져오기 실행
      const importPromises = contractIds.map(async (contractId) => {
        const response = await fetch('/api/sync/import', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ 
            contractId, 
            sourceSystem: 'DOLCE' 
          })
        })

        if (!response.ok) {
          const errorData = await response.json()
          throw new Error(`Contract ${contractId}: ${errorData.message || 'Import failed'}`)
        }

        return response.json()
      })

      const results = await Promise.all(importPromises)
      
      clearInterval(progressInterval)
      setImportProgress(100)
      
      // 결과 집계
      const totalResult = results.reduce((acc, result) => ({
        newCount: acc.newCount + (result.newCount || 0),
        updatedCount: acc.updatedCount + (result.updatedCount || 0),
        skippedCount: acc.skippedCount + (result.skippedCount || 0),
        success: acc.success && result.success
      }), {
        newCount: 0,
        updatedCount: 0,
        skippedCount: 0,
        success: true
      })
      
      setTimeout(() => {
        setImportProgress(0)
        setIsDialogOpen(false)
        setIsImporting(false)
        
        if (totalResult.success) {
          toast.success(
            `DOLCE 가져오기 완료`,
            {
              description: `신규 ${totalResult.newCount}건, 업데이트 ${totalResult.updatedCount}건, 건너뜀 ${totalResult.skippedCount}건 (${contractIds.length}개 계약)`
            }
          )
        } else {
          toast.error(
            `DOLCE 가져오기 부분 실패`,
            {
              description: '일부 계약에서 가져오기에 실패했습니다.'
            }
          )
        }
        
        fetchAllImportStatus() // 상태 갱신
        onImportComplete?.()
      }, 500)
      
    } catch (error) {
      setImportProgress(0)
      setIsImporting(false)
      
      toast.error('DOLCE 가져오기 실패', {
        description: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.'
      })
    }
  }

  const getStatusBadge = () => {
    if (loadingVendorContracts) {
      return <Badge variant="secondary">계약 정보 로딩 중...</Badge>
    }

    if (statusLoading) {
      return <Badge variant="secondary">DOLCE 연결 확인 중...</Badge>
    }

    if (importStatusMap.size === 0) {
      return <Badge variant="destructive">DOLCE 연결 오류</Badge>
    }

    if (!totalStats.importEnabled) {
      return <Badge variant="secondary">DOLCE 가져오기 비활성화</Badge>
    }

    if (totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0) {
      return (
        <Badge variant="samsung" className="gap-1">
          <AlertTriangle className="w-3 h-3" />
          업데이트 가능 ({contractIds.length}개 계약)
        </Badge>
      )
    }

    return (
      <Badge variant="default" className="gap-1 bg-green-500 hover:bg-green-600">
        <CheckCircle className="w-3 h-3" />
        DOLCE와 동기화됨
      </Badge>
    )
  }

  const canImport = totalStats.importEnabled && 
    (totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0)

  // 로딩 중이거나 contractIds가 없으면 버튼을 표시하지 않음
  if (loadingVendorContracts || contractIds.length === 0) {
    return null 
  }

  return (
    <>
      <Popover>
        <PopoverTrigger asChild>
          <div className="flex items-center gap-3">
            <Button
              variant="outline"
              size="sm"
              className="flex items-center border-blue-200 hover:bg-blue-50"
              disabled={isImporting || statusLoading}
            >
              {isImporting ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Download className="w-4 h-4" />
              )}
              <span className="hidden sm:inline">DOLCE에서 가져오기</span>
              {totalStats.newDocuments + totalStats.updatedDocuments > 0 && (
                <Badge 
                  variant="samsung" 
                  className="h-5 w-5 p-0 text-xs flex items-center justify-center"
                >
                  {totalStats.newDocuments + totalStats.updatedDocuments}
                </Badge>
              )}
            </Button>
          </div>
        </PopoverTrigger>
        
        <PopoverContent className="w-96">
          <div className="space-y-4">
            <div className="space-y-2">
              <h4 className="font-medium">DOLCE 가져오기 상태</h4>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">현재 상태</span>
                {getStatusBadge()}
              </div>
            </div>

            {/* 계약 소스 표시 */}
            {allDocuments.length === 0 && vendorContractIds.length > 0 && (
              <div className="text-xs text-blue-600 bg-blue-50 p-2 rounded">
                문서가 없어서 전체 계약에서 가져오기를 진행합니다.
              </div>
            )}

            {/* 다중 계약 정보 표시 */}
            {contractIds.length > 1 && (
              <div className="text-sm">
                <div className="text-muted-foreground">대상 계약</div>
                <div className="font-medium">{contractIds.length}개 계약</div>
                <div className="text-xs text-muted-foreground">
                  Contract IDs: {contractIds.join(', ')}
                </div>
              </div>
            )}

            {totalStats && (
              <div className="space-y-3">
                <Separator />
                
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <div className="text-muted-foreground">신규 문서</div>
                    <div className="font-medium">{totalStats.newDocuments || 0}건</div>
                  </div>
                  <div>
                    <div className="text-muted-foreground">업데이트</div>
                    <div className="font-medium">{totalStats.updatedDocuments || 0}건</div>
                  </div>
                </div>

                <div className="text-sm">
                  <div className="text-muted-foreground">DOLCE 전체 문서 (B3/B4/B5)</div>
                  <div className="font-medium">{totalStats.availableDocuments || 0}건</div>
                </div>

                {/* 각 계약별 세부 정보 (펼치기/접기 가능) */}
                {contractIds.length > 1 && (
                  <details className="text-sm">
                    <summary className="cursor-pointer text-muted-foreground hover:text-foreground">
                      계약별 세부 정보
                    </summary>
                    <div className="mt-2 space-y-2 pl-2 border-l-2 border-muted">
                      {contractIds.map(contractId => {
                        const status = importStatusMap.get(contractId)
                        return (
                          <div key={contractId} className="text-xs">
                            <div className="font-medium">Contract {contractId}</div>
                            {status ? (
                              <div className="text-muted-foreground">
                                신규 {status.newDocuments}건, 업데이트 {status.updatedDocuments}건
                              </div>
                            ) : (
                              <div className="text-destructive">상태 확인 실패</div>
                            )}
                          </div>
                        )
                      })}
                    </div>
                  </details>
                )}
              </div>
            )}

            <Separator />

            <div className="flex gap-2">
              <Button
                onClick={() => setIsDialogOpen(true)}
                disabled={!canImport || isImporting}
                className="flex-1"
                size="sm"
              >
                {isImporting ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    가져오는 중...
                  </>
                ) : (
                  <>
                    <Download className="w-4 h-4 mr-2" />
                    지금 가져오기
                  </>
                )}
              </Button>
              
              <Button
                variant="outline"
                size="sm"
                onClick={fetchAllImportStatus}
                disabled={statusLoading}
              >
                {statusLoading ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <RefreshCw className="w-4 h-4" />
                )}
              </Button>
            </div>
          </div>
        </PopoverContent>
      </Popover>

      {/* 가져오기 진행 다이얼로그 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>DOLCE에서 문서 목록 가져오기</DialogTitle>
            <DialogDescription>
              삼성중공업 DOLCE 시스템에서 최신 문서 목록을 가져옵니다.
              {contractIds.length > 1 && ` (${contractIds.length}개 계약 대상)`}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {totalStats && (
              <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.newDocuments + totalStats.updatedDocuments}건
                  </span>
                </div>
                
                <div className="text-xs text-muted-foreground">
                  신규 문서와 업데이트된 문서가 포함됩니다. (B3, B4, B5)
                  <br />
                  B4 문서의 경우 GTTPreDwg, GTTWorkingDwg 이슈 스테이지가 자동 생성됩니다.
                  {contractIds.length > 1 && (
                    <>
                      <br />
                      {contractIds.length}개 계약에서 순차적으로 가져옵니다.
                    </>
                  )}
                </div>

                {isImporting && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span>진행률</span>
                      <span>{importProgress}%</span>
                    </div>
                    <Progress value={importProgress} className="h-2" />
                  </div>
                )}
              </div>
            )}

            <div className="flex justify-end gap-2">
              <Button
                variant="outline"
                onClick={() => setIsDialogOpen(false)}
                disabled={isImporting}
              >
                취소
              </Button>
              <Button
                onClick={handleImport}
                disabled={isImporting || !canImport}
              >
                {isImporting ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    가져오는 중...
                  </>
                ) : (
                  <>
                    <Download className="w-4 h-4 mr-2" />
                    가져오기 시작
                  </>
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}