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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
|
"use client";
import React, { useState, useCallback, useEffect } from 'react';
import { ScrollArea } from "@/components/ui/scroll-area";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import {
MessageSquare,
Plus,
Trash2,
Paperclip,
X,
Save,
Upload,
FileText,
User,
Building2,
Loader2,
Download,
Send,
CheckCircle2,
} from "lucide-react";
import { cn, formatDateTime } from "@/lib/utils";
import {
getAgreementComments,
addAgreementComment,
deleteAgreementComment,
uploadCommentAttachment,
deleteCommentAttachment,
completeNegotiation,
type AgreementCommentData,
type AgreementCommentAuthorType,
} from "./actions";
export interface AgreementCommentListProps {
basicContractId: number;
currentUserType?: AgreementCommentAuthorType;
readOnly?: boolean;
className?: string;
onCommentCountChange?: (count: number) => void;
isNegotiationCompleted?: boolean; // 협의 완료 여부
onNegotiationComplete?: () => void; // 협의 완료 콜백
}
export function AgreementCommentList({
basicContractId,
currentUserType = 'Vendor',
readOnly = false,
className,
onCommentCountChange,
isNegotiationCompleted = false,
onNegotiationComplete,
}: AgreementCommentListProps) {
const [comments, setComments] = useState<AgreementCommentData[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isAdding, setIsAdding] = useState(false);
const [newComment, setNewComment] = useState('');
const [newAuthorName, setNewAuthorName] = useState('');
const [uploadingFiles, setUploadingFiles] = useState<Set<number>>(new Set());
const [isSaving, setIsSaving] = useState(false);
const [pendingFiles, setPendingFiles] = useState<File[]>([]); // 첨부 대기 중인 파일들
const [isCompletingNegotiation, setIsCompletingNegotiation] = useState(false);
// 코멘트 로드
const loadComments = useCallback(async () => {
try {
setIsLoading(true);
const data = await getAgreementComments(basicContractId);
setComments(data);
onCommentCountChange?.(data.length);
} catch (error) {
console.error('코멘트 로드 실패:', error);
toast.error("코멘트를 불러오는데 실패했습니다.");
} finally {
setIsLoading(false);
}
}, [basicContractId]); // onCommentCountChange를 dependency에서 제거
// 초기 로드
useEffect(() => {
loadComments();
}, [basicContractId]); // loadComments 대신 basicContractId만 의존
// 코멘트 추가 핸들러 (저장만 - 이메일 발송 없음)
const handleAddComment = useCallback(async (shouldSendEmail: boolean = false) => {
if (!newComment.trim()) {
toast.error("코멘트를 입력해주세요.");
return;
}
setIsSaving(true);
try {
const result = await addAgreementComment({
basicContractId,
comment: newComment.trim(),
authorName: newAuthorName.trim() || undefined,
files: pendingFiles,
shouldSendEmail, // 이메일 발송 여부 전달
});
if (result.success) {
setNewComment('');
setNewAuthorName('');
setPendingFiles([]);
setIsAdding(false);
if (shouldSendEmail) {
toast.success("코멘트가 제출되었으며 상대방에게 이메일이 발송되었습니다.");
} else {
toast.success("코멘트가 저장되었습니다.");
}
await loadComments(); // 목록 새로고침
} else {
toast.error(result.error || "코멘트 추가에 실패했습니다.");
}
} catch (error) {
console.error('코멘트 추가 실패:', error);
toast.error("코멘트 추가에 실패했습니다.");
} finally {
setIsSaving(false);
}
}, [newComment, newAuthorName, basicContractId, pendingFiles]); // pendingFiles 추가
// 파일 선택 핸들러
const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
if (files.length > 0) {
setPendingFiles(prev => [...prev, ...files]);
toast.success(`${files.length}개의 파일이 추가되었습니다.`);
}
e.target.value = ''; // 파일 입력 초기화
}, []);
// 대기 중인 파일 삭제 핸들러
const handleRemovePendingFile = useCallback((index: number) => {
setPendingFiles(prev => prev.filter((_, i) => i !== index));
}, []);
// 코멘트 삭제 핸들러
const handleDeleteComment = useCallback(async (commentId: number) => {
if (!confirm("이 코멘트를 삭제하시겠습니까?")) {
return;
}
try {
const result = await deleteAgreementComment(commentId);
if (result.success) {
toast.success("코멘트가 삭제되었습니다.");
await loadComments(); // 목록 새로고침
} else {
toast.error(result.error || "코멘트 삭제에 실패했습니다.");
}
} catch (error) {
console.error('코멘트 삭제 실패:', error);
toast.error("코멘트 삭제에 실패했습니다.");
}
}, []); // loadComments 제거
// 첨부파일 업로드 핸들러
const handleUploadAttachment = useCallback(async (commentId: number, file: File) => {
setUploadingFiles(prev => new Set(prev).add(commentId));
try {
const result = await uploadCommentAttachment(commentId, file);
if (result.success) {
toast.success(`${file.name}이(가) 업로드되었습니다.`);
await loadComments(); // 목록 새로고침
} else {
toast.error(result.error || "파일 업로드에 실패했습니다.");
}
} catch (error) {
console.error('파일 업로드 실패:', error);
toast.error("파일 업로드에 실패했습니다.");
} finally {
setUploadingFiles(prev => {
const next = new Set(prev);
next.delete(commentId);
return next;
});
}
}, []); // loadComments 제거
// 첨부파일 삭제 핸들러
const handleDeleteAttachment = useCallback(async (commentId: number, attachmentId: string) => {
if (!confirm("이 첨부파일을 삭제하시겠습니까?")) {
return;
}
try {
const result = await deleteCommentAttachment(commentId, attachmentId);
if (result.success) {
toast.success("첨부파일이 삭제되었습니다.");
await loadComments(); // 목록 새로고침
} else {
toast.error(result.error || "첨부파일 삭제에 실패했습니다.");
}
} catch (error) {
console.error('첨부파일 삭제 실패:', error);
toast.error("첨부파일 삭제에 실패했습니다.");
}
}, []); // loadComments 제거
// 협의 완료 핸들러
const handleCompleteNegotiation = useCallback(async () => {
if (!confirm("협의를 완료하시겠습니까?\n협의 완료 후에는 법무검토 요청이 가능합니다.")) {
return;
}
setIsCompletingNegotiation(true);
try {
const result = await completeNegotiation(basicContractId);
if (result.success) {
toast.success("협의가 완료되었습니다. 이제 법무검토 요청이 가능합니다.");
if (onNegotiationComplete) {
onNegotiationComplete();
}
} else {
toast.error(result.error || "협의 완료 처리에 실패했습니다.");
}
} catch (error) {
console.error('협의 완료 실패:', error);
toast.error("협의 완료 처리 중 오류가 발생했습니다.");
} finally {
setIsCompletingNegotiation(false);
}
}, [basicContractId, onNegotiationComplete]);
// 파일 크기 포맷팅
const formatFileSize = (bytes: number): string => {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
};
if (isLoading) {
return (
<div className={cn("h-full flex items-center justify-center", className)}>
<Loader2 className="h-8 w-8 animate-spin text-blue-500" />
</div>
);
}
return (
<div className={cn("h-full flex flex-col", className)}>
{/* 헤더 */}
<div className="flex-shrink-0 border-b bg-gray-50 p-3">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center space-x-2">
<MessageSquare className="h-5 w-5 text-blue-500" />
<h3 className="font-semibold text-gray-800">협의 코멘트</h3>
{isNegotiationCompleted && (
<Badge className="bg-green-500 text-white border-green-600">
협의 완료
</Badge>
)}
</div>
<div className="flex items-center space-x-2">
<Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200 h-8 px-3 text-sm flex items-center">
총 {comments.length}개
</Badge>
{!readOnly && !isNegotiationCompleted && (
<>
<Button
size="sm"
onClick={() => setIsAdding(true)}
disabled={isAdding}
className="h-8"
>
<Plus className="h-4 w-4 mr-1" />
코멘트 추가
</Button>
{comments.length > 0 && currentUserType === 'SHI' && (
<Button
size="sm"
onClick={handleCompleteNegotiation}
disabled={isCompletingNegotiation}
className="h-8 bg-green-600 hover:bg-green-700"
>
{isCompletingNegotiation ? (
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
) : (
<CheckCircle2 className="h-4 w-4 mr-1" />
)}
협의 완료
</Button>
)}
</>
)}
</div>
</div>
<p className="text-sm text-gray-600">
{isNegotiationCompleted
? "협의가 완료되었습니다. 법무검토 요청이 가능합니다."
: "SHI와 협력업체 간 기본계약서 협의 내용을 작성하고 공유합니다."}
</p>
</div>
{/* 코멘트 리스트 */}
<ScrollArea className="flex-1">
<div className="p-3 space-y-3">
{/* 새 코멘트 입력 폼 */}
{isAdding && !readOnly && !isNegotiationCompleted && (
<Card
className={cn(
"border-l-4",
currentUserType === 'SHI'
? "border-l-blue-500 border-blue-200 bg-blue-50"
: "border-l-green-500 border-green-200 bg-green-50"
)}
>
<CardContent className="pt-4">
<div className="space-y-3">
<div>
<Label className="text-sm font-medium text-gray-700">
작성자 유형
</Label>
<div className="mt-1.5 flex items-center space-x-2">
<Badge
variant="outline"
className={cn(
"px-3 py-1 font-semibold",
currentUserType === 'SHI'
? "bg-blue-600 text-white border-blue-700"
: "bg-green-600 text-white border-green-700"
)}
>
{currentUserType === 'SHI' ? (
<>
<Building2 className="h-3.5 w-3.5 mr-1.5" />
SHI
</>
) : (
<>
<User className="h-3.5 w-3.5 mr-1.5" />
Vendor
</>
)}
</Badge>
</div>
</div>
<div>
<Label htmlFor="authorName" className="text-sm font-medium text-gray-700">
작성자 이름 (선택사항)
</Label>
<Input
id="authorName"
value={newAuthorName}
onChange={(e) => setNewAuthorName(e.target.value)}
placeholder="작성자 이름을 입력하세요..."
className="mt-1.5"
/>
</div>
<div>
<Label htmlFor="comment" className="text-sm font-medium text-gray-700">
코멘트 *
</Label>
<Textarea
id="comment"
value={newComment}
onChange={(e) => setNewComment(e.target.value)}
placeholder="협의하고 싶은 내용을 입력하세요..."
className="mt-1.5 min-h-[100px]"
/>
</div>
{/* 파일 첨부 영역 */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-sm font-medium text-gray-700 flex items-center">
<Paperclip className="h-4 w-4 mr-1" />
첨부파일 {pendingFiles.length > 0 ? `(${pendingFiles.length})` : ''}
</Label>
<label htmlFor="new-comment-files">
<Button
type="button"
variant="outline"
size="sm"
className="h-8"
onClick={() => document.getElementById('new-comment-files')?.click()}
disabled={isSaving}
>
<Upload className="h-3 w-3 mr-1" />
파일 추가
</Button>
<input
id="new-comment-files"
type="file"
multiple
className="hidden"
onChange={handleFileSelect}
accept="*/*"
/>
</label>
</div>
{/* 대기 중인 파일 목록 */}
{pendingFiles.length > 0 && (
<div className="space-y-1.5 max-h-32 overflow-y-auto">
{pendingFiles.map((file, index) => (
<div
key={`${file.name}-${index}`}
className="flex items-center justify-between bg-white rounded p-2 border border-gray-200"
>
<div className="flex items-center space-x-2 flex-1 min-w-0">
<FileText className="h-4 w-4 text-blue-500 flex-shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-sm text-gray-700 truncate">
{file.name}
</p>
<p className="text-xs text-gray-500">
{formatFileSize(file.size)}
</p>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => handleRemovePendingFile(index)}
className="h-6 w-6 p-0 text-red-500 hover:text-red-700 hover:bg-red-50"
>
<X className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
<p className="text-xs text-gray-500">
💡 파일을 먼저 추가한 후 저장 또는 제출 버튼을 눌러주세요.
</p>
</div>
<div className="flex items-center justify-end gap-2 pt-2 border-t">
<Button
variant="outline"
size="sm"
onClick={() => {
setIsAdding(false);
setNewComment('');
setNewAuthorName('');
setPendingFiles([]);
}}
disabled={isSaving}
>
<X className="h-4 w-4 mr-1" />
취소
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleAddComment(false)}
disabled={isSaving || !newComment.trim()}
>
{isSaving ? (
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
) : (
<Save className="h-4 w-4 mr-1" />
)}
저장
</Button>
<Button
size="sm"
onClick={() => handleAddComment(true)}
disabled={isSaving || !newComment.trim()}
className="bg-blue-600 hover:bg-blue-700"
>
{isSaving ? (
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
) : (
<Send className="h-4 w-4 mr-1" />
)}
제출 (메일발송)
</Button>
</div>
</div>
</CardContent>
</Card>
)}
{/* 기존 코멘트 목록 */}
{comments.length === 0 && !isAdding ? (
<div className="text-center py-8">
<MessageSquare className="h-12 w-12 text-gray-300 mx-auto mb-3" />
<p className="text-sm text-gray-500">
{isNegotiationCompleted
? "협의가 완료되어 더 이상 코멘트를 추가할 수 없습니다."
: "아직 코멘트가 없습니다."}
</p>
{!readOnly && !isNegotiationCompleted && (
<Button
variant="outline"
size="sm"
className="mt-3"
onClick={() => setIsAdding(true)}
>
<Plus className="h-4 w-4 mr-1" />
첫 번째 코멘트 작성하기
</Button>
)}
</div>
) : (
comments.map((comment) => {
// 현재 사용자가 이 코멘트의 작성자인지 확인
const isCommentOwner = comment.authorType === currentUserType;
return (
<Card
key={comment.id}
className={cn(
"transition-all duration-200 hover:shadow-md",
comment.authorType === 'SHI'
? "border-l-4 border-l-blue-500 border-blue-200 bg-blue-50/50"
: "border-l-4 border-l-green-500 border-green-200 bg-green-50/50"
)}
>
<CardContent className="pt-4">
<div className="space-y-3">
{/* 헤더: 작성자 정보 */}
<div className="flex items-start justify-between">
<div className="flex items-center space-x-2">
<Badge
variant="outline"
className={cn(
"px-3 py-1 font-semibold",
comment.authorType === 'SHI'
? "bg-blue-600 text-white border-blue-700"
: "bg-green-600 text-white border-green-700"
)}
>
{comment.authorType === 'SHI' ? (
<>
<Building2 className="h-3.5 w-3.5 mr-1.5" />
SHI
</>
) : (
<>
<User className="h-3.5 w-3.5 mr-1.5" />
Vendor
</>
)}
</Badge>
{comment.authorName && (
<span className="text-sm font-medium text-gray-700">
{comment.authorName}
</span>
)}
</div>
{!readOnly && isCommentOwner && (
<Button
variant="ghost"
size="sm"
onClick={() => handleDeleteComment(comment.id)}
className="h-7 w-7 p-0 text-red-500 hover:text-red-700 hover:bg-red-50"
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
{/* 코멘트 내용 */}
<div className="bg-white rounded-md p-3 border border-gray-200">
<p className="text-sm text-gray-800 whitespace-pre-wrap leading-relaxed">
{comment.comment}
</p>
</div>
{/* 첨부파일 */}
{(comment.attachments.length > 0 || (!readOnly && isCommentOwner)) && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs font-medium text-gray-600 flex items-center">
<Paperclip className="h-3 w-3 mr-1" />
첨부파일 {comment.attachments.length > 0 ? `(${comment.attachments.length})` : ''}
</Label>
{!readOnly && isCommentOwner && (
<label htmlFor={`file-${comment.id}`}>
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 text-xs"
disabled={uploadingFiles.has(comment.id)}
onClick={() => document.getElementById(`file-${comment.id}`)?.click()}
>
{uploadingFiles.has(comment.id) ? (
<Loader2 className="h-3 w-3 mr-1 animate-spin" />
) : (
<Upload className="h-3 w-3 mr-1" />
)}
업로드
</Button>
<input
id={`file-${comment.id}`}
type="file"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) {
handleUploadAttachment(comment.id, file);
}
e.target.value = '';
}}
/>
</label>
)}
</div>
{comment.attachments.length > 0 && (
<div className="space-y-1.5">
{comment.attachments.map((attachment) => (
<div
key={attachment.id}
className="flex items-center justify-between bg-white rounded p-2 border border-gray-200 hover:border-gray-300 transition-colors"
>
<div className="flex items-center space-x-2 flex-1 min-w-0">
<FileText className="h-4 w-4 text-blue-500 flex-shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-sm text-gray-700 truncate">
{attachment.fileName}
</p>
<p className="text-xs text-gray-500">
{formatFileSize(attachment.fileSize)}
</p>
</div>
</div>
<div className="flex items-center space-x-1">
<Button
variant="ghost"
size="sm"
asChild
className="h-6 w-6 p-0 text-blue-500 hover:text-blue-700 hover:bg-blue-50"
>
<a
href={attachment.filePath}
download={attachment.fileName}
target="_blank"
rel="noopener noreferrer"
title={`${attachment.fileName} 다운로드`}
>
<Download className="h-3 w-3" />
</a>
</Button>
{!readOnly && isCommentOwner && (
<Button
variant="ghost"
size="sm"
onClick={() => handleDeleteAttachment(comment.id, attachment.id)}
className="h-6 w-6 p-0 text-red-500 hover:text-red-700 hover:bg-red-50"
>
<X className="h-3 w-3" />
</Button>
)}
</div>
</div>
))}
</div>
)}
</div>
)}
{/* 푸터: 작성일시 */}
<div className="flex items-center justify-between text-xs text-gray-500 pt-2 border-t border-gray-200">
<span>
작성일: {formatDateTime(comment.createdAt, "KR")}
</span>
{comment.updatedAt && comment.updatedAt.getTime() !== comment.createdAt.getTime() && (
<span>
수정일: {formatDateTime(comment.updatedAt, "KR")}
</span>
)}
</div>
</div>
</CardContent>
</Card>
);
})
)}
</div>
</ScrollArea>
</div>
);
}
|