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
|
"use client"
import * as React from "react"
import { z } from "zod"
import { useForm, useFieldArray } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetDescription,
SheetFooter,
SheetClose,
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
FormDescription
} from "@/components/ui/form"
import { Loader, Download, X, Eye, AlertCircle } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { Badge } from "@/components/ui/badge"
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 prettyBytes from "pretty-bytes"
import { processRfqAttachments } from "../service"
import { formatDate } from "@/lib/utils"
import { RfqType } from "../validations"
import { RfqWithItemCount } from "@/db/schema/rfq"
import { quickDownload } from "@/lib/file-download"
import { type FileRejection } from "react-dropzone"
const MAX_FILE_SIZE = 6e8 // 600MB
/** 기존 첨부 파일 정보 */
interface ExistingAttachment {
id: number
fileName: string
filePath: string
createdAt?: Date // or Date
vendorId?: number | null
size?: number
}
/** 새로 업로드할 파일 */
const newUploadSchema = z.object({
fileObj: z.any().optional(), // 실제 File
})
/** 기존 첨부 (react-hook-form에서 관리) */
const existingAttachSchema = z.object({
id: z.number(),
fileName: z.string(),
filePath: z.string(),
vendorId: z.number().nullable().optional(),
createdAt: z.custom<Date>().optional(), // or use z.any().optional()
size: z.number().optional(),
})
/** RHF 폼 전체 스키마 */
const attachmentsFormSchema = z.object({
rfqId: z.number().int(),
existing: z.array(existingAttachSchema),
newUploads: z.array(newUploadSchema),
})
type AttachmentsFormValues = z.infer<typeof attachmentsFormSchema>
interface RfqAttachmentsSheetProps
extends React.ComponentPropsWithRef<typeof Sheet> {
defaultAttachments?: ExistingAttachment[]
rfqType?: RfqType
rfq: RfqWithItemCount | null
/** 업로드/삭제 후 상위 테이블에 itemCount 등을 업데이트하기 위한 콜백 */
onAttachmentsUpdated?: (rfqId: number, newItemCount: number) => void
}
/**
* RfqAttachmentsSheet:
* - 기존 첨부 목록 (다운로드 + 삭제)
* - 새 파일 Dropzone
* - Save 시 processRfqAttachments(server action)
*/
export function RfqAttachmentsSheet({
defaultAttachments = [],
onAttachmentsUpdated,
rfq,
rfqType,
...props
}: RfqAttachmentsSheetProps) {
const { toast } = useToast()
const [isPending, startUpdate] = React.useTransition()
const rfqId = rfq?.rfqId ?? 0;
// 편집 가능 여부 확인 - DRAFT 상태일 때만 편집 가능
const isEditable = rfq?.status === "DRAFT";
// React Hook Form
const form = useForm<AttachmentsFormValues>({
resolver: zodResolver(attachmentsFormSchema),
defaultValues: {
rfqId,
existing: [],
newUploads: [],
},
})
const { reset, control, handleSubmit } = form
// defaultAttachments가 바뀔 때마다, RHF 상태를 reset
React.useEffect(() => {
reset({
rfqId,
existing: defaultAttachments.map((att) => ({
...att,
vendorId: att.vendorId ?? null,
size: att.size ?? undefined,
})),
newUploads: [],
})
}, [rfqId, defaultAttachments, reset])
// Field Arrays
const {
fields: existingFields,
remove: removeExisting,
} = useFieldArray({ control, name: "existing" })
const {
fields: newUploadFields,
append: appendNewUpload,
remove: removeNewUpload,
} = useFieldArray({ control, name: "newUploads" })
// 기존 첨부 항목 중 삭제된 것 찾기
function findRemovedExistingIds(data: AttachmentsFormValues): number[] {
const finalIds = data.existing.map((att) => att.id)
const originalIds = defaultAttachments.map((att) => att.id)
return originalIds.filter((id) => !finalIds.includes(id))
}
async function onSubmit(data: AttachmentsFormValues) {
// 편집 불가능한 상태에서는 제출 방지
if (!isEditable) return;
startUpdate(async () => {
try {
const removedExistingIds = findRemovedExistingIds(data)
const newFiles = data.newUploads
.map((it) => it.fileObj)
.filter((f): f is File => !!f)
// 서버 액션
const res = await processRfqAttachments({
rfqId,
removedExistingIds,
newFiles,
vendorId: null, // vendor ID if needed
rfqType
})
if (!res.ok) throw new Error(res.error ?? "Unknown error")
const newCount = res.updatedItemCount ?? 0
toast({
variant: "default",
title: "Success",
description: "File(s) updated",
})
// 상위 테이블 등에 itemCount 업데이트
onAttachmentsUpdated?.(rfqId, newCount)
// 모달 닫기
props.onOpenChange?.(false)
} catch (err) {
toast({
variant: "destructive",
title: "Error",
description: String(err),
})
}
})
}
/** 기존 첨부 - X 버튼 */
function handleRemoveExisting(idx: number) {
// 편집 불가능한 상태에서는 삭제 방지
if (!isEditable) return;
removeExisting(idx)
}
/** 드롭존에서 파일 받기 */
function handleDropAccepted(acceptedFiles: File[]) {
// 편집 불가능한 상태에서는 파일 추가 방지
if (!isEditable) return;
const mapped = acceptedFiles.map((file) => ({ fileObj: file }))
appendNewUpload(mapped)
}
/** 드롭존에서 파일 거부(에러) */
function handleDropRejected(fileRejections: FileRejection[]) {
// 편집 불가능한 상태에서는 무시
if (!isEditable) return;
fileRejections.forEach((rej) => {
toast({
variant: "destructive",
title: "File Error",
description: rej.file.name + " not accepted",
})
})
}
return (
<Sheet {...props}>
<SheetContent className="flex flex-col gap-6 sm:max-w-sm">
<SheetHeader>
<SheetTitle className="flex items-center gap-2">
{isEditable ? "Manage Attachments" : "View Attachments"}
{rfq?.status && (
<Badge
variant={rfq.status === "DRAFT" ? "outline" : "secondary"}
className="ml-1"
>
{rfq.status}
</Badge>
)}
</SheetTitle>
<SheetDescription>
{`RFQ ${rfq?.rfqCode} - `}
{isEditable ? '파일 첨부/삭제' : '첨부 파일 보기'}
{!isEditable && (
<div className="mt-1 text-xs flex items-center gap-1 text-amber-600">
<AlertCircle className="h-3 w-3" />
<span>드래프트 상태가 아닌 RFQ는 첨부파일을 수정할 수 없습니다.</span>
</div>
)}
</SheetDescription>
</SheetHeader>
<Form {...form}>
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
{/* 1) 기존 첨부 목록 */}
<div className="space-y-2">
<p className="font-semibold text-sm">Existing Attachments</p>
{existingFields.length === 0 && (
<p className="text-sm text-muted-foreground">No existing attachments</p>
)}
{existingFields.map((field, index) => {
const vendorLabel = field.vendorId ? "(Vendor)" : "(Internal)"
return (
<div
key={field.id}
className="flex items-center justify-between rounded border p-2"
>
<div className="flex flex-col text-sm">
<span className="font-medium">
{field.fileName} {vendorLabel}
</span>
{field.size && (
<span className="text-xs text-muted-foreground">
{Math.round(field.size / 1024)} KB
</span>
)}
{field.createdAt && (
<span className="text-xs text-muted-foreground">
Created at {formatDate(field.createdAt, "KR")}
</span>
)}
</div>
<div className="flex items-center gap-2">
{/* 1) Download button (if filePath) */}
{field.filePath && (
<Button
variant="ghost"
size="icon"
type="button"
onClick={() => quickDownload(field.filePath, field.fileName)}
>
<Download className="h-4 w-4" />
</Button>
)}
{/* 2) Remove button - 편집 가능할 때만 표시 */}
{isEditable && (
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => handleRemoveExisting(index)}
>
<X className="h-4 w-4" />
</Button>
)}
</div>
</div>
)
})}
</div>
{/* 2) Dropzone for new uploads - 편집 가능할 때만 표시 */}
{isEditable ? (
<>
<Dropzone
maxSize={MAX_FILE_SIZE}
onDropAccepted={handleDropAccepted}
onDropRejected={handleDropRejected}
>
{({ maxSize }) => (
<FormField
control={control}
name="newUploads" // not actually used for storing each file detail
render={() => (
<FormItem>
<FormLabel>Drop Files Here</FormLabel>
<DropzoneZone className="flex justify-center">
<FormControl>
<DropzoneInput />
</FormControl>
<div className="flex items-center gap-6">
<DropzoneUploadIcon />
<div className="grid gap-0.5">
<DropzoneTitle>Drop to upload</DropzoneTitle>
<DropzoneDescription>
Max size: {maxSize ? prettyBytes(maxSize) : "??? MB"}
</DropzoneDescription>
</div>
</div>
</DropzoneZone>
<FormDescription>Alternatively, click browse.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
)}
</Dropzone>
{/* newUpload fields -> FileList */}
{newUploadFields.length > 0 && (
<div className="grid gap-4">
<h6 className="font-semibold leading-none tracking-tight">
{`Files (${newUploadFields.length})`}
</h6>
<FileList>
{newUploadFields.map((field, idx) => {
const fileObj = form.getValues(`newUploads.${idx}.fileObj`)
if (!fileObj) return null
const fileName = fileObj.name
const fileSize = fileObj.size
return (
<FileListItem key={field.id}>
<FileListHeader>
<FileListIcon />
<FileListInfo>
<FileListName>{fileName}</FileListName>
<FileListDescription>
{`${prettyBytes(fileSize)}`}
</FileListDescription>
</FileListInfo>
<FileListAction onClick={() => removeNewUpload(idx)}>
<X />
<span className="sr-only">Remove</span>
</FileListAction>
</FileListHeader>
</FileListItem>
)
})}
</FileList>
</div>
)}
</>
) : (
<div className="p-3 bg-muted rounded-md flex items-center justify-center">
<div className="text-center text-sm text-muted-foreground">
<Eye className="h-4 w-4 mx-auto mb-2" />
<p>보기 모드에서는 파일 첨부를 할 수 없습니다.</p>
</div>
</div>
)}
<SheetFooter className="gap-2 pt-2 sm:space-x-0">
<SheetClose asChild>
<Button type="button" variant="outline">
{isEditable ? "Cancel" : "Close"}
</Button>
</SheetClose>
{isEditable && (
<Button
type="submit"
disabled={isPending || (form.getValues().newUploads.length === 0 && defaultAttachments.length === form.getValues().existing.length)}
>
{isPending && <Loader className="mr-2 h-4 w-4 animate-spin" />}
Save
</Button>
)}
</SheetFooter>
</form>
</Form>
</SheetContent>
</Sheet>
)
}
|