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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
|
"use client";
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { ScrollArea } from "@/components/ui/scroll-area";
import { Card, CardContent, CardHeader, CardTitle } 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 { toast } from "sonner";
import {
FileText,
MessageSquare,
ChevronRight,
ChevronDown,
Search,
AlertTriangle,
CheckCircle2,
Edit3,
Save,
X,
Loader2,
Hash,
BookOpen,
Minimize2,
Maximize2,
} from "lucide-react";
import { cn, formatDateTime } from "@/lib/utils";
import {
getVendorGtcData,
updateVendorClause,
checkVendorClausesCommentStatus,
type GtcVendorData
} from "../service";
import { useSession } from "next-auth/react"
interface GtcClausesComponentProps {
contractId?: number;
onCommentStatusChange?: (
hasComments: boolean,
commentCount: number,
reviewStatus?: string,
isComplete?: boolean
) => void;
t?: (key: string) => string;
}
// GTC 조항의 기본 타입 정의
type GtcVendorClause = {
id: number;
vendorClauseId: number | null;
baseClauseId: number;
vendorDocumentId: number | null;
parentId: number | null;
depth: number;
sortOrder: string;
fullPath: string | null;
reviewStatus: string;
negotiationNote: string | null;
isExcluded: boolean;
// 실제 표시될 값들 (기본 조항 값)
effectiveItemNumber: string;
effectiveCategory: string | null;
effectiveSubtitle: string;
effectiveContent: string | null;
// 기본 조항 정보 (동일)
baseItemNumber: string;
baseCategory: string | null;
baseSubtitle: string;
baseContent: string | null;
// 수정 여부 (코멘트만 있으면 false)
hasModifications: boolean;
isNumberModified: boolean;
isCategoryModified: boolean;
isSubtitleModified: boolean;
isContentModified: boolean;
// 코멘트 관련
hasComment: boolean;
pendingComment: string | null;
};
interface ClauseState extends GtcVendorClause {
isExpanded?: boolean;
isEditing?: boolean;
tempComment?: string;
isSaving?: boolean;
uniqueId: number;
commentHistory?: CommentHistory[]; // 추가
showHistory?: boolean; // 이력 표시 여부
}
interface CommentHistory {
vendorClauseId: number;
comment: string;
actorName?: string;
actorEmail?: string;
createdAt: Date;
action: string;
}
export function GtcClausesComponent({
contractId,
onCommentStatusChange,
t = (key: string) => key
}: GtcClausesComponentProps) {
const [gtcData, setGtcData] = useState<GtcVendorData | null>(null);
const [clauses, setClauses] = useState<ClauseState[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [searchTerm, setSearchTerm] = useState("");
const [expandedItems, setExpandedItems] = useState<Set<number>>(new Set());
const [compactMode, setCompactMode] = useState(true); // 컴팩트 모드 상태 추가
const { data: session } = useSession();
const onCommentStatusChangeRef = useRef(onCommentStatusChange);
onCommentStatusChangeRef.current = onCommentStatusChange;
// 데이터 로드
const loadGtcData = useCallback(async () => {
try {
setLoading(true);
setError(null);
const data = await getVendorGtcData(contractId);
if (!data) {
setError("GTC 데이터를 찾을 수 없습니다.");
return;
}
setGtcData(data);
const initialClauses: ClauseState[] = data.clauses.map(clause => ({
...clause,
uniqueId: clause.id,
isExpanded: false,
isEditing: false,
tempComment: clause.negotiationNote || "",
isSaving: false,
}));
setClauses(initialClauses);
} catch (err) {
console.error('GTC 데이터 로드 실패:', err);
setError(err instanceof Error ? err.message : 'GTC 데이터를 불러오는데 실패했습니다.');
} finally {
setLoading(false);
}
}, [contractId]);
const lastCommentStatusRef = useRef<{ hasComments: boolean; commentCount: number , reviewStatus:string} | null>(null);
// 코멘트 상태 변경을 별도 useEffect로 처리
useEffect(() => {
if (clauses.length > 0 && gtcData) {
const commentCount = clauses.filter(c => c.hasComment).length;
const hasComments = commentCount > 0;
const reviewStatus = gtcData.vendorDocument?.reviewStatus || 'draft';
// reviewStatus가 complete이면 코멘트가 있어도 완료된 것으로 처리
const isComplete = reviewStatus === 'complete' || reviewStatus === 'approved';
const currentStatus = { hasComments, commentCount, reviewStatus, isComplete };
if (!lastCommentStatusRef.current ||
lastCommentStatusRef.current.hasComments !== hasComments ||
lastCommentStatusRef.current.commentCount !== commentCount ||
lastCommentStatusRef.current.reviewStatus !== reviewStatus) {
lastCommentStatusRef.current = currentStatus;
// isComplete 정보도 전달
onCommentStatusChangeRef.current?.(hasComments, commentCount, reviewStatus, isComplete);
}
}
}, [clauses, gtcData]);
useEffect(() => {
loadGtcData();
}, [loadGtcData]);
// 검색 필터링
const filteredClauses = React.useMemo(() => {
if (!searchTerm.trim()) return clauses;
const term = searchTerm.toLowerCase();
return clauses.filter(clause =>
clause.effectiveItemNumber.toLowerCase().includes(term) ||
clause.effectiveSubtitle.toLowerCase().includes(term) ||
clause.effectiveContent?.toLowerCase().includes(term) ||
clause.negotiationNote?.toLowerCase().includes(term)
);
}, [clauses, searchTerm]);
// 계층 구조로 조항 그룹화
const groupedClauses = React.useMemo(() => {
const grouped: { [key: number]: ClauseState[] } = { 0: [] }; // 최상위는 0
filteredClauses.forEach(clause => {
// parentId를 baseClauseId와 매핑 (parentId는 실제 baseClauseId를 가리킴)
let parentKey = 0; // 기본값은 최상위
if (clause.parentId !== null) {
// parentId에 해당하는 조항을 찾아서 그 조항의 uniqueId를 사용
const parentClause = filteredClauses.find(c => c.baseClauseId === clause.parentId);
if (parentClause) {
parentKey = parentClause.uniqueId;
}
}
if (!grouped[parentKey]) {
grouped[parentKey] = [];
}
grouped[parentKey].push(clause);
});
// 정렬
Object.keys(grouped).forEach(key => {
grouped[parseInt(key)].sort((a, b) => parseFloat(a.sortOrder) - parseFloat(b.sortOrder));
});
return grouped;
}, [filteredClauses]);
// 토글 확장/축소
const toggleExpand = useCallback((uniqueId: number) => {
setExpandedItems(prev => {
const next = new Set(prev);
if (next.has(uniqueId)) {
next.delete(uniqueId);
} else {
next.add(uniqueId);
}
return next;
});
}, []);
// 편집 모드 토글
const toggleEdit = useCallback((uniqueId: number) => {
setClauses(prev => prev.map(clause => {
if (clause.uniqueId === uniqueId) {
return {
...clause,
isEditing: !clause.isEditing,
tempComment: "",
};
}
return clause;
}));
}, []);
// 임시 코멘트 업데이트
const updateTempComment = useCallback((uniqueId: number, comment: string) => {
setClauses(prev => prev.map(clause => {
if (clause.uniqueId === uniqueId) {
return { ...clause, tempComment: comment };
}
return clause;
}));
}, []);
// toggleCommentHistory 함수 추가
const toggleCommentHistory = useCallback((uniqueId: number) => {
setClauses(prev => prev.map(clause => {
if (clause.uniqueId === uniqueId) {
return { ...clause, showHistory: !clause.showHistory };
}
return clause;
}));
}, []);
// 코멘트 저장
const saveComment = useCallback(async (uniqueId: number) => {
const clause = clauses.find(c => c.uniqueId === uniqueId);
if (!clause) return;
// 빈 코멘트 체크 - 신규 입력 시에만
if (!clause.hasComment && (!clause.tempComment || clause.tempComment.trim() === "")) {
toast.error("코멘트를 입력해주세요.");
return;
}
setClauses(prev => prev.map(c =>
c.uniqueId === uniqueId ? { ...c, isSaving: true } : c
));
try {
const clauseData = {
itemNumber: clause.effectiveItemNumber,
category: clause.effectiveCategory,
subtitle: clause.effectiveSubtitle,
content: clause.effectiveContent,
comment: clause.tempComment || "",
};
const result = await updateVendorClause(
clause.id,
clause.vendorClauseId,
clauseData,
gtcData?.vendorDocument
);
if (result.success) {
if (!session?.user?.id) {
toast.error("로그인이 필요합니다.");
return;
}
// 새 코멘트를 이력에 추가
const newHistory = {
vendorClauseId: result.vendorClauseId,
comment: clause.tempComment || "",
actorName: session.user.name ||"현재 사용자", // 실제로는 세션에서 가져와야 함
createdAt: new Date(),
action: "commented"
};
setClauses(prev => prev.map(c => {
if (c.uniqueId === uniqueId) {
const updatedHistory = [newHistory, ...(c.commentHistory || [])];
return {
...c,
vendorClauseId: result.vendorClauseId || c.vendorClauseId,
negotiationNote: clause.tempComment?.trim() || null,
latestComment: clause.tempComment?.trim() || null,
commentHistory: updatedHistory,
hasComment: true,
isEditing: false,
isSaving: false,
};
}
return c;
}));
toast.success("코멘트가 저장되었습니다.");
} else {
toast.error(result.error || "코멘트 저장에 실패했습니다.");
setClauses(prev => prev.map(c =>
c.uniqueId === uniqueId ? { ...c, isSaving: false } : c
));
}
} catch (error) {
console.error('코멘트 저장 실패:', error);
toast.error("코멘트 저장 중 오류가 발생했습니다.");
setClauses(prev => prev.map(c =>
c.uniqueId === uniqueId ? { ...c, isSaving: false } : c
));
}
}, [clauses, gtcData]);
// 편집 취소
const cancelEdit = useCallback((uniqueId: number) => {
setClauses(prev => prev.map(clause => {
if (clause.uniqueId === uniqueId) {
return {
...clause,
isEditing: false,
tempComment: clause.negotiationNote || "",
};
}
return clause;
}));
}, []);
// 컴팩트 모드 렌더링
const renderCompactClause = useCallback((clause: ClauseState, depth: number = 0): React.ReactNode => {
const isExpanded = expandedItems.has(clause.uniqueId);
const children = groupedClauses[clause.uniqueId] || [];
const hasChildren = children.length > 0;
return (
<div key={clause.uniqueId} className={`${depth > 0 ? 'ml-4' : ''}`}>
<div className={cn(
"flex items-center justify-between p-2 rounded border transition-all duration-200 hover:bg-gray-50 mb-1",
clause.hasComment && "border-amber-200 bg-amber-50",
clause.isExcluded && "opacity-50 border-gray-300"
)}>
<div className="flex items-center space-x-2 flex-1 min-w-0">
{/* 확장/축소 버튼 */}
<Button
variant="ghost"
size="sm"
className="h-5 w-5 p-0 flex-shrink-0"
onClick={() => toggleExpand(clause.uniqueId)}
>
{isExpanded ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronRight className="h-3 w-3" />
)}
</Button>
{/* 조항 번호 */}
<span className="font-mono text-blue-600 text-sm flex-shrink-0 min-w-0 font-medium">
{clause.effectiveItemNumber}
</span>
{/* 제목 */}
<span className="text-sm text-gray-800 truncate flex-1 min-w-0">
{clause.effectiveSubtitle}
</span>
{/* 상태 표시 */}
<div className="flex items-center space-x-1 flex-shrink-0">
{/* {clause.hasComment && (
<Badge variant="outline" className="text-xs px-1.5 py-0.5 h-5 bg-amber-50 text-amber-600 border-amber-200">
<MessageSquare className="h-2.5 w-2.5" />
</Badge>
)} */}
{clause.isExcluded && (
<Badge variant="outline" className="text-xs px-1.5 py-0.5 h-5 bg-gray-50 text-gray-500 border-gray-300">
제외
</Badge>
)}
</div>
</div>
{/* 편집 버튼 */}
<div className="flex items-center space-x-1 flex-shrink-0 ml-2">
{clause.isEditing ? (
<div className="flex items-center space-x-1">
<Button
variant="ghost"
size="sm"
onClick={() => saveComment(clause.uniqueId)}
disabled={clause.isSaving}
className="h-6 w-6 p-0 text-green-600 hover:text-green-700 hover:bg-green-50"
>
{clause.isSaving ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<Save className="h-3 w-3" />
)}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => cancelEdit(clause.uniqueId)}
disabled={clause.isSaving}
className="h-6 w-6 p-0 text-gray-500 hover:text-gray-700 hover:bg-gray-50"
>
<X className="h-3 w-3" />
</Button>
</div>
) : (
<Button
variant="ghost"
size="sm"
onClick={() => toggleEdit(clause.uniqueId)}
className={cn(
"h-6 w-6 p-0 transition-colors",
clause.hasComment
? "text-amber-600 hover:text-amber-700 hover:bg-amber-50"
: "text-gray-500 hover:text-gray-700 hover:bg-gray-50"
)}
>
{clause.hasComment ? (
<MessageSquare className="h-3 w-3" />
) : (
<Edit3 className="h-3 w-3" />
)}
</Button>
)}
</div>
</div>
{/* 확장된 내용 */}
{isExpanded && (
<div className="mt-1 ml-5 p-3 bg-white rounded border border-gray-200">
{/* 카테고리 */}
{clause.effectiveCategory && (
<div className="mb-2">
<span className="text-sm text-gray-500 font-medium">카테고리: </span>
<span className="text-sm text-gray-700">{clause.effectiveCategory}</span>
</div>
)}
{/* 내용 */}
{clause.effectiveContent && (
<p className="text-sm text-gray-700 leading-relaxed mb-3 whitespace-pre-wrap">
{clause.effectiveContent}
</p>
)}
{/* 코멘트 편집 영역 */}
{clause.isEditing && (
<div className="mb-3 p-2.5 bg-amber-50 rounded border border-amber-200">
<div className="flex items-center text-sm font-medium text-amber-800 mb-2">
<MessageSquare className="h-4 w-4 mr-2" />
협의 코멘트
</div>
<Textarea
value={clause.tempComment || ""}
onChange={(e) => updateTempComment(clause.uniqueId, e.target.value)}
placeholder="이 조항에 대한 의견이나 수정 요청 사항을 입력해주세요..."
className="min-h-[60px] text-sm bg-white border-amber-200 focus:border-amber-300"
disabled={clause.isSaving}
/>
<p className="text-xs text-amber-600 mt-1">
코멘트를 입력하면 이 계약서는 서명할 수 없게 됩니다.
</p>
</div>
)}
{/* 기존 코멘트 표시 */}
{!clause.isEditing && clause.hasComment && (
<div className="mb-2 p-2.5 bg-amber-50 rounded border border-amber-200">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center text-sm font-medium text-amber-800">
<MessageSquare className="h-4 w-4 mr-2" />
협의 코멘트
{clause.commentHistory && clause.commentHistory.length > 1 && (
<Badge variant="outline" className="ml-2 text-xs">
{clause.commentHistory.length}개 이력
</Badge>
)}
</div>
{clause.commentHistory && clause.commentHistory.length > 1 && (
<Button
variant="ghost"
size="sm"
onClick={() => toggleCommentHistory(clause.uniqueId)}
className="h-6 px-2 text-xs text-amber-600 hover:text-amber-700"
>
{clause.showHistory ? "이력 숨기기" : "이력 보기"}
</Button>
)}
</div>
{/* 최신 코멘트 */}
<div className="space-y-2">
<div className="bg-white p-2 rounded border border-amber-100">
<p className="text-sm text-amber-700 whitespace-pre-wrap">
{clause.latestComment || clause.negotiationNote}
</p>
{clause.commentHistory?.[0] && (
<div className="flex items-center justify-between mt-1 pt-1 border-t border-amber-100">
<span className="text-xs text-amber-600">
{clause.commentHistory[0].actorName || "SHI"}
</span>
<span className="text-xs text-amber-500">
{formatDateTime(clause.commentHistory[0].createdAt, "KR")}
</span>
</div>
)}
</div>
{/* 이전 코멘트 이력 */}
{clause.showHistory && clause.commentHistory && clause.commentHistory.length > 1 && (
<div className="space-y-1.5 max-h-60 overflow-y-auto">
{clause.commentHistory.slice(1).map((history, idx) => (
<div key={idx} className="bg-white/50 p-2 rounded border border-amber-100/50">
<p className="text-xs text-amber-600 whitespace-pre-wrap">
{history.comment}
</p>
<div className="flex items-center justify-between mt-1 pt-1 border-t border-amber-100/50">
<span className="text-xs text-amber-500">
{history.actorName || "SHI"}
</span>
<span className="text-xs text-amber-400">
{formatDateTime(history.createdAt, "KR")}
</span>
</div>
</div>
))}
</div>
)}
</div>
</div>
)}
</div>
)}
{/* 자식 조항들 */}
{hasChildren && (
<div className={isExpanded ? "mt-1 border-l border-gray-200 pl-3" : ""}>
{children.map(child => renderCompactClause(child, depth + 1))}
</div>
)}
</div>
);
}, [expandedItems, groupedClauses, toggleExpand, saveComment, cancelEdit, toggleEdit, updateTempComment]);
// 기본 모드 렌더링 (기존 코드 최적화)
const renderNormalClause = useCallback((clause: ClauseState, depth: number = 0): React.ReactNode => {
const isExpanded = expandedItems.has(clause.uniqueId);
const children = groupedClauses[clause.uniqueId] || [];
const hasChildren = children.length > 0;
return (
<div key={clause.uniqueId} className={`mb-1 ${depth > 0 ? 'ml-4' : ''}`}>
<Card className={cn(
"transition-all duration-200",
clause.hasComment && "border-amber-200 bg-amber-50",
clause.isExcluded && "opacity-50 border-gray-300"
)}>
<CardHeader className="pb-1 pt-2 px-3">
<div className="flex items-start justify-between">
<div className="flex items-start space-x-2 flex-1 min-w-0">
{/* 확장/축소 버튼 */}
<Button
variant="ghost"
size="sm"
className="h-5 w-5 p-0 flex-shrink-0"
onClick={() => toggleExpand(clause.uniqueId)}
>
{isExpanded ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronRight className="h-3 w-3" />
)}
</Button>
<div className="flex-1 min-w-0">
<CardTitle className="text-sm font-medium text-gray-800 flex items-center">
<Hash className="h-3 w-3 mr-1 text-blue-500" />
{clause.effectiveItemNumber}
{clause.hasComment && (
<Badge variant="outline" className="ml-2 text-xs bg-amber-50 text-amber-700 border-amber-200">
<MessageSquare className="h-2 w-2 mr-1" />
코멘트
</Badge>
)}
{clause.isExcluded && (
<Badge variant="outline" className="ml-2 text-xs bg-gray-50 text-gray-500 border-gray-300">
제외됨
</Badge>
)}
</CardTitle>
<p className="text-sm font-medium text-gray-700 mt-0.5">
{clause.effectiveSubtitle}
</p>
</div>
{/* 코멘트 버튼 */}
<div className="flex items-center space-x-0.5 flex-shrink-0">
{clause.isEditing ? (
<div className="flex items-center space-x-0.5">
<Button
variant="ghost"
size="sm"
onClick={() => saveComment(clause.uniqueId)}
disabled={clause.isSaving}
className="h-6 px-2 text-green-600 hover:text-green-700 hover:bg-green-50"
>
{clause.isSaving ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<Save className="h-3 w-3" />
)}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => cancelEdit(clause.uniqueId)}
disabled={clause.isSaving}
className="h-6 px-2 text-gray-500 hover:text-gray-700 hover:bg-gray-50"
>
<X className="h-3 w-3" />
</Button>
</div>
) : (
<Button
variant="ghost"
size="sm"
onClick={() => toggleEdit(clause.uniqueId)}
className={cn(
"h-6 px-2 transition-colors",
clause.hasComment
? "text-amber-600 hover:text-amber-700 hover:bg-amber-50"
: "text-gray-500 hover:text-gray-700 hover:bg-gray-50"
)}
>
{clause.hasComment ? (
<MessageSquare className="h-3 w-3" />
) : (
<Edit3 className="h-3 w-3" />
)}
</Button>
)}
</div>
</div>
</div>
</CardHeader>
{isExpanded && (
<CardContent className="pt-0 px-3 pb-2">
{/* 카테고리 */}
{clause.effectiveCategory && (
<div className="mb-2">
<div className="flex items-center text-xs text-gray-500 mb-1">
<BookOpen className="h-3 w-3 mr-1" />
카테고리
</div>
<p className="text-sm text-gray-700 bg-gray-50 p-2 rounded">
{clause.effectiveCategory}
</p>
</div>
)}
{/* 내용 */}
{clause.effectiveContent && (
<div className="mb-2">
<div className="flex items-center text-xs text-gray-500 mb-1">
<FileText className="h-3 w-3 mr-1" />
내용
</div>
<p className="text-sm text-gray-700 bg-gray-50 p-2 rounded whitespace-pre-wrap leading-tight">
{clause.effectiveContent}
</p>
</div>
)}
{/* 코멘트 편집 영역 */}
{clause.isEditing && (
<div className="mb-2 p-2 bg-amber-50 rounded border border-amber-200">
<div className="flex items-center text-sm font-medium text-amber-800 mb-1">
<MessageSquare className="h-4 w-4 mr-2" />
협의 코멘트
</div>
<Textarea
value={clause.tempComment || ""}
onChange={(e) => updateTempComment(clause.uniqueId, e.target.value)}
placeholder="이 조항에 대한 의견이나 수정 요청 사항을 입력해주세요..."
className="min-h-[60px] text-sm bg-white border-amber-200 focus:border-amber-300"
disabled={clause.isSaving}
/>
<p className="text-xs text-amber-600 mt-1">
코멘트를 입력하면 이 계약서는 서명할 수 없게 됩니다.
</p>
</div>
)}
{/* 기존 코멘트 표시 */}
{!clause.isEditing && clause.hasComment && clause.negotiationNote && (
<div className="mb-2 p-2 bg-amber-50 rounded border border-amber-200">
<div className="flex items-center text-sm font-medium text-amber-800 mb-1">
<MessageSquare className="h-4 w-4 mr-2" />
협의 코멘트
</div>
<p className="text-sm text-amber-700 whitespace-pre-wrap">
{clause.negotiationNote}
</p>
</div>
)}
{/* 자식 조항들 */}
{hasChildren && (
<div className="mt-2 border-l-2 border-gray-200 pl-2">
{children.map(child => renderNormalClause(child, depth + 1))}
</div>
)}
</CardContent>
)}
</Card>
{/* 확장되지 않았을 때 자식 조항들 */}
{!isExpanded && hasChildren && (
<div className="ml-4">
{children.map(child => renderNormalClause(child, depth + 1))}
</div>
)}
</div>
);
}, [expandedItems, groupedClauses, toggleExpand, saveComment, cancelEdit, toggleEdit, updateTempComment]);
if (loading) {
return (
<div className="flex items-center justify-center h-64">
<div className="text-center">
<Loader2 className="h-8 w-8 text-blue-500 animate-spin mx-auto mb-4" />
<p className="text-sm text-gray-500">GTC 조항을 불러오는 중...</p>
</div>
</div>
);
}
if (error) {
return (
<div className="flex items-center justify-center h-64">
<div className="text-center">
<AlertTriangle className="h-8 w-8 text-red-500 mx-auto mb-4" />
<p className="text-sm text-gray-700 font-medium mb-2">GTC 데이터 로드 실패</p>
<p className="text-sm text-gray-500 mb-4">{error}</p>
<Button onClick={loadGtcData} size="sm">
다시 시도
</Button>
</div>
</div>
);
}
if (!gtcData) {
return (
<div className="flex items-center justify-center h-64">
<div className="text-center">
<FileText className="h-8 w-8 text-gray-400 mx-auto mb-4" />
<p className="text-sm text-gray-500">GTC 데이터가 없습니다.</p>
</div>
</div>
);
}
const totalComments = clauses.filter(c => c.hasComment).length;
return (
<div className="h-full flex flex-col">
{/* 헤더 */}
<div className={cn(
"flex-shrink-0 border-b bg-gray-50",
compactMode ? "p-2.5" : "p-3"
)}>
<div className={cn(
"flex items-center justify-between",
compactMode ? "mb-2" : "mb-2"
)}>
<div className="flex-1 min-w-0">
<h3 className={cn(
"font-semibold text-gray-800 flex items-center",
compactMode ? "text-sm" : "text-base"
)}>
<FileText className={cn(
"mr-2 text-blue-500",
compactMode ? "h-4 w-4" : "h-5 w-5"
)} />
{gtcData.vendorDocument.name}
{/* reviewStatus 배지 추가 */}
{gtcData.vendorDocument.reviewStatus && (
<Badge
variant="outline"
className={cn(
"ml-2",
gtcData.vendorDocument.reviewStatus === 'complete' || gtcData.vendorDocument.reviewStatus === 'approved'
? "bg-green-50 text-green-700 border-green-200"
: gtcData.vendorDocument.reviewStatus === 'reviewing'
? "bg-blue-50 text-blue-700 border-blue-200"
: "bg-gray-50 text-gray-700 border-gray-200"
)}
>
{gtcData.vendorDocument.reviewStatus === 'complete' ? '협의 완료' :
gtcData.vendorDocument.reviewStatus === 'approved' ? '승인됨' :
gtcData.vendorDocument.reviewStatus === 'reviewing' ? '협의 중' :
gtcData.vendorDocument.reviewStatus === 'draft' ? '초안' :
gtcData.vendorDocument.reviewStatus}
</Badge>
)}
</h3>
{!compactMode && (
<p className="text-sm text-gray-500 mt-0.5">
{gtcData.vendorDocument.description || "GTC 조항 검토 및 협의"}
</p>
)}
</div>
<div className="flex items-center space-x-1.5">
{/* 모드 전환 버튼 */}
<Button
variant="ghost"
size="sm"
onClick={() => setCompactMode(!compactMode)}
className={cn(
"transition-colors",
compactMode ? "h-7 px-2" : "h-7 px-2"
)}
title={compactMode ? "일반 모드로 전환" : "컴팩트 모드로 전환"}
>
{compactMode ? (
<Maximize2 className="h-3 w-3" />
) : (
<Minimize2 className="h-3 w-3" />
)}
</Button>
<Badge variant="outline" className={cn(
"bg-blue-50 text-blue-700 border-blue-200",
compactMode ? "text-xs px-1.5 py-0.5" : "text-xs"
)}>
총 {clauses.length}개 조항
</Badge>
{totalComments > 0 && (
<Badge variant="outline" className={cn(
"bg-amber-50 text-amber-700 border-amber-200",
compactMode ? "text-xs px-1.5 py-0.5" : "text-xs"
)}>
<MessageSquare className={cn(
"mr-1",
compactMode ? "h-2.5 w-2.5" : "h-3 w-3"
)} />
{totalComments}개 코멘트
</Badge>
)}
</div>
</div>
{/* 검색 */}
<div className="relative">
<div className="absolute inset-y-0 left-2 flex items-center pointer-events-none">
<Search className={cn(
"text-gray-400",
compactMode ? "h-3.5 w-3.5" : "h-4 w-4"
)} />
</div>
<Input
placeholder={compactMode ? "조항 검색..." : "조항 번호, 제목, 내용, 코멘트로 검색..."}
className={cn(
"bg-white text-gray-700",
compactMode ? "pl-8 text-sm h-8" : "pl-8 text-sm"
)}
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
{/* 안내 메시지 수정 - reviewStatus 체크 */}
{totalComments > 0 && gtcData.vendorDocument.reviewStatus !== 'complete' && gtcData.vendorDocument.reviewStatus !== 'approved' && (
<div className={cn(
"bg-amber-50 rounded border border-amber-200",
compactMode ? "mt-2 p-2" : "mt-2 p-2"
)}>
<div className={cn(
"flex items-center text-amber-800",
compactMode ? "text-sm" : "text-sm"
)}>
<AlertTriangle className={cn(
"mr-2",
compactMode ? "h-4 w-4" : "h-4 w-4"
)} />
<span className="font-medium">코멘트가 있어 서명할 수 없습니다.</span>
</div>
{!compactMode && (
<p className="text-sm text-amber-700 mt-0.5">
모든 코멘트를 삭제하거나 협의를 완료한 후 서명해주세요.
</p>
)}
</div>
)}
{/* 협의 완료 메시지 */}
{totalComments > 0 && (gtcData.vendorDocument.reviewStatus === 'complete' || gtcData.vendorDocument.reviewStatus === 'approved') && (
<div className={cn(
"bg-green-50 rounded border border-green-200",
compactMode ? "mt-2 p-2" : "mt-2 p-2"
)}>
<div className={cn(
"flex items-center text-green-800",
compactMode ? "text-sm" : "text-sm"
)}>
<CheckCircle2 className={cn(
"mr-2",
compactMode ? "h-4 w-4" : "h-4 w-4"
)} />
<span className="font-medium">협의가 완료되어 서명 가능합니다.</span>
</div>
</div>
)}
</div>
{/* 조항 목록 */}
<ScrollArea className="flex-1">
<div className={compactMode ? "p-2.5" : "p-3"}>
{filteredClauses.length === 0 ? (
<div className="text-center py-6">
<FileText className="h-6 w-6 text-gray-300 mx-auto mb-2" />
<p className="text-sm text-gray-500">
{searchTerm ? "검색 결과가 없습니다." : "조항이 없습니다."}
</p>
</div>
) : (
<div className={compactMode ? "space-y-0.5" : "space-y-1"}>
{(groupedClauses[0] || []).map(clause =>
compactMode ? renderCompactClause(clause) : renderNormalClause(clause)
)}
</div>
)}
</div>
</ScrollArea>
</div>
);
}
|