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
|
// lib/sync-service.ts (시스템별 분리 버전 - DOLCE 업로드 통합)
import db from "@/db/db"
import {
changeLogs,
syncBatches,
type ChangeLog,
type SyncBatch
} from "@/db/schema/vendorDocu"
import { documents, revisions, documentAttachments } from "@/db/schema/vendorDocu"
import { eq, and, lt, desc, sql, inArray } from "drizzle-orm"
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
export interface SyncableEntity {
entityType: 'document' | 'revision' | 'attachment'
entityId: number
action: 'CREATE' | 'UPDATE' | 'DELETE'
data: any
metadata?: Record<string, any>
}
export interface SyncResult {
batchId: number
success: boolean
successCount: number
failureCount: number
errors?: string[]
endpointResults?: Record<string, any>
}
class SyncService {
private readonly CHUNK_SIZE = 50
/**
* 동기화 활성화 여부 확인
*/
private isSyncEnabled(targetSystem: string): boolean {
const upperSystem = targetSystem.toUpperCase()
const enabled = process.env[`SYNC_${upperSystem}_ENABLED`]
return enabled === 'true' || enabled === '1'
}
/**
* 변경사항을 change_logs에 기록
*/
async logChange(
vendorId: number,
entityType: 'document' | 'revision' | 'attachment',
entityId: number,
action: 'CREATE' | 'UPDATE' | 'DELETE',
newValues?: any,
oldValues?: any,
userId?: number,
userName?: string,
targetSystems: string[] = ["DOLCE", "SWP"]
) {
try {
const changedFields = this.detectChangedFields(oldValues, newValues)
await db.insert(changeLogs).values({
vendorId,
entityType,
entityId,
action,
changedFields,
oldValues,
newValues,
userId,
userName,
targetSystems,
})
console.log(`Change logged: ${entityType}/${entityId} - ${action}`)
} catch (error) {
console.error('Failed to log change:', error)
throw error
}
}
/**
* 변경된 필드 감지
*/
private detectChangedFields(oldValues: any, newValues: any): Record<string, any> | null {
if (!oldValues || !newValues) return null
const changes: Record<string, any> = {}
for (const [key, newValue] of Object.entries(newValues)) {
if (JSON.stringify(oldValues[key]) !== JSON.stringify(newValue)) {
changes[key] = {
from: oldValues[key],
to: newValue
}
}
}
return Object.keys(changes).length > 0 ? changes : null
}
/**
* 동기화할 변경사항 조회 (증분)
*/
async getPendingChanges(
userId: number,
targetSystem: string = 'DOLCE',
limit?: number
): Promise<ChangeLog[]> {
const query = db
.select()
.from(changeLogs)
.where(and(
eq(changeLogs.userId, userId),
eq(changeLogs.isSynced, false),
lt(changeLogs.syncAttempts, 3),
sql`(${changeLogs.targetSystems} IS NULL OR ${changeLogs.targetSystems} @> ${JSON.stringify([targetSystem])})`
))
.orderBy(changeLogs.createdAt)
if (limit) {
query.limit(limit)
}
return await query
}
/**
* 배열을 청크 단위로 분할
*/
private chunkArray<T>(array: T[], chunkSize: number): T[][] {
const chunks: T[][] = []
for (let i = 0; i < array.length; i += chunkSize) {
chunks.push(array.slice(i, i + chunkSize))
}
return chunks
}
/**
* 동기화 배치 생성
*/
async createSyncBatch(
vendorId: number,
targetSystem: string,
changeLogIds: number[]
): Promise<number> {
const [batch] = await db
.insert(syncBatches)
.values({
vendorId,
targetSystem,
batchSize: changeLogIds.length,
changeLogIds,
status: 'PENDING'
})
.returning({ id: syncBatches.id })
return batch.id
}
/**
* 메인 동기화 실행 함수 (청크 처리 포함)
*/
async syncToExternalSystem(
projectId: number,
targetSystem: string = 'DOLCE',
manualTrigger: boolean = false
): Promise<SyncResult> {
try {
// 1. 동기화 활성화 확인
if (!this.isSyncEnabled(targetSystem)) {
throw new Error(`Sync not enabled for ${targetSystem}`)
}
const session = await getServerSession(authOptions)
if (!session?.user?.companyId) {
throw new Error("인증이 필요합니다.")
}
const vendorId = Number(session.user.companyId)
const userId = Number(session.user.id)
// 2. 대기 중인 변경사항 조회 (전체)
const pendingChanges = await this.getPendingChanges(userId, targetSystem)
if (pendingChanges.length === 0) {
return {
batchId: 0,
success: true,
successCount: 0,
failureCount: 0
}
}
// 3. 배치 생성
const batchId = await this.createSyncBatch(
vendorId,
targetSystem,
pendingChanges.map(c => c.id)
)
// 4. 배치 상태를 PROCESSING으로 업데이트
await db
.update(syncBatches)
.set({
status: 'PROCESSING',
startedAt: new Date(),
updatedAt: new Date()
})
.where(eq(syncBatches.id, batchId))
// 5. 청크 단위로 동기화 수행 - 시스템별 분기
const chunks = this.chunkArray(pendingChanges, this.CHUNK_SIZE)
let totalSuccessCount = 0
let totalFailureCount = 0
const allErrors: string[] = []
const endpointResults: Record<string, any> = {}
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i]
console.log(`Processing chunk ${i + 1}/${chunks.length} (${chunk.length} items) for ${targetSystem}`)
try {
let chunkResult;
// 시스템별로 다른 동기화 메서드 호출
switch (targetSystem.toUpperCase()) {
case 'DOLCE':
chunkResult = await this.performSyncDOLCE(chunk, projectId)
break
case 'SWP':
chunkResult = await this.performSyncSWP(chunk, projectId)
break
default:
throw new Error(`Unsupported target system: ${targetSystem}`)
}
totalSuccessCount += chunkResult.successCount
totalFailureCount += chunkResult.failureCount
if (chunkResult.errors) {
allErrors.push(...chunkResult.errors)
}
// 엔드포인트별 결과 병합
Object.assign(endpointResults, chunkResult.endpointResults || {})
// 성공한 변경사항들을 동기화 완료로 표시
if (chunkResult.successCount > 0) {
const successfulChangeIds = chunk
.slice(0, chunkResult.successCount)
.map(c => c.id)
await this.markChangesAsSynced(successfulChangeIds)
}
// 실패한 변경사항들의 재시도 횟수 증가
if (chunkResult.failureCount > 0) {
const failedChangeIds = chunk
.slice(chunkResult.successCount)
.map(c => c.id)
await this.incrementSyncAttempts(failedChangeIds, chunkResult.errors?.[0])
}
} catch (error) {
console.error(`Chunk ${i + 1} failed for ${targetSystem}:`, error)
totalFailureCount += chunk.length
allErrors.push(`Chunk ${i + 1}: ${error instanceof Error ? error.message : 'Unknown error'}`)
// 전체 청크 실패 시 재시도 횟수 증가
await this.incrementSyncAttempts(chunk.map(c => c.id), error instanceof Error ? error.message : 'Unknown error')
}
}
const overallSuccess = totalFailureCount === 0
// 6. 배치 상태 업데이트
await db
.update(syncBatches)
.set({
status: overallSuccess ? 'SUCCESS' : (totalSuccessCount > 0 ? 'PARTIAL' : 'FAILED'),
completedAt: new Date(),
successCount: totalSuccessCount,
failureCount: totalFailureCount,
errorMessage: allErrors.length > 0 ? allErrors.join('; ') : null,
updatedAt: new Date()
})
.where(eq(syncBatches.id, batchId))
return {
batchId,
success: overallSuccess,
successCount: totalSuccessCount,
failureCount: totalFailureCount,
errors: allErrors.length > 0 ? allErrors : undefined,
endpointResults
}
} catch (error) {
console.error('Sync failed:', error)
throw error
}
}
/**
* DOLCE 시스템 전용 동기화 수행 - 실제 업로드 서비스 사용
*/
private async performSyncDOLCE(
changes: ChangeLog[],
projectId: number
): Promise<{ success: boolean; successCount: number; failureCount: number; errors?: string[]; endpointResults?: Record<string, any> }> {
const errors: string[] = []
const endpointResults: Record<string, any> = {}
try {
// 세션에서 사용자 정보 가져오기
const session = await getServerSession(authOptions)
if (!session?.user) {
throw new Error("사용자 인증이 필요합니다.")
}
// DOLCE 업로드 서비스 동적 임포트
const { dolceUploadService } = await import('./dolce-upload-service')
if (!dolceUploadService.isUploadEnabled()) {
throw new Error('DOLCE upload is not enabled')
}
// 변경사항에서 리비전 ID들 추출 (revision 엔티티 + attachment 엔티티의 revisionId)
const revisionIds = [...new Set([
...changes
.filter(change => change.entityType === 'revision')
.map(change => change.entityId),
...changes
.filter(change => change.entityType === 'attachment')
.map(change => change.newValues?.revisionId)
.filter((id): id is number => typeof id === 'number' && id > 0)
])]
if (revisionIds.length === 0) {
return {
success: true,
successCount: 0,
failureCount: 0,
endpointResults: { message: 'No revisions to upload' }
}
}
// DOLCE 업로드 실행 - 사용자 정보 전달
const uploadResult = await dolceUploadService.uploadToDoLCE(
projectId,
revisionIds,
session.user.email || 'system_user', // 사용자 email
session.user.name || 'System Upload' // 사용자 name
)
endpointResults['dolce_upload'] = uploadResult
if (uploadResult.success) {
console.log(`✅ DOLCE upload successful: ${uploadResult.uploadedDocuments} documents, ${uploadResult.uploadedFiles} files`)
return {
success: true,
successCount: changes.length,
failureCount: 0,
endpointResults
}
} else {
console.error(`❌ DOLCE upload failed:`, uploadResult.errors)
return {
success: false,
successCount: 0,
failureCount: changes.length,
errors: uploadResult.errors,
endpointResults
}
}
} catch (error) {
const errorMessage = `DOLCE upload failed: ${error instanceof Error ? error.message : 'Unknown error'}`
errors.push(errorMessage)
console.error(`❌ DOLCE upload error:`, error)
return {
success: false,
successCount: 0,
failureCount: changes.length,
errors,
endpointResults
}
}
}
/**
* SWP 시스템 전용 동기화 수행
*/
private async performSyncSWP(
changes: ChangeLog[],
projectId: number
): Promise<{ success: boolean; successCount: number; failureCount: number; errors?: string[]; endpointResults?: Record<string, any> }> {
// SWP 동기화 로직 구현
// 현재는 플레이스홀더
return {
success: true,
successCount: changes.length,
failureCount: 0,
endpointResults: { message: 'SWP sync placeholder' }
}
}
/**
* 성공한 변경사항들을 동기화 완료로 표시
*/
private async markChangesAsSynced(changeIds: number[]) {
if (changeIds.length === 0) return
await db
.update(changeLogs)
.set({
isSynced: true,
syncedAt: new Date()
})
.where(inArray(changeLogs.id, changeIds))
// 리비전 상태 업데이트
const revisionChanges = await db
.select({ entityId: changeLogs.entityId })
.from(changeLogs)
.where(and(
inArray(changeLogs.id, changeIds),
eq(changeLogs.entityType, 'revision')
))
if (revisionChanges.length > 0) {
const revisionIds = revisionChanges.map(c => c.entityId)
await db.update(revisions)
.set({
revisionStatus: "SUBMITTED",
submittedDate: new Date().toISOString().slice(0, 10)
})
.where(inArray(revisions.id, revisionIds))
}
}
/**
* 실패한 변경사항들의 재시도 횟수 증가
*/
private async incrementSyncAttempts(changeIds: number[], errorMessage?: string) {
if (changeIds.length === 0) return
await db
.update(changeLogs)
.set({
syncAttempts: sql`${changeLogs.syncAttempts} + 1`,
lastSyncError: errorMessage || 'Unknown error'
})
.where(inArray(changeLogs.id, changeIds))
}
/**
* 동기화 상태 조회 - entityType별 상세 통계 포함
*/
async getSyncStatus(projectId: number, targetSystem: string = 'DOLCE') {
try {
const session = await getServerSession(authOptions)
if (!session?.user?.companyId) {
throw new Error("인증이 필요합니다.")
}
const vendorId = Number(session.user.companyId)
const userId = Number(session.user.id)
// 기본 조건
const baseConditions = and(
eq(changeLogs.userId, userId),
sql`(${changeLogs.targetSystems} IS NULL OR ${changeLogs.targetSystems} @> ${JSON.stringify([targetSystem])})`
)
// entityType별 통계를 위한 쿼리
const entityStats = await db
.select({
entityType: changeLogs.entityType,
pendingCount: sql<number>`COUNT(*) FILTER (WHERE ${changeLogs.isSynced} = false AND ${changeLogs.syncAttempts} < 3)`,
syncedCount: sql<number>`COUNT(*) FILTER (WHERE ${changeLogs.isSynced} = true)`,
failedCount: sql<number>`COUNT(*) FILTER (WHERE ${changeLogs.isSynced} = false AND ${changeLogs.syncAttempts} >= 3)`,
totalCount: sql<number>`COUNT(*)`
})
.from(changeLogs)
.where(baseConditions)
.groupBy(changeLogs.entityType)
// 전체 통계 계산
const totals = entityStats.reduce((acc, stat) => ({
pendingChanges: acc.pendingChanges + Number(stat.pendingCount),
syncedChanges: acc.syncedChanges + Number(stat.syncedCount),
failedChanges: acc.failedChanges + Number(stat.failedCount),
totalChanges: acc.totalChanges + Number(stat.totalCount)
}), {
pendingChanges: 0,
syncedChanges: 0,
failedChanges: 0,
totalChanges: 0
})
// entityType별 상세 정보 구성
const entityTypeDetails = {
document: {
pending: 0,
synced: 0,
failed: 0,
total: 0
},
revision: {
pending: 0,
synced: 0,
failed: 0,
total: 0
},
attachment: {
pending: 0,
synced: 0,
failed: 0,
total: 0
}
}
// 통계 데이터를 entityTypeDetails에 매핑
entityStats.forEach(stat => {
const entityType = stat.entityType as 'document' | 'revision' | 'attachment'
if (entityTypeDetails[entityType]) {
entityTypeDetails[entityType] = {
pending: Number(stat.pendingCount),
synced: Number(stat.syncedCount),
failed: Number(stat.failedCount),
total: Number(stat.totalCount)
}
}
})
return {
projectId,
vendorId,
targetSystem,
...totals,
entityTypeDetails, // entityType별 상세 통계
syncEnabled: this.isSyncEnabled(targetSystem),
// 추가 메타데이터
hasPendingChanges: totals.pendingChanges > 0,
hasFailedChanges: totals.failedChanges > 0,
syncHealthy: totals.failedChanges === 0 && totals.pendingChanges < 100,
requiresSync: totals.pendingChanges > 0
}
} catch (error) {
console.error('Failed to get sync status:', error)
throw error
}
}
/**
* 최근 동기화 배치 목록 조회
*/
async getRecentSyncBatches(projectId: number, targetSystem: string = 'DOLCE', limit: number = 10) {
try {
const session = await getServerSession(authOptions)
if (!session?.user?.companyId) {
throw new Error("인증이 필요합니다.")
}
const vendorId = Number(session.user.companyId)
const batches = await db
.select()
.from(syncBatches)
.where(and(
eq(syncBatches.vendorId, vendorId),
eq(syncBatches.targetSystem, targetSystem)
))
.orderBy(desc(syncBatches.createdAt))
.limit(limit)
// Date 객체를 문자열로 변환
return batches.map(batch => ({
id: Number(batch.id),
vendorId: batch.vendorId,
targetSystem: batch.targetSystem,
batchSize: batch.batchSize,
status: batch.status,
startedAt: batch.startedAt?.toISOString() || null,
completedAt: batch.completedAt?.toISOString() || null,
errorMessage: batch.errorMessage,
retryCount: batch.retryCount,
successCount: batch.successCount,
failureCount: batch.failureCount,
createdAt: batch.createdAt.toISOString(),
updatedAt: batch.updatedAt.toISOString()
}))
} catch (error) {
console.error('Failed to get sync batches:', error)
throw error
}
}
}
export const syncService = new SyncService()
// 편의 함수들 (기본 타겟 시스템을 DOLCE로 변경)
export async function logDocumentChange(
projectId: number,
documentId: number,
action: 'CREATE' | 'UPDATE' | 'DELETE',
newValues?: any,
oldValues?: any,
userId?: number,
userName?: string,
targetSystems: string[] = ["DOLCE", "SWP"]
) {
return syncService.logChange(projectId, 'document', documentId, action, newValues, oldValues, userId, userName, targetSystems)
}
export async function logRevisionChange(
vendorId: number,
revisionId: number,
action: 'CREATE' | 'UPDATE' | 'DELETE',
newValues?: any,
oldValues?: any,
userId?: number,
userName?: string,
targetSystems: string[] = ["DOLCE", "SWP"]
) {
return syncService.logChange(vendorId, 'revision', revisionId, action, newValues, oldValues, userId, userName, targetSystems)
}
export async function logAttachmentChange(
vendorId: number,
attachmentId: number,
action: 'CREATE' | 'UPDATE' | 'DELETE',
newValues?: any,
oldValues?: any,
userId?: number,
userName?: string,
targetSystems: string[] = ["DOLCE", "SWP"]
) {
return syncService.logChange(vendorId, 'attachment', attachmentId, action, newValues, oldValues, userId, userName, targetSystems)
}
|