summaryrefslogtreecommitdiff
path: root/lib/evaluation-criteria/table/reg-eval-criteria-form-sheet.tsx
diff options
context:
space:
mode:
Diffstat (limited to 'lib/evaluation-criteria/table/reg-eval-criteria-form-sheet.tsx')
-rw-r--r--lib/evaluation-criteria/table/reg-eval-criteria-form-sheet.tsx586
1 files changed, 586 insertions, 0 deletions
diff --git a/lib/evaluation-criteria/table/reg-eval-criteria-form-sheet.tsx b/lib/evaluation-criteria/table/reg-eval-criteria-form-sheet.tsx
new file mode 100644
index 00000000..d33e7d29
--- /dev/null
+++ b/lib/evaluation-criteria/table/reg-eval-criteria-form-sheet.tsx
@@ -0,0 +1,586 @@
+/* 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 {
+ createRegEvalCriteriaWithDetails,
+ getRegEvalCriteriaWithDetails,
+ modifyRegEvalCriteriaWithDetails,
+} 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 RegEvalCriteriaView,
+} from '@/db/schema';
+import { ScrollArea } from '@/components/ui/scroll-area';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from '@/components/ui/select';
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet';
+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, '평가부문은 필수 항목입니다.'),
+ scoreCategory: z.string().min(1, '점수구분은 필수 항목입니다.'),
+ item: z.string().min(1, '항목은 필수 항목입니다.'),
+ classification: z.string().min(1, '구분은 필수 항목입니다.'),
+ range: z.string().nullable().optional(),
+ remarks: z.string().nullable().optional(),
+ criteriaDetails: z.array(
+ z.object({
+ id: z.number().optional(),
+ detail: z.string().min(1, '평가내용은 필수 항목입니다.'),
+ scoreEquipShip: z.coerce.number().nullable().optional(),
+ scoreEquipMarine: z.coerce.number().nullable().optional(),
+ scoreBulkShip: z.coerce.number().nullable().optional(),
+ scoreBulkMarine: z.coerce.number().nullable().optional(),
+ })
+ ).min(1, '최소 1개의 평가 내용이 필요합니다.'),
+});
+type RegEvalCriteriaFormData = z.infer<typeof regEvalCriteriaFormSchema>;
+interface CriteriaDetailFormProps {
+ index: number
+ form: any
+ onRemove: () => void
+ canRemove: boolean
+ disabled?: boolean
+}
+interface RegEvalCriteriaFormSheetProps {
+ open: boolean,
+ onOpenChange: (open: boolean) => void,
+ criteriaViewData: RegEvalCriteriaView | null,
+ onSuccess: () => void,
+};
+
+// ----------------------------------------------------------------------------------------------------
+
+/* CRITERIA DETAIL FORM COPONENT */
+function CriteriaDetailForm({
+ index,
+ form,
+ onRemove,
+ canRemove,
+ disabled = false,
+}: CriteriaDetailFormProps) {
+
+ return (
+ <Card>
+ <CardHeader>
+ <div className="flex items-center justify-between">
+ <CardTitle className="text-lg">Detail Item - {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>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`criteriaDetails.${index}.scoreEquipShip`}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>배점/기자재/조선</FormLabel>
+ <FormControl>
+ <Input
+ type="number"
+ step="0.1"
+ placeholder="배점/기자재/조선"
+ {...field}
+ value={field.value ?? 0}
+ disabled={disabled}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`criteriaDetails.${index}.scoreEquipMarine`}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>배점/기자재/해양</FormLabel>
+ <FormControl>
+ <Input
+ type="number"
+ step="0.1"
+ placeholder="배점/기자재/해양"
+ {...field}
+ value={field.value ?? 0}
+ disabled={disabled}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`criteriaDetails.${index}.scoreBulkShip`}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>배점/벌크/조선</FormLabel>
+ <FormControl>
+ <Input
+ type="number"
+ step="0.1"
+ placeholder="배점/벌크/조선"
+ {...field}
+ value={field.value ?? 0}
+ disabled={disabled}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`criteriaDetails.${index}.scoreBulkMarine`}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>배점/벌크/해양</FormLabel>
+ <FormControl>
+ <Input
+ type="number"
+ step="0.1"
+ placeholder="배점/벌크/해양"
+ {...field}
+ value={field.value ?? 0}
+ disabled={disabled}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </CardContent>
+ </Card>
+ )
+}
+
+/* CRITERIA FORM SHEET COPONENT */
+function RegEvalCriteriaFormSheet({
+ open,
+ onOpenChange,
+ criteriaViewData,
+ onSuccess,
+}: RegEvalCriteriaFormSheetProps) {
+ const [isPending, startTransition] = useTransition();
+ const isUpdateMode = !!criteriaViewData;
+
+ const form = useForm<RegEvalCriteriaFormData>({
+ resolver: zodResolver(regEvalCriteriaFormSchema),
+ defaultValues: {
+ category: '',
+ scoreCategory: '',
+ item: '',
+ classification: '',
+ range: '',
+ remarks: '',
+ criteriaDetails: [
+ {
+ id: undefined,
+ detail: '',
+ scoreEquipShip: null,
+ scoreEquipMarine: null,
+ scoreBulkShip: null,
+ scoreBulkMarine: null,
+ },
+ ],
+ },
+ });
+
+ const { fields, append, remove } = useFieldArray({
+ control: form.control,
+ name: 'criteriaDetails',
+ });
+
+ useEffect(() => {
+ if (open && isUpdateMode && criteriaViewData) {
+ startTransition(async () => {
+ try {
+ const targetData = await getRegEvalCriteriaWithDetails(criteriaViewData.criteriaId!);
+ if (targetData) {
+ form.reset({
+ category: targetData.category,
+ scoreCategory: targetData.scoreCategory,
+ item: targetData.item,
+ classification: targetData.classification,
+ range: targetData.range,
+ remarks: targetData.remarks,
+ 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 : '편집할 데이터를 불러오는 데 실패했습니다.')
+ }
+ })
+ } else if (open && !isUpdateMode) {
+ form.reset({
+ category: '',
+ scoreCategory: '',
+ item: '',
+ classification: '',
+ range: '',
+ remarks: '',
+ criteriaDetails: [
+ {
+ id: undefined,
+ detail: '',
+ scoreEquipShip: null,
+ scoreEquipMarine: null,
+ scoreBulkShip: null,
+ scoreBulkMarine: null,
+ },
+ ],
+ })
+ }
+ }, [open, isUpdateMode, criteriaViewData, form]);
+
+ const onSubmit = async (data: RegEvalCriteriaFormData) => {
+ startTransition(async () => {
+ try {
+ const criteriaData = {
+ category: data.category,
+ scoreCategory: data.scoreCategory,
+ item: data.item,
+ classification: data.classification,
+ range: data.range,
+ remarks: data.remarks,
+ };
+ const detailList = data.criteriaDetails.map((detailItem) => ({
+ id: detailItem.id,
+ detail: detailItem.detail,
+ 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,
+ }));
+
+ if (isUpdateMode && criteriaViewData) {
+ await modifyRegEvalCriteriaWithDetails(criteriaViewData.criteriaId!, criteriaData, detailList);
+ toast.success('평가 기준표가 수정되었습니다.');
+ } else {
+ await createRegEvalCriteriaWithDetails(criteriaData, detailList);
+ 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] overflow-y-auto">
+ <SheetHeader className="mb-4">
+ <SheetTitle className="font-bold">
+ {isUpdateMode ? '협력업체 평가 기준표 수정' : '새 협력업체 평가 기준표 생성'}
+ </SheetTitle>
+ <SheetDescription>
+ {isUpdateMode ? '협력업체 평가 기준표의 정보를 수정합니다.' : '새로운 협력업체 평가 기준표를 생성합니다.'}
+ </SheetDescription>
+ </SheetHeader>
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
+ <ScrollArea className="h-[calc(100vh-200px)] pr-4">
+ <div className="space-y-6">
+ <Card>
+ <CardHeader>
+ <CardTitle>Criterion Info</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-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="scoreCategory"
+ 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>
+ )}
+ />
+ <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>
+ )}
+ />
+ <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>
+ )}
+ />
+ </CardContent>
+ </Card>
+ <Card>
+ <CardHeader>
+ <div className="flex items-center justify-between">
+ <div>
+ <CardTitle>Evaluation Criteria Item</CardTitle>
+ <CardDescription>
+ Set Evaluation Criteria Item.
+ </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" />
+ New Item
+ </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}
+ />
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ </ScrollArea>
+ <div className="flex justify-end gap-2 pt-4 border-t">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={isPending}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={isPending}>
+ {isPending
+ ? 'Saving...'
+ : isUpdateMode
+ ? 'Modify'
+ : 'Create'}
+ </Button>
+ </div>
+ </form>
+ </Form>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+// ----------------------------------------------------------------------------------------------------
+
+/* EXPORT */
+export default RegEvalCriteriaFormSheet; \ No newline at end of file