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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
|
// import-from-dolce-button.tsx - 최적화된 버전
"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 { getProjectIdsByVendor } from "../service"
import { useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"
// 🔥 API 응답 캐시 (컴포넌트 외부에 선언하여 인스턴스 간 공유)
const statusCache = new Map<string, { data: ImportStatus; timestamp: number }>()
const CACHE_TTL = 2 * 60 * 1000 // 2분 캐시
interface ImportFromDOLCEButtonProps {
allDocuments: SimplifiedDocumentsView[]
projectIds?: number[] // 🔥 미리 계산된 projectIds를 props로 받음
onImportComplete?: () => void
}
// 🔥 디바운스 훅
function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = React.useState(value)
React.useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(handler)
}
}, [value, delay])
return debouncedValue
}
export function ImportFromDOLCEButton({
allDocuments,
projectIds: propProjectIds,
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 [vendorProjectIds, setVendorProjectIds] = React.useState<number[]>([])
const [loadingVendorProjects, setLoadingVendorProjects] = React.useState(false)
const { data: session } = useSession()
const vendorId = session?.user.companyId
const params = useParams()
const lng = (params?.lng as string) || "ko"
const { t } = useTranslation(lng, "engineering")
// 🔥 allDocuments에서 projectIds 추출 (props로 전달받은 경우 사용)
const documentsProjectIds = React.useMemo(() => {
if (propProjectIds) return propProjectIds // props로 받은 경우 그대로 사용
const uniqueIds = [...new Set(allDocuments.map(doc => doc.projectId).filter(Boolean))]
return uniqueIds.sort()
}, [allDocuments, propProjectIds])
// 🔥 최종 projectIds (변경 빈도 최소화)
const projectIds = React.useMemo(() => {
if (documentsProjectIds.length > 0) {
return documentsProjectIds
}
return vendorProjectIds
}, [documentsProjectIds, vendorProjectIds])
// 🔥 projectIds 디바운싱 (API 호출 과다 방지)
const debouncedProjectIds = useDebounce(projectIds, 300)
// 🔥 주요 projectId 메모이제이션
const primaryProjectId = React.useMemo(() => {
if (projectIds.length === 1) return projectIds[0]
if (allDocuments.length > 0) {
const counts = allDocuments.reduce((acc, doc) => {
const id = doc.projectId || 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] || projectIds[0] || 0)
}
return projectIds[0] || 0
}, [projectIds, allDocuments])
// 🔥 캐시된 API 호출 함수
const fetchImportStatusCached = React.useCallback(async (projectId: number): Promise<ImportStatus | null> => {
const cacheKey = `import-status-${projectId}`
const cached = statusCache.get(cacheKey)
// 캐시된 데이터가 있고 유효하면 사용
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.data
}
try {
const response = await fetch(`/api/sync/import/status?projectId=${projectId}&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 project ${projectId}:`, status.error)
return null
}
// 캐시에 저장
statusCache.set(cacheKey, {
data: status,
timestamp: Date.now()
})
return status
} catch (error) {
console.error(`Failed to fetch status for project ${projectId}:`, error)
return null
}
}, [])
// 🔥 모든 projectId에 대한 상태 조회 (최적화된 버전)
const fetchAllImportStatus = React.useCallback(async () => {
if (debouncedProjectIds.length === 0) return
setStatusLoading(true)
const statusMap = new Map<number, ImportStatus>()
try {
// 🔥 병렬 처리하되 동시 연결 수 제한 (3개씩)
const batchSize = 3
const batches = []
for (let i = 0; i < debouncedProjectIds.length; i += batchSize) {
batches.push(debouncedProjectIds.slice(i, i + batchSize))
}
for (const batch of batches) {
const batchPromises = batch.map(async (projectId) => {
const status = await fetchImportStatusCached(projectId)
return { projectId, status }
})
const batchResults = await Promise.all(batchPromises)
batchResults.forEach(({ projectId, status }) => {
if (status) {
statusMap.set(projectId, status)
}
})
// 배치 간 짧은 지연
if (batches.length > 1) {
await new Promise(resolve => setTimeout(resolve, 100))
}
}
setImportStatusMap(statusMap)
} catch (error) {
console.error('Failed to fetch import statuses:', error)
toast.error(t('dolceImport.messages.statusCheckError'))
} finally {
setStatusLoading(false)
}
}, [debouncedProjectIds, fetchImportStatusCached, t])
// 🔥 vendorId로 projects 가져오기 (최적화)
React.useEffect(() => {
let isCancelled = false;
if (allDocuments.length !== 0 || !vendorId) return;
setLoadingVendorProjects(true);
getProjectIdsByVendor(vendorId)
.then((projectIds) => {
if (!isCancelled) setVendorProjectIds(projectIds);
})
.catch((error) => {
if (!isCancelled) toast.error(t('dolceImport.messages.projectFetchError'));
})
.finally(() => {
if (!isCancelled) setLoadingVendorProjects(false);
});
return () => { isCancelled = true; };
}, [allDocuments, vendorId, t]);
// 🔥 컴포넌트 마운트 시 상태 조회 (디바운싱 적용)
React.useEffect(() => {
if (debouncedProjectIds.length > 0) {
fetchAllImportStatus()
}
}, [debouncedProjectIds, fetchAllImportStatus])
// 🔥 전체 통계 메모이제이션
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 primaryImportStatus = React.useMemo(() => {
return importStatusMap.get(primaryProjectId)
}, [importStatusMap, primaryProjectId])
// 🔥 가져오기 실행 함수 최적화
const handleImport = React.useCallback(async () => {
if (projectIds.length === 0) return
setImportProgress(0)
setIsImporting(true)
try {
const progressInterval = setInterval(() => {
setImportProgress(prev => Math.min(prev + 10, 85))
}, 500)
// 🔥 순차 처리로 서버 부하 방지
const results = []
for (const projectId of projectIds) {
try {
const response = await fetch('/api/sync/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
projectId,
sourceSystem: 'DOLCE'
})
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(`Project ${projectId}: ${errorData.message || 'Import failed'}`)
}
const result = await response.json()
results.push(result)
// 프로젝트 간 짧은 지연
if (projectIds.length > 1) {
await new Promise(resolve => setTimeout(resolve, 200))
}
} catch (error) {
console.error(`Import failed for project ${projectId}:`, error)
results.push({ success: false, error: error instanceof Error ? error.message : 'Unknown error' })
}
}
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(
t('dolceImport.messages.importSuccess'),
{
description: t('dolceImport.messages.importSuccessDescription', {
newCount: totalResult.newCount,
updatedCount: totalResult.updatedCount,
skippedCount: totalResult.skippedCount,
projectCount: projectIds.length
})
}
)
} else {
toast.error(
t('dolceImport.messages.importPartiallyFailed'),
{
description: t('dolceImport.messages.importPartiallyFailedDescription')
}
)
}
// 🔥 캐시 무효화
statusCache.clear()
fetchAllImportStatus()
onImportComplete?.()
}, 500)
} catch (error) {
setImportProgress(0)
setIsImporting(false)
toast.error(t('dolceImport.messages.importFailed'), {
description: error instanceof Error ? error.message : t('dolceImport.messages.unknownError')
})
}
}, [projectIds, fetchAllImportStatus, onImportComplete, t])
// 🔥 상태 뱃지 메모이제이션
const statusBadge = React.useMemo(() => {
if (loadingVendorProjects) {
return <Badge variant="secondary">{t('dolceImport.status.loadingProjectInfo')}</Badge>
}
if (statusLoading) {
return <Badge variant="secondary">{t('dolceImport.status.checkingConnection')}</Badge>
}
if (importStatusMap.size === 0) {
return <Badge variant="destructive">{t('dolceImport.status.connectionError')}</Badge>
}
if (!totalStats.importEnabled) {
return <Badge variant="secondary">{t('dolceImport.status.importDisabled')}</Badge>
}
if (totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0) {
return (
<Badge variant="samsung" className="gap-1">
<AlertTriangle className="w-3 h-3" />
{t('dolceImport.status.updatesAvailable', { projectCount: projectIds.length })}
</Badge>
)
}
return (
<Badge variant="default" className="gap-1 bg-green-500 hover:bg-green-600">
<CheckCircle className="w-3 h-3" />
{t('dolceImport.status.synchronized')}
</Badge>
)
}, [loadingVendorProjects, statusLoading, importStatusMap.size, totalStats, projectIds.length, t])
const canImport = totalStats.importEnabled &&
(totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0)
// 🔥 새로고침 핸들러 최적화
const handleRefresh = React.useCallback(() => {
statusCache.clear() // 캐시 무효화
fetchAllImportStatus()
}, [fetchAllImportStatus])
// 🔥 자동 동기화 실행 (기존 useEffect들 다음에 추가)
React.useEffect(() => {
// 조건: 가져오기 가능하고, 동기화할 항목이 있고, 현재 진행중이 아닐 때
if (canImport &&
(totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0) &&
!isImporting &&
!isDialogOpen) {
// 상태 로딩이 완료된 후 잠깐 대기 (사용자가 상태를 확인할 수 있도록)
const timer = setTimeout(() => {
console.log(`🔄 자동 동기화 시작: 새 문서 ${totalStats.newDocuments}개, 업데이트 ${totalStats.updatedDocuments}개`)
// 동기화 시작 알림
toast.info(
'새로운 문서가 발견되어 자동 동기화를 시작합니다',
{
description: `새 문서 ${totalStats.newDocuments}개, 업데이트 ${totalStats.updatedDocuments}개`,
duration: 3000
}
)
// 자동으로 다이얼로그 열고 동기화 실행
setIsDialogOpen(true)
// 잠깐 후 실제 동기화 시작 (다이얼로그가 열리는 시간)
setTimeout(() => {
handleImport()
}, 500)
}, 1500) // 1.5초 대기
return () => clearTimeout(timer)
}
}, [canImport, totalStats.newDocuments, totalStats.updatedDocuments, isImporting, isDialogOpen, handleImport])
// 로딩 중이거나 projectIds가 없으면 버튼을 표시하지 않음
if (projectIds.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">{t('dolceImport.buttons.getList')}</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">{t('dolceImport.labels.importStatus')}</h4>
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">{t('dolceImport.labels.currentStatus')}</span>
{statusBadge}
</div>
</div>
{/* 프로젝트 소스 표시 */}
{allDocuments.length === 0 && vendorProjectIds.length > 0 && (
<div className="text-xs text-blue-600 bg-blue-50 p-2 rounded">
{t('dolceImport.descriptions.noDocumentsImportAll')}
</div>
)}
{/* 다중 프로젝트 정보 표시 */}
{projectIds.length > 1 && (
<div className="text-sm">
<div className="text-muted-foreground">{t('dolceImport.labels.targetProjects')}</div>
<div className="font-medium">{t('dolceImport.labels.projectCount', { count: projectIds.length })}</div>
<div className="text-xs text-muted-foreground">
{t('dolceImport.labels.projectIds')}: {projectIds.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">{t('dolceImport.labels.newDocuments')}</div>
<div className="font-medium">{totalStats.newDocuments || 0}</div>
</div>
<div>
<div className="text-muted-foreground">{t('dolceImport.labels.updates')}</div>
<div className="font-medium">{totalStats.updatedDocuments || 0}</div>
</div>
</div>
<div className="text-sm">
<div className="text-muted-foreground">{t('dolceImport.labels.totalDocuments')}</div>
<div className="font-medium">{totalStats.availableDocuments || 0}</div>
</div>
{/* 각 프로젝트별 세부 정보 */}
{projectIds.length > 1 && (
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">
{t('dolceImport.labels.detailsByProject')}
</summary>
<div className="mt-2 space-y-2 pl-2 border-l-2 border-muted">
{projectIds.map(projectId => {
const status = importStatusMap.get(projectId)
return (
<div key={projectId} className="text-xs">
<div className="font-medium">{t('dolceImport.labels.projectLabel', { projectId })}</div>
{status ? (
<div className="text-muted-foreground">
{t('dolceImport.descriptions.projectDetails', {
newDocuments: status.newDocuments,
updatedDocuments: status.updatedDocuments
})}
</div>
) : (
<div className="text-destructive">{t('dolceImport.status.statusCheckFailed')}</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" />
{t('dolceImport.buttons.importing')}
</>
) : (
<>
<Download className="w-4 h-4 mr-2" />
{t('dolceImport.buttons.importNow')}
</>
)}
</Button>
<Button
variant="outline"
size="sm"
onClick={handleRefresh}
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>{t('dolceImport.dialog.title')}</DialogTitle>
<DialogDescription>
{t('dolceImport.dialog.description')}
{projectIds.length > 1 && ` (${t('dolceImport.dialog.multipleProjects', { count: projectIds.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>{t('dolceImport.labels.itemsToImport')}</span>
<span className="font-medium">
{totalStats.newDocuments + totalStats.updatedDocuments}
</span>
</div>
<div className="text-xs text-muted-foreground">
{t('dolceImport.descriptions.includesNewAndUpdated')}
<br />
{t('dolceImport.descriptions.b4DocumentsNote')}
{projectIds.length > 1 && (
<>
<br />
{t('dolceImport.descriptions.sequentialImport', { count: projectIds.length })}
</>
)}
</div>
{isImporting && (
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span>{t('dolceImport.labels.progress')}</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}
>
{t('buttons.cancel')}
</Button>
<Button
onClick={handleImport}
disabled={isImporting || !canImport}
>
{isImporting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
{t('dolceImport.buttons.importing')}
</>
) : (
<>
<Download className="w-4 h-4 mr-2" />
{t('dolceImport.buttons.startImport')}
</>
)}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</>
)
}
|