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
|
import { debugLog, debugSuccess, debugError, debugWarn } from '@/lib/debug-utils';
import db from '@/db/db';
import { vendors } from '@/db/schema/vendors';
import {
VENDOR_MASTER_BP_HEADER_BP_VENGEN,
VENDOR_MASTER_BP_HEADER_BP_TAXNUM,
VENDOR_MASTER_BP_HEADER_ADDRESS_AD_POSTAL,
VENDOR_MASTER_BP_HEADER_ADDRESS_AD_TEL,
VENDOR_MASTER_BP_HEADER_ADDRESS_AD_EMAIL,
VENDOR_MASTER_BP_HEADER_ADDRESS_AD_URL
} from '@/db/schema/MDG/mdg';
import { eq, and } from 'drizzle-orm';
/**
* 벤더 매퍼
*
* MDG에서 받은 벤더 데이터를 수신테이블에 적재하고 나서
* 해당 벤더 데이터를 비즈니스 테이블로 매핑 & 적재해주는 도구
*
* 수신테이블: mdg 스키마의 VENDOR_MASTER 관련 테이블
* 비즈니스테이블: public 스키마의 vendors 테이블
*
* 대부분 VENDOR_MASTER_BP_HEADER_BP_VENGEN 테이블에 적재된 데이터로 처리 가능함
* 아래 매핑 규칙에서 좌측이 수신테이블이며, 우측은 비즈니스테이블(vendors)임
* 모든 수신테이블 내 join 처리는 수신테이블의 외래키 필드인 VNDRCD 필드를 기준으로 처리함
* 아래 순서는 vendors 테이블의 필드 순서를 기준으로 함.
*
* [BP_VENGEN]VNDRCD -> [vendors]vendorCode
* [BP_POSTAL]VNDRNM_1 -> [vendors]vendorName
* [BP_TAXNUM]BIZ_PTNR_TX_NO -> [vendors]taxId
* [BP_POSTAL]ETC_ADR1 -> [vendors]address
* [BP_POSTAL]ADR_1 + ADR_2 -> [vendors]addressDetail
* [BP_POSTAL]CITY_ZIP_NO -> [vendors]postalCode
* [BP_POSTAL]NTN_CD -> [vendors]country (국가코드)
* [BP_ADDRESS_AD_TEL]TEL_NO -> [vendors]phone (수신테이블쪽이 여러개일 수 있는데 1개만 처리)
* [BP_ADDRESS_AD_EMAIL]EMAIL_ADR -> [vendors]email (수신테이블쪽이 여러개일 수 있는데 1개만 처리)
* [BP_ADDRESS_AD_URL]URL -> [vendors]website (수신테이블쪽이 여러개일 수 있는데 1개만 처리)
* [vendors]status 항목은 항상 'ACTIVE'로 처리
* ? vendorTypeId는 기존 값에서 처리할 수 없음. null로 남겨두기.
* [BP_VENGEN]REPR_NM -> [vendors]representativeName (대표자명)
* [BP_VENGEN]REPR_RESNO -> [vendors]representativeBirth (대표자생년월일) (앞 6자리만 잘라 넣어야 함)
* [BP_ADDRESS_AD_EMAIL]EMAIL_ADR -> [vendors]representativeEmail (대표자이메일, email과 동일한 값 사용)
* [BP_VENGEN]REP_TEL_NO -> [vendors]representativePhone (대표자연락처)
* ? representativeWorkExpirence은 기존 값에서 처리할 수 없음. null로 남겨두기 (오타난 거 암. 나중에 바꿀 것)
* [BP_VENGEN]CO_REG_NO -> [vendors]corporateRegistrationNumber (법인등록번호)
* [BP_VENGEN]CO_VLM -> [vendors]businessSize (사업규모)
*
*/
// MDG 벤더 데이터 타입 정의
export type MDGVendorData = {
VNDRCD: string;
VNDRNM_1?: string;
BIZ_PTNR_TX_NO?: string;
ETC_ADR_1?: string;
ADR_1?: string;
ADR_2?: string;
CITY_ZIP_NO?: string;
NTN_CD?: string;
TEL_NO?: string;
EMAIL_ADR?: string;
URL?: string;
REPR_NM?: string;
REPR_RESNO?: string;
REPR_EMAIL?: string;
REP_TEL_NO?: string;
CO_REG_NO?: string;
CO_VLM?: string;
};
// 비즈니스 테이블 데이터 타입 정의
export type VendorData = typeof vendors.$inferInsert;
/**
* MDG 벤더 마스터 데이터를 비즈니스 테이블 vendors에 매핑하여 저장
*/
export async function mapAndSaveMDGVendorData(
vndrCodes: string[]
): Promise<{ success: boolean; message: string; processedCount: number }> {
try {
debugLog('MDG 벤더 마스터 데이터 매핑 시작', { count: vndrCodes.length });
if (vndrCodes.length === 0) {
return { success: true, message: '처리할 데이터가 없습니다', processedCount: 0 };
}
// MDG 수신테이블에서 데이터 조회
const mdgVendorDataList = await fetchMDGVendorData(vndrCodes);
if (mdgVendorDataList.length === 0) {
return { success: false, message: 'MDG 수신테이블에서 데이터를 찾을 수 없습니다', processedCount: 0 };
}
const mappedVendors: VendorData[] = [];
let processedCount = 0;
for (const mdgVendorData of mdgVendorDataList) {
try {
debugLog('벤더 매핑 시작', { vndrCode: mdgVendorData.VNDRCD });
// MDG 데이터를 vendors 테이블 구조에 매핑
const mappedVendor = mapMDGToVendor(mdgVendorData);
if (mappedVendor) {
mappedVendors.push(mappedVendor);
processedCount++;
debugSuccess('벤더 매핑 성공 및 저장 대기열 추가', {
vndrCode: mdgVendorData.VNDRCD,
vendorName: mappedVendor.vendorName
});
} else {
debugWarn('벤더 매핑 실패 - null 반환', {
vndrCode: mdgVendorData.VNDRCD
});
}
} catch (error) {
debugError('개별 벤더 매핑 중 오류', {
vndrCode: mdgVendorData.VNDRCD,
error: error instanceof Error ? error.message : 'Unknown error'
});
// 개별 오류는 로그만 남기고 계속 진행
continue;
}
}
if (mappedVendors.length === 0) {
return { success: false, message: '매핑된 벤더가 없습니다', processedCount: 0 };
}
// 데이터베이스에 저장
await saveVendorsToDatabase(mappedVendors);
debugSuccess('MDG 벤더 마스터 데이터 매핑 완료', {
total: vndrCodes.length,
processed: processedCount
});
return {
success: true,
message: `${processedCount}개 벤더 매핑 및 저장 완료`,
processedCount
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
debugError('MDG 벤더 마스터 데이터 매핑 중 오류 발생', { error: errorMessage });
return {
success: false,
message: `매핑 실패: ${errorMessage}`,
processedCount: 0
};
}
}
/**
* MDG 수신테이블에서 벤더 데이터 조회
* 여러 테이블을 조인하여 매핑에 필요한 모든 데이터를 수집
*/
async function fetchMDGVendorData(vndrCodes: string[]): Promise<MDGVendorData[]> {
try {
debugLog('MDG 수신테이블에서 벤더 데이터 조회 시작', { vndrCodes });
const vendorDataList: MDGVendorData[] = [];
for (const vndrCode of vndrCodes) {
try {
debugLog('MDG 테이블 조회 시작', { vndrCode });
// 1. BP_VENGEN 테이블에서 기본 벤더 정보 조회
const bpVengenData = await db
.select()
.from(VENDOR_MASTER_BP_HEADER_BP_VENGEN)
.where(eq(VENDOR_MASTER_BP_HEADER_BP_VENGEN.VNDRCD, vndrCode))
.limit(1);
debugLog('BP_VENGEN 조회 완료', {
vndrCode,
found: bpVengenData.length > 0,
data: bpVengenData[0] || null
});
if (bpVengenData.length === 0) {
debugError('BP_VENGEN 데이터가 없음', { vndrCode });
continue;
}
const vengenData = bpVengenData[0];
// 2. BP_TAXNUM 테이블에서 사업자번호 조회
const bpTaxnumData = await db
.select()
.from(VENDOR_MASTER_BP_HEADER_BP_TAXNUM)
.where(eq(VENDOR_MASTER_BP_HEADER_BP_TAXNUM.VNDRCD, vndrCode))
.limit(1);
debugLog('BP_TAXNUM 조회 완료 (상세)', {
vndrCode,
found: bpTaxnumData.length > 0,
taxId: bpTaxnumData[0]?.BIZ_PTNR_TX_NO || null,
TX_NO_CTG: bpTaxnumData[0]?.TX_NO_CTG || null,
rawData: bpTaxnumData[0] || null
});
// 3. BP_POSTAL 테이블에서 주소 정보 조회
const bpPostalData = await db
.select()
.from(VENDOR_MASTER_BP_HEADER_ADDRESS_AD_POSTAL)
.where(eq(VENDOR_MASTER_BP_HEADER_ADDRESS_AD_POSTAL.VNDRCD, vndrCode))
.limit(1);
debugLog('BP_POSTAL 조회 완료', {
vndrCode,
found: bpPostalData.length > 0,
vendorName: bpPostalData[0]?.VNDRNM_1 || null
});
// 4. BP_ADDRESS_AD_TEL 테이블에서 전화번호 조회 (첫 번째만)
const bpTelData = await db
.select()
.from(VENDOR_MASTER_BP_HEADER_ADDRESS_AD_TEL)
.where(eq(VENDOR_MASTER_BP_HEADER_ADDRESS_AD_TEL.VNDRCD, vndrCode))
.limit(1);
debugLog('BP_TEL 조회 완료', {
vndrCode,
found: bpTelData.length > 0,
phone: bpTelData[0]?.TELNO || null
});
// 5. BP_ADDRESS_AD_EMAIL 테이블에서 이메일 조회 (첫 번째만)
const bpEmailData = await db
.select()
.from(VENDOR_MASTER_BP_HEADER_ADDRESS_AD_EMAIL)
.where(eq(VENDOR_MASTER_BP_HEADER_ADDRESS_AD_EMAIL.VNDRCD, vndrCode))
.limit(1);
debugLog('BP_EMAIL 조회 완료', {
vndrCode,
found: bpEmailData.length > 0,
email: bpEmailData[0]?.EMAIL_ADR || null
});
// 6. BP_ADDRESS_AD_URL 테이블에서 웹사이트 조회 (첫 번째만)
const bpUrlData = await db
.select()
.from(VENDOR_MASTER_BP_HEADER_ADDRESS_AD_URL)
.where(eq(VENDOR_MASTER_BP_HEADER_ADDRESS_AD_URL.VNDRCD, vndrCode))
.limit(1);
debugLog('BP_URL 조회 완료', {
vndrCode,
found: bpUrlData.length > 0,
url: bpUrlData[0]?.URL || null
});
// 데이터 병합
const mdgVendorData: MDGVendorData = {
VNDRCD: vndrCode,
VNDRNM_1: bpPostalData[0]?.VNDRNM_1 || undefined, // BP_POSTAL 테이블에서 벤더명 조회
BIZ_PTNR_TX_NO: bpTaxnumData[0]?.BIZ_PTNR_TX_NO || undefined,
ETC_ADR_1: bpPostalData[0]?.ETC_ADR_1 || undefined,
ADR_1: bpPostalData[0]?.ADR_1 || undefined,
ADR_2: bpPostalData[0]?.ADR_2 || undefined,
CITY_ZIP_NO: bpPostalData[0]?.CITY_ZIP_NO || undefined,
NTN_CD: bpPostalData[0]?.NTN_CD || undefined,
TEL_NO: bpTelData[0]?.TELNO || undefined,
EMAIL_ADR: bpEmailData[0]?.EMAIL_ADR || undefined,
URL: bpUrlData[0]?.URL || undefined,
REPR_NM: vengenData.REPR_NM || undefined,
REPR_RESNO: vengenData.REPR_RESNO || undefined,
REPR_EMAIL: bpEmailData[0]?.EMAIL_ADR || undefined, // email과 동일한 값 사용
REP_TEL_NO: vengenData.REP_TEL_NO || undefined,
CO_REG_NO: vengenData.CO_REG_NO || undefined,
CO_VLM: vengenData.CO_VLM || undefined,
};
debugSuccess('MDG 벤더 데이터 병합 완료 (상세)', {
vndrCode,
hasVendorName: !!mdgVendorData.VNDRNM_1,
hasTaxId: !!mdgVendorData.BIZ_PTNR_TX_NO,
taxId: mdgVendorData.BIZ_PTNR_TX_NO, // ⚠️ 사업자번호
representativeBirth: mdgVendorData.REPR_RESNO, // ⚠️ 대표자 주민번호
mergedData: mdgVendorData
});
vendorDataList.push(mdgVendorData);
} catch (error) {
debugError('개별 벤더 데이터 조회 중 오류', { vndrCode, error });
continue;
}
}
debugSuccess('MDG 수신테이블에서 벤더 데이터 조회 완료', {
requested: vndrCodes.length,
found: vendorDataList.length
});
return vendorDataList;
} catch (error) {
debugError('MDG 벤더 데이터 조회 중 오류', { error });
throw error;
}
}
/**
* MDG 벤더 데이터를 비즈니스 테이블 vendors 구조로 변환
*
* vendors 테이블 구조:
* - id: serial (자동)
* - vendorName: varchar (필수)
* - vendorCode: varchar
* - taxId: varchar (nullable - MDG에서 없이 수신될 수 있음)
* - address: text
* - addressDetail: text
* - postalCode: varchar
* - country: varchar
* - phone: varchar
* - email: varchar
* - website: varchar
* - status: varchar (기본값 'ACTIVE')
* - vendorTypeId: integer (null 허용)
* - representativeName: varchar
* - representativeBirth: varchar
* - representativeEmail: varchar
* - representativePhone: varchar
* - representativeWorkExpirence: boolean (기본값 false)
* - corporateRegistrationNumber: varchar
* - businessSize: varchar
* - createdAt: timestamp (자동)
* - updatedAt: timestamp (자동)
*/
function mapMDGToVendor(mdgVendorData: MDGVendorData): VendorData | null {
try {
debugLog('MDG 벤더 데이터 상세', {
vndrCode: mdgVendorData.VNDRCD,
vendorName: mdgVendorData.VNDRNM_1,
taxId: mdgVendorData.BIZ_PTNR_TX_NO,
fullData: mdgVendorData
});
// 필수 필드 검증
if (!mdgVendorData.VNDRCD) {
debugError('VNDRCD가 없는 벤더 데이터', { data: mdgVendorData });
return null;
}
// vendorName이 없으면 처리하지 않음 (vendors 테이블에서 필수)
if (!mdgVendorData.VNDRNM_1) {
debugError('VNDRNM_1이 없는 벤더 데이터', {
vndrCode: mdgVendorData.VNDRCD,
reason: '필수 필드 누락: vendorName'
});
return null;
}
// taxId가 없는 경우 경고 로그만 출력 (nullable이므로 처리 계속)
if (!mdgVendorData.BIZ_PTNR_TX_NO) {
debugWarn('BIZ_PTNR_TX_NO가 없는 벤더 데이터 - taxId null로 저장됨', {
vndrCode: mdgVendorData.VNDRCD
});
}
debugSuccess('필수 필드 검증 통과', {
vndrCode: mdgVendorData.VNDRCD,
vendorName: mdgVendorData.VNDRNM_1,
taxId: mdgVendorData.BIZ_PTNR_TX_NO || 'null'
});
// 주소 상세 정보 결합
const addressDetail = [mdgVendorData.ADR_1, mdgVendorData.ADR_2]
.filter(Boolean)
.join(' ')
.trim() || undefined;
// 대표자 생년월일 처리 (앞 6자리만)
const representativeBirth = mdgVendorData.REPR_RESNO
? mdgVendorData.REPR_RESNO.substring(0, 6)
: undefined;
debugLog('⚠️ 필드 매핑 상세 (문제2 확인용)', {
vndrCode: mdgVendorData.VNDRCD,
'BIZ_PTNR_TX_NO(사업자번호 원본)': mdgVendorData.BIZ_PTNR_TX_NO,
'REPR_RESNO(대표자주민번호 원본)': mdgVendorData.REPR_RESNO,
'taxId(매핑될 사업자번호)': mdgVendorData.BIZ_PTNR_TX_NO,
'representativeBirth(매핑될 대표자생년월일)': representativeBirth,
});
const mappedVendor: VendorData = {
vendorCode: mdgVendorData.VNDRCD,
vendorName: mdgVendorData.VNDRNM_1,
taxId: mdgVendorData.BIZ_PTNR_TX_NO, // ⚠️ 사업자번호 (BIZ_PTNR_TX_NO에서 가져옴)
address: mdgVendorData.ETC_ADR_1 || undefined,
addressDetail: addressDetail,
postalCode: mdgVendorData.CITY_ZIP_NO || undefined,
country: mdgVendorData.NTN_CD || undefined,
phone: mdgVendorData.TEL_NO || undefined,
email: mdgVendorData.EMAIL_ADR || undefined,
website: mdgVendorData.URL || undefined,
status: 'ACTIVE', // 매핑 규칙에 따라 항상 'ACTIVE'
vendorTypeId: undefined, // 매핑 규칙에 따라 null
representativeName: mdgVendorData.REPR_NM || undefined,
representativeBirth: representativeBirth, // ⚠️ 대표자 생년월일 (REPR_RESNO에서 가져옴)
representativeEmail: mdgVendorData.REPR_EMAIL || undefined, // email과 동일한 값
representativePhone: mdgVendorData.REP_TEL_NO || undefined,
representativeWorkExpirence: undefined, // 매핑 규칙에 따라 null
corporateRegistrationNumber: mdgVendorData.CO_REG_NO || undefined,
businessSize: mdgVendorData.CO_VLM || undefined,
// id, createdAt, updatedAt는 자동 생성
};
debugLog('벤더 매핑 완료 - 매핑된 데이터 상세', {
vndrCode: mdgVendorData.VNDRCD,
taxId: mappedVendor.taxId,
representativeBirth: mappedVendor.representativeBirth,
mappedVendor: mappedVendor
});
return mappedVendor;
} catch (error) {
debugError('벤더 매핑 중 오류', {
vndrCode: mdgVendorData.VNDRCD,
error: error instanceof Error ? error.message : 'Unknown error'
});
return null;
}
}
/**
* 매핑된 벤더 데이터를 데이터베이스에 저장
*
* 수정사항:
* - vendorCode뿐만 아니라 taxId(사업자번호)로도 기존 벤더 검색
* - MDG에서 vendorCode를 최초로 받는 경우, taxId로 매칭하여 기존 벤더에 vendorCode 업데이트
*/
async function saveVendorsToDatabase(mappedVendors: VendorData[]): Promise<void> {
try {
debugLog('벤더 데이터베이스 저장 시작', { count: mappedVendors.length });
let insertCount = 0;
let updateCount = 0;
let errorCount = 0;
await db.transaction(async (tx) => {
// 기존 데이터와 중복 체크 및 UPSERT
for (const vendor of mappedVendors) {
try {
debugLog('벤더 저장 시도', {
vendorCode: vendor.vendorCode,
taxId: vendor.taxId,
vendorName: vendor.vendorName
});
let existingVendor: { id: number; vendorCode: string | null; taxId: string | null }[] = [];
// 1차: vendorCode로 기존 벤더 검색
if (vendor.vendorCode) {
existingVendor = await tx
.select({ id: vendors.id, vendorCode: vendors.vendorCode, taxId: vendors.taxId })
.from(vendors)
.where(eq(vendors.vendorCode, vendor.vendorCode))
.limit(1);
debugLog('1차: vendorCode로 기존 벤더 조회', {
vendorCode: vendor.vendorCode,
found: existingVendor.length > 0
});
}
// 2차: vendorCode로 못 찾았고 taxId가 있으면, taxId로 검색
if (existingVendor.length === 0 && vendor.taxId) {
existingVendor = await tx
.select({ id: vendors.id, vendorCode: vendors.vendorCode, taxId: vendors.taxId })
.from(vendors)
.where(eq(vendors.taxId, vendor.taxId))
.limit(1);
debugLog('2차: taxId로 기존 벤더 조회', {
taxId: vendor.taxId,
found: existingVendor.length > 0,
existingVendorCode: existingVendor.length > 0 ? existingVendor[0].vendorCode : null
});
if (existingVendor.length > 0 && !existingVendor[0].vendorCode && vendor.vendorCode) {
debugSuccess('기존 벤더에 MDG vendorCode 매핑 발견 (taxId 매칭)', {
taxId: vendor.taxId,
newVendorCode: vendor.vendorCode,
existingId: existingVendor[0].id
});
}
}
// 3차: vendorName AND country로 검색
if (existingVendor.length === 0 && vendor.vendorName && vendor.country) {
existingVendor = await tx
.select({ id: vendors.id, vendorCode: vendors.vendorCode, taxId: vendors.taxId })
.from(vendors)
.where(
and(
eq(vendors.vendorName, vendor.vendorName),
eq(vendors.country, vendor.country)
)
)
.limit(1);
debugLog('3차: vendorName + country로 기존 벤더 조회', {
vendorName: vendor.vendorName,
country: vendor.country,
found: existingVendor.length > 0,
existingVendorCode: existingVendor.length > 0 ? existingVendor[0].vendorCode : null,
existingTaxId: existingVendor.length > 0 ? existingVendor[0].taxId : null
});
if (existingVendor.length > 0) {
debugSuccess('기존 벤더 매칭 발견 (이름+국가 매칭)', {
vendorName: vendor.vendorName,
country: vendor.country,
newVendorCode: vendor.vendorCode || 'null',
newTaxId: vendor.taxId || 'null',
existingId: existingVendor[0].id
});
}
}
if (existingVendor.length > 0) {
// 기존 데이터 업데이트
debugLog('기존 벤더 업데이트 시작', {
existingId: existingVendor[0].id,
vendorCode: vendor.vendorCode,
taxId: vendor.taxId
});
await tx
.update(vendors)
.set({
vendorCode: vendor.vendorCode, // ⚠️ MDG에서 최초로 vendorCode를 받는 경우 업데이트
vendorName: vendor.vendorName,
taxId: vendor.taxId,
address: vendor.address,
addressDetail: vendor.addressDetail,
postalCode: vendor.postalCode,
country: vendor.country,
phone: vendor.phone,
email: vendor.email,
website: vendor.website,
status: vendor.status,
representativeName: vendor.representativeName,
representativeBirth: vendor.representativeBirth,
representativeEmail: vendor.representativeEmail,
representativePhone: vendor.representativePhone,
corporateRegistrationNumber: vendor.corporateRegistrationNumber,
businessSize: vendor.businessSize,
updatedAt: new Date(),
})
.where(eq(vendors.id, existingVendor[0].id));
updateCount++;
debugSuccess('벤더 업데이트 완료', {
id: existingVendor[0].id,
vendorCode: vendor.vendorCode,
taxId: vendor.taxId,
vendorName: vendor.vendorName
});
} else {
// 새 데이터 삽입
debugLog('신규 벤더 삽입 시작', {
vendorCode: vendor.vendorCode,
taxId: vendor.taxId,
vendorData: vendor
});
await tx.insert(vendors).values(vendor);
insertCount++;
debugSuccess('벤더 삽입 완료', {
vendorCode: vendor.vendorCode,
taxId: vendor.taxId,
vendorName: vendor.vendorName
});
}
} catch (vendorError) {
errorCount++;
debugError('개별 벤더 저장 중 오류', {
vendorCode: vendor.vendorCode,
vendorName: vendor.vendorName,
error: vendorError instanceof Error ? vendorError.message : 'Unknown error',
stack: vendorError instanceof Error ? vendorError.stack : undefined
});
// 개별 벤더 저장 실패 시 전체 트랜잭션을 롤백하도록 오류를 다시 던짐
throw vendorError;
}
}
});
debugSuccess('벤더 데이터베이스 저장 완료', {
total: mappedVendors.length,
inserted: insertCount,
updated: updateCount,
errors: errorCount
});
} catch (error) {
debugError('벤더 데이터베이스 저장 중 오류', {
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : undefined
});
throw error;
}
}
|