summaryrefslogtreecommitdiff
path: root/lib/risk-management/table/risks-table-toolbar-actions.tsx
blob: a55634b5edf5dd34976ecdad4a57eba089a3b595 (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
'use client';

/* IMPORT */
import { Button } from '@/components/ui/button';
import { ChangeEvent, useRef } from 'react';
import { Download, FileInput, Mail, Upload } from 'lucide-react';
import { exportTableToExcel } from '@/lib/export';
import { generateRiskEventsTemplate, importRiskEventsExcel } from '../service';
import { toast } from 'sonner';
import { type DataTableRowAction } from '@/types/table';
import { type RisksView } from '@/db/schema';
import { type Table } from '@tanstack/react-table';

// ----------------------------------------------------------------------------------------------------

/* TYPES */
interface RisksTableToolbarActionsProps {
  table: Table<RisksView>;
  onOpenMailDialog: () => void;
  onRefresh: () => void;
}

// ----------------------------------------------------------------------------------------------------

/* RISKS TABLE TOOLBAR ACTIONS COMPONENT */
function RisksTableToolbarActions(props: RisksTableToolbarActionsProps) {
  const { table, onOpenMailDialog, onRefresh } = props;
  const selectedRows = table.getFilteredSelectedRowModel().rows;
  const hasSelection = selectedRows.length > 0;
  const fileInputRef = useRef<HTMLInputElement>(null);

  // EXCEL IMPORT
  function handleImport() {
    fileInputRef.current?.click();
  };
  async function onFileChange(event: ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file) {
      toast.error('가져올 파일을 선택해주십시오.');
      return;
    }
    if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
      toast.error('.xlsx 또는 .xls 확장자인 Excel 파일만 업로드 가능합니다.');
      return;
    }
    event.target.value = '';

    try {
      const { errorFile, errorMessage, successMessage } = await importRiskEventsExcel(file);

      if (errorMessage) {
        toast.error(errorMessage);
 
        if (errorFile) {
          const url = URL.createObjectURL(errorFile);
          const link = document.createElement('a');
          link.href = url;
          link.download = 'errors.xlsx';
          link.click();
          URL.revokeObjectURL(url);
        }
      } else {
        toast.success(successMessage || 'Excel 파일이 성공적으로 업로드되었습니다.');
      }
    } catch (error) {
      toast.error('Excel 파일을 업로드하는 중 오류가 발생했습니다.');
      console.error('Error in Excel File Upload: ', error);
    } finally {
      onRefresh();
    }
  };

  // EXCEL EXPORT
  const handleExport = async () => {
    try {
      exportTableToExcel(table, {
        filename: '협력업체_리스크_관리',
        excludeColumns: ['id', 'actions'],
      });
      toast.success('Excel 파일이 다운로드되었습니다.');
    } catch (error) {
      console.error('Error in Exporting to Excel: ', error);
      toast.error('Excel 파일 내보내기 중 오류가 발생했습니다.');
    }
  };

  // EXCEL TEMPLATE DOWNLOAD
  const handleTemplateDownload = async () => {
    try {
      const buffer = await generateRiskEventsTemplate();
      const blob = new Blob([buffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = "협력업체_리스크_템플릿.xlsx";
      link.click();
      URL.revokeObjectURL(url);
      toast.success('템플릿 파일이 다운로드되었습니다.');
    } catch (error) {
      console.error('Error in Template Download: ', error);
      toast.error('템플릿 다운로드 중 오류가 발생했습니다.');
    }
  };

  return (
    <div className="flex items-center gap-2">
      <Button
        size="sm"
        className="gap-2"
        onClick={onOpenMailDialog}
        disabled={!hasSelection}
      >
        <Mail className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">
          메일 발송
        </span>
      </Button>
      <Button
        variant="outline"
        size="sm"
        className="gap-2"
        onClick={handleImport}
      >
        <Upload className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">Import</span>
      </Button>
      <input
        ref={fileInputRef}
        type="file"
        accept=".xlsx,.xls"
        className="hidden"
        onChange={onFileChange}
      />
      <Button
        variant="outline"
        size="sm"
        onClick={handleExport}
        className="gap-2"
      >
        <Download className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">Export</span>
      </Button>
      <Button
        variant="outline"
        size="sm"
        onClick={handleTemplateDownload}
        className="gap-2"
      >
        <FileInput className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">Template</span>
      </Button>
    </div>
  );
}

// ----------------------------------------------------------------------------------------------------

/* EXPORT */
export default RisksTableToolbarActions;