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
|
"use server";
import { logIntegrationExecution } from "./service";
/**
* DB 연동 로깅 래퍼 함수
*
* @description
* 데이터베이스 작업을 자동으로 로깅하는 래퍼 함수입니다.
* 동기화, 삽입, 수정, 삭제 등 다양한 DB 작업의 실행 시간과 결과를 기록합니다.
*
* @param integrationId 인터페이스 ID (추후 매핑 필요)
* @param tableName 테이블명
* @param operation 작업 유형 (sync, upsert, delete 등)
* @param processor 실제 DB 작업 함수
* @returns 처리 결과
*
* @example
* // 기본 DB 동기화 로깅
* const syncResult = await withDbLogging(
* 1, // 인터페이스 ID
* 'users',
* 'sync',
* async () => {
* // 외부 시스템에서 사용자 데이터 가져오기
* const externalUsers = await fetchExternalUsers();
*
* // 로컬 DB에 동기화
* const result = await syncUsersToLocalDb(externalUsers);
*
* return {
* totalProcessed: result.length,
* updated: result.filter(u => u.action === 'updated').length,
* created: result.filter(u => u.action === 'created').length
* };
* }
* );
*
* @example
* // 데이터 삽입/수정 로깅
* const upsertResult = await withDbLogging(
* 2,
* 'products',
* 'upsert',
* async () => {
* const productData = await getProductDataFromSap();
*
* // 기존 데이터 확인 후 삽입/수정
* const existingProduct = await db.products.findFirst({
* where: { sapId: productData.sapId }
* });
*
* if (existingProduct) {
* return await db.products.update({
* where: { id: existingProduct.id },
* data: productData
* });
* } else {
* return await db.products.create({
* data: productData
* });
* }
* }
* );
*
* @example
* // 에러 처리와 함께
* try {
* const deleteResult = await withDbLogging(
* 3,
* 'temp_data',
* 'cleanup',
* async () => {
* // 7일 이전 임시 데이터 삭제
* const cutoffDate = new Date();
* cutoffDate.setDate(cutoffDate.getDate() - 7);
*
* const result = await db.tempData.deleteMany({
* where: {
* createdAt: { lt: cutoffDate }
* }
* });
*
* return { deletedCount: result.count };
* }
* );
*
* console.log(`${deleteResult.deletedCount}개의 임시 데이터가 삭제됨`);
* } catch (error) {
* console.error('DB 정리 작업 실패:', error);
* }
*
* @example
* // 트랜잭션 내에서 사용
* const transactionResult = await withDbLogging(
* 4,
* 'orders',
* 'bulk_update',
* async () => {
* return await db.$transaction(async (tx) => {
* // 여러 테이블 업데이트
* const orders = await tx.orders.updateMany({
* where: { status: 'pending' },
* data: { status: 'processing' }
* });
*
* const orderItems = await tx.orderItems.updateMany({
* where: { order: { status: 'processing' } },
* data: { processedAt: new Date() }
* });
*
* return { ordersUpdated: orders.count, itemsUpdated: orderItems.count };
* });
* }
* );
*/
export async function withDbLogging<T>(
integrationId: number,
tableName: string,
operation: string,
processor: () => Promise<T>
): Promise<T> {
const start = Date.now();
try {
// 실제 DB 작업 실행
const result = await processor();
const duration = Date.now() - start;
// 성공 로그 기록
await logIntegrationExecution({
integrationId,
status: 'success',
responseTime: duration,
requestMethod: 'DB',
requestUrl: `${operation}:${tableName}`,
correlationId: `db_${tableName}_${Date.now()}`,
});
return result;
} catch (error) {
const duration = Date.now() - start;
// 실패 로그 기록
await logIntegrationExecution({
integrationId,
status: 'failed',
responseTime: duration,
errorMessage: error instanceof Error ? error.message : 'Unknown error',
requestMethod: 'DB',
requestUrl: `${operation}:${tableName}`,
correlationId: `db_${tableName}_${Date.now()}`,
});
throw error;
}
}
/**
* nonsap 동기화 로깅 헬퍼 함수
*
* @description
* Non-SAP 시스템과의 데이터 동기화를 로깅하는 전용 헬퍼 함수입니다.
* 전체 동기화(full)와 증분 동기화(delta) 모두 지원합니다.
*
* @param tableName 테이블명
* @param syncType 동기화 유형 (full, delta)
* @param processor 동기화 작업 함수
* @returns 처리 결과
*
* @example
* // 전체 동기화 로깅
* const fullSyncResult = await withNonsapSyncLogging(
* 'vendors',
* 'full',
* async () => {
* // 외부 시스템에서 전체 벤더 데이터 가져오기
* const allVendors = await fetchAllVendorsFromExternalSystem();
*
* // 기존 데이터 모두 삭제 후 재생성
* await db.vendors.deleteMany({});
*
* // 새 데이터 삽입
* const created = await db.vendors.createMany({
* data: allVendors
* });
*
* return {
* syncType: 'full',
* totalProcessed: allVendors.length,
* created: created.count,
* updated: 0,
* deleted: 0
* };
* }
* );
*
* @example
* // 증분 동기화 로깅
* const deltaSyncResult = await withNonsapSyncLogging(
* 'purchase_orders',
* 'delta',
* async () => {
* // 마지막 동기화 이후 변경된 데이터만 가져오기
* const lastSync = await getLastSyncTimestamp('purchase_orders');
* const changedOrders = await fetchChangedOrdersSince(lastSync);
*
* let created = 0, updated = 0, deleted = 0;
*
* for (const order of changedOrders) {
* if (order.isDeleted) {
* // 삭제된 데이터 처리
* await db.purchaseOrders.delete({ where: { externalId: order.id } });
* deleted++;
* } else {
* // 삽입/수정 데이터 처리
* const result = await db.purchaseOrders.upsert({
* where: { externalId: order.id },
* create: order,
* update: order
* });
*
* if (result.createdAt === result.updatedAt) {
* created++;
* } else {
* updated++;
* }
* }
* }
*
* // 동기화 타임스탬프 업데이트
* await updateLastSyncTimestamp('purchase_orders', new Date());
*
* return {
* syncType: 'delta',
* totalProcessed: changedOrders.length,
* created,
* updated,
* deleted
* };
* }
* );
*
* @example
* // 에러 복구가 포함된 동기화
* const resilientSyncResult = await withNonsapSyncLogging(
* 'inventory',
* 'delta',
* async () => {
* let processedCount = 0;
* let errorCount = 0;
* const errors: string[] = [];
*
* const inventoryUpdates = await fetchInventoryUpdates();
*
* for (const update of inventoryUpdates) {
* try {
* await db.inventory.upsert({
* where: { productId: update.productId },
* create: update,
* update: { quantity: update.quantity, updatedAt: new Date() }
* });
* processedCount++;
* } catch (error) {
* errorCount++;
* errors.push(`Product ${update.productId}: ${error.message}`);
*
* // 개별 에러는 로그에 남기지만 전체 작업은 계속 진행
* console.warn(`재고 업데이트 실패 - ${update.productId}:`, error);
* }
* }
*
* return {
* totalItems: inventoryUpdates.length,
* processedCount,
* errorCount,
* errors: errors.slice(0, 10) // 최대 10개 에러만 반환
* };
* }
* );
*/
export async function withNonsapSyncLogging<T>(
tableName: string,
syncType: 'full' | 'delta',
processor: () => Promise<T>
): Promise<T> {
return withDbLogging(
2, // nonsap 동기화 인터페이스 ID (추후 매핑 필요)
tableName,
`nonsap_${syncType}_sync`,
processor
);
}
|