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
|
'use server'
import db from '@/db/db'
import { biddingCompanies, companyConditionResponses, biddings, prItemsForBidding, biddingDocuments, companyPrItemBids, priceAdjustmentForms } from '@/db/schema/bidding'
import { vendors } from '@/db/schema/vendors'
import { users } from '@/db/schema'
import { sendEmail } from '@/lib/mail/sendEmail'
import { eq, inArray, and } from 'drizzle-orm'
import { saveFile } from '@/lib/file-stroage'
import { downloadFile } from '@/lib/file-download'
import { revalidateTag, revalidatePath } from 'next/cache'
// 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를 그대로 반환
}
}
interface CreateBiddingCompanyInput {
biddingId: number
companyId: number
contactPerson?: string
contactEmail?: string
contactPhone?: string
notes?: string
}
interface UpdateBiddingCompanyInput {
contactPerson?: string
contactEmail?: string
contactPhone?: string
preQuoteAmount?: number
notes?: string
invitationStatus?: 'pending' | 'accepted' | 'declined'
isPreQuoteSelected?: boolean
isAttendingMeeting?: boolean
}
interface PrItemQuotation {
prItemId: number
bidUnitPrice: number
bidAmount: number
proposedDeliveryDate?: string
technicalSpecification?: string
}
interface PreQuoteDocumentUpload {
fileName: string
originalFileName: string
fileSize: number
mimeType: string
filePath: string
}
// 사전견적용 업체 추가 - biddingCompanies와 company_condition_responses 레코드 생성
export async function createBiddingCompany(input: CreateBiddingCompanyInput) {
try {
const result = await db.transaction(async (tx) => {
// 1. biddingCompanies 레코드 생성
const biddingCompanyResult = await tx.insert(biddingCompanies).values({
biddingId: input.biddingId,
companyId: input.companyId,
invitationStatus: 'pending', // 초기 상태: 입찰생성
invitedAt: new Date(),
contactPerson: input.contactPerson,
contactEmail: input.contactEmail,
contactPhone: input.contactPhone,
notes: input.notes,
}).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,
// 나머지 필드들은 null로 시작 (벤더가 나중에 응답)
})
return biddingCompanyId
})
return {
success: true,
message: '업체가 성공적으로 추가되었습니다.',
data: { id: result }
}
} catch (error) {
console.error('Failed to create bidding company:', error)
return {
success: false,
error: error instanceof Error ? error.message : '업체 추가에 실패했습니다.'
}
}
}
// 사전견적용 업체 정보 업데이트
export async function updateBiddingCompany(id: number, input: UpdateBiddingCompanyInput) {
try {
const updateData: any = {
updatedAt: new Date()
}
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.preQuoteAmount !== undefined) updateData.preQuoteAmount = input.preQuoteAmount
if (input.notes !== undefined) updateData.notes = input.notes
if (input.invitationStatus !== undefined) {
updateData.invitationStatus = input.invitationStatus
if (input.invitationStatus !== 'pending') {
updateData.respondedAt = new Date()
}
}
if (input.isPreQuoteSelected !== undefined) updateData.isPreQuoteSelected = input.isPreQuoteSelected
if (input.isAttendingMeeting !== undefined) updateData.isAttendingMeeting = input.isAttendingMeeting
await db.update(biddingCompanies)
.set(updateData)
.where(eq(biddingCompanies.id, id))
return {
success: true,
message: '업체 정보가 성공적으로 업데이트되었습니다.',
}
} catch (error) {
console.error('Failed to update bidding company:', error)
return {
success: false,
error: error instanceof Error ? error.message : '업체 정보 업데이트에 실패했습니다.'
}
}
}
// 본입찰 등록 상태 업데이트 (복수 업체 선택 가능)
export async function updatePreQuoteSelection(companyIds: number[], isSelected: boolean) {
try {
// 업체들의 입찰 ID 조회 (캐시 무효화를 위해)
const companies = await db
.select({ biddingId: biddingCompanies.biddingId })
.from(biddingCompanies)
.where(inArray(biddingCompanies.id, companyIds))
.limit(1)
await db.update(biddingCompanies)
.set({
isPreQuoteSelected: isSelected,
invitationStatus: 'pending', // 초기 상태: 입찰생성
updatedAt: new Date()
})
.where(inArray(biddingCompanies.id, companyIds))
// 캐시 무효화
if (companies.length > 0) {
const biddingId = companies[0].biddingId
revalidateTag(`bidding-${biddingId}`)
revalidateTag('bidding-detail')
revalidateTag('quotation-vendors')
revalidateTag('quotation-details')
revalidatePath(`/evcp/bid/${biddingId}`)
}
const message = isSelected
? `${companyIds.length}개 업체가 본입찰 대상으로 선정되었습니다.`
: `${companyIds.length}개 업체의 본입찰 선정이 취소되었습니다.`
return {
success: true,
message
}
} catch (error) {
console.error('Failed to update pre-quote selection:', error)
return {
success: false,
error: error instanceof Error ? error.message : '본입찰 선정 상태 업데이트에 실패했습니다.'
}
}
}
// 사전견적용 업체 삭제
export async function deleteBiddingCompany(id: number) {
try {
await db.transaction(async (tx) => {
// 1. 먼저 관련된 조건 응답들 삭제
await tx.delete(companyConditionResponses)
.where(eq(companyConditionResponses.biddingCompanyId, id))
// 2. biddingCompanies 레코드 삭제
await tx.delete(biddingCompanies)
.where(eq(biddingCompanies.id, id))
})
return {
success: true,
message: '업체가 성공적으로 삭제되었습니다.'
}
} catch (error) {
console.error('Failed to delete bidding company:', error)
return {
success: false,
error: error instanceof Error ? error.message : '업체 삭제에 실패했습니다.'
}
}
}
// 특정 입찰의 참여 업체 목록 조회 (company_condition_responses와 vendors 조인)
export async function getBiddingCompanies(biddingId: number) {
try {
const companies = await db
.select({
// bidding_companies 필드들
id: biddingCompanies.id,
biddingId: biddingCompanies.biddingId,
companyId: biddingCompanies.companyId,
invitationStatus: biddingCompanies.invitationStatus,
invitedAt: biddingCompanies.invitedAt,
respondedAt: biddingCompanies.respondedAt,
preQuoteAmount: biddingCompanies.preQuoteAmount,
preQuoteSubmittedAt: biddingCompanies.preQuoteSubmittedAt,
preQuoteDeadline: biddingCompanies.preQuoteDeadline,
isPreQuoteSelected: biddingCompanies.isPreQuoteSelected,
isPreQuoteParticipated: biddingCompanies.isPreQuoteParticipated,
isAttendingMeeting: biddingCompanies.isAttendingMeeting,
notes: biddingCompanies.notes,
contactPerson: biddingCompanies.contactPerson,
contactEmail: biddingCompanies.contactEmail,
contactPhone: biddingCompanies.contactPhone,
createdAt: biddingCompanies.createdAt,
updatedAt: biddingCompanies.updatedAt,
// vendors 테이블에서 업체 정보
companyName: vendors.vendorName,
companyCode: vendors.vendorCode,
// company_condition_responses 필드들
paymentTermsResponse: companyConditionResponses.paymentTermsResponse,
taxConditionsResponse: companyConditionResponses.taxConditionsResponse,
proposedContractDeliveryDate: companyConditionResponses.proposedContractDeliveryDate,
priceAdjustmentResponse: companyConditionResponses.priceAdjustmentResponse,
isInitialResponse: companyConditionResponses.isInitialResponse,
incotermsResponse: companyConditionResponses.incotermsResponse,
proposedShippingPort: companyConditionResponses.proposedShippingPort,
proposedDestinationPort: companyConditionResponses.proposedDestinationPort,
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))
return {
success: true,
data: companies
}
} catch (error) {
console.error('Failed to get bidding companies:', error)
return {
success: false,
error: error instanceof Error ? error.message : '업체 목록 조회에 실패했습니다.'
}
}
}
// 선택된 업체들에게 사전견적 초대 발송
export async function sendPreQuoteInvitations(companyIds: number[], preQuoteDeadline?: Date | string) {
try {
if (companyIds.length === 0) {
return {
success: false,
error: '선택된 업체가 없습니다.'
}
}
// 선택된 업체들의 정보와 입찰 정보 조회
const companiesInfo = await db
.select({
biddingCompanyId: biddingCompanies.id,
companyId: biddingCompanies.companyId,
biddingId: biddingCompanies.biddingId,
companyName: vendors.vendorName,
companyEmail: vendors.email,
// 입찰 정보
biddingNumber: biddings.biddingNumber,
revision: biddings.revision,
projectName: biddings.projectName,
biddingTitle: biddings.title,
itemName: biddings.itemName,
preQuoteDate: biddings.preQuoteDate,
budget: biddings.budget,
currency: biddings.currency,
managerName: biddings.managerName,
managerEmail: biddings.managerEmail,
managerPhone: biddings.managerPhone,
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
.leftJoin(biddings, eq(biddingCompanies.biddingId, biddings.id))
.where(inArray(biddingCompanies.id, companyIds))
if (companiesInfo.length === 0) {
return {
success: false,
error: '업체 정보를 찾을 수 없습니다.'
}
}
await db.transaction(async (tx) => {
// 선택된 업체들의 상태를 '사전견적요청(초대발송)'으로 변경
for (const id of companyIds) {
await tx.update(biddingCompanies)
.set({
invitationStatus: 'sent', // 사전견적 초대 발송 상태
invitedAt: new Date(),
preQuoteDeadline: preQuoteDeadline ? new Date(preQuoteDeadline) : null,
updatedAt: new Date()
})
.where(eq(biddingCompanies.id, id))
}
})
// 각 업체별로 이메일 발송
for (const company of companiesInfo) {
if (company.companyEmail) {
try {
await sendEmail({
to: company.companyEmail,
template: 'pre-quote-invitation',
context: {
companyName: company.companyName,
biddingNumber: company.biddingNumber,
revision: company.revision,
projectName: company.projectName,
biddingTitle: company.biddingTitle,
itemName: company.itemName,
preQuoteDate: company.preQuoteDate ? new Date(company.preQuoteDate).toLocaleDateString() : null,
budget: company.budget ? company.budget.toLocaleString() : null,
currency: company.currency,
managerName: company.managerName,
managerEmail: company.managerEmail,
managerPhone: company.managerPhone,
loginUrl: `${process.env.NEXT_PUBLIC_APP_URL}/partners/bid/${company.biddingId}/pre-quote`,
currentYear: new Date().getFullYear(),
language: 'ko'
}
})
} catch (emailError) {
console.error(`Failed to send email to ${company.companyEmail}:`, emailError)
// 이메일 발송 실패해도 전체 프로세스는 계속 진행
}
}
}
// 3. 입찰 상태를 사전견적 요청으로 변경 (bidding_generated 상태에서만)
for (const company of companiesInfo) {
await db.transaction(async (tx) => {
await tx
.update(biddings)
.set({
status: 'request_for_quotation',
updatedAt: new Date()
})
.where(and(
eq(biddings.id, company.biddingId),
eq(biddings.status, 'bidding_generated')
))
})
}
return {
success: true,
message: `${companyIds.length}개 업체에 사전견적 초대를 발송했습니다.`
}
} catch (error) {
console.error('Failed to send pre-quote invitations:', error)
return {
success: false,
error: error instanceof Error ? error.message : '초대 발송에 실패했습니다.'
}
}
}
// Partners에서 특정 업체의 입찰 정보 조회 (사전견적 단계)
export async function getBiddingCompaniesForPartners(biddingId: number, companyId: number) {
try {
// 1. 먼저 입찰 기본 정보를 가져옴
const biddingResult = 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,
})
.from(biddings)
.where(eq(biddings.id, biddingId))
.limit(1)
if (biddingResult.length === 0) {
return null
}
const biddingData = biddingResult[0]
// 2. 해당 업체의 biddingCompanies 정보 조회
const companyResult = await db
.select({
biddingCompanyId: biddingCompanies.id,
biddingId: biddingCompanies.biddingId,
invitationStatus: biddingCompanies.invitationStatus,
preQuoteAmount: biddingCompanies.preQuoteAmount,
preQuoteSubmittedAt: biddingCompanies.preQuoteSubmittedAt,
preQuoteDeadline: biddingCompanies.preQuoteDeadline,
isPreQuoteSelected: biddingCompanies.isPreQuoteSelected,
isPreQuoteParticipated: biddingCompanies.isPreQuoteParticipated,
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,
isInitialResponse: companyConditionResponses.isInitialResponse,
additionalProposals: companyConditionResponses.additionalProposals,
})
.from(biddingCompanies)
.leftJoin(
companyConditionResponses,
eq(biddingCompanies.id, companyConditionResponses.biddingCompanyId)
)
.where(
and(
eq(biddingCompanies.biddingId, biddingId),
eq(biddingCompanies.companyId, companyId)
)
)
.limit(1)
// 3. 결과 조합
if (companyResult.length === 0) {
// 아직 초대되지 않은 상태
return {
...biddingData,
biddingCompanyId: null,
biddingId: biddingData.id,
invitationStatus: null,
preQuoteAmount: null,
preQuoteSubmittedAt: null,
preQuoteDeadline: null,
isPreQuoteSelected: false,
isPreQuoteParticipated: null,
isAttendingMeeting: null,
paymentTermsResponse: null,
taxConditionsResponse: null,
incotermsResponse: null,
proposedContractDeliveryDate: null,
proposedShippingPort: null,
proposedDestinationPort: null,
priceAdjustmentResponse: null,
sparePartResponse: null,
isInitialResponse: null,
additionalProposals: null,
}
}
const companyData = companyResult[0]
return {
...biddingData,
...companyData,
biddingId: biddingData.id, // bidding ID 보장
}
} catch (error) {
console.error('Failed to get bidding companies for partners:', error)
throw error
}
}
// Partners에서 사전견적 응답 제출
export async function submitPreQuoteResponse(
biddingCompanyId: number,
responseData: {
preQuoteAmount?: number // 품목별 계산에서 자동으로 계산되므로 optional
prItemQuotations?: PrItemQuotation[] // 품목별 견적 정보 추가
paymentTermsResponse?: string
taxConditionsResponse?: string
incotermsResponse?: string
proposedContractDeliveryDate?: string
proposedShippingPort?: string
proposedDestinationPort?: string
priceAdjustmentResponse?: boolean
isInitialResponse?: boolean
sparePartResponse?: string
additionalProposals?: string
priceAdjustmentForm?: any
},
userId: string
) {
try {
let finalAmount = responseData.preQuoteAmount || 0
await db.transaction(async (tx) => {
// 1. 품목별 견적 정보 최종 저장 (사전견적 제출)
if (responseData.prItemQuotations && responseData.prItemQuotations.length > 0) {
// 기존 사전견적 품목 삭제 후 새로 생성
await tx.delete(companyPrItemBids)
.where(
and(
eq(companyPrItemBids.biddingCompanyId, biddingCompanyId),
eq(companyPrItemBids.isPreQuote, true)
)
)
// 품목별 견적 최종 저장
for (const item of responseData.prItemQuotations) {
await tx.insert(companyPrItemBids)
.values({
biddingCompanyId,
prItemId: item.prItemId,
bidUnitPrice: item.bidUnitPrice.toString(),
bidAmount: item.bidAmount.toString(),
proposedDeliveryDate: item.proposedDeliveryDate || null,
technicalSpecification: item.technicalSpecification || null,
currency: 'KRW',
isPreQuote: true,
submittedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date()
})
}
// 총 금액 다시 계산
finalAmount = responseData.prItemQuotations.reduce((sum, item) => sum + item.bidAmount, 0)
}
// 2. biddingCompanies 업데이트 (사전견적 금액, 제출 시간, 상태 변경)
await tx.update(biddingCompanies)
.set({
preQuoteAmount: finalAmount.toString(),
preQuoteSubmittedAt: new Date(),
invitationStatus: 'submitted', // 사전견적 제출 완료 상태로 변경
updatedAt: new Date()
})
.where(eq(biddingCompanies.id, biddingCompanyId))
// 3. company_condition_responses 업데이트
const finalConditionResult = await tx.update(companyConditionResponses)
.set({
paymentTermsResponse: responseData.paymentTermsResponse,
taxConditionsResponse: responseData.taxConditionsResponse,
incotermsResponse: responseData.incotermsResponse,
proposedContractDeliveryDate: responseData.proposedContractDeliveryDate,
proposedShippingPort: responseData.proposedShippingPort,
proposedDestinationPort: responseData.proposedDestinationPort,
priceAdjustmentResponse: responseData.priceAdjustmentResponse,
isInitialResponse: responseData.isInitialResponse,
sparePartResponse: responseData.sparePartResponse,
additionalProposals: responseData.additionalProposals,
updatedAt: new Date()
})
.where(eq(companyConditionResponses.biddingCompanyId, biddingCompanyId))
.returning()
// 4. 연동제 정보 저장 (연동제 적용이 true이고 연동제 정보가 있는 경우)
if (responseData.priceAdjustmentResponse && responseData.priceAdjustmentForm && finalConditionResult.length > 0) {
const companyConditionResponseId = finalConditionResult[0].id
const priceAdjustmentData = {
companyConditionResponsesId: companyConditionResponseId,
itemName: responseData.priceAdjustmentForm.itemName,
adjustmentReflectionPoint: responseData.priceAdjustmentForm.adjustmentReflectionPoint,
majorApplicableRawMaterial: responseData.priceAdjustmentForm.majorApplicableRawMaterial,
adjustmentFormula: responseData.priceAdjustmentForm.adjustmentFormula,
rawMaterialPriceIndex: responseData.priceAdjustmentForm.rawMaterialPriceIndex,
referenceDate: responseData.priceAdjustmentForm.referenceDate as string || null,
comparisonDate: responseData.priceAdjustmentForm.comparisonDate as string || null,
adjustmentRatio: responseData.priceAdjustmentForm.adjustmentRatio || null,
notes: responseData.priceAdjustmentForm.notes,
adjustmentConditions: responseData.priceAdjustmentForm.adjustmentConditions,
majorNonApplicableRawMaterial: responseData.priceAdjustmentForm.majorNonApplicableRawMaterial,
adjustmentPeriod: responseData.priceAdjustmentForm.adjustmentPeriod,
contractorWriter: responseData.priceAdjustmentForm.contractorWriter,
adjustmentDate: responseData.priceAdjustmentForm.adjustmentDate as string || null,
nonApplicableReason: responseData.priceAdjustmentForm.nonApplicableReason,
} as any
// 기존 연동제 정보가 있는지 확인
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)
}
}
// 5. 입찰 상태를 사전견적 접수로 변경 (request_for_quotation 상태에서만)
// 또한 사전견적 접수일 업데이트
const biddingCompany = await tx
.select({ biddingId: biddingCompanies.biddingId })
.from(biddingCompanies)
.where(eq(biddingCompanies.id, biddingCompanyId))
.limit(1)
if (biddingCompany.length > 0) {
await tx
.update(biddings)
.set({
status: 'received_quotation',
preQuoteDate: new Date().toISOString().split('T')[0], // 사전견적 접수일 업데이트
updatedAt: new Date()
})
.where(and(
eq(biddings.id, biddingCompany[0].biddingId),
eq(biddings.status, 'request_for_quotation')
))
}
})
return {
success: true,
message: '사전견적이 성공적으로 제출되었습니다.'
}
} catch (error) {
console.error('Failed to submit pre-quote response:', error)
return {
success: false,
error: error instanceof Error ? error.message : '사전견적 제출에 실패했습니다.'
}
}
}
// Partners에서 사전견적 참여 의사 결정 (수락/거절)
export async function respondToPreQuoteInvitation(
biddingCompanyId: number,
response: 'accepted' | 'declined'
) {
try {
await db.update(biddingCompanies)
.set({
invitationStatus: response, // accepted 또는 declined
respondedAt: new Date(),
updatedAt: new Date()
})
.where(eq(biddingCompanies.id, biddingCompanyId))
const message = response === 'accepted' ?
'사전견적 참여를 수락했습니다.' :
'사전견적 참여를 거절했습니다.'
return {
success: true,
message
}
} catch (error) {
console.error('Failed to respond to pre-quote invitation:', error)
return {
success: false,
error: error instanceof Error ? error.message : '응답 처리에 실패했습니다.'
}
}
}
// 벤더에서 사전견적 참여 여부 결정 (isPreQuoteSelected, isPreQuoteParticipated 사용)
export async function setPreQuoteParticipation(
biddingCompanyId: number,
isParticipating: boolean
) {
try {
await db.update(biddingCompanies)
.set({
isPreQuoteParticipated: isParticipating,
isPreQuoteSelected: isParticipating,
respondedAt: new Date(),
updatedAt: new Date()
})
.where(eq(biddingCompanies.id, biddingCompanyId))
const message = isParticipating ?
'사전견적 참여를 확정했습니다. 이제 견적서를 작성하실 수 있습니다.' :
'사전견적 참여를 거절했습니다.'
return {
success: true,
message
}
} catch (error) {
console.error('Failed to set pre-quote participation:', error)
return {
success: false,
error: error instanceof Error ? error.message : '참여 의사 처리에 실패했습니다.'
}
}
}
// PR 아이템 조회 (입찰에 포함된 품목들)
export async function getPrItemsForBidding(biddingId: number) {
try {
const prItems = await db
.select({
id: prItemsForBidding.id,
itemNumber: prItemsForBidding.itemNumber,
prNumber: prItemsForBidding.prNumber,
itemInfo: prItemsForBidding.itemInfo,
materialDescription: prItemsForBidding.materialDescription,
quantity: prItemsForBidding.quantity,
quantityUnit: prItemsForBidding.quantityUnit,
totalWeight: prItemsForBidding.totalWeight,
weightUnit: prItemsForBidding.weightUnit,
currency: prItemsForBidding.currency,
requestedDeliveryDate: prItemsForBidding.requestedDeliveryDate,
hasSpecDocument: prItemsForBidding.hasSpecDocument
})
.from(prItemsForBidding)
.where(eq(prItemsForBidding.biddingId, biddingId))
return prItems
} catch (error) {
console.error('Failed to get PR items for bidding:', error)
return []
}
}
// SPEC 문서 조회 (PR 아이템에 연결된 문서들)
export async function getSpecDocumentsForPrItem(prItemId: number) {
try {
const specDocs = await db
.select({
id: biddingDocuments.id,
fileName: biddingDocuments.fileName,
originalFileName: biddingDocuments.originalFileName,
fileSize: biddingDocuments.fileSize,
filePath: biddingDocuments.filePath,
title: biddingDocuments.title,
description: biddingDocuments.description,
uploadedAt: biddingDocuments.uploadedAt
})
.from(biddingDocuments)
.where(
and(
eq(biddingDocuments.prItemId, prItemId),
eq(biddingDocuments.documentType, 'spec_document')
)
)
return specDocs
} catch (error) {
console.error('Failed to get spec documents for PR item:', error)
return []
}
}
// 사전견적 임시저장
export async function savePreQuoteDraft(
biddingCompanyId: number,
responseData: {
prItemQuotations?: PrItemQuotation[]
paymentTermsResponse?: string
taxConditionsResponse?: string
incotermsResponse?: string
proposedContractDeliveryDate?: string
proposedShippingPort?: string
proposedDestinationPort?: string
priceAdjustmentResponse?: boolean
isInitialResponse?: boolean
sparePartResponse?: string
additionalProposals?: string
priceAdjustmentForm?: any
},
userId: string
) {
try {
let totalAmount = 0
await db.transaction(async (tx) => {
// 품목별 견적 정보 저장
if (responseData.prItemQuotations && responseData.prItemQuotations.length > 0) {
// 기존 사전견적 품목 삭제 (임시저장 시 덮어쓰기)
await tx.delete(companyPrItemBids)
.where(
and(
eq(companyPrItemBids.biddingCompanyId, biddingCompanyId),
eq(companyPrItemBids.isPreQuote, true)
)
)
// 새로운 품목별 견적 저장
for (const item of responseData.prItemQuotations) {
await tx.insert(companyPrItemBids)
.values({
biddingCompanyId,
prItemId: item.prItemId,
bidUnitPrice: item.bidUnitPrice.toString(),
bidAmount: item.bidAmount.toString(),
proposedDeliveryDate: item.proposedDeliveryDate || null,
technicalSpecification: item.technicalSpecification || null,
currency: 'KRW',
isPreQuote: true, // 사전견적 표시
submittedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date()
})
}
// 총 금액 계산
totalAmount = responseData.prItemQuotations.reduce((sum, item) => sum + item.bidAmount, 0)
// biddingCompanies에 총 금액 임시 저장 (status는 변경하지 않음)
await tx.update(biddingCompanies)
.set({
preQuoteAmount: totalAmount.toString(),
updatedAt: new Date()
})
.where(eq(biddingCompanies.id, biddingCompanyId))
}
// company_condition_responses 업데이트 (임시저장)
const conditionResult = await tx.update(companyConditionResponses)
.set({
paymentTermsResponse: responseData.paymentTermsResponse || null,
taxConditionsResponse: responseData.taxConditionsResponse || null,
incotermsResponse: responseData.incotermsResponse || null,
proposedContractDeliveryDate: responseData.proposedContractDeliveryDate || null,
proposedShippingPort: responseData.proposedShippingPort || null,
proposedDestinationPort: responseData.proposedDestinationPort || null,
priceAdjustmentResponse: responseData.priceAdjustmentResponse || null,
isInitialResponse: responseData.isInitialResponse || null,
sparePartResponse: responseData.sparePartResponse || null,
additionalProposals: responseData.additionalProposals || null,
updatedAt: new Date()
})
.where(eq(companyConditionResponses.biddingCompanyId, biddingCompanyId))
.returning()
// 연동제 정보 저장 (연동제 적용이 true이고 연동제 정보가 있는 경우)
if (responseData.priceAdjustmentResponse && responseData.priceAdjustmentForm && conditionResult.length > 0) {
const companyConditionResponseId = conditionResult[0].id
const priceAdjustmentData = {
companyConditionResponsesId: companyConditionResponseId,
itemName: responseData.priceAdjustmentForm.itemName,
adjustmentReflectionPoint: responseData.priceAdjustmentForm.adjustmentReflectionPoint,
majorApplicableRawMaterial: responseData.priceAdjustmentForm.majorApplicableRawMaterial,
adjustmentFormula: responseData.priceAdjustmentForm.adjustmentFormula,
rawMaterialPriceIndex: responseData.priceAdjustmentForm.rawMaterialPriceIndex,
referenceDate: responseData.priceAdjustmentForm.referenceDate as string || null,
comparisonDate: responseData.priceAdjustmentForm.comparisonDate as string || null,
adjustmentRatio: responseData.priceAdjustmentForm.adjustmentRatio || null,
notes: responseData.priceAdjustmentForm.notes,
adjustmentConditions: responseData.priceAdjustmentForm.adjustmentConditions,
majorNonApplicableRawMaterial: responseData.priceAdjustmentForm.majorNonApplicableRawMaterial,
adjustmentPeriod: responseData.priceAdjustmentForm.adjustmentPeriod,
contractorWriter: responseData.priceAdjustmentForm.contractorWriter,
adjustmentDate: responseData.priceAdjustmentForm.adjustmentDate as string || null,
nonApplicableReason: responseData.priceAdjustmentForm.nonApplicableReason,
} as any
// 기존 연동제 정보가 있는지 확인
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)
}
}
})
return {
success: true,
message: '임시저장이 완료되었습니다.',
totalAmount
}
} catch (error) {
console.error('Failed to save pre-quote draft:', error)
return {
success: false,
error: error instanceof Error ? error.message : '임시저장에 실패했습니다.'
}
}
}
// 견적 문서 업로드
export async function uploadPreQuoteDocument(
biddingId: number,
companyId: number,
file: File,
userId: string
) {
try {
const userName = await getUserNameById(userId)
// 파일 저장
const saveResult = await saveFile({
file,
directory: `bidding/${biddingId}/quotations`,
originalName: file.name,
userId
})
if (!saveResult.success) {
return {
success: false,
error: saveResult.error || '파일 저장에 실패했습니다.'
}
}
// 데이터베이스에 문서 정보 저장
const result = await db.insert(biddingDocuments)
.values({
biddingId,
companyId,
documentType: 'other', // 견적서 타입
fileName: saveResult.fileName!,
originalFileName: file.name,
fileSize: file.size,
mimeType: file.type,
filePath: saveResult.publicPath!, // publicPath 사용 (웹 접근 가능한 경로)
title: `견적서 - ${file.name}`,
description: '협력업체 제출 견적서',
isPublic: false,
isRequired: false,
uploadedBy: userName,
uploadedAt: new Date()
})
.returning()
return {
success: true,
message: '견적서가 성공적으로 업로드되었습니다.',
documentId: result[0].id
}
} catch (error) {
console.error('Failed to upload pre-quote document:', error)
return {
success: false,
error: error instanceof Error ? error.message : '견적서 업로드에 실패했습니다.'
}
}
}
// 업로드된 견적 문서 목록 조회
export async function getPreQuoteDocuments(biddingId: number, companyId: number) {
try {
const documents = await db
.select({
id: biddingDocuments.id,
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),
eq(biddingDocuments.companyId, companyId),
)
)
return documents
} catch (error) {
console.error('Failed to get pre-quote documents:', error)
return []
}
}
// 저장된 품목별 견적 조회 (임시저장/기존 데이터 불러오기용)
export async function getSavedPrItemQuotations(biddingCompanyId: number) {
try {
const savedQuotations = await db
.select({
prItemId: companyPrItemBids.prItemId,
bidUnitPrice: companyPrItemBids.bidUnitPrice,
bidAmount: companyPrItemBids.bidAmount,
proposedDeliveryDate: companyPrItemBids.proposedDeliveryDate,
technicalSpecification: companyPrItemBids.technicalSpecification,
currency: companyPrItemBids.currency
})
.from(companyPrItemBids)
.where(
and(
eq(companyPrItemBids.biddingCompanyId, biddingCompanyId),
eq(companyPrItemBids.isPreQuote, true)
)
)
// Decimal 타입을 number로 변환
return savedQuotations.map(item => ({
prItemId: item.prItemId,
bidUnitPrice: parseFloat(item.bidUnitPrice || '0'),
bidAmount: parseFloat(item.bidAmount || '0'),
proposedDeliveryDate: item.proposedDeliveryDate,
technicalSpecification: item.technicalSpecification,
currency: item.currency
}))
} catch (error) {
console.error('Failed to get saved PR item quotations:', error)
return []
}
}
// 견적 문서 정보 조회 (다운로드용)
export async function getPreQuoteDocumentForDownload(
documentId: number,
biddingId: number,
companyId: number
) {
try {
const document = await db
.select({
fileName: biddingDocuments.fileName,
originalFileName: biddingDocuments.originalFileName,
filePath: biddingDocuments.filePath
})
.from(biddingDocuments)
.where(
and(
eq(biddingDocuments.id, documentId),
eq(biddingDocuments.biddingId, biddingId),
eq(biddingDocuments.companyId, companyId),
eq(biddingDocuments.documentType, 'other')
)
)
.limit(1)
if (document.length === 0) {
return {
success: false,
error: '문서를 찾을 수 없습니다.'
}
}
return {
success: true,
document: document[0]
}
} catch (error) {
console.error('Failed to get pre-quote document:', error)
return {
success: false,
error: '문서 정보 조회에 실패했습니다.'
}
}
}
// 견적 문서 삭제
export async function deletePreQuoteDocument(
documentId: number,
biddingId: number,
companyId: number,
userId: string
) {
try {
// 문서 존재 여부 및 권한 확인
const document = await db
.select({
id: biddingDocuments.id,
fileName: biddingDocuments.fileName,
filePath: biddingDocuments.filePath,
uploadedBy: biddingDocuments.uploadedBy
})
.from(biddingDocuments)
.where(
and(
eq(biddingDocuments.id, documentId),
eq(biddingDocuments.biddingId, biddingId),
eq(biddingDocuments.companyId, companyId),
eq(biddingDocuments.documentType, 'other')
)
)
.limit(1)
if (document.length === 0) {
return {
success: false,
error: '문서를 찾을 수 없습니다.'
}
}
const doc = document[0]
// 데이터베이스에서 문서 정보 삭제
await db
.delete(biddingDocuments)
.where(eq(biddingDocuments.id, documentId))
return {
success: true,
message: '문서가 성공적으로 삭제되었습니다.'
}
} catch (error) {
console.error('Failed to delete pre-quote document:', error)
return {
success: false,
error: '문서 삭제에 실패했습니다.'
}
}
}
|