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
|
'use server'
import db from '@/db/db'
import { biddings, prItemsForBidding, biddingDocuments, biddingCompanies, vendors, companyPrItemBids, companyConditionResponses, vendorSelectionResults, priceAdjustmentForms, users } from '@/db/schema'
import { specificationMeetings } from '@/db/schema/bidding'
import { eq, and, sql, desc, ne } from 'drizzle-orm'
import { revalidatePath, revalidateTag } from 'next/cache'
import { unstable_cache } from "@/lib/unstable-cache";
import { sendEmail } from '@/lib/mail/sendEmail'
import { saveFile } from '@/lib/file-stroage'
// userId를 user.name으로 변환하는 유틸리티 함수
async function getUserNameById(userId: string): Promise<string> {
try {
const user = await db
.select({ name: users.name })
.from(users)
.where(eq(users.id, parseInt(userId)))
.limit(1)
return user[0]?.name || userId // user.name이 없으면 userId를 그대로 반환
} catch (error) {
console.error('Failed to get user name:', error)
return userId // 에러 시 userId를 그대로 반환
}
}
// 데이터 조회 함수들
export interface BiddingDetailData {
bidding: Awaited<ReturnType<typeof getBiddingById>>
quotationDetails: QuotationDetails | null
quotationVendors: QuotationVendor[]
prItems: Awaited<ReturnType<typeof getPRItemsForBidding>>
}
// getBiddingById 함수 임포트 (기존 함수 재사용)
import { getBiddingById } from '@/lib/bidding/service'
// Promise.all을 사용하여 모든 데이터를 병렬로 조회 (캐시 적용)
export async function getBiddingDetailData(biddingId: number): Promise<BiddingDetailData> {
return unstable_cache(
async () => {
const [
bidding,
quotationDetails,
quotationVendors,
prItems
] = await Promise.all([
getBiddingById(biddingId),
getQuotationDetails(biddingId),
getQuotationVendors(biddingId),
getPRItemsForBidding(biddingId)
])
return {
bidding,
quotationDetails,
quotationVendors,
prItems
}
},
[`bidding-detail-data-${biddingId}`],
{
tags: [`bidding-${biddingId}`, 'bidding-detail', 'quotation-vendors', 'pr-items']
}
)()
}
export interface QuotationDetails {
biddingId: number
estimatedPrice: number // 예상액
lowestQuote: number // 최저견적가
averageQuote: number // 평균견적가
targetPrice: number // 내정가
quotationCount: number // 견적 수
lastUpdated: string // 최종 업데이트일
}
export interface QuotationVendor {
id: number
biddingId: number
vendorId: number
vendorName: string
vendorCode: string
vendorEmail?: string // 벤더의 기본 이메일
contactPerson: string
contactEmail: string
contactPhone: string
quotationAmount: number // 견적금액
currency: string
submissionDate: string // 제출일
isWinner: boolean | null // 낙찰여부 (null: 미정, true: 낙찰, false: 탈락)
awardRatio: number | null // 발주비율
isBiddingParticipated: boolean | null // 본입찰 참여여부
invitationStatus: 'pending' | 'pre_quote_sent' | 'pre_quote_accepted' | 'pre_quote_declined' | 'pre_quote_submitted' | 'bidding_sent' | 'bidding_accepted' | 'bidding_declined' | 'bidding_cancelled' | 'bidding_submitted'
documents: Array<{
id: number
fileName: string
originalFileName: string
filePath: string
uploadedAt: string
}>
}
// 견적 시스템에서 내정가 및 관련 정보를 가져오는 함수 (캐시 적용)
export async function getQuotationDetails(biddingId: number): Promise<QuotationDetails | null> {
return unstable_cache(
async () => {
try {
// bidding_companies 테이블에서 견적 데이터를 집계
const quotationStats = await db
.select({
biddingId: biddingCompanies.biddingId,
estimatedPrice: sql<number>`AVG(${biddingCompanies.finalQuoteAmount})`.as('estimated_price'),
lowestQuote: sql<number>`MIN(${biddingCompanies.finalQuoteAmount})`.as('lowest_quote'),
averageQuote: sql<number>`AVG(${biddingCompanies.finalQuoteAmount})`.as('average_quote'),
targetPrice: sql<number>`AVG(${biddings.targetPrice})`.as('target_price'),
quotationCount: sql<number>`COUNT(*)`.as('quotation_count'),
lastUpdated: sql<string>`MAX(${biddingCompanies.updatedAt})`.as('last_updated')
})
.from(biddingCompanies)
.leftJoin(biddings, eq(biddingCompanies.biddingId, biddings.id))
.where(and(
eq(biddingCompanies.biddingId, biddingId),
sql`${biddingCompanies.finalQuoteAmount} IS NOT NULL`
))
.groupBy(biddingCompanies.biddingId)
.limit(1)
if (quotationStats.length === 0) {
return {
biddingId,
estimatedPrice: 0,
lowestQuote: 0,
averageQuote: 0,
targetPrice: 0,
quotationCount: 0,
lastUpdated: new Date().toISOString()
}
}
const stat = quotationStats[0]
return {
biddingId,
estimatedPrice: Number(stat.estimatedPrice) || 0,
lowestQuote: Number(stat.lowestQuote) || 0,
averageQuote: Number(stat.averageQuote) || 0,
targetPrice: Number(stat.targetPrice) || 0,
quotationCount: Number(stat.quotationCount) || 0,
lastUpdated: stat.lastUpdated || new Date().toISOString()
}
} catch (error) {
console.error('Failed to get quotation details:', error)
return null
}
},
[`quotation-details-${biddingId}`],
{
tags: [`bidding-${biddingId}`, 'quotation-details']
}
)()
}
// bidding_companies 테이블을 메인으로 vendors 테이블을 조인하여 협력업체 정보 조회
export async function getBiddingCompaniesData(biddingId: number) {
try {
const companies = await db
.select({
id: biddingCompanies.id,
biddingId: biddingCompanies.biddingId,
companyId: biddingCompanies.companyId,
companyName: vendors.vendorName,
companyCode: vendors.vendorCode,
invitationStatus: biddingCompanies.invitationStatus,
invitedAt: biddingCompanies.invitedAt,
respondedAt: biddingCompanies.respondedAt,
preQuoteAmount: biddingCompanies.preQuoteAmount,
preQuoteSubmittedAt: biddingCompanies.preQuoteSubmittedAt,
isPreQuoteSelected: biddingCompanies.isPreQuoteSelected,
finalQuoteAmount: biddingCompanies.finalQuoteAmount,
finalQuoteSubmittedAt: biddingCompanies.finalQuoteSubmittedAt,
isWinner: biddingCompanies.isWinner,
notes: biddingCompanies.notes,
contactPerson: biddingCompanies.contactPerson,
contactEmail: biddingCompanies.contactEmail,
contactPhone: biddingCompanies.contactPhone,
createdAt: biddingCompanies.createdAt,
updatedAt: biddingCompanies.updatedAt
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
.where(
and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.isPreQuoteSelected, true)
)
)
.orderBy(desc(biddingCompanies.finalQuoteAmount))
console.log(companies)
return companies
} catch (error) {
console.error('Failed to get bidding companies data:', error)
return []
}
}
// prItemsForBidding 테이블에서 품목 정보 조회 (캐시 적용)
export async function getPRItemsForBidding(biddingId: number) {
return unstable_cache(
async () => {
try {
const items = await db
.select()
.from(prItemsForBidding)
.where(eq(prItemsForBidding.biddingId, biddingId))
.orderBy(prItemsForBidding.id)
return items
} catch (error) {
console.error('Failed to get PR items for bidding:', error)
return []
}
},
[`pr-items-for-bidding-${biddingId}`],
{
tags: [`bidding-${biddingId}`, 'pr-items']
}
)()
}
// 견적 시스템에서 협력업체 정보를 가져오는 함수 (캐시 적용)
export async function getQuotationVendors(biddingId: number): Promise<QuotationVendor[]> {
return unstable_cache(
async () => {
try {
// bidding_companies 테이블을 메인으로 vendors를 조인하여 협력업체 정보 조회
const vendorsData = await db
.select({
id: biddingCompanies.id,
biddingId: biddingCompanies.biddingId,
vendorId: biddingCompanies.companyId,
vendorName: vendors.vendorName,
vendorCode: vendors.vendorCode,
vendorEmail: vendors.email, // 벤더의 기본 이메일
contactPerson: biddingCompanies.contactPerson,
contactEmail: biddingCompanies.contactEmail,
contactPhone: biddingCompanies.contactPhone,
quotationAmount: biddingCompanies.finalQuoteAmount,
currency: sql<string>`'KRW'`,
submissionDate: biddingCompanies.finalQuoteSubmittedAt,
isWinner: biddingCompanies.isWinner,
// awardRatio: sql<number>`CASE WHEN ${biddingCompanies.isWinner} THEN 100 ELSE 0 END`,
awardRatio: biddingCompanies.awardRatio,
isBiddingParticipated: biddingCompanies.isBiddingParticipated,
invitationStatus: biddingCompanies.invitationStatus,
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
.where(and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.isPreQuoteSelected, true) // 본입찰 선정된 업체만 조회
))
.orderBy(desc(biddingCompanies.finalQuoteAmount))
return vendorsData.map(vendor => ({
id: vendor.id,
biddingId: vendor.biddingId,
vendorId: vendor.vendorId,
vendorName: vendor.vendorName || `Vendor ${vendor.vendorId}`,
vendorCode: vendor.vendorCode || '',
vendorEmail: vendor.vendorEmail || '', // 벤더의 기본 이메일
contactPerson: vendor.contactPerson || '',
contactEmail: vendor.contactEmail || '',
contactPhone: vendor.contactPhone || '',
quotationAmount: Number(vendor.quotationAmount) || 0,
currency: vendor.currency,
submissionDate: vendor.submissionDate ? (vendor.submissionDate instanceof Date ? vendor.submissionDate.toISOString().split('T')[0] : String(vendor.submissionDate).split('T')[0]) : '',
isWinner: vendor.isWinner,
awardRatio: vendor.awardRatio ? Number(vendor.awardRatio) : null,
isBiddingParticipated: vendor.isBiddingParticipated,
invitationStatus: vendor.invitationStatus,
documents: [], // 빈 배열로 초기화
}))
} catch (error) {
console.error('Failed to get quotation vendors:', error)
return []
}
},
[`quotation-vendors-${biddingId}`],
{
tags: [`bidding-${biddingId}`, 'quotation-vendors']
}
)()
}
// 사전견적 데이터 조회 (내정가 산정용)
export async function getPreQuoteData(biddingId: number) {
try {
const preQuotes = await db
.select({
id: biddingCompanies.id,
companyId: biddingCompanies.companyId,
vendorName: vendors.vendorName,
preQuoteAmount: biddingCompanies.preQuoteAmount,
submittedAt: biddingCompanies.preQuoteSubmittedAt,
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
.where(and(
eq(biddingCompanies.biddingId, biddingId),
sql`${biddingCompanies.preQuoteAmount} IS NOT NULL AND ${biddingCompanies.preQuoteAmount} > 0`
))
.orderBy(biddingCompanies.preQuoteAmount)
if (preQuotes.length === 0) {
return {
quotes: [],
lowestQuote: null,
highestQuote: null,
averageQuote: null,
quotationCount: 0
}
}
const amounts = preQuotes
.map(q => Number(q.preQuoteAmount))
.filter(amount => !isNaN(amount) && amount > 0)
console.log('Pre-quote amounts:', amounts)
if (amounts.length === 0) {
return {
quotes: preQuotes,
lowestQuote: null,
highestQuote: null,
averageQuote: null,
quotationCount: 0
}
}
const lowestQuote = Math.min(...amounts)
const highestQuote = Math.max(...amounts)
const averageQuote = amounts.reduce((sum, amount) => sum + amount, 0) / amounts.length
console.log('Calculated quotes:', { lowestQuote, highestQuote, averageQuote })
return {
quotes: preQuotes,
lowestQuote,
highestQuote,
averageQuote,
quotationCount: amounts.length
}
} catch (error) {
console.error('Failed to get pre-quote data:', error)
return {
quotes: [],
lowestQuote: null,
highestQuote: null,
averageQuote: null,
quotationCount: 0
}
}
}
// 입찰유형별 내정가 자동 산정 로직
export async function calculateTargetPrice(
biddingType: string,
budget: number | null,
lowestQuote: number | null,
highestQuote: number | null
): Promise<{ targetPrice: number; criteria: string }> {
const results: Array<{ price: number; description: string }> = []
// 입찰유형별 로직
switch (biddingType) {
case 'equipment':
case 'construction':
case 'service':
case 'lease':
case 'steel_stock':
case 'piping': {
// 예산가 85%, 최저견적가 85% 중 최저가 (직전실적가 95% 제외)
if (budget) {
results.push({ price: budget * 0.85, description: '예산가 85%' })
}
if (lowestQuote) {
results.push({ price: lowestQuote * 0.85, description: '최저견적가 85%' })
}
break
}
case 'transport': {
// 예산가 85%, 최저견적가 85% 중 최저가 (직전실적가 95% 제외)
// 만약 예산이 없을 경우 최저견적가의 70%
if (budget) {
results.push({ price: budget * 0.85, description: '예산가 85%' })
}
if (lowestQuote) {
if (budget) {
results.push({ price: lowestQuote * 0.85, description: '최저견적가 85%' })
} else {
results.push({ price: lowestQuote * 0.70, description: '최저견적가 70% (예산 없음)' })
}
}
break
}
case 'waste': {
// 예산가 85%, 최저견적가 70% 중 최저가 (직전실적가 95% 제외)
if (budget) {
results.push({ price: budget * 0.85, description: '예산가 85%' })
}
if (lowestQuote) {
results.push({ price: lowestQuote * 0.70, description: '최저견적가 70%' })
}
break
}
case 'sale': {
// 최고견적가 130% (직전실적가 105% 제외)
if (highestQuote) {
results.push({ price: highestQuote * 1.30, description: '최고견적가 130%' })
}
break
}
default: {
// 기본: 최저견적가 85%
if (lowestQuote) {
results.push({ price: lowestQuote * 0.85, description: '최저견적가 85%' })
}
break
}
}
if (results.length === 0) {
return {
targetPrice: 0,
criteria: '산정 가능한 데이터가 없습니다.'
}
}
// 매각의 경우 최고가, 나머지는 최저가
const prices = results.map(r => r.price).filter(p => !isNaN(p) && isFinite(p))
if (prices.length === 0) {
return {
targetPrice: 0,
criteria: '유효한 가격 데이터가 없습니다.'
}
}
const targetPrice = biddingType === 'sale'
? Math.max(...prices)
: Math.min(...prices)
if (!isFinite(targetPrice) || isNaN(targetPrice)) {
return {
targetPrice: 0,
criteria: '내정가 계산 오류가 발생했습니다.'
}
}
const selectedResult = results.find(r => r.price === targetPrice)
const criteria = `입찰유형: ${biddingType} - ${selectedResult?.description || ''}로 산정`
return {
targetPrice: Math.round(targetPrice),
criteria
}
}
// 내정가 자동 산정 및 업데이트
export async function calculateAndUpdateTargetPrice(
biddingId: number
) {
try {
// 입찰 정보 조회
const bidding = await getBiddingById(biddingId)
if (!bidding) {
return { success: false, error: '입찰 정보를 찾을 수 없습니다.' }
}
// 사전견적 데이터 조회
const preQuoteData = await getPreQuoteData(biddingId)
if (preQuoteData.quotationCount === 0) {
return { success: false, error: '사전견적 데이터가 없습니다.' }
}
// 내정가 산정
console.log('Bidding data for calculation:', {
biddingType: bidding.biddingType,
budget: bidding.budget,
preQuoteData
})
const { targetPrice, criteria } = await calculateTargetPrice(
bidding.biddingType || '',
bidding.budget ? Number(bidding.budget) : null,
preQuoteData.lowestQuote,
preQuoteData.highestQuote
)
console.log('Calculated target price:', { targetPrice, criteria })
if (!targetPrice || targetPrice <= 0 || isNaN(targetPrice)) {
return { success: false, error: `내정가 산정에 실패했습니다. (계산된 값: ${targetPrice})` }
}
// 내정가 업데이트
const updateResult = await updateTargetPrice(biddingId, targetPrice, criteria)
if (updateResult.success) {
// // 내정가 산정 후 입찰 상태를 set_target_price로 변경 (received_quotation 상태에서만)
// await db
// .update(biddings)
// .set({
// status: 'set_target_price',
// updatedAt: new Date()
// })
// .where(and(
// eq(biddings.id, biddingId)
// ))
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
return {
success: true,
message: '내정가가 자동으로 산정되었습니다.',
data: {
targetPrice,
criteria,
preQuoteData
}
}
} else {
return updateResult
}
} catch (error) {
console.error('Failed to calculate and update target price:', error)
return { success: false, error: '내정가 자동 산정에 실패했습니다.' }
}
}
// 내정가 수동 업데이트 (실제 저장)
export async function updateTargetPrice(
biddingId: number,
targetPrice: number,
targetPriceCalculationCriteria: string,
) {
try {
// 입력값 검증
if (!targetPrice || targetPrice <= 0 || isNaN(targetPrice)) {
return { success: false, error: `유효하지 않은 내정가입니다: ${targetPrice}` }
}
console.log('Updating target price:', { biddingId, targetPrice, targetPriceCalculationCriteria })
await db
.update(biddings)
.set({
targetPrice: Math.round(targetPrice).toString(),
targetPriceCalculationCriteria: targetPriceCalculationCriteria,
updatedAt: new Date()
})
.where(eq(biddings.id, biddingId))
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
revalidateTag('quotation-details')
revalidatePath(`/evcp/bid/${biddingId}`)
return { success: true, message: '내정가가 성공적으로 업데이트되었습니다.' }
} catch (error) {
console.error('Failed to update target price:', error)
return { success: false, error: '내정가 업데이트에 실패했습니다.' }
}
}
// 본입찰용 업체 수정 (간소화 버전 - 발주비율만 UI에서 수정 가능, 견적금액/통화는 기존값 유지)
export async function updateBiddingDetailVendor(
biddingCompanyId: number,
quotationAmount: number, // 기존값 유지용
currency: string, // 기존값 유지용
awardRatio: number, // UI에서 수정 가능
) {
try {
const result = await db.update(biddingCompanies)
.set({
finalQuoteAmount: quotationAmount.toString(),
awardRatio: awardRatio.toString(),
isWinner: awardRatio > 0,
updatedAt: new Date(),
})
.where(eq(biddingCompanies.id, biddingCompanyId))
.returning({ biddingId: biddingCompanies.biddingId })
// 캐시 무효화
if (result.length > 0) {
const biddingId = result[0].biddingId
revalidateTag(`bidding-${biddingId}`)
revalidateTag('quotation-vendors')
revalidateTag('quotation-details')
revalidatePath(`/evcp/bid/${biddingId}`)
}
return {
success: true,
message: '업체 정보가 성공적으로 수정되었습니다.',
}
} catch (error) {
console.error('Failed to update bidding detail vendor:', error)
return {
success: false,
error: error instanceof Error ? error.message : '업체 정보 수정에 실패했습니다.'
}
}
}
// 본입찰용 업체 추가
export async function createBiddingDetailVendor(
biddingId: number,
vendorId: number,
isPriceAdjustmentApplicableQuestion?: boolean
) {
try {
const result = await db.transaction(async (tx) => {
// 1. biddingCompanies 레코드 생성 (본입찰 선정 기본값 true)
const biddingCompanyResult = await tx.insert(biddingCompanies).values({
biddingId: biddingId,
companyId: vendorId,
invitationStatus: 'pending', // 초대 대기
isPreQuoteSelected: true, // 본입찰 등록 기본값
isWinner: null, // 미정 상태로 초기화 0916
isPriceAdjustmentApplicableQuestion: isPriceAdjustmentApplicableQuestion ?? false,
createdAt: new Date(),
updatedAt: new Date(),
}).returning({ id: biddingCompanies.id })
if (biddingCompanyResult.length === 0) {
throw new Error('업체 추가에 실패했습니다.')
}
const biddingCompanyId = biddingCompanyResult[0].id
// 2. company_condition_responses 레코드 생성 (기본값)
await tx.insert(companyConditionResponses).values({
biddingCompanyId: biddingCompanyId,
submittedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
})
return biddingCompanyId
})
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
revalidateTag('quotation-vendors')
revalidateTag('quotation-details')
revalidatePath(`/evcp/bid/${biddingId}`)
return {
success: true,
message: '업체가 성공적으로 추가되었습니다.',
data: { id: result }
}
} catch (error) {
console.error('Failed to create bidding detail vendor:', error)
return {
success: false,
error: error instanceof Error ? error.message : '업체 추가에 실패했습니다.'
}
}
}
// 유찰 처리
export async function markAsDisposal(biddingId: number, userId: string) {
try {
// 입찰 정보 조회
const biddingInfo = await db
.select()
.from(biddings)
.where(eq(biddings.id, biddingId))
.limit(1)
if (biddingInfo.length === 0) {
return { success: false, error: '입찰 정보를 찾을 수 없습니다.' }
}
const bidding = biddingInfo[0]
// 입찰 참여 업체들 조회
const participantCompanies = await db
.select({
companyId: biddingCompanies.companyId,
companyName: vendors.vendorName,
contactEmail: vendors.email
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
.where(and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.isBiddingParticipated, true)
))
const userName = await getUserNameById(userId)
// 입찰 상태를 유찰로 변경
await db
.update(biddings)
.set({
status: 'bidding_disposal',
updatedBy: userName,
updatedAt: new Date()
})
.where(eq(biddings.id, biddingId))
// 참여 업체들에게 유찰 안내 메일 발송
for (const company of participantCompanies) {
if (company.contactEmail) {
try {
await sendEmail({
to: company.contactEmail,
template: 'bidding-disposal',
context: {
companyName: company.companyName,
biddingNumber: bidding.biddingNumber,
title: bidding.title,
projectName: bidding.projectName,
itemName: bidding.itemName,
biddingType: bidding.biddingType,
processedDate: new Date().toLocaleDateString('ko-KR'),
bidPicName: bidding.bidPicName,
supplyPicName: bidding.supplyPicName,
language: 'ko'
}
})
} catch (emailError) {
console.error(`Failed to send disposal email to ${company.contactEmail}:`, emailError)
}
}
}
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
revalidateTag('quotation-vendors')
revalidateTag('quotation-details')
revalidatePath(`/evcp/bid/${biddingId}`)
return {
success: true,
message: `유찰 처리가 완료되었습니다. ${participantCompanies.length}개 업체에 안내 메일을 발송했습니다.`
}
} catch (error) {
console.error('Failed to mark as disposal:', error)
return { success: false, error: '유찰 처리에 실패했습니다.' }
}
}
// 입찰 등록 (사전견적에서 선정된 업체들에게 본입찰 초대 발송)
export async function registerBidding(biddingId: number, userId: string) {
try {
// 사전견적에서 선정된 업체들 + 본입찰에서 개별적으로 추가한 업체들 조회
const selectedCompanies = await db
.select({
companyId: biddingCompanies.companyId,
companyName: vendors.vendorName,
contactEmail: vendors.email
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
.where(and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.isPreQuoteSelected, true)
))
// 입찰 정보 조회
const biddingInfo = await db
.select()
.from(biddings)
.where(eq(biddings.id, biddingId))
.limit(1)
if (biddingInfo.length === 0) {
return { success: false, error: '입찰 정보를 찾을 수 없습니다.' }
}
const bidding = biddingInfo[0]
const userName = await getUserNameById(userId)
await db.transaction(async (tx) => {
// 1. 입찰 상태를 오픈으로 변경
await tx
.update(biddings)
.set({
status: 'bidding_opened',
updatedBy: userName,
updatedAt: new Date()
})
.where(eq(biddings.id, biddingId))
// 2. 선정된 업체들의 입찰 초대 여부를 true로 변경하고 초대 상태 업데이트
for (const company of selectedCompanies) {
await tx
.update(biddingCompanies)
.set({
isBiddingInvited: true,
invitationStatus: 'bidding_sent', // 입찰 초대 발송
updatedAt: new Date()
})
.where(and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.companyId, company.companyId)
))
}
})
// 3. 선정된 업체들에게 본입찰 초대 메일 발송
for (const company of selectedCompanies) {
if (company.contactEmail) {
try {
await sendEmail({
to: company.contactEmail,
template: 'bidding-invitation', // 새로운 본입찰 초대 템플릿 필요
context: {
companyName: company.companyName,
biddingNumber: bidding.biddingNumber,
title: bidding.title,
projectName: bidding.projectName,
itemName: bidding.itemName,
biddingType: bidding.biddingType,
submissionStartDate: bidding.submissionStartDate,
submissionEndDate: bidding.submissionEndDate,
biddingUrl: `${process.env.NEXT_PUBLIC_BASE_URL}/partners/bid/${biddingId}`,
bidPicName: bidding.bidPicName,
supplyPicName: bidding.supplyPicName,
language: 'ko'
}
})
} catch (emailError) {
console.error(`Failed to send bidding invitation email to ${company.contactEmail}:`, emailError)
}
}
}
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
revalidateTag('bidding-detail')
revalidateTag('quotation-vendors')
revalidateTag('quotation-details')
revalidateTag('pr-items')
revalidatePath(`/evcp/bid/${biddingId}`)
return {
success: true,
message: `입찰이 성공적으로 등록되었습니다. ${selectedCompanies.length}개 업체에 초대 메일을 발송했습니다.`
}
} catch (error) {
console.error('Failed to register bidding:', error)
return { success: false, error: '입찰 등록에 실패했습니다.' }
}
}
// 재입찰 생성 (기존 입찰의 revision 업데이트 + 메일 발송)
export async function createRebidding(biddingId: number, userId: string) {
try {
// 기존 입찰 정보 조회
const bidding = await db
.select()
.from(biddings)
.where(eq(biddings.id, biddingId))
.limit(1)
if (bidding.length === 0) {
return { success: false, error: '입찰을 찾을 수 없습니다.' }
}
const originalBidding = bidding[0]
// 기존 입찰 참여 업체들 조회
const participantCompanies = await db
.select({
companyId: biddingCompanies.companyId,
companyName: vendors.vendorName,
contactEmail: vendors.email
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
.where(and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.isBiddingParticipated, true)
))
const userName = await getUserNameById(userId)
// 기존 입찰의 revision 증가 및 상태 변경
const updatedBidding = await db
.update(biddings)
.set({
revision: (originalBidding.revision || 0) + 1,
status: 'bidding_opened', // 재입찰 시 다시 오픈 상태로
updatedBy: userName,
updatedAt: new Date()
})
.where(eq(biddings.id, biddingId))
.returning({
id: biddings.id,
biddingNumber: biddings.biddingNumber,
revision: biddings.revision
})
if (updatedBidding.length === 0) {
return { success: false, error: '재입찰 업데이트에 실패했습니다.' }
}
// // 참여 업체들의 상태를 대기로 변경
// await db
// .update(biddingCompanies)
// .set({
// isBiddingParticipated: null, // 대기 상태로 변경
// invitationStatus: 'sent',
// updatedAt: new Date()
// })
// .where(and(
// eq(biddingCompanies.biddingId, biddingId),
// eq(biddingCompanies.isBiddingParticipated, true)
// ))
// 재입찰 안내 메일 발송
for (const company of participantCompanies) {
if (company.contactEmail) {
try {
await sendEmail({
to: company.contactEmail,
template: 'rebidding-invitation',
context: {
companyName: company.companyName,
biddingNumber: updatedBidding[0].biddingNumber,
title: originalBidding.title,
projectName: originalBidding.projectName,
itemName: originalBidding.itemName,
biddingType: originalBidding.biddingType,
revision: updatedBidding[0].revision || 1,
submissionStartDate: originalBidding.submissionStartDate,
submissionEndDate: originalBidding.submissionEndDate,
biddingUrl: `${process.env.NEXT_PUBLIC_BASE_URL}/partners/bid/${biddingId}`,
bidPicName: originalBidding.bidPicName,
supplyPicName: originalBidding.supplyPicName,
language: 'ko'
}
})
} catch (emailError) {
console.error(`Failed to send rebidding email to ${company.contactEmail}:`, emailError)
}
}
}
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
revalidateTag('quotation-vendors')
revalidateTag('quotation-details')
revalidatePath('/evcp/bid')
revalidatePath(`/evcp/bid/${biddingId}`)
return {
success: true,
message: `재입찰이 성공적으로 처리되었습니다. ${participantCompanies.length}개 업체에 안내 메일을 발송했습니다.`
}
} catch (error) {
console.error('Failed to create rebidding:', error)
return { success: false, error: '재입찰 처리에 실패했습니다.' }
}
}
// 업체 선정 사유 업데이트
export async function updateVendorSelectionReason(biddingId: number, selectedCompanyId: number, selectionReason: string, userId: string) {
try {
const userName = await getUserNameById(userId)
// vendorSelectionResults 테이블에 삽입 또는 업데이트
await db
.insert(vendorSelectionResults)
.values({
biddingId,
selectedCompanyId,
selectionReason,
selectedBy: userName,
selectedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date()
})
.onConflictDoUpdate({
target: [vendorSelectionResults.biddingId],
set: {
selectedCompanyId,
selectionReason,
selectedBy: userName,
selectedAt: new Date(),
updatedAt: new Date()
}
})
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
revalidateTag('quotation-vendors')
revalidatePath(`/evcp/bid/${biddingId}`)
return { success: true, message: '업체 선정 사유가 성공적으로 업데이트되었습니다.' }
} catch (error) {
console.error('Failed to update vendor selection reason:', error)
return { success: false, error: '업체 선정 사유 업데이트에 실패했습니다.' }
}
}
// 낙찰용 문서 업로드
export async function uploadAwardDocument(biddingId: number, file: File, userId: string) {
try {
const userName = await getUserNameById(userId)
const saveResult = await saveFile({
file,
directory: `biddings/${biddingId}/award`,
userId: userId
})
if (saveResult.success && saveResult.filePath) {
// biddingDocuments 테이블에 저장
const [document] = await db.insert(biddingDocuments).values({
biddingId,
fileName: saveResult.fileName || file.name,
originalFileName: file.name,
filePath: saveResult.filePath,
fileSize: file.size,
documentType: 'other',
title: '낙찰 관련 문서',
description: '낙찰 관련 첨부파일',
uploadedBy: userName,
uploadedAt: new Date(),
// createdAt, updatedAt 필드가 스키마에 없으므로 제거
}).returning()
return {
success: true,
message: '파일이 성공적으로 업로드되었습니다.',
document
}
} else {
return {
success: false,
error: saveResult.error || '파일 저장에 실패했습니다.'
}
}
} catch (error) {
console.error('Failed to upload award document:', error)
return {
success: false,
error: '파일 업로드에 실패했습니다.'
}
}
}
// 낙찰용 문서 목록 조회
export async function getAwardDocuments(biddingId: number) {
try {
const documents = await db
.select()
.from(biddingDocuments)
.where(and(
eq(biddingDocuments.biddingId, biddingId),
eq(biddingDocuments.documentType, 'other')
))
.orderBy(desc(biddingDocuments.uploadedAt))
return documents
} catch (error) {
console.error('Failed to get award documents:', error)
return []
}
}
// 낙찰용 문서 다운로드
export async function getAwardDocumentForDownload(documentId: number, biddingId: number) {
try {
const documents = await db
.select()
.from(biddingDocuments)
.where(and(
eq(biddingDocuments.id, documentId),
eq(biddingDocuments.biddingId, biddingId),
eq(biddingDocuments.documentType, 'other')
))
.limit(1)
if (documents.length === 0) {
return {
success: false,
error: '문서를 찾을 수 없습니다.'
}
}
return {
success: true,
document: documents[0]
}
} catch (error) {
console.error('Failed to get award document for download:', error)
return {
success: false,
error: '문서 다운로드 준비에 실패했습니다.'
}
}
}
// 낙찰용 문서 삭제
export async function deleteAwardDocument(documentId: number, biddingId: number, userId: string) {
try {
const userName = await getUserNameById(userId)
// 문서 정보 조회
const documents = await db
.select()
.from(biddingDocuments)
.where(and(
eq(biddingDocuments.id, documentId),
eq(biddingDocuments.biddingId, biddingId),
eq(biddingDocuments.documentType, 'other'),
eq(biddingDocuments.uploadedBy, userName)
))
.limit(1)
if (documents.length === 0) {
return {
success: false,
error: '삭제할 수 있는 문서가 없습니다.'
}
}
// DB에서 삭제
await db
.delete(biddingDocuments)
.where(eq(biddingDocuments.id, documentId))
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
return {
success: true,
message: '문서가 성공적으로 삭제되었습니다.'
}
} catch (error) {
console.error('Failed to delete award document:', error)
return {
success: false,
error: '문서 삭제에 실패했습니다.'
}
}
}
// 낙찰 처리 (발주비율과 함께)
export async function awardBidding(biddingId: number, selectionReason: string, userId: string) {
try {
const userName = await getUserNameById(userId)
// 입찰 정보 조회 (contractType 포함)
const biddingInfo = await db
.select({
contractType: biddings.contractType,
status: biddings.status
})
.from(biddings)
.where(eq(biddings.id, biddingId))
.limit(1)
if (biddingInfo.length === 0) {
return { success: false, error: '입찰 정보를 찾을 수 없습니다.' }
}
const bidding = biddingInfo[0]
// 낙찰된 업체들 조회 (isWinner가 true인 업체들)
const awardedCompanies = await db
.select({
companyId: biddingCompanies.companyId,
finalQuoteAmount: biddingCompanies.finalQuoteAmount,
awardRatio: biddingCompanies.awardRatio
})
.from(biddingCompanies)
.where(and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.isWinner, true)
))
if (awardedCompanies.length === 0) {
return { success: false, error: '낙찰된 업체가 없습니다. 먼저 발주비율을 산정해주세요.' }
}
// 일반/매각 입찰의 경우 비율 합계 100% 검증
const contractType = bidding.contractType
if (contractType === 'general' || contractType === 'sale') {
const totalRatio = awardedCompanies.reduce((sum, company) =>
sum + (Number(company.awardRatio) || 0), 0)
if (totalRatio !== 100) {
return { success: false, error: `일반/매각 입찰의 경우 비율 합계가 100%여야 합니다. 현재 합계: ${totalRatio}%` }
}
}
// 최종입찰가 계산 (낙찰된 업체의 견적금액 * 발주비율의 합)
let finalBidPrice = 0
for (const company of awardedCompanies) {
const quoteAmount = parseFloat(company.finalQuoteAmount?.toString() || '0')
const ratio = parseFloat(company.awardRatio?.toString() || '0') / 100
finalBidPrice += quoteAmount * ratio
}
await db.transaction(async (tx) => {
// 1. 입찰 상태를 낙찰로 변경하고 최종입찰가 업데이트
await tx
.update(biddings)
.set({
status: 'vendor_selected',
finalBidPrice: finalBidPrice.toString(),
updatedAt: new Date()
})
.where(eq(biddings.id, biddingId))
// 2. 선정 사유 저장 (첫 번째 낙찰 업체 기준으로 저장)
const firstAwardedCompany = awardedCompanies[0]
// 기존 선정 결과 확인
const existingResult = await tx
.select()
.from(vendorSelectionResults)
.where(eq(vendorSelectionResults.biddingId, biddingId))
.limit(1)
if (existingResult.length > 0) {
// 업데이트
await tx
.update(vendorSelectionResults)
.set({
selectedCompanyId: firstAwardedCompany.companyId,
selectionReason,
selectedBy: userName,
selectedAt: new Date(),
updatedAt: new Date()
})
.where(eq(vendorSelectionResults.biddingId, biddingId))
} else {
// 삽입
await tx
.insert(vendorSelectionResults)
.values({
biddingId,
selectedCompanyId: firstAwardedCompany.companyId,
selectionReason,
selectedBy: userName,
selectedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date()
})
}
})
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
revalidateTag('quotation-vendors')
revalidateTag('quotation-details')
revalidatePath(`/evcp/bid/${biddingId}`)
return {
success: true,
message: `낙찰 처리가 완료되었습니다. 최종입찰가: ${finalBidPrice.toLocaleString()}원`
}
} catch (error) {
console.error('Failed to award bidding:', error)
return { success: false, error: '낙찰 처리에 실패했습니다.' }
}
}
// 낙찰된 업체 정보 조회
export async function getAwardedCompanies(biddingId: number) {
try {
const awardedCompanies = await db
.select({
companyId: biddingCompanies.companyId,
companyName: vendors.vendorName,
finalQuoteAmount: biddingCompanies.finalQuoteAmount,
awardRatio: biddingCompanies.awardRatio
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
.where(and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.isWinner, true)
))
return awardedCompanies.map(company => ({
companyId: company.companyId,
companyName: company.companyName,
finalQuoteAmount: parseFloat(company.finalQuoteAmount?.toString() || '0'),
awardRatio: parseFloat(company.awardRatio?.toString() || '0')
}))
} catch (error) {
console.error('Failed to get awarded companies:', error)
return []
}
}
// PR 품목 정보 업데이트
export async function updatePrItem(prItemId: number, input: Partial<typeof prItemsForBidding.$inferSelect>, userId: string) {
try {
await db
.update(prItemsForBidding)
.set({
...input,
updatedAt: new Date()
})
.where(eq(prItemsForBidding.id, prItemId))
// 캐시 무효화
if (input.biddingId) {
revalidateTag(`bidding-${input.biddingId}`)
revalidateTag('pr-items')
revalidatePath(`/evcp/bid/${input.biddingId}`)
}
return { success: true, message: '품목 정보가 성공적으로 업데이트되었습니다.' }
} catch (error) {
console.error('Failed to update PR item:', error)
return { success: false, error: '품목 정보 업데이트에 실패했습니다.' }
}
}
// 입찰 참여여부 업데이트
export async function updateBiddingParticipation(
biddingCompanyId: number,
participated: boolean,
userId: string
) {
try {
const result = await db.update(biddingCompanies)
.set({
isBiddingParticipated: participated,
updatedAt: new Date(),
})
.where(eq(biddingCompanies.id, biddingCompanyId))
.returning({ biddingId: biddingCompanies.biddingId })
// 캐시 무효화
if (result.length > 0) {
const biddingId = result[0].biddingId
revalidateTag(`bidding-${biddingId}`)
revalidateTag('quotation-vendors')
revalidatePath(`/evcp/bid/${biddingId}`)
}
return {
success: true,
message: `입찰 참여상태가 ${participated ? '응찰' : '미응찰'}로 업데이트되었습니다.`,
}
} catch (error) {
console.error('Failed to update bidding participation:', error)
return {
success: false,
error: error instanceof Error ? error.message : '입찰 참여상태 업데이트에 실패했습니다.'
}
}
}
// =================================================
// 품목별 견적 관련 함수들 (본입찰용)
// =================================================
// 품목별 견적 임시 저장 (본입찰용)
export async function saveBiddingDraft(
biddingCompanyId: number,
prItemQuotations: Array<{
prItemId: number
bidUnitPrice: number
bidAmount: number
proposedDeliveryDate?: string
technicalSpecification?: string
}>,
userId: string
) {
try {
const userName = await getUserNameById(userId)
let totalAmount = 0
await db.transaction(async (tx) => {
// 품목별 견적 Upsert 방식으로 저장
for (const item of prItemQuotations) {
// 기존 데이터 확인
const existingItem = await tx
.select()
.from(companyPrItemBids)
.where(
and(
eq(companyPrItemBids.biddingCompanyId, biddingCompanyId),
eq(companyPrItemBids.prItemId, item.prItemId),
)
)
.limit(1)
const itemData = {
bidUnitPrice: item.bidUnitPrice.toString(),
bidAmount: item.bidAmount.toString(),
proposedDeliveryDate: item.proposedDeliveryDate,
technicalSpecification: item.technicalSpecification,
currency: 'KRW',
updatedAt: new Date()
}
if (existingItem.length > 0) {
// 업데이트
await tx
.update(companyPrItemBids)
.set(itemData)
.where(
and(
eq(companyPrItemBids.biddingCompanyId, biddingCompanyId),
eq(companyPrItemBids.prItemId, item.prItemId),
eq(companyPrItemBids.isPreQuote, false)
)
)
} else {
// 새로 생성
await tx.insert(companyPrItemBids)
.values({
biddingCompanyId,
prItemId: item.prItemId,
isPreQuote: false, // 본입찰 데이터
createdAt: new Date(),
...itemData
})
}
totalAmount += item.bidAmount
}
})
// 캐시 무효화
revalidateTag(`bidding-${biddingCompanyId}`)
revalidateTag('quotation-vendors')
return {
success: true,
message: '품목별 견적이 임시 저장되었습니다.',
totalAmount
}
} catch (error) {
console.error('Failed to save bidding draft:', error)
return {
success: false,
error: error instanceof Error ? error.message : '임시 저장에 실패했습니다.'
}
}
}
// =================================================
// 협력업체 페이지용 함수들 (Partners)
// =================================================
// 협력업체용 입찰 참여여부 업데이트
export async function updatePartnerBiddingParticipation(
biddingCompanyId: number,
participated: boolean,
userId: string
) {
try {
const result = await db.update(biddingCompanies)
.set({
isBiddingParticipated: participated,
updatedAt: new Date(),
})
.where(eq(biddingCompanies.id, biddingCompanyId))
.returning({ biddingId: biddingCompanies.biddingId })
// 캐시 무효화
if (result.length > 0) {
const biddingId = result[0].biddingId
revalidateTag(`bidding-${biddingId}`)
revalidateTag('quotation-vendors')
revalidateTag(`partners-bidding-${biddingId}`)
revalidatePath(`/partners/bid/${biddingId}`)
}
return {
success: true,
message: `입찰 참여상태가 ${participated ? '응찰' : '미응찰'}로 업데이트되었습니다.`,
}
} catch (error) {
console.error('Failed to update partner bidding participation:', error)
return {
success: false,
error: error instanceof Error ? error.message : '입찰 참여상태 업데이트에 실패했습니다.'
}
}
}
// 협력업체용 입찰 목록 조회 (bidding_companies 기준)
export interface PartnersBiddingListItem {
// bidding_companies 정보
id: number
biddingCompanyId: number
invitationStatus: string
respondedAt: string | null
finalQuoteAmount: number | null
finalQuoteSubmittedAt: string | null
isWinner: boolean | null
isAttendingMeeting: boolean | null
isPreQuoteSelected: boolean | null
isPreQuoteParticipated: boolean | null
isBiddingParticipated: boolean | null
preQuoteDeadline: Date | null
isBiddingInvited: boolean | null
notes: string | null
createdAt: Date
updatedAt: Date
// updatedBy: string | null
hasSpecificationMeeting: boolean | null
// biddings 정보
biddingId: number
biddingNumber: string
originalBiddingNumber: string | null // 원입찰번호
revision: number | null
projectName: string
itemName: string
title: string
contractType: string
biddingType: string
preQuoteDate: Date | null
contractStartDate: Date | null
contractEndDate: Date | null
submissionStartDate: Date | null
submissionEndDate: Date | null
status: string
// 입찰담당자
bidPicName: string | null
// 조달담당자
supplyPicName: string | null
currency: string
budget: number | null
isUrgent: boolean | null // 긴급여부
// 계산된 필드
responseDeadline: Date | null // 참여회신 마감일 (submissionStartDate 전 3일)
submissionDate: Date | null // 입찰제출일 (submissionEndDate)
}
// 협력업체용 입찰 목록 조회 (bidding_companies 기준)
export async function getBiddingListForPartners(companyId: number): Promise<PartnersBiddingListItem[]> {
try {
const result = await db
.select({
// bidding_companies 정보
id: biddingCompanies.id,
biddingCompanyId: biddingCompanies.id, // 동일
invitationStatus: biddingCompanies.invitationStatus,
respondedAt: biddingCompanies.respondedAt,
finalQuoteAmount: biddingCompanies.finalQuoteAmount,
finalQuoteSubmittedAt: biddingCompanies.finalQuoteSubmittedAt,
isWinner: biddingCompanies.isWinner,
isAttendingMeeting: biddingCompanies.isAttendingMeeting,
isPreQuoteSelected: biddingCompanies.isPreQuoteSelected,
isPreQuoteParticipated: biddingCompanies.isPreQuoteParticipated,
isBiddingParticipated: biddingCompanies.isBiddingParticipated,
preQuoteDeadline: biddingCompanies.preQuoteDeadline,
isBiddingInvited: biddingCompanies.isBiddingInvited,
notes: biddingCompanies.notes,
createdAt: biddingCompanies.createdAt,
updatedAt: biddingCompanies.updatedAt,
// updatedBy: biddingCompanies.updatedBy, // 이 필드가 존재하지 않음
// biddings 정보
biddingId: biddings.id,
biddingNumber: biddings.biddingNumber,
originalBiddingNumber: biddings.originalBiddingNumber, // 원입찰번호
revision: biddings.revision,
projectName: biddings.projectName,
itemName: biddings.itemName,
title: biddings.title,
contractType: biddings.contractType,
biddingType: biddings.biddingType,
preQuoteDate: biddings.preQuoteDate,
contractStartDate: biddings.contractStartDate,
contractEndDate: biddings.contractEndDate,
submissionStartDate: biddings.submissionStartDate,
submissionEndDate: biddings.submissionEndDate,
status: biddings.status,
// 기존 담당자 필드 (하위호환성 유지)
// 입찰담당자
bidPicName: biddings.bidPicName,
// 조달담당자
supplyPicName: biddings.supplyPicName,
currency: biddings.currency,
budget: biddings.budget,
isUrgent: biddings.isUrgent,
hasSpecificationMeeting: biddings.hasSpecificationMeeting,
})
.from(biddingCompanies)
.innerJoin(biddings, eq(biddingCompanies.biddingId, biddings.id))
.where(and(
eq(biddingCompanies.companyId, companyId),
ne(biddingCompanies.invitationStatus, 'pending') // 초대 대기 상태 제외
))
.orderBy(desc(biddingCompanies.createdAt))
console.log(result, "result")
// 계산된 필드 추가
const resultWithCalculatedFields = result.map(item => ({
...item,
respondedAt: item.respondedAt ? (item.respondedAt instanceof Date ? item.respondedAt.toISOString() : item.respondedAt.toString()) : null,
finalQuoteAmount: item.finalQuoteAmount ? Number(item.finalQuoteAmount) : null, // string을 number로 변환
finalQuoteSubmittedAt: item.finalQuoteSubmittedAt ? (item.finalQuoteSubmittedAt instanceof Date ? item.finalQuoteSubmittedAt.toISOString() : item.finalQuoteSubmittedAt.toString()) : null,
responseDeadline: item.submissionStartDate
? new Date(item.submissionStartDate.getTime() - 3 * 24 * 60 * 60 * 1000) // 3일 전
: null,
submissionDate: item.submissionEndDate,
}))
return resultWithCalculatedFields
} catch (error) {
console.error('Failed to get bidding list for partners:', error)
return []
}
}
// 협력업체용 입찰 상세 정보 조회
export async function getBiddingDetailsForPartners(biddingId: number, companyId: number) {
try {
const result = await db
.select({
// 입찰 기본 정보
id: biddings.id,
biddingId: biddings.id, // partners-bidding-detail.tsx에서 필요한 필드
biddingNumber: biddings.biddingNumber,
revision: biddings.revision,
projectName: biddings.projectName,
itemName: biddings.itemName,
title: biddings.title,
description: biddings.description,
// 계약 정보
contractType: biddings.contractType,
biddingType: biddings.biddingType,
awardCount: biddings.awardCount,
preQuoteDate: biddings.preQuoteDate,
contractStartDate: biddings.contractStartDate,
contractEndDate: biddings.contractEndDate,
// 일정 정보
biddingRegistrationDate: biddings.biddingRegistrationDate,
submissionStartDate: biddings.submissionStartDate,
submissionEndDate: biddings.submissionEndDate,
evaluationDate: biddings.evaluationDate,
// 가격 정보
currency: biddings.currency,
budget: biddings.budget,
targetPrice: biddings.targetPrice,
// 상태 및 담당자
status: biddings.status,
isUrgent: biddings.isUrgent,
bidPicName: biddings.bidPicName,
supplyPicName: biddings.supplyPicName,
// 협력업체 특정 정보
biddingCompanyId: biddingCompanies.id,
invitationStatus: biddingCompanies.invitationStatus,
finalQuoteAmount: biddingCompanies.finalQuoteAmount,
finalQuoteSubmittedAt: biddingCompanies.finalQuoteSubmittedAt,
isFinalSubmission: biddingCompanies.isFinalSubmission,
isWinner: biddingCompanies.isWinner,
isAttendingMeeting: biddingCompanies.isAttendingMeeting,
isPreQuoteSelected: biddingCompanies.isPreQuoteSelected,
isBiddingParticipated: biddingCompanies.isBiddingParticipated,
isPreQuoteParticipated: biddingCompanies.isPreQuoteParticipated,
hasSpecificationMeeting: biddings.hasSpecificationMeeting,
// 응답한 조건들 (company_condition_responses) - 제시된 조건과 응답 모두 여기서 관리
paymentTermsResponse: companyConditionResponses.paymentTermsResponse,
taxConditionsResponse: companyConditionResponses.taxConditionsResponse,
incotermsResponse: companyConditionResponses.incotermsResponse,
proposedContractDeliveryDate: companyConditionResponses.proposedContractDeliveryDate,
proposedShippingPort: companyConditionResponses.proposedShippingPort,
proposedDestinationPort: companyConditionResponses.proposedDestinationPort,
priceAdjustmentResponse: companyConditionResponses.priceAdjustmentResponse,
isInitialResponse: companyConditionResponses.isInitialResponse,
sparePartResponse: companyConditionResponses.sparePartResponse,
additionalProposals: companyConditionResponses.additionalProposals,
responseSubmittedAt: companyConditionResponses.submittedAt,
})
.from(biddings)
.innerJoin(biddingCompanies, eq(biddings.id, biddingCompanies.biddingId))
.leftJoin(companyConditionResponses, eq(biddingCompanies.id, companyConditionResponses.biddingCompanyId))
.where(and(
eq(biddings.id, biddingId),
eq(biddingCompanies.companyId, companyId)
))
.limit(1)
return result[0] || null
} catch (error) {
console.error('Failed to get bidding details for partners:', error)
return null
}
}
// 협력업체 응찰 제출
export async function submitPartnerResponse(
biddingCompanyId: number,
response: {
paymentTermsResponse?: string
taxConditionsResponse?: string
incotermsResponse?: string
proposedContractDeliveryDate?: string
proposedShippingPort?: string
proposedDestinationPort?: string
priceAdjustmentResponse?: boolean
isInitialResponse?: boolean
sparePartResponse?: string
additionalProposals?: string
finalQuoteAmount?: number
isFinalSubmission?: boolean // 최종제출 여부 추가
prItemQuotations?: Array<{
prItemId: number
bidUnitPrice: number
bidAmount: number
proposedDeliveryDate?: string
technicalSpecification?: string
}>
priceAdjustmentForm?: {
itemName?: string
adjustmentReflectionPoint?: string
majorApplicableRawMaterial?: string
adjustmentFormula?: string
rawMaterialPriceIndex?: string
referenceDate?: string
comparisonDate?: string
adjustmentRatio?: number
notes?: string
adjustmentConditions?: string
majorNonApplicableRawMaterial?: string
adjustmentPeriod?: string
contractorWriter?: string
adjustmentDate?: string
nonApplicableReason?: string
}
},
userId: string
) {
try {
const userName = await getUserNameById(userId)
const result = await db.transaction(async (tx) => {
// 0. 품목별 견적 정보 최종 저장 (본입찰 제출) - Upsert 방식
if (response.prItemQuotations && response.prItemQuotations.length > 0) {
for (const item of response.prItemQuotations) {
// 기존 데이터 확인
const existingItem = await tx
.select()
.from(companyPrItemBids)
.where(
and(
eq(companyPrItemBids.biddingCompanyId, biddingCompanyId),
eq(companyPrItemBids.prItemId, item.prItemId),
)
)
.limit(1)
const itemData = {
bidUnitPrice: item.bidUnitPrice.toString(),
bidAmount: item.bidAmount.toString(),
proposedDeliveryDate: item.proposedDeliveryDate || null,
technicalSpecification: item.technicalSpecification || null,
currency: 'KRW',
submittedAt: new Date(),
updatedAt: new Date()
}
if (existingItem.length > 0) {
// 업데이트
await tx
.update(companyPrItemBids)
.set(itemData)
.where(
and(
eq(companyPrItemBids.biddingCompanyId, biddingCompanyId),
eq(companyPrItemBids.prItemId, item.prItemId),
eq(companyPrItemBids.isPreQuote, false)
)
)
} else {
// 새로 생성
await tx.insert(companyPrItemBids)
.values({
biddingCompanyId,
prItemId: item.prItemId,
isPreQuote: false, // 본입찰 데이터
createdAt: new Date(),
...itemData
})
}
}
}
// 3. 연동제 정보 저장 (연동제 적용이 true이고 연동제 정보가 있는 경우)
// if (response.priceAdjustmentResponse && response.priceAdjustmentForm) {
// const priceAdjustmentData = {
// companyConditionResponsesId: companyConditionResponseId,
// itemName: response.priceAdjustmentForm.itemName,
// adjustmentReflectionPoint: response.priceAdjustmentForm.adjustmentReflectionPoint,
// majorApplicableRawMaterial: response.priceAdjustmentForm.majorApplicableRawMaterial,
// adjustmentFormula: response.priceAdjustmentForm.adjustmentFormula,
// rawMaterialPriceIndex: response.priceAdjustmentForm.rawMaterialPriceIndex,
// referenceDate: response.priceAdjustmentForm.referenceDate || null,
// comparisonDate: response.priceAdjustmentForm.comparisonDate || null,
// adjustmentRatio: response.priceAdjustmentForm.adjustmentRatio,
// notes: response.priceAdjustmentForm.notes,
// adjustmentConditions: response.priceAdjustmentForm.adjustmentConditions,
// majorNonApplicableRawMaterial: response.priceAdjustmentForm.majorNonApplicableRawMaterial,
// adjustmentPeriod: response.priceAdjustmentForm.adjustmentPeriod,
// contractorWriter: response.priceAdjustmentForm.contractorWriter,
// adjustmentDate: response.priceAdjustmentForm.adjustmentDate || null,
// nonApplicableReason: response.priceAdjustmentForm.nonApplicableReason,
// }
// // 기존 연동제 정보가 있는지 확인
// const existingPriceAdjustment = await tx
// .select()
// .from(priceAdjustmentForms)
// .where(eq(priceAdjustmentForms.companyConditionResponsesId, companyConditionResponseId))
// .limit(1)
// if (existingPriceAdjustment.length > 0) {
// // 업데이트
// await tx
// .update(priceAdjustmentForms)
// .set(priceAdjustmentData)
// .where(eq(priceAdjustmentForms.companyConditionResponsesId, companyConditionResponseId))
// } else {
// // 새로 생성
// await tx.insert(priceAdjustmentForms).values(priceAdjustmentData)
// }
// }
// 2. biddingCompanies 테이블에 견적 금액과 상태 업데이트
const companyUpdateData: any = {
respondedAt: new Date(),
updatedAt: new Date(),
// updatedBy: userName, // 이 필드가 존재하지 않음
}
if (response.finalQuoteAmount !== undefined) {
companyUpdateData.finalQuoteAmount = response.finalQuoteAmount
companyUpdateData.finalQuoteSubmittedAt = new Date()
// 최종제출 여부에 따라 상태 및 플래그 설정
if (response.isFinalSubmission) {
companyUpdateData.isFinalSubmission = true
companyUpdateData.invitationStatus = 'bidding_submitted' // 응찰 완료
} else {
companyUpdateData.isFinalSubmission = false
// 임시저장: invitationStatus는 변경하지 않음 (bidding_accepted 유지)
}
}
await tx
.update(biddingCompanies)
.set(companyUpdateData)
.where(eq(biddingCompanies.id, biddingCompanyId))
// biddingId 조회
const biddingCompanyInfo = await tx
.select({ biddingId: biddingCompanies.biddingId })
.from(biddingCompanies)
.where(eq(biddingCompanies.id, biddingCompanyId))
.limit(1)
const biddingId = biddingCompanyInfo[0]?.biddingId
// 최종제출인 경우, 입찰 상태를 평가중으로 변경 (bidding_opened 상태에서만)
if (biddingId && response.finalQuoteAmount !== undefined && response.isFinalSubmission) {
await tx
.update(biddings)
.set({
status: 'evaluation_of_bidding',
updatedAt: new Date()
})
.where(and(
eq(biddings.id, biddingId),
eq(biddings.status, 'bidding_opened')
))
}
return biddingId
})
// 캐시 무효화
if (result) {
revalidateTag(`bidding-${result}`)
revalidateTag('quotation-vendors')
revalidateTag('quotation-details')
}
revalidatePath('/partners/bid/[id]')
return {
success: true,
message: '응찰이 성공적으로 제출되었습니다.',
}
} catch (error) {
console.error('Failed to submit partner response:', error)
return { success: false, error: '응찰 제출에 실패했습니다.' }
}
}
// 사양설명회 정보 조회 (협력업체용)
export async function getSpecificationMeetingForPartners(biddingId: number) {
try {
// specification_meetings 테이블에서 사양설명회 정보 조회
const specMeeting = await db
.select({
id: specificationMeetings.id,
meetingDate: specificationMeetings.meetingDate,
meetingTime: specificationMeetings.meetingTime,
location: specificationMeetings.location,
address: specificationMeetings.address,
contactPerson: specificationMeetings.contactPerson,
contactPhone: specificationMeetings.contactPhone,
contactEmail: specificationMeetings.contactEmail,
agenda: specificationMeetings.agenda,
materials: specificationMeetings.materials,
notes: specificationMeetings.notes,
isRequired: specificationMeetings.isRequired,
})
.from(specificationMeetings)
.where(eq(specificationMeetings.biddingId, biddingId))
.limit(1)
// bidding_documents에서 사양설명회 관련 문서 조회
const documents = await db
.select({
id: biddingDocuments.id,
fileName: biddingDocuments.fileName,
originalFileName: biddingDocuments.originalFileName,
filePath: biddingDocuments.filePath,
fileSize: biddingDocuments.fileSize,
title: biddingDocuments.title,
})
.from(biddingDocuments)
.where(and(
eq(biddingDocuments.biddingId, biddingId),
eq(biddingDocuments.documentType, 'specification_meeting')
))
// 기본 입찰 정보도 가져오기 (제목, 입찰번호 등)
const bidding = await db
.select({
id: biddings.id,
title: biddings.title,
biddingNumber: biddings.biddingNumber,
})
.from(biddings)
.where(eq(biddings.id, biddingId))
.limit(1)
if (bidding.length === 0) {
return { success: false, error: '입찰 정보를 찾을 수 없습니다.' }
}
// 사양설명회 정보가 없는 경우
if (specMeeting.length === 0) {
return {
success: true,
data: {
...bidding[0],
documents,
meetingDate: null,
meetingTime: null,
location: null,
address: null,
contactPerson: null,
contactPhone: null,
contactEmail: null,
agenda: null,
materials: null,
notes: null,
isRequired: false,
}
}
}
return {
success: true,
data: {
...bidding[0],
documents,
meetingDate: specMeeting[0].meetingDate ? (specMeeting[0].meetingDate instanceof Date ? specMeeting[0].meetingDate.toISOString().split('T')[0] : specMeeting[0].meetingDate.toString().split('T')[0]) : null,
meetingTime: specMeeting[0].meetingTime,
location: specMeeting[0].location,
address: specMeeting[0].address,
contactPerson: specMeeting[0].contactPerson,
contactPhone: specMeeting[0].contactPhone,
contactEmail: specMeeting[0].contactEmail,
agenda: specMeeting[0].agenda,
materials: specMeeting[0].materials,
notes: specMeeting[0].notes,
isRequired: specMeeting[0].isRequired,
}
}
} catch (error) {
console.error('Failed to get specification meeting info:', error)
return { success: false, error: '사양설명회 정보 조회에 실패했습니다.' }
}
}
// 사양설명회 참석 여부 업데이트 (상세 정보 포함)
export async function updatePartnerAttendance(
biddingCompanyId: number,
attendanceData: {
isAttending: boolean
attendeeCount?: number
representativeName?: string
representativePhone?: string
}
) {
try {
const result = await db.transaction(async (tx) => {
// biddingCompanies 테이블 업데이트 (참석여부만 저장)
await tx
.update(biddingCompanies)
.set({
isAttendingMeeting: attendanceData.isAttending,
updatedAt: new Date(),
})
.where(eq(biddingCompanies.id, biddingCompanyId))
// 참석하는 경우, 사양설명회 담당자(contactEmail)에 이메일 발송을 위한 정보 반환
if (attendanceData.isAttending) {
// 입찰 + 사양설명회 + 업체 정보 불러오기
const biddingInfo = await tx
.select({
biddingId: biddingCompanies.biddingId,
companyId: biddingCompanies.companyId,
bidPicName: biddings.bidPicName,
supplyPicName: biddings.supplyPicName,
title: biddings.title,
biddingNumber: biddings.biddingNumber,
})
.from(biddingCompanies)
.innerJoin(biddings, eq(biddingCompanies.biddingId, biddings.id))
.where(eq(biddingCompanies.id, biddingCompanyId))
.limit(1)
if (biddingInfo.length > 0) {
// 업체 정보
const companyInfo = await tx
.select({
vendorName: vendors.vendorName,
})
.from(vendors)
.where(eq(vendors.id, biddingInfo[0].companyId))
.limit(1)
const companyName = companyInfo.length > 0 ? companyInfo[0].vendorName : '알 수 없음'
// 사양설명회 상세 정보(담당자 email 포함)
const specificationMeetingInfo = await tx
.select({
contactEmail: specificationMeetings.contactEmail,
meetingDate: specificationMeetings.meetingDate,
meetingTime: specificationMeetings.meetingTime,
location: specificationMeetings.location,
})
.from(specificationMeetings)
.where(eq(specificationMeetings.biddingId, biddingInfo[0].biddingId))
.limit(1)
const contactEmail = specificationMeetingInfo.length > 0 ? specificationMeetingInfo[0].contactEmail : null
// 메일 발송 (템플릿 사용)
if (contactEmail) {
try {
const { sendEmail } = await import('@/lib/mail/sendEmail')
await sendEmail({
to: contactEmail,
template: 'specification-meeting-attendance',
context: {
biddingNumber: biddingInfo[0].biddingNumber,
title: biddingInfo[0].title,
companyName: companyName,
attendeeCount: attendanceData.attendeeCount,
representativeName: attendanceData.representativeName,
representativePhone: attendanceData.representativePhone,
bidPicName: biddingInfo[0].bidPicName,
supplyPicName: biddingInfo[0].supplyPicName,
meetingDate: specificationMeetingInfo[0]?.meetingDate,
meetingTime: specificationMeetingInfo[0]?.meetingTime,
location: specificationMeetingInfo[0]?.location,
contactEmail: contactEmail,
currentYear: new Date().getFullYear(),
language: 'ko'
}
})
console.log(`사양설명회 참석 알림 메일 발송 완료: ${contactEmail}`)
} catch (emailError) {
console.error('메일 발송 실패:', emailError)
// 메일 발송 실패해도 참석 여부 업데이트는 성공으로 처리
}
} else {
console.warn('사양설명회 담당자 이메일이 없습니다.')
}
// 캐시 무효화
revalidateTag(`bidding-${biddingInfo[0].biddingId}`)
revalidateTag('quotation-vendors')
return {
...biddingInfo[0],
companyName,
attendeeCount: attendanceData.attendeeCount,
representativeName: attendanceData.representativeName,
representativePhone: attendanceData.representativePhone
}
}
}
return null
})
revalidatePath('/partners/bid/[id]')
return {
success: true,
message: `사양설명회 ${attendanceData.isAttending ? '참석' : '불참'}으로 설정되었습니다.`,
data: result
}
} catch (error) {
console.error('Failed to update partner attendance:', error)
return { success: false, error: '참석 여부 업데이트에 실패했습니다.' }
}
}
// 연동제 정보 조회
export async function getPriceAdjustmentForm(companyConditionResponseId: number) {
try {
const priceAdjustment = await db
.select()
.from(priceAdjustmentForms)
.where(eq(priceAdjustmentForms.companyConditionResponsesId, companyConditionResponseId))
.limit(1)
return priceAdjustment[0] || null
} catch (error) {
console.error('Failed to get price adjustment form:', error)
return null
}
}
// 입찰업체 ID로 연동제 정보 조회
export async function getPriceAdjustmentFormByBiddingCompanyId(biddingCompanyId: number) {
try {
const result = await db
.select({
priceAdjustmentForm: priceAdjustmentForms,
companyConditionResponse: companyConditionResponses,
})
.from(companyConditionResponses)
.leftJoin(priceAdjustmentForms, eq(companyConditionResponses.id, priceAdjustmentForms.companyConditionResponsesId))
.where(eq(companyConditionResponses.biddingCompanyId, biddingCompanyId))
.limit(1)
return result[0]?.priceAdjustmentForm || null
} catch (error) {
console.error('Failed to get price adjustment form by bidding company id:', error)
return null
}
}
// =================================================
// 입찰 문서 관리 함수들 (발주처 문서용)
// =================================================
// 입찰 문서 업로드 (발주처 문서용 - companyId: null)
export async function uploadBiddingDocument(
biddingId: number,
file: File,
documentType: string,
title: string,
description: string,
userId: string
) {
try {
const userName = await getUserNameById(userId)
// 파일 저장
const saveResult = await saveFile({
file,
directory: `bidding/${biddingId}/documents`,
originalName: file.name,
userId
})
if (!saveResult.success) {
return {
success: false,
error: saveResult.error || '파일 저장에 실패했습니다.'
}
}
// 데이터베이스에 문서 정보 저장 (companyId는 null로 설정)
const result = await db.insert(biddingDocuments)
.values({
biddingId,
companyId: null, // 발주처 문서
documentType: documentType as any,
fileName: saveResult.fileName!,
originalFileName: file.name,
fileSize: file.size,
mimeType: file.type,
filePath: saveResult.publicPath!, // publicPath 사용 (웹 접근 가능한 경로)
title,
description,
isPublic: true, // 발주처 문서는 기본적으로 공개
isRequired: false,
uploadedBy: userName,
uploadedAt: new Date()
})
.returning()
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
revalidateTag('bidding-documents')
return {
success: true,
message: '문서가 성공적으로 업로드되었습니다.',
documentId: result[0].id
}
} catch (error) {
console.error('Failed to upload bidding document:', error)
return {
success: false,
error: error instanceof Error ? error.message : '문서 업로드에 실패했습니다.'
}
}
}
// 업로드된 입찰 문서 목록 조회 (발주처 문서용)
export async function getBiddingDocuments(biddingId: number) {
try {
const documents = await db
.select({
id: biddingDocuments.id,
biddingId: biddingDocuments.biddingId,
companyId: biddingDocuments.companyId,
documentType: biddingDocuments.documentType,
fileName: biddingDocuments.fileName,
originalFileName: biddingDocuments.originalFileName,
fileSize: biddingDocuments.fileSize,
filePath: biddingDocuments.filePath,
title: biddingDocuments.title,
description: biddingDocuments.description,
uploadedAt: biddingDocuments.uploadedAt,
uploadedBy: biddingDocuments.uploadedBy
})
.from(biddingDocuments)
.where(
and(
eq(biddingDocuments.biddingId, biddingId),
sql`${biddingDocuments.companyId} IS NULL` // 발주처 문서만
)
)
.orderBy(desc(biddingDocuments.uploadedAt))
return documents
} catch (error) {
console.error('Failed to get bidding documents:', error)
return []
}
}
// 입찰 문서 다운로드용 정보 조회
export async function getBiddingDocumentForDownload(documentId: number, biddingId: number) {
try {
const documents = await db
.select()
.from(biddingDocuments)
.where(
and(
eq(biddingDocuments.id, documentId),
eq(biddingDocuments.biddingId, biddingId),
sql`${biddingDocuments.companyId} IS NULL` // 발주처 문서만
)
)
.limit(1)
if (documents.length === 0) {
return {
success: false,
error: '문서를 찾을 수 없습니다.'
}
}
return {
success: true,
document: documents[0]
}
} catch (error) {
console.error('Failed to get bidding document for download:', error)
return {
success: false,
error: '문서 다운로드 준비에 실패했습니다.'
}
}
}
// 입찰 문서 삭제 (발주처 문서용)
export async function deleteBiddingDocument(documentId: number, biddingId: number, userId: string) {
try {
const userName = await getUserNameById(userId)
// 문서 정보 조회 (업로더 확인)
const documents = await db
.select()
.from(biddingDocuments)
.where(
and(
eq(biddingDocuments.id, documentId),
eq(biddingDocuments.biddingId, biddingId),
sql`${biddingDocuments.companyId} IS NULL`, // 발주처 문서만
eq(biddingDocuments.uploadedBy, userName)
)
)
.limit(1)
if (documents.length === 0) {
return {
success: false,
error: '삭제할 수 있는 문서가 없습니다.'
}
}
// DB에서 삭제
await db
.delete(biddingDocuments)
.where(eq(biddingDocuments.id, documentId))
// 캐시 무효화
revalidateTag(`bidding-${biddingId}`)
revalidateTag('bidding-documents')
return {
success: true,
message: '문서가 성공적으로 삭제되었습니다.'
}
} catch (error) {
console.error('Failed to delete bidding document:', error)
return {
success: false,
error: '문서 삭제에 실패했습니다.'
}
}
}
// 협력업체용 발주처 문서 조회 (캐시 적용)
export async function getBiddingDocumentsForPartners(biddingId: number) {
return unstable_cache(
async () => {
try {
const documents = await db
.select({
id: biddingDocuments.id,
biddingId: biddingDocuments.biddingId,
companyId: biddingDocuments.companyId,
documentType: biddingDocuments.documentType,
fileName: biddingDocuments.fileName,
originalFileName: biddingDocuments.originalFileName,
fileSize: biddingDocuments.fileSize,
filePath: biddingDocuments.filePath,
title: biddingDocuments.title,
description: biddingDocuments.description,
uploadedAt: biddingDocuments.uploadedAt,
uploadedBy: biddingDocuments.uploadedBy
})
.from(biddingDocuments)
.where(
and(
eq(biddingDocuments.biddingId, biddingId),
sql`${biddingDocuments.companyId} IS NULL`, // 발주처 문서만
eq(biddingDocuments.isPublic, true) // 공개 문서만
)
)
.orderBy(desc(biddingDocuments.uploadedAt))
return documents
} catch (error) {
console.error('Failed to get bidding documents for partners:', error)
return []
}
},
[`bidding-documents-partners-${biddingId}`],
{
tags: [`bidding-${biddingId}`, 'bidding-documents']
}
)()
}
// =================================================
// 입찰가 비교 분석 함수들
// =================================================
// 벤더별 입찰가 정보 조회 (캐시 적용)
export async function getVendorPricesForBidding(biddingId: number) {
return unstable_cache(
async () => {
try {
// 각 회사의 입찰가 정보를 조회 - 본입찰 참여 업체들
const vendorPrices = await db
.select({
companyId: biddingCompanies.companyId,
companyName: vendors.vendorName,
biddingCompanyId: biddingCompanies.id,
currency: sql<string>`'KRW'`, // 기본값 KRW
finalQuoteAmount: biddingCompanies.finalQuoteAmount,
isBiddingParticipated: biddingCompanies.isBiddingParticipated,
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
.where(and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.isBiddingParticipated, true), // 본입찰 참여 업체만
sql`${biddingCompanies.finalQuoteAmount} IS NOT NULL` // 입찰가를 제출한 업체만
))
console.log(`Found ${vendorPrices.length} vendors for bidding ${biddingId}`)
const result: any[] = []
for (const vendor of vendorPrices) {
try {
// 해당 회사의 품목별 입찰가 조회 (본입찰 데이터)
const itemPrices = await db
.select({
prItemId: companyPrItemBids.prItemId,
itemName: prItemsForBidding.itemInfo, // itemInfo 사용
itemNumber: prItemsForBidding.itemNumber, // itemNumber도 포함
quantity: prItemsForBidding.quantity,
quantityUnit: prItemsForBidding.quantityUnit,
weight: prItemsForBidding.totalWeight, // totalWeight 사용
weightUnit: prItemsForBidding.weightUnit,
unitPrice: companyPrItemBids.bidUnitPrice,
amount: companyPrItemBids.bidAmount,
proposedDeliveryDate: companyPrItemBids.proposedDeliveryDate,
})
.from(companyPrItemBids)
.leftJoin(prItemsForBidding, eq(companyPrItemBids.prItemId, prItemsForBidding.id))
.where(and(
eq(companyPrItemBids.biddingCompanyId, vendor.biddingCompanyId),
eq(companyPrItemBids.isPreQuote, false) // 본입찰 데이터만
))
.orderBy(prItemsForBidding.id)
console.log(`Vendor ${vendor.companyName}: Found ${itemPrices.length} item prices`)
// 총 금액은 biddingCompanies.finalQuoteAmount 사용
const totalAmount = parseFloat(vendor.finalQuoteAmount || '0')
result.push({
companyId: vendor.companyId,
companyName: vendor.companyName || `Vendor ${vendor.companyId}`,
biddingCompanyId: vendor.biddingCompanyId,
totalAmount,
currency: vendor.currency,
itemPrices: itemPrices.map(item => ({
prItemId: item.prItemId,
itemName: item.itemName || item.itemNumber || `Item ${item.prItemId}`,
quantity: parseFloat(item.quantity || '0'),
quantityUnit: item.quantityUnit || 'ea',
weight: item.weight ? parseFloat(item.weight) : null,
weightUnit: item.weightUnit,
unitPrice: parseFloat(item.unitPrice || '0'),
amount: parseFloat(item.amount || '0'),
proposedDeliveryDate: item.proposedDeliveryDate ?
(typeof item.proposedDeliveryDate === 'string'
? item.proposedDeliveryDate
: item.proposedDeliveryDate.toISOString().split('T')[0])
: null,
}))
})
} catch (vendorError) {
console.error(`Error processing vendor ${vendor.companyId}:`, vendorError)
// 벤더 처리 중 에러가 발생해도 다른 벤더들은 계속 처리
}
}
return result
} catch (error) {
console.error('Failed to get vendor prices for bidding:', error)
return []
}
},
[`bidding-vendor-prices-${biddingId}`],
{
tags: [`bidding-${biddingId}`, 'quotation-vendors', 'pr-items']
}
)()
}
// 사양설명회 참여 여부 업데이트
export async function setSpecificationMeetingParticipation(biddingCompanyId: number, participated: boolean) {
try {
const result = await db.update(biddingCompanies)
.set({
isAttendingMeeting: participated,
updatedAt: new Date(),
})
.where(eq(biddingCompanies.id, biddingCompanyId))
.returning({ biddingId: biddingCompanies.biddingId })
if (result.length > 0) {
const biddingId = result[0].biddingId
revalidateTag(`bidding-${biddingId}`)
revalidateTag('quotation-vendors')
revalidatePath(`/partners/bid/${biddingId}`)
}
return {
success: true,
message: `사양설명회 참여상태가 ${participated ? '참여' : '불참'}로 업데이트되었습니다.`,
}
} catch (error) {
console.error('Failed to update specification meeting participation:', error)
return { success: false, error: '사양설명회 참여상태 업데이트에 실패했습니다.' }
}
}
|