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
|
/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';
/* IMPORT */
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import {
getRegEvalCriteriaWithDetails,
modifyRegEvalCriteriaFixed,
modifyRegEvalCriteriaVariable,
} from '../service';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Plus, Trash2 } from 'lucide-react';
import {
REG_EVAL_CRITERIA_CATEGORY,
REG_EVAL_CRITERIA_CATEGORY2,
REG_EVAL_CRITERIA_ITEM,
type RegEvalCriteriaDetails,
type RegEvalCriteria, // RegEvalCriteriaView 대신 RegEvalCriteria 사용
} from '@/db/schema';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { toast } from 'sonner';
import { useForm, useFieldArray } from 'react-hook-form';
import { useEffect, useTransition } from 'react';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
// ----------------------------------------------------------------------------------------------------
/* TYPES */
const regEvalCriteriaFormSchema = z.object({
category: z.string().min(1, '평가부문은 필수 항목입니다.'),
category2: z.string().min(1, '점수구분은 필수 항목입니다.'),
item: z.string().min(1, '항목은 필수 항목입니다.'),
classification: z.string().min(1, '구분은 필수 항목입니다.'),
range: z.string().nullable().optional(),
remarks: z.string().nullable().optional(),
scoreType: z.enum(['fixed', 'variable']).default('fixed'),
variableScoreMin: z.coerce.number().nullable().optional(),
variableScoreMax: z.coerce.number().nullable().optional(),
variableScoreUnit: z.string().nullable().optional(),
criteriaDetails: z.array(
z.object({
id: z.number().optional(),
detail: z.string().optional(),
scoreEquipShip: z.coerce.number().nullable().optional(),
scoreEquipMarine: z.coerce.number().nullable().optional(),
scoreBulkShip: z.coerce.number().nullable().optional(),
scoreBulkMarine: z.coerce.number().nullable().optional(),
})
).optional(),
});
type RegEvalCriteriaFormData = z.infer<typeof regEvalCriteriaFormSchema>;
interface CriteriaDetailFormProps {
index: number
form: any
onRemove: () => void
canRemove: boolean
disabled?: boolean
scoreType: 'fixed' | 'variable'
}
interface RegEvalCriteriaUpdateSheetProps {
open: boolean,
onOpenChange: (open: boolean) => void,
criteriaData: RegEvalCriteria, // criteriaViewData → criteriaData로 변경
onSuccess: () => void,
};
// ----------------------------------------------------------------------------------------------------
/* CRITERIA DETAIL FORM COPONENT */
function CriteriaDetailForm({
index,
form,
onRemove,
canRemove,
disabled = false,
scoreType,
}: CriteriaDetailFormProps) {
return (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="text-lg">평가 옵션 {index + 1}</CardTitle>
{canRemove && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={onRemove}
className="text-destructive hover:text-destructive"
disabled={disabled}
>
<Trash2 className="w-4 h-4" />
</Button>
)}
</div>
</CardHeader>
<CardContent className="space-y-4">
<FormField
control={form.control}
name={`criteriaDetails.${index}.id`}
render={({ field }) => (
<Input type="hidden" {...field} />
)}
/>
<FormField
control={form.control}
name={`criteriaDetails.${index}.detail`}
render={({ field }) => (
<FormItem>
<FormLabel>평가 옵션 내용</FormLabel>
<FormControl>
<Textarea
placeholder="평가 옵션 내용을 입력하세요. (예: 우수, 보통, 미흡)"
{...field}
disabled={disabled}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* 고정점수인 경우에만 점수 입력 필드들 표시 - 한 줄에 4개 */}
{scoreType === 'fixed' && (
<div className="grid grid-cols-4 gap-4">
<FormField
control={form.control}
name={`criteriaDetails.${index}.scoreEquipShip`}
render={({ field }) => (
<FormItem>
<FormLabel>기자재-조선</FormLabel>
<FormControl>
<Input
type="number"
step="0.01"
placeholder="0.00"
{...field}
value={field.value ?? ''}
disabled={disabled}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`criteriaDetails.${index}.scoreEquipMarine`}
render={({ field }) => (
<FormItem>
<FormLabel>기자재-해양</FormLabel>
<FormControl>
<Input
type="number"
step="0.01"
placeholder="0.00"
{...field}
value={field.value ?? ''}
disabled={disabled}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`criteriaDetails.${index}.scoreBulkShip`}
render={({ field }) => (
<FormItem>
<FormLabel>벌크-조선</FormLabel>
<FormControl>
<Input
type="number"
step="0.01"
placeholder="0.00"
{...field}
value={field.value ?? ''}
disabled={disabled}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`criteriaDetails.${index}.scoreBulkMarine`}
render={({ field }) => (
<FormItem>
<FormLabel>벌크-해양</FormLabel>
<FormControl>
<Input
type="number"
step="0.01"
placeholder="0.00"
{...field}
value={field.value ?? ''}
disabled={disabled}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
)}
{/* 변동점수인 경우 안내 메시지 */}
{scoreType === 'variable' && (
<div className="p-4 bg-muted rounded-lg">
<p className="text-sm text-muted-foreground">
변동점수 유형에서는 개별 점수를 입력하지 않습니다.
기본 정보에서 설정한 최소/최대 점수 범위가 적용됩니다.
</p>
</div>
)}
</CardContent>
</Card>
)
}
/* CRITERIA FORM SHEET COPONENT */
function RegEvalCriteriaUpdateSheet({
open,
onOpenChange,
criteriaData,
onSuccess,
}: RegEvalCriteriaUpdateSheetProps) {
const [isPending, startTransition] = useTransition();
const form = useForm<RegEvalCriteriaFormData>({
resolver: zodResolver(regEvalCriteriaFormSchema),
defaultValues: {
category: '',
category2: '',
item: '',
classification: '',
range: '',
remarks: '',
scoreType: 'fixed',
variableScoreMin: null,
variableScoreMax: null,
variableScoreUnit: '',
criteriaDetails: [
{
id: undefined,
detail: '',
scoreEquipShip: null,
scoreEquipMarine: null,
scoreBulkShip: null,
scoreBulkMarine: null,
},
],
},
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: 'criteriaDetails',
});
// 현재 점수 유형 감시
const scoreType = form.watch('scoreType');
useEffect(() => {
if (open && criteriaData?.id) {
startTransition(async () => {
try {
const targetData = await getRegEvalCriteriaWithDetails(criteriaData.id);
if (targetData) {
form.reset({
category: targetData.category,
category2: targetData.category2,
item: targetData.item,
classification: targetData.classification,
range: targetData.range,
remarks: targetData.remarks,
scoreType: targetData.scoreType || 'fixed',
variableScoreMin: targetData.variableScoreMin
? Number(targetData.variableScoreMin) : null,
variableScoreMax: targetData.variableScoreMax
? Number(targetData.variableScoreMax) : null,
variableScoreUnit: targetData.variableScoreUnit,
criteriaDetails: targetData.criteriaDetails?.map((detailItem: RegEvalCriteriaDetails) => ({
id: detailItem.id,
detail: detailItem.detail,
scoreEquipShip: detailItem.scoreEquipShip !== null
? Number(detailItem.scoreEquipShip) : null,
scoreEquipMarine: detailItem.scoreEquipMarine !== null
? Number(detailItem.scoreEquipMarine) : null,
scoreBulkShip: detailItem.scoreBulkShip !== null
? Number(detailItem.scoreBulkShip) : null,
scoreBulkMarine: detailItem.scoreBulkMarine !== null
? Number(detailItem.scoreBulkMarine) : null,
})) || [],
})
}
} catch (error) {
console.error('Error in Loading Regular Evaluation Criteria for Updating:', error)
toast.error(error instanceof Error ? error.message : '편집할 데이터를 불러오는 데 실패했습니다.')
}
});
}
}, [open, criteriaData, form]);
const onSubmit = async (data: RegEvalCriteriaFormData) => {
startTransition(async () => {
try {
if (data.scoreType === 'fixed') {
// 고정 점수 검증
if (!data.criteriaDetails || data.criteriaDetails.length === 0) {
toast.error('고정 점수 유형에서는 최소 1개의 평가내용이 필요합니다.');
return;
}
// 평가내용이 비어있는지 확인
const hasEmptyDetail = data.criteriaDetails.some((detail: NonNullable<RegEvalCriteriaFormData['criteriaDetails']>[0]) =>
!detail.detail || (detail.detail && detail.detail.trim() === '')
);
if (hasEmptyDetail) {
toast.error('평가내용을 입력해주세요.');
return;
}
const criteriaDataToUpdate = {
category: data.category,
category2: data.category2,
item: data.item,
classification: data.classification,
range: data.range || null,
remarks: data.remarks || null,
scoreType: data.scoreType,
variableScoreMin: null, // 고정 점수에서는 null
variableScoreMax: null, // 고정 점수에서는 null
variableScoreUnit: null, // 고정 점수에서는 null
};
const detailList = data.criteriaDetails.map((detailItem: NonNullable<RegEvalCriteriaFormData['criteriaDetails']>[0]) => ({
id: detailItem.id,
detail: detailItem.detail?.trim() || '',
scoreEquipShip: detailItem.scoreEquipShip != null ? String(detailItem.scoreEquipShip) : null,
scoreEquipMarine: detailItem.scoreEquipMarine != null ? String(detailItem.scoreEquipMarine) : null,
scoreBulkShip: detailItem.scoreBulkShip != null ? String(detailItem.scoreBulkShip) : null,
scoreBulkMarine: detailItem.scoreBulkMarine != null ? String(detailItem.scoreBulkMarine) : null,
}));
await modifyRegEvalCriteriaFixed(criteriaData.id, criteriaDataToUpdate, detailList);
} else if (data.scoreType === 'variable') {
// 변동 점수 검증
if (data.variableScoreMin == null) {
toast.error('변동 점수 유형에서는 최소 점수가 필수입니다.');
return;
}
if (data.variableScoreMax == null) {
toast.error('변동 점수 유형에서는 최대 점수가 필수입니다.');
return;
}
if (!data.variableScoreUnit || data.variableScoreUnit.trim() === '') {
toast.error('변동 점수 유형에서는 단위가 필수입니다.');
return;
}
if (Number(data.variableScoreMin) >= Number(data.variableScoreMax)) {
toast.error('최소 점수는 최대 점수보다 작아야 합니다.');
return;
}
const criteriaDataToUpdate = {
category: data.category,
category2: data.category2,
item: data.item,
classification: data.classification,
range: data.range || null,
remarks: data.remarks || null,
scoreType: data.scoreType,
variableScoreMin: String(data.variableScoreMin),
variableScoreMax: String(data.variableScoreMax),
variableScoreUnit: data.variableScoreUnit.trim(),
};
await modifyRegEvalCriteriaVariable(criteriaData.id, criteriaDataToUpdate);
} else {
toast.error('올바른 점수 유형을 선택해주세요.');
return;
}
toast.success('평가 기준이 수정되었습니다.');
onSuccess();
onOpenChange(false);
} catch (error) {
console.error('Error in Saving Regular Evaluation Criteria:', error);
toast.error(
error instanceof Error ? error.message : '평가 기준 저장 중 오류가 발생했습니다.'
);
}
})
}
if (!open) {
return null;
}
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="w-[900px] sm:max-w-[900px] flex flex-col" style={{width:900, height: '100vh'}}>
{/* 고정 헤더 */}
<SheetHeader className="flex-shrink-0 pb-4 border-b">
<SheetTitle className="font-bold">
평가 기준 수정
</SheetTitle>
<SheetDescription>
평가 기준의 정보를 수정합니다.
</SheetDescription>
</SheetHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col flex-1 min-h-0">
{/* 스크롤 가능한 메인 콘텐츠 영역 */}
<div className="flex-1 overflow-y-auto py-4 min-h-0">
<div className="space-y-6 pr-4">
<Card>
<CardHeader>
<CardTitle>기본 정보</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="category"
render={({ field }) => (
<FormItem>
<FormLabel>평가부문</FormLabel>
<FormControl>
<Select onValueChange={field.onChange} value={field.value || ""}>
<SelectTrigger>
<SelectValue placeholder="선택" />
</SelectTrigger>
<SelectContent>
{REG_EVAL_CRITERIA_CATEGORY.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="category2"
render={({ field }) => (
<FormItem>
<FormLabel>점수구분</FormLabel>
<FormControl>
<Select onValueChange={field.onChange} value={field.value || ""}>
<SelectTrigger>
<SelectValue placeholder="선택" />
</SelectTrigger>
<SelectContent>
{REG_EVAL_CRITERIA_CATEGORY2.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="item"
render={({ field }) => (
<FormItem>
<FormLabel>항목</FormLabel>
<FormControl>
<Select onValueChange={field.onChange} value={field.value || ""}>
<SelectTrigger>
<SelectValue placeholder="선택" />
</SelectTrigger>
<SelectContent>
{REG_EVAL_CRITERIA_ITEM.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="classification"
render={({ field }) => (
<FormItem>
<FormLabel>구분</FormLabel>
<FormControl>
<Input placeholder="구분을 입력하세요." {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="range"
render={({ field }) => (
<FormItem>
<FormLabel>평가명</FormLabel>
<FormControl>
<Input
placeholder="평가명을 입력하세요." {...field}
value={field.value ?? ''}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="remarks"
render={({ field }) => (
<FormItem>
<FormLabel>비고</FormLabel>
<FormControl>
<Textarea
placeholder="비고를 입력하세요."
{...field}
value={field.value ?? ''}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="scoreType"
render={({ field }) => (
<FormItem>
<FormLabel>점수유형</FormLabel>
<FormControl>
<Select onValueChange={field.onChange} value={field.value}>
<SelectTrigger>
<SelectValue placeholder="선택" />
</SelectTrigger>
<SelectContent>
<SelectItem value="fixed">고정점수</SelectItem>
<SelectItem value="variable">변동점수</SelectItem>
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* 변동점수 설정 */}
{scoreType === 'variable' && (
<>
<Separator />
<div className="space-y-4">
<h4 className="font-medium">변동점수 설정</h4>
<div className="grid grid-cols-3 gap-4">
<FormField
control={form.control}
name="variableScoreMin"
render={({ field }) => (
<FormItem>
<FormLabel>최소점수</FormLabel>
<FormControl>
<Input
type="number"
min="0"
step="1"
placeholder="점수 입력 (0 이상)"
{...field}
value={field.value ?? ''}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="variableScoreMax"
render={({ field }) => (
<FormItem>
<FormLabel>최대점수</FormLabel>
<FormControl>
<Input
type="number"
min="0"
step="1"
placeholder="점수 입력 (0 이상)"
{...field}
value={field.value ?? ''}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="variableScoreUnit"
render={({ field }) => (
<FormItem>
<FormLabel>점수단위</FormLabel>
<FormControl>
<Input
placeholder="예: 감점, 가점"
{...field}
value={field.value ?? ''}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
</>
)}
</CardContent>
</Card>
{scoreType === 'fixed' && (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>평가 옵션</CardTitle>
<CardDescription>
{scoreType === 'fixed'
? '각 평가 옵션별 점수를 설정하세요.'
: '평가 옵션을 설정하세요. (점수는 변동점수 설정을 따릅니다.)'}
</CardDescription>
</div>
<Button
type="button"
variant="outline"
size="sm"
className="ml-4"
onClick={() =>
append({
id: undefined,
detail: '',
scoreEquipShip: null,
scoreEquipMarine: null,
scoreBulkShip: null,
scoreBulkMarine: null,
})
}
disabled={isPending}
>
<Plus className="w-4 h-4 mr-2" />
옵션 추가
</Button>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
{fields.map((field, index) => (
<CriteriaDetailForm
key={field.id}
index={index}
form={form}
onRemove={() => remove(index)}
canRemove={fields.length > 1}
disabled={isPending}
scoreType={scoreType}
/>
))}
</div>
</CardContent>
</Card>
)}
{scoreType === 'variable' && (
<Card>
<CardHeader>
<CardTitle>변동 점수 설정</CardTitle>
<CardDescription>
변동 점수 유형에서는 개별 평가 옵션을 설정할 수 없습니다.
최소/최대 점수와 단위를 설정하여 점수 범위를 정의하세요.
</CardDescription>
</CardHeader>
</Card>
)}
</div>
</div>
{/* 고정 푸터 */}
<div className="flex-shrink-0 flex justify-end gap-2 bg-background">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isPending}
>
취소
</Button>
<Button type="submit" disabled={isPending}>
{isPending ? '저장 중...' : '수정'}
</Button>
</div>
</form>
</Form>
</SheetContent>
</Sheet>
)
}
// ----------------------------------------------------------------------------------------------------
/* EXPORT */
export default RegEvalCriteriaUpdateSheet;
|