summaryrefslogtreecommitdiff
path: root/lib/swp/document-service.ts
blob: f83488d9e0285c765d7e5bd989742a53b385273b (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
"use server";

/**
 * SWP Document Service
 * 
 * ## 목적
 * SWP API 응답을 가공하여 프론트엔드에 최적화된 데이터 구조를 제공합니다.
 * 
 * ## 역할
 * 1. **데이터 변환**: API 응답을 UI 친화적 구조로 변환
 * 2. **데이터 집계**: 여러 API 호출 결과를 조합 (예: 문서 + 파일 개수)
 * 3. **비즈니스 로직**: 파일 다운로드, 취소 가능 여부 판단 등
 * 4. **에러 처리**: API 실패 시 사용자 친화적 에러 메시지 반환
 * 
 * ## 주요 함수
 * 
 * ### 조회
 * - `getDocumentList(projNo, vndrCd)`: 문서 목록 + 파일 개수 집계
 * - `getDocumentDetail(projNo, docNo)`: Rev → Activity → File 3단계 트리 구조
 * 
 * ### 액션
 * - `cancelStandbyFile(boxSeq, actvSeq, userId)`: Standby 파일 취소 (SCW01만)
 * - `downloadDocumentFile(projNo, ownDocNo, fileName)`: NFS에서 파일 다운로드
 * 
 * ## 데이터 구조
 * 
 * ### DocumentListItem (문서 목록)
 * ```typescript
 * {
 *   DOC_NO: string,
 *   DOC_TITLE: string,
 *   LTST_REV_NO: string,
 *   STAGE: string,
 *   fileCount: number,        // 전체 파일 개수
 *   standbyFileCount: number, // 업로드 대기 중 (SCW01)
 *   ...
 * }
 * ```
 * 
 * ### DocumentDetail (문서 상세)
 * ```typescript
 * {
 *   docNo: string,
 *   revisions: [
 *     {
 *       revNo: "04",
 *       stage: "IFC",
 *       activities: [
 *         {
 *           actvNo: "ACTV123",
 *           type: "External Outbox",
 *           files: [
 *             {
 *               fileNm: "drawing.pdf",
 *               stat: "COM01",
 *               canDownload: true,
 *               canCancel: false,
 *               ...
 *             }
 *           ]
 *         }
 *       ]
 *     }
 *   ]
 * }
 * ```
 * 
 * ## 설계 원칙
 * 1. **API 호출 최소화**: 필요한 데이터를 한 번에 조회 후 가공
 * 2. **타입 안전성**: 모든 반환 타입을 명확히 정의
 * 3. **UI 친화적**: 프론트엔드가 바로 사용 가능한 구조
 * 4. **에러 복원력**: API 실패 시에도 부분 데이터 제공 시도
 * 
 * @see lib/swp/api-client.ts - 저수준 API 호출
 * @see lib/swp/vendor-actions.ts - 서버 액션 (권한 체크 추가)
 * @see lib/swp/README.md - 전체 시스템 문서
 */

import {
  fetchGetVDRDocumentList,
  fetchGetExternalInboxList,
  fetchGetActivityFileList,
  callSaveInBoxListCancelStatus,
  type SwpDocumentApiResponse,
  type SwpFileApiResponse,
  type ActivityFileApiResponse,
} from "./api-client";
import { debugLog, debugError, debugSuccess, debugWarn } from "@/lib/debug-utils";
import * as fs from "fs/promises";
import * as path from "path";

// ============================================================================
// 타입 정의
// ============================================================================

/**
 * 파일 정보 (Activity 파일 + Inbox 파일 결합)
 */
export interface DocumentFile {
  fileNm: string;
  fileSeq: string;
  fileSz: string;
  fileFmt: string;
  fldPath?: string;
  stat?: string; // SCW01=Standby, SCW03=Complete 등
  statNm?: string;
  canCancel: boolean; // STAT=SCW01인 경우만 취소 가능
  canDownload: boolean; // FLD_PATH가 있으면 다운로드 가능
  boxSeq?: string;
  actvSeq?: string;
  objId: string;
  crteDate: string;
}

/**
 * Activity 정보
 */
export interface Activity {
  actvNo: string;
  type: "Receive" | "Send" | "Review"; // STAT 첫 글자로 판단
  stat: string; // R00, S30 등
  toFrom: string; // 업체명
  createDate: string;
  files: DocumentFile[];
}

/**
 * Revision 정보
 */
export interface Revision {
  revNo: string;
  revSeq: string;
  stage: string;
  activities: Activity[];
  totalFiles: number;
}

/**
 * 문서 상세 (Rev-Activity-File 트리)
 */
export interface DocumentDetail {
  docNo: string;
  docTitle: string;
  projNo: string;
  revisions: Revision[];
}

/**
 * 문서 목록 아이템 (통계 포함)
 */
export interface DocumentListItem extends SwpDocumentApiResponse {
  fileCount: number;
  standbyFileCount: number; // STAT=SCW01
  latestFiles: SwpFileApiResponse[];
}

// ============================================================================
// 문서 목록 조회 (시나리오 1)
// ============================================================================

/**
 * 문서 목록 조회
 * - GetVDRDocumentList + GetExternalInboxList 병합
 * - 파일 통계 계산
 */
export async function getDocumentList(
  projNo: string,
  vndrCd?: string
): Promise<DocumentListItem[]> {
  debugLog("[getDocumentList] 시작", { projNo, vndrCd });

  try {
    // 병렬 API 호출
    const [documents, allFiles] = await Promise.all([
      fetchGetVDRDocumentList({
        proj_no: projNo,
        doc_gb: "V",
        vndrCd: vndrCd,
      }),
      fetchGetExternalInboxList({
        projNo: projNo,
        vndrCd: vndrCd,
      }),
    ]);

    debugLog("[getDocumentList] API 조회 완료", {
      documents: documents.length,
      files: allFiles.length,
    });

    // 파일을 문서별로 그룹핑
    const filesByDoc = new Map<string, SwpFileApiResponse[]>();
    for (const file of allFiles) {
      const docNo = file.OWN_DOC_NO;
      if (!filesByDoc.has(docNo)) {
        filesByDoc.set(docNo, []);
      }
      filesByDoc.get(docNo)!.push(file);
    }

    // 문서에 파일 통계 추가
    const result = documents.map((doc) => {
      const files = filesByDoc.get(doc.DOC_NO) || [];
      const standbyFiles = files.filter((f) => f.STAT === "SCW01");

      return {
        ...doc,
        fileCount: files.length,
        standbyFileCount: standbyFiles.length,
        latestFiles: files
          .sort((a, b) => b.CRTE_DTM.localeCompare(a.CRTE_DTM))
          .slice(0, 5), // 최신 5개만
      };
    });

    debugSuccess("[getDocumentList] 완료", { count: result.length });
    return result;
  } catch (error) {
    debugError("[getDocumentList] 실패", error);
    throw new Error(
      error instanceof Error ? error.message : "문서 목록 조회 실패"
    );
  }
}

// ============================================================================
// 문서 상세 조회 (Rev-Activity-File 트리) (시나리오 1 상세)
// ============================================================================

/**
 * 문서 상세 조회
 * - GetActivityFileList + GetExternalInboxList 결합
 * - Rev → Activity → File 트리 구성
 */
export async function getDocumentDetail(
  projNo: string,
  docNo: string
): Promise<DocumentDetail> {
  debugLog("[getDocumentDetail] 시작", { projNo, docNo });

  try {
    // 병렬 API 호출
    const [activityFiles, inboxFiles] = await Promise.all([
      fetchGetActivityFileList({ proj_no: projNo, doc_no: docNo }),
      fetchGetExternalInboxList({ projNo: projNo, owndocno: docNo }),
    ]);

    debugLog("[getDocumentDetail] API 조회 완료", {
      activityFiles: activityFiles.length,
      inboxFiles: inboxFiles.length,
    });

    // Inbox 파일을 빠른 조회를 위해 Map으로 변환
    const inboxFileMap = new Map<string, SwpFileApiResponse>();
    for (const file of inboxFiles) {
      const key = `${file.OWN_DOC_NO}|${file.FILE_NM}`;
      inboxFileMap.set(key, file);
    }

    // 트리 구조 빌드
    const tree = buildDocumentTree(activityFiles, inboxFileMap);

    debugSuccess("[getDocumentDetail] 완료", {
      docNo: tree.docNo,
      revisions: tree.revisions.length,
    });

    return tree;
  } catch (error) {
    debugError("[getDocumentDetail] 실패", error);
    throw new Error(
      error instanceof Error ? error.message : "문서 상세 조회 실패"
    );
  }
}

/**
 * Rev-Activity-File 트리 빌더
 */
function buildDocumentTree(
  activityFiles: ActivityFileApiResponse[],
  inboxFileMap: Map<string, SwpFileApiResponse>
): DocumentDetail {
  if (activityFiles.length === 0) {
    return {
      docNo: "",
      docTitle: "",
      projNo: "",
      revisions: [],
    };
  }

  const first = activityFiles[0];

  // REV_NO로 그룹핑
  const revisionMap = new Map<string, ActivityFileApiResponse[]>();
  for (const item of activityFiles) {
    const revKey = `${item.REV_NO}|${item.REV_SEQ}`;
    if (!revisionMap.has(revKey)) {
      revisionMap.set(revKey, []);
    }
    revisionMap.get(revKey)!.push(item);
  }

  // 각 리비전 처리
  const revisions: Revision[] = [];
  for (const [revKey, revFiles] of revisionMap) {
    const [revNo, revSeq] = revKey.split("|");
    const stage = revFiles[0].STAGE;

    // ACTV_NO로 그룹핑
    const activityMap = new Map<string, ActivityFileApiResponse[]>();
    for (const item of revFiles) {
      if (!activityMap.has(item.ACTV_NO)) {
        activityMap.set(item.ACTV_NO, []);
      }
      activityMap.get(item.ACTV_NO)!.push(item);
    }

    // 각 액티비티 처리
    const activities: Activity[] = [];
    for (const [actvNo, actvFiles] of activityMap) {
      const firstActvFile = actvFiles[0];

      // 파일 정보에 Inbox 데이터 결합
      const files: DocumentFile[] = actvFiles.map((af) => {
        const inboxFile = inboxFileMap.get(`${af.OWN_DOC_NO}|${af.FILE_NM}`);

        return {
          fileNm: af.FILE_NM,
          fileSeq: af.FILE_SEQ,
          fileSz: af.FILE_SZ,
          fileFmt: af.FILE_FMT,
          fldPath: inboxFile?.FLD_PATH,
          stat: inboxFile?.STAT,
          statNm: inboxFile?.STAT_NM,
          canCancel: inboxFile?.STAT === "SCW01", // Standby만 취소 가능
          canDownload: !!inboxFile?.FLD_PATH,
          boxSeq: inboxFile?.BOX_SEQ,
          actvSeq: inboxFile?.ACTV_SEQ,
          objId: af.OBJT_ID,
          crteDate: af.CRTE_DTM,
        };
      });

      activities.push({
        actvNo: actvNo,
        type: getActivityType(firstActvFile.STAT),
        stat: firstActvFile.STAT,
        toFrom: firstActvFile.TO_FROM,
        createDate: firstActvFile.CRTE_DTM,
        files: files,
      });
    }

    revisions.push({
      revNo: revNo,
      revSeq: revSeq,
      stage: stage,
      activities: activities.sort((a, b) =>
        b.createDate.localeCompare(a.createDate)
      ),
      totalFiles: revFiles.length,
    });
  }

  return {
    docNo: first.DOC_NO,
    docTitle: first.DOC_TITLE,
    projNo: first.OWN_DOC_NO.split("-")[0] || "", // 프로젝트 코드 추출
    revisions: revisions.sort((a, b) => b.revNo.localeCompare(a.revNo)),
  };
}

/**
 * STAT 코드로 Activity 타입 판단
 */
function getActivityType(stat: string): "Receive" | "Send" | "Review" {
  const firstChar = stat.charAt(0).toUpperCase();
  if (firstChar === "R") return "Receive";
  if (firstChar === "S") return "Send";
  if (firstChar === "V") return "Review";
  return "Send"; // 기본값
}

// ============================================================================
// 파일 취소 (시나리오 1-1)
// ============================================================================

/**
 * Standby 상태 파일 취소
 */
export async function cancelStandbyFile(
  boxSeq: string,
  actvSeq: string,
  userId: string
): Promise<void> {
  debugLog("[cancelStandbyFile] 시작", { boxSeq, actvSeq, userId });

  try {
    // varchar(13) 제한
    const chgr = `evcp${userId}`.substring(0, 13);

    await callSaveInBoxListCancelStatus({
      boxSeq: boxSeq,
      actvSeq: actvSeq,
      chgr: chgr,
    });

    debugSuccess("[cancelStandbyFile] 완료", { boxSeq, actvSeq });
  } catch (error) {
    debugError("[cancelStandbyFile] 실패", error);
    throw new Error(
      error instanceof Error ? error.message : "파일 취소 실패"
    );
  }
}

// ============================================================================
// 파일 다운로드 (시나리오 1-2)
// ============================================================================

export interface DownloadFileResult {
  success: boolean;
  data?: Uint8Array;
  fileName?: string;
  mimeType?: string;
  error?: string;
}

/**
 * 문서 파일 다운로드
 * - GetExternalInboxList에서 FLD_PATH 조회
 * - 네트워크 드라이브에서 파일 읽기
 */
export async function downloadDocumentFile(
  projNo: string,
  ownDocNo: string,
  fileName: string
): Promise<DownloadFileResult> {
  debugLog("[downloadDocumentFile] 시작", { projNo, ownDocNo, fileName });

  try {
    // 1. GetExternalInboxList에서 파일 정보 찾기
    const files = await fetchGetExternalInboxList({
      projNo: projNo,
      owndocno: ownDocNo,
    });

    const targetFile = files.find((f) => f.FILE_NM === fileName);

    if (!targetFile || !targetFile.FLD_PATH) {
      debugWarn("[downloadDocumentFile] 파일 없음", { fileName });
      return {
        success: false,
        error: "파일을 찾을 수 없습니다",
      };
    }

    debugLog("[downloadDocumentFile] 파일 정보 조회 완료", {
      fileName: targetFile.FILE_NM,
      fldPath: targetFile.FLD_PATH,
    });

    // 2. NFS 마운트 경로 확인
    const nfsBasePath = process.env.SWP_MOUNT_DIR;
    if (!nfsBasePath) {
      debugError("[downloadDocumentFile] SWP_MOUNT_DIR 미설정");
      return {
        success: false,
        error: "서버 설정 오류: NFS 경로가 설정되지 않았습니다",
      };
    }

    // 3. 전체 파일 경로 생성
    const normalizedFldPath = targetFile.FLD_PATH.replace(/\\/g, "/");
    const fullPath = path.join(nfsBasePath, normalizedFldPath, targetFile.FILE_NM);

    debugLog("[downloadDocumentFile] 파일 경로", { fullPath });

    // 4. 파일 존재 여부 확인
    try {
      await fs.access(fullPath, fs.constants.R_OK);
    } catch (accessError) {
      debugError("[downloadDocumentFile] 파일 접근 불가", accessError);
      return {
        success: false,
        error: `파일을 찾을 수 없습니다: ${targetFile.FILE_NM}`,
      };
    }

    // 5. 파일 읽기
    const fileBuffer = await fs.readFile(fullPath);
    const fileData = new Uint8Array(fileBuffer);

    // 6. MIME 타입 결정
    const mimeType = getMimeType(targetFile.FILE_NM);

    debugSuccess("[downloadDocumentFile] 완료", {
      fileName: targetFile.FILE_NM,
      size: fileData.length,
      mimeType,
    });

    return {
      success: true,
      data: fileData,
      fileName: targetFile.FILE_NM,
      mimeType,
    };
  } catch (error) {
    debugError("[downloadDocumentFile] 실패", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "파일 다운로드 실패",
    };
  }
}

/**
 * MIME 타입 결정
 */
function getMimeType(fileName: string): string {
  const ext = path.extname(fileName).toLowerCase();

  const mimeTypes: Record<string, string> = {
    ".pdf": "application/pdf",
    ".doc": "application/msword",
    ".docx":
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    ".xls": "application/vnd.ms-excel",
    ".xlsx":
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ".ppt": "application/vnd.ms-powerpoint",
    ".pptx":
      "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    ".txt": "text/plain",
    ".csv": "text/csv",
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".png": "image/png",
    ".gif": "image/gif",
    ".zip": "application/zip",
    ".rar": "application/x-rar-compressed",
    ".7z": "application/x-7z-compressed",
    ".dwg": "application/acad",
    ".dxf": "application/dxf",
  };

  return mimeTypes[ext] || "application/octet-stream";
}