summaryrefslogtreecommitdiff
path: root/app/api/s-erp-import/rpa/route.ts
blob: 749de90f587e9a7a079776e19b4480e222cec462 (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
import { NextRequest, NextResponse } from 'next/server'
import { getSapTableCounts, importExcel, exportTemplate } from '@/lib/s-erp-import/actions'

// RPA용 API 엔드포인트
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const action = searchParams.get('action')
    const tableName = searchParams.get('tableName')

    switch (action) {
      case 'get-counts':
        // 모든 테이블의 데이터 건수 조회
        const TABLES = [
          'TB_SAP_EquipInfo',
          'TB_SAP_Order',
          'TB_SAP_OrderConfirm',
          'TB_SAP_OrderNotice',
          'TB_SAP_OrderBreakdown',
          'TB_SAP_MainternanceBOM',
          'TB_SAP_MaterialRepair',
          'TB_SAP_MaterialInfo',
          'TB_SAP_MaterialStock',
          'TB_SAP_MaterialRelease',
          'TB_SAP_MaterialReceiving',
          'TB_SAP_MaterialPurchase',
        ]
        const counts = await getSapTableCounts(TABLES)
        return NextResponse.json({
          success: true,
          data: counts,
          timestamp: new Date().toISOString()
        })

      case 'get-template':
        // 템플릿 다운로드
        if (!tableName) {
          return NextResponse.json({
            success: false,
            message: 'tableName is required'
          }, { status: 400 })
        }
        
        const templateBuffer = await exportTemplate(tableName)
        return new NextResponse(templateBuffer, {
          headers: {
            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'Content-Disposition': `attachment; filename="${tableName}_template.xlsx"`
          }
        })

      case 'get-table-info':
        // 테이블 정보 조회
        const tableInfo = {
          'TB_SAP_EquipInfo': { title: '장비 정보', category: '장비 관리', description: 'SAP 장비 마스터 데이터' },
          'TB_SAP_Order': { title: '작업 주문', category: '작업 관리', description: '유지보수 작업 주문 정보' },
          'TB_SAP_OrderConfirm': { title: '주문 확인', category: '작업 관리', description: '작업 주문 확인 및 완료 정보' },
          'TB_SAP_OrderNotice': { title: '주문 통지', category: '작업 관리', description: '작업 주문 통지 및 알림 정보' },
          'TB_SAP_OrderBreakdown': { title: '주문 고장', category: '고장 관리', description: '장비 고장 및 수리 정보' },
          'TB_SAP_MainternanceBOM': { title: '유지보수 BOM', category: '부품 관리', description: '유지보수용 부품 목록' },
          'TB_SAP_MaterialRepair': { title: '자재 수리', category: '자재 관리', description: '자재 수리 및 교체 정보' },
          'TB_SAP_MaterialInfo': { title: '자재 정보', category: '자재 관리', description: '자재 마스터 데이터' },
          'TB_SAP_MaterialStock': { title: '자재 재고', category: '자재 관리', description: '자재 재고 현황' },
          'TB_SAP_MaterialRelease': { title: '자재 출고', category: '자재 관리', description: '자재 출고 내역' },
          'TB_SAP_MaterialReceiving': { title: '자재 입고', category: '자재 관리', description: '자재 입고 내역' },
          'TB_SAP_MaterialPurchase': { title: '자재 구매', category: '자재 관리', description: '자재 구매 요청 정보' }
        }

        if (tableName) {
          return NextResponse.json({
            success: true,
            data: tableInfo[tableName as keyof typeof tableInfo] || null
          })
        } else {
          return NextResponse.json({
            success: true,
            data: tableInfo
          })
        }

      default:
        return NextResponse.json({
          success: false,
          message: 'Invalid action. Supported actions: get-counts, get-template, get-table-info'
        }, { status: 400 })
    }
  } catch (error: any) {
    console.error('RPA API Error:', error)
    return NextResponse.json({
      success: false,
      message: error.message || 'Internal server error',
      timestamp: new Date().toISOString()
    }, { status: 500 })
  }
}

// RPA용 파일 업로드 엔드포인트
export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData()
    const tableName = formData.get('tableName') as string
    const file = formData.get('file') as File

    if (!tableName || !file) {
      return NextResponse.json({
        success: false,
        message: 'tableName and file are required'
      }, { status: 400 })
    }

    // 파일 업로드 처리
    const result = await importExcel(tableName, file)

    return NextResponse.json({
      success: result.success,
      data: {
        tableName,
        fileName: file.name,
        fileSize: file.size,
        inserted: result.inserted || 0,
        message: result.message,
        unknownHeaders: (result as any).unknownHeaders,
        errors: (result as any).errors
      },
      timestamp: new Date().toISOString()
    })
  } catch (error: any) {
    console.error('RPA Upload Error:', error)
    return NextResponse.json({
      success: false,
      message: error.message || 'Upload failed',
      timestamp: new Date().toISOString()
    }, { status: 500 })
  }
}