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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
|
"use client"
import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { Download, FileDown, Mail, CheckCircle, AlertTriangle, Send, Check, FileSignature, FileText, ExternalLink, Globe, Flag } from "lucide-react"
import { exportTableToExcel } from "@/lib/export"
import { downloadFile } from "@/lib/file-download"
import { Button } from "@/components/ui/button"
import { BasicContractView } from "@/db/schema"
import { toast } from "sonner"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Badge } from "@/components/ui/badge"
import { prepareFinalApprovalAction, quickFinalApprovalAction, resendContractsAction, updateLegalReviewStatusFromSSLVW, updateComplianceReviewStatusFromCPVW, requestComplianceInquiryAction } from "../service"
import { BasicContractSignDialog } from "../vendor-table/basic-contract-sign-dialog"
import { SSLVWPurInqReqDialog } from "@/components/common/legal/sslvw-pur-inq-req-dialog"
import { CPVWWabQustListViewDialog } from "@/components/common/legal/cpvw-wab-qust-list-view-dialog"
import { prepareRedFlagResolutionApproval, requestRedFlagResolution } from "@/lib/compliance/red-flag-resolution"
import { useRouter } from "next/navigation"
import { useSession } from "next-auth/react"
import { ApprovalPreviewDialog } from "@/lib/approval/client"
interface RedFlagResolutionState {
resolved: boolean
resolvedAt: Date | null
pendingApprovalId: string | null
}
interface BasicContractDetailTableToolbarActionsProps {
table: Table<BasicContractView>
gtcData?: Record<number, { gtcDocumentId: number | null; hasComments: boolean }>
agreementCommentData?: Record<number, { hasComments: boolean; commentCount: number }>
redFlagData?: Record<number, boolean>
redFlagResolutionData?: Record<number, RedFlagResolutionState>
isComplianceTemplate?: boolean
}
export function BasicContractDetailTableToolbarActions({
table,
gtcData = {},
agreementCommentData = {},
redFlagData = {},
redFlagResolutionData = {},
isComplianceTemplate = false
}: BasicContractDetailTableToolbarActionsProps) {
// 선택된 행들 가져오기
const selectedRows = table.getSelectedRowModel().rows
const hasSelectedRows = selectedRows.length > 0
// 다이얼로그 상태
const [resendDialog, setResendDialog] = React.useState(false)
const [finalApproveDialog, setFinalApproveDialog] = React.useState(false)
const [legalReviewDialog, setLegalReviewDialog] = React.useState(false)
const [loading, setLoading] = React.useState(false)
const [buyerSignDialog, setBuyerSignDialog] = React.useState(false)
const [contractsToSign, setContractsToSign] = React.useState<any[]>([])
const [redFlagApprovalPreview, setRedFlagApprovalPreview] = React.useState<{
contractIds: number[]
templateName: string
variables: Record<string, string>
title: string
defaultApprovers?: string[]
} | null>(null)
const [showRedFlagApprovalDialog, setShowRedFlagApprovalDialog] = React.useState(false)
const router = useRouter()
const { data: session } = useSession()
// 각 버튼별 활성화 조건 계산
const canBulkDownload = hasSelectedRows && selectedRows.some(row =>
row.original.signedFilePath && row.original.signedFileName && row.original.vendorSignedAt
)
const canBulkResend = hasSelectedRows
const canFinalApprove = hasSelectedRows && selectedRows.some(row => {
const contract = row.original;
if (contract.completedAt !== null || !contract.signedFilePath) {
return false;
}
// ⚠️ 법무/준법문의 완료 여부는 SSLVW/CPVW 상태 및 완료 시간에 의존하므로,
// 여기서는 legalReviewCompletedAt / complianceReviewCompletedAt 기반으로
// 최종 승인 버튼을 막지 않습니다. (상태/시간은 UI 참고용으로만 사용)
return true;
});
// 법무검토 요청 가능 여부 (준법서약 템플릿이 아닐 때만)
// 1. 협력업체 서명 완료 (vendorSignedAt 있음)
// 2. 협의 완료됨 (negotiationCompletedAt 있음) OR
// 3. 협의 없음 (코멘트 없음, hasComments: false)
// 협의 중 (negotiationCompletedAt 없고 코멘트 있음)은 불가
const canRequestLegalReview = !isComplianceTemplate && hasSelectedRows && selectedRows.some(row => {
const contract = row.original;
// 필수 조건 확인: 최종승인 미완료, 법무검토 미요청, 협력업체 서명 완료
if (
contract.legalReviewRequestedAt ||
contract.completedAt ||
!contract.vendorSignedAt
) {
return false;
}
// 협의 완료된 경우 → 가능
if (contract.negotiationCompletedAt) {
return true;
}
// 협의 완료되지 않은 경우
// GTC 템플릿인 경우 코멘트 존재 여부 확인
if (contract.templateName?.includes('GTC')) {
const contractGtcData = gtcData[contract.id];
// 코멘트가 없으면 가능 (협의 없음)
if (contractGtcData && !contractGtcData.hasComments) {
return true;
}
// 코멘트가 있으면 불가 (협의 중)
return false;
}
// GTC가 아닌 경우는 협의 완료 여부만 확인
return false;
});
// 준법문의 버튼 활성화 가능 여부
// 1. 협력업체 서명 완료 (vendorSignedAt 있음)
// 2. 협의 완료됨 (negotiationCompletedAt 있음) OR 협의 없음 (코멘트 없음)
// 3. 레드플래그 해소됨 (redFlagResolutionData에서 resolved 상태)
// 4. 이미 준법문의 요청되지 않음 (complianceReviewRequestedAt 없음)
const canRequestComplianceInquiry = hasSelectedRows && selectedRows.some(row => {
const contract = row.original;
// 필수 조건 확인: 준법서약 템플릿, 최종승인 미완료, 협력업체 서명 완료, 준법문의 미요청
if (
!isComplianceTemplate ||
contract.completedAt ||
!contract.vendorSignedAt ||
contract.complianceReviewRequestedAt
) {
return false;
}
// 협의 완료 확인
// 협의 완료된 경우 → 가능
if (contract.negotiationCompletedAt) {
// 협의 완료됨, 레드플래그만 확인하면 됨
} else {
// 협의 완료되지 않은 경우: 코멘트가 없으면 협의 없음으로 간주하여 가능
const commentData = agreementCommentData[contract.id];
if (commentData && commentData.hasComments) {
// 코멘트가 있으면 협의 중이므로 불가
return false;
}
// 코멘트가 없으면 협의 없음으로 간주하여 가능
}
// 레드플래그 해소 확인
const resolution = redFlagResolutionData[contract.id];
// 레드플래그가 있는 경우, 해소되어야 함
if (redFlagData[contract.id] === true && !resolution?.resolved) {
return false;
}
return true;
});
// 필터링된 계약서들 계산
const resendContracts = selectedRows.map(row => row.original)
const finalApproveContracts = selectedRows
.map(row => row.original)
.filter(contract => {
if (contract.completedAt !== null || !contract.signedFilePath) {
return false;
}
if (contract.legalReviewRequestedAt && !contract.legalReviewCompletedAt) {
return false;
}
return true;
});
const contractsWithoutLegalReview = finalApproveContracts.filter(contract =>
!contract.legalReviewRequestedAt && !contract.legalReviewCompletedAt
);
// 법무검토 요청 가능한 계약서들
const legalReviewContracts = selectedRows
.map(row => row.original)
.filter(contract => {
// 이미 법무검토 요청됨
if (contract.legalReviewRequestedAt) {
return false;
}
// 이미 최종승인 완료됨
if (contract.completedAt) {
return false;
}
// 협의 완료된 경우
if (contract.negotiationCompletedAt) {
return true;
}
// 협의 완료되지 않은 경우
// GTC 템플릿인 경우 코멘트 없으면 가능
if (contract.templateName?.includes('GTC')) {
const contractGtcData = gtcData[contract.id];
// 코멘트가 없으면 가능 (협의 없음)
if (contractGtcData && !contractGtcData.hasComments) {
return true;
}
// 코멘트가 있으면 불가 (협의 중)
return false;
}
// GTC가 아닌 경우는 협의 완료 여부만 확인
return false;
});
// 대량 재발송
const handleBulkResend = async () => {
if (!hasSelectedRows) {
toast.error("재발송할 계약서를 선택해주세요")
return
}
setResendDialog(true)
}
// 선택된 계약서들 일괄 다운로드
const handleBulkDownload = async () => {
if (!canBulkDownload) {
toast.error("다운로드할 파일이 있는 계약서를 선택해주세요")
return
}
const selectedContracts = selectedRows
.map(row => row.original)
.filter(contract => contract.signedFilePath && contract.signedFileName)
if (selectedContracts.length === 0) {
toast.error("다운로드할 파일이 없습니다")
return
}
// 다운로드 시작 알림
toast.success(`${selectedContracts.length}건의 파일 다운로드를 시작합니다`)
let successCount = 0
let failedCount = 0
const failedFiles: string[] = []
// 순차적으로 다운로드 (병렬 다운로드는 브라우저 제한으로 인해 문제가 될 수 있음)
for (let i = 0; i < selectedContracts.length; i++) {
const contract = selectedContracts[i]
try {
// 진행 상황 표시
if (selectedContracts.length > 3) {
toast.loading(`다운로드 중... (${i + 1}/${selectedContracts.length})`, {
id: 'bulk-download-progress'
})
}
const result = await downloadFile(
contract.signedFilePath!,
contract.signedFileName!,
{
action: 'download',
showToast: false, // 개별 토스트는 비활성화
onError: (error) => {
console.error(`다운로드 실패 - ${contract.signedFileName}:`, error)
failedFiles.push(`${contract.vendorName || '업체명 없음'} (${contract.signedFileName})`)
failedCount++
},
onSuccess: (fileName) => {
console.log(`다운로드 성공 - ${fileName}`)
successCount++
}
}
)
if (result.success) {
successCount++
} else {
failedCount++
failedFiles.push(`${contract.vendorName || '업체명 없음'} (${contract.signedFileName})`)
}
// 다운로드 간격 (브라우저 부하 방지)
if (i < selectedContracts.length - 1) {
await new Promise(resolve => setTimeout(resolve, 300))
}
} catch (error) {
console.error(`다운로드 에러 - ${contract.signedFileName}:`, error)
failedCount++
failedFiles.push(`${contract.vendorName || '업체명 없음'} (${contract.signedFileName})`)
}
}
// 진행 상황 토스트 제거
toast.dismiss('bulk-download-progress')
// 최종 결과 표시
if (successCount === selectedContracts.length) {
toast.success(`모든 파일 다운로드 완료 (${successCount}건)`)
} else if (successCount > 0) {
toast.warning(
`일부 파일 다운로드 완료\n성공: ${successCount}건, 실패: ${failedCount}건`,
{
duration: 5000,
description: failedFiles.length > 0
? `실패한 파일: ${failedFiles.slice(0, 3).join(', ')}${failedFiles.length > 3 ? ` 외 ${failedFiles.length - 3}건` : ''}`
: undefined
}
)
} else {
toast.error(
`모든 파일 다운로드 실패 (${failedCount}건)`,
{
duration: 5000,
description: failedFiles.length > 0
? `실패한 파일: ${failedFiles.slice(0, 3).join(', ')}${failedFiles.length > 3 ? ` 외 ${failedFiles.length - 3}건` : ''}`
: undefined
}
)
}
console.log("일괄 다운로드 완료:", {
total: selectedContracts.length,
success: successCount,
failed: failedCount,
failedFiles
})
}
// 최종승인
const handleFinalApprove = async () => {
if (!canFinalApprove) {
toast.error("최종승인 가능한 계약서를 선택해주세요")
return
}
setFinalApproveDialog(true)
}
// 재요청 확인
const confirmResend = async () => {
setLoading(true)
try {
// TODO: 서버액션 호출
await resendContractsAction(resendContracts.map(c => c.id))
console.log("대량 재발송:", resendContracts)
toast.success(`${resendContracts.length}건의 계약서 재발송을 완료했습니다`)
setResendDialog(false)
table.toggleAllPageRowsSelected(false) // 선택 해제
} catch (error) {
toast.error("재발송 중 오류가 발생했습니다")
console.error(error)
} finally {
setLoading(false)
}
}
// 최종승인 확인 (수정됨)
const confirmFinalApprove = async () => {
setLoading(true)
try {
// 먼저 서명 가능한 계약서들을 준비
const prepareResult = await prepareFinalApprovalAction(
finalApproveContracts.map(c => c.id)
)
if (prepareResult.success && prepareResult.contracts) {
// 서명이 필요한 경우 서명 다이얼로그 열기
setContractsToSign(prepareResult.contracts)
setFinalApproveDialog(false) // 기존 다이얼로그는 닫기
// buyerSignDialog는 더 이상 필요 없으므로 제거
} else {
toast.error(prepareResult.message)
}
} catch (error) {
toast.error("최종승인 준비 중 오류가 발생했습니다")
console.error(error)
} finally {
setLoading(false)
}
}
// 구매자 서명 완료 콜백
const handleBuyerSignComplete = () => {
setContractsToSign([]) // 계약서 목록 초기화하여 BasicContractSignDialog 언마운트
table.toggleAllPageRowsSelected(false)
toast.success("모든 계약서의 최종승인이 완료되었습니다!")
}
// SSLVW 데이터 선택 확인 핸들러
const handleSSLVWConfirm = async (selectedSSLVWData: any[]) => {
if (!selectedSSLVWData || selectedSSLVWData.length === 0) {
toast.error("선택된 데이터가 없습니다.")
return
}
if (selectedRows.length !== 1) {
toast.error("계약서 한 건을 선택해주세요.")
return
}
try {
setLoading(true)
// 선택된 계약서 ID들 추출
const selectedContractIds = selectedRows.map(row => row.original.id)
// 서버 액션 호출
const result = await updateLegalReviewStatusFromSSLVW(selectedSSLVWData, selectedContractIds)
if (result.success) {
toast.success(result.message)
router.refresh()
table.toggleAllPageRowsSelected(false)
} else {
toast.error(result.message)
}
if (result.errors && result.errors.length > 0) {
toast.warning(`일부 처리 실패: ${result.errors.join(', ')}`)
}
} catch (error) {
console.error('SSLVW 확인 처리 실패:', error)
toast.error('법무검토 상태 업데이트 중 오류가 발생했습니다.')
} finally {
setLoading(false)
}
}
// CPVW 데이터 선택 확인 핸들러
const handleCPVWConfirm = async (selectedCPVWData: any[]) => {
if (!selectedCPVWData || selectedCPVWData.length === 0) {
toast.error("선택된 데이터가 없습니다.")
return
}
if (selectedRows.length !== 1) {
toast.error("계약서 한 건을 선택해주세요.")
return
}
try {
setLoading(true)
// 선택된 계약서 ID들 추출
const selectedContractIds = selectedRows.map(row => row.original.id)
// 서버 액션 호출
const result = await updateComplianceReviewStatusFromCPVW(selectedCPVWData, selectedContractIds)
if (result.success) {
toast.success(result.message)
router.refresh()
table.toggleAllPageRowsSelected(false)
} else {
toast.error(result.message)
}
if (result.errors && result.errors.length > 0) {
toast.warning(`일부 처리 실패: ${result.errors.join(', ')}`)
}
} catch (error) {
console.error('CPVW 확인 처리 실패:', error)
toast.error('준법문의 상태 업데이트 중 오류가 발생했습니다.')
} finally {
setLoading(false)
}
}
// 빠른 승인 (서명 없이)
const confirmQuickApproval = async () => {
setLoading(true)
try {
const result = await quickFinalApprovalAction(
finalApproveContracts.map(c => c.id)
)
if (result.success) {
toast.success(result.message)
setFinalApproveDialog(false)
table.toggleAllPageRowsSelected(false)
} else {
toast.error(result.message)
}
} catch (error) {
toast.error("최종승인 중 오류가 발생했습니다")
console.error(error)
} finally {
setLoading(false)
}
}
const hasPendingResolution = (contractId: number) => {
const state = redFlagResolutionData[contractId]
return Boolean(state?.pendingApprovalId && !state?.resolved)
}
const redFlagEligibleContracts = selectedRows
.map(row => row.original)
.filter(contract => {
if (redFlagData[contract.id] !== true) return false
return !hasPendingResolution(contract.id)
})
const redFlagPendingContracts = selectedRows
.map(row => row.original)
.filter(contract => hasPendingResolution(contract.id))
const canRequestRedFlagResolution =
hasSelectedRows && isComplianceTemplate && redFlagEligibleContracts.length > 0
// RED FLAG 해소요청
const handleRequestRedFlagResolution = async () => {
if (!canRequestRedFlagResolution) {
toast.error("해소요청 가능한 RED FLAG 계약서를 선택해주세요")
return
}
if (redFlagPendingContracts.length > 0) {
const preview = redFlagPendingContracts
.map((contract) => contract.vendorName || `계약 ${contract.id}`)
.slice(0, 2)
.join(", ")
toast.info(
`${preview}${redFlagPendingContracts.length > 2 ? ` 외 ${redFlagPendingContracts.length - 2}건` : ""}은 해소요청이 이미 진행 중입니다.`,
{
description: "진행 중인 계약서는 자동으로 제외하고 요청합니다.",
}
)
}
setLoading(true)
try {
const contractIds = redFlagEligibleContracts.map(c => c.id)
const preview = await prepareRedFlagResolutionApproval(contractIds)
setRedFlagApprovalPreview(preview)
setShowRedFlagApprovalDialog(true)
} catch (error) {
console.error("RED FLAG 해소요청 준비 오류:", error)
toast.error(
error instanceof Error
? error.message
: "RED FLAG 해소요청 정보를 준비하는 중 오류가 발생했습니다."
)
} finally {
setLoading(false)
}
}
const handleRedFlagApprovalConfirm = async (approvalData: {
approvers: string[]
title: string
attachments?: File[]
}) => {
if (!redFlagApprovalPreview) {
toast.error("결재 정보를 찾을 수 없습니다. 다시 시도해주세요.")
return
}
setLoading(true)
try {
const result = await requestRedFlagResolution({
contractIds: redFlagApprovalPreview.contractIds,
approvers: approvalData.approvers,
title: approvalData.title,
})
toast.success("RED FLAG 해소요청 결재가 상신되었습니다.", {
description: `결재 ID: ${result.approvalId}`,
})
table.toggleAllPageRowsSelected(false)
setShowRedFlagApprovalDialog(false)
setRedFlagApprovalPreview(null)
} catch (error) {
console.error("RED FLAG 해소요청 오류:", error)
toast.error(
error instanceof Error
? error.message
: "RED FLAG 해소요청 중 오류가 발생했습니다."
)
} finally {
setLoading(false)
}
}
// 법무검토 요청 링크 목록
const legalReviewLinks = [
{
id: 'domestic-contract',
label: '국내계약',
url: 'http://60.101.208.95:8080/#/pjt/register-inquiry/domestic-contract',
description: '삼성중공업 법무관리시스템 - 국내계약'
},
{
id: 'domestic-advice',
label: '국내자문',
url: 'http://60.101.208.95:8080/#/pjt/register-inquiry/domestic-advice',
description: '삼성중공업 법무관리시스템 - 국내자문'
},
{
id: 'overseas-contract',
label: '해외계약',
url: 'http://60.101.208.95:8080/#/pjt/register-inquiry/overseas-contract',
description: '삼성중공업 법무관리시스템 - 해외계약'
},
{
id: 'overseas-advice',
label: '해외자문',
url: 'http://60.101.208.95:8080/#/pjt/register-inquiry/overseas-advice',
description: '삼성중공업 법무관리시스템 - 해외자문'
}
]
const complianceInquiryUrl = 'http://60.101.207.55/Inquiry/Write/InquiryWrite.aspx'
// 법무검토 요청 / 준법문의
const handleRequestLegalReview = async () => {
if (isComplianceTemplate) {
// 준법문의: 요청일 기록 후 외부 URL 열기
const selectedContractIds = selectedRows.map(row => row.original.id)
try {
setLoading(true)
const result = await requestComplianceInquiryAction(selectedContractIds)
if (result.success) {
toast.success(result.message)
router.refresh()
window.open(complianceInquiryUrl, '_blank', 'noopener,noreferrer')
} else {
toast.error(result.message)
}
} catch (error) {
console.error('준법문의 요청 처리 실패:', error)
toast.error('준법문의 요청 중 오류가 발생했습니다.')
} finally {
setLoading(false)
}
return
}
setLegalReviewDialog(true)
}
// 법무검토 링크 클릭 핸들러
const handleLegalReviewLinkClick = (url: string) => {
window.open(url, '_blank', 'noopener,noreferrer')
setLegalReviewDialog(false)
}
return (
<>
<div className="flex items-center gap-2">
{/* 일괄 다운로드 버튼 */}
<Button
variant="outline"
size="sm"
onClick={handleBulkDownload}
disabled={!canBulkDownload}
className="gap-2"
title={!hasSelectedRows
? "계약서를 선택해주세요"
: !canBulkDownload
? "다운로드할 파일이 있는 계약서를 선택해주세요"
: `${selectedRows.filter(row => row.original.signedFilePath && row.original.signedFileName).length}건 다운로드`
}
>
<FileDown className="size-4" aria-hidden="true" />
<span className="hidden sm:inline">
일괄 다운로드 {hasSelectedRows ? `(${selectedRows.length})` : ''}
</span>
</Button>
{/* RED FLAG 해소요청 버튼 (준법서약 템플릿만) */}
{isComplianceTemplate && (
<Button
variant="outline"
size="sm"
onClick={handleRequestRedFlagResolution}
disabled={!canRequestRedFlagResolution || loading}
className="gap-2"
title={!hasSelectedRows
? "계약서를 선택해주세요"
: !canRequestRedFlagResolution
? redFlagPendingContracts.length > 0
? "이미 해소요청이 진행 중인 계약서만 선택되어 있습니다"
: "RED FLAG가 있는 계약서를 선택해주세요"
: `${redFlagEligibleContracts.length}건 RED FLAG 해소요청`
}
>
<Flag className="size-4" aria-hidden="true" />
<span className="hidden sm:inline">
RED FLAG 해소요청 {hasSelectedRows ? `(${redFlagEligibleContracts.length})` : ''}
</span>
</Button>
)}
{/* 재요청 버튼 */}
<Button
variant="outline"
size="sm"
onClick={handleBulkResend}
disabled={!canBulkResend}
className="gap-2"
title={!hasSelectedRows ? "계약서를 선택해주세요" : `${selectedRows.length}건 재발송`}
>
<Mail className="size-4" aria-hidden="true" />
<span className="hidden sm:inline">
재요청 {hasSelectedRows ? `(${selectedRows.length})` : ''}
</span>
</Button>
{/* 법무검토 버튼 (SSLVW 데이터 조회) - 준법서약 템플릿이 아닐 때만 표시 */}
{!isComplianceTemplate && (
<SSLVWPurInqReqDialog
onConfirm={handleSSLVWConfirm}
requireSingleSelection
triggerDisabled={selectedRows.length !== 1 || loading}
triggerTitle={
selectedRows.length !== 1
? "계약서 한 건을 선택해주세요"
: undefined
}
/>
)}
{/* 준법문의 요청 데이터 조회 버튼 (준법서약 템플릿만) */}
{isComplianceTemplate && (
<CPVWWabQustListViewDialog
onConfirm={handleCPVWConfirm}
requireSingleSelection
triggerDisabled={selectedRows.length !== 1 || loading}
triggerTitle={
selectedRows.length !== 1
? "계약서 한 건을 선택해주세요"
: undefined
}
/>
)}
{/* 법무검토 요청 / 준법문의 버튼 */}
{isComplianceTemplate ? (
<Button
variant="outline"
size="sm"
onClick={handleRequestLegalReview}
className="gap-2"
disabled={!canRequestComplianceInquiry || loading}
title={
!canRequestComplianceInquiry
? "협력업체 서명 완료, 협의 완료, 레드플래그 해소가 필요합니다"
: "준법문의 링크로 이동"
}
>
<FileText className="size-4" aria-hidden="true" />
<span className="hidden sm:inline">
준법문의
</span>
</Button>
) : (
<Button
variant="outline"
size="sm"
onClick={handleRequestLegalReview}
className="gap-2"
disabled={!canRequestLegalReview || loading}
title={
!canRequestLegalReview
? "협력업체 서명 완료 및 협의 완료가 필요합니다"
: "법무검토 요청 링크 선택"
}
>
<FileText className="size-4" aria-hidden="true" />
<span className="hidden sm:inline">
법무검토 요청
</span>
</Button>
)}
{/* 최종승인 버튼 */}
<Button
variant="outline"
size="sm"
onClick={handleFinalApprove}
disabled={!canFinalApprove}
className="gap-2"
title={!hasSelectedRows
? "계약서를 선택해주세요"
: !canFinalApprove
? "최종승인 가능한 계약서가 없습니다"
: `${finalApproveContracts.length}건 최종승인`
}
>
<CheckCircle className="size-4" aria-hidden="true" />
<span className="hidden sm:inline">
최종승인 {hasSelectedRows ? `(${selectedRows.length})` : ''}
</span>
</Button>
{/* 실제 구매자 서명을 위한 BasicContractSignDialog */}
{contractsToSign.length > 0 && (
<BasicContractSignDialog
contracts={contractsToSign}
onSuccess={handleBuyerSignComplete}
hasSelectedRows={contractsToSign.length > 0}
mode="buyer" // 구매자 모드 prop
t={(key) => key}
/>
)}
{/* Export 버튼 */}
<Button
variant="outline"
size="sm"
onClick={() =>
exportTableToExcel(table, {
filename: "basic-contract-details",
excludeColumns: ["select", "actions"],
})
}
className="gap-2"
>
<Download className="size-4" aria-hidden="true" />
<span className="hidden sm:inline">Export</span>
</Button>
</div>
{/* 재발송 다이얼로그 */}
<Dialog open={resendDialog} onOpenChange={setResendDialog}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Send className="size-5" />
계약서 재발송 확인
</DialogTitle>
<DialogDescription>
선택한 {resendContracts.length}건의 계약서를 재발송합니다.
</DialogDescription>
</DialogHeader>
<div className="max-h-60 overflow-y-auto">
<div className="space-y-3">
{resendContracts.map((contract, index) => (
<div key={contract.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
<div className="flex-1">
<div className="font-medium">{contract.vendorName || '업체명 없음'}</div>
<div className="text-sm text-gray-500">
{contract.vendorCode || '코드 없음'} | {contract.templateName || '템플릿명 없음'}
</div>
</div>
<Badge variant="secondary">{contract.status}</Badge>
</div>
))}
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setResendDialog(false)}
disabled={loading}
>
취소
</Button>
<Button
onClick={confirmResend}
disabled={loading}
className="gap-2"
>
<Send className="size-4" />
{loading ? "재발송 중..." : `${resendContracts.length}건 재발송`}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 법무검토 요청 다이얼로그 (준법 템플릿 제외) */}
{!isComplianceTemplate && (
<Dialog open={legalReviewDialog} onOpenChange={setLegalReviewDialog}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<FileText className="size-5" />
법무검토 요청
</DialogTitle>
<DialogDescription>
법무검토 요청 유형을 선택하세요. 선택한 링크가 새 창에서 열립니다.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="flex items-start gap-3 p-4 bg-blue-50 border border-blue-200 rounded-lg">
<Globe className="size-5 text-blue-600 flex-shrink-0 mt-0.5" />
<div>
<div className="font-medium text-blue-800">삼성중공업 법무관리시스템</div>
<div className="text-sm text-blue-700 mt-1">
아래 링크 중 해당하는 유형을 선택하여 법무검토를 요청하세요.
</div>
</div>
</div>
<div className="space-y-2">
{legalReviewLinks.map((link) => (
<button
key={link.id}
onClick={() => handleLegalReviewLinkClick(link.url)}
className="w-full flex items-center justify-between p-4 rounded-lg border border-gray-200 hover:border-blue-300 hover:bg-blue-50 transition-colors text-left group"
>
<div className="flex-1">
<div className="font-medium text-gray-900 group-hover:text-blue-700">
{link.label}
</div>
<div className="text-sm text-gray-500 mt-1">
{link.description}
</div>
</div>
<ExternalLink className="size-5 text-gray-400 group-hover:text-blue-600 flex-shrink-0 ml-4" />
</button>
))}
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setLegalReviewDialog(false)}
>
닫기
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
{/* 최종승인 다이얼로그 */}
<Dialog open={finalApproveDialog} onOpenChange={setFinalApproveDialog}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Check className="size-5" />
최종승인 전 확인
</DialogTitle>
<DialogDescription>
선택한 {finalApproveContracts.length}건의 계약서를 최종승인을 위해 서명을 호출합니다.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{contractsWithoutLegalReview.length > 0 && (
<div className="flex items-start gap-3 p-4 bg-amber-50 border border-amber-200 rounded-lg">
<AlertTriangle className="size-5 text-amber-600 flex-shrink-0 mt-0.5" />
<div>
<div className="font-medium text-amber-800">법무검토 없이 승인되는 계약서</div>
<div className="text-sm text-amber-700 mt-1">
{contractsWithoutLegalReview.length}건의 계약서가 법무검토 없이 승인됩니다.
승인 후에는 되돌릴 수 없으니 신중히 검토해주세요.
</div>
</div>
</div>
)}
<div className="max-h-60 overflow-y-auto">
<div className="space-y-3">
{finalApproveContracts.map((contract) => {
const hasLegalReview = contract.legalReviewRequestedAt && contract.legalReviewCompletedAt
const noLegalReview = !contract.legalReviewRequestedAt && !contract.legalReviewCompletedAt
return (
<div
key={contract.id}
className={`flex items-center justify-between p-3 rounded-lg ${noLegalReview ? 'bg-amber-50 border border-amber-200' : 'bg-green-50 border border-green-200'
}`}
>
<div className="flex-1">
<div className="font-medium">{contract.vendorName || '업체명 없음'}</div>
<div className="text-sm text-gray-500">
{contract.vendorCode || '코드 없음'} | {contract.templateName || '템플릿명 없음'}
</div>
{noLegalReview && (
<div className="text-xs text-amber-600 mt-1">법무검토 없음</div>
)}
{hasLegalReview && (
<div className="text-xs text-green-600 mt-1">법무검토 완료</div>
)}
</div>
<Badge variant="secondary">{contract.status}</Badge>
</div>
)
})}
</div>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setFinalApproveDialog(false)}
disabled={loading}
>
취소
</Button>
<Button
onClick={confirmFinalApprove}
disabled={loading}
className="gap-2"
variant={contractsWithoutLegalReview.length > 0 ? "destructive" : "default"}
>
<Check className="size-4" />
{loading ? "호출 중..." : `${finalApproveContracts.length}건 서명호출`}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{redFlagApprovalPreview && session?.user?.epId && (
<ApprovalPreviewDialog
open={showRedFlagApprovalDialog}
onOpenChange={(open) => {
setShowRedFlagApprovalDialog(open)
if (!open) {
setRedFlagApprovalPreview(null)
}
}}
templateName={redFlagApprovalPreview.templateName}
variables={redFlagApprovalPreview.variables}
title={redFlagApprovalPreview.title}
defaultApprovers={redFlagApprovalPreview.defaultApprovers}
currentUser={{
id: Number(session.user.id),
epId: session.user.epId,
name: session.user.name || undefined,
email: session.user.email || undefined,
}}
onConfirm={handleRedFlagApprovalConfirm}
/>
)}
</>
)
}
|