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
|
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
Building2,
CheckCircle,
Clock,
Save,
Send,
ArrowLeft,
AlertCircle,
FileText,
Upload,
File,
X,
Download,
Paperclip
} from "lucide-react"
import { useRouter } from "next/navigation"
import { useToast } from "@/hooks/use-toast"
import {
updateEvaluationResponse,
updateVariableEvaluationResponse,
completeEvaluation
} from "./service"
import {
type EvaluationQuestionItem,
EVALUATION_CATEGORIES
} from "./validation"
import { DEPARTMENT_CODE_LABELS, divisionMap, vendortypeMap } from "@/types/evaluation"
import { EvaluationFormData } from "@/types/evaluation-form"
// 파일 다운로드 유틸리티 import
import { downloadFile, formatFileSize, getFileInfo } from "@/lib/file-download"
interface EvaluationFormProps {
formData: EvaluationFormData
onSubmit?: () => void
}
interface QuestionResponse {
detailId: number | null
score: number | null
comment: string
}
interface AttachmentInfo {
id: number
originalFileName: string
publicPath: string
fileSize: number
description?: string
createdAt: Date
}
/**
* 평가 폼 메인 컴포넌트 (테이블 레이아웃)
*/
export function EvaluationForm({ formData, onSubmit }: EvaluationFormProps) {
const router = useRouter()
const { toast } = useToast()
const [isLoading, setIsLoading] = React.useState(false)
const [isSaving, setIsSaving] = React.useState(false)
const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false)
const [showCompleteDialog, setShowCompleteDialog] = React.useState(false)
const [uploadingFiles, setUploadingFiles] = React.useState<Set<number>>(new Set())
const { evaluationInfo, questions } = formData
// 로컬 상태로 모든 응답 관리
const [responses, setResponses] = React.useState<Record<number, QuestionResponse>>(() => {
const initial: Record<number, QuestionResponse> = {}
questions.forEach(question => {
const isVariable = question.scoreType === 'variable'
// 선택된 답변 옵션 찾기
const selectedOption = question.selectedDetailId ?
question.availableOptions.find(opt => opt.detailId === question.selectedDetailId) : null;
initial[question.criteriaId] = {
detailId: isVariable ? -1 : question.selectedDetailId,
score: isVariable ?
(question.currentScore ? Number(question.currentScore) : null) :
(selectedOption?.score ?? (question.currentScore ? Number(question.currentScore) : null)),
comment: question.currentComment || "",
}
})
return initial
})
// 첨부파일 상태 관리 (서버에서 받은 데이터로 초기화)
const [attachments, setAttachments] = React.useState<Record<number, AttachmentInfo[]>>(() => {
console.log('Initializing attachments from server data...')
const initial: Record<number, AttachmentInfo[]> = {}
questions.forEach(question => {
const questionAttachments = Array.isArray(question.attachments) ? question.attachments : []
initial[question.criteriaId] = questionAttachments
if (questionAttachments.length > 0) {
console.log(`Question ${question.criteriaId} has ${questionAttachments.length} attachments:`, questionAttachments)
}
})
console.log('Initial attachments state:', initial)
return initial
})
// 첨부파일 다운로드 핸들러 - downloadFile 사용
const handleDownloadAttachment = async (attachment: AttachmentInfo) => {
try {
await downloadFile(
attachment.publicPath,
attachment.originalFileName,
{
action: 'download',
showToast: true,
showSuccessToast: true,
onError: (error) => {
console.error("파일 다운로드 실패:", error)
},
onSuccess: (fileName, fileSize) => {
console.log("파일 다운로드 성공:", fileName, fileSize ? formatFileSize(fileSize) : '')
}
}
)
} catch (error) {
console.error("다운로드 처리 중 오류:", error)
}
}
// 카테고리별 질문 그룹화
const questionsByCategory = React.useMemo(() => {
const grouped = questions.reduce((acc, question) => {
const key = question.category
if (!acc[key]) {
acc[key] = []
}
acc[key].push(question)
return acc
}, {} as Record<string, EvaluationQuestionItem[]>)
return grouped
}, [questions])
const categoryNames = EVALUATION_CATEGORIES
// 응답 변경 핸들러
const handleResponseChange = (questionId: number, detailId: number, customScore?: number) => {
const question = questions.find(q => q.criteriaId === questionId)
if (!question) return
const selectedOption = question.availableOptions.find(opt => opt.detailId === detailId)
setResponses(prev => ({
...prev,
[questionId]: {
...prev[questionId],
detailId,
score: customScore !== undefined ? customScore : selectedOption?.score || null,
}
}))
setHasUnsavedChanges(true)
}
// 점수 직접 입력 핸들러 (variable 타입용)
const handleScoreChange = (questionId: number, score: number | null) => {
console.log('Score changed:', questionId, score)
setResponses(prev => ({
...prev,
[questionId]: {
...prev[questionId],
score,
detailId: prev[questionId].detailId || -1
}
}))
setHasUnsavedChanges(true)
}
// 코멘트 변경 핸들러
const handleCommentChange = (questionId: number, comment: string) => {
setResponses(prev => ({
...prev,
[questionId]: {
...prev[questionId],
comment
}
}))
setHasUnsavedChanges(true)
}
// 파일 업로드 핸들러
const handleFileUpload = async (questionId: number, file: File, description?: string) => {
try {
console.log('Starting file upload for question:', questionId, 'file:', file.name)
setUploadingFiles(prev => new Set(prev).add(questionId))
// 질문 정보 확인
const question = questions.find(q => q.criteriaId === questionId)
if (!question) {
throw new Error('질문을 찾을 수 없습니다.')
}
// 답변이 있는지 확인
const response = responses[questionId]
const isVariable = question.scoreType === 'variable'
const isAnswered = isVariable ?
(response.score !== null) :
(response.detailId !== null && response.detailId > 0)
if (!isAnswered) {
throw new Error('먼저 답변을 선택해주세요.')
}
// FormData 생성
const formData = new FormData()
formData.append('file', file)
formData.append('questionId', questionId.toString())
formData.append('evaluationId', evaluationInfo.id.toString())
if (description) {
formData.append('description', description)
}
if (isVariable) {
formData.append('isVariable', 'true')
}
console.log('Sending upload request...')
// 파일 업로드 API 호출
const response_api = await fetch('/api/evaluation/attachments', {
method: 'POST',
body: formData,
})
console.log('Upload response status:', response_api.status)
if (!response_api.ok) {
const errorText = await response_api.text()
console.error('Upload failed with status:', response_api.status, 'error:', errorText)
throw new Error(`파일 업로드에 실패했습니다. (${response_api.status})`)
}
const result = await response_api.json()
console.log('Upload result:', result)
if (result.success && result.attachment) {
// 첨부파일 목록 업데이트
setAttachments(prev => ({
...prev,
[questionId]: [...(prev[questionId] || []), {
id: result.attachment.id,
originalFileName: result.attachment.originalFileName,
publicPath: result.attachment.publicPath,
fileSize: result.attachment.fileSize,
description: result.attachment.description,
createdAt: new Date(result.attachment.createdAt),
}]
}))
toast({
title: "파일 업로드 완료",
description: `${file.name}이 성공적으로 업로드되었습니다.`,
})
} else {
throw new Error(result.error || '파일 업로드에 실패했습니다.')
}
} catch (error) {
console.error('File upload failed:', error)
toast({
title: "업로드 실패",
description: error instanceof Error ? error.message : "파일 업로드 중 오류가 발생했습니다.",
variant: "destructive",
})
} finally {
setUploadingFiles(prev => {
const newSet = new Set(prev)
newSet.delete(questionId)
return newSet
})
}
}
// 첨부파일 삭제 핸들러
const handleDeleteAttachment = async (questionId: number, attachmentId: number) => {
try {
const response = await fetch(`/api/evaluation/attachments/${attachmentId}`, {
method: 'DELETE',
})
if (!response.ok) {
throw new Error('파일 삭제에 실패했습니다.')
}
// 첨부파일 목록에서 제거
setAttachments(prev => ({
...prev,
[questionId]: prev[questionId]?.filter(att => att.id !== attachmentId) || []
}))
toast({
title: "파일 삭제 완료",
description: "첨부파일이 삭제되었습니다.",
})
} catch (error) {
console.error('File deletion failed:', error)
toast({
title: "삭제 실패",
description: "파일 삭제 중 오류가 발생했습니다.",
variant: "destructive",
})
}
}
// 임시저장
const handleSave = async () => {
try {
setIsSaving(true)
const promises = Object.entries(responses)
.filter(([questionId, response]) => {
const question = questions.find(q => q.criteriaId === parseInt(questionId))
const isVariable = question?.scoreType === 'variable'
if (isVariable) {
return response.score !== null
} else {
return response.detailId !== null && response.detailId > 0
}
})
.map(([questionId, response]) => {
const question = questions.find(q => q.criteriaId === parseInt(questionId))
const isVariable = question?.scoreType === 'variable'
if (isVariable) {
// Variable 타입은 별도 함수 사용
return updateVariableEvaluationResponse(
evaluationInfo.id,
parseInt(questionId), // criteriaId
response.score!,
response.comment || undefined
)
} else {
// 일반 타입
return updateEvaluationResponse(
evaluationInfo.id,
response.detailId!,
response.comment || undefined,
response.score || undefined
)
}
})
await Promise.all(promises)
setHasUnsavedChanges(false)
toast({
title: "임시저장 완료",
description: "응답이 성공적으로 저장되었습니다.",
})
} catch (error) {
console.error('Failed to save responses:', error)
toast({
title: "저장 실패",
description: "응답 저장 중 오류가 발생했습니다.",
variant: "destructive",
})
} finally {
setIsSaving(false)
}
}
// 평가 완료 처리 (실제 완료 로직)
const handleCompleteConfirmed = async () => {
try {
setIsLoading(true)
setShowCompleteDialog(false)
// 먼저 모든 응답 저장
await handleSave()
// 평가 완료 처리
await completeEvaluation(evaluationInfo.id)
toast({
title: "평가 완료",
description: "평가가 성공적으로 완료되었습니다.",
})
onSubmit?.()
router.push('/evcp/evaluation-input')
} catch (error) {
console.error('Failed to complete evaluation:', error)
toast({
title: "완료 실패",
description: "평가 완료 처리 중 오류가 발생했습니다.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}
// 평가 완료 버튼 클릭 (다이얼로그 표시)
const handleCompleteClick = () => {
setShowCompleteDialog(true)
}
const completedCount = Object.values(responses).filter(r => {
const question = questions.find(q => q.criteriaId === parseInt(Object.keys(responses).find(key => responses[parseInt(key)] === r) || '0'))
const isVariable = question?.scoreType === 'variable'
if (isVariable) {
return r.score !== null
} else {
return r.detailId !== null && r.detailId > 0
}
}).length
const totalCount = questions.length
const allCompleted = completedCount === totalCount
return (
<div className="container mx-auto py-6 space-y-6">
{/* 헤더 */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="icon"
onClick={() => router.back()}
>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<h1 className="text-2xl font-bold">평가 작성</h1>
<p className="text-muted-foreground">협력업체 평가를 진행해주세요</p>
</div>
</div>
<div className="flex items-center gap-2">
{evaluationInfo.isCompleted ? (
<Badge variant="default" className="flex items-center gap-1">
<CheckCircle className="h-3 w-3" />
완료
</Badge>
) : (
<Badge variant="secondary" className="flex items-center gap-1">
<Clock className="h-3 w-3" />
진행중
</Badge>
)}
</div>
</div>
{/* 평가 정보 카드 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Building2 className="h-5 w-5" />
평가 정보
</CardTitle>
</CardHeader>
<CardContent className="pt-4 pb-4">
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
<div className="space-y-1">
<Label className="text-sm text-muted-foreground">협력업체</Label>
<div className="font-medium text-sm">{evaluationInfo.vendorName} ({evaluationInfo.vendorCode})</div>
</div>
<div className="space-y-1">
<Label className="text-sm text-muted-foreground">사업부</Label>
<div>
<Badge variant="outline">
{divisionMap[evaluationInfo.division] || evaluationInfo.division}
</Badge>
</div>
</div>
<div className="space-y-1">
<Label className="text-sm text-muted-foreground">자재유형</Label>
<div>
<Badge variant="outline">
{vendortypeMap[evaluationInfo.materialType] || evaluationInfo.materialType}
</Badge>
</div>
</div>
<div className="space-y-1">
<Label className="text-sm text-muted-foreground">담당부서</Label>
<div className="font-medium text-sm">
{DEPARTMENT_CODE_LABELS[evaluationInfo.departmentCode] || evaluationInfo.departmentCode}
</div>
</div>
</div>
{/* 📎 첨부파일 통계 정보 */}
{formData.attachmentStats && formData.attachmentStats.totalFiles > 0 && (
<div className="border-t pt-4">
<div className="flex items-center gap-4 text-sm">
<div className="flex items-center gap-2">
<Paperclip className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">첨부파일 현황</span>
</div>
<div className="flex items-center gap-4">
<div className="text-muted-foreground">
총 <span className="font-medium text-foreground">{formData.attachmentStats.totalFiles}</span>개 파일
</div>
<div className="text-muted-foreground">
크기: <span className="font-medium text-foreground">{formatFileSize(formData.attachmentStats.totalSize)}</span>
</div>
<div className="text-muted-foreground">
첨부 질문: <span className="font-medium text-foreground">{formData.attachmentStats.questionsWithAttachments}</span>개
</div>
</div>
</div>
</div>
)}
</CardContent>
</Card>
{/* 평가 테이블 - 카테고리별 */}
{Object.entries(questionsByCategory).map(([category, categoryQuestions]) => {
const categoryCompletedCount = categoryQuestions.filter(q => {
const response = responses[q.criteriaId]
const isVariable = q.scoreType === 'variable'
if (isVariable) {
return response.score !== null
} else {
return response.detailId !== null
}
}).length
const categoryTotalCount = categoryQuestions.length
const categoryProgress = (categoryCompletedCount / categoryTotalCount) * 100
return (
<Card key={category}>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<CardTitle className="text-lg">{categoryNames[category] || category}</CardTitle>
<Badge variant="secondary">
{categoryQuestions.length}개 질문
</Badge>
</div>
<div className="flex items-center gap-4">
<div className="text-right">
<div className="text-sm font-medium">
{categoryCompletedCount} / {categoryTotalCount} 완료
</div>
<div className="text-xs text-muted-foreground">
{Math.round(categoryProgress)}%
</div>
</div>
<div className="w-24 bg-muted rounded-full h-2">
<div
className="bg-primary h-2 rounded-full transition-all duration-300"
style={{ width: `${categoryProgress}%` }}
/>
</div>
</div>
</div>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[150px]">평가</TableHead>
<TableHead className="w-[200px]">범위</TableHead>
<TableHead className="w-[250px]">비고</TableHead>
<TableHead className="w-[200px]">답변 선택</TableHead>
<TableHead className="w-[80px]">점수</TableHead>
<TableHead className="w-[250px]">추가 의견</TableHead>
<TableHead className="w-[200px]">첨부파일</TableHead>
<TableHead className="w-[80px]">상태</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{categoryQuestions.map((question) => {
const response = responses[question.criteriaId]
const questionAttachments = attachments[question.criteriaId] || []
const isVariable = question.scoreType === 'variable'
const isAnswered = isVariable ?
(response.score !== null) :
(response.detailId !== null && response.detailId > 0)
return (
<TableRow key={question.criteriaId} className={isAnswered ? "bg-green-50" : "bg-yellow-50"}>
<TableCell className="font-medium">
{question.classification}
</TableCell>
<TableCell className="text-sm">
{question.range}
</TableCell>
<TableCell className="text-sm">
{question.remarks}
</TableCell>
<TableCell>
{!isVariable && (
<Select
value={response.detailId?.toString() || ""}
onValueChange={(value) => handleResponseChange(question.criteriaId, parseInt(value))}
disabled={isLoading || isSaving}
>
<SelectTrigger>
<SelectValue placeholder="답변을 선택하세요" />
</SelectTrigger>
<SelectContent>
{question.availableOptions
.sort((a, b) => b.score - a.score)
.map((option) => (
<SelectItem key={option.detailId} value={option.detailId.toString()}>
<div className="flex items-center justify-between w-full">
<span>{option.detail}</span>
{!option.detail.includes('variable') && (
<Badge variant="outline" className="ml-2">
{option.score}점
</Badge>
)}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
)}
{isVariable && (
<Input
type="number"
min="0"
step="1"
value={response.score !== null ? response.score : ""}
onChange={(e) => {
const value = e.target.value
if (value === '') {
handleScoreChange(question.criteriaId, null)
return
}
const numericValue = parseInt(value)
// 0 이상의 정수만 허용
if (!isNaN(numericValue) && numericValue >= 0) {
handleScoreChange(question.criteriaId, numericValue)
}
}}
onBlur={(e) => {
// 포커스를 잃을 때 추가 검증
const value = e.target.value
if (value !== '' && (isNaN(parseInt(value)) || parseInt(value) < 0)) {
handleScoreChange(question.criteriaId, null)
}
}}
placeholder="점수 입력 (0 이상)"
className="w-48"
disabled={isLoading || isSaving}
/>
)}
</TableCell>
<TableCell>
{isAnswered && (
<Badge variant={response.score! >= 4 ? "default" : response.score! >= 3 ? "secondary" : "destructive"}>
{response.score}점
</Badge>
)}
</TableCell>
<TableCell>
<Textarea
placeholder={isAnswered ? "추가 의견을 입력하세요..." : "먼저 답변을 선택하세요"}
value={response.comment}
onChange={(e) => handleCommentChange(question.criteriaId, e.target.value)}
disabled={isLoading || isSaving || !isAnswered}
rows={2}
className="resize-none min-w-[200px]"
/>
</TableCell>
<TableCell>
<div className="space-y-2">
{/* 파일 업로드 버튼 */}
<div className="flex items-center gap-2">
<input
type="file"
id={`file-${question.criteriaId}`}
className="hidden"
accept=".pdf,.doc,.docx,.hwp,.xls,.xlsx,.jpg,.jpeg,.png,.gif"
onChange={(e) => {
const file = e.target.files?.[0]
if (file && isAnswered) handleFileUpload(question.criteriaId, file)
}}
disabled={!isAnswered || isLoading || isSaving || uploadingFiles.has(question.criteriaId)}
/>
<Button
asChild /* shadcn/ui -> 내부에 <button> 대신 원하는 태그로 감싸 줌 */
variant="outline"
size="sm"
disabled={!isAnswered || isLoading || isSaving || uploadingFiles.has(question.criteriaId)}
className="flex items-center gap-1"
>
<label htmlFor={`file-${question.criteriaId}`} className="cursor-pointer">
<Upload className="h-3 w-3" />
{uploadingFiles.has(question.criteriaId) ? "업로드 중..." : "파일 첨부"}
</label>
</Button>
</div>
{/* 첨부된 파일 목록 - 개선된 버전 */}
{questionAttachments.length > 0 && (
<div className="space-y-1">
{questionAttachments.map((attachment) => {
const fileInfo = getFileInfo(attachment.originalFileName)
return (
<div key={attachment.id} className="flex items-center justify-between p-2 bg-muted rounded-md">
<div className="flex items-center gap-2 flex-1">
<span className="text-sm">{fileInfo.icon}</span>
<div className="flex-1 min-w-0">
<div className="text-xs font-medium truncate">
{attachment.originalFileName}
</div>
<div className="text-xs text-muted-foreground">
{formatFileSize(attachment.fileSize)}
</div>
</div>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => handleDownloadAttachment(attachment)}
className="h-6 w-6 p-0"
>
<Download className="h-3 w-3" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleDeleteAttachment(question.criteriaId, attachment.id)}
className="h-6 w-6 p-0 text-destructive hover:text-destructive"
>
<X className="h-3 w-3" />
</Button>
</div>
</div>
)
})}
</div>
)}
</div>
</TableCell>
<TableCell>
{isAnswered ? (
<Badge variant="default" className="text-xs">
완료
</Badge>
) : (
<Badge variant="destructive" className="text-xs">
미답변
</Badge>
)}
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</CardContent>
</Card>
)
})}
{/* 하단 액션 버튼 */}
<div className="sticky bottom-0 bg-background border-t p-4">
<div className="flex items-center justify-between max-w-7xl mx-auto">
{!evaluationInfo.isCompleted && (
<>
<div className="flex items-center gap-4 text-sm text-muted-foreground">
{hasUnsavedChanges && (
<div className="flex items-center gap-1">
<AlertCircle className="h-4 w-4 text-amber-500" />
<span>저장되지 않은 변경사항이 있습니다</span>
</div>
)}
<div className="flex items-center gap-1">
<FileText className="h-4 w-4" />
<span>진행률: {completedCount}/{totalCount}</span>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
onClick={() => router.back()}
disabled={isLoading || isSaving}
>
취소
</Button>
<Button
variant="secondary"
onClick={handleSave}
disabled={isLoading || isSaving || !hasUnsavedChanges}
className="flex items-center gap-2"
>
<Save className="h-4 w-4" />
{isSaving ? "저장 중..." : "임시저장"}
</Button>
<Button
onClick={handleCompleteClick}
disabled={isLoading || isSaving || !allCompleted}
className="flex items-center gap-2"
>
<Send className="h-4 w-4" />
평가 완료
</Button>
</div>
</>
)}
</div>
</div>
{/* 평가 완료 확인 다이얼로그 */}
<AlertDialog open={showCompleteDialog} onOpenChange={setShowCompleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<CheckCircle className="h-5 w-5 text-green-600" />
평가 완료 확인
</AlertDialogTitle>
<AlertDialogDescription className="space-y-2">
<p>평가를 완료하시겠습니까?</p>
<div className="bg-muted p-3 rounded-md text-sm">
<div className="font-medium text-foreground mb-1">평가 정보</div>
<div>• 협력업체: {evaluationInfo.vendorName}</div>
<div>• 완료된 문항: {completedCount}/{totalCount}개</div>
<div>• 진행률: {Math.round((completedCount / totalCount) * 100)}%</div>
</div>
<p className="text-sm text-muted-foreground">
완료 후에는 수정이 제한될 수 있습니다.
</p>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isLoading}>취소</AlertDialogCancel>
<AlertDialogAction
onClick={handleCompleteConfirmed}
disabled={isLoading}
className="bg-green-600 hover:bg-green-700"
>
{isLoading ? "처리 중..." : "평가 완료"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
|