summaryrefslogtreecommitdiff
path: root/app/api/vendors/erp/route.ts
blob: 0724eeeb9b2ec61d269d6e7742b59fed9b7bc624 (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
import { NextRequest, NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { getErrorMessage } from '@/lib/handle-error';

/**
 * 기간계 시스템에 벤더 정보를 전송하는 API 엔드포인트
 * 서버 액션 내부에서 호출됨
 */
export async function POST(request: NextRequest) {
  try {
     
    // 요청 본문 파싱
    const vendorData = await request.json();
    
    // 기간계 시스템 API 설정
    const erpApiUrl = process.env.ERP_API_URL;
    const erpApiKey = process.env.ERP_API_KEY;
    
    if (!erpApiUrl || !erpApiKey) {
      return NextResponse.json(
        { success: false, message: 'ERP API configuration is missing' },
        { status: 500 }
      );
    }
    
    // 기간계 시스템이 요구하는 형식으로 데이터 변환
    const erpRequestData = {
      vendor: {
        name: vendorData.vendorName,
        tax_id: vendorData.taxId,
        address: vendorData.address || "",
        country: vendorData.country || "",
        phone: vendorData.phone || "",
        email: vendorData.email || "",
        website: vendorData.website || "",
        external_id: vendorData.id.toString(),
      },
      contacts: vendorData.contacts.map((contact: any) => ({
        name: contact.contactName,
        position: contact.contactPosition || "",
        email: contact.contactEmail,
        phone: contact.contactPhone || "",
        is_primary: contact.isPrimary ? 1 : 0,
      })),
      items: vendorData.possibleItems.map((item: any) => ({
        item_code: item.itemCode,
        description: item.description || "",
      })),
      attachments: vendorData.attachments.map((attach: any) => ({
        file_name: attach.fileName,
        file_path: attach.filePath,
      })),
    };
    
    // 기간계 시스템 API 호출
    const response = await fetch(erpApiUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${erpApiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(erpRequestData),
      // Next.js의 fetch는 기본 30초 타임아웃
    });
    
    // 응답 처리
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      return NextResponse.json(
        { 
          success: false, 
          message: `ERP system error: ${response.status} ${response.statusText}`,
          details: errorData
        },
        { status: 502 } // Bad Gateway (외부 서버 오류)
      );
    }
    
    const result = await response.json();
    
    // 벤더 코드 검증
    if (!result.vendor_code) {
      return NextResponse.json(
        { success: false, message: 'Vendor code not provided in ERP response' },
        { status: 502 }
      );
    }
    
    // 성공 응답
    return NextResponse.json({
      success: true,
      vendorCode: result.vendor_code,
      message: 'Vendor successfully registered in ERP system',
      ...result
    });
  } catch (error) {
    console.error('Error in ERP API:', error);
    return NextResponse.json(
      { 
        success: false, 
        message: getErrorMessage(error)
      },
      { status: 500 }
    );
  }
}

/**
 * 기간계 시스템 연결 상태 확인 (헬스 체크)
 */
export async function GET() {
  try {
    const healthCheckUrl = process.env.ERP_HEALTH_CHECK_URL;
    
    if (!healthCheckUrl) {
      return NextResponse.json(
        { success: false, message: 'ERP health check URL not configured' },
        { status: 500 }
      );
    }
    
    const response = await fetch(healthCheckUrl, {
      method: 'GET',
      next: { revalidate: 60 } // 1분마다 재검증
    });
    
    const isAvailable = response.ok;
    
    return NextResponse.json({
      success: true,
      available: isAvailable,
      status: response.status,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    console.error('ERP health check error:', error);
    return NextResponse.json({
      success: false,
      available: false,
      error: getErrorMessage(error),
      timestamp: new Date().toISOString()
    });
  }
}