summaryrefslogtreecommitdiff
path: root/lib/soap/ecc/mapper/bidding-and-pr-mapper.ts
blob: 4ab9a745a0e897aa3a62d6a72cb88d1fc4b482e5 (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
/**
 * SAP ECC에서 PR을 묶어 Bidding을 생성한 경우 SOAP으로 수신하여 처리하는 매퍼
 * 
 * ZBSART = AB (Bidding)인 경우 이 파일에서 처리하여 biddings, prItemsForBidding 테이블에 매핑합니다.
 * ZBSART = AN (RFQ)인 경우는 rfq-and-pr-mapper.ts 파일에서 매핑합니다.
 * 
 * 주요 변경사항:
 * - POS 파일 자동 다운로드 로직 제거됨 (온디맨드 방식으로 변경)
 * - syncBiddingPosFiles 함수 제거됨
 * - 사용자가 필요할 때만 POS 파일을 다운로드하도록 개선
 */

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, eq } from 'drizzle-orm';
import {
  findUserInfoByEKGRP,
  findProjectInfoByPSPID,
  findProjectIdByPSPID,
  findMaterialNameByMATNR,
  parseSAPDateTime,
  parseSAPDateToString,
} from './common-mapper-utils';
// Note: POS 파일은 온디맨드 방식으로 다운로드됩니다.
// 자동 동기화 관련 import는 제거되었습니다.

// 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;

// Note: syncBiddingPosFiles 함수는 제거되었습니다.
// POS 파일은 온디맨드 방식으로 사용자가 필요할 때 다운로드됩니다.


/**
 * 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 기반으로 projectName, itemName 설정
  let projectName: string | null = null;
  let itemName: string | null = null;
  let prNumber: string | null = null;
  
  if (firstItem) {
    // projectName: 첫번째 PR Item의 PSPID와 projects.code 매칭
    const projectInfo = await findProjectInfoByPSPID(firstItem.PSPID || null);
    if (projectInfo) {
      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 고정)
    projectName, // 첫번째 PR Item의 PSPID로 찾은 프로젝트 이름
    itemName, // 첫번째 PR Item의 MATNR로 조회한 자재명
    title: `${firstItem?.PSPID || ''}${itemName || ''}입찰`, // PSPID+자재그룹명+계약구분+입찰, 계약구분은 없으니까 제외했음
    description: 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 기반으로 설정 (입찰담당자로 매핑)
    bidPicId: inChargeUserInfo?.userId || null,
    bidPicName: inChargeUserInfo?.userName || 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 async function mapECCBiddingItemToPrItemForBidding(
  eccItem: ECCBidItem,
  biddingId: number
): Promise<PrItemForBiddingData> {
  debugLog('ECC Bidding 아이템 매핑 시작', {
    anfnr: eccItem.ANFNR,
    anfps: eccItem.ANFPS,
  });

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

  // PSPID(Project Code)로 프로젝트 ID 조회
  const projectId = await findProjectIdByPSPID(eccItem.PSPID || null);

  const mappedData: PrItemForBiddingData = {
    biddingId, // 부모 Bidding ID
    itemNumber: eccItem.ANFPS || null, // 아이템 번호
    projectId, // PSSID로 조회한 프로젝트 ID
    projectInfo: eccItem.PSPID || null, // 프로젝트 정보 (PSPID)
    itemInfo: eccItem.TXZ01 || null, // 품목정보 (자재 설명)
    shi: null, // ECC에서 제공되지 않음
    
    // 자재 그룹 정보
    materialGroupNumber: eccItem.MATKL || null, // 자재그룹번호 (Material Group Code)
    materialGroupInfo: null, // ECC에서 제공되지 않음
    
    // 자재 정보
    materialNumber: eccItem.MATNR || null, // 자재번호 (Material Number)
    materialInfo: eccItem.TXZ01 || null, // 자재정보 (Material Description)
    
    requestedDeliveryDate, // 납품요청일
    annualUnitPrice: null, // ECC에서 제공되지 않음
    currency: eccItem.WAERS1 || null, // 기본 통화
    quantity: eccItem.MENGE || null, // 수량
    quantityUnit: eccItem.MEINS || null, // 수량단위
    totalWeight: eccItem.BRGEW || null, // 총중량
    weightUnit: eccItem.GEWEI || null, // 중량단위
    
    // WBS 정보
    wbsCode: eccItem.POSID || null, // WBS No
    wbsName: null, // ECC에서 제공되지 않음
    
    // Cost Center 정보
    costCenterCode: eccItem.KOSTL || null, // Cost Center
    costCenterName: null, // ECC에서 제공되지 않음
    
    // GL Account 정보
    glAccountCode: eccItem.SAKTO || null, // G/L Account Number
    glAccountName: null, // ECC에서 제공되지 않음
    
    prNumber: eccItem.BANFN || null, // PR번호
    hasSpecDocument: false, // 기본값 false
  };

  debugSuccess('ECC Bidding 아이템 매핑 완료', {
    itemNumber: eccItem.ANFPS,
    prNumber: eccItem.BANFN,
    projectId,
  });
  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}`);
        }

        // 각 아이템을 병렬로 매핑 (async 함수로 변경되었으므로)
        const itemsData = await Promise.all(
          group.relatedItems.map(eccItem => 
            mapECCBiddingItemToPrItemForBidding(eccItem, biddingId)
          )
        );
        allItemsToInsert.push(...itemsData);
      }

      // 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,
    });

    // Note: POS 파일은 온디맨드 방식으로 사용자가 필요할 때 다운로드됩니다.
    // 자동 다운로드는 더 이상 수행하지 않습니다.

    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,
    };
  }
}