summaryrefslogtreecommitdiff
path: root/lib/edp-sync/sync-edp.ts
blob: 26f3d493546861f866dd44901378b7a48e8608a9 (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
// EDP 마스터 데이터 동기화 함수들
// SEDP API에서 마스터 데이터를 가져와 데이터베이스에 동기화하는 함수들

import { syncTagSubfields } from "@/lib/sedp/sync-tag-types";
import { syncTagFormMappings } from "@/lib/sedp/sync-form";
import { syncObjectClasses } from "@/lib/sedp/sync-object-class";

/**
 * EDP 마스터 데이터를 순차적으로 동기화하는 메인 함수
 * 1. 오브젝트 클래스 동기화 (태그 타입 포함)
 * 2. 태그 서브필드 동기화
 * 3. 태그 폼 매핑 동기화
 */
export async function syncEDPMasterData(): Promise<{
  success: boolean;
  message: string;
  results: {
    objectClasses?: any;
    tagSubfields?: any;
    tagFormMappings?: any;
  };
  totalExecutionTime: number;
}> {
  const startTime = Date.now();
  const results: any = {};

  try {
    console.log('🚀 EDP 마스터 데이터 동기화 시작:', new Date().toISOString());

    // 1. 오브젝트 클래스 동기화 (태그 타입 포함)
    console.log('1단계: 오브젝트 클래스 동기화 시작...');
    try {
      results.objectClasses = await syncObjectClasses();
      console.log('오브젝트 클래스 동기화 완료');
    } catch (error) {
      console.error('❌ 오브젝트 클래스 동기화 실패:', error);
      results.objectClasses = { error: error instanceof Error ? error.message : String(error) };
    }

    // 2. 태그 서브필드 동기화
    console.log('2단계: 태그 서브필드 동기화 시작...');
    try {
      results.tagSubfields = await syncTagSubfields();
      console.log('태그 서브필드 동기화 완료');
    } catch (error) {
      console.error('❌ 태그 서브필드 동기화 실패:', error);
      results.tagSubfields = { error: error instanceof Error ? error.message : String(error) };
    }

    // 3. 태그 폼 매핑 동기화
    console.log('3단계: 태그 폼 매핑 동기화 시작...');
    try {
      results.tagFormMappings = await syncTagFormMappings();
      console.log('태그 폼 매핑 동기화 완료');
    } catch (error) {
      console.error('❌ 태그 폼 매핑 동기화 실패:', error);
      results.tagFormMappings = { error: error instanceof Error ? error.message : String(error) };
    }

    const totalExecutionTime = Date.now() - startTime;

    // 성공/실패 요약
    const resultValues = Object.values(results);
    const hasErrors = resultValues.some((result: any) =>
      result && (result.error || (result.failed && result.failed > 0))
    );

    const message = hasErrors
      ? 'EDP 마스터 데이터 동기화 완료 (일부 단계에서 오류 발생)'
      : 'EDP 마스터 데이터 동기화 완료 (모든 단계 성공)';

    console.log(`${message} - 총 실행 시간: ${totalExecutionTime}ms`);

    return {
      success: !hasErrors,
      message,
      results,
      totalExecutionTime
    };

  } catch (error) {
    const totalExecutionTime = Date.now() - startTime;
    console.error('EDP 마스터 데이터 동기화 중 전체 오류 발생:', error);

    return {
      success: false,
      message: `EDP 마스터 데이터 동기화 실패: ${error instanceof Error ? error.message : String(error)}`,
      results,
      totalExecutionTime
    };
  }
}

/**
 * EDP 마스터 데이터 동기화 스케줄러 시작 함수
 * instrumentation.ts에서 호출되어 cron job을 등록
 */
export async function startEDPMasterDataSyncScheduler(): Promise<void> {
  try {
    // 환경변수에서 cron 표현식 가져오기 (기본값: 매 20분마다)
    const cronExpression = process.env.EDP_MASTER_DATA_SYNC_CRON || '*/20 * * * *';

    // node-cron import
    const cron = (await import('node-cron')).default;

    // cron job 등록
    cron.schedule(cronExpression, async () => {
      try {
        console.log(`⏰ EDP 마스터 데이터 동기화 시작 (크론: ${cronExpression})`);
        const result = await syncEDPMasterData();

        if (result.success) {
          console.log(`✅ EDP 마스터 데이터 동기화 성공 - 실행 시간: ${result.totalExecutionTime}ms`);
        } else {
          console.error(`❌ EDP 마스터 데이터 동기화 실패: ${result.message}`);
        }
      } catch (error) {
        console.error('❌ EDP 마스터 데이터 동기화 중 예외 발생:', error);
      }
    }, { timezone: 'Asia/Seoul' });

    console.log(`✅ EDP 마스터 데이터 동기화 스케줄러 등록 완료 (크론: ${cronExpression})`);
  } catch (error) {
    console.error('❌ EDP 마스터 데이터 동기화 스케줄러 등록 실패:', error);
    throw error;
  }
}