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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
|
// lib/sync-service.ts (시스템별 분리 버전)
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"
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(
contractId: 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({
contractId,
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(
contractId: number,
targetSystem: string = 'DOLCE',
limit?: number
): Promise<ChangeLog[]> {
const query = db
.select()
.from(changeLogs)
.where(and(
eq(changeLogs.contractId, contractId),
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(
contractId: number,
targetSystem: string,
changeLogIds: number[]
): Promise<number> {
const [batch] = await db
.insert(syncBatches)
.values({
contractId,
targetSystem,
batchSize: changeLogIds.length,
changeLogIds,
status: 'PENDING'
})
.returning({ id: syncBatches.id })
return batch.id
}
/**
* 메인 동기화 실행 함수 (청크 처리 포함)
*/
async syncToExternalSystem(
contractId: number,
targetSystem: string = 'DOLCE',
manualTrigger: boolean = false
): Promise<SyncResult> {
try {
// 1. 동기화 활성화 확인
if (!this.isSyncEnabled(targetSystem)) {
throw new Error(`Sync not enabled for ${targetSystem}`)
}
// 2. 대기 중인 변경사항 조회 (전체)
const pendingChanges = await this.getPendingChanges(contractId, targetSystem)
if (pendingChanges.length === 0) {
return {
batchId: 0,
success: true,
successCount: 0,
failureCount: 0
}
}
// 3. 배치 생성
const batchId = await this.createSyncBatch(
contractId,
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, contractId)
break
case 'SWP':
chunkResult = await this.performSyncSWP(chunk, contractId)
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[],
contractId: number
): Promise<{ success: boolean; successCount: number; failureCount: number; errors?: string[]; endpointResults?: Record<string, any> }> {
const errors: string[] = []
const endpointResults: Record<string, any> = {}
let overallSuccess = true
// 변경사항을 DOLCE 시스템 형태로 변환
const syncData = await this.transformChangesForDOLCE(changes)
// DOLCE 엔드포인트 호출들을 직접 정의
const endpointPromises = []
// 1. DOLCE 메인 엔드포인트
const mainUrl = process.env.SYNC_DOLCE_URL
if (mainUrl) {
endpointPromises.push(
(async () => {
try {
console.log(`Sending to DOLCE main: ${mainUrl}`)
const transformedData = {
contractId,
systemType: 'DOLCE',
changes: syncData,
batchSize: changes.length,
timestamp: new Date().toISOString(),
source: 'EVCP',
version: '1.0'
}
// 헤더 구성 (토큰이 있을 때만 Authorization 포함)
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'X-API-Version': process.env.SYNC_DOLCE_VERSION || 'v1',
'X-System': 'DOLCE'
}
if (process.env.SYNC_DOLCE_TOKEN) {
headers['Authorization'] = `Bearer ${process.env.SYNC_DOLCE_TOKEN}`
}
const response = await fetch(mainUrl, {
method: 'POST',
headers,
body: JSON.stringify(transformedData)
})
if (!response.ok) {
const errorText = await response.text()
throw new Error(`DOLCE main: HTTP ${response.status} - ${errorText}`)
}
const result = await response.json()
endpointResults['dolce_main'] = result
console.log(`✅ DOLCE main sync successful`)
return { success: true, endpoint: 'dolce_main', result }
} catch (error) {
const errorMessage = `DOLCE main: ${error instanceof Error ? error.message : 'Unknown error'}`
errors.push(errorMessage)
overallSuccess = false
console.error(`❌ DOLCE main sync failed:`, error)
return { success: false, endpoint: 'dolce_main', error: errorMessage }
}
})()
)
}
// 2. DOLCE 문서 전용 엔드포인트 (선택사항)
const docUrl = process.env.SYNC_DOLCE_DOCUMENT_URL
if (docUrl) {
endpointPromises.push(
(async () => {
try {
console.log(`Sending to DOLCE documents: ${docUrl}`)
const documentData = {
documents: syncData.filter(item => item.entityType === 'document'),
source: 'EVCP_DOLCE',
timestamp: new Date().toISOString()
}
// 헤더 구성 (토큰이 있을 때만 Authorization 포함)
const headers: Record<string, string> = {
'Content-Type': 'application/json'
}
if (process.env.SYNC_DOLCE_TOKEN) {
headers['Authorization'] = `Bearer ${process.env.SYNC_DOLCE_TOKEN}`
}
const response = await fetch(docUrl, {
method: 'PUT',
headers,
body: JSON.stringify(documentData)
})
if (!response.ok) {
const errorText = await response.text()
throw new Error(`DOLCE documents: HTTP ${response.status} - ${errorText}`)
}
const result = await response.json()
endpointResults['dolce_documents'] = result
console.log(`✅ DOLCE documents sync successful`)
return { success: true, endpoint: 'dolce_documents', result }
} catch (error) {
const errorMessage = `DOLCE documents: ${error instanceof Error ? error.message : 'Unknown error'}`
errors.push(errorMessage)
overallSuccess = false
console.error(`❌ DOLCE documents sync failed:`, error)
return { success: false, endpoint: 'dolce_documents', error: errorMessage }
}
})()
)
}
if (endpointPromises.length === 0) {
throw new Error('No DOLCE sync endpoints configured')
}
// 모든 엔드포인트 요청 완료 대기
const results = await Promise.allSettled(endpointPromises)
// 결과 집계
const successfulEndpoints = results.filter(r => r.status === 'fulfilled' && r.value.success).length
const totalEndpoints = endpointPromises.length
console.log(`DOLCE endpoint results: ${successfulEndpoints}/${totalEndpoints} successful`)
return {
success: overallSuccess && errors.length === 0,
successCount: overallSuccess ? changes.length : 0,
failureCount: overallSuccess ? 0 : changes.length,
errors: errors.length > 0 ? errors : undefined,
endpointResults
}
}
/**
* SWP 시스템 전용 동기화 수행
*/
private async performSyncSWP(
changes: ChangeLog[],
contractId: number
): Promise<{ success: boolean; successCount: number; failureCount: number; errors?: string[]; endpointResults?: Record<string, any> }> {
const errors: string[] = []
const endpointResults: Record<string, any> = {}
let overallSuccess = true
// 변경사항을 SWP 시스템 형태로 변환
const syncData = await this.transformChangesForSWP(changes)
// 1. SWP 메인 엔드포인트 (XML 전송)
const mainUrl = process.env.SYNC_SWP_URL
if (mainUrl) {
try {
console.log(`Sending to SWP main: ${mainUrl}`)
const transformedData = this.convertToXML({
contractId,
systemType: 'SWP',
changes: syncData,
batchSize: changes.length,
timestamp: new Date().toISOString(),
source: 'EVCP'
})
const response = await fetch(mainUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/xml',
'Authorization': `Basic ${Buffer.from(`${process.env.SYNC_SWP_USER}:${process.env.SYNC_SWP_PASSWORD}`).toString('base64')}`,
'X-System': 'SWP'
},
body: transformedData
})
if (!response.ok) {
const errorText = await response.text()
throw new Error(`SWP main: HTTP ${response.status} - ${errorText}`)
}
let result
const contentType = response.headers.get('content-type')
if (contentType?.includes('application/json')) {
result = await response.json()
} else {
result = await response.text()
}
endpointResults['swp_main'] = result
console.log(`✅ SWP main sync successful`)
} catch (error) {
const errorMessage = `SWP main: ${error instanceof Error ? error.message : 'Unknown error'}`
errors.push(errorMessage)
overallSuccess = false
console.error(`❌ SWP main sync failed:`, error)
}
}
// 2. SWP 알림 엔드포인트 (선택사항)
const notificationUrl = process.env.SYNC_SWP_NOTIFICATION_URL
if (notificationUrl) {
try {
console.log(`Sending to SWP notification: ${notificationUrl}`)
const notificationData = {
event: 'swp_sync_notification',
itemCount: syncData.length,
syncTime: new Date().toISOString(),
system: 'SWP'
}
const response = await fetch(notificationUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(notificationData)
})
if (!response.ok) {
const errorText = await response.text()
throw new Error(`SWP notification: HTTP ${response.status} - ${errorText}`)
}
const result = await response.json()
endpointResults['swp_notification'] = result
console.log(`✅ SWP notification sync successful`)
} catch (error) {
const errorMessage = `SWP notification: ${error instanceof Error ? error.message : 'Unknown error'}`
errors.push(errorMessage)
// 알림은 실패해도 전체 동기화는 성공으로 처리
console.error(`❌ SWP notification sync failed:`, error)
}
}
if (!mainUrl) {
throw new Error('No SWP main endpoint configured')
}
console.log(`SWP sync completed with ${errors.length} errors`)
return {
success: overallSuccess && errors.length === 0,
successCount: overallSuccess ? changes.length : 0,
failureCount: overallSuccess ? 0 : changes.length,
errors: errors.length > 0 ? errors : undefined,
endpointResults
}
}
/**
* DOLCE 시스템용 데이터 변환
*/
private async transformChangesForDOLCE(changes: ChangeLog[]): Promise<SyncableEntity[]> {
const syncData: SyncableEntity[] = []
for (const change of changes) {
try {
let entityData = null
// 엔티티 타입별로 현재 데이터 조회
switch (change.entityType) {
case 'document':
if (change.action !== 'DELETE') {
const [document] = await db
.select()
.from(documents)
.where(eq(documents.id, change.entityId))
.limit(1)
entityData = document
}
break
case 'revision':
if (change.action !== 'DELETE') {
const [revision] = await db
.select()
.from(revisions)
.where(eq(revisions.id, change.entityId))
.limit(1)
entityData = revision
}
break
case 'attachment':
if (change.action !== 'DELETE') {
const [attachment] = await db
.select()
.from(documentAttachments)
.where(eq(documentAttachments.id, change.entityId))
.limit(1)
entityData = attachment
}
break
}
// DOLCE 특화 데이터 구조
syncData.push({
entityType: change.entityType as any,
entityId: change.entityId,
action: change.action as any,
data: entityData || change.oldValues,
metadata: {
changeId: change.id,
changedAt: change.createdAt,
changedBy: change.userName,
changedFields: change.changedFields,
// DOLCE 전용 메타데이터
dolceVersion: '2.0',
processingPriority: change.entityType === 'revision' ? 'HIGH' : 'NORMAL',
requiresApproval: change.action === 'DELETE'
}
})
} catch (error) {
console.error(`Failed to transform change ${change.id} for DOLCE:`, error)
}
}
return syncData
}
/**
* SWP 시스템용 데이터 변환
*/
private async transformChangesForSWP(changes: ChangeLog[]): Promise<SyncableEntity[]> {
const syncData: SyncableEntity[] = []
for (const change of changes) {
try {
let entityData = null
// 엔티티 타입별로 현재 데이터 조회
switch (change.entityType) {
case 'document':
if (change.action !== 'DELETE') {
const [document] = await db
.select()
.from(documents)
.where(eq(documents.id, change.entityId))
.limit(1)
entityData = document
}
break
case 'revision':
if (change.action !== 'DELETE') {
const [revision] = await db
.select()
.from(revisions)
.where(eq(revisions.id, change.entityId))
.limit(1)
entityData = revision
}
break
case 'attachment':
if (change.action !== 'DELETE') {
const [attachment] = await db
.select()
.from(documentAttachments)
.where(eq(documentAttachments.id, change.entityId))
.limit(1)
entityData = attachment
}
break
}
// SWP 특화 데이터 구조
syncData.push({
entityType: change.entityType as any,
entityId: change.entityId,
action: change.action as any,
data: entityData || change.oldValues,
metadata: {
changeId: change.id,
changedAt: change.createdAt,
changedBy: change.userName,
changedFields: change.changedFields,
// SWP 전용 메타데이터
swpFormat: 'legacy',
batchSequence: syncData.length + 1,
needsValidation: change.entityType === 'document',
legacyId: `SWP_${change.entityId}_${Date.now()}`
}
})
} catch (error) {
console.error(`Failed to transform change ${change.id} for SWP:`, error)
}
}
return syncData
}
/**
* 간단한 XML 변환 헬퍼 (SWP용)
*/
private convertToXML(data: any): string {
const xmlHeader = '<?xml version="1.0" encoding="UTF-8"?>'
const xmlBody = `
<SyncRequest>
<ContractId>${data.contractId}</ContractId>
<SystemType>${data.systemType}</SystemType>
<BatchSize>${data.batchSize}</BatchSize>
<Timestamp>${data.timestamp}</Timestamp>
<Source>${data.source}</Source>
<Changes>
${data.changes.map((change: SyncableEntity) => `
<Change>
<EntityType>${change.entityType}</EntityType>
<EntityId>${change.entityId}</EntityId>
<Action>${change.action}</Action>
<Data>${JSON.stringify(change.data)}</Data>
</Change>
`).join('')}
</Changes>
</SyncRequest>`
return xmlHeader + xmlBody
}
/**
* 성공한 변경사항들을 동기화 완료로 표시
*/
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",
externalSentAt: 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))
}
/**
* 동기화 상태 조회
*/
async getSyncStatus(contractId: number, targetSystem: string = 'DOLCE') {
try {
// 대기 중인 변경사항 수 조회
const pendingCount = await db.$count(
changeLogs,
and(
eq(changeLogs.contractId, contractId),
eq(changeLogs.isSynced, false),
lt(changeLogs.syncAttempts, 3),
sql`(${changeLogs.targetSystems} IS NULL OR ${changeLogs.targetSystems} @> ${JSON.stringify([targetSystem])})`
)
)
// 동기화된 변경사항 수 조회
const syncedCount = await db.$count(
changeLogs,
and(
eq(changeLogs.contractId, contractId),
eq(changeLogs.isSynced, true),
sql`(${changeLogs.targetSystems} IS NULL OR ${changeLogs.targetSystems} @> ${JSON.stringify([targetSystem])})`
)
)
// 실패한 변경사항 수 조회
const failedCount = await db.$count(
changeLogs,
and(
eq(changeLogs.contractId, contractId),
eq(changeLogs.isSynced, false),
sql`${changeLogs.syncAttempts} >= 3`,
sql`(${changeLogs.targetSystems} IS NULL OR ${changeLogs.targetSystems} @> ${JSON.stringify([targetSystem])})`
)
)
// 마지막 성공한 배치 조회
const [lastSuccessfulBatch] = await db
.select()
.from(syncBatches)
.where(and(
eq(syncBatches.contractId, contractId),
eq(syncBatches.targetSystem, targetSystem),
eq(syncBatches.status, 'SUCCESS')
))
.orderBy(desc(syncBatches.completedAt))
.limit(1)
return {
contractId,
targetSystem,
totalChanges: pendingCount + syncedCount + failedCount,
pendingChanges: pendingCount,
syncedChanges: syncedCount,
failedChanges: failedCount,
lastSyncAt: lastSuccessfulBatch?.completedAt?.toISOString() || null,
syncEnabled: this.isSyncEnabled(targetSystem)
}
} catch (error) {
console.error('Failed to get sync status:', error)
throw error
}
}
/**
* 최근 동기화 배치 목록 조회
*/
async getRecentSyncBatches(contractId: number, targetSystem: string = 'DOLCE', limit: number = 10) {
try {
const batches = await db
.select()
.from(syncBatches)
.where(and(
eq(syncBatches.contractId, contractId),
eq(syncBatches.targetSystem, targetSystem)
))
.orderBy(desc(syncBatches.createdAt))
.limit(limit)
// Date 객체를 문자열로 변환
return batches.map(batch => ({
id: Number(batch.id),
contractId: batch.contractId,
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(
contractId: number,
documentId: number,
action: 'CREATE' | 'UPDATE' | 'DELETE',
newValues?: any,
oldValues?: any,
userId?: number,
userName?: string,
targetSystems: string[] = ["DOLCE", "SWP"]
) {
return syncService.logChange(contractId, 'document', documentId, action, newValues, oldValues, userId, userName, targetSystems)
}
export async function logRevisionChange(
contractId: number,
revisionId: number,
action: 'CREATE' | 'UPDATE' | 'DELETE',
newValues?: any,
oldValues?: any,
userId?: number,
userName?: string,
targetSystems: string[] = ["DOLCE", "SWP"]
) {
return syncService.logChange(contractId, 'revision', revisionId, action, newValues, oldValues, userId, userName, targetSystems)
}
export async function logAttachmentChange(
contractId: number,
attachmentId: number,
action: 'CREATE' | 'UPDATE' | 'DELETE',
newValues?: any,
oldValues?: any,
userId?: number,
userName?: string,
targetSystems: string[] = ["DOLCE", "SWP"]
) {
return syncService.logChange(contractId, 'attachment', attachmentId, action, newValues, oldValues, userId, userName, targetSystems)
}
|