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
|
"use client"
import { useState,useEffect } from "react"
import { useForm, FormProvider } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { toast } from "sonner"
import RfqInfoHeader from "./rfq-info-header"
import CommercialTermsForm from "./commercial-terms-form"
import QuotationItemsTable from "./quotation-items-table"
import AttachmentsUpload from "./attachments-upload"
interface FileWithType extends File {
attachmentType?: "구매" | "설계"
description?: string
}
import { formatDate, formatCurrency } from "@/lib/utils"
import { Shield, FileText, CheckCircle, Clock, Save, Send, AlertCircle, Upload, } from "lucide-react"
import { Progress } from "@/components/ui/progress"
import { Alert, AlertDescription } from "@/components/ui/alert"
const quotationItemSchema = z.object({
rfqPrItemId: z.number(),
unitPrice: z.number().min(0),
totalPrice: z.number().min(0),
vendorDeliveryDate: z.date().optional().nullable(),
leadTime: z.number().optional(),
manufacturer: z.string().optional(),
manufacturerCountry: z.string().optional(),
modelNo: z.string().optional(),
technicalCompliance: z.boolean(),
alternativeProposal: z.string().optional(),
discountRate: z.number().optional(),
itemRemark: z.string().optional(),
deviationReason: z.string().optional(),
}).passthrough(); // ⬅️ 여기가 핵심: 정의 안 된 키도 유지
// 폼 스키마 정의
const vendorResponseSchema = z.object({
// 상업 조건
vendorCurrency: z.string().optional(),
vendorPaymentTermsCode: z.string().optional(),
vendorIncotermsCode: z.string().optional(),
vendorIncotermsDetail: z.string().nullable().optional(),
vendorDeliveryDate: z.date().optional().nullable(),
vendorContractDuration: z.string().nullable().optional(),
vendorTaxCode: z.string().optional(),
vendorPlaceOfShipping: z.string().optional(),
vendorPlaceOfDestination: z.string().optional(),
// 초도품관리
vendorFirstYn: z.boolean().optional(),
vendorFirstDescription: z.string().optional(),
vendorFirstAcceptance: z.enum(["수용", "부분수용", "거부"]).optional().nullable(),
// Spare part
vendorSparepartYn: z.boolean().optional(),
vendorSparepartDescription: z.string().optional(),
vendorSparepartAcceptance: z.enum(["수용", "부분수용", "거부"]).optional().nullable(),
// 연동제
vendorMaterialPriceRelatedYn: z.boolean().optional(),
vendorMaterialPriceRelatedReason: z.string().optional(),
priceAdjustmentForm: z.object({
priceAdjustmentResponse: z.boolean().nullable().optional(),
itemName: z.string().optional(),
adjustmentReflectionPoint: z.string().optional(),
adjustmentRatio: z.number().optional(),
adjustmentPeriod: z.string().optional(),
referenceDate: z.string().optional(),
comparisonDate: z.string().optional(),
adjustmentDate: z.string().optional(),
contractorWriter: z.string().optional(),
majorApplicableRawMaterial: z.string().optional(),
adjustmentFormula: z.string().optional(),
rawMaterialPriceIndex: z.string().optional(),
adjustmentConditions: z.string().optional(),
notes: z.string().optional(),
majorNonApplicableRawMaterial: z.string().optional(),
nonApplicableReason: z.string().optional(),
}).optional(),
// 변경 사유
currencyReason: z.string().optional(),
paymentTermsReason: z.string().optional(),
deliveryDateReason: z.string().optional(),
incotermsReason: z.string().optional(),
taxReason: z.string().optional(),
shippingReason: z.string().optional(),
// 비고
generalRemark: z.string().optional(),
technicalProposal: z.string().optional(),
// 견적 아이템
quotationItems: z.array(quotationItemSchema),
})
type VendorResponseFormData = z.infer<typeof vendorResponseSchema>
interface VendorResponseEditorProps {
rfq: any
rfqDetail: any
prItems: any[]
vendor: any
existingResponse?: any
userId: number
basicContracts?: any[] // 추가
}
export default function VendorResponseEditor({
rfq,
rfqDetail,
prItems,
vendor,
existingResponse,
userId,
basicContracts = [] // 추가
}: VendorResponseEditorProps) {
const router = useRouter()
const [loading, setLoading] = useState(false)
const [activeTab, setActiveTab] = useState("info")
const [attachments, setAttachments] = useState<FileWithType[]>([])
const [existingAttachments, setExistingAttachments] = useState<any[]>([])
const [deletedAttachments, setDeletedAttachments] = useState<any[]>([])
const [uploadProgress, setUploadProgress] = useState(0) // 추가
const [currencyDecimalPlaces, setCurrencyDecimalPlaces] = useState<number>(2) // 통화별 소수점 자리수
console.log(existingResponse,"existingResponse")
// 제출완료 상태 확인
const isSubmitted = existingResponse?.status === "제출완료" || existingResponse?.submission?.submittedAt
// existingResponse가 변경될 때 existingAttachments 초기화
useEffect(() => {
if (existingResponse?.attachments) {
setExistingAttachments([...existingResponse.attachments])
setDeletedAttachments([]) // 삭제 목록 초기화
} else {
setExistingAttachments([])
setDeletedAttachments([])
}
}, [existingResponse?.attachments])
// 기존 첨부파일 삭제 처리
const handleExistingAttachmentsChange = (files: any[]) => {
const currentAttachments = existingResponse?.attachments || []
const deleted = currentAttachments.filter(
curr => !files.some(f => f.id === curr.id)
)
setExistingAttachments(files)
setDeletedAttachments(prev => [...prev, ...deleted])
}
// Form 초기값 설정
const defaultValues: VendorResponseFormData = {
vendorCurrency: existingResponse?.vendorCurrency || rfqDetail.currency,
vendorPaymentTermsCode: existingResponse?.vendorPaymentTermsCode || rfqDetail.paymentTermsCode,
vendorIncotermsCode: existingResponse?.vendorIncotermsCode || rfqDetail.incotermsCode,
vendorIncotermsDetail: existingResponse?.vendorIncotermsDetail || rfqDetail.incotermsDetail,
vendorDeliveryDate: existingResponse?.vendorDeliveryDate ? new Date(existingResponse.vendorDeliveryDate) :
rfqDetail.deliveryDate ? new Date(rfqDetail.deliveryDate) : null,
vendorContractDuration: existingResponse?.vendorContractDuration || rfqDetail.contractDuration,
vendorTaxCode: existingResponse?.vendorTaxCode || rfqDetail.taxCode,
vendorPlaceOfShipping: existingResponse?.vendorPlaceOfShipping || rfqDetail.placeOfShipping,
vendorPlaceOfDestination: existingResponse?.vendorPlaceOfDestination || rfqDetail.placeOfDestination,
vendorFirstYn: existingResponse?.vendorFirstYn ?? rfqDetail.firstYn,
vendorFirstDescription: existingResponse?.vendorFirstDescription || "",
vendorFirstAcceptance: existingResponse?.vendorFirstAcceptance || null,
vendorSparepartYn: existingResponse?.vendorSparepartYn ?? rfqDetail.sparepartYn,
vendorSparepartDescription: existingResponse?.vendorSparepartDescription || "",
vendorSparepartAcceptance: existingResponse?.vendorSparepartAcceptance || null,
vendorMaterialPriceRelatedYn: existingResponse?.vendorMaterialPriceRelatedYn ?? rfqDetail.materialPriceRelatedYn,
vendorMaterialPriceRelatedReason: existingResponse?.vendorMaterialPriceRelatedReason || "",
priceAdjustmentForm: existingResponse?.priceAdjustmentForm ? {
priceAdjustmentResponse: existingResponse.priceAdjustmentForm.majorApplicableRawMaterial ? true :
existingResponse.priceAdjustmentForm.majorNonApplicableRawMaterial ? false : null,
itemName: existingResponse.priceAdjustmentForm.itemName || "",
adjustmentReflectionPoint: existingResponse.priceAdjustmentForm.adjustmentReflectionPoint || "",
adjustmentRatio: existingResponse.priceAdjustmentForm.adjustmentRatio ? Number(existingResponse.priceAdjustmentForm.adjustmentRatio) : undefined,
adjustmentPeriod: existingResponse.priceAdjustmentForm.adjustmentPeriod || "",
referenceDate: existingResponse.priceAdjustmentForm.referenceDate ?
(typeof existingResponse.priceAdjustmentForm.referenceDate === 'string'
? existingResponse.priceAdjustmentForm.referenceDate
: existingResponse.priceAdjustmentForm.referenceDate.toISOString().split('T')[0]) : "",
comparisonDate: existingResponse.priceAdjustmentForm.comparisonDate ?
(typeof existingResponse.priceAdjustmentForm.comparisonDate === 'string'
? existingResponse.priceAdjustmentForm.comparisonDate
: existingResponse.priceAdjustmentForm.comparisonDate.toISOString().split('T')[0]) : "",
adjustmentDate: existingResponse.priceAdjustmentForm.adjustmentDate ?
(typeof existingResponse.priceAdjustmentForm.adjustmentDate === 'string'
? existingResponse.priceAdjustmentForm.adjustmentDate
: existingResponse.priceAdjustmentForm.adjustmentDate.toISOString().split('T')[0]) : "",
contractorWriter: existingResponse.priceAdjustmentForm.contractorWriter || "",
majorApplicableRawMaterial: existingResponse.priceAdjustmentForm.majorApplicableRawMaterial || "",
adjustmentFormula: existingResponse.priceAdjustmentForm.adjustmentFormula || "",
rawMaterialPriceIndex: existingResponse.priceAdjustmentForm.rawMaterialPriceIndex || "",
adjustmentConditions: existingResponse.priceAdjustmentForm.adjustmentConditions || "",
notes: existingResponse.priceAdjustmentForm.notes || "",
majorNonApplicableRawMaterial: existingResponse.priceAdjustmentForm.majorNonApplicableRawMaterial || "",
nonApplicableReason: existingResponse.priceAdjustmentForm.nonApplicableReason || "",
} : {
priceAdjustmentResponse: null,
itemName: "",
adjustmentReflectionPoint: "",
adjustmentRatio: undefined,
adjustmentPeriod: "",
referenceDate: "",
comparisonDate: "",
adjustmentDate: "",
contractorWriter: "",
majorApplicableRawMaterial: "",
adjustmentFormula: "",
rawMaterialPriceIndex: "",
adjustmentConditions: "",
notes: "",
majorNonApplicableRawMaterial: "",
nonApplicableReason: "",
},
currencyReason: existingResponse?.currencyReason || "",
paymentTermsReason: existingResponse?.paymentTermsReason || "",
deliveryDateReason: existingResponse?.deliveryDateReason || "",
incotermsReason: existingResponse?.incotermsReason || "",
taxReason: existingResponse?.taxReason || "",
shippingReason: existingResponse?.shippingReason || "",
generalRemark: existingResponse?.generalRemark || "",
technicalProposal: existingResponse?.technicalProposal || "",
quotationItems: prItems.map(item => {
const existingItem = existingResponse?.quotationItems?.find(
(q: any) => q.rfqPrItemId === item.id
)
return {
rfqPrItemId: item.id,
unitPrice: existingItem?.unitPrice || 0,
totalPrice: existingItem?.totalPrice || 0,
vendorDeliveryDate: existingItem?.vendorDeliveryDate ? new Date(existingItem.vendorDeliveryDate) : null,
leadTime: existingItem?.leadTime || undefined,
manufacturer: existingItem?.manufacturer || "",
manufacturerCountry: existingItem?.manufacturerCountry || "",
modelNo: existingItem?.modelNo || "",
technicalCompliance: existingItem?.technicalCompliance ?? true,
alternativeProposal: existingItem?.alternativeProposal || "",
discountRate: existingItem?.discountRate || undefined,
itemRemark: existingItem?.itemRemark || "",
deviationReason: existingItem?.deviationReason || "",
}
})
}
const methods = useForm<VendorResponseFormData>({
resolver: zodResolver(vendorResponseSchema),
defaultValues,
mode: 'onChange' // 추가: 실시간 validation
})
const { formState: { errors, isValid } } = methods
useEffect(() => {
if (Object.keys(errors).length > 0) {
console.log('Validation errors:', errors)
}
}, [errors])
console.log(methods.getValues())
const handleFormSubmit = (isSubmit: boolean = false) => {
// 임시저장일 경우 validation 없이 바로 저장
if (!isSubmit) {
const formData = methods.getValues()
onSubmit(formData, false)
return
}
// 제출일 경우에만 validation 수행
// 0원 입력 확인
const items = methods.watch('quotationItems') || []
const zeroPriceItems = items.filter((item: any) => item.unitPrice === 0 || item.totalPrice === 0)
if (zeroPriceItems.length > 0) {
const confirmed = window.confirm(
`견적품목 중 ${zeroPriceItems.length}개 항목에 0원이 입력되어 있습니다.\n` +
`계속 제출하시겠습니까?`
)
if (!confirmed) {
setActiveTab('items')
return
}
}
methods.handleSubmit(
(data) => onSubmit(data, isSubmit),
(errors) => {
console.error('Form validation errors:', errors)
// 첫 번째 에러 필드로 포커스 이동
const firstErrorField = Object.keys(errors)[0]
if (firstErrorField) {
// 어느 탭에 에러가 있는지 확인
if (firstErrorField.startsWith('vendor') &&
!firstErrorField.startsWith('vendorFirst') &&
!firstErrorField.startsWith('vendorSparepart')) {
setActiveTab('terms')
} else if (firstErrorField === 'quotationItems') {
setActiveTab('items')
}
// 구체적인 에러 메시지 표시
if (errors.quotationItems) {
toast.error("견적 품목 정보를 확인해주세요. 모든 품목의 단가와 총액을 입력해야 합니다.")
} else {
toast.error("기본계약 또는 상업조건 정보를 확인해주세요.")
}
}
}
)()
}
const onSubmit = async (data: VendorResponseFormData, isSubmit: boolean = false) => {
console.log('onSubmit called with:', { data, isSubmit, attachmentsCount: attachments.length }) // 디버깅용
setLoading(true)
setUploadProgress(0)
try {
const formData = new FormData()
// 첨부파일 메타데이터 생성 시 타입 확인
const fileMetadata = attachments.map((file: FileWithType) => {
const metadata = {
attachmentType: file.attachmentType || "기타",
description: file.description || ""
};
console.log(`파일 메타데이터 생성: ${file.name} -> 타입: ${metadata.attachmentType}`);
return metadata;
});
// 디버그: 첨부파일 attachmentType 확인
console.log('최종 첨부파일 목록:', attachments.map(f => ({
name: f.name,
attachmentType: f.attachmentType,
size: f.size
})))
console.log('파일 메타데이터:', fileMetadata)
// 기본 데이터 추가
const submitData = {
...data,
rfqsLastId: rfq.id,
rfqLastDetailsId: rfqDetail.id,
vendorId: vendor.id,
status: isSubmit ? "제출완료" : "작성중",
submittedAt: isSubmit ? new Date().toISOString() : null,
submittedBy: isSubmit ? userId : null,
totalAmount: data.quotationItems.reduce((sum, item) => sum + item.totalPrice, 0),
updatedBy: userId,
fileMetadata,
}
console.log('Submitting data:', submitData) // 디버깅용
formData.append('data', JSON.stringify(submitData))
// 첨부파일 추가 (메타데이터를 통해 타입 정보 전달)
attachments.forEach((file, index) => {
const metadata = fileMetadata[index];
console.log(`첨부파일 추가: ${file.name}, 타입: ${metadata?.attachmentType}`);
formData.append(`attachments`, file)
})
// XMLHttpRequest 사용하여 업로드 진행률 추적
const xhr = new XMLHttpRequest()
const uploadPromise = new Promise((resolve, reject) => {
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const percentComplete = Math.round((event.loaded / event.total) * 100)
setUploadProgress(percentComplete)
}
})
xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) {
setUploadProgress(100)
try {
const response = JSON.parse(xhr.responseText)
resolve(response)
} catch (e) {
console.error('Response parsing error:', e)
reject(new Error('응답 파싱 실패'))
}
} else {
console.error('Server error:', xhr.status, xhr.responseText)
reject(new Error(`서버 오류: ${xhr.status}`))
}
})
xhr.addEventListener('error', () => {
console.error('Network error')
reject(new Error('네트워크 오류가 발생했습니다.'))
})
// 요청 전송
const method = existingResponse ? 'PUT' : 'POST'
const url = `/api/partners/rfq-last/${rfq.id}/response`
console.log(`Sending ${method} request to ${url}`) // 디버깅용
xhr.open(method, url)
xhr.send(formData)
})
await uploadPromise
// 임시저장 성공 시 첨부파일 목록 초기화 (중복 저장 방지)
if (!isSubmit) {
console.log('임시저장 완료 - 첨부파일 목록 초기화');
setAttachments([]);
setExistingAttachments([]);
setDeletedAttachments([]);
}
toast.success(isSubmit ? "견적서가 제출되었습니다." : "견적서가 저장되었습니다.")
if (isSubmit) {
router.push('/partners/rfq-last')
}
router.refresh()
} catch (error) {
console.error('Submit error:', error) // 더 상세한 에러 로깅
toast.error(error instanceof Error ? error.message : "오류가 발생했습니다.")
} finally {
setLoading(false)
setUploadProgress(0)
}
}
const totalAmount = methods.watch('quotationItems')?.reduce(
(sum, item) => sum + (item.totalPrice || 0), 0
) || 0
const allContractsSigned = basicContracts.length === 0 ||
basicContracts.every(contract => contract.signedAt);
return (
<FormProvider {...methods}>
<form onSubmit={(e) => {
e.preventDefault() // 기본 submit 동작 방지
handleFormSubmit(false)
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault() // 엔터 키로 인한 폼 제출 방지
}
}}>
<div className="space-y-6">
{/* 헤더 정보 */}
<RfqInfoHeader rfq={rfq} rfqDetail={rfqDetail} vendor={vendor} />
{/* 견적 총액 표시 */}
{totalAmount > 0 && (
<Card>
<CardContent className="pt-6">
<div className="flex items-center justify-between">
<span className="text-lg font-medium">견적 총액</span>
<span className="text-2xl font-bold text-primary">
{formatCurrency(totalAmount, methods.watch('vendorCurrency') || 'USD')}
</span>
</div>
</CardContent>
</Card>
)}
{/* 탭 콘텐츠 */}
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="info">기본계약</TabsTrigger>
<TabsTrigger value="terms">상업조건</TabsTrigger>
<TabsTrigger value="items">견적품목</TabsTrigger>
<TabsTrigger value="attachments">첨부파일</TabsTrigger>
</TabsList>
<TabsContent value="info" className="mt-6">
<Card>
<CardHeader>
<CardTitle>기본계약 정보</CardTitle>
<CardDescription>
이 RFQ에 요청된 기본계약 목록 및 상태입니다
</CardDescription>
</CardHeader>
<CardContent>
{basicContracts.length > 0 ? (
<div className="space-y-4">
{/* 계약 목록 - 그리드 레이아웃 */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
{basicContracts.map((contract) => (
<div
key={contract.id}
className="p-3 border rounded-lg bg-card hover:bg-muted/50 transition-colors"
>
<div className="flex items-start gap-2">
<div className="p-1.5 bg-primary/10 rounded">
<Shield className="h-3.5 w-3.5 text-primary" />
</div>
<div className="flex-1 min-w-0">
<h4 className="font-medium text-sm truncate" title={contract.templateName}>
{contract.templateName}
</h4>
<Badge
variant={contract.signedAt ? "success" : "secondary"}
className="text-xs mt-1.5"
>
{contract.signedAt ? (
<>
<CheckCircle className="h-3 w-3 mr-1" />
서명완료
</>
) : (
<>
<Clock className="h-3 w-3 mr-1" />
서명대기
</>
)}
</Badge>
<p className="text-xs text-muted-foreground mt-1">
{contract.signedAt
? `${formatDate(new Date(contract.signedAt))}`
: contract.deadline
? `~${formatDate(new Date(contract.deadline))}`
: '마감일 없음'}
</p>
</div>
</div>
</div>
))}
</div>
{/* 서명 상태 요약 및 액션 */}
{basicContracts.some(contract => !contract.signedAt) ? (
<div className="flex items-center justify-between p-3 bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-900 rounded-lg">
<div className="flex items-center gap-2">
<AlertCircle className="h-4 w-4 text-amber-600" />
<div>
<p className="text-sm font-medium">
서명 대기: {basicContracts.filter(c => !c.signedAt).length}/{basicContracts.length}개
</p>
<p className="text-xs text-muted-foreground">
견적서 제출 전 모든 계약서 서명 필요
</p>
</div>
</div>
<Button
type="button"
size="sm"
onClick={() => router.push(`/partners/basic-contract`)}
>
서명하기
</Button>
</div>
) : (
<Alert className="border-green-200 bg-green-50 dark:bg-green-950/20">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription className="text-sm">
모든 기본계약 서명 완료
</AlertDescription>
</Alert>
)}
</div>
) : (
<div className="text-center py-8">
<FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<p className="text-muted-foreground">
이 RFQ에 요청된 기본계약이 없습니다
</p>
</div>
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="terms" className="mt-6">
<CommercialTermsForm
rfqDetail={rfqDetail}
rfq={rfq}
onCurrencyDecimalPlacesChange={setCurrencyDecimalPlaces}
/>
</TabsContent>
<TabsContent value="items" className="mt-6">
<QuotationItemsTable
prItems={prItems}
decimalPlaces={currencyDecimalPlaces}
/>
</TabsContent>
<TabsContent value="attachments" className="mt-6">
<AttachmentsUpload
attachments={attachments}
onAttachmentsChange={setAttachments}
existingAttachments={existingAttachments}
onExistingAttachmentsChange={handleExistingAttachmentsChange}
responseId={existingResponse?.id}
userId={userId}
isSubmitted={isSubmitted}
/>
</TabsContent>
</Tabs>
{/* 하단 액션 버튼 */}
{loading && uploadProgress > 0 && (
<Card>
<CardContent className="pt-6">
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="flex items-center gap-2">
<Upload className="h-4 w-4 animate-pulse" />
파일 업로드 중...
</span>
<span className="font-medium">{uploadProgress}%</span>
</div>
<Progress value={uploadProgress} className="h-2" />
<p className="text-xs text-muted-foreground">
대용량 파일 업로드 시 시간이 걸릴 수 있습니다. 창을 닫지 마세요.
</p>
</div>
</CardContent>
</Card>
)}
<div className="flex justify-end gap-3">
<Button
type="button"
variant="outline"
onClick={() => router.back()}
disabled={loading}
>
취소
</Button>
{!isSubmitted && (
<Button
type="button" // submit에서 button으로 변경
variant="secondary"
onClick={() => handleFormSubmit(false)} // 직접 핸들러 호출
disabled={loading || isSubmitted}
>
{loading ? (
<>
<div className="h-4 w-4 mr-2 animate-spin rounded-full border-2 border-current border-t-transparent" />
처리중...
</>
) : isSubmitted ? (
<>
<CheckCircle className="h-4 w-4 mr-2" />
제출완료
</>
) : (
<>
<Save className="h-4 w-4 mr-2" />
임시저장
</>
)}
</Button>
)}
<Button
type="button"
variant="default"
onClick={() => handleFormSubmit(true)} // 직접 핸들러 호출
disabled={loading || !allContractsSigned || isSubmitted || activeTab !== 'attachments'}
>
{!allContractsSigned ? (
<>
<AlertCircle className="h-4 w-4 mr-2" />
기본계약 서명 필요
</>
) : activeTab !== 'attachments' ? (
<>
<AlertCircle className="h-4 w-4 mr-2" />
첨부파일 화면에서 제출 가능
</>
) : loading ? (
<>
<div className="h-4 w-4 mr-2 animate-spin rounded-full border-2 border-current border-t-transparent" />
처리중...
</>
) : isSubmitted ? (
<>
<CheckCircle className="h-4 w-4 mr-2" />
제출완료
</>
) : (
<>
<Send className="h-4 w-4 mr-2" />
견적서 제출
</>
)}
</Button>
</div>
</div>
</form>
</FormProvider>
)
}
|