summaryrefslogtreecommitdiff
path: root/lib/soap/ecc/mapper/bidding-and-pr-mapper.ts
blob: 5f3c7e788f565169e6cb3246b3f4397396617ac4 (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
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
/**
 * pr 발행 후, pr을 묶어서 rfq, bidding 을 sap ecc에서 생성한 경우
 * ZBSART = AB인 경우, 즉 bidding인 경우 해당 케이스를 soap으로 수신한 뒤 이 함수에서 헤더는 biddings 테이블에, 아이템은 prItemsForBidding 테이블에 매핑
 * ZBSART = AN인 경우, 즉 rfq인 경우 해당 케이스를 soap으로 수신한 뒤 rfq-and-pr-mapper.ts 파일에서 매핑
 */

import { debugLog, debugSuccess, debugError } from '@/lib/debug-utils';
import db from '@/db/db';
import {
  biddings,
  prItemsForBidding,
  prDocuments,
} from '@/db/schema/bidding';
import {
  PR_INFORMATION_T_BID_HEADER,
  PR_INFORMATION_T_BID_ITEM,
} from '@/db/schema/ECC/ecc';
import { inArray, max, sql } from 'drizzle-orm';
import {
  findUserInfoByEKGRP,
  findProjectInfoByPSPID,
  findMaterialNameByMATNR,
  parseSAPDateTime,
  parseSAPDateToString,
} from './common-mapper-utils';
import { 
  getDcmtmIdByMaterialCode, 
  getEncryptDocumentumFile, 
  downloadPosFile 
} from '@/lib/pos';

// ECC 데이터 타입 정의
export type ECCBidHeader = typeof PR_INFORMATION_T_BID_HEADER.$inferInsert;
export type ECCBidItem = typeof PR_INFORMATION_T_BID_ITEM.$inferInsert;

// 비즈니스 테이블 데이터 타입 정의
export type BiddingData = typeof biddings.$inferInsert;
export type PrItemForBiddingData = typeof prItemsForBidding.$inferInsert;

/**
 * Bidding용 POS 파일 동기화 함수
 * 자재코드 기준으로 POS 파일을 찾아서 prDocuments 테이블에 저장
 */
async function syncBiddingPosFiles(
  biddingId: number,
  materialCodes: string[],
  userId: string = '1'
): Promise<{
  success: boolean;
  successCount: number;
  failedCount: number;
  errors: string[];
}> {
  debugLog('Bidding POS 파일 동기화 시작', { biddingId, materialCodes });
  
  let successCount = 0;
  let failedCount = 0;
  const errors: string[] = [];
  
  // 중복 제거된 자재코드로 처리
  const uniqueMaterialCodes = [...new Set(materialCodes.filter(code => code && code.trim() !== ''))];
  
  for (const materialCode of uniqueMaterialCodes) {
    try {
      debugLog(`자재코드 ${materialCode} POS 파일 조회 시작`);
      
      // 1. 자재코드로 DCMTM_ID 조회
      const dcmtmResult = await getDcmtmIdByMaterialCode({ materialCode });
      
      if (!dcmtmResult.success || !dcmtmResult.files || dcmtmResult.files.length === 0) {
        debugLog(`자재코드 ${materialCode}: POS 파일 없음`);
        continue; // 에러로 카운트하지 않고 스킵
      }
      
      // 첫 번째 파일만 처리
      const posFile = dcmtmResult.files[0];
      
      // 2. POS API로 파일 경로 가져오기
      const posResult = await getEncryptDocumentumFile({
        objectID: posFile.dcmtmId
      });
      
      if (!posResult.success || !posResult.result) {
        errors.push(`${materialCode}: POS 파일 경로 조회 실패`);
        failedCount++;
        continue;
      }
      
      // 3. 파일 다운로드
      const downloadResult = await downloadPosFile({
        relativePath: posResult.result
      });
      
      if (!downloadResult.success || !downloadResult.fileBuffer) {
        errors.push(`${materialCode}: 파일 다운로드 실패`);
        failedCount++;
        continue;
      }
      
      // 4. 서버에 파일 저장 (uploads/bidding-pos 디렉토리)
      const path = await import('path');
      const fs = await import('fs/promises');
      
      const uploadDir = path.join(process.cwd(), 'uploads', 'bidding-pos');
      try {
        await fs.access(uploadDir);
      } catch {
        await fs.mkdir(uploadDir, { recursive: true });
      }
      
      const timestamp = Date.now();
      const sanitizedFileName = (downloadResult.fileName || `${materialCode}.pdf`).replace(/[^a-zA-Z0-9.-]/g, '_');
      const fileName = `${timestamp}_${sanitizedFileName}`;
      const filePath = path.join(uploadDir, fileName);
      
      await fs.writeFile(filePath, downloadResult.fileBuffer);
      
      // 5. prDocuments 테이블에 저장
      await db.insert(prDocuments).values({
        biddingId,
        documentName: `${materialCode} 설계문서`,
        fileName,
        originalFileName: posFile.fileName,
        fileSize: downloadResult.fileBuffer.length,
        mimeType: downloadResult.mimeType || 'application/pdf',
        filePath: `uploads/bidding-pos/${fileName}`,
        registeredBy: userId,
        description: `POS 시스템에서 자동 동기화됨 (DCMTM_ID: ${posFile.dcmtmId}, 자재코드: ${materialCode})`,
        version: 'Rev.0'
      });
      
      successCount++;
      debugSuccess(`자재코드 ${materialCode} POS 파일 동기화 완료`);
      
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '알 수 없는 오류';
      errors.push(`${materialCode}: ${errorMessage}`);
      failedCount++;
      debugError(`자재코드 ${materialCode} POS 파일 동기화 실패`, error);
    }
  }
  
  return {
    success: successCount > 0,
    successCount,
    failedCount,
    errors
  };
}


/**
 * Bidding 코드 생성 함수 (배치 처리용)
 * 형식: BID{EKGRP}{00001}
 * 기존 ANFNR은 기존 biddingNumber 사용, 새로운 ANFNR만 새 코드 생성
 */
async function generateBiddingCodes(eccHeaders: ECCBidHeader[]): Promise<Map<string, string>> {
  try {
    debugLog('Bidding 코드 배치 생성 시작', { headerCount: eccHeaders.length });
    
    const biddingCodeMap = new Map<string, string>();
    
    // 1) 먼저 기존 ANFNR들의 biddingNumber 조회
    const anfnrList = eccHeaders.map(h => h.ANFNR).filter(Boolean);
    if (anfnrList.length > 0) {
      const existingResult = await db
        .select({ 
          ANFNR: biddings.ANFNR, 
          biddingNumber: biddings.biddingNumber 
        })
        .from(biddings)
        .where(inArray(biddings.ANFNR, anfnrList));

      // 기존 ANFNR들의 biddingNumber 매핑
      for (const row of existingResult) {
        if (row.ANFNR && row.biddingNumber) {
          biddingCodeMap.set(row.ANFNR, row.biddingNumber);
        }
      }
    }
    
    // 2) 새로운 ANFNR들만 필터링 (기존에 없는 것들)
    const newHeaders = eccHeaders.filter(header => 
      header.ANFNR && !biddingCodeMap.has(header.ANFNR)
    );
    
    if (newHeaders.length === 0) {
      debugSuccess('모든 ANFNR이 기존에 존재함', { 
        totalCodes: biddingCodeMap.size 
      });
      return biddingCodeMap;
    }
    
    // 3) 새로운 ANFNR들을 EKGRP별로 그룹핑
    const ekgrpGroups = new Map<string, ECCBidHeader[]>();
    for (const header of newHeaders) {
      const ekgrp = header.EKGRP || 'UNKNOWN';
      if (!ekgrpGroups.has(ekgrp)) {
        ekgrpGroups.set(ekgrp, []);
      }
      ekgrpGroups.get(ekgrp)!.push(header);
    }
    
    // 4) EKGRP별로 새 코드 생성
    for (const [ekgrp, headers] of ekgrpGroups) {
      // 해당 EKGRP의 현재 최대 시퀀스 조회
      const maxResult = await db
        .select({ 
          maxBiddingNumber: max(biddings.biddingNumber)
        })
        .from(biddings)
        .where(sql`${biddings.biddingNumber} LIKE ${`B${ekgrp}%`}`);

      let nextSeq = 1;
      if (maxResult[0]?.maxBiddingNumber) {
        const prefix = `B${ekgrp}`;
        const currentCode = maxResult[0].maxBiddingNumber;
        if (currentCode.startsWith(prefix)) {
          const seqPart = currentCode.substring(prefix.length);
          const currentSeq = parseInt(seqPart, 10);
          if (!isNaN(currentSeq)) {
            nextSeq = currentSeq + 1;
          }
        }
      }
      
      // 동일 EKGRP 내에서 순차적으로 새 코드 생성
      for (const header of headers) {
        const seqString = nextSeq.toString().padStart(5, '0');
        const biddingCode = `B${ekgrp}${seqString}`;
        biddingCodeMap.set(header.ANFNR || '', biddingCode);
        nextSeq++; // 다음 시퀀스로 증가
      }
    }
    
    debugSuccess('Bidding 코드 배치 생성 완료', { 
      totalCodes: biddingCodeMap.size,
      newCodes: newHeaders.length,
      existingCodes: eccHeaders.length - newHeaders.length
    });
    return biddingCodeMap;
  } catch (error) {
    debugError('Bidding 코드 배치 생성 중 오류 발생', { error });
    
    // 오류 발생시 폴백: ANFNR 기반 코드 생성
    const fallbackMap = new Map<string, string>();
    eccHeaders.forEach((header, index) => {
      const ekgrp = header.EKGRP || 'UNKNOWN';
      const seqString = (index + 1).toString().padStart(5, '0');
      fallbackMap.set(header.ANFNR, `B${ekgrp}${seqString}`);
    });
    return fallbackMap;
  }
}



// *****************************mapping functions*********************************

/**
 * ECC Bidding 헤더 데이터를 biddings 테이블로 매핑
 */
export async function mapECCBiddingHeaderToBidding(
  eccHeader: ECCBidHeader,
  eccItems: ECCBidItem[],
  biddingNumber: string
): Promise<BiddingData> {
  debugLog('ECC Bidding 헤더 매핑 시작', { anfnr: eccHeader.ANFNR, biddingNumber });

  // 첫번째 PR Item 가져오기 (관련 아이템들 중 첫번째)
  const firstItem = eccItems.find(item => item.ANFNR === eccHeader.ANFNR);
  
  // 날짜 파싱 (실패시 현재 Date 들어감)
  const createdAt = parseSAPDateTime(eccHeader.ZRFQ_TRS_DT || null, eccHeader.ZRFQ_TRS_TM || null);

  // 담당자 찾기
  const inChargeUserInfo = await findUserInfoByEKGRP(eccHeader.EKGRP || null);

  // 첫번째 PR Item 기반으로 projectId, projectName, itemName 설정
  let projectId: number | null = null;
  let projectName: string | null = null;
  let itemName: string | null = null;
  let prNumber: string | null = null;
  
  if (firstItem) {
    // projectId, projectName: 첫번째 PR Item의 PSPID와 projects.code 매칭
    const projectInfo = await findProjectInfoByPSPID(firstItem.PSPID || null);
    if (projectInfo) {
      projectId = projectInfo.id;
      projectName = projectInfo.name;
    }
    
    // itemName: 첫번째 PR Item의 MATNR로 MDG에서 ZZNAME 조회
    itemName = await findMaterialNameByMATNR(firstItem.MATNR || null);
    
    // prNumber: 첫번째 PR의 ZREQ_FN 값
    prNumber = firstItem.ZREQ_FN || null;
  }

  // 매핑
  const mappedData: BiddingData = {
    biddingNumber, // 생성된 Bidding 코드
    revision: 0, // 기본 리비전 0 (I/F 해서 가져온 건 보낸 적 없으므로 0 고정)
    projectId, // 첫번째 PR Item의 PSPID로 찾은 프로젝트 ID
    projectName, // 첫번째 PR Item의 PSPID로 찾은 프로젝트 이름
    itemName, // 첫번째 PR Item의 MATNR로 조회한 자재명
    title: `${firstItem?.PSPID || ''}${itemName || ''}입찰`, // PSPID+자재그룹명+계약구분+입찰, 계약구분은 없으니까 제외했음
    description: null,
    content: null,
    
    // 계약 정보 - ECC에서 제공되지 않으므로 기본값 설정
    contractType: 'general', // 일반계약 기본값 (notNull)
    biddingType: 'equipment', // 입찰유형 기본값 (notNull)
    awardCount: 'single', // 낙찰수 기본값 (notNull)
    contractStartDate: null, // ECC에서 제공 X
    contractEndDate: null, // ECC에서 제공 X
    
    // 일정 관리 - ECC에서 제공되지 않음
    preQuoteDate: null,
    biddingRegistrationDate: null,
    submissionStartDate: null,
    submissionEndDate: null,
    evaluationDate: null,
    
    // 사양설명회
    hasSpecificationMeeting: false, // 기본값 처리하고, 입찰관리상세에서 사용자가 관리
    
    // 예산 및 가격 정보
    currency: firstItem?.WAERS1,
    budget: null,
    targetPrice: null,
    targetPriceCalculationCriteria: null,
    finalBidPrice: null,
    
    // PR 정보
    prNumber, // 첫번째 PR의 ZREQ_FN 값
    hasPrDocument: false, // PR문서는 POS를 말하는 것으로 보임.
    
    // 상태 및 설정
    status: 'bidding_generated', // 입찰생성 상태
    isPublic: false,
    
    // 담당자 정보 - EKGRP 기반으로 설정
    managerName: inChargeUserInfo?.userName || null,
    managerEmail: inChargeUserInfo?.userEmail || null,
    managerPhone: inChargeUserInfo?.userPhone || null,
    
    // 메타 정보
    remarks: `ECC ANFNR: ${eccHeader.ANFNR}`,
    createdBy: inChargeUserInfo?.userId?.toString() || '1',
    createdAt,
    updatedAt: createdAt,
    updatedBy: inChargeUserInfo?.userId?.toString() || '1',
    ANFNR: eccHeader.ANFNR, // 원본 ANFNR 추적용
  };

  debugSuccess('ECC Bidding 헤더 매핑 완료', { anfnr: eccHeader.ANFNR, biddingNumber });
  return mappedData;
}

/**
 * ECC Bidding 아이템 데이터를 prItemsForBidding 테이블로 매핑
 */
export function mapECCBiddingItemToPrItemForBidding(
  eccItem: ECCBidItem,
  biddingId: number
): PrItemForBiddingData {
  debugLog('ECC Bidding 아이템 매핑 시작', {
    anfnr: eccItem.ANFNR,
    anfps: eccItem.ANFPS,
  });

  // 날짜 파싱 (YYYY-MM-DD 형식의 문자열로 변환)
  const requestedDeliveryDate = parseSAPDateToString(eccItem.LFDAT || null);

  const mappedData: PrItemForBiddingData = {
    biddingId, // 부모 Bidding ID
    itemNumber: eccItem.ANFPS || null, // 아이템 번호
    projectInfo: eccItem.PSPID || null, // 프로젝트 정보 (PSPID)
    itemInfo: eccItem.TXZ01 || null, // 품목정보 (자재 설명)
    shi: null, // ECC에서 제공되지 않음
    requestedDeliveryDate, // 납품요청일
    annualUnitPrice: null, // ECC에서 제공되지 않음
    currency: eccItem.WAERS1 || null, // 기본 통화
    quantity: eccItem.MENGE || null, // 수량
    quantityUnit: eccItem.MEINS || null, // 수량단위
    totalWeight: eccItem.BRGEW || null, // 총중량
    weightUnit: eccItem.GEWEI || null, // 중량단위
    materialDescription: eccItem.TXZ01 || null, // 자재내역상세
    prNumber: eccItem.BANFN || null, // PR번호
    hasSpecDocument: false, // 기본값 false
  };

  debugSuccess('ECC Bidding 아이템 매핑 완료', {
    itemNumber: eccItem.ANFPS,
    prNumber: eccItem.BANFN,
  });
  return mappedData;
}

/**
 * ECC 데이터를 biddings/prItemsForBidding 테이블로 일괄 매핑 및 저장
 */
export async function mapAndSaveECCBiddingData(
  eccHeaders: ECCBidHeader[],
  eccItems: ECCBidItem[]
): Promise<{ success: boolean; message: string; processedCount: number }> {
  debugLog('ECC Bidding 데이터 일괄 매핑 및 저장 시작', {
    headerCount: eccHeaders.length,
    itemCount: eccItems.length,
  });

  // ANFNR이 없는 헤더들 필터링
  const validHeaders = eccHeaders.filter(header => {
    if (!header.ANFNR) {
      debugError('ANFNR이 없는 헤더 스킵', { header });
      return false;
    }
    return true;
  });

  if (validHeaders.length === 0) {
    debugError('처리할 유효한 헤더가 없음');
    return {
      success: false,
      message: '처리할 유효한 ANFNR이 있는 헤더가 없습니다.',
      processedCount: 0,
    };
  }

  try {
    const result = await db.transaction(async (tx) => {
      // 1) Bidding 코드 배치 생성 (중복 방지) - 유효한 헤더만 사용
      const biddingCodeMap = await generateBiddingCodes(validHeaders);
      
      // 2) 헤더별 관련 아이템 그룹핑 + 헤더 매핑을 병렬로 수행 - 유효한 헤더만 사용
      const biddingGroups = await Promise.all(
        validHeaders.map(async (eccHeader) => {
          const relatedItems = eccItems.filter((item) => item.ANFNR === eccHeader.ANFNR);
          const biddingNumber = biddingCodeMap.get(eccHeader.ANFNR) || `BID${eccHeader.EKGRP || 'UNKNOWN'}00001`;
          // 헤더 매핑 시 아이템 정보와 생성된 Bidding 코드 전달
          const biddingData = await mapECCBiddingHeaderToBidding(eccHeader, relatedItems, biddingNumber);
          return { biddingNumber: biddingData.biddingNumber, biddingData, relatedItems };
        })
      );

      const biddingRecords = biddingGroups.map((g) => g.biddingData);

      // 3) Bidding 다건 삽입
      const inserted = await tx
        .insert(biddings)
        .values(biddingRecords)
        .returning({ 
          id: biddings.id, 
          biddingNumber: biddings.biddingNumber,
          ANFNR: biddings.ANFNR,
          createdBy: biddings.createdBy
        });

      const biddingNumberToId = new Map<string, number>();
      for (const row of inserted) {
        if (row.biddingNumber) {
          biddingNumberToId.set(row.biddingNumber, row.id);
        }
      }

      // 4) 모든 새로 삽입된 레코드의 ID 매핑은 이미 완료됨

      // 5) 모든 아이템을 한 번에 생성할 데이터로 변환
      const allItemsToInsert: PrItemForBiddingData[] = [];
      for (const group of biddingGroups) {
        const biddingNumber = group.biddingNumber;
        if (!biddingNumber) continue;
        const biddingId = biddingNumberToId.get(biddingNumber);
        if (!biddingId) {
          debugError('Bidding ID 매핑 누락', { biddingNumber });
          throw new Error(`Bidding ID를 찾을 수 없습니다: ${biddingNumber}`);
        }

        for (const eccItem of group.relatedItems) {
          const itemData = mapECCBiddingItemToPrItemForBidding(eccItem, biddingId);
          allItemsToInsert.push(itemData);
        }
      }

      // 6) 아이템 일괄 삽입 (chunk 처리로 파라미터 제한 회피)
      const ITEM_CHUNK_SIZE = 1000;
      for (let i = 0; i < allItemsToInsert.length; i += ITEM_CHUNK_SIZE) {
        const chunk = allItemsToInsert.slice(i, i + ITEM_CHUNK_SIZE);
        await tx.insert(prItemsForBidding).values(chunk);
      }

      return { 
        processedCount: biddingRecords.length,
        insertedBiddings: inserted as Array<{ id: number; biddingNumber: string; ANFNR: string | null; createdBy: string | null }>,
        allEccItems: eccItems // POS 동기화를 위해 필요
      };
    });

    debugSuccess('ECC Bidding 데이터 일괄 처리 완료', {
      processedCount: result.processedCount,
    });

    // 7) 각 Bidding에 대해 POS 파일 자동 동기화 (비동기로 실행하여 메인 플로우 블록하지 않음)
    debugLog('Bidding POS 파일 자동 동기화 시작', { biddingCount: result.insertedBiddings.length });
    
    // 비동기로 각 Bidding의 POS 파일 동기화 실행 (결과를 기다리지 않음)
    result.insertedBiddings.forEach(async (bidding) => {
      try {
        // 해당 Bidding과 관련된 모든 자재코드 추출
        const relatedMaterialCodes = result.allEccItems
          .filter(item => item.ANFNR === bidding.ANFNR)
          .map(item => item.MATNR)
          .filter(Boolean) as string[];
        
        if (relatedMaterialCodes.length === 0) {
          debugLog(`Bidding ${bidding.biddingNumber}: 자재코드 없음`);
          return;
        }
        
        debugLog(`Bidding ${bidding.biddingNumber} POS 파일 동기화 시작`, { 
          biddingId: bidding.id, 
          materialCodes: relatedMaterialCodes 
        });
        
        const syncResult = await syncBiddingPosFiles(
          bidding.id, 
          relatedMaterialCodes, 
          bidding.createdBy || '1'
        );
        
        if (syncResult.success) {
          debugSuccess(`Bidding ${bidding.biddingNumber} POS 파일 동기화 완료`, {
            biddingId: bidding.id,
            successCount: syncResult.successCount,
            failedCount: syncResult.failedCount
          });
        } else {
          debugError(`Bidding ${bidding.biddingNumber} POS 파일 동기화 실패`, {
            biddingId: bidding.id,
            errors: syncResult.errors
          });
        }
      } catch (error) {
        debugError(`Bidding ${bidding.biddingNumber} POS 파일 동기화 중 예외 발생`, {
          biddingId: bidding.id,
          error: error instanceof Error ? error.message : '알 수 없는 오류'
        });
      }
    });

    return {
      success: true,
      message: `${result.processedCount}개의 Bidding 데이터가 성공적으로 처리되었습니다.`,
      processedCount: result.processedCount,
    };
  } catch (error) {
    debugError('ECC Bidding 데이터 처리 중 오류 발생', error);
    return {
      success: false,
      message:
        error instanceof Error
          ? error.message
          : '알 수 없는 오류가 발생했습니다.',
      processedCount: 0,
    };
  }
}

/**
 * ECC Bidding 데이터 유효성 검증
 */
export function validateECCBiddingData(
  eccHeaders: ECCBidHeader[],
  eccItems: ECCBidItem[]
): { isValid: boolean; errors: string[] } {
  const errors: string[] = [];

  // 헤더 데이터 검증
  for (const header of eccHeaders) {
    if (!header.ANFNR) {
      errors.push(`필수 필드 누락: ANFNR (Bidding Number)`);
    }
    if (!header.ZBSART) {
      errors.push(
        `필수 필드 누락: ZBSART (Bidding Type) - ANFNR: ${header.ANFNR}`
      );
    }
  }

  // 아이템 데이터 검증
  for (const item of eccItems) {
    if (!item.ANFNR) {
      errors.push(
        `필수 필드 누락: ANFNR (Bidding Number) - Item: ${item.ANFPS}`
      );
    }
    if (!item.ANFPS) {
      errors.push(`필수 필드 누락: ANFPS (Item Number) - ANFNR: ${item.ANFNR}`);
    }
    if (!item.BANFN) {
      errors.push(
        `필수 필드 누락: BANFN (Purchase Requisition Number) - ANFNR: ${item.ANFNR}, ANFPS: ${item.ANFPS}`
      );
    }
    if (!item.BANPO) {
      errors.push(
        `필수 필드 누락: BANPO (Item Number of Purchase Requisition) - ANFNR: ${item.ANFNR}, ANFPS: ${item.ANFPS}`
      );
    }
  }

  // 헤더와 아이템 간의 관계 검증
  const headerAnfnrs = new Set(eccHeaders.map((h) => h.ANFNR));
  const itemAnfnrs = new Set(eccItems.map((i) => i.ANFNR));

  for (const anfnr of itemAnfnrs) {
    if (!headerAnfnrs.has(anfnr)) {
      errors.push(`아이템의 ANFNR이 헤더에 존재하지 않음: ${anfnr}`);
    }
  }

  return {
    isValid: errors.length === 0,
    errors,
  };
}

/**
 * ECC Bidding 데이터를 삭제 (biddings/prItemsForBidding 테이블에서 삭제)
 */
export async function deleteECCBiddingData(
  eccHeaders: ECCBidHeader[]
): Promise<{ success: boolean; message: string; deletedCount: number }> {
  debugLog('ECC Bidding 데이터 삭제 시작', {
    headerCount: eccHeaders.length,
  });

  try {
    const result = await db.transaction(async (tx) => {
      const deletedBiddings: string[] = [];

      for (const eccHeader of eccHeaders) {
        const anfnr = eccHeader.ANFNR;
        if (!anfnr) {
          debugError('삭제할 ANFNR이 없음', { eccHeader });
          continue;
        }

        // 1) 해당 ANFNR의 Bidding 찾기
        const existingBidding = await tx
          .select({ id: biddings.id, biddingNumber: biddings.biddingNumber })
          .from(biddings)
          .where(eq(biddings.ANFNR, anfnr))
          .limit(1);

        if (existingBidding.length === 0) {
          debugLog(`ANFNR ${anfnr}에 해당하는 Bidding이 존재하지 않음`);
          continue;
        }

        const biddingId = existingBidding[0].id;
        const biddingNumber = existingBidding[0].biddingNumber;

        // 2) prItemsForBidding 삭제
        const deletedItems = await tx
          .delete(prItemsForBidding)
          .where(eq(prItemsForBidding.biddingId, biddingId));

        debugLog(`Bidding ${biddingNumber}의 PR 아이템 ${deletedItems.rowCount}개 삭제 완료`);

        // 3) prDocuments 삭제 (POS 파일 관련 문서)
        const deletedDocuments = await tx
          .delete(prDocuments)
          .where(eq(prDocuments.biddingId, biddingId));

        debugLog(`Bidding ${biddingNumber}의 문서 ${deletedDocuments.rowCount}개 삭제 완료`);

        // 4) biddings 삭제
        await tx
          .delete(biddings)
          .where(eq(biddings.id, biddingId));

        deletedBiddings.push(biddingNumber);
        debugLog(`Bidding ${biddingNumber} 삭제 완료`);
      }

      return { deletedBiddings };
    });

    debugSuccess('ECC Bidding 데이터 삭제 완료', {
      deletedCount: result.deletedBiddings.length,
      deletedBiddings: result.deletedBiddings,
    });

    return {
      success: true,
      message: `${result.deletedBiddings.length}개의 Bidding 데이터가 성공적으로 삭제되었습니다.`,
      deletedCount: result.deletedBiddings.length,
    };
  } catch (error) {
    debugError('ECC Bidding 데이터 삭제 중 오류 발생', error);
    return {
      success: false,
      message:
        error instanceof Error
          ? error.message
          : '알 수 없는 오류가 발생했습니다.',
      deletedCount: 0,
    };
  }
}