summaryrefslogtreecommitdiff
path: root/lib/vendor-evaluation-submit/table/evaluation-submit-dialog.tsx
blob: a6f62f826975ec3f022165fa4a6a9005fad3ba08 (plain)
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
"use client"

import * as React from "react"
import { 
  AlertTriangleIcon, 
  CheckCircleIcon, 
  SendIcon, 
  XCircleIcon,
  FileTextIcon,
  ClipboardListIcon,
  LoaderIcon
} from "lucide-react"

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Alert,
  AlertDescription,
  AlertTitle,
} from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { toast } from "sonner"

// Progress 컴포넌트 (간단한 구현)
function Progress({ value, className }: { value: number; className?: string }) {
  return (
    <div className={`w-full bg-gray-200 rounded-full overflow-hidden ${className}`}>
      <div
        className={`h-full bg-blue-600 transition-all duration-300 ${
          value === 100 ? 'bg-green-500' : value >= 50 ? 'bg-blue-500' : 'bg-yellow-500'
        }`}
        style={{ width: `${Math.min(100, Math.max(0, value))}%` }}
      />
    </div>
  )
}

import { 
  getEvaluationSubmissionCompleteness,
  updateEvaluationSubmissionStatus
} from "../service"
import type { EvaluationSubmissionWithVendor } from "../service"

interface EvaluationSubmissionDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  submission: EvaluationSubmissionWithVendor | null
  onSuccess: () => void
}

type CompletenessData = {
  general: {
    total: number
    completed: number
    percentage: number
    isComplete: boolean
  }
  esg: {
    total: number
    completed: number
    percentage: number
    averageScore: number
    isComplete: boolean
  }
  overall: {
    isComplete: boolean
    totalItems: number
    completedItems: number
  }
}

export function EvaluationSubmissionDialog({
  open,
  onOpenChange,
  submission,
  onSuccess,
}: EvaluationSubmissionDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  const [completeness, setCompleteness] = React.useState<CompletenessData | null>(null)

  // 완성도 데이터 로딩
  React.useEffect(() => {
    if (open && submission?.id) {
      loadCompleteness()
    }
  }, [open, submission?.id])

  const loadCompleteness = async () => {
    if (!submission?.id) return

    setIsLoading(true)
    try {
      const data = await getEvaluationSubmissionCompleteness(submission.id)
      setCompleteness(data)
    } catch (error) {
      console.error('Error loading completeness:', error)
      toast.error('완성도 정보를 불러오는데 실패했습니다.')
    } finally {
      setIsLoading(false)
    }
  }

  // 제출하기
  const handleSubmit = async () => {
    if (!submission?.id || !completeness) return

    if (!completeness.overall.isComplete) {
      toast.error('모든 평가 항목을 완료해야 제출할 수 있습니다.')
      return
    }

    setIsSubmitting(true)
    try {
      await updateEvaluationSubmissionStatus(submission.id, 'submitted')
      toast.success('평가가 성공적으로 제출되었습니다.')
      onSuccess()
    } catch (error: any) {
      console.error('Error submitting evaluation:', error)
      toast.error(error.message || '제출에 실패했습니다.')
    } finally {
      setIsSubmitting(false)
    }
  }

  const isKorean = submission?.vendor.countryCode === 'KR'

  // 조선/해양 동시 제출 안내 표시 조건: linkedEvaluations에 서로 다른 division이 2개 이상 존재할 때
  const hasBothDivisions =
    Array.isArray(submission?.linkedEvaluations) &&
    new Set((submission?.linkedEvaluations || []).map((e: any) => e.division)).size > 1

  if (isLoading) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[500px]">
          <div className="flex items-center justify-center py-8">
            <div className="text-center space-y-4">
              <LoaderIcon className="h-8 w-8 animate-spin mx-auto" />
              <p>완성도를 확인하는 중...</p>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <SendIcon className="h-5 w-5" />
            평가 제출하기
          </DialogTitle>
          <DialogDescription>
            {submission?.vendor.vendorName}의 {submission?.evaluationYear}년 평가를 제출합니다.
          </DialogDescription>
        </DialogHeader>

        {/* 안내 알림: 조선/해양 동시 제출 (조건부 표시) */}
        {hasBothDivisions && (
          <Alert className="mb-4 border-red-300 bg-red-50 text-red-800">
            <AlertTitle className="text-red-800">안내</AlertTitle>
            <AlertDescription className="text-red-700">
              제출 버튼을 누르면 동일 연도/라운드의 조선·해양 평가가 함께 제출 처리됩니다.
            </AlertDescription>
          </Alert>
        )}

        {completeness && (
          <div className="space-y-6">
            {/* 전체 완성도 카드 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base flex items-center justify-between">
                  <span>전체 완성도</span>
                  <Badge 
                    variant={completeness.overall.isComplete ? "default" : "secondary"}
                    className={
                      completeness.overall.isComplete 
                        ? "bg-green-100 text-green-800 border-green-200" 
                        : ""
                    }
                  >
                    {completeness.overall.isComplete ? "완료" : "미완료"}
                  </Badge>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <div className="flex items-center justify-between text-sm">
                    <span>전체 진행률</span>
                    <span className="font-medium">
                      {completeness.overall.completedItems}/{completeness.overall.totalItems}개 완료
                    </span>
                  </div>
                  <Progress 
                    value={
                      completeness.overall.totalItems > 0 
                        ? (completeness.overall.completedItems / completeness.overall.totalItems) * 100 
                        : 0
                    } 
                    className="h-2"
                  />
                  <p className="text-xs text-muted-foreground">
                    {completeness.overall.totalItems > 0 
                      ? Math.round((completeness.overall.completedItems / completeness.overall.totalItems) * 100)
                      : 0}% 완료
                  </p>
                </div>
              </CardContent>
            </Card>

            {/* 세부 완성도 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* 일반평가 */}
              <Card>
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm flex items-center gap-2">
                    <FileTextIcon className="h-4 w-4" />
                    일반평가
                    {completeness.general.isComplete ? (
                      <CheckCircleIcon className="h-4 w-4 text-green-600" />
                    ) : (
                      <XCircleIcon className="h-4 w-4 text-red-600" />
                    )}
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="space-y-1">
                    <div className="flex items-center justify-between text-xs">
                      <span>응답 완료</span>
                      <span className="font-medium">
                        {completeness.general.completed}/{completeness.general.total}개
                      </span>
                    </div>
                    <Progress value={completeness.general.percentage} className="h-1" />
                    <p className="text-xs text-muted-foreground">
                      {completeness.general.percentage.toFixed(0)}% 완료
                    </p>
                  </div>
                  
                  {!completeness.general.isComplete && (
                    <p className="text-xs text-red-600">
                      {completeness.general.total - completeness.general.completed}개 항목이 미완료입니다.
                    </p>
                  )}
                </CardContent>
              </Card>

              {/* ESG평가 */}
              {isKorean ? (
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm flex items-center gap-2">
                      <ClipboardListIcon className="h-4 w-4" />
                      ESG평가
                      {completeness.esg.isComplete ? (
                        <CheckCircleIcon className="h-4 w-4 text-green-600" />
                      ) : (
                        <XCircleIcon className="h-4 w-4 text-red-600" />
                      )}
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="space-y-1">
                      <div className="flex items-center justify-between text-xs">
                        <span>응답 완료</span>
                        <span className="font-medium">
                          {completeness.esg.completed}/{completeness.esg.total}개
                        </span>
                      </div>
                      <Progress value={completeness.esg.percentage} className="h-1" />
                      <p className="text-xs text-muted-foreground">
                        {completeness.esg.percentage.toFixed(0)}% 완료
                      </p>
                    </div>
                    
                    {completeness.esg.completed > 0 && (
                      <div className="text-xs">
                        <span className="text-muted-foreground">평균 점수: </span>
                        <span className="font-medium text-blue-600">
                          {completeness.esg.averageScore.toFixed(1)}점
                        </span>
                      </div>
                    )}
                    
                    {!completeness.esg.isComplete && (
                      <p className="text-xs text-red-600">
                        {completeness.esg.total - completeness.esg.completed}개 항목이 미완료입니다.
                      </p>
                    )}
                  </CardContent>
                </Card>
              ) : (
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm flex items-center gap-2">
                      <ClipboardListIcon className="h-4 w-4" />
                      ESG평가
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="text-center text-muted-foreground">
                      <Badge variant="outline">해당없음</Badge>
                      <p className="text-xs mt-2">한국 업체가 아니므로 ESG 평가가 제외됩니다.</p>
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>

            {/* 제출 상태 알림 */}
            {completeness.overall.isComplete ? (
              <Alert>
                <CheckCircleIcon className="h-4 w-4" />
                <AlertTitle>제출 준비 완료</AlertTitle>
                <AlertDescription>
                  모든 평가 항목이 완료되었습니다. 제출하시겠습니까?
                </AlertDescription>
              </Alert>
            ) : (
              <Alert variant="destructive">
                <AlertTriangleIcon className="h-4 w-4" />
                <AlertTitle>제출 불가</AlertTitle>
                <AlertDescription>
                  아직 완료되지 않은 평가 항목이 있습니다. 모든 항목을 완료한 후 제출해 주세요.
                </AlertDescription>
              </Alert>
            )}
          </div>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button 
            onClick={handleSubmit}
            disabled={!completeness?.overall.isComplete || isSubmitting}
            className="min-w-[100px]"
          >
            {isSubmitting ? (
              <>
                <LoaderIcon className="mr-2 h-4 w-4 animate-spin" />
                제출 중...
              </>
            ) : (
              <>
                <SendIcon className="mr-2 h-4 w-4" />
                제출하기
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}