summaryrefslogtreecommitdiff
path: root/lib/evaluation-criteria/table/reg-eval-criteria-table-toolbar-actions.tsx
blob: f066fa92a624723b8b0f27cb2103c4d4898169a1 (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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
'use client';

/* IMPORT */
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Download, Plus, Trash2, Upload } from 'lucide-react';
import { exportRegEvalCriteriaToExcel, exportRegEvalCriteriaTemplate } from '../excel/reg-eval-criteria-excel-export';
import { importRegEvalCriteriaExcel } from '../excel/reg-eval-criteria-excel-import';
import { removeRegEvalCriteria } from '../service';
import { toast } from 'sonner';
import { type RegEvalCriteriaView } from '@/db/schema';
import { type Table } from '@tanstack/react-table';
import { ChangeEvent, useMemo, useRef, useState } from 'react';

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

/* TYPES */
interface RegEvalCriteriaTableToolbarActionsProps {
  table: Table<RegEvalCriteriaView>,
  onCreateCriteria: () => void,
  onRefresh: () => void,
}

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

/* REGULAR EVALUATION CRITERIA TABLE TOOLBAR ACTIONS COMPONENT */
function RegEvalCriteriaTableToolbarActions(props: RegEvalCriteriaTableToolbarActionsProps) {
  const { table, onCreateCriteria, onRefresh } = props;
  const [isDeleting, setIsDeleting] = useState<boolean>(false);
  const selectedRows = table.getFilteredSelectedRowModel().rows;
  const hasSelection = selectedRows.length > 0;
  const selectedIds = useMemo(() => {
    return [...new Set(selectedRows.map(row => row.original.criteriaId))];
  }, [selectedRows]);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Function for Create New Criteria
  const handleCreateNew = () => {
    onCreateCriteria();
  }

  const handleDeleteSelected = async () => {
    if (!hasSelection) {
      return;
    }
    try {
      setIsDeleting(true);

      for (const selectedId of selectedIds) {
        if (selectedId) {
          await removeRegEvalCriteria(selectedId);
        }
      }
      table.resetRowSelection();
      toast.success(`${selectedIds.length}개의 평가 기준이 삭제되었습니다.`);
      onRefresh();
    } catch (error) {
      console.error('Error in Deleting Regular Evaluation Critria: ', error);
      toast.error(
        error instanceof Error
          ? error.message
          : '평가 기준 삭제 중 오류가 발생했습니다.'
      );
    } finally {
      setIsDeleting(false);
    }
  }

  // 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 importRegEvalCriteriaExcel(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 {
      await exportRegEvalCriteriaToExcel(table, {
        filename: 'Regular_Evaluation_Criteria',
        excludeColumns: ['select', 'actions'],
      });
      toast.success('Excel 파일이 다운로드되었습니다.');
    } catch (error) {
      console.error('Error in Exporting to Excel: ', error);
      toast.error('Excel 내보내기 중 오류가 발생했습니다.');
    }
  };

  // Excel Template Download
  const handleTemplateDownload = async () => {
    try {
      await exportRegEvalCriteriaTemplate();
      toast.success('템플릿 파일이 다운로드되었습니다.');
    } catch (error) {
      console.error('Error in Template Download: ', error);
      toast.error('템플릿 다운로드 중 오류가 발생했습니다.');
    }
  };

  return (
    <div className="flex items-center gap-2">
      <Button
        variant="default"
        size="sm"
        className="gap-2"
        onClick={handleCreateNew}
      >
        <Plus className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">New Criteria</span>
      </Button>
      {hasSelection && (
        <AlertDialog>
          <AlertDialogTrigger asChild>
            <Button
              variant="destructive"
              size="sm"
              className="gap-2"
              disabled={isDeleting}
            >
              <Trash2 className="size-4" aria-hidden="true" />
              <span className="hidden sm:inline">
                선택 삭제 ({selectedIds.length})
              </span>
            </Button>
          </AlertDialogTrigger>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>정말 삭제하시겠습니까?</AlertDialogTitle>
              <AlertDialogDescription>
                선택된 {selectedIds.length}개의 협력업체 평가 기준 항목이 영구적으로 삭제됩니다. 
                이 작업은 되돌릴 수 없으며, 연관된 평가 기준과 항목들도 함께 삭제됩니다.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>Cancel</AlertDialogCancel>
              <AlertDialogAction
                onClick={handleDeleteSelected}
                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              >
                {isDeleting ? 'Deleting...' : 'Delete'}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      )}
      <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"
      >
        <Download className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">Template</span>
      </Button>
    </div>
  );
}

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

/* EXPORT */
export default RegEvalCriteriaTableToolbarActions;