summaryrefslogtreecommitdiff
path: root/lib/tech-vendor-possible-items/table/excel-export.tsx
blob: d3c4dea55427873b7ffcd82b83384f5b79fe7eae (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
import * as ExcelJS from 'exceljs';
import { saveAs } from "file-saver";
import type { TechVendorPossibleItemsData } from '../service';
import { format } from 'date-fns';
import { ko } from 'date-fns/locale';

/**
 * 기술영업 벤더 가능 아이템 데이터를 Excel 파일로 내보내기
 */
export async function exportTechVendorPossibleItemsToExcel(
  data: TechVendorPossibleItemsData[]
) {
  try {
    // 워크북 생성
    const workbook = new ExcelJS.Workbook();
    workbook.creator = 'Tech Vendor Possible Items Management System';
    workbook.created = new Date();
    
    // 워크시트 생성
    const worksheet = workbook.addWorksheet('기술영업 벤더 가능 아이템');

    // 컬럼 헤더 정의 및 스타일 적용
    worksheet.columns = [
      { header: '번호', key: 'id', width: 10 },
      { header: '벤더코드', key: 'vendorCode', width: 15 },
      { header: '벤더명', key: 'vendorName', width: 25 },
      { header: '벤더타입', key: 'techVendorType', width: 20 },
      { header: '아이템코드', key: 'itemCode', width: 20 },
      { header: '생성일시', key: 'createdAt', width: 20 },
    ];

    // 헤더 스타일 적용
    const headerRow = worksheet.getRow(1);
    headerRow.eachCell((cell) => {
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE6F3FF' }
      };
      cell.font = {
        bold: true,
        color: { argb: 'FF1F4E79' }
      };
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' }
      };
      cell.alignment = {
        vertical: 'middle',
        horizontal: 'center'
      };
    });

    // 데이터 추가
    data.forEach((item, index) => {
      // 벤더 타입 파싱
      let vendorTypes = '';
      try {
        const parsed = JSON.parse(item.techVendorType || "[]");
        vendorTypes = Array.isArray(parsed) ? parsed.join(', ') : item.techVendorType;
      } catch {
        vendorTypes = item.techVendorType;
      }

      const row = worksheet.addRow({
        id: item.id,
        vendorCode: item.vendorCode || '-',
        vendorName: item.vendorName,
        techVendorType: vendorTypes,
        itemCode: item.itemCode,
        createdAt: format(item.createdAt, 'yyyy-MM-dd HH:mm', { locale: ko }),
      });

      // 데이터 행 스타일
      row.eachCell((cell, colNumber) => {
        cell.border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' }
        };
        
        if (colNumber === 1) {
          // ID 컬럼 가운데 정렬
          cell.alignment = { vertical: 'middle', horizontal: 'center' };
        } else {
          // 나머지 컬럼 왼쪽 정렬
          cell.alignment = { vertical: 'middle', horizontal: 'left' };
        }
      });

      // 홀수 행 배경색
      if (index % 2 === 1) {
        row.eachCell((cell) => {
          cell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFF8F9FA' }
          };
        });
      }
    });

    // 요약 정보 워크시트 생성
    const summarySheet = workbook.addWorksheet('요약 정보');
    
    const summaryData = [
      ['기술영업 벤더 가능 아이템 현황', ''],
      ['', ''],
      ['총 항목 수:', data.length.toLocaleString()],
      ['고유 벤더 수:', new Set(data.map(item => item.vendorId)).size.toLocaleString()],
      ['고유 아이템 수:', new Set(data.map(item => item.itemCode)).size.toLocaleString()],
      ['', ''],
      ['벤더 타입별 분포:', ''],
      ...getVendorTypeDistribution(data),
      ['', ''],
      ['내보내기 일시:', format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ko })],
    ];

    summaryData.forEach((rowData, index) => {
      const row = summarySheet.addRow(rowData);
      if (index === 0) {
        // 제목 스타일
        row.getCell(1).font = { bold: true, size: 16, color: { argb: 'FF1F4E79' } };
      } else if (typeof rowData[0] === 'string' && rowData[0].includes(':') && rowData[1] === '') {
        // 섹션 제목 스타일
        row.getCell(1).font = { bold: true, color: { argb: 'FF1F4E79' } };
      }
    });

    summarySheet.getColumn(1).width = 30;
    summarySheet.getColumn(2).width = 20;

    // 파일 생성 및 다운로드
    const buffer = await workbook.xlsx.writeBuffer();
    const blob = new Blob([buffer], { 
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" 
    });
    
    const fileName = `기술영업_벤더_가능_아이템_${format(new Date(), 'yyyyMMdd_HHmmss')}.xlsx`;
    saveAs(blob, fileName);
    
    return { success: true };
  } catch (error) {
    console.error("Excel 내보내기 중 오류:", error);
    return { 
      success: false, 
      error: error instanceof Error ? error.message : "내보내기 중 오류가 발생했습니다." 
    };
  }
}

/**
 * 벤더 타입별 분포 계산
 */
function getVendorTypeDistribution(data: TechVendorPossibleItemsData[]): [string, string][] {
  const typeCount = new Map<string, number>();
  
  data.forEach(item => {
    try {
      const parsed = JSON.parse(item.techVendorType || "[]");
      const types = Array.isArray(parsed) ? parsed : [item.techVendorType];
      
      types.forEach(type => {
        if (type) {
          typeCount.set(type, (typeCount.get(type) || 0) + 1);
        }
      });
    } catch {
      if (item.techVendorType) {
        typeCount.set(item.techVendorType, (typeCount.get(item.techVendorType) || 0) + 1);
      }
    }
  });

  return Array.from(typeCount.entries())
    .sort((a, b) => b[1] - a[1])
    .map(([type, count]) => [`  - ${type}`, count.toLocaleString()]);
}