summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/sync-service.ts
blob: 6978c1ccc2639da8d5cca993caf7192781b3a99c (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
// lib/sync-service.ts
import db from "@/db/db"
import { 
  syncConfigs, 
  changeLogs, 
  syncBatches, 
  syncStatusView,
  type SyncConfig,
  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 { toast } from "sonner"

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[]
}

class SyncService {
  
  /**
   * 변경사항을 change_logs에 기록
   */
  async logChange(
    contractId: number,
    entityType: 'document' | 'revision' | 'attachment',
    entityId: number,
    action: 'CREATE' | 'UPDATE' | 'DELETE',
    newValues?: any,
    oldValues?: any,
    userId?: number,
    userName?: string
  ) {
    try {
      const changedFields = this.detectChangedFields(oldValues, newValues)
      
      await db.insert(changeLogs).values({
        contractId,
        entityType,
        entityId,
        action,
        changedFields,
        oldValues,
        newValues,
        userId,
        userName,
        targetSystems: ['SHI'], // 기본적으로 SHI로 동기화
      })
      
      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 getSyncConfig(contractId: number, targetSystem: string = 'SHI'): Promise<SyncConfig | null> {
    const [config] = await db
      .select()
      .from(syncConfigs)
      .where(and(
        eq(syncConfigs.contractId, contractId),
        eq(syncConfigs.targetSystem, targetSystem)
      ))
      .limit(1)
    
    return config || null
  }

  /**
   * 동기화 설정 생성/업데이트
   */
  async upsertSyncConfig(config: Partial<SyncConfig> & { 
    contractId: number
    targetSystem: string 
    endpointUrl: string 
  }) {
    const existing = await this.getSyncConfig(config.contractId, config.targetSystem)
    
    if (existing) {
      await db
        .update(syncConfigs)
        .set({ ...config, updatedAt: new Date() })
        .where(eq(syncConfigs.id, existing.id))
    } else {
      await db.insert(syncConfigs).values(config)
    }
  }

  /**
   * 동기화할 변경사항 조회 (증분)
   */
  async getPendingChanges(
    contractId: number, 
    targetSystem: string = 'SHI',
    limit: number = 100
  ): Promise<ChangeLog[]> {
    return await db
      .select()
      .from(changeLogs)
      .where(and(
        eq(changeLogs.contractId, contractId),
        eq(changeLogs.isSynced, false),
        lt(changeLogs.syncAttempts, 3), // 최대 3회 재시도
        sql`(${changeLogs.targetSystems} IS NULL OR ${changeLogs.targetSystems} @> ${JSON.stringify([targetSystem])})`
      ))
      .orderBy(changeLogs.createdAt)
      .limit(limit)
  }

  /**
   * 동기화 배치 생성
   */
  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 = 'SHI',
    manualTrigger: boolean = false
  ): Promise<SyncResult> {
    try {
      // 1. 동기화 설정 확인
      const config = await this.getSyncConfig(contractId, targetSystem)
      if (!config || !config.syncEnabled) {
        throw new Error(`Sync not enabled for contract ${contractId} to ${targetSystem}`)
      }

      // 2. 대기 중인 변경사항 조회
      const pendingChanges = await this.getPendingChanges(
        contractId, 
        targetSystem, 
        config.maxBatchSize || 100
      )

      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 syncResult = await this.performSync(config, pendingChanges)
      
      // 6. 배치 상태 업데이트
      await db
        .update(syncBatches)
        .set({
          status: syncResult.success ? 'SUCCESS' : (syncResult.successCount > 0 ? 'PARTIAL' : 'FAILED'),
          completedAt: new Date(),
          successCount: syncResult.successCount,
          failureCount: syncResult.failureCount,
          errorMessage: syncResult.errors?.join('; '),
          updatedAt: new Date()
        })
        .where(eq(syncBatches.id, batchId))

      // 7. 성공한 변경사항들을 동기화 완료로 표시
      if (syncResult.successCount > 0) {
        const successfulChangeIds = pendingChanges
          .slice(0, syncResult.successCount)
          .map(c => c.id)
        
        await db
          .update(changeLogs)
          .set({
            isSynced: true,
            syncedAt: new Date()
          })
          .where(inArray(changeLogs.id, successfulChangeIds))
      }

      // 8. 실패한 변경사항들의 재시도 횟수 증가
      if (syncResult.failureCount > 0) {
        const failedChangeIds = pendingChanges
          .slice(syncResult.successCount)
          .map(c => c.id)
        
        await db
          .update(changeLogs)
          .set({
            syncAttempts: sql`${changeLogs.syncAttempts} + 1`,
            lastSyncError: syncResult.errors?.[0] || 'Unknown error'
          })
          .where(inArray(changeLogs.id, failedChangeIds))
      }

      // 9. 동기화 설정의 마지막 동기화 시간 업데이트
      await db
        .update(syncConfigs)
        .set({
          lastSyncAttempt: new Date(),
          ...(syncResult.success && { lastSuccessfulSync: new Date() }),
          updatedAt: new Date()
        })
        .where(eq(syncConfigs.id, config.id))

      return {
        batchId,
        success: syncResult.success,
        successCount: syncResult.successCount,
        failureCount: syncResult.failureCount,
        errors: syncResult.errors
      }

    } catch (error) {
      console.error('Sync failed:', error)
      throw error
    }
  }

  /**
   * 실제 외부 시스템으로 데이터 전송
   */
  private async performSync(
    config: SyncConfig, 
    changes: ChangeLog[]
  ): Promise<{ success: boolean; successCount: number; failureCount: number; errors?: string[] }> {
    const errors: string[] = []
    let successCount = 0
    let failureCount = 0

    try {
      // 변경사항을 외부 시스템 형태로 변환
      const syncData = await this.transformChangesForExternalSystem(changes)
      
      // 외부 API 호출
      const response = await fetch(config.endpointUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${config.authToken}`,
          'X-API-Version': config.apiVersion || 'v1'
        },
        body: JSON.stringify({
          contractId: changes[0]?.contractId,
          changes: syncData,
          batchSize: changes.length,
          timestamp: new Date().toISOString()
        })
      })

      if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`HTTP ${response.status}: ${errorText}`)
      }

      const result = await response.json()
      
      // 응답에 따라 성공/실패 카운트 처리
      if (result.success) {
        successCount = changes.length
      } else if (result.partialSuccess) {
        successCount = result.successCount || 0
        failureCount = changes.length - successCount
        if (result.errors) {
          errors.push(...result.errors)
        }
      } else {
        failureCount = changes.length
        if (result.error) {
          errors.push(result.error)
        }
      }

    } catch (error) {
      console.error('External sync failed:', error)
      failureCount = changes.length
      errors.push(error instanceof Error ? error.message : 'Unknown error')
    }

    return {
      success: failureCount === 0,
      successCount,
      failureCount,
      errors: errors.length > 0 ? errors : undefined
    }
  }

  /**
   * 변경사항을 외부 시스템 형태로 변환
   */
  private async transformChangesForExternalSystem(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
        }

        syncData.push({
          entityType: change.entityType as any,
          entityId: change.entityId,
          action: change.action as any,
          data: entityData || change.oldValues, // DELETE의 경우 oldValues 사용
          metadata: {
            changeId: change.id,
            changedAt: change.createdAt,
            changedBy: change.userName,
            changedFields: change.changedFields
          }
        })

      } catch (error) {
        console.error(`Failed to transform change ${change.id}:`, error)
      }
    }

    return syncData
  }

  /**
   * 동기화 상태 조회
   */
  async getSyncStatus(contractId: number, targetSystem: string = 'SHI') {
    const [status] = await db
      .select()
      .from(syncStatusView)
      .where(and(
        eq(syncStatusView.contractId, contractId),
        eq(syncStatusView.targetSystem, targetSystem)
      ))
      .limit(1)

    return status
  }

  /**
   * 최근 동기화 배치 목록 조회
   */
  async getRecentSyncBatches(contractId: number, targetSystem: string = 'SHI', limit: number = 10) {
    return await db
      .select()
      .from(syncBatches)
      .where(and(
        eq(syncBatches.contractId, contractId),
        eq(syncBatches.targetSystem, targetSystem)
      ))
      .orderBy(desc(syncBatches.createdAt))
      .limit(limit)
  }
}

export const syncService = new SyncService()

// 편의 함수들
export async function logDocumentChange(
  contractId: number,
  documentId: number,
  action: 'CREATE' | 'UPDATE' | 'DELETE',
  newValues?: any,
  oldValues?: any,
  userId?: number,
  userName?: string
) {
  return syncService.logChange(contractId, 'document', documentId, action, newValues, oldValues, userId, userName)
}

export async function logRevisionChange(
  contractId: number,
  revisionId: number,
  action: 'CREATE' | 'UPDATE' | 'DELETE',
  newValues?: any,
  oldValues?: any,
  userId?: number,
  userName?: string
) {
  return syncService.logChange(contractId, 'revision', revisionId, action, newValues, oldValues, userId, userName)
}

export async function logAttachmentChange(
  contractId: number,
  attachmentId: number,
  action: 'CREATE' | 'UPDATE' | 'DELETE',
  newValues?: any,
  oldValues?: any,
  userId?: number,
  userName?: string
) {
  return syncService.logChange(contractId, 'attachment', attachmentId, action, newValues, oldValues, userId, userName)
}