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
|
"use client"
import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm, useFieldArray } from "react-hook-form"
import * as z from "zod"
import { toast } from "sonner"
import { CheckCircle2, AlertCircle, Building2 } from "lucide-react"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { PeriodicEvaluationView } from "@/db/schema"
import { finalizeEvaluations } from "../service"
// 등급 옵션
const GRADE_OPTIONS = [
{ value: "A", label: "A등급 (95점 이상)" },
{ value: "B", label: "B등급 (90-95점 미만)" },
{ value: "C", label: "C등급 (60-90점 미만)" },
{ value: "D", label: "D등급 (60점 미만)" },
] as const
// 점수에 따른 등급 계산
const calculateGrade = (score: number): "A" | "B" | "C" | "D" => {
if (score >= 95) return "A"
if (score >= 90) return "B"
if (score >= 60) return "C"
return "D"
}
// 등급에 따른 점수 계산 (등급 변경 시 점수 자동 조정)
const calculateScoreFromGrade = (grade: "A" | "B" | "C" | "D"): number => {
switch (grade) {
case "A":
return 95 // A등급 최소 점수
case "B":
return 90 // B등급 최소 점수
case "C":
return 60 // C등급 최소 점수
case "D":
return 0 // D등급은 0점으로 설정 (또는 30점 중간값)
default:
return 0
}
}
// 평가점수 계산 (evaluation-columns.tsx와 동일한 로직)
const calculateEvaluationScore = (evaluation: PeriodicEvaluationView): number => {
const processScore = Number(evaluation.processScore || 0);
const priceScore = Number(evaluation.priceScore || 0);
const deliveryScore = Number(evaluation.deliveryScore || 0);
const selfEvaluationScore = Number(evaluation.selfEvaluationScore || 0);
const participationBonus = Number(evaluation.participationBonus || 0);
const qualityDeduction = Number(evaluation.qualityDeduction || 0);
const totalScore = processScore + priceScore + deliveryScore + selfEvaluationScore;
const evaluationScore = totalScore + participationBonus - qualityDeduction;
return evaluationScore;
}
// 개별 평가 스키마
const evaluationItemSchema = z.object({
id: z.number(),
vendorName: z.string(),
vendorCode: z.string(),
evaluationScore: z.coerce.number().nullable(),
finalScore: z.coerce.number()
.min(0, "점수는 0 이상이어야 합니다")
.max(100, "점수는 100 이하여야 합니다"),
finalGrade: z.enum(["A", "B", "C", "D"]),
})
// 전체 폼 스키마
const finalizeEvaluationSchema = z.object({
evaluations: z.array(evaluationItemSchema).min(1, "확정할 평가가 없습니다"),
})
type FinalizeEvaluationFormData = z.infer<typeof finalizeEvaluationSchema>
interface FinalizeEvaluationDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
evaluations: PeriodicEvaluationView[]
onSuccess?: () => void
}
export function FinalizeEvaluationDialog({
open,
onOpenChange,
evaluations,
onSuccess,
}: FinalizeEvaluationDialogProps) {
const [isLoading, setIsLoading] = React.useState(false)
const form = useForm<FinalizeEvaluationFormData>({
resolver: zodResolver(finalizeEvaluationSchema),
defaultValues: {
evaluations: [],
},
})
const { fields, update } = useFieldArray({
control: form.control,
name: "evaluations",
})
// evaluations가 변경될 때 폼 초기화
React.useEffect(() => {
if (evaluations.length > 0) {
const formData = evaluations.map(evaluation => {
// 평가점수 계산 (참고용)
const evaluationScore = calculateEvaluationScore(evaluation);
// 최종점수가 있으면 우선 사용, 없으면 평가점수 사용
const finalScoreValue = evaluation.finalScore
? Number(evaluation.finalScore)
: (evaluationScore > 0 ? evaluationScore : 0);
// 최종등급이 있으면 우선 사용, 없으면 점수 기반으로 계산
const finalGradeValue = evaluation.finalGrade
? evaluation.finalGrade
: calculateGrade(finalScoreValue);
return {
id: evaluation.id,
vendorName: evaluation.vendorName || "",
vendorCode: evaluation.vendorCode || "",
evaluationScore: evaluationScore > 0 ? evaluationScore : null,
finalScore: finalScoreValue,
finalGrade: finalGradeValue,
};
});
form.reset({ evaluations: formData })
}
}, [evaluations, form])
// 점수 변경 시 등급 자동 계산
const handleScoreChange = (index: number, score: number) => {
const newGrade = calculateGrade(score)
// form.setValue를 사용하여 리렌더링 최소화
form.setValue(`evaluations.${index}.finalGrade`, newGrade, { shouldValidate: false })
}
// 등급 변경 시 점수 자동 조정
const handleGradeChange = (index: number, grade: "A" | "B" | "C" | "D") => {
const currentEvaluation = form.getValues(`evaluations.${index}`)
const newScore = calculateScoreFromGrade(grade)
update(index, {
...currentEvaluation,
finalScore: newScore,
finalGrade: grade,
})
}
// 폼 제출
const onSubmit = async (data: FinalizeEvaluationFormData) => {
try {
setIsLoading(true)
const finalizeData = data.evaluations.map(evaluation => ({
id: evaluation.id,
finalScore: evaluation.finalScore,
finalGrade: evaluation.finalGrade,
}))
await finalizeEvaluations(finalizeData)
toast.success("평가가 확정되었습니다", {
description: `${data.evaluations.length}건의 평가가 최종 확정되었습니다.`,
})
onSuccess?.()
onOpenChange(false)
} catch (error) {
console.error("Failed to finalize evaluations:", error)
toast.error("평가 확정 실패", {
description: error instanceof Error ? error.message : "알 수 없는 오류가 발생했습니다.",
})
} finally {
setIsLoading(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<CheckCircle2 className="h-5 w-5 text-purple-600" />
평가 확정
</DialogTitle>
<DialogDescription>
검토가 완료된 평가의 최종 점수와 등급을 확정합니다.
확정 후에는 수정이 제한됩니다.
</DialogDescription>
</DialogHeader>
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
확정할 평가: <strong>{evaluations.length}건</strong>
<br />
평가 점수는 리뷰어들의 평가를 바탕으로 계산된 값을 기본으로 하며, 필요시 조정 가능합니다.
</AlertDescription>
</Alert>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[200px]">협력업체</TableHead>
<TableHead className="w-[100px]">평가점수</TableHead>
<TableHead className="w-[120px]">최종점수</TableHead>
<TableHead className="w-[120px]">최종등급</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{fields.map((field, index) => (
<TableRow key={field.id}>
<TableCell>
<div className="space-y-1">
<div className="font-medium">
{form.watch(`evaluations.${index}.vendorName`)}
</div>
<div className="text-sm text-muted-foreground">
{form.watch(`evaluations.${index}.vendorCode`)}
</div>
</div>
</TableCell>
<TableCell>
<div className="text-center">
{form.watch(`evaluations.${index}.evaluationScore`) !== null ? (
<Badge variant="outline" className="font-mono">
{Number(form.watch(`evaluations.${index}.evaluationScore`)).toFixed(1)}점
</Badge>
) : (
<span className="text-muted-foreground">-</span>
)}
</div>
</TableCell>
<TableCell>
<FormField
control={form.control}
name={`evaluations.${index}.finalScore`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
type="number"
min="0"
max="100"
step="0.1"
value={field.value ?? ""}
onChange={(e) => {
const inputValue = e.target.value
if (inputValue === "" || inputValue === "-") {
field.onChange(0)
} else {
const numValue = Number(inputValue)
if (!isNaN(numValue)) {
// 입력 중에는 제한하지 않고, blur 시에만 제한 적용
field.onChange(numValue)
}
}
}}
onBlur={(e) => {
const value = Number(e.target.value)
const clampedValue = isNaN(value) ? 0 : Math.max(0, Math.min(100, value))
field.onChange(clampedValue)
handleScoreChange(index, clampedValue)
field.onBlur()
}}
className="text-center font-mono"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={form.control}
name={`evaluations.${index}.finalGrade`}
render={({ field }) => (
<FormItem>
<FormControl>
<Select
value={field.value}
onValueChange={(value) => {
field.onChange(value as "A" | "B" | "C" | "D")
handleGradeChange(index, value as "A" | "B" | "C" | "D")
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{GRADE_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading}
>
취소
</Button>
<Button
type="submit"
disabled={isLoading}
className="bg-purple-600 hover:bg-purple-700"
>
{isLoading ? "확정 중..." : `평가 확정 (${fields.length}건)`}
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
)
}
|