summaryrefslogtreecommitdiff
path: root/app/api/basic-contract/get-template/route.ts
blob: ad30ae89ca4008b900f6bb3349415dc9d5808f00 (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
import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
import db from "@/db/db";
import { basicContractTemplates } from '@/db/schema';
import { eq } from 'drizzle-orm';

export async function POST(request: NextRequest) {
  try {
    const { templateId } = await request.json();
    
    if (!templateId) {
      return NextResponse.json({ error: '템플릿 ID가 누락되었습니다.' }, { status: 400 });
    }
    
    // 데이터베이스에서 템플릿 정보 가져오기
    const template = await db.query.basicContractTemplates.findFirst({
      where: eq(basicContractTemplates.id, templateId)
    });
    
    if (!template) {
      return NextResponse.json({ error: '템플릿을 찾을 수 없습니다.' }, { status: 404 });
    }
    
    if (!template.filePath) {
      return NextResponse.json({ error: '템플릿 파일 경로가 없습니다.' }, { status: 404 });
    }
    
    // 환경에 따른 파일 경로 설정
    let fullPath: string;
    
    if (process.env.NODE_ENV === 'production') {
      // production: NAS 경로 사용
      const nasPath = process.env.NAS_PATH || "/evcp_nas";
      // template.filePath가 /api/files/로 시작하는 경우 제거하고 basicContract로 시작하도록 정리
      const cleanPath = template.filePath.startsWith('/api/files/') 
        ? template.filePath.replace('/api/files/', '') 
        : template.filePath.startsWith('/') 
        ? template.filePath.slice(1) 
        : template.filePath;
      fullPath = path.join(nasPath, cleanPath);
    } else {
      // development: public 폴더 사용
      // template.filePath에서 앞의 슬래시를 제거
      const cleanPath = template.filePath.startsWith('/') ? template.filePath.slice(1) : template.filePath;
      fullPath = path.join(process.cwd(), "public", cleanPath);
    }
    
    console.log(`📁 템플릿 파일 경로: ${fullPath} (환경: ${process.env.NODE_ENV})`);
    
    try {
      const fileBuffer = await fs.readFile(fullPath);
      
      // 파일을 Blob으로 반환
      return new NextResponse(fileBuffer, {
        status: 200,
        headers: {
          'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'Content-Disposition': `attachment; filename="${encodeURIComponent(template.fileName || 'template.docx')}"`,
        },
      });
    } catch (fileError) {
      console.error('파일 읽기 오류:', fileError);
      console.error(`파일 경로: ${fullPath}`);
      console.error(`template.filePath: ${template.filePath}`);
      return NextResponse.json({ 
        error: '템플릿 파일을 읽을 수 없습니다.',
        details: `파일 경로: ${fullPath}`,
        originalPath: template.filePath 
      }, { status: 500 });
    }
    
  } catch (error) {
    console.error('템플릿 가져오기 오류:', error);
    return NextResponse.json({ error: '서버 오류가 발생했습니다.' }, { status: 500 });
  }
}