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
|
'use server'
import db from '@/db/db'
import { biddings, prItemsForBidding, biddingDocuments, biddingCompanies, vendors, companyPrItemBids, companyConditionResponses, vendorSelectionResults, BiddingListItem, biddingConditions } from '@/db/schema'
import { eq, and, sql, desc, ne } from 'drizzle-orm'
import { revalidatePath } from 'next/cache'
// 데이터 조회 함수들
export interface BiddingDetailData {
bidding: Awaited<ReturnType<typeof getBiddingById>>
quotationDetails: QuotationDetails | null
quotationVendors: QuotationVendor[]
biddingCompanies: Awaited<ReturnType<typeof getBiddingCompaniesData>>
prItems: Awaited<ReturnType<typeof getPRItemsForBidding>>
}
// getBiddingById 함수 임포트 (기존 함수 재사용)
import { getBiddingById, getPRDetailsAction } from '@/lib/bidding/service'
// Promise.all을 사용하여 모든 데이터를 병렬로 조회
export async function getBiddingDetailData(biddingId: number): Promise<BiddingDetailData> {
const [
bidding,
quotationDetails,
quotationVendors,
biddingCompanies,
prItems
] = await Promise.all([
getBiddingById(biddingId),
getQuotationDetails(biddingId),
getQuotationVendors(biddingId),
getBiddingCompaniesData(biddingId),
getPRItemsForBidding(biddingId)
])
return {
bidding,
quotationDetails,
quotationVendors,
biddingCompanies,
prItems
}
}
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
contactPerson: string
contactEmail: string
contactPhone: string
quotationAmount: number // 견적금액
currency: string
submissionDate: string // 제출일
isWinner: boolean // 낙찰여부
awardRatio: number // 발주비율
status: 'pending' | 'submitted' | 'selected' | 'rejected'
// companyConditionResponses에서 가져온 입찰 조건들
paymentTermsResponse?: string // 지급조건 응답
taxConditionsResponse?: string // 세금조건 응답
incotermsResponse?: string // 운송조건 응답
proposedContractDeliveryDate?: string // 제안 계약납기일
proposedShippingPort?: string // 제안 선적지
proposedDestinationPort?: string // 제안 도착지
priceAdjustmentResponse?: boolean // 연동제 적용 응답
sparePartResponse?: string // 스페어파트 응답
additionalProposals?: string // 추가 제안사항
documents: Array<{
id: number
fileName: string
originalFileName: string
filePath: string
uploadedAt: string
}>
}
// 견적 시스템에서 내정가 및 관련 정보를 가져오는 함수
export async function getQuotationDetails(biddingId: number): Promise<QuotationDetails | null> {
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
}
}
// 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(eq(biddingCompanies.biddingId, biddingId))
.orderBy(desc(biddingCompanies.finalQuoteAmount))
return companies
} catch (error) {
console.error('Failed to get bidding companies data:', error)
return []
}
}
// prItemsForBidding 테이블에서 품목 정보 조회
export async function getPRItemsForBidding(biddingId: number) {
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 []
}
}
// 견적 시스템에서 협력업체 정보를 가져오는 함수
export async function getQuotationVendors(biddingId: number): Promise<QuotationVendor[]> {
try {
// bidding_companies 테이블을 메인으로 vendors, company_condition_responses를 조인하여 협력업체 정보 조회
const vendorsData = await db
.select({
id: biddingCompanies.id,
biddingId: biddingCompanies.biddingId,
vendorId: biddingCompanies.companyId,
vendorName: vendors.vendorName,
vendorCode: vendors.vendorCode,
contactPerson: biddingCompanies.contactPerson,
contactEmail: biddingCompanies.contactEmail,
contactPhone: biddingCompanies.contactPhone,
quotationAmount: biddingCompanies.finalQuoteAmount,
currency: sql<string>`'KRW'` as currency,
submissionDate: biddingCompanies.finalQuoteSubmittedAt,
isWinner: biddingCompanies.isWinner,
awardRatio: sql<number>`CASE WHEN ${biddingCompanies.isWinner} THEN 100 ELSE 0 END`,
status: sql<string>`CASE
WHEN ${biddingCompanies.isWinner} THEN 'selected'
WHEN ${biddingCompanies.finalQuoteSubmittedAt} IS NOT NULL THEN 'submitted'
WHEN ${biddingCompanies.respondedAt} IS NOT NULL THEN 'submitted'
ELSE 'pending'
END`,
// companyConditionResponses에서 입찰 조건들
paymentTermsResponse: companyConditionResponses.paymentTermsResponse,
taxConditionsResponse: companyConditionResponses.taxConditionsResponse,
incotermsResponse: companyConditionResponses.incotermsResponse,
proposedContractDeliveryDate: companyConditionResponses.proposedContractDeliveryDate,
proposedShippingPort: companyConditionResponses.proposedShippingPort,
proposedDestinationPort: companyConditionResponses.proposedDestinationPort,
priceAdjustmentResponse: companyConditionResponses.priceAdjustmentResponse,
sparePartResponse: companyConditionResponses.sparePartResponse,
additionalProposals: companyConditionResponses.additionalProposals,
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
.leftJoin(companyConditionResponses, eq(biddingCompanies.id, companyConditionResponses.biddingCompanyId))
.where(eq(biddingCompanies.biddingId, biddingId))
.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 || '',
contactPerson: vendor.contactPerson || '',
contactEmail: vendor.contactEmail || '',
contactPhone: vendor.contactPhone || '',
quotationAmount: Number(vendor.quotationAmount) || 0,
currency: vendor.currency,
submissionDate: vendor.submissionDate ? vendor.submissionDate.toISOString().split('T')[0] : '',
isWinner: vendor.isWinner || false,
awardRatio: vendor.awardRatio || 0,
status: vendor.status as 'pending' | 'submitted' | 'selected' | 'rejected',
// companyConditionResponses에서 입찰 조건들
paymentTermsResponse: vendor.paymentTermsResponse || '',
taxConditionsResponse: vendor.taxConditionsResponse || '',
incotermsResponse: vendor.incotermsResponse || '',
proposedContractDeliveryDate: vendor.proposedContractDeliveryDate ? (typeof vendor.proposedContractDeliveryDate === 'string' ? vendor.proposedContractDeliveryDate : vendor.proposedContractDeliveryDate.toISOString().split('T')[0]) : undefined,
proposedShippingPort: vendor.proposedShippingPort || '',
proposedDestinationPort: vendor.proposedDestinationPort || '',
priceAdjustmentResponse: vendor.priceAdjustmentResponse || false,
sparePartResponse: vendor.sparePartResponse || '',
additionalProposals: vendor.additionalProposals || '',
documents: [] // TODO: 문서 정보 조회 로직 추가
}))
} catch (error) {
console.error('Failed to get quotation vendors:', error)
return []
}
}
// 내정가 수동 업데이트 (실제 저장)
export async function updateTargetPrice(
biddingId: number,
targetPrice: number,
targetPriceCalculationCriteria: string,
userId: string
) {
try {
await db
.update(biddings)
.set({
targetPrice: targetPrice.toString(),
targetPriceCalculationCriteria: targetPriceCalculationCriteria,
updatedAt: new Date()
})
.where(eq(biddings.id, biddingId))
revalidatePath(`/evcp/bid/${biddingId}`)
return { success: true, message: '내정가가 성공적으로 업데이트되었습니다.' }
} catch (error) {
console.error('Failed to update target price:', error)
return { success: false, error: '내정가 업데이트에 실패했습니다.' }
}
}
// 협력업체 정보 저장 - biddingCompanies와 companyConditionResponses 테이블에 레코드 생성
export async function createQuotationVendor(input: any, userId: string) {
try {
const result = await db.transaction(async (tx) => {
// 1. biddingCompanies에 레코드 생성
const biddingCompanyResult = await tx.insert(biddingCompanies).values({
biddingId: input.biddingId,
companyId: input.vendorId,
quotationAmount: input.quotationAmount,
currency: input.currency,
status: input.status,
awardRatio: input.awardRatio,
isWinner: false,
contactPerson: input.contactPerson,
contactEmail: input.contactEmail,
contactPhone: input.contactPhone,
submissionDate: new Date(),
createdBy: userId,
updatedBy: userId,
}).returning({ id: biddingCompanies.id })
if (biddingCompanyResult.length === 0) {
throw new Error('협력업체 정보 저장에 실패했습니다.')
}
const biddingCompanyId = biddingCompanyResult[0].id
// 2. companyConditionResponses에 입찰 조건 생성
await tx.insert(companyConditionResponses).values({
biddingCompanyId: biddingCompanyId,
paymentTermsResponse: input.paymentTermsResponse || '',
taxConditionsResponse: input.taxConditionsResponse || '',
proposedContractDeliveryDate: input.proposedContractDeliveryDate ? new Date(input.proposedContractDeliveryDate) : null,
priceAdjustmentResponse: input.priceAdjustmentResponse || false,
incotermsResponse: input.incotermsResponse || '',
proposedShippingPort: input.proposedShippingPort || '',
proposedDestinationPort: input.proposedDestinationPort || '',
sparePartResponse: input.sparePartResponse || '',
additionalProposals: input.additionalProposals || '',
isPreQuote: false,
submittedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
})
return biddingCompanyId
})
revalidatePath(`/evcp/bid/[id]`)
return {
success: true,
message: '협력업체 정보가 성공적으로 저장되었습니다.',
data: { id: result }
}
} catch (error) {
console.error('Failed to create quotation vendor:', error)
return { success: false, error: '협력업체 정보 저장에 실패했습니다.' }
}
}
// 협력업체 정보 업데이트
export async function updateQuotationVendor(id: number, input: any, userId: string) {
try {
const result = await db.transaction(async (tx) => {
// 1. biddingCompanies 테이블 업데이트
const updateData: any = {}
if (input.quotationAmount !== undefined) updateData.finalQuoteAmount = input.quotationAmount
if (input.contactPerson !== undefined) updateData.contactPerson = input.contactPerson
if (input.contactEmail !== undefined) updateData.contactEmail = input.contactEmail
if (input.contactPhone !== undefined) updateData.contactPhone = input.contactPhone
if (input.awardRatio !== undefined) updateData.awardRatio = input.awardRatio
if (input.status !== undefined) updateData.status = input.status
updateData.updatedBy = userId
updateData.updatedAt = new Date()
if (Object.keys(updateData).length > 0) {
await tx.update(biddingCompanies)
.set(updateData)
.where(eq(biddingCompanies.id, id))
}
// 2. companyConditionResponses 테이블 업데이트 (입찰 조건들)
if (input.paymentTermsResponse !== undefined ||
input.taxConditionsResponse !== undefined ||
input.incotermsResponse !== undefined ||
input.proposedContractDeliveryDate !== undefined ||
input.proposedShippingPort !== undefined ||
input.proposedDestinationPort !== undefined ||
input.priceAdjustmentResponse !== undefined ||
input.sparePartResponse !== undefined ||
input.additionalProposals !== undefined) {
const conditionsUpdateData: any = {}
if (input.paymentTermsResponse !== undefined) conditionsUpdateData.paymentTermsResponse = input.paymentTermsResponse
if (input.taxConditionsResponse !== undefined) conditionsUpdateData.taxConditionsResponse = input.taxConditionsResponse
if (input.incotermsResponse !== undefined) conditionsUpdateData.incotermsResponse = input.incotermsResponse
if (input.proposedContractDeliveryDate !== undefined) conditionsUpdateData.proposedContractDeliveryDate = input.proposedContractDeliveryDate ? new Date(input.proposedContractDeliveryDate) : null
if (input.proposedShippingPort !== undefined) conditionsUpdateData.proposedShippingPort = input.proposedShippingPort
if (input.proposedDestinationPort !== undefined) conditionsUpdateData.proposedDestinationPort = input.proposedDestinationPort
if (input.priceAdjustmentResponse !== undefined) conditionsUpdateData.priceAdjustmentResponse = input.priceAdjustmentResponse
if (input.sparePartResponse !== undefined) conditionsUpdateData.sparePartResponse = input.sparePartResponse
if (input.additionalProposals !== undefined) conditionsUpdateData.additionalProposals = input.additionalProposals
conditionsUpdateData.updatedAt = new Date()
await tx.update(companyConditionResponses)
.set(conditionsUpdateData)
.where(eq(companyConditionResponses.biddingCompanyId, id))
}
return true
})
revalidatePath(`/evcp/bid/[id]`)
return {
success: true,
message: '협력업체 정보가 성공적으로 업데이트되었습니다.',
}
} catch (error) {
console.error('Failed to update quotation vendor:', error)
return { success: false, error: '협력업체 정보 업데이트에 실패했습니다.' }
}
}
// 협력업체 정보 삭제
export async function deleteQuotationVendor(id: number) {
try {
// TODO: 실제로는 견적 시스템의 테이블에서 삭제
console.log(`[TODO] 견적 시스템에서 협력업체 정보 ${id} 삭제 예정`)
// 임시로 성공 응답
return { success: true, message: '협력업체 정보가 성공적으로 삭제되었습니다.' }
} catch (error) {
console.error('Failed to delete quotation vendor:', error)
return { success: false, error: '협력업체 정보 삭제에 실패했습니다.' }
}
}
// 낙찰 처리
export async function selectWinner(biddingId: number, vendorId: number, awardRatio: number, userId: string) {
try {
// 트랜잭션으로 처리
await db.transaction(async (tx) => {
// 기존 낙찰자 초기화
await tx
.update(biddingCompanies)
.set({
isWinner: false,
updatedAt: new Date()
})
.where(eq(biddingCompanies.biddingId, biddingId))
// 새로운 낙찰자 설정
const biddingCompany = await tx
.select()
.from(biddingCompanies)
.where(and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.companyId, vendorId)
))
.limit(1)
if (biddingCompany.length > 0) {
await tx
.update(biddingCompanies)
.set({
isWinner: true,
updatedAt: new Date()
})
.where(eq(biddingCompanies.id, biddingCompany[0].id))
}
// biddings 테이블의 상태 업데이트
await tx
.update(biddings)
.set({
status: 'vendor_selected',
finalBidPrice: undefined, // TODO: 낙찰가 설정 로직 추가
updatedAt: new Date()
})
.where(eq(biddings.id, biddingId))
})
revalidatePath(`/evcp/bid/${biddingId}`)
return { success: true, message: '낙찰 처리가 완료되었습니다.' }
} catch (error) {
console.error('Failed to select winner:', error)
return { success: false, error: '낙찰 처리에 실패했습니다.' }
}
}
// 유찰 처리
export async function markAsDisposal(biddingId: number, userId: string) {
try {
await db
.update(biddings)
.set({
status: 'bidding_disposal',
updatedAt: new Date()
})
.where(eq(biddings.id, biddingId))
revalidatePath(`/evcp/bid/${biddingId}`)
return { success: true, message: '유찰 처리가 완료되었습니다.' }
} catch (error) {
console.error('Failed to mark as disposal:', error)
return { success: false, error: '유찰 처리에 실패했습니다.' }
}
}
// 입찰 등록 (상태 변경)
export async function registerBidding(biddingId: number, userId: string) {
try {
await db
.update(biddings)
.set({
status: 'bidding_opened',
updatedAt: new Date()
})
.where(eq(biddings.id, biddingId))
//todo 입찰 등록하면 bidding_companies invitationStatus를 sent로 변경!
await db
.update(biddingCompanies)
.set({
invitationStatus: 'sent',
updatedAt: new Date()
})
.where(eq(biddingCompanies.biddingId, biddingId))
revalidatePath(`/evcp/bid/${biddingId}`)
return { success: true, message: '입찰이 성공적으로 등록되었습니다.' }
} catch (error) {
console.error('Failed to register bidding:', error)
return { success: false, error: '입찰 등록에 실패했습니다.' }
}
}
// 재입찰 생성
export async function createRebidding(originalBiddingId: number, userId: string) {
try {
// 원본 입찰 정보 조회
const originalBidding = await db
.select()
.from(biddings)
.where(eq(biddings.id, originalBiddingId))
.limit(1)
if (originalBidding.length === 0) {
return { success: false, error: '원본 입찰을 찾을 수 없습니다.' }
}
const original = originalBidding[0]
// 재입찰용 데이터 준비
const rebiddingData = {
...original,
id: undefined,
biddingNumber: `${original.biddingNumber}-R${(original.revision || 0) + 1}`,
revision: (original.revision || 0) + 1,
status: 'bidding_generated' as const,
createdAt: new Date(),
updatedAt: new Date()
}
// 새로운 입찰 생성
const [newBidding] = await db
.insert(biddings)
.values(rebiddingData)
.returning({ id: biddings.id, biddingNumber: biddings.biddingNumber })
revalidatePath('/evcp/bid')
revalidatePath(`/evcp/bid/${newBidding.id}`)
return {
success: true,
message: '재입찰이 성공적으로 생성되었습니다.',
data: newBidding
}
} 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 {
// vendorSelectionResults 테이블에 삽입 또는 업데이트
await db
.insert(vendorSelectionResults)
.values({
biddingId,
selectedCompanyId,
selectionReason,
selectedBy: userId,
selectedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date()
})
.onConflictDoUpdate({
target: [vendorSelectionResults.biddingId],
set: {
selectedCompanyId,
selectionReason,
selectedBy: userId,
selectedAt: new Date(),
updatedAt: new Date()
}
})
revalidatePath(`/evcp/bid/${biddingId}`)
return { success: true, message: '업체 선정 사유가 성공적으로 업데이트되었습니다.' }
} catch (error) {
console.error('Failed to update vendor selection reason:', error)
return { success: false, error: '업체 선정 사유 업데이트에 실패했습니다.' }
}
}
// 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))
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 addVendorToBidding(biddingId: number, companyId: number, userId: string) {
try {
// 이미 추가된 업체인지 확인
const existing = await db
.select()
.from(biddingCompanies)
.where(and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.companyId, companyId)
))
.limit(1)
if (existing.length > 0) {
return { success: false, error: '이미 추가된 협력업체입니다.' }
}
// 새로운 협력업체 추가
await db
.insert(biddingCompanies)
.values({
biddingId,
companyId,
invitationStatus: 'pending',
invitedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date()
})
revalidatePath(`/evcp/bid/${biddingId}`)
return { success: true, message: '협력업체가 성공적으로 추가되었습니다.' }
} catch (error) {
console.error('Failed to add vendor to bidding:', error)
return { success: false, error: '협력업체 추가에 실패했습니다.' }
}
}
// =================================================
// 협력업체 페이지용 함수들 (Partners)
// =================================================
// 협력업체용 입찰 목록 조회 (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
notes: string | null
createdAt: Date
updatedAt: Date
// updatedBy: string | null
// biddings 정보
biddingId: number
biddingNumber: string
revision: number
projectName: string
itemName: string
title: string
contractType: string
biddingType: string
contractPeriod: string | null
submissionStartDate: Date | null
submissionEndDate: Date | null
status: string
managerName: string | null
managerEmail: string | null
managerPhone: string | null
currency: string
budget: number | null
// 계산된 필드
responseDeadline: Date | null // 참여회신 마감일 (submissionStartDate 전 3일)
submissionDate: Date | null // 입찰제출일 (submissionEndDate)
}
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,
notes: biddingCompanies.notes,
createdAt: biddingCompanies.createdAt,
updatedAt: biddingCompanies.updatedAt,
// updatedBy: biddingCompanies.updatedBy, // 이 필드가 존재하지 않음
// biddings 정보
biddingId: biddings.id,
biddingNumber: biddings.biddingNumber,
revision: biddings.revision,
projectName: biddings.projectName,
itemName: biddings.itemName,
title: biddings.title,
contractType: biddings.contractType,
biddingType: biddings.biddingType,
contractPeriod: biddings.contractPeriod,
submissionStartDate: biddings.submissionStartDate,
submissionEndDate: biddings.submissionEndDate,
status: biddings.status,
managerName: biddings.managerName,
managerEmail: biddings.managerEmail,
managerPhone: biddings.managerPhone,
currency: biddings.currency,
budget: biddings.budget,
})
.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.toISOString() : null,
finalQuoteAmount: item.finalQuoteAmount ? Number(item.finalQuoteAmount) : null, // string을 number로 변환
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,
biddingNumber: biddings.biddingNumber,
revision: biddings.revision,
projectName: biddings.projectName,
itemName: biddings.itemName,
title: biddings.title,
description: biddings.description,
content: biddings.content,
// 계약 정보
contractType: biddings.contractType,
biddingType: biddings.biddingType,
awardCount: biddings.awardCount,
contractPeriod: biddings.contractPeriod,
// 일정 정보
preQuoteDate: biddings.preQuoteDate,
biddingRegistrationDate: biddings.biddingRegistrationDate,
submissionStartDate: biddings.submissionStartDate,
submissionEndDate: biddings.submissionEndDate,
evaluationDate: biddings.evaluationDate,
// 가격 정보
currency: biddings.currency,
budget: biddings.budget,
targetPrice: biddings.targetPrice,
// 상태 및 담당자
status: biddings.status,
managerName: biddings.managerName,
managerEmail: biddings.managerEmail,
managerPhone: biddings.managerPhone,
// 협력업체 특정 정보
biddingCompanyId: biddingCompanies.id,
invitationStatus: biddingCompanies.invitationStatus,
finalQuoteAmount: biddingCompanies.finalQuoteAmount,
finalQuoteSubmittedAt: biddingCompanies.finalQuoteSubmittedAt,
isWinner: biddingCompanies.isWinner,
isAttendingMeeting: biddingCompanies.isAttendingMeeting,
// 응답한 조건들 (company_condition_responses) - 제시된 조건과 응답 모두 여기서 관리
paymentTermsResponse: companyConditionResponses.paymentTermsResponse,
taxConditionsResponse: companyConditionResponses.taxConditionsResponse,
incotermsResponse: companyConditionResponses.incotermsResponse,
proposedContractDeliveryDate: companyConditionResponses.proposedContractDeliveryDate,
proposedShippingPort: companyConditionResponses.proposedShippingPort,
proposedDestinationPort: companyConditionResponses.proposedDestinationPort,
priceAdjustmentResponse: companyConditionResponses.priceAdjustmentResponse,
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
sparePartResponse?: string
additionalProposals?: string
finalQuoteAmount?: number
},
userId: string
) {
try {
const result = await db.transaction(async (tx) => {
// 1. company_condition_responses 테이블에 응답 저장/업데이트
const responseData = {
paymentTermsResponse: response.paymentTermsResponse,
taxConditionsResponse: response.taxConditionsResponse,
incotermsResponse: response.incotermsResponse,
proposedContractDeliveryDate: response.proposedContractDeliveryDate ? response.proposedContractDeliveryDate : null, // Date 대신 string 사용
proposedShippingPort: response.proposedShippingPort,
proposedDestinationPort: response.proposedDestinationPort,
priceAdjustmentResponse: response.priceAdjustmentResponse,
sparePartResponse: response.sparePartResponse,
additionalProposals: response.additionalProposals,
submittedAt: new Date(),
updatedAt: new Date(),
}
// 기존 응답이 있는지 확인
const existingResponse = await tx
.select()
.from(companyConditionResponses)
.where(eq(companyConditionResponses.biddingCompanyId, biddingCompanyId))
.limit(1)
if (existingResponse.length > 0) {
// 업데이트
await tx
.update(companyConditionResponses)
.set(responseData)
.where(eq(companyConditionResponses.biddingCompanyId, biddingCompanyId))
} else {
// 새로 생성
await tx
.insert(companyConditionResponses)
.values({
biddingCompanyId,
...responseData,
})
}
// 2. biddingCompanies 테이블에 견적 금액과 상태 업데이트
const companyUpdateData: any = {
respondedAt: new Date(),
updatedAt: new Date(),
// updatedBy: userId, // 이 필드가 존재하지 않음
}
if (response.finalQuoteAmount !== undefined) {
companyUpdateData.finalQuoteAmount = response.finalQuoteAmount
companyUpdateData.finalQuoteSubmittedAt = new Date()
companyUpdateData.invitationStatus = 'submitted'
}
await tx
.update(biddingCompanies)
.set(companyUpdateData)
.where(eq(biddingCompanies.id, biddingCompanyId))
return true
})
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 {
// 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')
))
// biddings 테이블에서 사양설명회 기본 정보 조회
const bidding = await db
.select({
id: biddings.id,
title: biddings.title,
biddingNumber: biddings.biddingNumber,
preQuoteDate: biddings.preQuoteDate,
biddingRegistrationDate: biddings.biddingRegistrationDate,
managerName: biddings.managerName,
managerEmail: biddings.managerEmail,
managerPhone: biddings.managerPhone,
})
.from(biddings)
.where(eq(biddings.id, biddingId))
.limit(1)
if (bidding.length === 0) {
return { success: false, error: '입찰 정보를 찾을 수 없습니다.' }
}
return {
success: true,
data: {
...bidding[0],
documents,
meetingDate: bidding[0].preQuoteDate ? bidding[0].preQuoteDate.toISOString().split('T')[0] : null,
contactPerson: bidding[0].managerName,
contactEmail: bidding[0].managerEmail,
contactPhone: bidding[0].managerPhone,
}
}
} 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
},
userId: 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))
// 참석하는 경우, 사양설명회 담당자에게 이메일 발송을 위한 정보 반환
if (attendanceData.isAttending) {
const biddingInfo = await tx
.select({
biddingId: biddingCompanies.biddingId,
companyId: biddingCompanies.companyId,
managerEmail: biddings.managerEmail,
managerName: biddings.managerName,
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 : '알 수 없음'
// 메일 발송 (템플릿 사용)
try {
const { sendEmail } = await import('@/lib/mail/sendEmail')
await sendEmail({
to: biddingInfo[0].managerEmail,
template: 'specification-meeting-attendance',
context: {
biddingNumber: biddingInfo[0].biddingNumber,
title: biddingInfo[0].title,
companyName: companyName,
attendeeCount: attendanceData.attendeeCount,
representativeName: attendanceData.representativeName,
representativePhone: attendanceData.representativePhone,
managerName: biddingInfo[0].managerName,
managerEmail: biddingInfo[0].managerEmail,
currentYear: new Date().getFullYear(),
language: 'ko'
}
})
console.log(`사양설명회 참석 알림 메일 발송 완료: ${biddingInfo[0].managerEmail}`)
} catch (emailError) {
console.error('메일 발송 실패:', emailError)
// 메일 발송 실패해도 참석 여부 업데이트는 성공으로 처리
}
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: '참석 여부 업데이트에 실패했습니다.' }
}
}
|