summaryrefslogtreecommitdiff
path: root/app/api/swp/upload/route.ts
blob: b38c4ff4b60bf976ab5278450f8838cf76795831 (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
import { NextRequest, NextResponse } from "next/server";
import * as fs from "fs/promises";
import * as path from "path";
import { eq, and } from "drizzle-orm";
import db from "@/db/db";
import { swpDocuments } from "@/db/schema/SWP/swp-documents";
import { fetchGetVDRDocumentList, fetchGetExternalInboxList } from "@/lib/swp/api-client";
import { syncSwpProject } from "@/lib/swp/sync-service";
import { debugLog, debugError, debugSuccess } from "@/lib/debug-utils";

// API Route 설정
export const runtime = "nodejs";
export const maxDuration = 300; // 5분 타임아웃 (대용량 파일 업로드 대응)

interface InBoxFileInfo {
  CPY_CD: string;
  FILE_NM: string;
  OFDC_NO: string | null;
  PROJ_NO: string;
  OWN_DOC_NO: string;
  REV_NO: string;
  STAGE: string;
  STAT: string;
  FILE_SZ: string;
  FLD_PATH: string;
}

/**
 * 파일명 파싱: [DOC_NO]_[REV_NO]_[STAGE]_[자유-파일명].[확장자]
 * 자유 파일명에는 언더스코어가 포함될 수 있음
 */
function parseFileName(fileName: string) {
  const lastDotIndex = fileName.lastIndexOf(".");
  const extension = lastDotIndex !== -1 ? fileName.substring(lastDotIndex + 1) : "";
  const nameWithoutExt = lastDotIndex !== -1 ? fileName.substring(0, lastDotIndex) : fileName;

  const parts = nameWithoutExt.split("_");
  
  // 최소 4개 파트 필요: docNo, revNo, stage, fileName
  if (parts.length < 4) {
    throw new Error(
      `잘못된 파일명 형식입니다: ${fileName}. ` +
      `형식: [DOC_NO]_[REV_NO]_[STAGE]_[파일명].확장자 (언더스코어 최소 3개 필요)`
    );
  }

  // 앞에서부터 3개는 고정: docNo, revNo, stage
  const ownDocNo = parts[0];
  const revNo = parts[1];
  const stage = parts[2];
  
  // 나머지는 자유 파일명 (언더스코어 포함 가능)
  const customFileName = parts.slice(3).join("_");

  return { ownDocNo, revNo, stage, fileName: customFileName, extension };
}

/**
 * 현재 시간을 YYYYMMDDhhmmss 형식으로 반환
 */
function generateTimestamp(): string {
  const now = new Date();
  const year = now.getFullYear().toString();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  const day = now.getDate().toString().padStart(2, "0");
  const hours = now.getHours().toString().padStart(2, "0");
  const minutes = now.getMinutes().toString().padStart(2, "0");
  const seconds = now.getSeconds().toString().padStart(2, "0");
  
  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}

/**
 * CPY_CD 조회
 */
async function getCpyCdForVendor(projNo: string, vndrCd: string): Promise<string> {
  const result = await db
    .select({ CPY_CD: swpDocuments.CPY_CD })
    .from(swpDocuments)
    .where(and(eq(swpDocuments.PROJ_NO, projNo), eq(swpDocuments.VNDR_CD, vndrCd)))
    .limit(1);

  if (!result || result.length === 0 || !result[0].CPY_CD) {
    throw new Error(
      `프로젝트 ${projNo}에서 벤더 코드 ${vndrCd}에 해당하는 회사 코드(CPY_CD)를 찾을 수 없습니다.`
    );
  }

  return result[0].CPY_CD;
}

/**
 * SaveInBoxList API 호출
 */
async function callSaveInBoxList(fileInfos: InBoxFileInfo[]): Promise<void> {
  const ddcUrl = process.env.DDC_BASE_URL || "http://60.100.99.217/DDC/Services/WebService.svc";
  const url = `${ddcUrl}/SaveInBoxList`;

  const request = { externalInboxLists: fileInfos };

  console.log("[callSaveInBoxList] 요청:", JSON.stringify(request, null, 2));

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify(request),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`SaveInBoxList API 호출 실패: ${response.statusText} - ${errorText}`);
  }

  const data = await response.json();
  console.log("[callSaveInBoxList] 응답:", JSON.stringify(data, null, 2));

  // SaveInBoxListResult는 성공한 FLD_PATH들을 쉼표로 구분한 문자열
  // 예: "\\\\ProjNo\\\\CpyCd\\\\YYYYMMDDhhmmss, \\\\ProjNo\\\\CpyCd\\\\YYYYMMDDhhmmss"
  if (!data.SaveInBoxListResult) {
    throw new Error("SaveInBoxList API 실패: 응답에 SaveInBoxListResult가 없습니다.");
  }

  const result = data.SaveInBoxListResult;
  
  // 문자열 응답인 경우 (정상)
  if (typeof result === "string") {
    if (result.trim().length === 0) {
      throw new Error("SaveInBoxList API 실패: 빈 응답이 반환되었습니다.");
    }
    // 성공한 FLD_PATH 개수 로깅
    const successPaths = result.split(",").map(p => p.trim()).filter(p => p.length > 0);
    console.log(`[callSaveInBoxList] 성공: ${successPaths.length}개 파일 등록 완료`);
    return;
  }
  
  // 객체 응답인 경우 (레거시 또는 에러)
  if (typeof result === "object" && result !== null) {
    const objResult = result as { success?: boolean; message?: string };
    if (objResult.success === false) {
      throw new Error(
        `SaveInBoxList API 실패: ${objResult.message || "알 수 없는 오류"}`
      );
    }
  }
}

/**
 * POST /api/swp/upload
 * FormData로 파일 업로드
 */
export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData();
    
    const projNo = formData.get("projNo") as string;
    const vndrCd = formData.get("vndrCd") as string;
    
    if (!projNo || !vndrCd) {
      return NextResponse.json(
        { success: false, message: "projNo와 vndrCd는 필수입니다." },
        { status: 400 }
      );
    }

    // CPY_CD 조회
    console.log(`[upload] CPY_CD 조회: projNo=${projNo}, vndrCd=${vndrCd}`);
    const cpyCd = await getCpyCdForVendor(projNo, vndrCd);
    console.log(`[upload] CPY_CD: ${cpyCd}`);

    const files = formData.getAll("files") as File[];
    
    if (!files || files.length === 0) {
      return NextResponse.json(
        { success: false, message: "업로드할 파일이 없습니다." },
        { status: 400 }
      );
    }

    const result = {
      successCount: 0,
      failedCount: 0,
      details: [] as Array<{ fileName: string; success: boolean; error?: string; networkPath?: string }>,
    };

    const inBoxFileInfos: InBoxFileInfo[] = [];
    const swpMountDir = process.env.SWP_MOUNT_DIR || "/mnt/swp-smb-dir/";
    
    // 업로드 시점의 timestamp 생성 (모든 파일에 동일한 timestamp 사용)
    const uploadTimestamp = generateTimestamp();
    console.log(`[upload] 업로드 타임스탬프 생성: ${uploadTimestamp}`);

    for (const file of files) {
      try {
        // 파일명 파싱
        const parsed = parseFileName(file.name);
        console.log(`[upload] 파일명 파싱:`, parsed);

        // 네트워크 경로 생성 (timestamp를 경로에만 사용)
        const networkPath = path.join(swpMountDir, projNo, cpyCd, uploadTimestamp, file.name);

        // 파일 중복 체크
        try {
          await fs.access(networkPath, fs.constants.F_OK);
          result.failedCount++;
          result.details.push({
            fileName: file.name,
            success: false,
            error: "파일이 이미 존재합니다.",
          });
          console.warn(`[upload] 파일 중복: ${networkPath}`);
          continue;
        } catch {
          // 파일이 존재하지 않음 (정상)
        }

        // 디렉토리 생성
        const directory = path.dirname(networkPath);
        await fs.mkdir(directory, { recursive: true });

        // 파일 저장 (스트리밍 방식)
        const arrayBuffer = await file.arrayBuffer();
        debugLog(`[upload] ArrayBuffer 변환 완료: ${file.name}`, {
          arrayBufferSize: arrayBuffer.byteLength,
          fileType: file.type,
          originalSize: file.size
        });
        
        const buffer = Buffer.from(arrayBuffer);
        debugLog(`[upload] Buffer 생성 완료: ${file.name}`, {
          bufferLength: buffer.length,
          bufferType: typeof buffer,
          isBuffer: Buffer.isBuffer(buffer),
          first20Bytes: buffer.slice(0, 20).toString('hex')
        });
        
        console.log(`[upload] 파일 저장: ${file.name} (${buffer.length} bytes)`);
        
        // 저장 전 buffer 상태 확인
        debugLog(`[upload] 저장 직전 buffer 상태`, {
          constructor: buffer.constructor.name,
          isBuffer: Buffer.isBuffer(buffer),
          jsonStringified: JSON.stringify(buffer).substring(0, 100) + '...'
        });
        
        await fs.writeFile(networkPath, buffer);
        debugSuccess(`[upload] 파일 저장 완료: ${networkPath}`);
        
        // 저장된 파일 검증
        const savedFileStats = await fs.stat(networkPath);
        debugLog(`[upload] 저장된 파일 정보`, {
          size: savedFileStats.size,
          expectedSize: buffer.length,
          sizeMatch: savedFileStats.size === buffer.length
        });
        
        // 저장된 파일 첫 부분 읽어서 검증
        const verifyBuffer = await fs.readFile(networkPath);
        debugLog(`[upload] 저장된 파일 검증`, {
          readSize: verifyBuffer.length,
          first20Bytes: verifyBuffer.slice(0, 20).toString('hex'),
          isBuffer: Buffer.isBuffer(verifyBuffer),
          matchesOriginal: buffer.slice(0, 20).equals(verifyBuffer.slice(0, 20))
        });

        // InBox 파일 정보 준비 (FLD_PATH에 업로드 timestamp 사용)
        const fldPath = `\\\\${projNo}\\\\${cpyCd}\\\\${uploadTimestamp}`;

        inBoxFileInfos.push({
          CPY_CD: cpyCd,
          FILE_NM: file.name,
          OFDC_NO: null,
          PROJ_NO: projNo,
          OWN_DOC_NO: parsed.ownDocNo,
          REV_NO: parsed.revNo,
          STAGE: parsed.stage,
          STAT: "SCW01",
          FILE_SZ: String(buffer.length),
          FLD_PATH: fldPath,
        });

        result.successCount++;
        result.details.push({
          fileName: file.name,
          success: true,
          networkPath,
        });
      } catch (error) {
        result.failedCount++;
        result.details.push({
          fileName: file.name,
          success: false,
          error: error instanceof Error ? error.message : "알 수 없는 오류",
        });
        console.error(`[upload] 파일 처리 실패: ${file.name}`, error);
        debugError(`[upload] 파일 처리 실패: ${file.name}`, {
          error: error instanceof Error ? error.message : String(error),
          stack: error instanceof Error ? error.stack : undefined
        });
      }
    }

    // SaveInBoxList API 호출
    if (inBoxFileInfos.length > 0) {
      console.log(`[upload] SaveInBoxList API 호출: ${inBoxFileInfos.length}개 파일`);
      await callSaveInBoxList(inBoxFileInfos);
    }

    // 업로드 성공 후 동기화 처리 (현재 벤더의 변경사항만)
    if (result.successCount > 0) {
      try {
        console.log(`[upload] 동기화 시작: projNo=${projNo}, vndrCd=${vndrCd}`);
        
        // GetVDRDocumentList 및 GetExternalInboxList API 호출 (벤더 필터 적용)
        const [documents, files] = await Promise.all([
          fetchGetVDRDocumentList({
            proj_no: projNo,
            doc_gb: "V",
            vndrCd: vndrCd, // 현재 벤더만 필터링
          }),
          fetchGetExternalInboxList({
            projNo: projNo,
            vndrCd: vndrCd, // 현재 벤더만 필터링
          }),
        ]);

        console.log(`[upload] API 조회 완료: 문서 ${documents.length}개, 파일 ${files.length}개`);

        // 동기화 실행
        const syncResult = await syncSwpProject(projNo, documents, files);
        
        if (syncResult.success) {
          console.log(`[upload] 동기화 완료:`, syncResult.stats);
        } else {
          console.warn(`[upload] 동기화 경고:`, syncResult.errors);
        }
      } catch (syncError) {
        // 동기화 실패는 경고로만 처리 (업로드 자체는 성공)
        console.error("[upload] 동기화 실패 (업로드는 성공):", syncError);
      }
    }

    // 결과 메시지 생성
    let message: string;
    let success: boolean;

    if (result.failedCount === 0) {
      success = true;
      message = `${result.successCount}개 파일이 성공적으로 업로드 및 동기화되었습니다.`;
    } else if (result.successCount === 0) {
      success = false;
      message = `모든 파일 업로드에 실패했습니다. (${result.failedCount}개)`;
    } else {
      success = true;
      message = `${result.successCount}개 파일 업로드 성공, ${result.failedCount}개 실패`;
    }

    console.log(`[upload] 완료:`, { success, message, result });

    // 동기화 완료 정보 추가
    const syncCompleted = result.successCount > 0;
    const syncTimestamp = new Date().toISOString();

    return NextResponse.json({
      success,
      message,
      successCount: result.successCount,
      failedCount: result.failedCount,
      details: result.details,
      syncCompleted,
      syncTimestamp,
      affectedVndrCd: vndrCd,
    });
  } catch (error) {
    console.error("[upload] 오류:", error);
    debugError(`[upload] 전체 프로세스 실패`, {
      error: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined
    });
    return NextResponse.json(
      {
        success: false,
        message: error instanceof Error ? error.message : "알 수 없는 오류가 발생했습니다.",
      },
      { status: 500 }
    );
  }
}