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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
|
"use client"
import * as React from "react"
import type { Table } from "@tanstack/react-table"
import { Plus, Trash2, Upload, Download, Users } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import type { TechVendorPossibleItem } from "../validations"
import {
deleteTechVendorPossibleItemsNew,
parsePossibleItemsImportFile,
importPossibleItemsFromExcel,
generatePossibleItemsImportTemplate,
generatePossibleItemsErrorExcel,
type PossibleItemImportData,
type PossibleItemErrorData,
// Contact Possible Import 관련 함수들
parseContactPossibleItemsImportFile,
importContactPossibleItemsFromExcel,
generateContactPossibleItemsImportTemplate,
generateContactPossibleItemsErrorExcel,
type ContactPossibleItemImportData,
type ContactPossibleItemErrorData
} from "../service"
interface PossibleItemsTableToolbarActionsProps {
table: Table<TechVendorPossibleItem>
vendorId: number
onAdd: () => void // 주석처리
onRefresh?: () => void // 데이터 새로고침 콜백
}
export function PossibleItemsTableToolbarActions({
table,
vendorId,
onAdd, // 주석처리
onRefresh,
}: PossibleItemsTableToolbarActionsProps) {
const [showDeleteAlert, setShowDeleteAlert] = React.useState(false)
const [isDeleting, setIsDeleting] = React.useState(false)
const [isImporting, setIsImporting] = React.useState(false)
const [isContactImporting, setIsContactImporting] = React.useState(false)
const fileInputRef = React.useRef<HTMLInputElement>(null)
const contactFileInputRef = React.useRef<HTMLInputElement>(null)
const selectedRows = table.getFilteredSelectedRowModel().rows
async function handleDelete() {
setIsDeleting(true)
try {
const ids = selectedRows.map((row) => row.original.id)
const { error } = await deleteTechVendorPossibleItemsNew(ids, vendorId)
if (error) {
throw new Error(error)
}
toast.success(`${ids.length}개의 아이템이 삭제되었습니다`)
table.resetRowSelection()
setShowDeleteAlert(false)
onRefresh?.() // 데이터 새로고침
} catch {
toast.error("아이템 삭제 중 오류가 발생했습니다")
} finally {
setIsDeleting(false)
}
}
// 템플릿 다운로드 핸들러
async function handleTemplateDownload() {
try {
const templateBlob = await generatePossibleItemsImportTemplate()
const url = window.URL.createObjectURL(templateBlob)
const link = document.createElement("a")
link.href = url
link.download = "벤더_possible_items_템플릿.xlsx"
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(url)
toast.success("템플릿 파일이 다운로드되었습니다")
} catch (error) {
toast.error("템플릿 다운로드 중 오류가 발생했습니다")
}
}
// 파일 선택 핸들러
function handleFileSelect() {
fileInputRef.current?.click()
}
// Excel 파일 import 핸들러
async function handleFileImport(event: React.ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0]
if (!file) return
// 파일 타입 검증
if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
toast.error("Excel 파일(.xlsx 또는 .xls)만 업로드 가능합니다")
return
}
setIsImporting(true)
try {
// Excel 파일 파싱
const importData: PossibleItemImportData[] = await parsePossibleItemsImportFile(file)
if (importData.length === 0) {
toast.error("업로드할 데이터가 없습니다")
return
}
// 데이터 import 실행
const result = await importPossibleItemsFromExcel(importData)
// 결과 메시지 생성
const successMessage = `${result.successCount}개의 아이템이 성공적으로 등록되었습니다`
const failMessage = result.failedRows.length > 0
? `, ${result.failedRows.length}개의 아이템 등록 실패`
: ""
toast.success(successMessage + failMessage)
// 실패한 행이 있는 경우 에러 파일 다운로드
if (result.failedRows.length > 0) {
const errorData: PossibleItemErrorData[] = result.failedRows.map(failedRow => ({
vendorEmail: failedRow.vendorEmail,
itemCode: failedRow.itemCode,
itemType: failedRow.itemType,
error: failedRow.error,
}))
const errorBlob = await generatePossibleItemsErrorExcel(errorData)
const url = window.URL.createObjectURL(errorBlob)
const link = document.createElement("a")
link.href = url
link.download = "possible_items_import_에러.xlsx"
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(url)
toast.error("에러 내역 파일이 다운로드되었습니다")
}
// 파일 입력 초기화
if (fileInputRef.current) {
fileInputRef.current.value = ""
}
// 데이터 새로고침
onRefresh?.()
} catch (error) {
console.error("Import error:", error)
toast.error(error instanceof Error ? error.message : "데이터 등록 중 오류가 발생했습니다")
} finally {
setIsImporting(false)
}
}
// Contact Possible Import용 템플릿 다운로드 핸들러
async function handleContactTemplateDownload() {
try {
const templateBlob = await generateContactPossibleItemsImportTemplate()
const url = window.URL.createObjectURL(templateBlob)
const link = document.createElement("a")
link.href = url
link.download = "담당자별_아이템매핑_템플릿.xlsx"
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(url)
toast.success("템플릿 파일이 다운로드되었습니다")
} catch (error) {
toast.error("템플릿 다운로드 중 오류가 발생했습니다")
}
}
// Contact Possible Import용 파일 선택 핸들러
function handleContactFileSelect() {
contactFileInputRef.current?.click()
}
// Contact Possible Import 핸들러
async function handleContactFileImport(event: React.ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0]
if (!file) return
// 파일 타입 검증
if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
toast.error("Excel 파일(.xlsx 또는 .xls)만 업로드 가능합니다")
return
}
setIsContactImporting(true)
try {
// Excel 파일 파싱 (새로운 함수 사용)
const importData: ContactPossibleItemImportData[] = await parseContactPossibleItemsImportFile(file)
if (importData.length === 0) {
toast.error("업로드할 데이터가 없습니다")
return
}
// 데이터 import 실행 (새로운 함수 사용)
const result = await importContactPossibleItemsFromExcel(importData)
console.log(result)
// 결과 메시지 생성
const successMessage = `${result.successCount}개의 아이템 매핑이 성공적으로 등록되었습니다`
const failMessage = result.failedRows.length > 0
? `, ${result.failedRows.length}개의 매핑 등록 실패`
: ""
toast.success(successMessage + failMessage)
// 실패한 행이 있는 경우 에러 파일 다운로드
if (result.failedRows.length > 0) {
const errorData: ContactPossibleItemErrorData[] = result.failedRows.map(failedRow => ({
contactEmail: failedRow.contactEmail,
itemCode: Array.isArray(failedRow.itemCode) ? failedRow.itemCode.join(', ') : failedRow.itemCode,
error: failedRow.error,
}))
const errorBlob = await generateContactPossibleItemsErrorExcel(errorData)
const url = window.URL.createObjectURL(errorBlob)
const link = document.createElement("a")
link.href = url
link.download = "contact_possible_items_import_에러.xlsx"
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(url)
toast.error("에러 내역 파일이 다운로드되었습니다")
}
// 파일 입력 초기화
if (contactFileInputRef.current) {
contactFileInputRef.current.value = ""
}
// 데이터 새로고침
onRefresh?.()
} catch (error) {
console.error("Contact Possible Import error:", error)
toast.error(error instanceof Error ? error.message : "데이터 등록 중 오류가 발생했습니다")
} finally {
setIsContactImporting(false)
}
}
return (
<>
<div className="flex items-center gap-2">
{/* 템플릿 다운로드 버튼 */}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="sm"
onClick={handleTemplateDownload}
>
<Download className="mr-2 h-4 w-4" />
템플릿
</Button>
</TooltipTrigger>
<TooltipContent>
Excel 템플릿 파일 다운로드
</TooltipContent>
</Tooltip>
{/* Excel Import 버튼 */}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="sm"
onClick={handleFileSelect}
disabled={isImporting}
>
<Upload className="mr-2 h-4 w-4" />
{isImporting ? "등록 중..." : "Import"}
</Button>
</TooltipTrigger>
<TooltipContent>
Excel 파일로 아이템 일괄 등록
</TooltipContent>
</Tooltip>
{/* Contact Possible Import 템플릿 버튼 */}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="sm"
onClick={handleContactTemplateDownload}
>
<Download className="mr-2 h-4 w-4" />
담당자 템플릿
</Button>
</TooltipTrigger>
<TooltipContent>
담당자별 아이템 매핑 템플릿 다운로드
</TooltipContent>
</Tooltip>
{/* Contact Possible Import 버튼 */}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="sm"
onClick={handleContactFileSelect}
disabled={isContactImporting}
>
<Users className="mr-2 h-4 w-4" />
{isContactImporting ? "등록 중..." : "Contact Import"}
</Button>
</TooltipTrigger>
<TooltipContent>
담당자별 아이템 매핑 등록
</TooltipContent>
</Tooltip>
{/* 숨겨진 파일 입력들 */}
<input
ref={fileInputRef}
type="file"
accept=".xlsx,.xls"
onChange={handleFileImport}
className="hidden"
/>
{/* Contact Possible Import용 숨겨진 파일 입력 */}
<input
ref={contactFileInputRef}
type="file"
accept=".xlsx,.xls"
onChange={handleContactFileImport}
className="hidden"
/>
{/* 아이템 추가 버튼 주석처리 */}
<Button
variant="outline"
size="sm"
onClick={onAdd}
>
<Plus className="mr-2 h-4 w-4" />
아이템 연결
</Button>
{selectedRows.length > 0 && (
<>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="sm"
onClick={() => setShowDeleteAlert(true)}
disabled={selectedRows.length === 0}
>
<Trash2 className="mr-2 h-4 w-4" />
삭제 ({selectedRows.length})
</Button>
</TooltipTrigger>
<TooltipContent>
선택된 {selectedRows.length}개 아이템을 삭제합니다
</TooltipContent>
</Tooltip>
</>
)}
</div>
<AlertDialog open={showDeleteAlert} onOpenChange={setShowDeleteAlert}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>아이템 삭제</AlertDialogTitle>
<AlertDialogDescription>
선택된 {selectedRows.length}개의 아이템을 삭제하시겠습니까?
이 작업은 되돌릴 수 없습니다.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>취소</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? "삭제 중..." : "삭제"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
|