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
|
"use client"
import * as React from "react"
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetDescription,
SheetFooter,
SheetClose,
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import {
Dropzone,
DropzoneDescription,
DropzoneInput,
DropzoneTitle,
DropzoneUploadIcon,
DropzoneZone,
} from "@/components/ui/dropzone"
import {
FileList,
FileListAction,
FileListDescription,
FileListHeader,
FileListIcon,
FileListInfo,
FileListItem,
FileListName,
} from "@/components/ui/file-list"
import { Badge } from "@/components/ui/badge"
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel } from "@/components/ui/form"
import { toast } from "sonner"
import { Download, Loader, Trash2, X } from "lucide-react"
import prettyBytes from "pretty-bytes"
import { useSession } from "next-auth/react"
import { useForm } from "react-hook-form"
import { formatDate } from "@/lib/utils"
import {
getTechSalesVendorQuotationEmlAttachments,
processTechSalesVendorQuotationEmlAttachments,
} from "@/lib/techsales-rfq/service"
const MAX_FILE_SIZE = 6e8 // 600MB
export interface VendorEmlAttachment {
id: number
quotationId: number
revisionId: number
fileName: string
originalFileName: string
fileSize: number
fileType: string | null
filePath: string
description: string | null
uploadedBy: number | null
vendorId: number | null
isVendorUpload: boolean
createdAt: Date
updatedAt: Date
}
interface QuotationInfo {
id: number
quotationCode: string | null
vendorName?: string
rfqCode?: string
}
interface TechSalesVendorEmlAttachmentsSheetProps extends React.ComponentPropsWithRef<typeof Sheet> {
quotation: QuotationInfo | null
attachments: VendorEmlAttachment[]
onAttachmentsChange?: (attachments: VendorEmlAttachment[]) => void
isLoading?: boolean
}
export function TechSalesVendorEmlAttachmentsSheet({
quotation,
attachments,
onAttachmentsChange,
isLoading = false,
...props
}: TechSalesVendorEmlAttachmentsSheetProps) {
const session = useSession()
const [isPending, setIsPending] = React.useState(false)
const [existing, setExisting] = React.useState<VendorEmlAttachment[]>(attachments)
const [newUploads, setNewUploads] = React.useState<File[]>([])
const [deleteIds, setDeleteIds] = React.useState<number[]>([])
const form = useForm({
defaultValues: {
dummy: true,
},
})
// sync when parent changes
React.useEffect(() => {
setExisting(attachments)
setNewUploads([])
setDeleteIds([])
}, [attachments])
const handleDownloadClick = React.useCallback(async (attachment: VendorEmlAttachment) => {
try {
const { downloadFile } = await import("@/lib/file-download")
await downloadFile(attachment.filePath, attachment.originalFileName || attachment.fileName, {
showToast: true,
onError: (error) => {
console.error("다운로드 오류:", error)
toast.error(error)
},
})
} catch (error) {
console.error("다운로드 오류:", error)
toast.error("파일 다운로드 중 오류가 발생했습니다.")
}
}, [])
const handleDropAccepted = React.useCallback((accepted: File[]) => {
setNewUploads((prev) => [...prev, ...accepted])
}, [])
const handleDropRejected = React.useCallback(() => {
toast.error("파일 크기가 너무 크거나 지원하지 않는 형식입니다.")
}, [])
const handleRemoveExisting = React.useCallback((id: number) => {
setDeleteIds((prev) => (prev.includes(id) ? prev : [...prev, id]))
setExisting((prev) => prev.filter((att) => att.id !== id))
}, [])
const handleRemoveNewUpload = React.useCallback((index: number) => {
setNewUploads((prev) => prev.filter((_, i) => i !== index))
}, [])
const handleSubmit = async () => {
if (!quotation) {
toast.error("견적 정보를 찾을 수 없습니다.")
return
}
const userId = Number(session.data?.user.id || 0)
if (!userId) {
toast.error("로그인 정보를 확인해주세요.")
return
}
setIsPending(true)
try {
const result = await processTechSalesVendorQuotationEmlAttachments({
quotationId: quotation.id,
newFiles: newUploads.map((file) => ({ file })),
deleteAttachmentIds: deleteIds,
uploadedBy: userId,
})
if (result.error) {
toast.error(result.error)
return
}
const refreshed =
result.data ||
(await getTechSalesVendorQuotationEmlAttachments(quotation.id)).data ||
[]
setExisting(refreshed)
setNewUploads([])
setDeleteIds([])
onAttachmentsChange?.(refreshed)
toast.success("Eml 첨부파일이 저장되었습니다.")
props.onOpenChange?.(false)
} catch (error) {
console.error("eml 첨부파일 저장 오류:", error)
toast.error("eml 첨부파일 저장 중 오류가 발생했습니다.")
} finally {
setIsPending(false)
}
}
const totalNewSize = newUploads.reduce((acc, f) => acc + f.size, 0)
return (
<Sheet {...props}>
<SheetContent className="flex flex-col gap-6 sm:max-w-md">
<SheetHeader className="text-left">
<SheetTitle>eml 첨부파일</SheetTitle>
<SheetDescription>
<div className="space-y-1">
{quotation?.vendorName && <div>벤더: {quotation.vendorName}</div>}
{quotation?.rfqCode && <div>RFQ: {quotation.rfqCode}</div>}
</div>
</SheetDescription>
</SheetHeader>
<Form {...form}>
<form onSubmit={(e) => e.preventDefault()} className="flex flex-1 flex-col gap-6">
{/* 기존 첨부 */}
<div className="grid gap-4">
<h6 className="font-semibold leading-none tracking-tight">
기존 첨부파일 ({existing.length}개)
</h6>
{isLoading ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader className="h-4 w-4 animate-spin" />
로딩 중...
</div>
) : existing.length === 0 ? (
<div className="text-sm text-muted-foreground">첨부파일이 없습니다.</div>
) : (
existing.map((att) => (
<div
key={att.id}
className="flex items-start justify-between p-3 border rounded-md gap-3"
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1 flex-wrap">
<p className="text-sm font-medium break-words leading-tight">
{att.originalFileName || att.fileName}
</p>
<Badge variant="outline" className="text-xs shrink-0">
rev {att.revisionId}
</Badge>
</div>
<p className="text-xs text-muted-foreground">
{prettyBytes(att.fileSize)} • {formatDate(att.createdAt, "KR")}
</p>
{att.description && (
<p className="text-xs text-muted-foreground mt-1 break-words">
{att.description}
</p>
)}
</div>
<div className="flex items-center gap-1 shrink-0">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
type="button"
onClick={() => handleDownloadClick(att)}
title="다운로드"
>
<Download className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
type="button"
onClick={() => handleRemoveExisting(att.id)}
title="삭제"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))
)}
</div>
{/* 새 업로드 */}
<Dropzone
maxSize={MAX_FILE_SIZE}
onDropAccepted={handleDropAccepted}
onDropRejected={handleDropRejected}
>
{({ maxSize }) => (
<FormField
control={form.control}
name="dummy"
render={() => (
<FormItem>
<FormLabel>새 eml 파일 업로드</FormLabel>
<DropzoneZone className="flex justify-center">
<FormControl>
<DropzoneInput />
</FormControl>
<div className="flex items-center gap-6">
<DropzoneUploadIcon />
<div className="grid gap-0.5">
<DropzoneTitle>파일을 드래그하거나 클릭하세요</DropzoneTitle>
<DropzoneDescription>
최대 크기: {maxSize ? prettyBytes(maxSize) : "600MB"}
</DropzoneDescription>
</div>
</div>
</DropzoneZone>
<FormDescription>복수 파일 업로드 가능</FormDescription>
</FormItem>
)}
/>
)}
</Dropzone>
{newUploads.length > 0 && (
<div className="grid gap-3">
<div className="flex items-center justify-between">
<h6 className="font-semibold leading-none tracking-tight">
새 파일 ({newUploads.length}개)
</h6>
<span className="text-xs text-muted-foreground">
총 용량 {prettyBytes(totalNewSize)}
</span>
</div>
<FileList>
{newUploads.map((file, idx) => (
<FileListItem key={`${file.name}-${idx}`}>
<FileListHeader>
<FileListIcon />
<FileListInfo>
<FileListName>{file.name}</FileListName>
<FileListDescription>{prettyBytes(file.size)}</FileListDescription>
</FileListInfo>
<FileListAction onClick={() => handleRemoveNewUpload(idx)}>
<X />
<span className="sr-only">제거</span>
</FileListAction>
</FileListHeader>
</FileListItem>
))}
</FileList>
</div>
)}
<SheetFooter className="gap-2 pt-2 sm:space-x-0">
<SheetClose asChild>
<Button type="button" variant="outline">
닫기
</Button>
</SheetClose>
<Button
type="button"
onClick={handleSubmit}
disabled={isPending || (!newUploads.length && deleteIds.length === 0)}
>
{isPending && <Loader className="mr-2 h-4 w-4 animate-spin" />}
{isPending ? "저장 중..." : "저장"}
</Button>
</SheetFooter>
</form>
</Form>
</SheetContent>
</Sheet>
)
}
|