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
|
'use client'
import * as React from 'react'
import { Package, Plus, Trash2, Save, RefreshCw, FileText, FileSpreadsheet, Upload } from 'lucide-react'
import { getPRItemsForBidding } from '@/lib/bidding/detail/service'
import { updatePrItem } from '@/lib/bidding/detail/service'
import { toast } from 'sonner'
import { useSession } from 'next-auth/react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Checkbox } from '@/components/ui/checkbox'
import { ProjectSelector } from '@/components/bidding/ProjectSelectorBid'
import { MaterialGroupSelectorDialogSingle } from '@/components/common/material/material-group-selector-dialog-single'
import { MaterialSelectorDialogSingle } from '@/components/common/selectors/material/material-selector-dialog-single'
import { WbsCodeSingleSelector } from '@/components/common/selectors/wbs-code/wbs-code-single-selector'
import { CostCenterSingleSelector } from '@/components/common/selectors/cost-center/cost-center-single-selector'
import { GlAccountSingleSelector } from '@/components/common/selectors/gl-account/gl-account-single-selector'
// PR 아이템 정보 타입 (create-bidding-dialog와 동일)
export interface PRItemInfo {
id: number // 실제 DB ID
prNumber?: string | null
projectId?: number | null
projectInfo?: string | null
shi?: string | null
quantity?: string | null
quantityUnit?: string | null
totalWeight?: string | null
weightUnit?: string | null
materialDescription?: string | null
hasSpecDocument?: boolean
requestedDeliveryDate?: string | null
isRepresentative?: boolean // 대표 아이템 여부
// 가격 정보
annualUnitPrice?: string | null
currency?: string | null
// 자재 그룹 정보 (필수)
materialGroupNumber?: string | null
materialGroupInfo?: string | null
// 자재 정보
materialNumber?: string | null
materialInfo?: string | null
// 단위 정보
priceUnit?: string | null
purchaseUnit?: string | null
materialWeight?: string | null
// WBS 정보
wbsCode?: string | null
wbsName?: string | null
// Cost Center 정보
costCenterCode?: string | null
costCenterName?: string | null
// GL Account 정보
glAccountCode?: string | null
glAccountName?: string | null
// 내정 정보
targetUnitPrice?: string | null
targetAmount?: string | null
targetCurrency?: string | null
// 예산 정보
budgetAmount?: string | null
budgetCurrency?: string | null
// 실적 정보
actualAmount?: string | null
actualCurrency?: string | null
}
interface BiddingItemsEditorProps {
biddingId: number
readonly?: boolean
}
import { removeBiddingItem, addPRItemForBidding, getBiddingById, getBiddingConditions } from '@/lib/bidding/service'
import { CreatePreQuoteRfqDialog } from './create-pre-quote-rfq-dialog'
import { ProcurementItemSelectorDialogSingle } from '@/components/common/selectors/procurement-item/procurement-item-selector-dialog-single'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { exportBiddingItemsToExcel } from '@/lib/bidding/manage/export-bidding-items-to-excel'
import { importBiddingItemsFromExcel } from '@/lib/bidding/manage/import-bidding-items-from-excel'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
export function BiddingItemsEditor({ biddingId, readonly = false }: BiddingItemsEditorProps) {
const { data: session } = useSession()
const [items, setItems] = React.useState<PRItemInfo[]>([])
const [isLoading, setIsLoading] = React.useState(false)
const [isSubmitting, setIsSubmitting] = React.useState(false)
const [quantityWeightMode, setQuantityWeightMode] = React.useState<'quantity' | 'weight'>('quantity')
const [costCenterDialogOpen, setCostCenterDialogOpen] = React.useState(false)
const [selectedItemForCostCenter, setSelectedItemForCostCenter] = React.useState<number | null>(null)
const [glAccountDialogOpen, setGlAccountDialogOpen] = React.useState(false)
const [selectedItemForGlAccount, setSelectedItemForGlAccount] = React.useState<number | null>(null)
const [wbsCodeDialogOpen, setWbsCodeDialogOpen] = React.useState(false)
const [selectedItemForWbs, setSelectedItemForWbs] = React.useState<number | null>(null)
const [tempIdCounter, setTempIdCounter] = React.useState(0) // 임시 ID 카운터
const [deletedItemIds, setDeletedItemIds] = React.useState<Set<number>>(new Set()) // 삭제된 아이템 ID 추적
const [preQuoteDialogOpen, setPreQuoteDialogOpen] = React.useState(false)
const [targetPriceCalculationCriteria, setTargetPriceCalculationCriteria] = React.useState('')
const [biddingPicUserId, setBiddingPicUserId] = React.useState<number | null>(null)
const [biddingType, setBiddingType] = React.useState<string | null>(null)
const [biddingConditions, setBiddingConditions] = React.useState<{
paymentTerms?: string | null
taxConditions?: string | null
incoterms?: string | null
incotermsOption?: string | null
contractDeliveryDate?: string | null
shippingPort?: string | null
destinationPort?: string | null
isPriceAdjustmentApplicable?: boolean | null
sparePartOptions?: string | null
} | null>(null)
const [importDialogOpen, setImportDialogOpen] = React.useState(false)
const [importFile, setImportFile] = React.useState<File | null>(null)
const [importErrors, setImportErrors] = React.useState<string[]>([])
const [isImporting, setIsImporting] = React.useState(false)
const [isExporting, setIsExporting] = React.useState(false)
// 초기 데이터 로딩 - 기존 품목이 있으면 자동으로 로드
React.useEffect(() => {
const loadItems = async () => {
if (!biddingId) return
setIsLoading(true)
try {
const prItems = await getPRItemsForBidding(biddingId)
if (prItems && prItems.length > 0) {
const formattedItems: PRItemInfo[] = prItems.map((item) => ({
id: item.id,
prNumber: item.prNumber || null,
projectId: item.projectId || null,
projectInfo: item.projectInfo || null,
shi: item.shi || null,
quantity: item.quantity ? item.quantity.toString() : null,
quantityUnit: item.quantityUnit || null,
totalWeight: item.totalWeight ? item.totalWeight.toString() : null,
weightUnit: item.weightUnit || null,
materialDescription: item.itemInfo || null,
hasSpecDocument: item.hasSpecDocument || false,
requestedDeliveryDate: item.requestedDeliveryDate ? new Date(item.requestedDeliveryDate).toISOString().split('T')[0] : null,
isRepresentative: false, // 첫 번째 아이템을 대표로 설정할 수 있음
annualUnitPrice: item.annualUnitPrice ? item.annualUnitPrice.toString() : null,
currency: item.currency || 'KRW',
materialGroupNumber: item.materialGroupNumber || null,
materialGroupInfo: item.materialGroupInfo || null,
materialNumber: item.materialNumber || null,
materialInfo: item.materialInfo || null,
priceUnit: item.priceUnit || null,
purchaseUnit: item.purchaseUnit || null,
materialWeight: item.materialWeight ? item.materialWeight.toString() : null,
wbsCode: item.wbsCode || null,
wbsName: item.wbsName || null,
costCenterCode: item.costCenterCode || null,
costCenterName: item.costCenterName || null,
glAccountCode: item.glAccountCode || null,
glAccountName: item.glAccountName || null,
targetUnitPrice: item.targetUnitPrice ? item.targetUnitPrice.toString() : null,
targetAmount: item.targetAmount ? item.targetAmount.toString() : null,
targetCurrency: item.targetCurrency || 'KRW',
budgetAmount: item.budgetAmount ? item.budgetAmount.toString() : null,
budgetCurrency: item.budgetCurrency || 'KRW',
actualAmount: item.actualAmount ? item.actualAmount.toString() : null,
actualCurrency: item.actualCurrency || 'KRW',
}))
// 첫 번째 아이템을 대표로 설정
if (formattedItems.length > 0) {
formattedItems[0].isRepresentative = true
}
setItems(formattedItems)
setDeletedItemIds(new Set()) // 삭제 목록 초기화
// 기존 품목 로드 성공 알림 (조용히 표시, 선택적)
console.log(`기존 품목 ${formattedItems.length}개를 불러왔습니다.`)
} else {
// 품목이 없을 때는 빈 배열로 초기화
setItems([])
setDeletedItemIds(new Set())
}
} catch (error) {
console.error('Failed to load items:', error)
toast.error('품목 정보를 불러오는데 실패했습니다.')
// 에러 발생 시에도 빈 배열로 초기화하여 UI가 깨지지 않도록
setItems([])
setDeletedItemIds(new Set())
} finally {
setIsLoading(false)
}
}
loadItems()
}, [biddingId])
// 입찰 정보 및 조건 로드 (사전견적 다이얼로그용)
React.useEffect(() => {
const loadBiddingInfo = async () => {
if (!biddingId) return
try {
const [bidding, conditions] = await Promise.all([
getBiddingById(biddingId),
getBiddingConditions(biddingId)
])
if (bidding) {
console.log('📋 bidding:', bidding.biddingType)
setBiddingPicUserId(bidding.bidPicId || null)
setBiddingType(bidding.biddingType || null)
setTargetPriceCalculationCriteria(bidding.targetPriceCalculationCriteria || '')
}
if (conditions) {
setBiddingConditions(conditions)
}
} catch (error) {
console.error('Failed to load bidding info:', error)
}
}
loadBiddingInfo()
}, [biddingId])
const handleSave = async () => {
setIsSubmitting(true)
try {
const userId = session?.user?.id?.toString() || '1'
let hasError = false
// 필수값 검증
for (let i = 0; i < items.length; i++) {
const item = items[i];
// 필수값: 자재그룹코드, 자재그룹명
if (!item.materialGroupNumber || !item.materialGroupInfo) {
toast.error(`${i + 1}번 품목의 자재그룹 정보를 입력해주세요.`);
setIsSubmitting(false);
return;
}
// 필수값: 수량 또는 중량
if (quantityWeightMode === 'quantity') {
if (!item.quantity || parseFloat(item.quantity) <= 0) {
toast.error(`${i + 1}번 품목의 수량을 입력해주세요.`);
setIsSubmitting(false);
return;
}
if (!item.quantityUnit) {
toast.error(`${i + 1}번 품목의 수량 단위를 선택해주세요.`);
setIsSubmitting(false);
return;
}
} else {
if (!item.totalWeight || parseFloat(item.totalWeight) <= 0) {
toast.error(`${i + 1}번 품목의 중량을 입력해주세요.`);
setIsSubmitting(false);
return;
}
if (!item.weightUnit) {
toast.error(`${i + 1}번 품목의 중량 단위를 선택해주세요.`);
setIsSubmitting(false);
return;
}
}
// 필수값: 납품요청일
if (!item.requestedDeliveryDate) {
toast.error(`${i + 1}번 품목의 납품요청일을 입력해주세요.`);
setIsSubmitting(false);
return;
}
// 필수값: 내정단가 (사용자 요청)
if (!item.targetUnitPrice || parseFloat(item.targetUnitPrice.replace(/,/g, '')) <= 0) {
toast.error(`${i + 1}번 품목의 내정단가를 입력해주세요.`);
setIsSubmitting(false);
return;
}
}
// 모든 아이템을 upsert 처리 (id가 있으면 update, 없으면 insert)
for (const item of items) {
const targetAmount = calculateTargetAmount(item)
let result
if (item.id > 0) {
// 기존 아이템 업데이트
result = await updatePrItem(item.id, {
projectId: item.projectId || null,
projectInfo: item.projectInfo || null,
shi: item.shi || null,
materialGroupNumber: item.materialGroupNumber || null,
materialGroupInfo: item.materialGroupInfo || null,
materialNumber: item.materialNumber || null,
materialInfo: item.materialInfo || null,
quantity: item.quantity ? parseFloat(item.quantity) : null,
quantityUnit: item.quantityUnit || null,
totalWeight: item.totalWeight ? parseFloat(item.totalWeight) : null,
weightUnit: item.weightUnit || null,
priceUnit: item.priceUnit || null,
purchaseUnit: item.purchaseUnit || null,
materialWeight: item.materialWeight ? parseFloat(item.materialWeight) : null,
wbsCode: item.wbsCode || null,
wbsName: item.wbsName || null,
costCenterCode: item.costCenterCode || null,
costCenterName: item.costCenterName || null,
glAccountCode: item.glAccountCode || null,
glAccountName: item.glAccountName || null,
targetUnitPrice: item.targetUnitPrice ? parseFloat(item.targetUnitPrice.replace(/,/g, '')) : null,
targetAmount: targetAmount ? parseFloat(targetAmount) : null,
targetCurrency: item.targetCurrency || 'KRW',
budgetAmount: item.budgetAmount ? parseFloat(item.budgetAmount.replace(/,/g, '')) : null,
budgetCurrency: item.budgetCurrency || 'KRW',
actualAmount: item.actualAmount ? parseFloat(item.actualAmount.replace(/,/g, '')) : null,
actualCurrency: item.actualCurrency || 'KRW',
requestedDeliveryDate: item.requestedDeliveryDate ? new Date(item.requestedDeliveryDate) : null,
currency: item.currency || 'KRW',
annualUnitPrice: item.annualUnitPrice ? parseFloat(item.annualUnitPrice) : null,
prNumber: item.prNumber || null,
hasSpecDocument: item.hasSpecDocument || false,
} as Parameters<typeof updatePrItem>[1], userId)
} else {
// 새 아이템 추가 (문자열 타입만 허용)
result = await addPRItemForBidding(biddingId, {
projectId: item.projectId ?? undefined,
projectInfo: item.projectInfo ?? null,
shi: item.shi ?? null,
materialGroupNumber: item.materialGroupNumber ?? null,
materialGroupInfo: item.materialGroupInfo ?? null,
materialNumber: item.materialNumber ?? null,
materialInfo: item.materialInfo ?? null,
quantity: item.quantity ?? null,
quantityUnit: item.quantityUnit ?? null,
totalWeight: item.totalWeight ?? null,
weightUnit: item.weightUnit ?? null,
priceUnit: item.priceUnit ?? null,
purchaseUnit: item.purchaseUnit ?? null,
materialWeight: item.materialWeight ?? null,
wbsCode: item.wbsCode ?? null,
wbsName: item.wbsName ?? null,
costCenterCode: item.costCenterCode ?? null,
costCenterName: item.costCenterName ?? null,
glAccountCode: item.glAccountCode ?? null,
glAccountName: item.glAccountName ?? null,
targetUnitPrice: item.targetUnitPrice ? item.targetUnitPrice.replace(/,/g, '') : null,
targetAmount: targetAmount,
targetCurrency: item.targetCurrency || 'KRW',
budgetAmount: item.budgetAmount ? item.budgetAmount.replace(/,/g, '') : null,
budgetCurrency: item.budgetCurrency || 'KRW',
actualAmount: item.actualAmount ? item.actualAmount.replace(/,/g, '') : null,
actualCurrency: item.actualCurrency || 'KRW',
requestedDeliveryDate: item.requestedDeliveryDate ?? null,
currency: item.currency || 'KRW',
annualUnitPrice: item.annualUnitPrice ?? null,
prNumber: item.prNumber ?? null,
hasSpecDocument: item.hasSpecDocument || false,
})
}
if (!result.success) {
hasError = true
}
}
// 삭제된 아이템들 서버에서 삭제
for (const deletedId of deletedItemIds) {
const result = await removeBiddingItem(deletedId)
if (!result.success) {
hasError = true
}
}
if (hasError) {
toast.error('일부 품목 정보 저장에 실패했습니다.')
} else {
// 내정가 산정 기준 별도 저장 (서버 액션으로 처리)
if (targetPriceCalculationCriteria.trim()) {
try {
const { updateTargetPriceCalculationCriteria } = await import('@/lib/bidding/service')
const criteriaResult = await updateTargetPriceCalculationCriteria(biddingId, targetPriceCalculationCriteria.trim(), userId)
if (!criteriaResult.success) {
console.warn('Failed to save target price calculation criteria:', criteriaResult.error)
}
} catch (error) {
console.error('Failed to save target price calculation criteria:', error)
}
}
toast.success('품목 정보가 성공적으로 저장되었습니다.')
// 삭제 목록 초기화
setDeletedItemIds(new Set())
// 데이터 다시 로딩하여 최신 상태 반영
console.log('🔄 저장 후 데이터 재로드 시작 - biddingId:', biddingId)
const prItems = await getPRItemsForBidding(biddingId)
console.log('📦 getPRItemsForBidding 결과:', prItems)
if (prItems && prItems.length > 0) {
console.log('✅ 저장된 아이템 수:', prItems.length)
const formattedItems: PRItemInfo[] = prItems.map((item, index) => {
console.log(`🔍 아이템 ${index + 1}:`, {
id: item.id,
materialGroupNumber: item.materialGroupNumber,
materialNumber: item.materialNumber,
quantity: item.quantity
})
return {
id: item.id,
prNumber: item.prNumber || null,
projectId: item.projectId || null,
projectInfo: item.projectInfo || null,
shi: item.shi || null,
quantity: item.quantity ? item.quantity.toString() : null,
quantityUnit: item.quantityUnit || null,
totalWeight: item.totalWeight ? item.totalWeight.toString() : null,
weightUnit: item.weightUnit || null,
materialDescription: item.itemInfo || null,
hasSpecDocument: item.hasSpecDocument || false,
requestedDeliveryDate: item.requestedDeliveryDate ? new Date(item.requestedDeliveryDate).toISOString().split('T')[0] : null,
isRepresentative: false,
annualUnitPrice: item.annualUnitPrice ? item.annualUnitPrice.toString() : null,
currency: item.currency || 'KRW',
materialGroupNumber: item.materialGroupNumber || null,
materialGroupInfo: item.materialGroupInfo || null,
materialNumber: item.materialNumber || null,
materialInfo: item.materialInfo || null,
priceUnit: item.priceUnit || null,
purchaseUnit: item.purchaseUnit || null,
materialWeight: item.materialWeight ? item.materialWeight.toString() : null,
wbsCode: item.wbsCode || null,
wbsName: item.wbsName || null,
costCenterCode: item.costCenterCode || null,
costCenterName: item.costCenterName || null,
glAccountCode: item.glAccountCode || null,
glAccountName: item.glAccountName || null,
targetUnitPrice: item.targetUnitPrice ? item.targetUnitPrice.toString() : null,
targetAmount: item.targetAmount ? item.targetAmount.toString() : null,
targetCurrency: item.targetCurrency || 'KRW',
budgetAmount: item.budgetAmount ? item.budgetAmount.toString() : null,
budgetCurrency: item.budgetCurrency || 'KRW',
actualAmount: item.actualAmount ? item.actualAmount.toString() : null,
actualCurrency: item.actualCurrency || 'KRW',
}
})
// 첫 번째 아이템을 대표로 설정
if (formattedItems.length > 0) {
formattedItems[0].isRepresentative = true
}
console.log('📋 최종 formattedItems:', formattedItems)
setItems(formattedItems)
console.log('✅ 상태 업데이트 완료')
} else {
console.log('❌ 저장 후 데이터가 없음 - 빈 배열 설정')
// 저장 후 데이터가 없으면 빈 배열로 설정
setItems([])
}
}
} catch (error) {
console.error('Failed to save items:', error)
toast.error('품목 정보 저장에 실패했습니다.')
} finally {
setIsSubmitting(false)
}
}
const handleAddItem = () => {
// 임시 ID 생성 (음수로 구분하여 실제 DB ID와 구분)
const tempId = -(tempIdCounter + 1)
setTempIdCounter(prev => prev + 1)
// 즉시 UI에 새 아이템 추가 (서버 저장 없음)
const newItem: PRItemInfo = {
id: tempId, // 임시 ID
prNumber: null,
projectId: null,
projectInfo: null,
shi: null,
quantity: null,
quantityUnit: 'EA',
totalWeight: null,
weightUnit: 'KG',
materialDescription: null,
hasSpecDocument: false,
requestedDeliveryDate: null,
isRepresentative: items.length === 0,
annualUnitPrice: null,
currency: 'KRW',
materialGroupNumber: null,
materialGroupInfo: null,
materialNumber: null,
materialInfo: null,
priceUnit: '1',
purchaseUnit: 'EA',
materialWeight: null,
wbsCode: null,
wbsName: null,
costCenterCode: null,
costCenterName: null,
glAccountCode: null,
glAccountName: null,
targetUnitPrice: null,
targetAmount: null,
targetCurrency: 'KRW',
budgetAmount: null,
budgetCurrency: 'KRW',
actualAmount: null,
actualCurrency: 'KRW',
}
setItems((prev) => {
// 첫 번째 아이템이면 대표로 설정
if (prev.length === 0) {
return [newItem]
}
return [...prev, newItem]
})
}
const handleRemoveItem = (itemId: number) => {
if (items.length <= 1) {
toast.error('최소 하나의 품목이 필요합니다.')
return
}
// 실제 아이템인 경우 삭제 목록에 추가 (저장 시 서버에서 삭제됨)
if (itemId > 0) {
setDeletedItemIds(prev => new Set([...prev, itemId]))
}
// UI에서 즉시 제거
setItems((prev) => {
const filteredItems = prev.filter((item) => item.id !== itemId)
const removedItem = prev.find((item) => item.id === itemId)
if (removedItem?.isRepresentative && filteredItems.length > 0) {
filteredItems[0].isRepresentative = true
}
return filteredItems
})
}
const updatePRItem = (id: number, updates: Partial<PRItemInfo>) => {
setItems((prev) =>
prev.map((item) => {
if (item.id === id) {
const updatedItem = { ...item, ...updates }
// 내정단가, 수량, 중량, 가격단위가 변경되면 내정금액 재계산
if (updates.targetUnitPrice || updates.quantity || updates.totalWeight || updates.priceUnit) {
updatedItem.targetAmount = calculateTargetAmount(updatedItem)
}
return updatedItem
}
return item
})
)
}
const setRepresentativeItem = (id: number) => {
setItems((prev) =>
prev.map((item) => ({
...item,
isRepresentative: item.id === id,
}))
)
}
const handleQuantityWeightModeChange = (mode: 'quantity' | 'weight') => {
setQuantityWeightMode(mode)
}
// 천단위 콤마 포맷팅 헬퍼 함수들
const formatNumberWithCommas = (value: string | number | null | undefined): string => {
if (!value) return ''
const numValue = typeof value === 'number' ? value : parseFloat(value.toString().replace(/,/g, ''))
if (isNaN(numValue)) return ''
return numValue.toLocaleString()
}
const parseNumberFromCommas = (value: string): string => {
return value.replace(/,/g, '')
}
const calculateTargetAmount = (item: PRItemInfo): string => {
const unitPrice = parseFloat(item.targetUnitPrice?.replace(/,/g, '') || '0') || 0
const priceUnit = parseFloat(item.priceUnit || '1') || 1
let amount = 0
if (quantityWeightMode === 'quantity') {
const quantity = parseFloat(item.quantity || '0') || 0
amount = (quantity / priceUnit) * unitPrice
} else {
const weight = parseFloat(item.totalWeight || '0') || 0
amount = (weight / priceUnit) * unitPrice
}
return Math.floor(amount).toString()
}
// 합계 계산 함수들
const calculateTotals = () => {
let quantityTotal = 0
let weightTotal = 0
let targetAmountTotal = 0
let budgetAmountTotal = 0
let actualAmountTotal = 0
items.forEach((item) => {
// 수량 합계
if (item.quantity) {
quantityTotal += parseFloat(item.quantity) || 0
}
// 중량 합계
if (item.totalWeight) {
weightTotal += parseFloat(item.totalWeight) || 0
}
// 내정금액 합계
if (item.targetAmount) {
targetAmountTotal += parseFloat(item.targetAmount.replace(/,/g, '')) || 0
}
// 예산금액 합계
if (item.budgetAmount) {
budgetAmountTotal += parseFloat(item.budgetAmount.replace(/,/g, '')) || 0
}
// 실적금액 합계
if (item.actualAmount) {
actualAmountTotal += parseFloat(item.actualAmount.replace(/,/g, '')) || 0
}
})
return {
quantityTotal,
weightTotal,
targetAmountTotal,
budgetAmountTotal,
actualAmountTotal,
}
}
const totals = calculateTotals()
// Excel 내보내기 핸들러
const handleExport = React.useCallback(async () => {
if (items.length === 0) {
toast.error('내보낼 품목이 없습니다.')
return
}
try {
setIsExporting(true)
await exportBiddingItemsToExcel(items, {
filename: `입찰품목목록_${biddingId}`,
})
toast.success('Excel 파일이 다운로드되었습니다.')
} catch (error) {
console.error('Excel export error:', error)
toast.error('Excel 내보내기 중 오류가 발생했습니다.')
} finally {
setIsExporting(false)
}
}, [items, biddingId])
// Excel 가져오기 핸들러
const handleImportFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (file) {
if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
toast.error('Excel 파일(.xlsx, .xls)만 업로드 가능합니다.')
return
}
setImportFile(file)
setImportErrors([])
}
}
const handleImport = async () => {
if (!importFile) return
setIsImporting(true)
setImportErrors([])
try {
const result = await importBiddingItemsFromExcel(importFile)
if (result.errors.length > 0) {
setImportErrors(result.errors)
toast.warning(
`${result.items.length}개의 품목을 파싱했지만 ${result.errors.length}개의 오류가 있습니다.`
)
return
}
if (result.items.length === 0) {
toast.error('가져올 품목이 없습니다.')
return
}
// 기존 아이템에 추가
setItems((prev) => [...prev, ...result.items])
setImportDialogOpen(false)
setImportFile(null)
setImportErrors([])
toast.success(`${result.items.length}개의 품목이 추가되었습니다.`)
} catch (error) {
console.error('Excel import error:', error)
toast.error('Excel 가져오기 중 오류가 발생했습니다.')
} finally {
setIsImporting(false)
}
}
if (isLoading) {
return (
<div className="flex items-center justify-center p-8">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
<span className="ml-2">품목 정보를 불러오는 중...</span>
</div>
)
}
// PR 아이템 테이블 렌더링 (create-bidding-dialog와 동일한 구조)
const renderPrItemsTable = () => {
return (
<div className="border rounded-lg overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full border-collapse">
<thead className="bg-muted/50">
<tr>
<th className="sticky left-0 z-10 bg-muted/50 border-r px-2 py-3 text-left text-xs font-medium min-w-[50px]">
<span className="sr-only">대표</span>
</th>
<th className="sticky left-[50px] z-10 bg-muted/50 border-r px-3 py-3 text-left text-xs font-medium min-w-[40px]">
#
</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">프로젝트코드</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[300px]">프로젝트명</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[150px]">자재그룹코드 <span className="text-red-500">*</span></th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[300px]">자재그룹명 <span className="text-red-500">*</span></th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[150px]">자재코드</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[300px]">자재명</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">수량(중량) <span className="text-red-500">*</span></th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[80px]">단위 <span className="text-red-500">*</span></th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">납품요청일 <span className="text-red-500">*</span></th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[80px]">가격단위</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[80px]">구매단위</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[100px]">자재순중량</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">내정단가</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">내정금액</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[80px]">내정통화</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">예산금액</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[80px]">예산통화</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">실적금액</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[80px]">실적통화</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[300px]">WBS코드</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[150px]">WBS명</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">코스트센터코드</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[150px]">코스트센터명</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">GL계정코드</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[150px]">GL계정명</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">PR 번호</th>
<th className="sticky right-0 z-10 bg-muted/50 border-l px-3 py-3 text-center text-xs font-medium min-w-[100px]">
액션
</th>
</tr>
</thead>
<tbody>
{/* 합계 행 */}
<tr className="bg-blue-50 border-y-2 border-blue-200 font-semibold">
<td className="sticky left-0 z-10 bg-blue-50 border-r px-2 py-3 text-center">
<span className="text-xs">합계</span>
</td>
<td className="sticky left-[50px] z-10 bg-blue-50 border-r px-3 py-3 text-center">
<span className="text-xs">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs">
{quantityWeightMode === 'quantity'
? `${formatNumberWithCommas(totals.quantityTotal.toString())}`
: `${formatNumberWithCommas(totals.weightTotal.toString())}`
}
</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs">
{quantityWeightMode === 'quantity'
? `${items[0]?.quantityUnit || 'EA'}`
: `${items[0]?.weightUnit || 'KG'}`
}
</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs">{formatNumberWithCommas(totals.targetAmountTotal.toString())}</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs">{formatNumberWithCommas(totals.budgetAmountTotal.toString())}</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs">{formatNumberWithCommas(totals.actualAmountTotal.toString())}</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="border-r px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
<td className="sticky right-0 z-10 bg-blue-50 border-l px-3 py-3 text-center">
<span className="text-xs text-muted-foreground">-</span>
</td>
</tr>
{items.map((item, index) => (
<tr key={item.id} className="border-t hover:bg-muted/30">
<td className="sticky left-0 z-10 bg-background border-r px-2 py-2 text-center">
<Checkbox
checked={item.isRepresentative}
onCheckedChange={() => setRepresentativeItem(item.id)}
disabled={(items.length <= 1 && item.isRepresentative) || readonly}
title="대표 아이템"
/>
</td>
<td className="sticky left-[50px] z-10 bg-background border-r px-3 py-2 text-xs text-muted-foreground">
{index + 1}
</td>
<td className="border-r px-3 py-2">
<ProjectSelector
selectedProjectId={item.projectId || null}
onProjectSelect={(project) => {
if (project) {
updatePRItem(item.id, {
projectId: project.id,
projectInfo: project.projectName
})
} else {
updatePRItem(item.id, {
projectId: null,
projectInfo: null
})
}
}}
placeholder="프로젝트 선택"
disabled={readonly}
/>
</td>
<td className="border-r px-3 py-2">
<Input
placeholder="프로젝트명"
value={item.projectInfo || ''}
readOnly
className="h-8 text-xs bg-muted/50"
/>
</td>
<td className="border-r px-3 py-2">
{biddingType !== 'equipment' ? (
<ProcurementItemSelectorDialogSingle
triggerLabel={item.materialGroupNumber || "품목 선택"}
triggerVariant="outline"
selectedProcurementItem={item.materialGroupNumber ? {
itemCode: item.materialGroupNumber,
itemName: item.materialGroupInfo || '',
displayText: `${item.materialGroupNumber}`
} : null}
onProcurementItemSelect={(procurementItem) => {
if (procurementItem) {
updatePRItem(item.id, {
materialGroupNumber: procurementItem.itemCode,
materialGroupInfo: procurementItem.itemName
})
} else {
updatePRItem(item.id, {
materialGroupNumber: '',
materialGroupInfo: ''
})
}
}}
title="1회성 품목 선택"
description="1회성 품목을 검색하고 선택해주세요."
disabled={readonly}
/>
) : (
<MaterialGroupSelectorDialogSingle
triggerLabel={item.materialGroupNumber || "자재그룹 선택"}
triggerVariant="outline"
selectedMaterial={item.materialGroupNumber ? {
materialGroupCode: item.materialGroupNumber,
materialGroupDescription: item.materialGroupInfo || '',
displayText: `${item.materialGroupNumber}`
} : null}
onMaterialSelect={(material) => {
if (material) {
updatePRItem(item.id, {
materialGroupNumber: material.materialGroupCode,
materialGroupInfo: material.materialGroupDescription
})
} else {
updatePRItem(item.id, {
materialGroupNumber: '',
materialGroupInfo: ''
})
}
}}
title="자재그룹 선택"
description="자재그룹을 검색하고 선택해주세요."
disabled={readonly}
/>
)}
</td>
<td className="border-r px-3 py-2">
<Input
placeholder="자재그룹명"
value={item.materialGroupInfo || ''}
readOnly
className="h-8 text-xs bg-muted/50"
/>
</td>
<td className="border-r px-3 py-2">
<MaterialSelectorDialogSingle
triggerLabel={item.materialNumber || "자재 선택"}
triggerVariant="outline"
selectedMaterial={item.materialNumber ? {
materialCode: item.materialNumber,
materialName: item.materialInfo || '',
displayText: `${item.materialNumber}`
} : null}
onMaterialSelect={(material) => {
if (material) {
updatePRItem(item.id, {
materialNumber: material.materialCode,
materialInfo: material.materialName
})
} else {
updatePRItem(item.id, {
materialNumber: '',
materialInfo: ''
})
}
}}
title="자재 선택"
description="자재를 검색하고 선택해주세요."
disabled={readonly}
/>
</td>
<td className="border-r px-3 py-2">
<Input
placeholder="자재명"
value={item.materialInfo || ''}
readOnly
className="h-8 text-xs bg-muted/50"
/>
</td>
<td className="border-r px-3 py-2">
{quantityWeightMode === 'quantity' ? (
<Input
type="number"
min="0"
step="0.001"
placeholder="수량"
value={item.quantity || ''}
onChange={(e) => updatePRItem(item.id, { quantity: e.target.value })}
className="h-8 text-xs"
required
disabled={readonly}
/>
) : (
<Input
type="number"
min="0"
step="0.001"
placeholder="중량"
value={item.totalWeight || ''}
onChange={(e) => updatePRItem(item.id, { totalWeight: e.target.value })}
className="h-8 text-xs"
required
disabled={readonly}
/>
)}
</td>
<td className="border-r px-3 py-2">
{quantityWeightMode === 'quantity' ? (
<Select
value={item.quantityUnit || 'EA'}
onValueChange={(value) => updatePRItem(item.id, { quantityUnit: value })}
required
disabled={readonly}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="EA">EA</SelectItem>
<SelectItem value="SET">SET</SelectItem>
<SelectItem value="LOT">LOT</SelectItem>
<SelectItem value="M">M</SelectItem>
<SelectItem value="M2">M²</SelectItem>
<SelectItem value="M3">M³</SelectItem>
</SelectContent>
</Select>
) : (
<Select
value={item.weightUnit || 'KG'}
onValueChange={(value) => updatePRItem(item.id, { weightUnit: value })}
required
disabled={readonly}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="KG">KG</SelectItem>
<SelectItem value="TON">TON</SelectItem>
<SelectItem value="G">G</SelectItem>
<SelectItem value="LB">LB</SelectItem>
</SelectContent>
</Select>
)}
</td>
<td className="border-r px-3 py-2">
<Input
type="date"
value={item.requestedDeliveryDate || ''}
onChange={(e) => updatePRItem(item.id, { requestedDeliveryDate: e.target.value })}
className="h-8 text-xs"
required
disabled={readonly}
min="1900-01-01"
max="2100-12-31"
/>
</td>
<td className="border-r px-3 py-2">
<Input
type="number"
min="1"
step="1"
placeholder="가격단위"
value={item.priceUnit || ''}
onChange={(e) => updatePRItem(item.id, { priceUnit: e.target.value })}
className="h-8 text-xs"
disabled={readonly}
/>
</td>
<td className="border-r px-3 py-2">
<Select
value={item.purchaseUnit || 'EA'}
onValueChange={(value) => updatePRItem(item.id, { purchaseUnit: value })}
disabled={readonly}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="EA">EA</SelectItem>
<SelectItem value="SET">SET</SelectItem>
<SelectItem value="LOT">LOT</SelectItem>
<SelectItem value="M">M</SelectItem>
<SelectItem value="M2">M²</SelectItem>
<SelectItem value="M3">M³</SelectItem>
<SelectItem value="KG">KG</SelectItem>
<SelectItem value="TON">TON</SelectItem>
<SelectItem value="G">G</SelectItem>
<SelectItem value="LB">LB</SelectItem>
</SelectContent>
</Select>
</td>
<td className="border-r px-3 py-2">
<Input
type="number"
min="0"
step="0.001"
placeholder="자재순중량"
value={item.materialWeight || ''}
onChange={(e) => updatePRItem(item.id, { materialWeight: e.target.value })}
className="h-8 text-xs"
disabled={readonly}
/>
</td>
<td className="border-r px-3 py-2">
<Input
type="text"
placeholder="내정단가"
value={formatNumberWithCommas(item.targetUnitPrice)}
onChange={(e) => updatePRItem(item.id, { targetUnitPrice: parseNumberFromCommas(e.target.value) })}
className="h-8 text-xs"
disabled={readonly}
/>
</td>
<td className="border-r px-3 py-2">
<Input
type="text"
placeholder="내정금액"
readOnly
value={formatNumberWithCommas(item.targetAmount)}
className="h-8 text-xs bg-muted/50"
/>
</td>
<td className="border-r px-3 py-2">
<Select
value={item.targetCurrency || 'KRW'}
onValueChange={(value) => updatePRItem(item.id, { targetCurrency: value })}
disabled={readonly}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="KRW">KRW</SelectItem>
<SelectItem value="USD">USD</SelectItem>
<SelectItem value="EUR">EUR</SelectItem>
<SelectItem value="JPY">JPY</SelectItem>
</SelectContent>
</Select>
</td>
<td className="border-r px-3 py-2">
<Input
type="text"
placeholder="예산금액"
value={formatNumberWithCommas(item.budgetAmount)}
onChange={(e) => updatePRItem(item.id, { budgetAmount: parseNumberFromCommas(e.target.value) })}
className="h-8 text-xs"
disabled={readonly}
/>
</td>
<td className="border-r px-3 py-2">
<Select
value={item.budgetCurrency || 'KRW'}
onValueChange={(value) => updatePRItem(item.id, { budgetCurrency: value })}
disabled={readonly}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="KRW">KRW</SelectItem>
<SelectItem value="USD">USD</SelectItem>
<SelectItem value="EUR">EUR</SelectItem>
<SelectItem value="JPY">JPY</SelectItem>
</SelectContent>
</Select>
</td>
<td className="border-r px-3 py-2">
<Input
type="text"
placeholder="실적금액"
value={formatNumberWithCommas(item.actualAmount)}
onChange={(e) => updatePRItem(item.id, { actualAmount: parseNumberFromCommas(e.target.value) })}
className="h-8 text-xs"
disabled={readonly}
/>
</td>
<td className="border-r px-3 py-2">
<Select
value={item.actualCurrency || 'KRW'}
onValueChange={(value) => updatePRItem(item.id, { actualCurrency: value })}
disabled={readonly}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="KRW">KRW</SelectItem>
<SelectItem value="USD">USD</SelectItem>
<SelectItem value="EUR">EUR</SelectItem>
<SelectItem value="JPY">JPY</SelectItem>
</SelectContent>
</Select>
</td>
<td className="border-r px-3 py-2">
<Button
variant="outline"
onClick={() => {
// 재클릭 시 기존 데이터 클리어
updatePRItem(item.id, {
wbsCode: null,
wbsName: null
})
setSelectedItemForWbs(item.id)
setWbsCodeDialogOpen(true)
}}
className="w-full justify-start h-8 text-xs"
disabled={readonly}
>
{item.wbsCode ? (
<span className="truncate">
{`${item.wbsCode}`}
</span>
) : (
<span className="text-muted-foreground">WBS 코드 선택</span>
)}
</Button>
<WbsCodeSingleSelector
open={wbsCodeDialogOpen && selectedItemForWbs === item.id}
onOpenChange={(open) => {
setWbsCodeDialogOpen(open)
if (!open) setSelectedItemForWbs(null)
}}
selectedCode={item.wbsCode ? {
WBS_ELMT: item.wbsCode,
WBS_ELMT_NM: item.wbsName || '',
} : undefined}
onCodeSelect={(wbsCode) => {
updatePRItem(item.id, {
wbsCode: wbsCode.WBS_ELMT,
wbsName: wbsCode.WBS_ELMT_NM
})
setWbsCodeDialogOpen(false)
setSelectedItemForWbs(null)
}}
title="WBS 코드 선택"
description="WBS 코드를 선택하세요"
showConfirmButtons={false}
/>
</td>
<td className="border-r px-3 py-2">
<Input
placeholder="WBS명"
value={item.wbsName || ''}
readOnly
className="h-8 text-xs bg-muted/50"
/>
</td>
<td className="border-r px-3 py-2">
<Button
variant="outline"
onClick={() => {
// 재클릭 시 기존 데이터 클리어
updatePRItem(item.id, {
costCenterCode: null,
costCenterName: null
})
setSelectedItemForCostCenter(item.id)
setCostCenterDialogOpen(true)
}}
className="w-full justify-start h-8 text-xs"
disabled={readonly}
>
{item.costCenterCode ? (
<span className="truncate">
{`${item.costCenterCode}`}
</span>
) : (
<span className="text-muted-foreground">코스트센터 선택</span>
)}
</Button>
<CostCenterSingleSelector
open={costCenterDialogOpen && selectedItemForCostCenter === item.id}
onOpenChange={(open) => {
setCostCenterDialogOpen(open)
if (!open) setSelectedItemForCostCenter(null)
}}
selectedCode={item.costCenterCode ? {
KOSTL: item.costCenterCode,
KTEXT: item.costCenterName || '',
} : undefined}
onCodeSelect={(costCenter) => {
updatePRItem(item.id, {
costCenterCode: costCenter.KOSTL,
costCenterName: costCenter.KTEXT
})
setCostCenterDialogOpen(false)
setSelectedItemForCostCenter(null)
}}
title="코스트센터 선택"
description="코스트센터를 선택하세요"
showConfirmButtons={false}
/>
</td>
<td className="border-r px-3 py-2">
<Input
placeholder="코스트센터명"
value={item.costCenterName || ''}
readOnly
className="h-8 text-xs bg-muted/50"
/>
</td>
<td className="border-r px-3 py-2">
<Button
variant="outline"
onClick={() => {
// 재클릭 시 기존 데이터 클리어
updatePRItem(item.id, {
glAccountCode: null,
glAccountName: null
})
setSelectedItemForGlAccount(item.id)
setGlAccountDialogOpen(true)
}}
className="w-full justify-start h-8 text-xs"
disabled={readonly}
>
{item.glAccountCode ? (
<span className="truncate">
{`${item.glAccountCode}`}
</span>
) : (
<span className="text-muted-foreground">GL계정 선택</span>
)}
</Button>
<GlAccountSingleSelector
open={glAccountDialogOpen && selectedItemForGlAccount === item.id}
onOpenChange={(open) => {
setGlAccountDialogOpen(open)
if (!open) setSelectedItemForGlAccount(null)
}}
selectedCode={item.glAccountCode ? {
SAKNR: item.glAccountCode,
TEXT1: item.glAccountName || ''
} : undefined}
onCodeSelect={(glAccount) => {
updatePRItem(item.id, {
glAccountCode: glAccount.SAKNR,
glAccountName: glAccount.TEXT1
})
setGlAccountDialogOpen(false)
setSelectedItemForGlAccount(null)
}}
title="GL 계정 선택"
description="GL 계정을 선택하세요"
showConfirmButtons={false}
/>
</td>
<td className="border-r px-3 py-2">
<Input
placeholder="GL계정명"
value={item.glAccountName || ''}
readOnly
className="h-8 text-xs bg-muted/50"
/>
</td>
<td className="border-r px-3 py-2">
<Input
placeholder="PR 번호"
value={item.prNumber || ''}
readOnly
className="h-8 text-xs bg-muted/50"
/>
</td>
<td className="sticky right-0 z-10 bg-background border-l px-3 py-2">
<div className="flex items-center justify-center gap-1">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => handleRemoveItem(item.id)}
disabled={items.length <= 1 || readonly}
className="h-7 w-7 p-0"
title="품목 삭제"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
return (
<div className="space-y-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<div>
<CardTitle className="flex items-center gap-2">
<Package className="h-5 w-5" />
입찰 품목 목록
</CardTitle>
<p className="text-sm text-muted-foreground mt-1">
입찰 대상 품목들을 관리합니다. 최소 하나의 아이템이 필요하며, 자재그룹코드는 필수입니다
</p>
<p className="text-xs text-amber-600 mt-1">
수량/단위 또는 중량/중량단위를 선택해서 입력하세요
</p>
</div>
<div className="flex gap-2">
<Button onClick={() => setPreQuoteDialogOpen(true)} variant="outline" className="flex items-center gap-2" disabled={readonly}>
<FileText className="h-4 w-4" />
사전견적
</Button>
<Button onClick={handleExport} variant="outline" className="flex items-center gap-2" disabled={readonly || isExporting || items.length === 0}>
<FileSpreadsheet className="h-4 w-4" />
{isExporting ? "내보내는 중..." : "Excel 내보내기"}
</Button>
<Button onClick={() => setImportDialogOpen(true)} variant="outline" className="flex items-center gap-2" disabled={readonly}>
<Upload className="h-4 w-4" />
Excel 가져오기
</Button>
<Button onClick={handleAddItem} className="flex items-center gap-2" disabled={readonly}>
<Plus className="h-4 w-4" />
품목 추가
</Button>
</div>
</CardHeader>
<CardContent className="space-y-6">
{/* 내정가 산정 기준 입력 폼 */}
<div className="space-y-2">
<Label htmlFor="targetPriceCalculationCriteria">내정가 산정 기준 (선택)</Label>
<Textarea
id="targetPriceCalculationCriteria"
placeholder="내정가 산정 기준을 입력하세요"
value={targetPriceCalculationCriteria}
onChange={(e) => setTargetPriceCalculationCriteria(e.target.value)}
rows={3}
className="resize-none"
disabled={readonly}
/>
<p className="text-xs text-muted-foreground">
내정가를 산정한 기준이나 방법을 입력하세요
</p>
</div>
<div className="flex items-center space-x-4 p-4 bg-muted rounded-lg">
<div className="text-sm font-medium">계산 기준:</div>
<div className="flex items-center space-x-2">
<input
type="radio"
id="quantity-mode"
name="quantityWeightMode"
checked={quantityWeightMode === 'quantity'}
onChange={() => handleQuantityWeightModeChange('quantity')}
className="h-4 w-4"
disabled={readonly}
/>
<label htmlFor="quantity-mode" className="text-sm">수량 기준</label>
</div>
<div className="flex items-center space-x-2">
<input
type="radio"
id="weight-mode"
name="quantityWeightMode"
checked={quantityWeightMode === 'weight'}
onChange={() => handleQuantityWeightModeChange('weight')}
className="h-4 w-4"
disabled={readonly}
/>
<label htmlFor="weight-mode" className="text-sm">중량 기준</label>
</div>
</div>
<div className="space-y-4">
{items.length > 0 ? (
renderPrItemsTable()
) : (
<div className="text-center py-12 border-2 border-dashed border-gray-300 rounded-lg">
<Package className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<p className="text-gray-500 mb-2">아직 품목이 없습니다</p>
<p className="text-sm text-gray-400 mb-4">
품목을 추가하여 입찰 세부내역을 작성하세요
</p>
<Button
type="button"
variant="outline"
onClick={handleAddItem}
className="flex items-center gap-2 mx-auto"
>
<Plus className="h-4 w-4" />
첫 번째 품목 추가
</Button>
</div>
)}
</div>
</CardContent>
</Card>
{/* 액션 버튼 */}
{!readonly && (
<div className="flex justify-end gap-4">
<Button
onClick={handleSave}
disabled={isSubmitting}
className="min-w-[120px]"
>
{isSubmitting ? (
<>
<RefreshCw className="w-4 h-4 mr-2 animate-spin" />
저장 중...
</>
) : (
<>
<Save className="w-4 h-4 mr-2" />
저장
</>
)}
</Button>
</div>
)}
{/* 사전견적용 일반견적 생성 다이얼로그 */}
<CreatePreQuoteRfqDialog
open={preQuoteDialogOpen}
onOpenChange={setPreQuoteDialogOpen}
biddingId={biddingId}
biddingItems={items.map(item => ({
id: item.id,
materialGroupNumber: item.materialGroupNumber || undefined,
materialGroupInfo: item.materialGroupInfo || undefined,
materialNumber: item.materialNumber || undefined,
materialInfo: item.materialInfo || undefined,
quantity: item.quantity || undefined,
quantityUnit: item.quantityUnit || undefined,
totalWeight: item.totalWeight || undefined,
weightUnit: item.weightUnit || undefined,
}))}
picUserId={biddingPicUserId}
biddingConditions={biddingConditions}
onSuccess={() => {
toast.success('사전견적용 일반견적이 생성되었습니다')
}}
/>
{/* Excel 가져오기 다이얼로그 */}
<Dialog open={importDialogOpen} onOpenChange={setImportDialogOpen}>
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Excel 가져오기</DialogTitle>
<DialogDescription>
Excel 파일을 업로드하여 품목을 일괄 추가합니다.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="import-file">Excel 파일 선택</Label>
<Input
id="import-file"
type="file"
accept=".xlsx,.xls"
onChange={handleImportFileSelect}
className="mt-2"
disabled={isImporting}
/>
{importFile && (
<p className="text-sm text-muted-foreground mt-2">
선택된 파일: {importFile.name}
</p>
)}
</div>
{importErrors.length > 0 && (
<div className="space-y-2">
<Label className="text-destructive">오류 목록</Label>
<div className="max-h-60 overflow-y-auto border rounded-md p-3 bg-destructive/5">
<ul className="list-disc list-inside space-y-1">
{importErrors.map((error, index) => (
<li key={index} className="text-sm text-destructive">
{error}
</li>
))}
</ul>
</div>
</div>
)}
<div className="text-sm text-muted-foreground space-y-1">
<p className="font-semibold">필수 컬럼:</p>
<ul className="list-disc list-inside ml-2">
<li>자재그룹코드, 자재그룹명</li>
<li>수량 또는 중량 (둘 중 하나 필수)</li>
<li>수량단위 또는 중량단위</li>
<li>납품요청일 (YYYY-MM-DD 형식)</li>
<li>내정단가</li>
</ul>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => {
setImportDialogOpen(false)
setImportFile(null)
setImportErrors([])
}}
disabled={isImporting}
>
취소
</Button>
<Button
onClick={handleImport}
disabled={!importFile || isImporting}
>
{isImporting ? (
<>
<RefreshCw className="w-4 h-4 mr-2 animate-spin" />
가져오는 중...
</>
) : (
"가져오기"
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
|