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
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
|
// src/lib/tasks/service.ts
"use server"; // Next.js 서버 액션에서 직접 import하려면 (선택)
import { revalidatePath, revalidateTag, unstable_noStore } from "next/cache";
import db from "@/db/db";
import { filterColumns } from "@/lib/filter-columns";
import { unstable_cache } from "@/lib/unstable-cache";
import { getErrorMessage } from "@/lib/handle-error";
import { GetRfqsSchema, CreateRfqSchema, UpdateRfqSchema, CreateRfqItemSchema, GetMatchedVendorsSchema, GetRfqsForVendorsSchema, UpdateRfqVendorSchema, GetTBESchema, RfqType, GetCBESchema } from "./validations";
import { asc, desc, ilike, inArray, and, gte, lte, not, or, sql, eq, isNull, ne, isNotNull, count } from "drizzle-orm";
import path from "path";
import fs from "fs/promises";
import { randomUUID } from "crypto";
import { writeFile, mkdir } from 'fs/promises'
import { join } from 'path'
import { vendorResponses, vendorResponsesView, Rfq, rfqs, rfqAttachments, rfqItems, RfqWithItems, rfqComments, rfqEvaluations, vendorRfqView, vendorTbeView, rfqsView, vendorResponseAttachments, vendorTechnicalResponses, vendorCbeView, cbeEvaluations, vendorCommercialResponses } from "@/db/schema/rfq";
import { countRfqs, deleteRfqById, deleteRfqsByIds, getRfqById, groupByStatus, insertRfq, insertRfqItem, selectRfqs, updateRfq, updateRfqs, updateRfqVendor } from "./repository";
import logger from '@/lib/logger';
import { vendorPossibleItems, vendors } from "@/db/schema/vendors";
import { sendEmail } from "../mail/sendEmail";
import { projects } from "@/db/schema/projects";
import { items } from "@/db/schema/items";
import * as z from "zod"
import { users } from "@/db/schema/users";
interface InviteVendorsInput {
rfqId: number
vendorIds: number[]
rfqType: RfqType
}
/* -----------------------------------------------------
1) 조회 관련
----------------------------------------------------- */
/**
* 복잡한 조건으로 Rfq 목록을 조회 (+ pagination) 하고,
* 총 개수에 따라 pageCount를 계산해서 리턴.
* Next.js의 unstable_cache를 사용해 일정 시간 캐시.
*/
export async function getRfqs(input: GetRfqsSchema) {
return unstable_cache(
async () => {
try {
const offset = (input.page - 1) * input.perPage;
// const advancedTable = input.flags.includes("advancedTable");
const advancedTable = true;
// advancedTable 모드면 filterColumns()로 where 절 구성
const advancedWhere = filterColumns({
table: rfqsView,
filters: input.filters,
joinOperator: input.joinOperator,
});
let globalWhere
if (input.search) {
const s = `%${input.search}%`
globalWhere = or(ilike(rfqsView.rfqCode, s), ilike(rfqsView.projectCode, s)
, ilike(rfqsView.projectName, s), ilike(rfqsView.dueDate, s), ilike(rfqsView.status, s)
)
// 필요시 여러 칼럼 OR조건 (status, priority, etc)
}
let rfqTypeWhere;
if (input.rfqType) {
rfqTypeWhere = eq(rfqsView.rfqType, input.rfqType);
}
let whereConditions = [];
if (advancedWhere) whereConditions.push(advancedWhere);
if (globalWhere) whereConditions.push(globalWhere);
if (rfqTypeWhere) whereConditions.push(rfqTypeWhere);
// 조건이 있을 때만 and() 사용
const finalWhere = whereConditions.length > 0
? and(...whereConditions)
: undefined;
const orderBy =
input.sort.length > 0
? input.sort.map((item) =>
item.desc ? desc(rfqsView[item.id]) : asc(rfqsView[item.id])
)
: [asc(rfqsView.createdAt)];
// 트랜잭션 내부에서 Repository 호출
const { data, total } = await db.transaction(async (tx) => {
const data = await selectRfqs(tx, {
where: finalWhere,
orderBy,
offset,
limit: input.perPage,
});
const total = await countRfqs(tx, finalWhere);
return { data, total };
});
const pageCount = Math.ceil(total / input.perPage);
return { data, pageCount };
} catch (err) {
console.error("getRfqs 에러:", err); // 자세한 에러 로깅
// 에러 발생 시 디폴트
return { data: [], pageCount: 0 };
}
},
[JSON.stringify(input)],
{
revalidate: 3600,
tags: [`rfqs-${input.rfqType}`],
}
)();
}
/** Status별 개수 */
export async function getRfqStatusCounts(rfqType: RfqType = RfqType.PURCHASE) {
return unstable_cache(
async () => {
try {
const initial: Record<Rfq["status"], number> = {
DRAFT: 0,
PUBLISHED: 0,
EVALUATION: 0,
AWARDED: 0,
};
const result = await db.transaction(async (tx) => {
// rfqType을 기준으로 필터링 추가
const rows = await groupByStatus(tx, rfqType);
return rows.reduce<Record<Rfq["status"], number>>((acc, { status, count }) => {
acc[status] = count;
return acc;
}, initial);
});
return result;
} catch (err) {
return {} as Record<Rfq["status"], number>;
}
},
[`rfq-status-counts-${rfqType}`], // 캐싱 키에 rfqType 추가
{
revalidate: 3600,
}
)();
}
/* -----------------------------------------------------
2) 생성(Create)
----------------------------------------------------- */
/**
* Rfq 생성 후, (가장 오래된 Rfq 1개) 삭제로
* 전체 Rfq 개수를 고정
*/
export async function createRfq(input: CreateRfqSchema) {
console.log(input.createdBy, "input.createdBy")
unstable_noStore(); // Next.js 서버 액션 캐싱 방지
try {
await db.transaction(async (tx) => {
// 새 Rfq 생성
const [newTask] = await insertRfq(tx, {
rfqCode: input.rfqCode,
projectId: input.projectId || null,
description: input.description || null,
dueDate: input.dueDate,
status: input.status,
rfqType: input.rfqType, // rfqType 추가
createdBy: input.createdBy,
});
return newTask;
});
// 캐시 무효화
revalidateTag(`rfqs-${input.rfqType}`);
revalidateTag(`rfq-status-counts-${input.rfqType}`);
return { data: null, error: null };
} catch (err) {
return { data: null, error: getErrorMessage(err) };
}
}
/* -----------------------------------------------------
3) 업데이트
----------------------------------------------------- */
/** 단건 업데이트 */
export async function modifyRfq(input: UpdateRfqSchema & { id: number }) {
unstable_noStore();
try {
const data = await db.transaction(async (tx) => {
const [res] = await updateRfq(tx, input.id, {
rfqCode: input.rfqCode,
projectId: input.projectId || null,
dueDate: input.dueDate,
rfqType: input.rfqType,
status: input.status as "DRAFT" | "PUBLISHED" | "EVALUATION" | "AWARDED",
createdBy: input.createdBy,
});
return res;
});
revalidateTag("rfqs");
if (data.status === input.status) {
revalidateTag("rfqs-status-counts");
}
return { data: null, error: null };
} catch (err) {
return { data: null, error: getErrorMessage(err) };
}
}
export async function modifyRfqs(input: {
ids: number[];
status?: Rfq["status"];
dueDate?: Date
}) {
unstable_noStore();
try {
const data = await db.transaction(async (tx) => {
const [res] = await updateRfqs(tx, input.ids, {
status: input.status,
dueDate: input.dueDate,
});
return res;
});
revalidateTag("rfqs");
if (data.status === input.status) {
revalidateTag("rfq-status-counts");
}
return { data: null, error: null };
} catch (err) {
return { data: null, error: getErrorMessage(err) };
}
}
/* -----------------------------------------------------
4) 삭제
----------------------------------------------------- */
/** 단건 삭제 */
export async function removeRfq(input: { id: number }) {
unstable_noStore();
try {
await db.transaction(async (tx) => {
// 삭제
await deleteRfqById(tx, input.id);
// 바로 새 Rfq 생성
});
revalidateTag("rfqs");
revalidateTag("rfq-status-counts");
return { data: null, error: null };
} catch (err) {
return { data: null, error: getErrorMessage(err) };
}
}
/** 복수 삭제 */
export async function removeRfqs(input: { ids: number[] }) {
unstable_noStore();
try {
await db.transaction(async (tx) => {
// 삭제
await deleteRfqsByIds(tx, input.ids);
});
revalidateTag("rfqs");
revalidateTag("rfq-status-counts");
return { data: null, error: null };
} catch (err) {
return { data: null, error: getErrorMessage(err) };
}
}
// 삭제를 위한 입력 스키마
const deleteRfqItemSchema = z.object({
id: z.number().int(),
rfqId: z.number().int(),
rfqType: z.nativeEnum(RfqType).default(RfqType.PURCHASE),
});
type DeleteRfqItemSchema = z.infer<typeof deleteRfqItemSchema>;
/**
* RFQ 아이템 삭제 함수
*/
export async function deleteRfqItem(input: DeleteRfqItemSchema) {
unstable_noStore(); // Next.js 서버 액션 캐싱 방지
try {
// 삭제 작업 수행
await db
.delete(rfqItems)
.where(
and(
eq(rfqItems.id, input.id),
eq(rfqItems.rfqId, input.rfqId)
)
);
console.log(`Deleted RFQ item: ${input.id} for RFQ ${input.rfqId}`);
// 캐시 무효화
revalidateTag("rfq-items");
revalidateTag(`rfqs-${input.rfqType}`);
revalidateTag(`rfq-${input.rfqId}`);
return { data: null, error: null };
} catch (err) {
console.error("Error in deleteRfqItem:", err);
return { data: null, error: getErrorMessage(err) };
}
}
// createRfqItem 함수 수정 (id 파라미터 추가)
export async function createRfqItem(input: CreateRfqItemSchema & { id?: number }) {
unstable_noStore();
try {
// DB 트랜잭션
await db.transaction(async (tx) => {
// id가 전달되었으면 해당 id로 업데이트, 그렇지 않으면 기존 로직대로 진행
if (input.id) {
// 기존 아이템 업데이트
await tx
.update(rfqItems)
.set({
description: input.description ?? null,
quantity: input.quantity ?? 1,
uom: input.uom ?? "",
updatedAt: new Date(),
})
.where(eq(rfqItems.id, input.id));
console.log(`Updated RFQ item with id: ${input.id}`);
} else {
// 기존 로직: 같은 itemCode로 이미 존재하는지 확인 후 업데이트/생성
const existingItems = await tx
.select()
.from(rfqItems)
.where(
and(
eq(rfqItems.rfqId, input.rfqId),
eq(rfqItems.itemCode, input.itemCode)
)
);
if (existingItems.length > 0) {
// 이미 존재하는 경우 업데이트
const existingItem = existingItems[0];
await tx
.update(rfqItems)
.set({
description: input.description ?? null,
quantity: input.quantity ?? 1,
uom: input.uom ?? "",
updatedAt: new Date(),
})
.where(eq(rfqItems.id, existingItem.id));
console.log(`Updated existing RFQ item: ${existingItem.id} for RFQ ${input.rfqId}, Item ${input.itemCode}`);
} else {
// 존재하지 않는 경우 새로 생성
const [newItem] = await insertRfqItem(tx, {
rfqId: input.rfqId,
itemCode: input.itemCode,
description: input.description ?? null,
quantity: input.quantity ?? 1,
uom: input.uom ?? "",
});
console.log(`Created new RFQ item for RFQ ${input.rfqId}, Item ${input.itemCode}`);
}
}
});
// 캐시 무효화
revalidateTag("rfq-items");
revalidateTag(`rfqs-${input.rfqType}`);
revalidateTag(`rfq-${input.rfqId}`);
return { data: null, error: null };
} catch (err) {
console.error("Error in createRfqItem:", err);
return { data: null, error: getErrorMessage(err) };
}
}
/**
* 서버 액션: 파일 첨부/삭제 처리
* @param rfqId RFQ ID
* @param removedExistingIds 기존 첨부 중 삭제된 record ID 배열
* @param newFiles 새로 업로드된 파일 (File[]) - Next.js server action에서
* @param vendorId (optional) 업로더가 vendor인지 구분
*/
export async function processRfqAttachments(args: {
rfqId: number;
removedExistingIds?: number[];
newFiles?: File[];
vendorId?: number | null;
rfqType?: RfqType | null;
}) {
const { rfqId, removedExistingIds = [], newFiles = [], vendorId = null } = args;
try {
// 1) 삭제된 기존 첨부: DB + 파일시스템에서 제거
if (removedExistingIds.length > 0) {
// 1-1) DB에서 filePath 조회
const rows = await db
.select({
id: rfqAttachments.id,
filePath: rfqAttachments.filePath
})
.from(rfqAttachments)
.where(inArray(rfqAttachments.id, removedExistingIds));
// 1-2) DB 삭제
await db
.delete(rfqAttachments)
.where(inArray(rfqAttachments.id, removedExistingIds));
// 1-3) 파일 삭제
for (const row of rows) {
// filePath: 예) "/rfq/123/...xyz"
const absolutePath = path.join(
process.cwd(),
"public",
row.filePath.replace(/^\/+/, "") // 슬래시 제거
);
try {
await fs.unlink(absolutePath);
} catch (err) {
console.error("File remove error:", err);
}
}
}
// 2) 새 파일 업로드
if (newFiles.length > 0) {
const rfqDir = path.join("public", "rfq", String(rfqId));
// 폴더 없으면 생성
await fs.mkdir(rfqDir, { recursive: true });
for (const file of newFiles) {
// 2-1) File -> Buffer
const ab = await file.arrayBuffer();
const buffer = Buffer.from(ab);
// 2-2) 고유 파일명
const uniqueName = `${randomUUID()}-${file.name}`;
// 예) "rfq/123/xxx"
const relativePath = path.join("rfq", String(rfqId), uniqueName);
const absolutePath = path.join("public", relativePath);
// 2-3) 파일 저장
await fs.writeFile(absolutePath, buffer);
// 2-4) DB Insert
await db.insert(rfqAttachments).values({
rfqId,
vendorId,
fileName: file.name,
filePath: "/" + relativePath.replace(/\\/g, "/"),
// (Windows 경로 대비)
});
}
}
const [countRow] = await db
.select({ cnt: sql<number>`count(*)`.as("cnt") })
.from(rfqAttachments)
.where(eq(rfqAttachments.rfqId, rfqId));
const newCount = countRow?.cnt ?? 0;
// 3) revalidateTag 등 캐시 무효화
revalidateTag("rfq-attachments");
revalidateTag(`rfqs-${args.rfqType}`)
return { ok: true, updatedItemCount: newCount };
} catch (error) {
console.error("processRfqAttachments error:", error);
return { ok: false, error: String(error) };
}
}
export async function fetchRfqAttachments(rfqId: number) {
// DB select
const rows = await db
.select()
.from(rfqAttachments)
.where(eq(rfqAttachments.rfqId, rfqId))
// rows: { id, fileName, filePath, createdAt, vendorId, ... }
// 필요 없는 필드는 omit하거나 transform 가능
return rows.map((row) => ({
id: row.id,
fileName: row.fileName,
filePath: row.filePath,
createdAt: row.createdAt, // or string
vendorId: row.vendorId,
size: undefined, // size를 DB에 저장하지 않았다면
}))
}
export async function fetchRfqItems(rfqId: number) {
// DB select
const rows = await db
.select()
.from(rfqItems)
.where(eq(rfqItems.rfqId, rfqId))
// rows: { id, fileName, filePath, createdAt, vendorId, ... }
// 필요 없는 필드는 omit하거나 transform 가능
return rows.map((row) => ({
// id: row.id,
itemCode: row.itemCode,
description: row.description,
quantity: row.quantity,
uom: row.uom,
}))
}
export const findRfqById = async (id: number): Promise<RfqWithItems | null> => {
try {
logger.info({ id }, 'Fetching user by ID');
const rfq = await getRfqById(id);
if (!rfq) {
logger.warn({ id }, 'User not found');
} else {
logger.debug({ rfq }, 'User fetched successfully');
}
return rfq;
} catch (error) {
logger.error({ error }, 'Error fetching user by ID');
throw new Error('Failed to fetch user');
}
};
export async function getMatchedVendors(input: GetMatchedVendorsSchema, rfqId: number) {
return unstable_cache(
async () => {
// ─────────────────────────────────────────────────────
// 1) rfq_items에서 distinct itemCode
// ─────────────────────────────────────────────────────
const itemRows = await db
.select({ code: rfqItems.itemCode })
.from(rfqItems)
.where(eq(rfqItems.rfqId, rfqId))
.groupBy(rfqItems.itemCode)
const itemCodes = itemRows.map((r) => r.code)
const itemCount = itemCodes.length
if (itemCount === 0) {
return { data: [], pageCount: 0 }
}
// ─────────────────────────────────────────────────────
// 2) vendorPossibleItems에서 모든 itemCodes를 보유한 vendor
// ─────────────────────────────────────────────────────
const inList = itemCodes.map((c) => `'${c}'`).join(",")
const sqlVendorIds = await db.execute(
sql`
SELECT vpi.vendor_id AS "vendorId"
FROM ${vendorPossibleItems} vpi
WHERE vpi.item_code IN (${sql.raw(inList)})
GROUP BY vpi.vendor_id
HAVING COUNT(DISTINCT vpi.item_code) = ${itemCount}
`
)
const vendorIdList = sqlVendorIds.rows.map((row: any) => +row.vendorId)
if (vendorIdList.length === 0) {
return { data: [], pageCount: 0 }
}
// ─────────────────────────────────────────────────────
// 3) 필터/검색/정렬
// ─────────────────────────────────────────────────────
const offset = ((input.page ?? 1) - 1) * (input.perPage ?? 10)
const limit = input.perPage ?? 10
// (가) 커스텀 필터
// 여기서는 "뷰(vendorRfqView)"의 컬럼들에 대해 필터합니다.
const advancedWhere = filterColumns({
// 테이블이 아니라 "뷰"를 넘길 수도 있고,
// 혹은 columns 객체(연결된 모든 컬럼)로 넘겨도 됩니다.
table: vendorRfqView,
filters: input.filters ?? [],
joinOperator: input.joinOperator ?? "and",
})
// (나) 글로벌 검색
let globalWhere
if (input.search) {
const s = `%${input.search}%`
globalWhere = or(
sql`${vendorRfqView.vendorName} ILIKE ${s}`,
sql`${vendorRfqView.vendorCode} ILIKE ${s}`,
sql`${vendorRfqView.email} ILIKE ${s}`
)
}
// (다) 최종 where
// vendorId가 vendorIdList 내에 있어야 하고,
// 특정 rfqId(뷰에 담긴 값)도 일치해야 함.
const finalWhere = and(
inArray(vendorRfqView.vendorId, vendorIdList),
// 아래 라인은 rfq에 초대된 벤더만 필터링하는 조건으로 추정되지만
// rfq 를 진행하기 전에도 벤더를 보여줘야 하므로 주석처리하겠습니다
// eq(vendorRfqView.rfqId, rfqId),
advancedWhere,
globalWhere
)
// (라) 정렬
const orderBy = input.sort?.length
? input.sort.map((s) => {
// "column id" -> vendorRfqView.* 중 하나
const col = (vendorRfqView as any)[s.id]
return s.desc ? desc(col) : asc(col)
})
: [asc(vendorRfqView.vendorId)]
// ─────────────────────────────────────────────────────
// 4) View에서 데이터 SELECT
// ─────────────────────────────────────────────────────
const [rows, total] = await db.transaction(async (tx) => {
const data = await tx
.select({
id: vendorRfqView.vendorId,
vendorID: vendorRfqView.vendorId,
vendorName: vendorRfqView.vendorName,
vendorCode: vendorRfqView.vendorCode,
address: vendorRfqView.address,
country: vendorRfqView.country,
email: vendorRfqView.email,
website: vendorRfqView.website,
vendorStatus: vendorRfqView.vendorStatus,
// rfqVendorStatus와 rfqVendorUpdated는 나중에 정확한 데이터로 교체할 예정
rfqVendorStatus: vendorRfqView.rfqVendorStatus,
rfqVendorUpdated: vendorRfqView.rfqVendorUpdated,
})
.from(vendorRfqView)
.where(finalWhere)
.orderBy(...orderBy)
.offset(offset)
.limit(limit)
// 중복 제거된 데이터 생성
const distinctData = Array.from(
new Map(data.map(row => [row.id, row])).values()
)
// 중복 제거된 총 개수 계산
const [{ count }] = await tx
.select({ count: sql<number>`count(DISTINCT ${vendorRfqView.vendorId})`.as("count") })
.from(vendorRfqView)
.where(finalWhere)
return [distinctData, Number(count)]
})
// ─────────────────────────────────────────────────────
// 4-1) 정확한 rfqVendorStatus와 rfqVendorUpdated 조회
// ─────────────────────────────────────────────────────
const distinctVendorIds = [...new Set(rows.map((r) => r.id))]
// vendorResponses 테이블에서 정확한 상태와 업데이트 시간 조회
const vendorStatuses = await db
.select({
vendorId: vendorResponses.vendorId,
status: vendorResponses.responseStatus,
updatedAt: vendorResponses.updatedAt
})
.from(vendorResponses)
.where(
and(
inArray(vendorResponses.vendorId, distinctVendorIds),
eq(vendorResponses.rfqId, rfqId)
)
)
// vendorId별 상태정보 맵 생성
const statusMap = new Map<number, { status: string, updatedAt: Date }>()
for (const vs of vendorStatuses) {
statusMap.set(vs.vendorId, {
status: vs.status,
updatedAt: vs.updatedAt
})
}
// 정확한 상태 정보로 업데이트된 rows 생성
const updatedRows = rows.map(row => ({
...row,
rfqVendorStatus: statusMap.get(row.id)?.status || null,
rfqVendorUpdated: statusMap.get(row.id)?.updatedAt || null
}))
// ─────────────────────────────────────────────────────
// 5) 코멘트 조회: 기존과 동일
// ─────────────────────────────────────────────────────
const commAll = await db
.select()
.from(rfqComments)
.where(
and(
inArray(rfqComments.vendorId, distinctVendorIds),
eq(rfqComments.rfqId, rfqId)
)
)
const commByVendorId = new Map<number, any[]>()
// 먼저 모든 사용자 ID를 수집
const userIds = new Set(commAll.map(c => c.commentedBy));
const userIdsArray = Array.from(userIds);
// Drizzle의 select 메서드를 사용하여 사용자 정보를 가져옴
const usersData = await db
.select({
id: users.id,
email: users.email,
})
.from(users)
.where(inArray(users.id, userIdsArray));
// 사용자 ID를 키로 하는 맵 생성
const userMap = new Map();
for (const user of usersData) {
userMap.set(user.id, user);
}
// 댓글 정보를 벤더 ID별로 그룹화하고, 사용자 이메일 추가
for (const c of commAll) {
const vid = c.vendorId!
if (!commByVendorId.has(vid)) {
commByVendorId.set(vid, [])
}
// 사용자 정보 가져오기
const user = userMap.get(c.commentedBy);
const userEmail = user ? user.email : 'unknown@example.com'; // 사용자를 찾지 못한 경우 기본값 설정
commByVendorId.get(vid)!.push({
id: c.id,
commentText: c.commentText,
vendorId: c.vendorId,
evaluationId: c.evaluationId,
createdAt: c.createdAt,
commentedBy: c.commentedBy,
commentedByEmail: userEmail, // 이메일 추가
})
}
// ─────────────────────────────────────────────────────
// 6) rows에 comments 병합
// ─────────────────────────────────────────────────────
const final = updatedRows.map((row) => ({
...row,
comments: commByVendorId.get(row.id) ?? [],
}))
// ─────────────────────────────────────────────────────
// 7) 반환
// ─────────────────────────────────────────────────────
const pageCount = Math.ceil(total / limit)
return { data: final, pageCount }
},
[JSON.stringify({ input, rfqId })],
{ revalidate: 3600, tags: ["rfq-vendors"] }
)()
}
export async function inviteVendors(input: InviteVendorsInput) {
unstable_noStore() // 서버 액션 캐싱 방지
try {
const { rfqId, vendorIds } = input
if (!rfqId || !Array.isArray(vendorIds) || vendorIds.length === 0) {
throw new Error("Invalid input")
}
// DB 데이터 준비 및 첨부파일 처리를 위한 트랜잭션
const rfqData = await db.transaction(async (tx) => {
// 2-A) RFQ 기본 정보 조회
const [rfqRow] = await tx
.select({
rfqCode: rfqsView.rfqCode,
description: rfqsView.description,
projectCode: rfqsView.projectCode,
projectName: rfqsView.projectName,
dueDate: rfqsView.dueDate,
createdBy: rfqsView.createdBy,
})
.from(rfqsView)
.where(eq(rfqsView.id, rfqId))
if (!rfqRow) {
throw new Error(`RFQ #${rfqId} not found`)
}
// 2-B) 아이템 목록 조회
const items = await tx
.select({
itemCode: rfqItems.itemCode,
description: rfqItems.description,
quantity: rfqItems.quantity,
uom: rfqItems.uom,
})
.from(rfqItems)
.where(eq(rfqItems.rfqId, rfqId))
// 2-C) 첨부파일 목록 조회
const attachRows = await tx
.select({
id: rfqAttachments.id,
fileName: rfqAttachments.fileName,
filePath: rfqAttachments.filePath,
})
.from(rfqAttachments)
.where(
and(
eq(rfqAttachments.rfqId, rfqId),
isNull(rfqAttachments.vendorId),
isNull(rfqAttachments.evaluationId)
)
)
const vendorRows = await tx
.select({ id: vendors.id, email: vendors.email })
.from(vendors)
.where(inArray(vendors.id, vendorIds))
// NodeMailer attachments 형식 맞추기
const attachments = []
for (const att of attachRows) {
const absolutePath = path.join(process.cwd(), "public", att.filePath.replace(/^\/+/, ""))
attachments.push({
path: absolutePath,
filename: att.fileName,
})
}
return { rfqRow, items, vendorRows, attachments }
})
const { rfqRow, items, vendorRows, attachments } = rfqData
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || 'http://3.36.56.124:3000'
const loginUrl = `${baseUrl}/en/partners/rfq`
// 이메일 전송 오류를 기록할 배열
const emailErrors = []
// 각 벤더에 대해 처리
for (const v of vendorRows) {
if (!v.email) {
continue // 이메일 없는 벤더 무시
}
try {
// DB 업데이트: 각 벤더 상태 별도 트랜잭션
await db.transaction(async (tx) => {
// rfq_vendors upsert
const existing = await tx
.select()
.from(vendorResponses)
.where(and(eq(vendorResponses.rfqId, rfqId), eq(vendorResponses.vendorId, v.id)))
if (existing.length > 0) {
await tx
.update(vendorResponses)
.set({
responseStatus: "INVITED",
updatedAt: new Date(),
})
.where(eq(vendorResponses.id, existing[0].id))
} else {
await tx.insert(vendorResponses).values({
rfqId,
vendorId: v.id,
responseStatus: "INVITED",
})
}
})
// 이메일 발송 (트랜잭션 외부)
await sendEmail({
to: v.email,
subject: `[RFQ ${rfqRow.rfqCode}] You are invited from Samgsung Heavy Industries!`,
template: "rfq-invite",
context: {
language: "en",
rfqId,
vendorId: v.id,
rfqCode: rfqRow.rfqCode,
projectCode: rfqRow.projectCode,
projectName: rfqRow.projectName,
dueDate: rfqRow.dueDate,
description: rfqRow.description,
items: items.map((it) => ({
itemCode: it.itemCode,
description: it.description,
quantity: it.quantity,
uom: it.uom,
})),
loginUrl
},
attachments,
})
} catch (err) {
// 개별 벤더 처리 실패 로깅
console.error(`Failed to process vendor ${v.id}: ${getErrorMessage(err)}`)
emailErrors.push({ vendorId: v.id, error: getErrorMessage(err) })
// 계속 진행 (다른 벤더 처리)
}
}
// 최종적으로 RFQ 상태 업데이트 (별도 트랜잭션)
try {
await db.transaction(async (tx) => {
await tx
.update(rfqs)
.set({
status: "PUBLISHED",
updatedAt: new Date(),
})
.where(eq(rfqs.id, rfqId))
console.log(`Updated RFQ #${rfqId} status to PUBLISHED`)
})
// 캐시 무효화
revalidateTag("rfq-vendors")
revalidateTag("cbe-vendors")
revalidateTag("rfqs")
revalidateTag(`rfqs-${input.rfqType}`)
revalidateTag(`rfq-${rfqId}`)
// 이메일 오류가 있었는지 확인
if (emailErrors.length > 0) {
return {
error: `일부 벤더에게 이메일 발송 실패 (${emailErrors.length}/${vendorRows.length}), RFQ 상태는 업데이트됨`,
emailErrors
}
}
return { error: null }
} catch (err) {
return { error: `RFQ 상태 업데이트 실패: ${getErrorMessage(err)}` }
}
} catch (err) {
return { error: getErrorMessage(err) }
}
}
/**
* TBE용 평가 데이터 목록 조회
*/
export async function getTBE(input: GetTBESchema, rfqId: number) {
return unstable_cache(
async () => {
// 1) 페이징
const offset = ((input.page ?? 1) - 1) * (input.perPage ?? 10)
const limit = input.perPage ?? 10
// 2) 고급 필터
const advancedWhere = filterColumns({
table: vendorTbeView,
filters: input.filters ?? [],
joinOperator: input.joinOperator ?? "and",
})
// 3) 글로벌 검색
let globalWhere
if (input.search) {
const s = `%${input.search}%`
globalWhere = or(
sql`${vendorTbeView.vendorName} ILIKE ${s}`,
sql`${vendorTbeView.vendorCode} ILIKE ${s}`,
sql`${vendorTbeView.email} ILIKE ${s}`
)
}
// 4) REJECTED 아니거나 NULL
const notRejected = or(
ne(vendorTbeView.rfqVendorStatus, "REJECTED"),
isNull(vendorTbeView.rfqVendorStatus)
)
// 5) finalWhere
const finalWhere = and(
eq(vendorTbeView.rfqId, rfqId),
notRejected,
advancedWhere,
globalWhere
)
// 6) 정렬
const orderBy = input.sort?.length
? input.sort.map((s) => {
const col = (vendorTbeView as any)[s.id]
return s.desc ? desc(col) : asc(col)
})
: [asc(vendorTbeView.vendorId)]
// 7) 메인 SELECT
const [rows, total] = await db.transaction(async (tx) => {
const data = await tx
.select({
// 원하는 컬럼들
id: vendorTbeView.vendorId,
tbeId: vendorTbeView.tbeId,
vendorId: vendorTbeView.vendorId,
vendorName: vendorTbeView.vendorName,
vendorCode: vendorTbeView.vendorCode,
address: vendorTbeView.address,
country: vendorTbeView.country,
email: vendorTbeView.email,
website: vendorTbeView.website,
vendorStatus: vendorTbeView.vendorStatus,
rfqId: vendorTbeView.rfqId,
rfqCode: vendorTbeView.rfqCode,
projectCode: vendorTbeView.projectCode,
projectName: vendorTbeView.projectName,
description: vendorTbeView.description,
dueDate: vendorTbeView.dueDate,
rfqVendorStatus: vendorTbeView.rfqVendorStatus,
rfqVendorUpdated: vendorTbeView.rfqVendorUpdated,
tbeResult: vendorTbeView.tbeResult,
tbeNote: vendorTbeView.tbeNote,
tbeUpdated: vendorTbeView.tbeUpdated,
})
.from(vendorTbeView)
.where(finalWhere)
.orderBy(...orderBy)
.offset(offset)
.limit(limit)
const [{ count }] = await tx
.select({ count: sql<number>`count(*)`.as("count") })
.from(vendorTbeView)
.where(finalWhere)
return [data, Number(count)]
})
if (!rows.length) {
return { data: [], pageCount: 0 }
}
// 8) Comments 조회
const distinctVendorIds = [...new Set(rows.map((r) => r.vendorId))]
const commAll = await db
.select({
id: rfqComments.id,
commentText: rfqComments.commentText,
vendorId: rfqComments.vendorId,
evaluationId: rfqComments.evaluationId,
createdAt: rfqComments.createdAt,
commentedBy: rfqComments.commentedBy,
evalType: rfqEvaluations.evalType,
})
.from(rfqComments)
.innerJoin(
rfqEvaluations,
and(
eq(rfqEvaluations.id, rfqComments.evaluationId),
eq(rfqEvaluations.evalType, "TBE")
)
)
.where(
and(
isNotNull(rfqComments.evaluationId),
eq(rfqComments.rfqId, rfqId),
inArray(rfqComments.vendorId, distinctVendorIds)
)
)
// 8-A) vendorId -> comments grouping
const commByVendorId = new Map<number, any[]>()
for (const c of commAll) {
const vid = c.vendorId!
if (!commByVendorId.has(vid)) {
commByVendorId.set(vid, [])
}
commByVendorId.get(vid)!.push({
id: c.id,
commentText: c.commentText,
vendorId: c.vendorId,
evaluationId: c.evaluationId,
createdAt: c.createdAt,
commentedBy: c.commentedBy,
})
}
// 9) TBE 파일 조회 - vendorResponseAttachments로 대체
// Step 1: Get vendorResponses for the rfqId and vendorIds
const responsesAll = await db
.select({
id: vendorResponses.id,
vendorId: vendorResponses.vendorId
})
.from(vendorResponses)
.where(
and(
eq(vendorResponses.rfqId, rfqId),
inArray(vendorResponses.vendorId, distinctVendorIds)
)
);
// Group responses by vendorId for later lookup
const responsesByVendorId = new Map<number, number[]>();
for (const resp of responsesAll) {
if (!responsesByVendorId.has(resp.vendorId)) {
responsesByVendorId.set(resp.vendorId, []);
}
responsesByVendorId.get(resp.vendorId)!.push(resp.id);
}
// Step 2: Get all responseIds
const allResponseIds = responsesAll.map(r => r.id);
// Step 3: Get technicalResponses for these responseIds
const technicalResponsesAll = await db
.select({
id: vendorTechnicalResponses.id,
responseId: vendorTechnicalResponses.responseId
})
.from(vendorTechnicalResponses)
.where(inArray(vendorTechnicalResponses.responseId, allResponseIds));
// Create mapping from responseId to technicalResponseIds
const technicalResponseIdsByResponseId = new Map<number, number[]>();
for (const tr of technicalResponsesAll) {
if (!technicalResponseIdsByResponseId.has(tr.responseId)) {
technicalResponseIdsByResponseId.set(tr.responseId, []);
}
technicalResponseIdsByResponseId.get(tr.responseId)!.push(tr.id);
}
// Step 4: Get all technicalResponseIds
const allTechnicalResponseIds = technicalResponsesAll.map(tr => tr.id);
// Step 5: Get attachments for these technicalResponseIds
const filesAll = await db
.select({
id: vendorResponseAttachments.id,
fileName: vendorResponseAttachments.fileName,
filePath: vendorResponseAttachments.filePath,
technicalResponseId: vendorResponseAttachments.technicalResponseId,
fileType: vendorResponseAttachments.fileType,
attachmentType: vendorResponseAttachments.attachmentType,
description: vendorResponseAttachments.description,
uploadedAt: vendorResponseAttachments.uploadedAt,
uploadedBy: vendorResponseAttachments.uploadedBy
})
.from(vendorResponseAttachments)
.where(
and(
inArray(vendorResponseAttachments.technicalResponseId, allTechnicalResponseIds),
isNotNull(vendorResponseAttachments.technicalResponseId)
)
);
// Step 6: Create mapping from technicalResponseId to attachments
const filesByTechnicalResponseId = new Map<number, any[]>();
for (const file of filesAll) {
// Skip if technicalResponseId is null (should never happen due to our filter above)
if (file.technicalResponseId === null) continue;
if (!filesByTechnicalResponseId.has(file.technicalResponseId)) {
filesByTechnicalResponseId.set(file.technicalResponseId, []);
}
filesByTechnicalResponseId.get(file.technicalResponseId)!.push({
id: file.id,
fileName: file.fileName,
filePath: file.filePath,
fileType: file.fileType,
attachmentType: file.attachmentType,
description: file.description,
uploadedAt: file.uploadedAt,
uploadedBy: file.uploadedBy
});
}
// Step 7: Create the final filesByVendorId map
const filesByVendorId = new Map<number, any[]>();
for (const [vendorId, responseIds] of responsesByVendorId.entries()) {
filesByVendorId.set(vendorId, []);
for (const responseId of responseIds) {
const technicalResponseIds = technicalResponseIdsByResponseId.get(responseId) || [];
for (const technicalResponseId of technicalResponseIds) {
const files = filesByTechnicalResponseId.get(technicalResponseId) || [];
filesByVendorId.get(vendorId)!.push(...files);
}
}
}
// 10) 최종 합치기
const final = rows.map((row) => ({
...row,
dueDate: row.dueDate ? new Date(row.dueDate) : null,
comments: commByVendorId.get(row.vendorId) ?? [],
files: filesByVendorId.get(row.vendorId) ?? [],
}))
const pageCount = Math.ceil(total / limit)
return { data: final, pageCount }
},
[JSON.stringify({ input, rfqId })],
{
revalidate: 3600,
tags: ["tbe-vendors"],
}
)()
}
export async function getTBEforVendor(input: GetTBESchema, vendorId: number) {
if (isNaN(vendorId) || vendorId === null || vendorId === undefined) {
throw new Error("유효하지 않은 vendorId: 숫자 값이 필요합니다");
}
return unstable_cache(
async () => {
// 1) 페이징
const offset = ((input.page ?? 1) - 1) * (input.perPage ?? 10)
const limit = input.perPage ?? 10
// 2) 고급 필터
const advancedWhere = filterColumns({
table: vendorTbeView,
filters: input.filters ?? [],
joinOperator: input.joinOperator ?? "and",
})
// 3) 글로벌 검색
let globalWhere
if (input.search) {
const s = `%${input.search}%`
globalWhere = or(
sql`${vendorTbeView.vendorName} ILIKE ${s}`,
sql`${vendorTbeView.vendorCode} ILIKE ${s}`,
sql`${vendorTbeView.email} ILIKE ${s}`
)
}
// 4) REJECTED 아니거나 NULL
const notRejected = or(
ne(vendorTbeView.rfqVendorStatus, "REJECTED"),
isNull(vendorTbeView.rfqVendorStatus)
)
// 5) finalWhere
const finalWhere = and(
isNotNull(vendorTbeView.tbeId),
eq(vendorTbeView.vendorId, vendorId),
notRejected,
advancedWhere,
globalWhere
)
// 6) 정렬
const orderBy = input.sort?.length
? input.sort.map((s) => {
const col = (vendorTbeView as any)[s.id]
return s.desc ? desc(col) : asc(col)
})
: [asc(vendorTbeView.vendorId)]
// 7) 메인 SELECT
const [rows, total] = await db.transaction(async (tx) => {
const data = await tx
.select({
// 원하는 컬럼들
id: vendorTbeView.vendorId,
tbeId: vendorTbeView.tbeId,
vendorId: vendorTbeView.vendorId,
vendorName: vendorTbeView.vendorName,
vendorCode: vendorTbeView.vendorCode,
address: vendorTbeView.address,
country: vendorTbeView.country,
email: vendorTbeView.email,
website: vendorTbeView.website,
vendorStatus: vendorTbeView.vendorStatus,
rfqId: vendorTbeView.rfqId,
rfqCode: vendorTbeView.rfqCode,
projectCode: vendorTbeView.projectCode,
projectName: vendorTbeView.projectName,
description: vendorTbeView.description,
dueDate: vendorTbeView.dueDate,
vendorResponseId: vendorTbeView.vendorResponseId,
rfqVendorStatus: vendorTbeView.rfqVendorStatus,
rfqVendorUpdated: vendorTbeView.rfqVendorUpdated,
tbeResult: vendorTbeView.tbeResult,
tbeNote: vendorTbeView.tbeNote,
tbeUpdated: vendorTbeView.tbeUpdated,
})
.from(vendorTbeView)
.where(finalWhere)
.orderBy(...orderBy)
.offset(offset)
.limit(limit)
const [{ count }] = await tx
.select({ count: sql<number>`count(*)`.as("count") })
.from(vendorTbeView)
.where(finalWhere)
return [data, Number(count)]
})
if (!rows.length) {
return { data: [], pageCount: 0 }
}
// 8) Comments 조회
// - evaluationId != null && evalType = "TBE"
// - => leftJoin(rfqEvaluations) or innerJoin
const distinctVendorIds = [...new Set(rows.map((r) => r.vendorId))]
const distinctTbeIds = [...new Set(rows.map((r) => r.tbeId).filter(Boolean))]
// (A) 조인 방식
const commAll = await db
.select({
id: rfqComments.id,
commentText: rfqComments.commentText,
vendorId: rfqComments.vendorId,
evaluationId: rfqComments.evaluationId,
createdAt: rfqComments.createdAt,
commentedBy: rfqComments.commentedBy,
evalType: rfqEvaluations.evalType, // (optional)
})
.from(rfqComments)
// evalType = 'TBE'
.innerJoin(
rfqEvaluations,
and(
eq(rfqEvaluations.id, rfqComments.evaluationId),
eq(rfqEvaluations.evalType, "TBE") // ★ TBE만
)
)
.where(
and(
isNotNull(rfqComments.evaluationId),
inArray(rfqComments.vendorId, distinctVendorIds)
)
)
// 8-A) vendorId -> comments grouping
const commByVendorId = new Map<number, any[]>()
for (const c of commAll) {
const vid = c.vendorId!
if (!commByVendorId.has(vid)) {
commByVendorId.set(vid, [])
}
commByVendorId.get(vid)!.push({
id: c.id,
commentText: c.commentText,
vendorId: c.vendorId,
evaluationId: c.evaluationId,
createdAt: c.createdAt,
commentedBy: c.commentedBy,
})
}
// 9) TBE 템플릿 파일 수 조회
const templateFiles = await db
.select({
tbeId: rfqAttachments.evaluationId,
fileCount: sql<number>`count(*)`.as("file_count"),
})
.from(rfqAttachments)
.where(
and(
inArray(rfqAttachments.evaluationId, distinctTbeIds),
isNull(rfqAttachments.vendorId),
isNull(rfqAttachments.commentId)
)
)
.groupBy(rfqAttachments.evaluationId)
// tbeId -> fileCount 매핑 - null 체크 추가
const templateFileCountMap = new Map<number, number>()
for (const tf of templateFiles) {
if (tf.tbeId !== null) {
templateFileCountMap.set(tf.tbeId, Number(tf.fileCount))
}
}
// 10) TBE 응답 파일 확인 (각 tbeId + vendorId 조합에 대해)
const tbeResponseFiles = await db
.select({
tbeId: rfqAttachments.evaluationId,
vendorId: rfqAttachments.vendorId,
responseFileCount: sql<number>`count(*)`.as("response_file_count"),
})
.from(rfqAttachments)
.where(
and(
inArray(rfqAttachments.evaluationId, distinctTbeIds),
inArray(rfqAttachments.vendorId, distinctVendorIds),
isNull(rfqAttachments.commentId)
)
)
.groupBy(rfqAttachments.evaluationId, rfqAttachments.vendorId)
// tbeId_vendorId -> hasResponse 매핑 - null 체크 추가
const tbeResponseMap = new Map<string, number>()
for (const rf of tbeResponseFiles) {
if (rf.tbeId !== null && rf.vendorId !== null) {
const key = `${rf.tbeId}_${rf.vendorId}`
tbeResponseMap.set(key, Number(rf.responseFileCount))
}
}
// 11) 최종 합치기
const final = rows.map((row) => {
const tbeId = row.tbeId
const vendorId = row.vendorId
// 템플릿 파일 수
const templateFileCount = tbeId !== null ? templateFileCountMap.get(tbeId) || 0 : 0
// 응답 파일 여부
const responseKey = tbeId !== null ? `${tbeId}_${vendorId}` : ""
const responseFileCount = responseKey ? tbeResponseMap.get(responseKey) || 0 : 0
return {
...row,
dueDate: row.dueDate ? new Date(row.dueDate) : null,
comments: commByVendorId.get(row.vendorId) ?? [],
templateFileCount, // 추가: 템플릿 파일 수
hasResponse: responseFileCount > 0, // 추가: 응답 파일 제출 여부
}
})
const pageCount = Math.ceil(total / limit)
return { data: final, pageCount }
},
[JSON.stringify(input), String(vendorId)], // 캐싱 키에 packagesId 추가
{
revalidate: 3600,
tags: [`tbe-vendors-${vendorId}`],
}
)()
}
export async function inviteTbeVendorsAction(formData: FormData) {
// 캐싱 방지
unstable_noStore()
try {
// 1) FormData에서 기본 필드 추출
const rfqId = Number(formData.get("rfqId"))
const vendorIdsRaw = formData.getAll("vendorIds[]")
const vendorIds = vendorIdsRaw.map((id) => Number(id))
// 2) FormData에서 파일들 추출 (multiple)
const tbeFiles = formData.getAll("tbeFiles") as File[]
if (!rfqId || !vendorIds.length || !tbeFiles.length) {
throw new Error("Invalid input or no files attached.")
}
// /public/rfq/[rfqId] 경로
const uploadDir = path.join(process.cwd(), "public", "rfq", String(rfqId))
// DB 트랜잭션
await db.transaction(async (tx) => {
// (A) RFQ 기본 정보 조회
const [rfqRow] = await tx
.select({
rfqCode: vendorResponsesView.rfqCode,
description: vendorResponsesView.rfqDescription,
projectCode: vendorResponsesView.projectCode,
projectName: vendorResponsesView.projectName,
dueDate: vendorResponsesView.rfqDueDate,
createdBy: vendorResponsesView.rfqCreatedBy,
})
.from(vendorResponsesView)
.where(eq(vendorResponsesView.rfqId, rfqId))
if (!rfqRow) {
throw new Error(`RFQ #${rfqId} not found`)
}
// (B) RFQ 아이템 목록
const items = await tx
.select({
itemCode: rfqItems.itemCode,
description: rfqItems.description,
quantity: rfqItems.quantity,
uom: rfqItems.uom,
})
.from(rfqItems)
.where(eq(rfqItems.rfqId, rfqId))
// (C) 대상 벤더들
const vendorRows = await tx
.select({ id: vendors.id, email: vendors.email })
.from(vendors)
.where(sql`${vendors.id} in (${vendorIds})`)
// (D) 모든 TBE 파일 저장 & 이후 벤더 초대 처리
// 파일은 한 번만 저장해도 되지만, 각 벤더별로 따로 저장/첨부가 필요하다면 루프를 돌려도 됨.
// 여기서는 "모든 파일"을 RFQ-DIR에 저장 + "각 벤더"에는 동일 파일 목록을 첨부한다는 예시.
const savedFiles = []
for (const file of tbeFiles) {
const originalName = file.name || "tbe-sheet.xlsx"
const savePath = path.join(uploadDir, originalName)
// 파일 ArrayBuffer → Buffer 변환 후 저장
const arrayBuffer = await file.arrayBuffer()
fs.writeFile(savePath, Buffer.from(arrayBuffer))
// 저장 경로 & 파일명 기록
savedFiles.push({
fileName: originalName,
filePath: `/rfq/${rfqId}/${originalName}`, // public 이하 경로
absolutePath: savePath,
})
}
// (E) 각 벤더별로 TBE 평가 레코드, 초대 처리, 메일 발송
for (const v of vendorRows) {
if (!v.email) {
// 이메일 없는 경우 로직 (스킵 or throw)
continue
}
// 1) TBE 평가 레코드 생성
const [evalRow] = await tx
.insert(rfqEvaluations)
.values({
rfqId,
vendorId: v.id,
evalType: "TBE",
})
.returning({ id: rfqEvaluations.id })
// 2) rfqAttachments에 저장한 파일들을 기록
for (const sf of savedFiles) {
await tx.insert(rfqAttachments).values({
rfqId,
// vendorId: v.id,
evaluationId: evalRow.id,
fileName: sf.fileName,
filePath: sf.filePath,
})
}
// 4) 메일 발송
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || 'http://3.36.56.124:3000'
const loginUrl = `${baseUrl}/ko/partners/rfq`
await sendEmail({
to: v.email,
subject: `[RFQ ${rfqRow.rfqCode}] You are invited for TBE!`,
template: "rfq-invite",
context: {
language: "en",
rfqId,
vendorId: v.id,
rfqCode: rfqRow.rfqCode,
projectCode: rfqRow.projectCode,
projectName: rfqRow.projectName,
dueDate: rfqRow.dueDate,
description: rfqRow.description,
items: items.map((it) => ({
itemCode: it.itemCode,
description: it.description,
quantity: it.quantity,
uom: it.uom,
})),
loginUrl,
},
attachments: savedFiles.map((sf) => ({
path: sf.absolutePath,
filename: sf.fileName,
})),
})
}
// 5) 캐시 무효화
revalidateTag("tbe-vendors")
})
// 성공
return { error: null }
} catch (err) {
console.error("[inviteTbeVendorsAction] Error:", err)
return { error: getErrorMessage(err) }
}
}
////partners
export async function modifyRfqVendor(input: UpdateRfqVendorSchema) {
unstable_noStore();
try {
const data = await db.transaction(async (tx) => {
const [res] = await updateRfqVendor(tx, input.id, {
responseStatus: input.status,
});
return res;
});
revalidateTag("rfqs-vendor");
revalidateTag("rfq-vendors");
return { data: null, error: null };
} catch (err) {
return { data: null, error: getErrorMessage(err) };
}
}
export async function createRfqCommentWithAttachments(params: {
rfqId: number
vendorId?: number | null
commentText: string
commentedBy: number
evaluationId?: number | null
cbeId?: number | null
files?: File[]
}) {
const { rfqId, vendorId, commentText, commentedBy, evaluationId,cbeId, files } = params
// 1) 새로운 코멘트 생성
const [insertedComment] = await db
.insert(rfqComments)
.values({
rfqId,
vendorId: vendorId || null,
commentText,
commentedBy,
evaluationId: evaluationId || null,
cbeId: cbeId || null,
})
.returning({ id: rfqComments.id, createdAt: rfqComments.createdAt }) // id만 반환하도록
if (!insertedComment) {
throw new Error("Failed to create comment")
}
// 2) 첨부파일 처리
if (files && files.length > 0) {
const rfqDir = path.join(process.cwd(), "public", "rfq", String(rfqId));
// 폴더 없으면 생성
await fs.mkdir(rfqDir, { recursive: true });
for (const file of files) {
const ab = await file.arrayBuffer();
const buffer = Buffer.from(ab);
// 2-2) 고유 파일명
const uniqueName = `${randomUUID()}-${file.name}`;
// 예) "rfq/123/xxx"
const relativePath = path.join("rfq", String(rfqId), uniqueName);
const absolutePath = path.join(process.cwd(), "public", relativePath);
// 2-3) 파일 저장
await fs.writeFile(absolutePath, buffer);
// DB에 첨부파일 row 생성
await db.insert(rfqAttachments).values({
rfqId,
vendorId: vendorId || null,
evaluationId: evaluationId || null,
cbeId: cbeId || null,
commentId: insertedComment.id, // 새 코멘트와 연결
fileName: file.name,
filePath: "/" + relativePath.replace(/\\/g, "/"),
})
}
}
revalidateTag("rfq-vendors");
return { ok: true, commentId: insertedComment.id, createdAt: insertedComment.createdAt }
}
export async function fetchRfqAttachmentsbyCommentId(commentId: number) {
// DB select
const rows = await db
.select()
.from(rfqAttachments)
.where(eq(rfqAttachments.commentId, commentId))
// rows: { id, fileName, filePath, createdAt, vendorId, ... }
// 필요 없는 필드는 omit하거나 transform 가능
return rows.map((row) => ({
id: row.id,
fileName: row.fileName,
filePath: row.filePath,
createdAt: row.createdAt, // or string
vendorId: row.vendorId,
evaluationId: row.evaluationId,
size: undefined, // size를 DB에 저장하지 않았다면
}))
}
export async function updateRfqComment(params: {
commentId: number
commentText: string
}) {
const { commentId, commentText } = params
// 예: 간단한 길이 체크 등 유효성 검사
if (!commentText || commentText.trim().length === 0) {
throw new Error("Comment text must not be empty.")
}
// DB 업데이트
const updatedRows = await db
.update(rfqComments)
.set({ commentText }) // 필요한 컬럼만 set
.where(eq(rfqComments.id, commentId))
.returning({ id: rfqComments.id })
// 혹은 returning 전체(row)를 받아서 확인할 수도 있음
if (updatedRows.length === 0) {
// 해당 id가 없으면 예외
throw new Error("Comment not found or already deleted.")
}
revalidateTag("rfq-vendors");
return { ok: true }
}
export type Project = {
id: number;
projectCode: string;
projectName: string;
}
export async function getProjects(): Promise<Project[]> {
try {
// 트랜잭션을 사용하여 프로젝트 데이터 조회
const projectList = await db.transaction(async (tx) => {
// 모든 프로젝트 조회
const results = await tx
.select({
id: projects.id,
projectCode: projects.code, // 테이블의 실제 컬럼명에 맞게 조정
projectName: projects.name, // 테이블의 실제 컬럼명에 맞게 조정
})
.from(projects)
.orderBy(projects.code);
return results;
});
return projectList;
} catch (error) {
console.error("프로젝트 목록 가져오기 실패:", error);
return []; // 오류 발생 시 빈 배열 반환
}
}
// 반환 타입 명시적 정의 - rfqCode가 null일 수 있음을 반영
export interface BudgetaryRfq {
id: number;
rfqCode: string | null; // null 허용으로 변경
description: string | null;
projectId: number | null;
projectCode: string | null;
projectName: string | null;
}
type GetBudgetaryRfqsResponse =
| { rfqs: BudgetaryRfq[]; totalCount: number; error?: never }
| { error: string; rfqs?: never; totalCount: number }
/**
* Budgetary 타입의 RFQ 목록을 가져오는 서버 액션
* Purchase RFQ 생성 시 부모 RFQ로 선택할 수 있도록 함
* 페이징 및 필터링 기능 포함
*/
export interface GetBudgetaryRfqsParams {
search?: string;
projectId?: number;
rfqId?: number; // 특정 ID로 단일 RFQ 검색
rfqTypes?: RfqType[]; // 특정 RFQ 타입들로 필터링
limit?: number;
offset?: number;
}
export async function getBudgetaryRfqs(params: GetBudgetaryRfqsParams = {}): Promise<GetBudgetaryRfqsResponse> {
const { search, projectId, rfqId, rfqTypes, limit = 50, offset = 0 } = params;
const cacheKey = `rfqs-query-${JSON.stringify(params)}`;
return unstable_cache(
async () => {
try {
// 기본 검색 조건 구성
let baseCondition;
// 특정 RFQ 타입들로 필터링 (rfqTypes 배열이 주어진 경우)
if (rfqTypes && rfqTypes.length > 0) {
// 여러 타입으로 필터링 (OR 조건)
baseCondition = inArray(rfqs.rfqType, rfqTypes);
} else {
// 기본적으로 BUDGETARY 타입만 검색 (이전 동작 유지)
baseCondition = eq(rfqs.rfqType, RfqType.BUDGETARY);
}
// 특정 ID로 검색하는 경우
if (rfqId) {
baseCondition = and(baseCondition, eq(rfqs.id, rfqId));
}
let where1;
// 검색어 조건 추가 (있을 경우)
if (search && search.trim()) {
const searchTerm = `%${search.trim()}%`;
const searchCondition = or(
ilike(rfqs.rfqCode, searchTerm),
ilike(rfqs.description, searchTerm),
ilike(projects.code, searchTerm),
ilike(projects.name, searchTerm)
);
where1 = searchCondition;
}
let where2;
// 프로젝트 ID 조건 추가 (있을 경우)
if (projectId) {
where2 = eq(rfqs.projectId, projectId);
}
const finalWhere = and(baseCondition, where1, where2);
// 총 개수 조회
const [countResult] = await db
.select({ count: count() })
.from(rfqs)
.leftJoin(projects, eq(rfqs.projectId, projects.id))
.where(finalWhere);
// 실제 데이터 조회
const resultRfqs = await db
.select({
id: rfqs.id,
rfqCode: rfqs.rfqCode,
description: rfqs.description,
rfqType: rfqs.rfqType, // RFQ 타입 필드 추가
projectId: rfqs.projectId,
projectCode: projects.code,
projectName: projects.name,
})
.from(rfqs)
.leftJoin(projects, eq(rfqs.projectId, projects.id))
.where(finalWhere)
.orderBy(desc(rfqs.createdAt))
.limit(limit)
.offset(offset);
return {
rfqs: resultRfqs,
totalCount: Number(countResult?.count) || 0
};
} catch (error) {
console.error("Error fetching RFQs:", error);
return {
error: "Failed to fetch RFQs",
totalCount: 0
};
}
},
[cacheKey],
{
revalidate: 60, // 1분 캐시
tags: ["rfqs-query"],
}
)();
}
export async function getAllVendors() {
// Adjust the query as needed (add WHERE, ORDER, etc.)
const allVendors = await db.select().from(vendors)
return allVendors
}
/**
* Server action to associate items from an RFQ with a vendor
*
* @param rfqId - The ID of the RFQ containing items to associate
* @param vendorId - The ID of the vendor to associate items with
* @returns Object indicating success or failure
*/
export async function addItemToVendors(rfqId: number, vendorIds: number[]) {
try {
// Input validation
if (!vendorIds.length) {
return {
success: false,
error: "No vendors selected"
};
}
// 1. Find all itemCodes associated with the given rfqId using select
const rfqItemResults = await db
.select({ itemCode: rfqItems.itemCode })
.from(rfqItems)
.where(eq(rfqItems.rfqId, rfqId));
// Extract itemCodes
const itemCodes = rfqItemResults.map(item => item.itemCode);
if (itemCodes.length === 0) {
return {
success: false,
error: "No items found for this RFQ"
};
}
// 2. Find existing vendor-item combinations to avoid duplicates
const existingCombinations = await db
.select({
vendorId: vendorPossibleItems.vendorId,
itemCode: vendorPossibleItems.itemCode
})
.from(vendorPossibleItems)
.where(
and(
inArray(vendorPossibleItems.vendorId, vendorIds),
inArray(vendorPossibleItems.itemCode, itemCodes)
)
);
// Create a Set of existing combinations for easy lookups
const existingSet = new Set();
existingCombinations.forEach(combo => {
existingSet.add(`${combo.vendorId}-${combo.itemCode}`);
});
// 3. Prepare records to insert (only non-existing combinations)
const recordsToInsert = [];
for (const vendorId of vendorIds) {
for (const itemCode of itemCodes) {
const key = `${vendorId}-${itemCode}`;
if (!existingSet.has(key)) {
recordsToInsert.push({
vendorId,
itemCode,
// createdAt and updatedAt will be set by defaultNow()
});
}
}
}
// 4. Bulk insert if there are records to insert
let insertedCount = 0;
if (recordsToInsert.length > 0) {
const result = await db.insert(vendorPossibleItems).values(recordsToInsert);
insertedCount = recordsToInsert.length;
}
// 5. Revalidate to refresh data
revalidateTag("rfq-vendors");
// 6. Return success with counts
return {
success: true,
insertedCount,
totalPossibleItems: vendorIds.length * itemCodes.length,
vendorCount: vendorIds.length,
itemCount: itemCodes.length
};
} catch (error) {
console.error("Error adding items to vendors:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Unknown error"
};
}
}
/**
* 특정 평가에 대한 TBE 템플릿 파일 목록 조회
* evaluationId가 일치하고 vendorId가 null인 파일 목록
*/
export async function fetchTbeTemplateFiles(evaluationId: number) {
console.log(evaluationId, "evaluationId")
try {
const files = await db
.select({
id: rfqAttachments.id,
fileName: rfqAttachments.fileName,
filePath: rfqAttachments.filePath,
createdAt: rfqAttachments.createdAt,
})
.from(rfqAttachments)
.where(
and(
isNull(rfqAttachments.commentId),
isNull(rfqAttachments.vendorId),
eq(rfqAttachments.evaluationId, evaluationId),
// eq(rfqAttachments.vendorId, vendorId),
)
)
return { files, error: null }
} catch (error) {
console.error("Error fetching TBE template files:", error)
return {
files: [],
error: "템플릿 파일을 가져오는 중 오류가 발생했습니다."
}
}
}
/**
* 특정 TBE 템플릿 파일 다운로드를 위한 정보 조회
*/
export async function getTbeTemplateFileInfo(fileId: number) {
try {
const file = await db
.select({
fileName: rfqAttachments.fileName,
filePath: rfqAttachments.filePath,
})
.from(rfqAttachments)
.where(eq(rfqAttachments.id, fileId))
.limit(1)
if (!file.length) {
return { file: null, error: "파일을 찾을 수 없습니다." }
}
return { file: file[0], error: null }
} catch (error) {
console.error("Error getting TBE template file info:", error)
return {
file: null,
error: "파일 정보를 가져오는 중 오류가 발생했습니다."
}
}
}
/**
* TBE 응답 파일 업로드 처리
*/
export async function uploadTbeResponseFile(formData: FormData) {
try {
const file = formData.get("file") as File
const rfqId = parseInt(formData.get("rfqId") as string)
const vendorId = parseInt(formData.get("vendorId") as string)
const evaluationId = parseInt(formData.get("evaluationId") as string)
const vendorResponseId = parseInt(formData.get("vendorResponseId") as string)
if (!file || !rfqId || !vendorId || !evaluationId) {
return {
success: false,
error: "필수 필드가 누락되었습니다."
}
}
// 타임스탬프 기반 고유 파일명 생성
const timestamp = Date.now()
const originalName = file.name
const fileExtension = originalName.split(".").pop()
const fileName = `${originalName.split(".")[0]}-${timestamp}.${fileExtension}`
// 업로드 디렉토리 및 경로 정의
const uploadDir = join(process.cwd(), "rfq", "tbe-responses")
// 디렉토리가 없으면 생성
try {
await mkdir(uploadDir, { recursive: true })
} catch (error) {
// 이미 존재하면 무시
}
const filePath = join(uploadDir, fileName)
// 파일을 버퍼로 변환
const bytes = await file.arrayBuffer()
const buffer = Buffer.from(bytes)
// 파일을 서버에 저장
await writeFile(filePath, buffer)
// 먼저 vendorTechnicalResponses 테이블에 엔트리 생성
const technicalResponse = await db.insert(vendorTechnicalResponses)
.values({
responseId: vendorResponseId,
summary: "TBE 응답 파일 업로드", // 필요에 따라 수정
notes: `파일명: ${originalName}`,
})
.returning({ id: vendorTechnicalResponses.id });
// 생성된 기술 응답 ID 가져오기
const technicalResponseId = technicalResponse[0].id;
// 파일 정보를 데이터베이스에 저장
const dbFilePath = `/rfq/tbe-responses/${fileName}`
// vendorResponseAttachments 테이블 스키마에 맞게 데이터 삽입
await db.insert(vendorResponseAttachments)
.values({
// 오류 메시지를 기반으로 올바른 필드 이름 사용
// 테이블 스키마에 정의된 필드만 포함해야 함
responseId: vendorResponseId,
technicalResponseId: technicalResponseId,
// vendorId와 evaluationId 필드가 테이블에 있다면 포함, 없다면 제거
// vendorId: vendorId,
// evaluationId: evaluationId,
fileName: originalName,
filePath: dbFilePath,
uploadedAt: new Date(),
});
// 경로 재검증 (캐시된 데이터 새로고침)
revalidatePath(`/rfq/${rfqId}/tbe`)
revalidateTag(`tbe-vendors-${vendorId}`)
return {
success: true,
message: "파일이 성공적으로 업로드되었습니다."
}
} catch (error) {
console.error("Error uploading file:", error)
return {
success: false,
error: "파일 업로드에 실패했습니다."
}
}
}
export async function getTbeSubmittedFiles(responseId: number) {
try {
// First, get the technical response IDs where vendorResponseId matches responseId
const technicalResponses = await db
.select({
id: vendorTechnicalResponses.id,
})
.from(vendorTechnicalResponses)
.where(
eq(vendorTechnicalResponses.responseId, responseId)
)
if (technicalResponses.length === 0) {
return { files: [], error: null }
}
// Extract the IDs from the result
const technicalResponseIds = technicalResponses.map(tr => tr.id)
// Then get attachments where technicalResponseId matches any of the IDs we found
const files = await db
.select({
id: vendorResponseAttachments.id,
fileName: vendorResponseAttachments.fileName,
filePath: vendorResponseAttachments.filePath,
uploadedAt: vendorResponseAttachments.uploadedAt,
fileType: vendorResponseAttachments.fileType,
attachmentType: vendorResponseAttachments.attachmentType,
description: vendorResponseAttachments.description,
})
.from(vendorResponseAttachments)
.where(
inArray(vendorResponseAttachments.technicalResponseId, technicalResponseIds)
)
.orderBy(vendorResponseAttachments.uploadedAt)
return { files, error: null }
} catch (error) {
return { files: [], error: 'Failed to fetch TBE submitted files' }
}
}
export async function getTbeFilesForVendor(rfqId: number, vendorId: number) {
try {
// Step 1: Get responseId from vendor_responses table
const response = await db
.select({
id: vendorResponses.id,
})
.from(vendorResponses)
.where(
and(
eq(vendorResponses.rfqId, rfqId),
eq(vendorResponses.vendorId, vendorId)
)
)
.limit(1);
if (!response || response.length === 0) {
return { files: [], error: 'No vendor response found' };
}
const responseId = response[0].id;
// Step 2: Get the technical response IDs
const technicalResponses = await db
.select({
id: vendorTechnicalResponses.id,
})
.from(vendorTechnicalResponses)
.where(
eq(vendorTechnicalResponses.responseId, responseId)
);
if (technicalResponses.length === 0) {
return { files: [], error: null };
}
// Extract the IDs from the result
const technicalResponseIds = technicalResponses.map(tr => tr.id);
// Step 3: Get attachments where technicalResponseId matches any of the IDs
const files = await db
.select({
id: vendorResponseAttachments.id,
fileName: vendorResponseAttachments.fileName,
filePath: vendorResponseAttachments.filePath,
uploadedAt: vendorResponseAttachments.uploadedAt,
fileType: vendorResponseAttachments.fileType,
attachmentType: vendorResponseAttachments.attachmentType,
description: vendorResponseAttachments.description,
})
.from(vendorResponseAttachments)
.where(
inArray(vendorResponseAttachments.technicalResponseId, technicalResponseIds)
)
.orderBy(vendorResponseAttachments.uploadedAt);
return { files, error: null };
} catch (error) {
return { files: [], error: 'Failed to fetch vendor files' };
}
}
export async function getAllTBE(input: GetTBESchema) {
return unstable_cache(
async () => {
// 1) 페이징
const offset = ((input.page ?? 1) - 1) * (input.perPage ?? 10)
const limit = input.perPage ?? 10
// 2) 고급 필터
const advancedWhere = filterColumns({
table: vendorTbeView,
filters: input.filters ?? [],
joinOperator: input.joinOperator ?? "and",
})
// 3) 글로벌 검색
let globalWhere
if (input.search) {
const s = `%${input.search}%`
globalWhere = or(
sql`${vendorTbeView.vendorName} ILIKE ${s}`,
sql`${vendorTbeView.vendorCode} ILIKE ${s}`,
sql`${vendorTbeView.email} ILIKE ${s}`,
sql`${vendorTbeView.rfqCode} ILIKE ${s}`,
sql`${vendorTbeView.projectCode} ILIKE ${s}`,
sql`${vendorTbeView.projectName} ILIKE ${s}`
)
}
// 4) REJECTED 아니거나 NULL
const notRejected = or(
ne(vendorTbeView.rfqVendorStatus, "REJECTED"),
isNull(vendorTbeView.rfqVendorStatus)
)
// 5) rfqType 필터 추가
const rfqTypeFilter = input.rfqType ? eq(vendorTbeView.rfqType, input.rfqType) : undefined
// 6) finalWhere - rfqType 필터 추가
const finalWhere = and(
notRejected,
advancedWhere,
globalWhere,
rfqTypeFilter // 새로 추가된 rfqType 필터
)
// 6) 정렬
const orderBy = input.sort?.length
? input.sort.map((s) => {
const col = (vendorTbeView as any)[s.id]
return s.desc ? desc(col) : asc(col)
})
: [desc(vendorTbeView.rfqId), asc(vendorTbeView.vendorId)] // Default sort by newest RFQ first
// 7) 메인 SELECT
const [rows, total] = await db.transaction(async (tx) => {
const data = await tx
.select({
// 원하는 컬럼들
id: vendorTbeView.vendorId,
tbeId: vendorTbeView.tbeId,
vendorId: vendorTbeView.vendorId,
vendorName: vendorTbeView.vendorName,
vendorCode: vendorTbeView.vendorCode,
address: vendorTbeView.address,
country: vendorTbeView.country,
email: vendorTbeView.email,
website: vendorTbeView.website,
vendorStatus: vendorTbeView.vendorStatus,
rfqId: vendorTbeView.rfqId,
rfqCode: vendorTbeView.rfqCode,
projectCode: vendorTbeView.projectCode,
projectName: vendorTbeView.projectName,
description: vendorTbeView.description,
dueDate: vendorTbeView.dueDate,
rfqVendorStatus: vendorTbeView.rfqVendorStatus,
rfqVendorUpdated: vendorTbeView.rfqVendorUpdated,
tbeResult: vendorTbeView.tbeResult,
tbeNote: vendorTbeView.tbeNote,
tbeUpdated: vendorTbeView.tbeUpdated,
})
.from(vendorTbeView)
.where(finalWhere)
.orderBy(...orderBy)
.offset(offset)
.limit(limit)
const [{ count }] = await tx
.select({ count: sql<number>`count(*)`.as("count") })
.from(vendorTbeView)
.where(finalWhere)
return [data, Number(count)]
})
if (!rows.length) {
return { data: [], pageCount: 0 }
}
// 8) Get distinct rfqIds and vendorIds - filter out nulls
const distinctVendorIds = [...new Set(rows.map((r) => r.vendorId).filter(Boolean))] as number[];
const distinctRfqIds = [...new Set(rows.map((r) => r.rfqId).filter(Boolean))] as number[];
// 9) Comments 조회
const commentsConditions = [isNotNull(rfqComments.evaluationId)];
// 배열이 비어있지 않을 때만 조건 추가
if (distinctRfqIds.length > 0) {
commentsConditions.push(inArray(rfqComments.rfqId, distinctRfqIds));
}
if (distinctVendorIds.length > 0) {
commentsConditions.push(inArray(rfqComments.vendorId, distinctVendorIds));
}
const commAll = await db
.select({
id: rfqComments.id,
commentText: rfqComments.commentText,
vendorId: rfqComments.vendorId,
rfqId: rfqComments.rfqId,
evaluationId: rfqComments.evaluationId,
createdAt: rfqComments.createdAt,
commentedBy: rfqComments.commentedBy,
evalType: rfqEvaluations.evalType,
})
.from(rfqComments)
.innerJoin(
rfqEvaluations,
and(
eq(rfqEvaluations.id, rfqComments.evaluationId),
eq(rfqEvaluations.evalType, "TBE")
)
)
.where(and(...commentsConditions));
// 9-A) Create a composite key (rfqId-vendorId) -> comments mapping
const commByCompositeKey = new Map<string, any[]>()
for (const c of commAll) {
if (!c.rfqId || !c.vendorId) continue;
const compositeKey = `${c.rfqId}-${c.vendorId}`;
if (!commByCompositeKey.has(compositeKey)) {
commByCompositeKey.set(compositeKey, [])
}
commByCompositeKey.get(compositeKey)!.push({
id: c.id,
commentText: c.commentText,
vendorId: c.vendorId,
evaluationId: c.evaluationId,
createdAt: c.createdAt,
commentedBy: c.commentedBy,
})
}
// 10) Responses 조회
const responsesAll = await db
.select({
id: vendorResponses.id,
rfqId: vendorResponses.rfqId,
vendorId: vendorResponses.vendorId
})
.from(vendorResponses)
.where(
and(
inArray(vendorResponses.rfqId, distinctRfqIds),
inArray(vendorResponses.vendorId, distinctVendorIds)
)
);
// Group responses by rfqId-vendorId composite key
const responsesByCompositeKey = new Map<string, number[]>();
for (const resp of responsesAll) {
const compositeKey = `${resp.rfqId}-${resp.vendorId}`;
if (!responsesByCompositeKey.has(compositeKey)) {
responsesByCompositeKey.set(compositeKey, []);
}
responsesByCompositeKey.get(compositeKey)!.push(resp.id);
}
// Get all responseIds
const allResponseIds = responsesAll.map(r => r.id);
// 11) Get technicalResponses for these responseIds
const technicalResponsesAll = await db
.select({
id: vendorTechnicalResponses.id,
responseId: vendorTechnicalResponses.responseId
})
.from(vendorTechnicalResponses)
.where(inArray(vendorTechnicalResponses.responseId, allResponseIds));
// Create mapping from responseId to technicalResponseIds
const technicalResponseIdsByResponseId = new Map<number, number[]>();
for (const tr of technicalResponsesAll) {
if (!technicalResponseIdsByResponseId.has(tr.responseId)) {
technicalResponseIdsByResponseId.set(tr.responseId, []);
}
technicalResponseIdsByResponseId.get(tr.responseId)!.push(tr.id);
}
// Get all technicalResponseIds
const allTechnicalResponseIds = technicalResponsesAll.map(tr => tr.id);
// 12) Get attachments for these technicalResponseIds
const filesAll = await db
.select({
id: vendorResponseAttachments.id,
fileName: vendorResponseAttachments.fileName,
filePath: vendorResponseAttachments.filePath,
technicalResponseId: vendorResponseAttachments.technicalResponseId,
fileType: vendorResponseAttachments.fileType,
attachmentType: vendorResponseAttachments.attachmentType,
description: vendorResponseAttachments.description,
uploadedAt: vendorResponseAttachments.uploadedAt,
uploadedBy: vendorResponseAttachments.uploadedBy
})
.from(vendorResponseAttachments)
.where(
and(
inArray(vendorResponseAttachments.technicalResponseId, allTechnicalResponseIds),
isNotNull(vendorResponseAttachments.technicalResponseId)
)
);
// Create mapping from technicalResponseId to attachments
const filesByTechnicalResponseId = new Map<number, any[]>();
for (const file of filesAll) {
if (file.technicalResponseId === null) continue;
if (!filesByTechnicalResponseId.has(file.technicalResponseId)) {
filesByTechnicalResponseId.set(file.technicalResponseId, []);
}
filesByTechnicalResponseId.get(file.technicalResponseId)!.push({
id: file.id,
fileName: file.fileName,
filePath: file.filePath,
fileType: file.fileType,
attachmentType: file.attachmentType,
description: file.description,
uploadedAt: file.uploadedAt,
uploadedBy: file.uploadedBy
});
}
// 13) Create the final filesByCompositeKey map
const filesByCompositeKey = new Map<string, any[]>();
for (const [compositeKey, responseIds] of responsesByCompositeKey.entries()) {
filesByCompositeKey.set(compositeKey, []);
for (const responseId of responseIds) {
const technicalResponseIds = technicalResponseIdsByResponseId.get(responseId) || [];
for (const technicalResponseId of technicalResponseIds) {
const files = filesByTechnicalResponseId.get(technicalResponseId) || [];
filesByCompositeKey.get(compositeKey)!.push(...files);
}
}
}
// 14) 최종 합치기
const final = rows.map((row) => {
const compositeKey = `${row.rfqId}-${row.vendorId}`;
return {
...row,
dueDate: row.dueDate ? new Date(row.dueDate) : null,
comments: commByCompositeKey.get(compositeKey) ?? [],
files: filesByCompositeKey.get(compositeKey) ?? [],
};
})
const pageCount = Math.ceil(total / limit)
return { data: final, pageCount }
},
[JSON.stringify(input)],
{
revalidate: 3600,
tags: ["all-tbe-vendors"],
}
)()
}
export async function getCBE(input: GetCBESchema, rfqId: number) {
return unstable_cache(
async () => {
// [1] 페이징
const offset = ((input.page ?? 1) - 1) * (input.perPage ?? 10);
const limit = input.perPage ?? 10;
// [2] 고급 필터
const advancedWhere = filterColumns({
table: vendorCbeView,
filters: input.filters ?? [],
joinOperator: input.joinOperator ?? "and",
});
// [3] 글로벌 검색
let globalWhere;
if (input.search) {
const s = `%${input.search}%`;
globalWhere = or(
sql`${vendorCbeView.vendorName} ILIKE ${s}`,
sql`${vendorCbeView.vendorCode} ILIKE ${s}`,
sql`${vendorCbeView.email} ILIKE ${s}`
);
}
// [4] REJECTED 아니거나 NULL
const notRejected = or(
ne(vendorCbeView.rfqVendorStatus, "REJECTED"),
isNull(vendorCbeView.rfqVendorStatus)
);
// [5] 최종 where
const finalWhere = and(
eq(vendorCbeView.rfqId, rfqId),
notRejected,
advancedWhere,
globalWhere
);
// [6] 정렬
const orderBy = input.sort?.length
? input.sort.map((s) => {
// vendor_cbe_view 컬럼 중 정렬 대상이 되는 것만 매핑
const col = (vendorCbeView as any)[s.id];
return s.desc ? desc(col) : asc(col);
})
: [asc(vendorCbeView.vendorId)];
// [7] 메인 SELECT
const [rows, total] = await db.transaction(async (tx) => {
const data = await tx
.select({
// 필요한 컬럼만 추출
id: vendorCbeView.vendorId,
cbeId: vendorCbeView.cbeId,
vendorId: vendorCbeView.vendorId,
vendorName: vendorCbeView.vendorName,
vendorCode: vendorCbeView.vendorCode,
address: vendorCbeView.address,
country: vendorCbeView.country,
email: vendorCbeView.email,
website: vendorCbeView.website,
vendorStatus: vendorCbeView.vendorStatus,
rfqId: vendorCbeView.rfqId,
rfqCode: vendorCbeView.rfqCode,
projectCode: vendorCbeView.projectCode,
projectName: vendorCbeView.projectName,
description: vendorCbeView.description,
dueDate: vendorCbeView.dueDate,
rfqVendorStatus: vendorCbeView.rfqVendorStatus,
rfqVendorUpdated: vendorCbeView.rfqVendorUpdated,
cbeResult: vendorCbeView.cbeResult,
cbeNote: vendorCbeView.cbeNote,
cbeUpdated: vendorCbeView.cbeUpdated,
// 상업평가 정보
totalCost: vendorCbeView.totalCost,
currency: vendorCbeView.currency,
paymentTerms: vendorCbeView.paymentTerms,
incoterms: vendorCbeView.incoterms,
deliverySchedule: vendorCbeView.deliverySchedule,
})
.from(vendorCbeView)
.where(finalWhere)
.orderBy(...orderBy)
.offset(offset)
.limit(limit);
const [{ count }] = await tx
.select({ count: sql<number>`count(*)`.as("count") })
.from(vendorCbeView)
.where(finalWhere);
return [data, Number(count)];
});
if (!rows.length) {
return { data: [], pageCount: 0 };
}
// [8] Comments 조회
// TBE 에서는 rfqComments + rfqEvaluations(evalType="TBE") 를 조인했지만,
// CBE는 cbeEvaluations 또는 evalType="CBE"를 기준으로 바꾸면 됩니다.
// 만약 cbeEvaluations.id 를 evaluationId 로 참조한다면 아래와 같이 innerJoin:
const distinctVendorIds = [...new Set(rows.map((r) => r.vendorId))];
const commAll = await db
.select({
id: rfqComments.id,
commentText: rfqComments.commentText,
vendorId: rfqComments.vendorId,
evaluationId: rfqComments.evaluationId,
createdAt: rfqComments.createdAt,
commentedBy: rfqComments.commentedBy,
// cbeEvaluations에는 evalType 컬럼이 별도로 없을 수도 있음(프로젝트 구조에 맞게 수정)
// evalType: cbeEvaluations.evalType,
})
.from(rfqComments)
.innerJoin(
cbeEvaluations,
eq(cbeEvaluations.id, rfqComments.evaluationId)
)
.where(
and(
isNotNull(rfqComments.evaluationId),
eq(rfqComments.rfqId, rfqId),
inArray(rfqComments.vendorId, distinctVendorIds)
)
);
// vendorId -> comments grouping
const commByVendorId = new Map<number, any[]>();
for (const c of commAll) {
const vid = c.vendorId!;
if (!commByVendorId.has(vid)) {
commByVendorId.set(vid, []);
}
commByVendorId.get(vid)!.push({
id: c.id,
commentText: c.commentText,
vendorId: c.vendorId,
evaluationId: c.evaluationId,
createdAt: c.createdAt,
commentedBy: c.commentedBy,
});
}
// [9] CBE 파일 조회 (프로젝트에 따라 구조가 달라질 수 있음)
// - TBE는 vendorTechnicalResponses 기준
// - CBE는 vendorCommercialResponses(가정) 등이 있을 수 있음
// - 여기서는 예시로 "동일한 vendorResponses + vendorResponseAttachments" 라고 가정
// Step 1: vendorResponses 가져오기 (rfqId + vendorIds)
const responsesAll = await db
.select({
id: vendorResponses.id,
vendorId: vendorResponses.vendorId,
})
.from(vendorResponses)
.where(
and(
eq(vendorResponses.rfqId, rfqId),
inArray(vendorResponses.vendorId, distinctVendorIds)
)
);
// Group responses by vendorId
const responsesByVendorId = new Map<number, number[]>();
for (const resp of responsesAll) {
if (!responsesByVendorId.has(resp.vendorId)) {
responsesByVendorId.set(resp.vendorId, []);
}
responsesByVendorId.get(resp.vendorId)!.push(resp.id);
}
// Step 2: responseIds
const allResponseIds = responsesAll.map((r) => r.id);
const commercialResponsesAll = await db
.select({
id: vendorCommercialResponses.id,
responseId: vendorCommercialResponses.responseId,
})
.from(vendorCommercialResponses)
.where(inArray(vendorCommercialResponses.responseId, allResponseIds));
const commercialResponseIdsByResponseId = new Map<number, number[]>();
for (const cr of commercialResponsesAll) {
if (!commercialResponseIdsByResponseId.has(cr.responseId)) {
commercialResponseIdsByResponseId.set(cr.responseId, []);
}
commercialResponseIdsByResponseId.get(cr.responseId)!.push(cr.id);
}
const allCommercialResponseIds = commercialResponsesAll.map((cr) => cr.id);
// 여기서는 예시로 TBE와 마찬가지로 vendorResponseAttachments를
// 직접 responseId로 관리한다고 가정(혹은 commercialResponseId로 연결)
// Step 3: vendorResponseAttachments 조회
const filesAll = await db
.select({
id: vendorResponseAttachments.id,
fileName: vendorResponseAttachments.fileName,
filePath: vendorResponseAttachments.filePath,
responseId: vendorResponseAttachments.responseId,
fileType: vendorResponseAttachments.fileType,
attachmentType: vendorResponseAttachments.attachmentType,
description: vendorResponseAttachments.description,
uploadedAt: vendorResponseAttachments.uploadedAt,
uploadedBy: vendorResponseAttachments.uploadedBy,
})
.from(vendorResponseAttachments)
.where(
and(
inArray(vendorResponseAttachments.responseId, allCommercialResponseIds),
isNotNull(vendorResponseAttachments.responseId)
)
);
// Step 4: responseId -> files
const filesByResponseId = new Map<number, any[]>();
for (const file of filesAll) {
const rid = file.responseId!;
if (!filesByResponseId.has(rid)) {
filesByResponseId.set(rid, []);
}
filesByResponseId.get(rid)!.push({
id: file.id,
fileName: file.fileName,
filePath: file.filePath,
fileType: file.fileType,
attachmentType: file.attachmentType,
description: file.description,
uploadedAt: file.uploadedAt,
uploadedBy: file.uploadedBy,
});
}
// Step 5: vendorId -> files
const filesByVendorId = new Map<number, any[]>();
for (const [vendorId, responseIds] of responsesByVendorId.entries()) {
filesByVendorId.set(vendorId, []);
for (const responseId of responseIds) {
const files = filesByResponseId.get(responseId) || [];
filesByVendorId.get(vendorId)!.push(...files);
}
}
// [10] 최종 데이터 합치기
const final = rows.map((row) => ({
...row,
dueDate: row.dueDate ? new Date(row.dueDate) : null,
comments: commByVendorId.get(row.vendorId) ?? [],
files: filesByVendorId.get(row.vendorId) ?? [],
}));
const pageCount = Math.ceil(total / limit);
return { data: final, pageCount };
},
// 캐싱 키 & 옵션
[JSON.stringify({ input, rfqId })],
{
revalidate: 3600,
tags: ["cbe-vendors"],
}
)();
}
export async function generateNextRfqCode(rfqType: RfqType): Promise<{ code: string; error?: string }> {
try {
if (!rfqType) {
return { code: "", error: 'RFQ 타입이 필요합니다' };
}
// 현재 연도 가져오기
const currentYear = new Date().getFullYear();
// 현재 연도와 타입에 맞는 최신 RFQ 코드 찾기
const latestRfqs = await db.select({ rfqCode: rfqs.rfqCode })
.from(rfqs)
.where(and(
sql`SUBSTRING(${rfqs.rfqCode}, 5, 4) = ${currentYear.toString()}`,
eq(rfqs.rfqType, rfqType)
))
.orderBy(desc(rfqs.rfqCode))
.limit(1);
let sequenceNumber = 1;
if (latestRfqs.length > 0 && latestRfqs[0].rfqCode) {
// null 체크 추가 - TypeScript 오류 해결
const latestCode = latestRfqs[0].rfqCode;
const matches = latestCode.match(/[A-Z]+-\d{4}-(\d{3})/);
if (matches && matches[1]) {
sequenceNumber = parseInt(matches[1], 10) + 1;
}
}
// 새로운 RFQ 코드 포맷팅
const typePrefix = rfqType === RfqType.BUDGETARY ? 'BUD' :
rfqType === RfqType.PURCHASE_BUDGETARY ? 'PBU' : 'RFQ';
const newCode = `${typePrefix}-${currentYear}-${String(sequenceNumber).padStart(3, '0')}`;
return { code: newCode };
} catch (error) {
console.error('Error generating next RFQ code:', error);
return { code: "", error: '코드 생성에 실패했습니다' };
}
}
|