summaryrefslogtreecommitdiff
path: root/lib/soap/ecc/mapper/common-mapper-utils.ts
blob: 2199490a6684b743b523ca177555f67c242f4e16 (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
/**
 * ECC Mapper 공통 유틸리티 함수들
 * bidding-and-pr-mapper.ts와 rfq-and-pr-mapper.ts에서 공통으로 사용하는 함수들
 * 
 * 1. 담당자 정보 조회 함수: 구매그룹코드로 id, email, phone 반환
 * 2. 프로젝트 정보 조회 함수: 프로젝트 코드로 id, name 반환
 * 3. 자재명 조회 함수: 자재코드로 자재명 반환
 * 4. SAP 날짜/시간 파싱 함수: SAP 날짜/시간 문자열을 JavaScript Date로 변환
 * 5. SAP 날짜를 YYYY-MM-DD 문자열로 변환 함수: SAP 날짜 문자열을 YYYY-MM-DD 문자열로 변환
 * 
 */

import { debugLog, debugSuccess, debugError } from '@/lib/debug-utils';
import db from '@/db/db';
import { users, vendors } from '@/db/schema';
import { projects } from '@/db/schema/projects';
import { EQUP_MASTER_MATL_CHARASGN } from '@/db/schema/MDG/mdg';
import { eq } from 'drizzle-orm';
import { oracleKnex } from '@/lib/oracle-db/db';

/**
 * 담당자 정보 조회 함수 (EKGRP 기반)
 * 
 * 조회 순서:
 * 1. Oracle DB에서 구매그룹코드(EKGRP)로 사번(EMPLOYEE_NUMBER) 조회
 * 2. 사번으로 users 테이블의 employeeNumber와 매칭하여 사용자 정보 조회
 * 3. 폴백: users 테이블의 userCode = EKGRP로 직접 조회
 */
export async function findUserInfoByEKGRP(EKGRP: string | null): Promise<{
  userId: number;
  userName: string;
  userEmail: string | null;
  userPhone: string | null;
} | null> {
  try {
    debugLog('담당자 찾기 시작', { EKGRP });

    if (!EKGRP) {
      debugError('EKGRP가 null 또는 undefined', { EKGRP });
      return null;
    }

    // 1. Oracle DB에서 구매그룹코드로 사번 조회
    try {
      debugLog('Oracle DB에서 구매그룹코드로 사번 조회 시도', { EKGRP });
      
      const oracleResult = await oracleKnex.raw(`
        SELECT 
          CD.USR_DF_CHAR_9 AS EMPLOYEE_NUMBER
        FROM CMCTB_CDNM NM
        JOIN CMCTB_CD CD 
          ON NM.CD_CLF = CD.CD_CLF
          AND NM.CD = CD.CD
          AND NM.CD2 = CD.CD3
        WHERE NM.CD_CLF = 'MMA070'
          AND CD.CD = :ekgrp
          AND CD.DEL_YN != 'Y'
      `, { ekgrp: EKGRP });

      const rows = (oracleResult.rows || oracleResult) as Array<Record<string, unknown>>;
      
      if (rows && rows.length > 0 && rows[0].EMPLOYEE_NUMBER) {
        const employeeNumber = String(rows[0].EMPLOYEE_NUMBER);
        debugLog('Oracle에서 사번 조회 성공', { EKGRP, employeeNumber });

        // 2. 사번으로 users 테이블에서 사용자 조회
        const userByEmployeeNumber = await db
          .select({
            id: users.id,
            name: users.name,
            email: users.email,
            phone: users.phone
          })
          .from(users)
          .where(eq(users.employeeNumber, employeeNumber))
          .limit(1);

        if (userByEmployeeNumber.length > 0) {
          const userInfo = {
            userId: userByEmployeeNumber[0].id,
            userName: userByEmployeeNumber[0].name,
            userEmail: userByEmployeeNumber[0].email,
            userPhone: userByEmployeeNumber[0].phone
          };
          debugSuccess('사번으로 담당자 찾음 (Oracle 경로)', { EKGRP, employeeNumber, userInfo });
          return userInfo;
        } else {
          debugLog('사번에 해당하는 사용자를 찾을 수 없음, 폴백 시도', { employeeNumber });
        }
      } else {
        debugLog('Oracle에서 구매그룹코드에 해당하는 사번을 찾을 수 없음, 폴백 시도', { EKGRP });
      }
    } catch (oracleError) {
      debugError('Oracle 조회 중 오류, 폴백 시도', { EKGRP, error: oracleError });
    }

    // 3. 폴백: users 테이블에서 userCode로 직접 조회
    debugLog('폴백: userCode로 직접 조회 시도', { EKGRP });
    const userByUserCode = await db
      .select({
        id: users.id,
        name: users.name,
        email: users.email,
        phone: users.phone
      })
      .from(users)
      .where(eq(users.userCode, EKGRP))
      .limit(1);

    if (userByUserCode.length === 0) {
      debugError('EKGRP에 해당하는 사용자를 찾을 수 없음 (모든 경로 실패)', { EKGRP });
      return null;
    }

    const userInfo = {
      userId: userByUserCode[0].id,
      userName: userByUserCode[0].name,
      userEmail: userByUserCode[0].email,
      userPhone: userByUserCode[0].phone
    };
    debugSuccess('담당자 찾음 (폴백 경로)', { EKGRP, userInfo });
    return userInfo;
  } catch (error) {
    debugError('담당자 찾기 중 오류 발생', { EKGRP, error });
    return null;
  }
}

/**
 * 프로젝트 정보 조회 함수 (PSPID 기반)
 * PSPID와 projects.code 매칭하여 프로젝트 ID와 이름 반환
 */
export async function findProjectInfoByPSPID(PSPID: string | null): Promise<{ 
  id: number; 
  name: string 
} | null> {
  try {
    debugLog('프로젝트 정보 찾기 시작', { PSPID });
    
    if (!PSPID) {
      debugError('PSPID가 null 또는 undefined', { PSPID });
      return null;
    }

    const projectResult = await db
      .select({ 
        id: projects.id,
        name: projects.name
      })
      .from(projects)
      .where(eq(projects.code, PSPID))
      .limit(1);

    if (projectResult.length === 0) {
      debugError('PSPID에 해당하는 프로젝트를 찾을 수 없음', { PSPID });
      return null;
    }

    const projectInfo = { 
      id: projectResult[0].id, 
      name: projectResult[0].name 
    };
    debugSuccess('프로젝트 정보 찾음', { PSPID, projectInfo });
    return projectInfo;
  } catch (error) {
    debugError('프로젝트 정보 찾기 중 오류 발생', { PSPID, error });
    return null;
  }
}

/**
 * 프로젝트 정보 조회 함수 (PSPID 기반으로 ID만 반환)
 * PSPID(Project Code)와 projects.code 매칭하여 프로젝트 ID 반환
 */
export async function findProjectIdByPSPID(PSPID: string | null): Promise<number | null> {
  try {
    debugLog('프로젝트 ID 찾기 시작 (PSPID 기준)', { PSPID });
    
    if (!PSPID) {
      debugError('PSPID가 null 또는 undefined', { PSPID });
      return null;
    }

    const projectResult = await db
      .select({ 
        id: projects.id
      })
      .from(projects)
      .where(eq(projects.code, PSPID))
      .limit(1);

    if (projectResult.length === 0) {
      debugError('PSPID에 해당하는 프로젝트를 찾을 수 없음', { PSPID });
      return null;
    }

    debugSuccess('프로젝트 ID 찾음', { PSPID, projectId: projectResult[0].id });
    return projectResult[0].id;
  } catch (error) {
    debugError('프로젝트 ID 찾기 중 오류 발생', { PSPID, error });
    return null;
  }
}

/**
 * 자재명 조회 함수 (MATNR 기반)
 * MATNR을 기반으로 EQUP_MASTER_MATL_CHARASGN 테이블에서 ATWTB 조회
 * 
 * 주의: MATERIAL_MASTER_PART_MATL.ZZNAME이 아닌 EQUP_MASTER_MATL_CHARASGN.ATWTB를 사용해야 함
 */
export async function findMaterialNameByMATNR(MATNR: string | null): Promise<string | null> {
  try {
    debugLog('자재명 조회 시작', { MATNR });
    
    if (!MATNR) {
      debugError('MATNR이 null 또는 undefined', { MATNR });
      return null;
    }

    const materialResult = await db
      .select({ ATWTB: EQUP_MASTER_MATL_CHARASGN.ATWTB })
      .from(EQUP_MASTER_MATL_CHARASGN)
      .where(eq(EQUP_MASTER_MATL_CHARASGN.MATNR, MATNR))
      .limit(1);

    if (materialResult.length === 0) {
      debugError('MATNR에 해당하는 자재를 찾을 수 없음', { MATNR });
      return null;
    }

    const materialName = materialResult[0].ATWTB;
    debugSuccess('자재명 조회 완료', { MATNR, materialName });
    return materialName;
  } catch (error) {
    debugError('자재명 조회 중 오류 발생', { MATNR, error });
    return null;
  }
}

/**
 * SAP 날짜/시간 파싱 함수
 * SAP 형식 (YYYYMMDD + HHMMSS)을 JavaScript Date로 변환
 */
export function parseSAPDateTime(
  dateStr: string | null, 
  timeStr: string | null
): Date {
  let parsedDate = new Date();

  if (dateStr && timeStr) {
    try {
      // SAP 날짜 형식 (YYYYMMDD) 파싱
      if (dateStr.length === 8) {
        const year = parseInt(dateStr.substring(0, 4));
        const month = parseInt(dateStr.substring(4, 6)) - 1; // 0-based
        const day = parseInt(dateStr.substring(6, 8));
        const hour = parseInt(timeStr.substring(0, 2));
        const minute = parseInt(timeStr.substring(2, 4));
        const second = parseInt(timeStr.substring(4, 6));
        parsedDate = new Date(year, month, day, hour, minute, second);
      }
    } catch (error) {
      debugError('SAP 날짜 파싱 오류', {
        date: dateStr,
        time: timeStr,
        error,
      });
    }
  }

  return parsedDate;
}

/**
 * SAP 날짜를 YYYY-MM-DD 문자열로 변환
 * YYYYMMDD 형식을 YYYY-MM-DD로 변환
 */
export function parseSAPDateToString(dateStr: string | null): string | null {
  if (!dateStr) return null;

  try {
    if (dateStr.length === 8) {
      const year = dateStr.substring(0, 4);
      const month = dateStr.substring(4, 6);
      const day = dateStr.substring(6, 8);
      return `${year}-${month}-${day}`;
    }
  } catch (error) {
    debugError('SAP 날짜 문자열 파싱 오류', { date: dateStr, error });
  }

  return null;
}

/**
 * 공통 타입 정의
 */
export interface UserInfo {
  userId: number;
  userName: string;
  userPhone: string | null;
}

export interface ProjectInfo {
  id: number;
  name: string;
}

/**
 * 협력업체 코드(LIFNR)로 vendorId 찾기
 * LIFNR = 벤더코드 (ex. A0001234)
 * vendors 테이블의 vendorCode 필드와 비교하여 vendorId를 찾음
 */
export async function findVendorIdByLIFNR(lifnr: string | null | undefined): Promise<number | null> {
  if (!lifnr || !lifnr.trim()) {
    debugLog('LIFNR이 없음');
    return null;
  }

  try {
    // vendorCode 또는 vendorSapCode로 조회
    const vendor = await db
      .select({ id: vendors.id })
      .from(vendors)
      .where(eq(vendors.vendorCode, lifnr.trim()))
      .limit(1);

    if (vendor.length > 0) {
      return vendor[0].id;
    }

    debugLog(`LIFNR ${lifnr}에 해당하는 vendor를 찾을 수 없음`);
    return null;
  } catch (error) {
    debugError('Vendor 조회 중 오류 발생', { lifnr, error });
    return null;
  }
}