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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
|
"use client"
import { useState, useRef } from "react"
import { useSession } from "next-auth/react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Alert, AlertDescription } from "@/components/ui/alert"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import {
Upload,
FileText,
File,
Trash2,
Download,
AlertCircle,
Paperclip,
FileCheck,
Calculator,
Wrench,
X
} from "lucide-react"
import { formatBytes } from "@/lib/utils"
import { cn } from "@/lib/utils"
import { toast } from "sonner"
import { deleteVendorResponseAttachment } from "../../service"
interface FileWithType extends File {
attachmentType?: "구매" | "설계"
description?: string
}
interface AttachmentsUploadProps {
attachments: FileWithType[]
onAttachmentsChange: (files: FileWithType[]) => void
existingAttachments?: any[]
onExistingAttachmentsChange?: (files: any[]) => void
responseId?: number
userId?: number
}
const acceptedFileTypes = {
documents: ".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx",
images: ".jpg,.jpeg,.png,.gif,.bmp",
compressed: ".zip,.rar,.7z",
all: ".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.gif,.bmp,.zip,.rar,.7z"
}
export default function AttachmentsUpload({
attachments,
onAttachmentsChange,
existingAttachments = [],
onExistingAttachmentsChange,
responseId,
userId
}: AttachmentsUploadProps) {
const purchaseInputRef = useRef<HTMLInputElement>(null)
const designInputRef = useRef<HTMLInputElement>(null)
const [purchaseDragActive, setPurchaseDragActive] = useState(false)
const [designDragActive, setDesignDragActive] = useState(false)
const [uploadErrors, setUploadErrors] = useState<string[]>([])
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const [fileToDelete, setFileToDelete] = useState<{file: any, isExisting: boolean, index: number} | null>(null)
// 파일 유효성 검사
const validateFile = (file: File): string | null => {
const maxSize = 1024 * 1024 * 1024 // 10MB
const allowedExtensions = acceptedFileTypes.all.split(',')
const fileExtension = `.${file.name.split('.').pop()?.toLowerCase()}`
if (file.size > maxSize) {
return `${file.name}: 파일 크기가 1GB를 초과합니다`
}
if (!allowedExtensions.includes(fileExtension)) {
return `${file.name}: 허용되지 않은 파일 형식입니다`
}
return null
}
// 파일 추가
const handleFileAdd = (files: FileList | null, type: "구매" | "설계") => {
if (!files) return
const newFiles: FileWithType[] = []
const errors: string[] = []
Array.from(files).forEach(file => {
const error = validateFile(file)
if (error) {
errors.push(error)
} else {
const fileWithType = Object.assign(file, {
attachmentType: type,
description: ""
})
newFiles.push(fileWithType)
}
})
if (errors.length > 0) {
setUploadErrors(errors)
setTimeout(() => setUploadErrors([]), 5000)
}
if (newFiles.length > 0) {
onAttachmentsChange([...attachments, ...newFiles])
}
}
// 구매 드래그 앤 드롭 핸들러
const handlePurchaseDrag = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
if (e.type === "dragenter" || e.type === "dragover") {
setPurchaseDragActive(true)
} else if (e.type === "dragleave") {
setPurchaseDragActive(false)
}
}
const handlePurchaseDrop = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
setPurchaseDragActive(false)
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
handleFileAdd(e.dataTransfer.files, "구매")
}
}
// 설계 드래그 앤 드롭 핸들러
const handleDesignDrag = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
if (e.type === "dragenter" || e.type === "dragover") {
setDesignDragActive(true)
} else if (e.type === "dragleave") {
setDesignDragActive(false)
}
}
const handleDesignDrop = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
setDesignDragActive(false)
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
handleFileAdd(e.dataTransfer.files, "설계")
}
}
// 파일 삭제
const handleFileRemove = (index: number) => {
const newFiles = attachments.filter((_, i) => i !== index)
onAttachmentsChange(newFiles)
}
// 파일 타입 변경
const handleTypeChange = (index: number, newType: "구매" | "설계") => {
const newFiles = [...attachments]
newFiles[index].attachmentType = newType
onAttachmentsChange(newFiles)
}
// 파일 삭제 확인
const handleDeleteClick = (file: any, isExisting: boolean, index: number) => {
setFileToDelete({ file, isExisting, index })
setDeleteDialogOpen(true)
}
// 파일 삭제 실행
const handleDeleteConfirm = async () => {
if (!fileToDelete) return
const { isExisting, index } = fileToDelete
if (isExisting) {
// 기존 첨부파일 삭제 - 서버액션 호출
if (responseId && userId && fileToDelete.file.id) {
try {
const result = await deleteVendorResponseAttachment({
attachmentId: fileToDelete.file.id,
responseId,
userId
})
if (result.success) {
// 클라이언트 상태 업데이트
const newExistingAttachments = existingAttachments.filter((_, i) => i !== index)
onExistingAttachmentsChange?.(newExistingAttachments)
} else {
toast.error(`삭제 실패: ${result.error}`)
return
}
} catch (error) {
console.error('삭제 API 호출 실패:', error)
toast.error('삭제 중 오류가 발생했습니다.')
return
}
}
} else {
// 새 첨부파일 삭제 (클라이언트에서만)
const newFiles = attachments.filter((_, i) => i !== index)
onAttachmentsChange(newFiles)
}
setDeleteDialogOpen(false)
setFileToDelete(null)
}
// 파일 삭제 취소
const handleDeleteCancel = () => {
setDeleteDialogOpen(false)
setFileToDelete(null)
}
// 파일 아이콘 가져오기
const getFileIcon = (fileName: string) => {
const extension = fileName.split('.').pop()?.toLowerCase()
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
if (imageExtensions.includes(extension || '')) {
return <File className="h-4 w-4 text-blue-500" />
}
return <FileText className="h-4 w-4 text-gray-500" />
}
// 구매/설계 문서 개수 계산
const purchaseCount = attachments.filter(f => f.attachmentType === "구매").length +
existingAttachments.filter(f => f.attachmentType === "구매").length
const designCount = attachments.filter(f => f.attachmentType === "설계").length +
existingAttachments.filter(f => f.attachmentType === "설계").length
return (
<div className="space-y-4">
{/* 필수 파일 안내 */}
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<strong>문서 분류:</strong> 구매 문서(견적서, 상업조건 등)와 설계 문서(기술문서, 성적서, 인증서 등)를 구분하여 업로드하세요.
<br />
<strong>허용 파일:</strong> PDF, Word, Excel, PowerPoint, 이미지 파일, 압축 파일(ZIP, RAR, 7Z) (최대 1GB)
</AlertDescription>
</Alert>
{/* 업로드 오류 표시 */}
{uploadErrors.length > 0 && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<ul className="list-disc list-inside">
{uploadErrors.map((error, index) => (
<li key={index}>{error}</li>
))}
</ul>
</AlertDescription>
</Alert>
)}
{/* 두 개의 드래그존 */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{/* 구매 문서 업로드 영역 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Calculator className="h-5 w-5" />
구매 문서
</CardTitle>
<CardDescription>
견적서, 금액, 상업조건 관련 문서
</CardDescription>
</CardHeader>
<CardContent>
<div
className={cn(
"border-2 border-dashed rounded-lg p-6 text-center transition-colors",
purchaseDragActive ? "border-blue-500 bg-blue-50" : "border-gray-300",
"hover:border-blue-400 hover:bg-blue-50/50"
)}
onDragEnter={handlePurchaseDrag}
onDragLeave={handlePurchaseDrag}
onDragOver={handlePurchaseDrag}
onDrop={handlePurchaseDrop}
>
<Calculator className="mx-auto h-10 w-10 text-blue-500 mb-3" />
<p className="text-sm text-gray-600 mb-2">
구매 문서를 드래그하여 업로드
</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => purchaseInputRef.current?.click()}
className="border-blue-500 text-blue-600 hover:bg-blue-50"
>
<Paperclip className="h-4 w-4 mr-2" />
구매 문서 선택
</Button>
<input
ref={purchaseInputRef}
type="file"
multiple
accept={acceptedFileTypes.all}
onChange={(e) => handleFileAdd(e.target.files, "구매")}
className="hidden"
/>
{purchaseCount > 0 && (
<div className="mt-2">
<Badge variant="secondary">{purchaseCount}개 업로드됨</Badge>
</div>
)}
</div>
</CardContent>
</Card>
{/* 설계 문서 업로드 영역 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Wrench className="h-5 w-5" />
설계 문서
</CardTitle>
<CardDescription>
기술문서, 성적서, 인증서, 도면 등
</CardDescription>
</CardHeader>
<CardContent>
<div
className={cn(
"border-2 border-dashed rounded-lg p-6 text-center transition-colors",
designDragActive ? "border-green-500 bg-green-50" : "border-gray-300",
"hover:border-green-400 hover:bg-green-50/50"
)}
onDragEnter={handleDesignDrag}
onDragLeave={handleDesignDrag}
onDragOver={handleDesignDrag}
onDrop={handleDesignDrop}
>
<Wrench className="mx-auto h-10 w-10 text-green-500 mb-3" />
<p className="text-sm text-gray-600 mb-2">
설계 문서를 드래그하여 업로드
</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => designInputRef.current?.click()}
className="border-green-500 text-green-600 hover:bg-green-50"
>
<Paperclip className="h-4 w-4 mr-2" />
설계 문서 선택
</Button>
<input
ref={designInputRef}
type="file"
multiple
accept={acceptedFileTypes.all}
onChange={(e) => handleFileAdd(e.target.files, "설계")}
className="hidden"
/>
{designCount > 0 && (
<div className="mt-2">
<Badge variant="secondary">{designCount}개 업로드됨</Badge>
</div>
)}
{/* <p className="text-xs text-gray-500 mt-2">
최대 1GB, 여러 파일 선택 가능
</p> */}
</div>
</CardContent>
</Card>
</div>
{/* 첨부파일 목록 */}
{(attachments.length > 0 || existingAttachments.length > 0) && (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>첨부파일 목록</CardTitle>
<div className="flex items-center gap-2">
<Badge variant="outline" className="gap-1">
<Calculator className="h-3 w-3" />
구매 {purchaseCount}
</Badge>
<Badge variant="outline" className="gap-1">
<Wrench className="h-3 w-3" />
설계 {designCount}
</Badge>
<Badge variant="secondary">
총 {attachments.length + existingAttachments.length}개
</Badge>
</div>
</div>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[50px]">유형</TableHead>
<TableHead>파일명</TableHead>
<TableHead className="w-[100px]">크기</TableHead>
<TableHead className="w-[120px]">문서 구분</TableHead>
<TableHead className="w-[100px]">상태</TableHead>
<TableHead className="w-[80px]">작업</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{/* 기존 첨부파일 */}
{existingAttachments.map((file, index) => (
<TableRow key={`existing-${index}`}>
<TableCell>
{getFileIcon(file.originalFileName)}
</TableCell>
<TableCell>
<div>
<p className="font-medium">{file.originalFileName}</p>
{file.description && (
<p className="text-xs text-muted-foreground">
{file.description}
</p>
)}
</div>
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{formatBytes(file.fileSize || 0)}
</TableCell>
<TableCell>
<Badge
variant={file.attachmentType === "구매" ? "default" : "secondary"}
className="gap-1"
>
{file.attachmentType === "구매" ?
<Calculator className="h-3 w-3" /> :
<Wrench className="h-3 w-3" />
}
{file.attachmentType}
</Badge>
</TableCell>
<TableCell>
<Badge variant="secondary">
<FileCheck className="h-3 w-3 mr-1" />
기존
</Badge>
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(file.filePath, '_blank')}
>
<Download className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => handleDeleteClick(file, true, index)}
>
<Trash2 className="h-4 w-4 text-red-500" />
</Button>
</div>
</TableCell>
</TableRow>
))}
{/* 새로 추가된 파일 */}
{attachments.map((file, index) => (
<TableRow key={`new-${index}`}>
<TableCell>
{getFileIcon(file.name)}
</TableCell>
<TableCell>
<div>
<p className="font-medium">{file.name}</p>
</div>
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{formatBytes(file.size)}
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
<Button
type="button"
variant={file.attachmentType === "구매" ? "default" : "ghost"}
size="sm"
className="h-7 px-2 text-xs"
onClick={() => handleTypeChange(index, "구매")}
>
<Calculator className="h-3 w-3 mr-1" />
구매
</Button>
<Button
type="button"
variant={file.attachmentType === "설계" ? "default" : "ghost"}
size="sm"
className="h-7 px-2 text-xs"
onClick={() => handleTypeChange(index, "설계")}
>
<Wrench className="h-3 w-3 mr-1" />
설계
</Button>
</div>
</TableCell>
<TableCell>
<Badge variant="default">
<Upload className="h-3 w-3 mr-1" />
신규
</Badge>
</TableCell>
<TableCell>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => handleDeleteClick(file, false, index)}
>
<Trash2 className="h-4 w-4 text-red-500" />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
)}
{/* 파일 삭제 확인 다이얼로그 */}
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>파일 삭제</DialogTitle>
<DialogDescription>
{fileToDelete?.isExisting ? '기존 첨부파일' : '새로 업로드한 파일'} "{fileToDelete?.file.originalFileName || fileToDelete?.file.name}"을(를) 삭제하시겠습니까?
<br />
<strong>삭제된 파일은 복구할 수 없습니다.</strong>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={handleDeleteCancel}
>
취소
</Button>
<Button
type="button"
variant="destructive"
onClick={handleDeleteConfirm}
>
<Trash2 className="h-4 w-4 mr-2" />
삭제
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
|