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
|
"use client"
import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { Plus ,X} from "lucide-react"
import { toast } from "sonner"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import {
Dropzone,
DropzoneDescription,
DropzoneInput,
DropzoneTitle,
DropzoneUploadIcon,
DropzoneZone,
} from "@/components/ui/dropzone"
import {
FileList,
FileListAction,
FileListDescription,
FileListHeader,
FileListIcon,
FileListInfo,
FileListItem,
FileListName,
FileListSize,
} from "@/components/ui/file-list"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { addRfqAttachmentRecord } from "../service"
// 첨부파일 추가 폼 스키마 (단일 파일)
const addAttachmentSchema = z.object({
attachmentType: z.enum(["구매", "설계"], {
required_error: "문서 타입을 선택해주세요.",
}),
description: z.string().optional(),
file: z.instanceof(File, {
message: "파일을 선택해주세요.",
}),
})
type AddAttachmentFormData = z.infer<typeof addAttachmentSchema>
interface AddAttachmentDialogProps {
rfqId: number
}
export function AddAttachmentDialog({ rfqId }: AddAttachmentDialogProps) {
const [open, setOpen] = React.useState(false)
const [isSubmitting, setIsSubmitting] = React.useState(false)
const [uploadProgress, setUploadProgress] = React.useState<number>(0)
const form = useForm<AddAttachmentFormData>({
resolver: zodResolver(addAttachmentSchema),
defaultValues: {
attachmentType: undefined,
description: "",
file: undefined,
},
})
const selectedFile = form.watch("file")
// 다이얼로그 닫기 핸들러
const handleOpenChange = (newOpen: boolean) => {
if (!newOpen && !isSubmitting) {
form.reset()
}
setOpen(newOpen)
}
// 파일 선택 처리
const handleFileChange = (files: File[]) => {
if (files.length === 0) return
const file = files[0] // 첫 번째 파일만 사용
// 파일 크기 검증
const maxFileSize = 10 * 1024 * 1024 // 10MB
if (file.size > maxFileSize) {
toast.error(`파일이 너무 큽니다. (최대 10MB)`)
return
}
form.setValue("file", file)
form.clearErrors("file")
}
// 파일 제거
const removeFile = () => {
form.resetField("file")
}
// 파일 업로드 API 호출
const uploadFile = async (file: File): Promise<{
fileName: string
originalFileName: string
filePath: string
fileSize: number
fileType: string
}> => {
const formData = new FormData()
formData.append("rfqId", rfqId.toString())
formData.append("file", file)
const response = await fetch("/api/upload/rfq-attachment", {
method: "POST",
body: formData,
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.message || "파일 업로드 실패")
}
return response.json()
}
// 폼 제출
const onSubmit = async (data: AddAttachmentFormData) => {
setIsSubmitting(true)
setUploadProgress(0)
try {
// 1단계: 파일 업로드
setUploadProgress(30)
const uploadedFile = await uploadFile(data.file)
// 2단계: DB 레코드 생성 (시리얼 번호 자동 생성)
setUploadProgress(70)
const attachmentRecord = {
rfqId,
attachmentType: data.attachmentType,
description: data.description,
fileName: uploadedFile.fileName,
originalFileName: uploadedFile.originalFileName,
filePath: uploadedFile.filePath,
fileSize: uploadedFile.fileSize,
fileType: uploadedFile.fileType,
}
const result = await addRfqAttachmentRecord(attachmentRecord)
setUploadProgress(100)
if (result.success) {
toast.success(result.message)
form.reset()
handleOpenChange(false)
} else {
toast.error(result.message)
}
} catch (error) {
console.error("Upload error:", error)
toast.error(error instanceof Error ? error.message : "파일 업로드 중 오류가 발생했습니다.")
} finally {
setIsSubmitting(false)
setUploadProgress(0)
}
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant="outline" size="sm" className="gap-2">
<Plus className="size-4" aria-hidden="true" />
<span className="hidden sm:inline">새 첨부</span>
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>새 첨부파일 추가</DialogTitle>
<DialogDescription>
RFQ에 첨부할 문서를 업로드합니다. 시리얼 번호는 자동으로 부여됩니다.
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* 문서 타입 선택 */}
<FormField
control={form.control}
name="attachmentType"
render={({ field }) => (
<FormItem>
<FormLabel>문서 타입</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="문서 타입을 선택하세요" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="구매">구매</SelectItem>
<SelectItem value="설계">설계</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
{/* 설명 */}
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>설명 (선택)</FormLabel>
<FormControl>
<Textarea
placeholder="첨부파일에 대한 설명을 입력하세요"
className="resize-none"
rows={3}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* 파일 선택 - Dropzone (단일 파일) */}
<FormField
control={form.control}
name="file"
render={({ field }) => (
<FormItem>
<FormLabel>파일 선택</FormLabel>
<FormControl>
<div className="space-y-3">
<Dropzone
onDrop={(acceptedFiles) => {
handleFileChange(acceptedFiles)
}}
accept={{
'application/pdf': ['.pdf'],
'application/msword': ['.doc'],
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'],
'application/vnd.ms-excel': ['.xls'],
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
'application/vnd.ms-powerpoint': ['.ppt'],
'application/vnd.openxmlformats-officedocument.presentationml.presentation': ['.pptx'],
'application/zip': ['.zip'],
'application/x-rar-compressed': ['.rar']
}}
maxSize={10 * 1024 * 1024} // 10MB
multiple={false} // 단일 파일만
disabled={isSubmitting}
>
<DropzoneZone>
<DropzoneUploadIcon />
<DropzoneTitle>클릭하여 파일 선택 또는 드래그 앤 드롭</DropzoneTitle>
<DropzoneDescription>
PDF, DOC, XLS, PPT 등 (최대 10MB, 파일 1개)
</DropzoneDescription>
<DropzoneInput />
</DropzoneZone>
</Dropzone>
{/* 선택된 파일 표시 */}
{selectedFile && (
<div className="space-y-2">
<FileListHeader>
선택된 파일
</FileListHeader>
<FileList>
<FileListItem className="flex items-center justify-between gap-3">
<FileListIcon />
<FileListInfo>
<FileListName>{selectedFile.name}</FileListName>
<FileListDescription>
<FileListSize>{selectedFile.size}</FileListSize>
</FileListDescription>
</FileListInfo>
<FileListAction
onClick={removeFile}
disabled={isSubmitting}
>
<X className="h-4 w-4" />
</FileListAction>
</FileListItem>
</FileList>
</div>
)}
{/* 업로드 진행률 */}
{isSubmitting && uploadProgress > 0 && (
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span>업로드 진행률</span>
<span>{uploadProgress}%</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className="bg-blue-600 h-2 rounded-full transition-all duration-300"
style={{ width: `${uploadProgress}%` }}
/>
</div>
</div>
)}
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isSubmitting}
>
취소
</Button>
<Button type="submit" disabled={isSubmitting || !selectedFile}>
{isSubmitting ? "업로드 중..." : "업로드"}
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
)
}
|