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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
|
"use client";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Plus,
Send,
Eye,
Edit,
Trash2,
Building2,
Calendar,
DollarSign,
FileText,
RefreshCw,
Mail,
CheckCircle,
Clock,
XCircle,
AlertCircle,
Settings2,
ClipboardList,
Globe,
Package,
MapPin,
Info,
Loader2,
Router,
Shield,
CheckSquare,
GitCompare,
Link
} from "lucide-react";
import { format } from "date-fns";
import { ko } from "date-fns/locale";
import { type ColumnDef } from "@tanstack/react-table";
import { Checkbox } from "@/components/ui/checkbox";
import { ClientDataTableColumnHeaderSimple } from "@/components/client-data-table/data-table-column-simple-header";
import { ClientDataTable } from "@/components/client-data-table/data-table";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import type { DataTableAdvancedFilterField } from "@/types/table";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { AddVendorDialog } from "./add-vendor-dialog";
import { BatchUpdateConditionsDialog } from "./batch-update-conditions-dialog";
import { SendRfqDialog } from "./send-rfq-dialog";
import {
getRfqSendData,
getSelectedVendorsWithEmails,
sendRfqToVendors,
updateShortList,
type RfqSendData,
type VendorEmailInfo
} from "../service"
import { VendorResponseDetailDialog } from "./vendor-detail-dialog";
import { DeleteVendorDialog } from "./delete-vendor-dialog";
import { useRouter } from "next/navigation"
import { EditContractDialog } from "./edit-contract-dialog";
import { createFilterFn } from "@/components/client-data-table/table-filters";
import { AvlVendorDialog } from "./avl-vendor-dialog";
// 타입 정의
interface RfqDetail {
detailId: number;
vendorId: number | null;
vendorName: string | null;
vendorCode: string | null;
vendorCountry: string | null;
vendorEmail?: string | null;
vendorCategory?: string | null;
vendorGrade?: string | null;
basicContract?: string | null;
shortList: boolean;
currency: string | null;
paymentTermsCode: string | null;
paymentTermsDescription: string | null;
incotermsCode: string | null;
incotermsDescription: string | null;
incotermsDetail?: string | null;
deliveryDate: Date | null;
contractDuration: string | null;
taxCode: string | null;
placeOfShipping?: string | null;
placeOfDestination?: string | null;
materialPriceRelatedYn?: boolean | null;
sparepartYn?: boolean | null;
firstYn?: boolean | null;
firstDescription?: string | null;
sparepartDescription?: string | null;
updatedAt?: Date | null;
updatedByUserName?: string | null;
emailSentAt: string | null;
emailSentTo: string | null; // JSON string
emailResentCount: number;
lastEmailSentAt: string | null;
emailStatus: string | null;
}
interface VendorResponse {
id: number;
rfqsLastId: number;
rfqLastDetailsId: number;
responseVersion: number;
isLatest: boolean;
status: "초대됨" | "작성중" | "제출완료" | "수정요청" | "최종확정" | "취소";
vendor: {
id: number;
code: string | null;
name: string;
email: string;
};
submission: {
submittedAt: Date | null;
submittedBy: string | null;
submittedByName: string | null;
};
pricing: {
totalAmount: number | null;
currency: string | null;
vendorCurrency: string | null;
};
vendorTerms: {
paymentTermsCode: string | null;
incotermsCode: string | null;
deliveryDate: Date | null;
contractDuration: string | null;
};
additionalRequirements: {
firstArticle: {
required: boolean | null;
acceptance: boolean | null;
};
sparePart: {
required: boolean | null;
acceptance: boolean | null;
};
};
counts: {
quotedItems: number;
attachments: number;
};
remarks: {
general: string | null;
technical: string | null;
};
timestamps: {
createdAt: string;
updatedAt: string;
};
}
// Props 타입 정의
interface RfqVendorTableProps {
rfqId: number;
rfqCode?: string;
rfqDetails: RfqDetail[];
vendorResponses: VendorResponse[];
rfqInfo?: {
rfqTitle: string;
rfqType: string;
projectCode?: string;
projectName?: string;
picName?: string;
picCode?: string;
picTeam?: string;
packageNo?: string;
packageName?: string;
designPicName?: string;
designTeam?: string;
materialGroup?: string;
materialGroupDesc?: string;
dueDate: Date;
quotationType?: string;
evaluationApply?: boolean;
contractType?: string;
};
attachments?: Array<{
id: number;
attachmentType: string;
serialNo: string;
currentRevision: string;
description?: string;
fileName?: string;
fileSize?: number;
uploadedAt?: Date;
}>;
}
// 상태별 아이콘 반환
const getStatusIcon = (status: string) => {
switch (status) {
case "초대됨": return <Mail className="h-4 w-4" />;
case "작성중": return <Clock className="h-4 w-4" />;
case "제출완료": return <CheckCircle className="h-4 w-4" />;
case "수정요청": return <AlertCircle className="h-4 w-4" />;
case "최종확정": return <FileText className="h-4 w-4" />;
case "취소": return <XCircle className="h-4 w-4" />;
default: return <Clock className="h-4 w-4" />;
}
};
// 상태별 색상
const getStatusVariant = (status: string) => {
switch (status) {
case "초대됨": return "secondary";
case "작성중": return "outline";
case "제출완료": return "default";
case "수정요청": return "warning";
case "최종확정": return "success";
case "취소": return "destructive";
default: return "outline";
}
};
// 데이터 병합 (rfqDetails + vendorResponses)
const mergeVendorData = (
rfqDetails: RfqDetail[],
vendorResponses: VendorResponse[],
rfqCode?: string
): (RfqDetail & { response?: VendorResponse; rfqCode?: string })[] => {
return rfqDetails.map(detail => {
const response = vendorResponses.find(
r => r.vendor.id === detail.vendorId && r.isLatest
);
return { ...detail, response, rfqCode };
});
};
// 추가 조건 포맷팅
const formatAdditionalConditions = (data: any) => {
const conditions = [];
if (data.firstYn) conditions.push("초도품");
if (data.materialPriceRelatedYn) conditions.push("연동제");
if (data.sparepartYn) conditions.push("스페어");
return conditions.length > 0 ? conditions.join(", ") : "-";
};
export function RfqVendorTable({
rfqId,
rfqCode,
rfqDetails,
vendorResponses,
rfqInfo,
attachments,
}: RfqVendorTableProps) {
const [isRefreshing, setIsRefreshing] = React.useState(false);
const [selectedRows, setSelectedRows] = React.useState<any[]>([]);
const [isAddDialogOpen, setIsAddDialogOpen] = React.useState(false);
const [isBatchUpdateOpen, setIsBatchUpdateOpen] = React.useState(false);
const [selectedVendor, setSelectedVendor] = React.useState<any | null>(null);
const [isSendDialogOpen, setIsSendDialogOpen] = React.useState(false);
const [isLoadingSendData, setIsLoadingSendData] = React.useState(false);
const [deleteVendorData, setDeleteVendorData] = React.useState<{
detailId: number;
vendorId: number;
vendorName: string;
vendorCode?: string | null;
hasResponse?: boolean;
responseStatus?: string | null;
} | null>(null);
const [sendDialogData, setSendDialogData] = React.useState<{
rfqInfo: RfqSendData['rfqInfo'] | null;
attachments: RfqSendData['attachments'];
selectedVendors: VendorEmailInfo[];
}>({
rfqInfo: null,
attachments: [],
selectedVendors: [],
});
const [editContractVendor, setEditContractVendor] = React.useState<any | null>(null);
const [isUpdatingShortList, setIsUpdatingShortList] = React.useState(false);
const [isAvlDialogOpen, setIsAvlDialogOpen] = React.useState(false);
// AVL 연동 핸들러
const handleAvlIntegration = React.useCallback(() => {
setIsAvlDialogOpen(true);
}, []);
const router = useRouter()
// 데이터 병합
const mergedData = React.useMemo(
() => mergeVendorData(rfqDetails, vendorResponses, rfqCode),
[rfqDetails, vendorResponses, rfqCode]
);
console.log(mergedData, "mergedData")
console.log(rfqId, "rfqId")
// Short List 확정 핸들러
const handleShortListConfirm = React.useCallback(async () => {
try {
setIsUpdatingShortList(true);
// response가 있는 벤더들만 필터링
const vendorsWithResponse = selectedRows.filter(vendor =>
vendor.response && vendor.response.vendor&& vendor.response.isDocumentConfirmed
);
if (vendorsWithResponse.length === 0) {
toast.warning("응답이 있는 벤더를 선택해주세요.");
return;
}
const vendorIds = vendorsWithResponse
.map(vendor => vendor.vendorId)
.filter(id => id != null);
const result = await updateShortList(rfqId, vendorIds, true);
if (result.success) {
toast.success(`${result.updatedCount}개 벤더를 Short List로 확정했습니다.`);
setSelectedRows([]);
router.refresh();
}
} catch (error) {
console.error("Short List 확정 실패:", error);
toast.error("Short List 확정에 실패했습니다.");
} finally {
setIsUpdatingShortList(false);
}
}, [selectedRows, rfqId, router]);
// 견적 비교 핸들러
const handleQuotationCompare = React.useCallback(() => {
const vendorsWithQuotation = selectedRows.filter(row =>
row.response?.submission?.submittedAt
);
if (vendorsWithQuotation.length < 2) {
toast.warning("비교를 위해 최소 2개 이상의 견적서가 필요합니다.");
return;
}
// 견적 비교 페이지로 이동 또는 모달 열기
const vendorIds = vendorsWithQuotation
.map(v => v.vendorId)
.filter(id => id != null)
.join(',');
router.push(`/evcp/rfq-last/${rfqId}/compare?vendors=${vendorIds}`);
}, [selectedRows, rfqId, router]);
// 일괄 발송 핸들러
const handleBulkSend = React.useCallback(async () => {
if (selectedRows.length === 0) {
toast.warning("발송할 벤더를 선택해주세요.");
return;
}
try {
setIsLoadingSendData(true);
// 선택된 벤더 ID들 추출
const selectedVendorIds = rfqCode?.startsWith("I") ? selectedRows
// .filter(v => v.shortList)
.map(row => row.vendorId)
.filter(id => id != null) :
selectedRows
.map(row => row.vendorId)
.filter(id => id != null)
if (selectedVendorIds.length === 0) {
toast.error("유효한 벤더가 선택되지 않았습니다.");
return;
}
// 병렬로 데이터 가져오기 (에러 처리 포함)
const [rfqSendData, vendorEmailInfos] = await Promise.all([
getRfqSendData(rfqId),
getSelectedVendorsWithEmails(rfqId, selectedVendorIds)
]);
// 데이터 검증
if (!rfqSendData?.rfqInfo) {
toast.error("RFQ 정보를 불러올 수 없습니다.");
return;
}
if (!vendorEmailInfos || vendorEmailInfos.length === 0) {
toast.error("선택된 벤더의 이메일 정보를 찾을 수 없습니다.");
return;
}
// 다이얼로그 데이터 설정
setSendDialogData({
rfqInfo: rfqSendData.rfqInfo,
attachments: rfqSendData.attachments || [],
selectedVendors: vendorEmailInfos.map(v => ({
vendorId: v.vendorId,
vendorName: v.vendorName,
vendorCode: v.vendorCode,
vendorCountry: v.vendorCountry,
vendorEmail: v.vendorEmail,
representativeEmail: v.representativeEmail,
contacts: v.contacts || [],
contactsByPosition: v.contactsByPosition || {},
primaryEmail: v.primaryEmail,
currency: v.currency,
ndaYn: v.ndaYn,
generalGtcYn: v.generalGtcYn,
projectGtcYn: v.projectGtcYn,
agreementYn: v.agreementYn,
sendVersion: v.sendVersion
})),
});
// 다이얼로그 열기
setIsSendDialogOpen(true);
} catch (error) {
console.error("RFQ 발송 데이터 로드 실패:", error);
toast.error("데이터를 불러오는데 실패했습니다. 다시 시도해주세요.");
} finally {
setIsLoadingSendData(false);
}
}, [selectedRows, rfqId]);
// RFQ 발송 핸들러
const handleSendRfq = React.useCallback(async (data: {
vendors: Array<{
vendorId: number;
vendorName: string;
vendorCode?: string | null;
vendorCountry?: string | null;
selectedMainEmail: string;
additionalEmails: string[];
customEmails?: Array<{ email: string; name?: string }>;
currency?: string | null;
contractRequirements?: {
ndaYn: boolean;
generalGtcYn: boolean;
projectGtcYn: boolean;
agreementYn: boolean;
projectCode?: string;
};
isResend: boolean;
sendVersion?: number;
}>;
attachments: number[];
message?: string;
generatedPdfs?: Array<{ // 타입 추가
key: string;
buffer: number[];
fileName: string;
}>;
hasToSendEmail?: boolean;
}) => {
try {
// 서버 액션 호출
const result = await sendRfqToVendors({
rfqId,
rfqCode,
vendors: data.vendors,
attachmentIds: data.attachments,
message: data.message,
generatedPdfs: data.generatedPdfs,
hasToSendEmail: data.hasToSendEmail,
});
// 성공 후 처리
setSelectedRows([]);
setSendDialogData({
rfqInfo: null,
attachments: [],
selectedVendors: [],
});
// 기본계약 생성 결과 표시
let message = "";
if (result.contractResults && result.contractResults.length > 0) {
const totalContracts = result.contractResults.reduce((acc, r) => acc + r.totalCreated, 0);
message = `${data.vendors.length}개 업체에 RFQ를 발송하고 ${totalContracts}개의 기본계약을 생성했습니다.`;
} else {
message = `${data.vendors.length}개 업체에 RFQ를 발송했습니다.`;
}
// 성공 결과를 반환
return {
success: true,
message: message,
totalSent: result.totalSent || data.vendors.length,
totalFailed: result.totalFailed || 0,
totalContracts: result.totalContracts || 0,
totalTbeSessions: result.totalTbeSessions || 0
};
} catch (error) {
console.error("RFQ 발송 실패:", error);
// 실패 결과를 반환
return {
success: false,
message: error instanceof Error ? error.message : "RFQ 발송에 실패했습니다.",
totalSent: 0,
totalFailed: data.vendors.length,
totalContracts: 0,
totalTbeSessions: 0
};
}
}, [rfqId, rfqCode, router]);
// vendor status에 따른 category 분류 함수
const getVendorCategoryFromStatus = React.useCallback((status: string | null): string => {
if (!status) return "미분류";
const categoryMap: Record<string, string> = {
"PENDING_REVIEW": "발굴업체", // 가입 신청 중
"IN_REVIEW": "잠재업체", // 심사 중
"REJECTED": "발굴업체", // 심사 거부됨
"IN_PQ": "잠재업체", // PQ 진행 중
"PQ_SUBMITTED": "잠재업체", // PQ 제출
"PQ_FAILED": "잠재업체", // PQ 실패
"PQ_APPROVED": "잠재업체", // PQ 통과
"APPROVED": "잠재업체", // 승인됨
"READY_TO_SEND": "잠재업체", // 정규등록검토
"ACTIVE": "정규업체", // 활성 상태 (실제 거래 중)
"INACTIVE": "중지업체", // 비활성 상태
"BLACKLISTED": "중지업체", // 거래 금지
};
return categoryMap[status] || "미분류";
}, []);
// vendorCountry를 보기 좋은 형태로 변환
const formatVendorCountry = React.useCallback((country: string | null): string => {
if (!country) return "미지정";
// KR 또는 한국이면 내자, 그 외는 전부 외자
const isLocal = country === "KR" || country === "한국";
return isLocal ? `내자(${country})` : `외자(${country})`;
}, []);
// 액션 처리
const handleAction = React.useCallback(async (action: string, vendor: any) => {
switch (action) {
case "view":
setSelectedVendor(vendor);
break;
case "send":
// 개별 RFQ 발송
try {
setIsLoadingSendData(true);
const [rfqSendData, vendorEmailInfos] = await Promise.all([
getRfqSendData(rfqId),
getSelectedVendorsWithEmails(rfqId, [vendor.vendorId])
]);
if (!rfqSendData?.rfqInfo || !vendorEmailInfos || vendorEmailInfos.length === 0) {
toast.error("벤더 정보를 불러올 수 없습니다.");
return;
}
setSendDialogData({
rfqInfo: rfqSendData.rfqInfo,
attachments: rfqSendData.attachments || [],
selectedVendors: vendorEmailInfos.map(v => ({
vendorId: v.vendorId,
vendorName: v.vendorName,
vendorCode: v.vendorCode,
vendorCountry: v.vendorCountry,
vendorEmail: v.vendorEmail,
representativeEmail: v.representativeEmail,
contacts: v.contacts || [],
contactsByPosition: v.contactsByPosition || {},
primaryEmail: v.primaryEmail,
currency: v.currency,
ndaYn: v.ndaYn,
generalGtcYn: v.generalGtcYn,
projectGtcYn: v.projectGtcYn,
agreementYn: v.agreementYn,
sendVersion: v.sendVersion,
})),
});
setIsSendDialogOpen(true);
} catch (error) {
console.error("개별 발송 데이터 로드 실패:", error);
toast.error("데이터를 불러오는데 실패했습니다.");
} finally {
setIsLoadingSendData(false);
}
break;
case "edit":
toast.info("수정 기능은 준비중입니다.");
break;
case "edit-contract":
// 기본계약 수정
setEditContractVendor(vendor);
break;
case "delete":
// quotationStatus 체크
const hasQuotation = !!vendor.quotationStatus;
if (hasQuotation) {
// 견적서가 있으면 즉시 에러 토스트 표시
toast.error("이미 발송된 벤더는 삭제할 수 없습니다.");
return;
}
// 삭제 다이얼로그 열기
setDeleteVendorData({
detailId: vendor.detailId,
vendorId: vendor.vendorId,
vendorName: vendor.vendorName,
vendorCode: vendor.vendorCode,
hasQuotation: hasQuotation,
});
break;
case "response-detail":
toast.info(`${vendor.vendorName}의 회신 상세를 확인합니다.`);
break;
}
}, [rfqId]);
// 컬럼 정의
const columns: ColumnDef<any>[] = React.useMemo(() => [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
onCheckedChange={(v) => table.toggleAllPageRowsSelected(!!v)}
aria-label="select all"
className="translate-y-0.5"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(v) => row.toggleSelected(!!v)}
aria-label="select row"
className="translate-y-0.5"
/>
),
size: 40,
enableSorting: false,
enableHiding: false,
},
{
accessorKey: "rfqCode",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="ITB/RFQ/견적 No." />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
return (
<span className="font-mono text-xs">{row.original.rfqCode || "-"}</span>
);
},
size: 120,
},
{
accessorKey: "vendorName",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="협력업체정보" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const vendor = row.original;
return (
<div className="flex items-center gap-2">
<Building2 className="h-4 w-4 text-muted-foreground" />
<div className="flex flex-col">
<span className="text-sm font-medium">{vendor.vendorName || "-"}</span>
<span className="text-xs text-muted-foreground">{vendor.vendorCode}</span>
</div>
</div>
);
},
size: 180,
},
{
accessorKey: "vendorCategory",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="업체분류" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const status = row.original.status;
const category = getVendorCategoryFromStatus(status);
return (
<Badge variant="outline" className="text-xs">
{category}
</Badge>
);
},
size: 100,
},
{
accessorKey: "vendorCountry",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="내외자 (위치)" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const country = row.original.vendorCountry;
const formattedCountry = formatVendorCountry(country);
const isLocal = country === "KR" || country === "한국";
return (
<Badge variant={isLocal ? "default" : "secondary"}>
{formattedCountry}
</Badge>
);
},
size: 100,
},
{
accessorKey: "vendorGrade",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="AVL 정보 (등급)" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const grade = row.original.vendorGrade;
if (!grade) return <span className="text-muted-foreground">-</span>;
const gradeColor = {
"A": "text-green-600",
"B": "text-blue-600",
"C": "text-yellow-600",
"D": "text-red-600",
}[grade] || "text-gray-600";
return <span className={cn("font-semibold", gradeColor)}>{grade}</span>;
},
size: 100,
},
{
accessorKey: "tbeStatus",
header: ({ column }) => (
<ClientDataTableColumnHeaderSimple column={column} title="TBE 상태" />
),
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const status = row.original.tbeStatus;
if (!status || status === "준비중") {
return (
<Badge variant="outline" className="text-gray-500">
<Clock className="h-3 w-3 mr-1" />
대기
</Badge>
);
}
const statusConfig = {
"진행중": { variant: "default", icon: <Clock className="h-3 w-3 mr-1" />, color: "text-blue-600" },
"검토중": { variant: "secondary", icon: <Eye className="h-3 w-3 mr-1" />, color: "text-orange-600" },
"보류": { variant: "outline", icon: <AlertCircle className="h-3 w-3 mr-1" />, color: "text-yellow-600" },
"완료": { variant: "success", icon: <CheckCircle className="h-3 w-3 mr-1" />, color: "text-green-600" },
"취소": { variant: "destructive", icon: <XCircle className="h-3 w-3 mr-1" />, color: "text-red-600" },
}[status] || { variant: "outline", icon: null, color: "text-gray-600" };
return (
<Badge variant={statusConfig.variant as any} className={statusConfig.color}>
{statusConfig.icon}
{status}
</Badge>
);
},
size: 100,
},
{
accessorKey: "tbeEvaluationResult",
header: ({ column }) => (
<ClientDataTableColumnHeaderSimple column={column} title="TBE 평가" />
),
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const result = row.original.tbeEvaluationResult;
const status = row.original.tbeStatus;
// TBE가 완료되지 않았으면 표시하지 않음
if (status !== "완료" || !result) {
return <span className="text-xs text-muted-foreground">-</span>;
}
const resultConfig = {
"Acceptable": {
variant: "success",
icon: <CheckCircle className="h-3 w-3" />,
text: "적합",
color: "bg-green-50 text-green-700 border-green-200"
},
"Acceptable with Comment": {
variant: "warning",
icon: <AlertCircle className="h-3 w-3" />,
text: "조건부 적합",
color: "bg-yellow-50 text-yellow-700 border-yellow-200"
},
"Not Acceptable": {
variant: "destructive",
icon: <XCircle className="h-3 w-3" />,
text: "부적합",
color: "bg-red-50 text-red-700 border-red-200"
},
}[result];
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<Badge className={cn("text-xs", resultConfig?.color)}>
{resultConfig?.icon}
<span className="ml-1">{resultConfig?.text}</span>
</Badge>
</TooltipTrigger>
<TooltipContent>
<div className="text-xs">
<p className="font-semibold">{result}</p>
{row.original.conditionalRequirements && (
<p className="mt-1 text-muted-foreground">
조건: {row.original.conditionalRequirements}
</p>
)}
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
},
size: 120,
},
{
accessorKey: "contractRequirements",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="기본계약 요청" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const vendor = row.original;
const isKorean = vendor.vendorCountry === "KR" || vendor.vendorCountry === "한국";
// 기본계약 상태 확인
const requirements = [];
// 필수 계약들
if (vendor.agreementYn) {
requirements.push({
name: "기술자료",
icon: <FileText className="h-3 w-3" />,
color: "text-blue-500"
});
}
if (vendor.ndaYn) {
requirements.push({
name: "NDA",
icon: <Shield className="h-3 w-3" />,
color: "text-green-500"
});
}
// GTC (국외 업체만)
if (!isKorean) {
if (vendor.generalGtcYn || vendor.gtcType === "general") {
requirements.push({
name: "General GTC",
icon: <Globe className="h-3 w-3" />,
color: "text-purple-500"
});
} else if (vendor.projectGtcYn || vendor.gtcType === "project") {
requirements.push({
name: "Project GTC",
icon: <Globe className="h-3 w-3" />,
color: "text-indigo-500"
});
}
}
if (requirements.length === 0) {
return <span className="text-xs text-muted-foreground">없음</span>;
}
return (
<div className="flex flex-wrap gap-1">
{requirements.map((req, idx) => (
<TooltipProvider key={idx}>
<Tooltip>
<TooltipTrigger asChild>
<Badge variant="outline" className="text-xs px-1.5 py-0">
<span className={cn("mr-1", req.color)}>
{req.icon}
</span>
{req.name}
</Badge>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">
{req.name === "기술자료" && "기술자료 제공 동의서"}
{req.name === "NDA" && "비밀유지 계약서"}
{req.name === "General GTC" && "일반 거래 약관"}
{req.name === "Project GTC" && "프로젝트별 거래 약관"}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
))}
</div>
);
},
size: 150,
},
{
accessorKey: "sendVersion",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="발송 회차" />,
filterFn: createFilterFn("number"),
cell: ({ row }) => {
const version = row.original.sendVersion;
return <span>{version}</span>;
},
size: 80,
},
{
accessorKey: "emailStatus",
header: "이메일 상태",
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const response = row.original;
const emailSentAt = response?.emailSentAt;
const emailResentCount = response?.emailResentCount || 0;
const emailStatus = response?.emailStatus;
const status = response?.status;
if (!emailSentAt) {
return (
<Badge variant="outline" className="bg-gray-50">
<Mail className="h-3 w-3 mr-1" />
미발송
</Badge>
);
}
// 이메일 상태 표시 (failed인 경우 특별 처리)
const getEmailStatusBadge = () => {
if (emailStatus === "failed") {
return (
<Badge variant="destructive">
<XCircle className="h-3 w-3 mr-1" />
발송 실패
</Badge>
);
}
return (
<Badge variant={status === "제출완료" ? "success" : "default"}>
{getStatusIcon(status || "")}
{status}
</Badge>
);
};
// emailSentTo JSON 파싱
let recipients = { to: [], cc: [], sentBy: "" };
try {
if (response?.emailSentTo) {
recipients = JSON.parse(response.emailSentTo);
}
} catch (e) {
console.error("Failed to parse emailSentTo", e);
}
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<div className="flex flex-col gap-1">
{getEmailStatusBadge()}
{emailResentCount > 1 && (
<Badge variant="secondary" className="text-xs">
재발송 {emailResentCount - 1}회
</Badge>
)}
</div>
</TooltipTrigger>
<TooltipContent>
<div className="space-y-1">
<p>최초 발송: {format(new Date(emailSentAt), "yyyy-MM-dd HH:mm")}</p>
{response?.email?.lastEmailSentAt && (
<p>최근 발송: {format(new Date(response.email.lastEmailSentAt), "yyyy-MM-dd HH:mm")}</p>
)}
{recipients.to.length > 0 && (
<p>수신자: {recipients.to.join(", ")}</p>
)}
{recipients.cc.length > 0 && (
<p>참조: {recipients.cc.join(", ")}</p>
)}
{recipients.sentBy && (
<p>발신자: {recipients.sentBy}</p>
)}
{emailStatus === "failed" && (
<p className="text-red-500 font-semibold">⚠️ 이메일 발송 실패</p>
)}
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
},
size: 120,
},
// {
// accessorKey: "basicContract",
// header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="기본계약" />,
// cell: ({ row }) => row.original.basicContract || "-",
// size: 100,
// },
{
accessorKey: "currency",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="요청 통화" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const currency = row.original.currency;
return currency ? (
<Badge variant="outline">{currency}</Badge>
) : (
<span className="text-muted-foreground">-</span>
);
},
size: 80,
},
{
accessorKey: "paymentTermsCode",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="지급조건" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const code = row.original.paymentTermsCode;
const desc = row.original.paymentTermsDescription;
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span className="text-sm">{code || "-"}</span>
</TooltipTrigger>
{desc && (
<TooltipContent>
<p>{desc}</p>
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
);
},
size: 100,
},
{
accessorKey: "taxCode",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="Tax" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => row.original.taxCode || "-",
size: 60,
},
{
accessorKey: "deliveryDate",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="계약납기일/기간" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const deliveryDate = row.original.deliveryDate;
const contractDuration = row.original.contractDuration;
return (
<div className="flex flex-col gap-0.5">
{deliveryDate && !rfqCode?.startsWith("F") && (
<span className="text-xs">
{format(new Date(deliveryDate), "yyyy-MM-dd")}
</span>
)}
{contractDuration && rfqCode?.startsWith("F") && (
<span className="text-xs text-muted-foreground">{contractDuration}</span>
)}
{!deliveryDate && !contractDuration && (
<span className="text-muted-foreground">-</span>
)}
</div>
);
},
size: 120,
},
{
accessorKey: "incotermsCode",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="Incoterms" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const code = row.original.incotermsCode;
const detail = row.original.incotermsDetail;
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="flex items-center gap-1">
<Globe className="h-3 w-3 text-muted-foreground" />
<span className="text-sm">{code || "-"}</span>
</div>
</TooltipTrigger>
{detail && (
<TooltipContent>
<p>{detail}</p>
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
);
},
size: 100,
},
{
accessorKey: "placeOfShipping",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="선적지" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const place = row.original.placeOfShipping;
return place ? (
<div className="flex items-center gap-1">
<MapPin className="h-3 w-3 text-muted-foreground" />
<span className="text-xs">{place}</span>
</div>
) : (
<span className="text-muted-foreground">-</span>
);
},
size: 100,
},
{
accessorKey: "placeOfDestination",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="도착지" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const place = row.original.placeOfDestination;
return place ? (
<div className="flex items-center gap-1">
<Package className="h-3 w-3 text-muted-foreground" />
<span className="text-xs">{place}</span>
</div>
) : (
<span className="text-muted-foreground">-</span>
);
},
size: 100,
},
{
id: "additionalConditions",
header: "추가조건",
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const conditions = formatAdditionalConditions(row.original);
if (conditions === "-") {
return <span className="text-muted-foreground">-</span>;
}
const items = conditions.split(", ");
return (
<div className="flex flex-wrap gap-1">
{items.map((item, idx) => (
<Badge key={idx} variant="outline" className="text-xs">
{item}
</Badge>
))}
</div>
);
},
size: 120,
},
{
accessorKey: "response.submission.submittedAt",
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="참여여부 (회신일)" />,
filterFn: createFilterFn("text"),
cell: ({ row }) => {
const participationRepliedAt = row.original.response?.attend?.participationRepliedAt;
if (!participationRepliedAt) {
return <Badge variant="outline">미응답</Badge>;
}
const participationStatus = row.original.response?.attend?.participationStatus;
return (
<div className="flex flex-col gap-0.5">
<Badge variant="default" className="text-xs">{participationStatus}</Badge>
<span className="text-xs text-muted-foreground">
{format(new Date(participationRepliedAt), "yyyy-MM-dd")}
</span>
</div>
);
},
size: 100,
},
{
id: "responseDetail",
header: "회신상세",
cell: ({ row }) => {
const hasResponse = !!row.original.response?.submission?.submittedAt;
if (!hasResponse) {
return <span className="text-muted-foreground text-xs">-</span>;
}
return (
<Button
variant="ghost"
size="sm"
onClick={() => handleAction("view", row.original)}
className="h-7 px-2"
>
<Eye className="h-3 w-3 mr-1" />
상세
</Button>
);
},
size: 80,
},
...(!rfqCode?.startsWith("F") ? [{
accessorKey: "shortList",
filterFn: createFilterFn("boolean"), // boolean으로 변경
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="Short List" />,
cell: ({ row }) => (
row.original.shortList ? (
<Badge variant="default">선정</Badge>
) : (
<Badge variant="outline">대기</Badge>
)
),
size: 80,
}] : []),
{
accessorKey: "updatedByUserName",
filterFn: createFilterFn("text"), // 추가
header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="최신수정자" />,
cell: ({ row }) => {
const name = row.original.updatedByUserName;
return name ? (
<span className="text-xs">{name}</span>
) : (
<span className="text-muted-foreground">-</span>
);
},
size: 100,
},
{
id: "actions",
header: "작업",
cell: ({ row }) => {
const vendor = row.original;
const hasResponse = !!vendor.response;
const emailSentAt = vendor.response?.email?.emailSentAt;
const emailResentCount = vendor.response?.email?.emailResentCount || 0;
const hasQuotation = !!vendor.quotationStatus;
const isKorean = vendor.vendorCountry === "KR" || vendor.vendorCountry === "한국";
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">메뉴 열기</span>
<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.625 7.5C3.625 8.12132 3.12132 8.625 2.5 8.625C1.87868 8.625 1.375 8.12132 1.375 7.5C1.375 6.87868 1.87868 6.375 2.5 6.375C3.12132 6.375 3.625 6.87868 3.625 7.5ZM8.625 7.5C8.625 8.12132 8.12132 8.625 7.5 8.625C6.87868 8.625 6.375 8.12132 6.375 7.5C6.375 6.87868 6.87868 6.375 7.5 6.375C8.12132 6.375 8.625 6.87868 8.625 7.5ZM12.5 8.625C13.1213 8.625 13.625 8.12132 13.625 7.5C13.625 6.87868 13.1213 6.375 12.5 6.375C11.8787 6.375 11.375 6.87868 11.375 7.5C11.375 8.12132 11.8787 8.625 12.5 8.625Z" fill="currentColor" fillRule="evenodd" clipRule="evenodd"></path>
</svg>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleAction("view", vendor)}>
<Eye className="mr-2 h-4 w-4" />
상세보기
</DropdownMenuItem>
{/* 기본계약 수정 메뉴 추가 */}
<DropdownMenuItem onClick={() => handleAction("edit-contract", vendor)}>
<FileText className="mr-2 h-4 w-4" />
기본계약 수정
</DropdownMenuItem>
{emailSentAt && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => handleAction("resend", vendor)}
disabled={isLoadingSendData}
>
<RefreshCw className="mr-2 h-4 w-4" />
이메일 재발송
{emailResentCount > 0 && (
<Badge variant="outline" className="ml-2 text-xs">
{emailResentCount}
</Badge>
)}
</DropdownMenuItem>
</>
)}
{!emailSentAt && (
<DropdownMenuItem
onClick={() => handleAction("send", vendor)}
disabled={isLoadingSendData}
>
<Send className="mr-2 h-4 w-4" />
RFQ 발송
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => handleAction("delete", vendor)}
className={cn(
"text-red-600",
hasQuotation && "opacity-50 cursor-not-allowed"
)}
disabled={hasQuotation}
>
<Trash2 className="mr-2 h-4 w-4" />
삭제
{hasQuotation && (
<span className="ml-2 text-xs">(불가)</span>
)}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
},
size: 60,
}
], [handleAction, rfqCode, isLoadingSendData]);
// advancedFilterFields 정의 - columns와 매칭되도록 정리
const advancedFilterFields: DataTableAdvancedFilterField<any>[] = [
{
id: "rfqCode",
label: "ITB/RFQ/견적 No.",
type: "text"
},
{
id: "vendorName",
label: "협력업체명",
type: "text"
},
{
id: "vendorCode",
label: "협력업체코드",
type: "text"
},
{
id: "vendorCategory",
label: "업체분류",
type: "select",
options: [
{ label: "제조업체", value: "제조업체" },
{ label: "무역업체", value: "무역업체" },
{ label: "대리점", value: "대리점" },
// 실제 카테고리에 맞게 추가
]
},
{
id: "vendorCountry",
label: "내외자(위치)",
type: "select",
options: [
{ label: "한국(KR)", value: "KR" },
{ label: "한국", value: "한국" },
{ label: "중국(CN)", value: "CN" },
{ label: "일본(JP)", value: "JP" },
{ label: "미국(US)", value: "US" },
{ label: "독일(DE)", value: "DE" },
// 필요한 국가 추가
]
},
{
id: "vendorGrade",
label: "AVL 등급",
type: "select",
options: [
{ label: "A", value: "A" },
{ label: "B", value: "B" },
{ label: "C", value: "C" },
{ label: "D", value: "D" },
]
},
{
id: "tbeStatus",
label: "TBE 상태",
type: "select",
options: [
{ label: "대기", value: "준비중" },
{ label: "진행중", value: "진행중" },
{ label: "검토중", value: "검토중" },
{ label: "보류", value: "보류" },
{ label: "완료", value: "완료" },
{ label: "취소", value: "취소" },
]
},
{
id: "tbeEvaluationResult",
label: "TBE 평가결과",
type: "select",
options: [
{ label: "적합", value: "Acceptable" },
{ label: "조건부 적합", value: "Acceptable with Comment" },
{ label: "부적합", value: "Not Acceptable" },
]
},
{
id: "sendVersion",
label: "발송 회차",
type: "number"
},
{
id: "emailStatus",
label: "이메일 상태",
type: "select",
options: [
{ label: "미발송", value: "미발송" },
{ label: "발송됨", value: "sent" },
{ label: "발송 실패", value: "failed" },
]
},
{
id: "currency",
label: "요청 통화",
type: "select",
options: [
{ label: "KRW", value: "KRW" },
{ label: "USD", value: "USD" },
{ label: "EUR", value: "EUR" },
{ label: "JPY", value: "JPY" },
{ label: "CNY", value: "CNY" },
]
},
{
id: "paymentTermsCode",
label: "지급조건",
type: "text"
},
{
id: "taxCode",
label: "Tax",
type: "text",
},
{
id: "deliveryDate",
label: "계약납기일",
type: "date"
},
{
id: "contractDuration",
label: "계약기간",
type: "text"
},
{
id: "incotermsCode",
label: "Incoterms",
type: "text",
},
{
id: "placeOfShipping",
label: "선적지",
type: "text"
},
{
id: "placeOfDestination",
label: "도착지",
type: "text"
},
{
id: "firstYn",
label: "초도품",
type: "boolean"
},
{
id: "materialPriceRelatedYn",
label: "연동제",
type: "boolean"
},
{
id: "sparepartYn",
label: "스페어파트",
type: "boolean"
},
...(!rfqCode?.startsWith("I") ? [{
id: "shortList",
label: "Short List",
type: "select",
options: [
{ label: "선정", value: "true" },
{ label: "대기", value: "false" },
]
}] : []),
{
id: "updatedByUserName",
label: "최신수정자",
type: "text"
}
];
// 선택된 벤더 정보 (BatchUpdate용)
const selectedVendorsForBatch = React.useMemo(() => {
return selectedRows.map(row => ({
id: row.vendorId,
vendorName: row.vendorName,
vendorCode: row.vendorCode,
}));
}, [selectedRows]);
// 추가 액션 버튼들
const additionalActions = React.useMemo(() => {
// 참여 의사가 있는 선택된 벤더 수 계산
const participatingCount = selectedRows.length;
const shortListCount = selectedRows.filter(v => v.shortList).length;
const vendorsWithResponseCount = selectedRows.filter(v => v.response && v.response.vendor && v.response.isDocumentConfirmed).length;
// 견적서가 있는 선택된 벤더 수 계산
const quotationCount = selectedRows.filter(row =>
row.response?.submission?.submittedAt
).length;
return (
<div className="flex items-center gap-2">
{(rfqCode?.startsWith("I") || rfqCode?.startsWith("R")) && (
<Button
variant="outline"
size="sm"
onClick={handleAvlIntegration}
className="border-purple-500 text-purple-600 hover:bg-purple-50"
>
<Link className="h-4 w-4 mr-2" />
AVL 연동
</Button>
)}
<Button
variant="outline"
size="sm"
onClick={() => setIsAddDialogOpen(true)}
disabled={isLoadingSendData}
>
<Plus className="h-4 w-4 mr-2" />
벤더 추가
</Button>
{selectedRows.length > 0 && (
<>
{/* 정보 일괄 입력 버튼 */}
<Button
variant="outline"
size="sm"
onClick={() => setIsBatchUpdateOpen(true)}
disabled={isLoadingSendData}
>
<Settings2 className="h-4 w-4 mr-2" />
협력업체 조건 설정 ({selectedRows.length})
</Button>
{/* RFQ 발송 버튼 */}
<Button
variant="outline"
size="sm"
onClick={handleBulkSend}
disabled={isLoadingSendData || selectedRows.length === 0}
>
{isLoadingSendData ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
데이터 준비중...
</>
) : (
<>
<Send className="h-4 w-4 mr-2" />
RFQ 발송 ({shortListCount})
</>
)}
</Button>
{/* Short List 확정 버튼 */}
{!rfqCode?.startsWith("F") &&
<Button
variant="outline"
size="sm"
onClick={handleShortListConfirm}
disabled={isUpdatingShortList || vendorsWithResponseCount===0}
// className={ "border-green-500 text-green-600 hover:bg-green-50" }
>
{isUpdatingShortList ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
처리중...
</>
) : (
<>
<CheckSquare className="h-4 w-4 mr-2" />
Short List 확정
{vendorsWithResponseCount > 0 && ` (${vendorsWithResponseCount})`}
</>
)}
</Button>
}
{/* 견적 비교 버튼 */}
<Button
variant="outline"
size="sm"
onClick={handleQuotationCompare}
disabled={quotationCount < 1}
className={quotationCount >= 2 ? "border-blue-500 text-blue-600 hover:bg-blue-50" : ""}
>
<GitCompare className="h-4 w-4 mr-2" />
견적 비교
{quotationCount > 0 && ` (${quotationCount})`}
</Button>
</>
)}
<Button
variant="outline"
size="sm"
onClick={() => {
setIsRefreshing(true);
setTimeout(() => {
setIsRefreshing(false);
toast.success("데이터를 새로고침했습니다.");
}, 1000);
}}
disabled={isRefreshing || isLoadingSendData}
>
<RefreshCw className={cn("h-4 w-4 mr-2", isRefreshing && "animate-spin")} />
새로고침
</Button>
</div>
);
}, [selectedRows, isRefreshing, isLoadingSendData, handleBulkSend, handleShortListConfirm, handleQuotationCompare, isUpdatingShortList]);
return (
<>
<ClientDataTable
columns={columns}
data={mergedData}
advancedFilterFields={advancedFilterFields}
autoSizeColumns={false}
compact={true}
maxHeight="34rem"
onSelectedRowsChange={setSelectedRows}
>
{additionalActions}
</ClientDataTable>
{/* 벤더 추가 다이얼로그 */}
<AddVendorDialog
open={isAddDialogOpen}
onOpenChange={setIsAddDialogOpen}
rfqId={rfqId}
onSuccess={() => {
toast.success("벤더가 추가되었습니다.");
setIsAddDialogOpen(false);
}}
/>
{/* 조건 일괄 설정 다이얼로그 */}
<BatchUpdateConditionsDialog
open={isBatchUpdateOpen}
onOpenChange={setIsBatchUpdateOpen}
rfqId={rfqId}
rfqCode={rfqCode}
selectedVendors={selectedVendorsForBatch}
onSuccess={() => {
toast.success("조건이 업데이트되었습니다.");
setIsBatchUpdateOpen(false);
setSelectedRows([]);
}}
/>
{/* RFQ 발송 다이얼로그 */}
<SendRfqDialog
open={isSendDialogOpen}
onOpenChange={setIsSendDialogOpen}
selectedVendors={sendDialogData.selectedVendors}
rfqInfo={sendDialogData.rfqInfo}
attachments={sendDialogData.attachments || []}
onSend={handleSendRfq}
/>
{/* 벤더 상세 다이얼로그 */}
{selectedVendor && (
<VendorResponseDetailDialog
open={!!selectedVendor}
onOpenChange={(open) => !open && setSelectedVendor(null)}
data={selectedVendor}
rfqId={rfqId}
/>
)}
{/* 삭제 다이얼로그 추가 */}
{deleteVendorData && (
<DeleteVendorDialog
open={!!deleteVendorData}
onOpenChange={(open) => !open && setDeleteVendorData(null)}
rfqId={rfqId}
vendorData={deleteVendorData}
onSuccess={() => {
setDeleteVendorData(null);
router.refresh();
// 데이터 새로고침
}}
/>
)}
{/* 기본계약 수정 다이얼로그 - 새로 추가 */}
{editContractVendor && (
<EditContractDialog
open={!!editContractVendor}
onOpenChange={(open) => !open && setEditContractVendor(null)}
rfqId={rfqId}
vendor={editContractVendor}
onSuccess={() => {
setEditContractVendor(null);
router.refresh();
}}
/>
)}
{/* AVL 벤더 연동 다이얼로그 */}
<AvlVendorDialog
open={isAvlDialogOpen}
onOpenChange={setIsAvlDialogOpen}
rfqId={rfqId}
rfqCode={rfqCode}
onSuccess={() => {
setIsAvlDialogOpen(false);
router.refresh();
}}
/>
</>
);
}
|