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
|
"use client"
import * as React from "react"
import { useForm, useFieldArray } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { Loader, Download, X } from "lucide-react"
import prettyBytes from "pretty-bytes"
import { toast } from "sonner"
import {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import {
Textarea,
} from "@/components/ui/textarea"
import {
Dropzone,
DropzoneZone,
DropzoneUploadIcon,
DropzoneTitle,
DropzoneDescription,
DropzoneInput
} from "@/components/ui/dropzone"
import {
Table,
TableHeader,
TableRow,
TableHead,
TableBody,
TableCell
} from "@/components/ui/table"
// DB 스키마에서 필요한 타입들을 가져온다고 가정
import { RfqWithAll } from "../types"
import { createRfqCommentWithAttachments, updateRfqComment } from "../../rfqs/service"
import { formatDate } from "@/lib/utils"
// 코멘트 + 첨부파일 구조 (단순 예시)
// 실제 DB 스키마에 맞춰 조정
export interface RfqComment {
id: number
commentText: string
commentedBy?: number
createdAt?: Date
attachments?: {
id: number
fileName: string
filePath?: string
}[]
}
interface CommentSheetProps extends React.ComponentPropsWithRef<typeof Sheet> {
/** 코멘트를 작성할 RFQ 정보 */
/** 이미 존재하는 모든 코멘트 목록 (서버에서 불러와 주입) */
initialComments?: RfqComment[]
/** 사용자(작성자) ID (로그인 세션 등에서 가져옴) */
currentUserId: number
rfq:RfqWithAll
/** 댓글 저장 후 갱신용 콜백 (옵션) */
onCommentsUpdated?: (comments: RfqComment[]) => void
}
// 새 코멘트 작성 폼 스키마
const commentFormSchema = z.object({
commentText: z.string().min(1, "댓글을 입력하세요."),
newFiles: z.array(z.any()).optional() // File[]
})
type CommentFormValues = z.infer<typeof commentFormSchema>
const MAX_FILE_SIZE = 30e6 // 30MB
export function CommentSheet({
rfq,
initialComments = [],
currentUserId,
onCommentsUpdated,
...props
}: CommentSheetProps) {
const [comments, setComments] = React.useState<RfqComment[]>(initialComments)
const [isPending, startTransition] = React.useTransition()
React.useEffect(() => {
setComments(initialComments)
}, [initialComments])
// RHF 세팅
const form = useForm<CommentFormValues>({
resolver: zodResolver(commentFormSchema),
defaultValues: {
commentText: "",
newFiles: []
}
})
// formFieldArray 예시 (파일 목록)
const { fields: newFileFields, append, remove } = useFieldArray({
control: form.control,
name: "newFiles"
})
// 1) 기존 코멘트 + 첨부 보여주기
// 간단히 테이블 하나로 표현
// 실제로는 Bubble 형태의 UI, Accordion, Timeline 등 다양하게 구성할 수 있음
function renderExistingComments() {
// 1) 편집 상태 관리
const [editingId, setEditingId] = React.useState<number | null>(null)
const [editText, setEditText] = React.useState("")
// 2) Edit 시작 핸들러
function handleEditClick(c: RfqComment) {
setEditingId(c.id)
setEditText(c.commentText)
}
// 3) Save 핸들러
async function handleSave(commentId: number) {
try {
// (예시) 서버 액션 or API 요청
await updateRfqComment({ commentId, commentText: editText })
// 만약 단순 로컬 수정만 할 거라면,
// parent state의 comments를 갱신하는 로직 필요
setComments((prev) =>
prev.map((comment) =>
comment.id === commentId
? { ...comment, commentText: editText }
: comment
)
)
toast.success("Comment updated.")
} catch (err) {
toast.error("Error updating comment.")
} finally {
// 편집 모드 종료
setEditingId(null)
setEditText("")
}
}
// 4) Cancel 핸들러
function handleCancel() {
setEditingId(null)
setEditText("")
}
// 만약 comments가 비어 있다면
if (comments.length === 0) {
return <p className="text-sm text-muted-foreground">No comments yet</p>
}
// 5) 테이블 렌더링
return (
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-1/2">Comment</TableHead>
<TableHead>Attachments</TableHead>
<TableHead>Created At</TableHead>
<TableHead>Created By</TableHead>
{/* 추가된 Actions 컬럼 */}
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{comments.map((c) => (
<TableRow key={c.id}>
{/* 1) Comment 셀 */}
<TableCell>
{/* 현재 행이 editing 모드인지 체크 */}
{editingId === c.id ? (
// 편집 모드
<textarea
value={editText}
onChange={(e) => setEditText(e.target.value)}
className="w-full border p-1 rounded"
rows={3}
/>
) : (
// 일반 모드
c.commentText
)}
</TableCell>
{/* 2) Attachments 셀 (기존과 동일) */}
<TableCell>
{(!c.attachments || c.attachments.length === 0) && (
<span className="text-sm text-muted-foreground">No files</span>
)}
{c.attachments && c.attachments.length > 0 && (
<div className="flex flex-col gap-1">
{c.attachments.map((att) => (
<div key={att.id} className="flex items-center gap-2">
<a
href={att.filePath}
download
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-blue-600 underline"
>
<Download className="h-4 w-4" />
{att.fileName}
</a>
</div>
))}
</div>
)}
</TableCell>
{/* 3) Created At */}
<TableCell> { c.createdAt ? formatDate(c.createdAt): "-"}</TableCell>
{/* 4) Created By */}
<TableCell>{c.commentedBy ?? "-"}</TableCell>
{/* 5) 새로 추가된 Actions */}
<TableCell>
{editingId === c.id ? (
// 편집 중일 때
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => handleSave(c.id)}>
Save
</Button>
<Button variant="ghost" size="sm" onClick={handleCancel}>
Cancel
</Button>
</div>
) : (
// 일반 상태
<Button variant="outline" size="sm" onClick={() => handleEditClick(c)}>
Edit
</Button>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)
}
// 2) 새 파일 Drop
function handleDropAccepted(files: File[]) {
// 드롭된 File[]을 RHF field array에 추가
const toAppend = files.map((f) => f)
append(toAppend)
}
// 3) 저장(Submit)
async function onSubmit(data: CommentFormValues) {
if (!rfq) return
startTransition(async () => {
try {
// 서버 액션 호출
const res = await createRfqCommentWithAttachments({
rfqId: rfq.id,
vendorId: rfq.vendorId, // 필요시 세팅
commentText: data.commentText,
commentedBy: currentUserId,
evaluationId: null, // 필요시 세팅
files: data.newFiles
})
if (!res.ok) {
throw new Error("Failed to create comment")
}
toast.success("Comment created")
// 새 코멘트를 다시 불러오거나,
// 여기서는 임시로 "새로운 코멘트가 추가됐다" 라고 가정하여 클라이언트에서 상태 업데이트
const newComment: RfqComment = {
id: res.commentId, // 서버에서 반환된 commentId
commentText: data.commentText,
commentedBy: currentUserId,
createdAt: res.createdAt,
attachments: (data.newFiles?.map((f, idx) => ({
id: Math.random() * 100000,
fileName: f.name,
})) || [])
}
setComments((prev) => [...prev, newComment])
onCommentsUpdated?.([...comments, newComment])
// 폼 리셋
form.reset()
} catch (err: any) {
console.error(err)
toast.error("Error: " + err.message)
}
})
}
return (
<Sheet {...props}>
<SheetContent className="flex flex-col gap-6 sm:max-w-lg">
<SheetHeader className="text-left">
<SheetTitle>Comments</SheetTitle>
<SheetDescription>
필요시 첨부파일과 함께 문의/코멘트를 남길 수 있습니다.
</SheetDescription>
</SheetHeader>
{/* 기존 코멘트 목록 */}
<div className="max-h-[300px] overflow-y-auto">
{renderExistingComments()}
</div>
{/* 새 코멘트 작성 Form */}
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">
<FormField
control={form.control}
name="commentText"
render={({ field }) => (
<FormItem>
<FormLabel>New Comment</FormLabel>
<FormControl>
<Textarea
placeholder="Enter your comment..."
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* Dropzone (파일 첨부) */}
<Dropzone
maxSize={MAX_FILE_SIZE}
onDropAccepted={handleDropAccepted}
onDropRejected={(rej) => {
toast.error("File rejected: " + (rej[0]?.file?.name || ""))
}}
>
{({ maxSize }) => (
<DropzoneZone className="flex justify-center">
<DropzoneInput />
<div className="flex items-center gap-6">
<DropzoneUploadIcon />
<div className="grid gap-0.5">
<DropzoneTitle>Drop to attach files</DropzoneTitle>
<DropzoneDescription>
Max size: {prettyBytes(maxSize || 0)}
</DropzoneDescription>
</div>
</div>
</DropzoneZone>
)}
</Dropzone>
{/* 선택된 파일 목록 */}
{newFileFields.length > 0 && (
<div className="flex flex-col gap-2">
{newFileFields.map((field, idx) => {
const file = form.getValues(`newFiles.${idx}`)
if (!file) return null
return (
<div key={field.id} className="flex items-center justify-between border rounded p-2">
<span className="text-sm">{file.name} ({prettyBytes(file.size)})</span>
<Button
variant="ghost"
size="icon"
type="button"
onClick={() => remove(idx)}
>
<X className="h-4 w-4" />
</Button>
</div>
)
})}
</div>
)}
<SheetFooter className="gap-2 pt-4">
<SheetClose asChild>
<Button type="button" variant="outline">
Cancel
</Button>
</SheetClose>
<Button disabled={isPending}>
{isPending && <Loader className="mr-2 h-4 w-4 animate-spin" />}
Save
</Button>
</SheetFooter>
</form>
</Form>
</SheetContent>
</Sheet>
)
}
|