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
|
"use client"
import * as React from "react"
import { ChevronsUpDown, MessagesSquare, Download, Loader2 } from "lucide-react"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { Card } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { PQGroupData } from "@/lib/pq/service"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Textarea } from "@/components/ui/textarea"
import { addReviewCommentAction, getItemReviewLogsAction } from "@/lib/pq/service"
import { useToast } from "@/hooks/use-toast"
import { formatDate } from "@/lib/utils"
import { downloadFileAction } from "@/lib/downloadFile"
interface ReviewLog {
id: number
reviewerComment: string
reviewerName: string | null
createdAt: Date
}
interface VendorPQReviewPageProps {
data: PQGroupData[];
onCommentAdded?: () => void; // 코멘트 추가 콜백
}
export default function VendorPQReviewPage({ data, onCommentAdded }: VendorPQReviewPageProps) {
const { toast } = useToast()
// 파일 다운로드 함수 - 서버 액션 사용
const handleFileDownload = async (filePath: string, fileName: string) => {
try {
toast({
title: "Download Started",
description: `Preparing ${fileName} for download...`,
});
// 서버 액션 호출
const result = await downloadFileAction(filePath);
if (!result.ok || !result.data) {
throw new Error(result.error || 'Failed to download file');
}
// Base64 디코딩하여 Blob 생성
const binaryString = atob(result.data.content);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// Blob 생성 및 다운로드
const blob = new Blob([bytes.buffer], { type: result.data.mimeType });
const url = URL.createObjectURL(blob);
// 다운로드 링크 생성 및 클릭
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
// 정리
URL.revokeObjectURL(url);
document.body.removeChild(a);
toast({
title: "Download Complete",
description: `${fileName} downloaded successfully`,
});
} catch (error) {
console.error('Download error:', error);
toast({
title: "Download Error",
description: error instanceof Error ? error.message : "Failed to download file",
variant: "destructive"
});
}
};
return (
<div className="space-y-4">
{data.map((group) => (
<Collapsible key={group.groupName} defaultOpen>
<CollapsibleTrigger asChild>
<div className="flex items-center justify-between cursor-pointer p-3 bg-muted rounded">
<h2 className="font-semibold text-lg">{group.groupName}</h2>
<Button variant="ghost" size="sm" className="p-0 h-7 w-7">
<ChevronsUpDown className="h-4 w-4" />
</Button>
</div>
</CollapsibleTrigger>
<CollapsibleContent>
<Card className="mt-2 p-4">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[60px]">Code</TableHead>
<TableHead>Check Point</TableHead>
<TableHead>Answer</TableHead>
<TableHead className="w-[180px]">Attachments</TableHead>
<TableHead className="w-[60px] text-center">Comments</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{group.items.map((item) => (
<TableRow key={item.criteriaId}>
<TableCell className="font-medium">{item.code}</TableCell>
<TableCell>{item.checkPoint}</TableCell>
<TableCell>
{item.answer ? (
<p className="whitespace-pre-wrap text-sm">
{item.answer}
</p>
) : (
<p className="text-sm text-muted-foreground">(no answer)</p>
)}
</TableCell>
<TableCell>
{item.attachments.length > 0 ? (
<ul className="list-none space-y-1">
{item.attachments.map((file) => (
<li key={file.attachId} className="text-sm flex items-center">
<button
className="text-blue-600 hover:text-blue-800 hover:underline flex items-center truncate max-w-[160px]"
onClick={() => handleFileDownload(file.filePath, file.fileName)}
>
<Download className="h-3 w-3 mr-1 flex-shrink-0" />
<span className="truncate">{file.fileName}</span>
</button>
</li>
))}
</ul>
) : (
<p className="text-sm text-muted-foreground">(none)</p>
)}
</TableCell>
<TableCell className="text-center">
<ItemReviewButton
answerId={item.answerId ?? undefined}
checkPoint={item.checkPoint}
onCommentAdded={onCommentAdded}
/>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
</CollapsibleContent>
</Collapsible>
))}
</div>
)
}
interface ItemReviewButtonProps {
answerId?: number;
checkPoint: string; // Check Point 추가
onCommentAdded?: () => void;
}
/**
* A button that opens a dialog to show logs + add new comment for a single item (vendorPqCriteriaAnswers).
*/
function ItemReviewButton({ answerId, checkPoint, onCommentAdded }: ItemReviewButtonProps) {
const { toast } = useToast();
const [open, setOpen] = React.useState(false);
const [logs, setLogs] = React.useState<ReviewLog[]>([]);
const [newComment, setNewComment] = React.useState("");
const [isLoading, setIsLoading] = React.useState(false);
const [hasComments, setHasComments] = React.useState(false);
// If there's no answerId, item wasn't answered
if (!answerId) {
return <p className="text-xs text-muted-foreground">N/A</p>;
}
// fetchLogs 함수를 useCallback으로 메모이제이션
const fetchLogs = React.useCallback(async () => {
try {
setIsLoading(true);
const res = await getItemReviewLogsAction({ answerId });
if (res.ok && res.data) {
setLogs(res.data);
// 코멘트 존재 여부 설정
setHasComments(res.data.length > 0);
} else {
console.error("Error response:", res.error);
toast({ title: "Error", description: res.error, variant: "destructive" });
}
} catch (error) {
console.error("Fetch error:", error);
toast({ title: "Error", description: String(error), variant: "destructive" });
} finally {
setIsLoading(false);
}
}, [answerId, toast]);
// 초기 로드 시 코멘트 존재 여부 확인 (아이콘 색상용)
React.useEffect(() => {
const checkComments = async () => {
try {
const res = await getItemReviewLogsAction({ answerId });
if (res.ok && res.data) {
setHasComments(res.data.length > 0);
}
} catch (error) {
console.error("Error checking comments:", error);
}
};
checkComments();
}, [answerId]);
// open 상태가 변경될 때 로그 가져오기
React.useEffect(() => {
if (open) {
fetchLogs();
}
}, [open, fetchLogs]);
// 버튼 클릭 핸들러 - 다이얼로그 열기
const handleButtonClick = React.useCallback(() => {
setOpen(true);
}, []);
// 다이얼로그 상태 변경 핸들러
const handleOpenChange = React.useCallback((nextOpen: boolean) => {
setOpen(nextOpen);
}, []);
// 코멘트 추가 핸들러
const handleAddComment = React.useCallback(async () => {
try {
setIsLoading(true);
const res = await addReviewCommentAction({
answerId,
comment: newComment,
reviewerName: "AdminUser",
});
if (res.ok) {
toast({ title: "Comment added", description: "New review comment saved" });
setNewComment("");
setHasComments(true); // 코멘트 추가 성공 시 상태 업데이트
// 코멘트가 추가되었음을 부모 컴포넌트에 알림
if (onCommentAdded) {
onCommentAdded();
}
// 로그 다시 가져오기
fetchLogs();
} else {
toast({ title: "Error", description: res.error, variant: "destructive" });
}
} catch (error) {
toast({ title: "Error", description: String(error), variant: "destructive" });
} finally {
setIsLoading(false);
}
}, [answerId, newComment, onCommentAdded, fetchLogs, toast]);
return (
<>
<Button variant="ghost" size="sm" onClick={handleButtonClick}>
<MessagesSquare
className={`h-4 w-4 ${hasComments ? 'text-blue-600' : ''}`}
/>
</Button>
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>{checkPoint} Comments</DialogTitle>
</DialogHeader>
{/* Logs section */}
<div className="max-h-[200px] overflow-y-auto space-y-2">
{isLoading ? (
<div className="flex justify-center p-4">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : logs.length > 0 ? (
logs.map((log) => (
<div key={log.id} className="p-2 border rounded text-sm">
<p className="font-medium">{log.reviewerName}</p>
<p>{log.reviewerComment}</p>
<p className="text-xs text-muted-foreground">
{formatDate(log.createdAt)}
</p>
</div>
))
) : (
<p className="text-sm text-muted-foreground">No comments yet.</p>
)}
</div>
{/* Add new comment */}
<div className="space-y-2">
<Textarea
placeholder="Add a new comment..."
value={newComment}
onChange={(e) => setNewComment(e.target.value)}
/>
<Button
size="sm"
onClick={handleAddComment}
disabled={isLoading || !newComment.trim()}
>
Add Comment
</Button>
</div>
</DialogContent>
</Dialog>
</>
);
}
|