summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/ship/send-to-shi-button.tsx
blob: 7bb857108273ca096c65c4f1136b64324db48127 (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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
// components/sync/send-to-shi-button.tsx (최종 완성 버전)
"use client"

import * as React from "react"
import { Send, Loader2, CheckCircle, AlertTriangle, Settings, RefreshCw } 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 { Alert, AlertDescription } from "@/components/ui/alert"
// ✅ 업데이트된 Hook import
import { useClientSyncStatus, useTriggerSync, syncUtils } from "@/hooks/use-sync-status"
import type { EnhancedDocument } from "@/types/enhanced-documents"
import { useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"
import { useSession } from "next-auth/react"

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

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 { data: session } = useSession();

  const params = useParams()
  const lng = (params?.lng as string) || "ko"
  const { t } = useTranslation(lng, "engineering")

  const targetSystem = projectType === 'ship' ? "DOLCE" : "SWP"

  // 문서에서 유효한 계약 ID 목록 추출 (projectId 사용)
  const documentsContractIds = React.useMemo(() => {
    const validIds = documents
      .map(doc => (doc as any).projectId)
      .filter((id): id is number => typeof id === 'number' && id > 0)

    const uniqueIds = [...new Set(validIds)]
    return uniqueIds.sort()
  }, [documents])

  const vendorId = session?.user.companyId

  // ✅ 클라이언트 전용 Hook 사용 (서버 사이드 렌더링 호환)
  const { contractStatuses, totalStats, refetchAll } = useClientSyncStatus(
    documentsContractIds,
    targetSystem
  )

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


  // 동기화 실행 함수
  const handleSync = async () => {
    if (documentsContractIds.length === 0) {
      toast.info(t('shiSync.messages.noContractsToSync'))
      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 }) => {
        if (error) {
          console.warn(`Contract ${contractStatuses.find(c => c.error === error)?.projectId} has error:`, error)
          return false
        }
        if (!syncStatus) return false
        if (!syncStatus.syncEnabled) return false
        if (syncStatus.pendingChanges <= 0) return false
        return true
      })

      if (contractsToSync.length === 0) {
        toast.info(t('shiSync.messages.noPendingChanges'))
        setIsDialogOpen(false)
        return
      }

      console.log(`Starting sync for ${contractsToSync.length} contracts`)

      // 각 contract별로 순차 동기화
      for (let i = 0; i < contractsToSync.length; i++) {
        const { projectId } = contractsToSync[i]
        setCurrentSyncingContract(projectId)

        try {
          console.log(`Syncing contract ${projectId}...`)
          const result = await triggerSync({
            projectId,
            targetSystem
          })

          if (result?.success) {
            successfulSyncs++
            totalSuccessCount += result.successCount || 0
            console.log(`Contract ${projectId} sync successful:`, result)
          } else {
            failedSyncs++
            totalFailureCount += result?.failureCount || 0
            const errorMsg = result?.errors?.[0] || result?.message || 'Unknown sync error'
            errors.push(t('shiSync.messages.contractError', { projectId, error: errorMsg }))
            console.error(`Contract ${projectId} sync failed:`, result)
          }
        } catch (error) {
          failedSyncs++
          const errorMessage = error instanceof Error ? error.message : t('shiSync.messages.unknownError')
          errors.push(t('shiSync.messages.contractError', { projectId, error: errorMessage }))
          console.error(`Contract ${projectId} sync exception:`, error)
        }

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

      setCurrentSyncingContract(null)

      // 결과 처리 및 토스트 표시
      setTimeout(() => {
        setSyncProgress(0)
        setIsDialogOpen(false)

        if (failedSyncs === 0) {
          toast.success(
            t('shiSync.messages.allSyncCompleted', { successCount: totalSuccessCount }),
            {
              description: t('shiSync.messages.allSyncCompletedDescription', {
                contractCount: successfulSyncs,
                itemCount: totalSuccessCount
              })
            }
          )
        } else if (successfulSyncs > 0) {
          toast.warning(
            t('shiSync.messages.partialSyncCompleted', {
              successfulCount: successfulSyncs,
              failedCount: failedSyncs
            }),
            {
              description: errors.slice(0, 3).join(', ') +
                (errors.length > 3 ? t('shiSync.messages.andMore') : '')
            }
          )
        } else {
          toast.error(
            t('shiSync.messages.allSyncFailed', { failedCount: failedSyncs }),
            {
              description: errors[0] || t('shiSync.messages.allContractsSyncFailed')
            }
          )
        }

        // 모든 contract 상태 갱신
        refetchAll()
        onSyncComplete?.()
      }, 500)

    } catch (error) {
      setSyncProgress(0)
      setCurrentSyncingContract(null)

      const errorMessage = syncUtils.formatError(error as Error)
      toast.error(t('shiSync.messages.syncFailed'), {
        description: errorMessage
      })
      console.error('Sync process failed:', error)
    }
  }

  // 동기화 상태에 따른 뱃지 생성
  const getSyncStatusBadge = () => {
    if (totalStats.isLoading) {
      return (
        <Badge variant="secondary" className="gap-1">
          <Loader2 className="w-3 h-3 animate-spin" />
          {t('shiSync.status.checking')}
        </Badge>
      )
    }

    if (totalStats.hasError) {
      return (
        <Badge variant="destructive" className="gap-1">
          <AlertTriangle className="w-3 h-3" />
          {t('shiSync.status.connectionError')}
        </Badge>
      )
    }

    if (documentsContractIds.length === 0) {
      return <Badge variant="secondary">{t('shiSync.status.noContracts')}</Badge>
    }

    if (totalStats.totalPending > 0) {
      return (
        <Badge variant="destructive" className="gap-1">
          <AlertTriangle className="w-3 h-3" />
          {t('shiSync.status.pendingItems', { count: totalStats.totalPending })}
        </Badge>
      )
    }

    if (totalStats.totalSynced > 0) {
      return (
        <Badge variant="default" className="gap-1 bg-emerald-500 hover:bg-emerald-600 dark:bg-emerald-600 dark:hover:bg-emerald-700">
          <CheckCircle className="w-3 h-3" />
          {t('shiSync.status.synchronized')}
        </Badge>
      )
    }

    return <Badge variant="secondary">{t('shiSync.status.noChanges')}</Badge>
  }

  return (
    <>
      <Popover>
        <PopoverTrigger asChild>
          <div className="flex items-center gap-3">
            <Button
              variant="default"
              size="sm"
              className="flex items-center gap-2 bg-primary hover:bg-primary/90"
              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">{t('shiSync.buttons.sendToSHI')}</span>
              {totalStats.totalPending > 0 && (
                <Badge
                  variant="destructive"
                  className="h-5 w-5 p-0 text-xs flex items-center justify-center ml-1"
                >
                  {totalStats.totalPending}
                </Badge>
              )}
            </Button>
          </div>
        </PopoverTrigger>

        <PopoverContent className="w-96" align="end">
          <div className="space-y-4">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <h4 className="font-medium">{t('shiSync.labels.syncStatus')}</h4>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={refetchAll}
                  disabled={totalStats.isLoading}
                  className="h-6 w-6 p-0"
                >
                  {totalStats.isLoading ? (
                    <Loader2 className="w-3 h-3 animate-spin" />
                  ) : (
                    <RefreshCw className="w-3 h-3" />
                  )}
                </Button>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('shiSync.labels.overallStatus')}</span>
                {getSyncStatusBadge()}
              </div>

              <div className="text-xs text-muted-foreground">
                {t('shiSync.descriptions.targetInfo', {
                  contractCount: documentsContractIds.length,
                  targetSystem
                })}
              </div>
            </div>

            {/* 에러 상태 표시 */}
            {totalStats.hasError && (
              <Alert variant="destructive">
                <AlertTriangle className="h-4 w-4" />
                <AlertDescription>
                  {t('shiSync.descriptions.statusCheckError')}
                  {process.env.NODE_ENV === 'development' && (
                    <div className="text-xs mt-1 font-mono">
                      Debug: {t('shiSync.descriptions.contractsWithError', {
                        count: contractStatuses.filter(({ error }) => error).length
                      })}
                    </div>
                  )}
                </AlertDescription>
              </Alert>
            )}

            {/* 정상 상태일 때 통계 표시 */}
            {!totalStats.hasError && documentsContractIds.length > 0 && (
              <div className="space-y-3">
                <Separator />

                {/* 전체 통계 */}
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div className="text-center">
                    <div className="text-muted-foreground">{t('shiSync.labels.pending')}</div>
                    <div className="font-medium text-orange-600">
                      {t('shiSync.labels.itemCount', { count: totalStats.totalPending })}
                    </div>
                  </div>
                  <div className="text-center">
                    <div className="text-muted-foreground">{t('shiSync.labels.synced')}</div>
                    <div className="font-medium text-emerald-600 dark:text-emerald-400">
                      {t('shiSync.labels.itemCount', { count: totalStats.totalSynced })}
                    </div>
                  </div>
                  <div className="text-center">
                    <div className="text-muted-foreground">{t('shiSync.labels.failed')}</div>
                    <div className="font-medium text-destructive">
                      {t('shiSync.labels.itemCount', { count: totalStats.totalFailed })}
                    </div>
                  </div>
                </div>

                {/* EntityType별 상세 통계 추가 */}
                {totalStats.entityTypeDetailsTotals && (
                  <>
                    <Separator className="my-2" />
                    <div className="space-y-2">
                      <div className="text-sm font-medium flex items-center gap-2">
                        {t('shiSync.labels.detailsByType')}
                        <Badge variant="outline" className="text-xs">
                          {t('shiSync.labels.experimental')}
                        </Badge>
                      </div>

                      <div className="space-y-1 text-xs">
                        {/* Document 통계 */}
                        {totalStats.entityTypeDetailsTotals.document && (
                          <div className="flex items-center justify-between p-2 rounded bg-muted/50">
                            <span className="font-medium">
                              {t('shiSync.labels.documents')}
                            </span>
                            <div className="flex gap-3 text-xs">
                              {totalStats.entityTypeDetailsTotals.document.pending > 0 && (
                                <span className="text-orange-600">
                                  {totalStats.entityTypeDetailsTotals.document.pending} {t('shiSync.labels.pendingShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.document.synced > 0 && (
                                <span className="text-emerald-600">
                                  {totalStats.entityTypeDetailsTotals.document.synced} {t('shiSync.labels.syncedShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.document.failed > 0 && (
                                <span className="text-destructive">
                                  {totalStats.entityTypeDetailsTotals.document.failed} {t('shiSync.labels.failedShort')}
                                </span>
                              )}
                            </div>
                          </div>
                        )}

                        {/* Revision 통계 */}
                        {totalStats.entityTypeDetailsTotals.revision && (
                          <div className="flex items-center justify-between p-2 rounded bg-muted/50">
                            <span className="font-medium">
                              {t('shiSync.labels.revisions')}
                            </span>
                            <div className="flex gap-3 text-xs">
                              {totalStats.entityTypeDetailsTotals.revision.pending > 0 && (
                                <span className="text-orange-600">
                                  {totalStats.entityTypeDetailsTotals.revision.pending} {t('shiSync.labels.pendingShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.revision.synced > 0 && (
                                <span className="text-emerald-600">
                                  {totalStats.entityTypeDetailsTotals.revision.synced} {t('shiSync.labels.syncedShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.revision.failed > 0 && (
                                <span className="text-destructive">
                                  {totalStats.entityTypeDetailsTotals.revision.failed} {t('shiSync.labels.failedShort')}
                                </span>
                              )}
                            </div>
                          </div>
                        )}

                        {/* Attachment 통계 */}
                        {totalStats.entityTypeDetailsTotals.attachment && (
                          <div className="flex items-center justify-between p-2 rounded bg-muted/50">
                            <span className="font-medium">
                              {t('shiSync.labels.attachments')}
                            </span>
                            <div className="flex gap-3 text-xs">
                              {totalStats.entityTypeDetailsTotals.attachment.pending > 0 && (
                                <span className="text-orange-600">
                                  {totalStats.entityTypeDetailsTotals.attachment.pending} {t('shiSync.labels.pendingShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.attachment.synced > 0 && (
                                <span className="text-emerald-600">
                                  {totalStats.entityTypeDetailsTotals.attachment.synced} {t('shiSync.labels.syncedShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.attachment.failed > 0 && (
                                <span className="text-destructive">
                                  {totalStats.entityTypeDetailsTotals.attachment.failed} {t('shiSync.labels.failedShort')}
                                </span>
                              )}
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </>
                )}

                {/* 계약별 상세 상태 */}
                {contractStatuses.length > 1 && (
                  <div className="space-y-2">
                    <div className="text-sm font-medium">{t('shiSync.labels.statusByContract')}</div>
                    <ScrollArea className="h-32">
                      <div className="space-y-2">
                        {contractStatuses.map(({ projectId, syncStatus, isLoading, error }) => (
                          <div key={projectId} className="flex items-center justify-between text-xs p-2 rounded border">
                            <span className="font-medium">{t('shiSync.labels.contractLabel', { projectId })}</span>
                            {isLoading ? (
                              <Badge variant="secondary" className="text-xs">
                                <Loader2 className="w-3 h-3 mr-1 animate-spin" />
                                {t('shiSync.status.loading')}
                              </Badge>
                            ) : error ? (
                              <Badge variant="destructive" className="text-xs">
                                <AlertTriangle className="w-3 h-3 mr-1" />
                                {t('shiSync.status.error')}
                              </Badge>
                            ) : syncStatus && syncStatus.pendingChanges > 0 ? (
                              <Badge variant="destructive" className="text-xs">
                                {t('shiSync.status.pendingCount', { count: syncStatus.pendingChanges })}
                              </Badge>
                            ) : (
                              <Badge variant="secondary" className="text-xs">
                                <CheckCircle className="w-3 h-3 mr-1" />
                                {t('shiSync.status.upToDate')}
                              </Badge>
                            )}
                          </div>
                        ))}
                      </div>
                    </ScrollArea>
                  </div>
                )}
              </div>
            )}

            {/* 계약 정보가 없는 경우 */}
            {documentsContractIds.length === 0 && (
              <Alert>
                <AlertDescription>
                  {t('shiSync.descriptions.noDocumentsToSync')}
                </AlertDescription>
              </Alert>
            )}

            <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" />
                    {t('shiSync.buttons.syncing')}
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4 mr-2" />
                    {t('shiSync.buttons.syncNow')}
                  </>
                )}
              </Button>

              <Button
                variant="outline"
                size="sm"
                onClick={refetchAll}
                disabled={totalStats.isLoading}
                className="px-3"
              >
                {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 className="flex items-center gap-2">
              <Send className="w-5 h-5" />
              {t('shiSync.dialog.title')}
            </DialogTitle>
            <DialogDescription>
              {t('shiSync.dialog.description', {
                contractCount: documentsContractIds.length,
                targetSystem
              })}
            </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>{t('shiSync.labels.syncTarget')}</span>
                  <span className="font-medium">{t('shiSync.labels.itemCount', { count: totalStats.totalPending })}</span>
                </div>

                <div className="flex items-center justify-between text-sm">
                  <span>{t('shiSync.labels.targetContracts')}</span>
                  <span className="font-medium">{t('shiSync.labels.contractCount', { count: documentsContractIds.length })}</span>
                </div>

                <div className="text-xs text-muted-foreground">
                  {t('shiSync.descriptions.includesChanges')}
                </div>

                {isSyncing && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span>{t('shiSync.labels.progress')}</span>
                      <span>{Math.round(syncProgress)}%</span>
                    </div>
                    <Progress value={syncProgress} className="h-2" />
                    {currentSyncingContract && (
                      <div className="text-xs text-muted-foreground flex items-center gap-1">
                        <Loader2 className="w-3 h-3 animate-spin" />
                        {t('shiSync.descriptions.currentlyProcessing', { contractId: currentSyncingContract })}
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}

            {totalStats.hasError && (
              <Alert variant="destructive">
                <AlertTriangle className="h-4 w-4" />
                <AlertDescription>
                  {t('shiSync.descriptions.dialogStatusCheckError')}
                </AlertDescription>
              </Alert>
            )}

            {documentsContractIds.length === 0 && (
              <Alert>
                <AlertDescription>
                  {t('shiSync.descriptions.noContractsToSync')}
                </AlertDescription>
              </Alert>
            )}

            <div className="flex justify-end gap-2">
              <Button
                variant="outline"
                onClick={() => setIsDialogOpen(false)}
                disabled={isSyncing}
              >
                {t('buttons.cancel')}
              </Button>
              <Button
                onClick={handleSync}
                disabled={isSyncing || !totalStats.canSync}
              >
                {isSyncing ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    {t('shiSync.buttons.syncing')}
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4 mr-2" />
                    {t('shiSync.buttons.startSync')}
                  </>
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}