현대적 라이브러리 도입 완료
This commit is contained in:
@@ -1,322 +1,227 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useEffect } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
// import { useCommonCode } from "@/hooks/useCommonCode"; // 제거: 상태 공유 문제 해결
|
||||
// import { useMultiLang } from "@/hooks/useMultiLang"; // 무한 루프 방지를 위해 임시 제거
|
||||
|
||||
import { LoadingSpinner } from "@/components/common/LoadingSpinner";
|
||||
import { CodeInfo, CreateCodeRequest, UpdateCodeRequest } from "@/types/commonCode";
|
||||
import { useCodes, useCreateCode, useUpdateCode } from "@/hooks/queries/useCodes";
|
||||
import { createCodeSchema, updateCodeSchema, type CreateCodeData, type UpdateCodeData } from "@/lib/schemas/commonCode";
|
||||
import type { CodeInfo } from "@/types/commonCode";
|
||||
import type { FieldError } from "react-hook-form";
|
||||
|
||||
interface CodeFormModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
categoryCode: string;
|
||||
editingCode?: CodeInfo | null; // 수정할 코드 객체 (null이면 새 코드)
|
||||
codes: CodeInfo[];
|
||||
onCreateCode: (categoryCode: string, data: CreateCodeRequest) => Promise<void>;
|
||||
onUpdateCode: (categoryCode: string, codeValue: string, data: UpdateCodeRequest) => Promise<void>;
|
||||
editingCode?: CodeInfo | null;
|
||||
}
|
||||
|
||||
export function CodeFormModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
categoryCode,
|
||||
editingCode,
|
||||
codes,
|
||||
onCreateCode,
|
||||
onUpdateCode,
|
||||
}: CodeFormModalProps) {
|
||||
// const { getText } = useMultiLang(); // 무한 루프 방지를 위해 임시 제거
|
||||
// const { codes, createCode, updateCode } = useCommonCode(); // 제거: props로 전달받음
|
||||
// 에러 메시지를 안전하게 문자열로 변환하는 헬퍼 함수
|
||||
const getErrorMessage = (error: FieldError | undefined): string => {
|
||||
if (!error) return "";
|
||||
if (typeof error === "string") return error;
|
||||
return error.message || "";
|
||||
};
|
||||
|
||||
// 폼 상태
|
||||
const [formData, setFormData] = useState({
|
||||
codeValue: "",
|
||||
codeName: "",
|
||||
codeNameEng: "",
|
||||
description: "",
|
||||
sortOrder: 1,
|
||||
isActive: true,
|
||||
export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode }: CodeFormModalProps) {
|
||||
const { data: codes = [] } = useCodes(categoryCode);
|
||||
const createCodeMutation = useCreateCode();
|
||||
const updateCodeMutation = useUpdateCode();
|
||||
|
||||
const isEditing = !!editingCode;
|
||||
|
||||
// 폼 스키마 선택 (생성/수정에 따라)
|
||||
const schema = isEditing ? updateCodeSchema : createCodeSchema;
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(schema),
|
||||
mode: "onChange", // 실시간 검증 활성화
|
||||
defaultValues: {
|
||||
codeValue: "",
|
||||
codeName: "",
|
||||
codeNameEng: "",
|
||||
description: "",
|
||||
sortOrder: 1,
|
||||
...(isEditing && { isActive: "Y" as const }),
|
||||
},
|
||||
});
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
|
||||
// 모달 열릴 때 데이터 초기화
|
||||
// 편집 모드일 때 기존 데이터 로드
|
||||
useEffect(() => {
|
||||
console.log("🚀 CodeFormModal useEffect 실행:", {
|
||||
isOpen,
|
||||
editingCode,
|
||||
categoryCode,
|
||||
});
|
||||
|
||||
if (isOpen) {
|
||||
if (editingCode) {
|
||||
// 수정 모드: 전달받은 코드 데이터 사용
|
||||
console.log("🔄 수정 모드 - 기존 데이터 로드:", editingCode);
|
||||
setFormData({
|
||||
codeValue: editingCode.code_value,
|
||||
if (isEditing && editingCode) {
|
||||
// 수정 모드: 기존 데이터 로드 (codeValue는 표시용으로만 설정)
|
||||
form.reset({
|
||||
codeName: editingCode.code_name,
|
||||
codeNameEng: editingCode.code_name_eng || "",
|
||||
description: editingCode.description || "",
|
||||
sortOrder: editingCode.sort_order,
|
||||
isActive: editingCode.is_active === "Y",
|
||||
isActive: editingCode.is_active as "Y" | "N", // 타입 캐스팅
|
||||
});
|
||||
|
||||
// codeValue는 별도로 설정 (표시용)
|
||||
form.setValue("codeValue" as any, editingCode.code_value);
|
||||
} else {
|
||||
// 새 코드 모드: 초기값 설정
|
||||
// 새 코드 모드: 자동 순서 계산
|
||||
const maxSortOrder = codes.length > 0 ? Math.max(...codes.map((c) => c.sort_order)) : 0;
|
||||
console.log("✨ 새 코드 모드 - 초기값 설정, 다음 순서:", maxSortOrder + 1);
|
||||
setFormData({
|
||||
|
||||
form.reset({
|
||||
codeValue: "",
|
||||
codeName: "",
|
||||
codeNameEng: "",
|
||||
description: "",
|
||||
sortOrder: maxSortOrder + 1,
|
||||
isActive: true,
|
||||
});
|
||||
}
|
||||
setErrors({});
|
||||
}
|
||||
}, [isOpen, editingCode, codes, categoryCode]);
|
||||
|
||||
// 실시간 필드 검증
|
||||
const validateField = (fieldName: string, value: string) => {
|
||||
const newErrors = { ...errors };
|
||||
|
||||
switch (fieldName) {
|
||||
case "codeValue":
|
||||
if (!value.trim()) {
|
||||
newErrors.codeValue = "필수 입력 항목입니다.";
|
||||
} else if (value.length > 50) {
|
||||
newErrors.codeValue = "코드값은 50자 이하로 입력해주세요.";
|
||||
} else if (!/^[A-Z0-9_]+$/.test(value)) {
|
||||
newErrors.codeValue = "대문자, 숫자, 언더스코어(_)만 사용 가능합니다.";
|
||||
} else {
|
||||
delete newErrors.codeValue;
|
||||
}
|
||||
break;
|
||||
|
||||
case "codeName":
|
||||
if (!value.trim()) {
|
||||
newErrors.codeName = "필수 입력 항목입니다.";
|
||||
} else if (value.length > 100) {
|
||||
newErrors.codeName = "코드명은 100자 이하로 입력해주세요.";
|
||||
} else {
|
||||
delete newErrors.codeName;
|
||||
}
|
||||
break;
|
||||
|
||||
case "codeNameEng":
|
||||
if (value && value.length > 100) {
|
||||
newErrors.codeNameEng = "영문명은 100자 이하로 입력해주세요.";
|
||||
} else {
|
||||
delete newErrors.codeNameEng;
|
||||
}
|
||||
break;
|
||||
|
||||
case "description":
|
||||
if (value && value.length > 500) {
|
||||
newErrors.description = "설명은 500자 이하로 입력해주세요.";
|
||||
} else {
|
||||
delete newErrors.description;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
};
|
||||
|
||||
// 전체 폼 검증
|
||||
const validateForm = () => {
|
||||
const newErrors: Record<string, string> = {};
|
||||
|
||||
// 필수 필드 검증
|
||||
if (!formData.codeValue.trim()) {
|
||||
newErrors.codeValue = "필수 입력 항목입니다.";
|
||||
} else if (!/^[A-Z0-9_]+$/.test(formData.codeValue)) {
|
||||
newErrors.codeValue = "대문자, 숫자, 언더스코어(_)만 사용 가능합니다.";
|
||||
}
|
||||
|
||||
if (!formData.codeName.trim()) {
|
||||
newErrors.codeName = "필수 입력 항목입니다.";
|
||||
}
|
||||
|
||||
// 중복 검사 (신규 생성 시)
|
||||
if (!editingCode) {
|
||||
const existingCode = codes.find((c) => c.code_value === formData.codeValue);
|
||||
if (existingCode) {
|
||||
newErrors.codeValue = "이미 존재하는 코드값입니다.";
|
||||
}
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
// 폼 제출 핸들러
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!validateForm()) return;
|
||||
|
||||
setLoading(true);
|
||||
}, [isOpen, isEditing, editingCode, codes, form]);
|
||||
|
||||
const handleSubmit = form.handleSubmit(async (data) => {
|
||||
try {
|
||||
if (editingCode) {
|
||||
if (isEditing && editingCode) {
|
||||
// 수정
|
||||
await onUpdateCode(categoryCode, editingCode.code_value, {
|
||||
codeName: formData.codeName,
|
||||
codeNameEng: formData.codeNameEng,
|
||||
description: formData.description,
|
||||
sortOrder: formData.sortOrder,
|
||||
isActive: formData.isActive,
|
||||
await updateCodeMutation.mutateAsync({
|
||||
categoryCode,
|
||||
codeValue: editingCode.code_value,
|
||||
data: data as UpdateCodeData,
|
||||
});
|
||||
} else {
|
||||
// 생성
|
||||
await onCreateCode(categoryCode, {
|
||||
codeValue: formData.codeValue,
|
||||
codeName: formData.codeName,
|
||||
codeNameEng: formData.codeNameEng,
|
||||
description: formData.description,
|
||||
sortOrder: formData.sortOrder,
|
||||
await createCodeMutation.mutateAsync({
|
||||
categoryCode,
|
||||
data: data as CreateCodeData,
|
||||
});
|
||||
}
|
||||
|
||||
onClose();
|
||||
form.reset();
|
||||
} catch (error) {
|
||||
console.error("코드 저장 오류:", error);
|
||||
// 에러 처리는 useCommonCode 훅에서 처리됨
|
||||
} finally {
|
||||
setLoading(false);
|
||||
console.error("코드 저장 실패:", error);
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
// 입력값 변경 핸들러 (실시간 검증 포함)
|
||||
const handleChange = (field: string, value: string | number | boolean) => {
|
||||
setFormData((prev) => ({ ...prev, [field]: value }));
|
||||
|
||||
// 실시간 검증 (문자열 필드만)
|
||||
if (typeof value === "string") {
|
||||
validateField(field, value);
|
||||
} else {
|
||||
// 에러 제거 (숫자, 불린 필드)
|
||||
if (errors[field]) {
|
||||
setErrors((prev) => ({ ...prev, [field]: "" }));
|
||||
}
|
||||
}
|
||||
};
|
||||
const isLoading = createCodeMutation.isPending || updateCodeMutation.isPending;
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingCode ? "코드 수정" : "새 코드"}</DialogTitle>
|
||||
<DialogTitle>{isEditing ? "코드 수정" : "새 코드"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{/* 코드값 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="codeValue">{"코드값"} *</Label>
|
||||
<Label htmlFor="codeValue">코드값 *</Label>
|
||||
<Input
|
||||
id="codeValue"
|
||||
value={formData.codeValue}
|
||||
onChange={(e) => handleChange("codeValue", e.target.value.toUpperCase())}
|
||||
disabled={!!editingCode || loading}
|
||||
placeholder={"코드값을 입력하세요 (예: USER_ACTIVE)"}
|
||||
className={errors.codeValue ? "border-red-500" : ""}
|
||||
{...form.register("codeValue")}
|
||||
disabled={isLoading || isEditing} // 수정 시에는 비활성화
|
||||
placeholder="코드값을 입력하세요"
|
||||
className={(form.formState.errors as any)?.codeValue ? "border-red-500" : ""}
|
||||
/>
|
||||
{errors.codeValue && <p className="text-sm text-red-600">{errors.codeValue}</p>}
|
||||
{(form.formState.errors as any)?.codeValue && (
|
||||
<p className="text-sm text-red-600">{getErrorMessage((form.formState.errors as any)?.codeValue)}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 코드명 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="codeName">{"코드명"} *</Label>
|
||||
<Label htmlFor="codeName">코드명 *</Label>
|
||||
<Input
|
||||
id="codeName"
|
||||
value={formData.codeName}
|
||||
onChange={(e) => handleChange("codeName", e.target.value)}
|
||||
disabled={loading}
|
||||
placeholder={"코드명을 입력하세요"}
|
||||
className={errors.codeName ? "border-red-500" : ""}
|
||||
{...form.register("codeName")}
|
||||
disabled={isLoading}
|
||||
placeholder="코드명을 입력하세요"
|
||||
className={form.formState.errors.codeName ? "border-red-500" : ""}
|
||||
/>
|
||||
{errors.codeName && <p className="text-sm text-red-600">{errors.codeName}</p>}
|
||||
{form.formState.errors.codeName && (
|
||||
<p className="text-sm text-red-600">{getErrorMessage(form.formState.errors.codeName)}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 영문명 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="codeNameEng">{"코드 영문명"}</Label>
|
||||
<Label htmlFor="codeNameEng">코드 영문명 *</Label>
|
||||
<Input
|
||||
id="codeNameEng"
|
||||
value={formData.codeNameEng}
|
||||
onChange={(e) => handleChange("codeNameEng", e.target.value)}
|
||||
disabled={loading}
|
||||
placeholder={"코드 영문명을 입력하세요"}
|
||||
className={errors.codeNameEng ? "border-red-500" : ""}
|
||||
{...form.register("codeNameEng")}
|
||||
disabled={isLoading}
|
||||
placeholder="코드 영문명을 입력하세요"
|
||||
className={form.formState.errors.codeNameEng ? "border-red-500" : ""}
|
||||
/>
|
||||
{errors.codeNameEng && <p className="text-sm text-red-600">{errors.codeNameEng}</p>}
|
||||
{form.formState.errors.codeNameEng && (
|
||||
<p className="text-sm text-red-600">{getErrorMessage(form.formState.errors.codeNameEng)}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 설명 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">{"설명"}</Label>
|
||||
<Label htmlFor="description">설명 *</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
value={formData.description}
|
||||
onChange={(e) => handleChange("description", e.target.value)}
|
||||
disabled={loading}
|
||||
placeholder={"설명을 입력하세요"}
|
||||
{...form.register("description")}
|
||||
disabled={isLoading}
|
||||
placeholder="설명을 입력하세요"
|
||||
rows={3}
|
||||
className={errors.description ? "border-red-500" : ""}
|
||||
className={form.formState.errors.description ? "border-red-500" : ""}
|
||||
/>
|
||||
{errors.description && <p className="text-sm text-red-600">{errors.description}</p>}
|
||||
{form.formState.errors.description && (
|
||||
<p className="text-sm text-red-600">{getErrorMessage(form.formState.errors.description)}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 정렬 순서 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="sortOrder">{"정렬 순서"}</Label>
|
||||
<Label htmlFor="sortOrder">정렬 순서</Label>
|
||||
<Input
|
||||
id="sortOrder"
|
||||
type="number"
|
||||
value={formData.sortOrder}
|
||||
onChange={(e) => handleChange("sortOrder", parseInt(e.target.value) || 0)}
|
||||
disabled={loading}
|
||||
min={0}
|
||||
{...form.register("sortOrder", { valueAsNumber: true })}
|
||||
disabled={isLoading}
|
||||
min={1}
|
||||
className={form.formState.errors.sortOrder ? "border-red-500" : ""}
|
||||
/>
|
||||
{form.formState.errors.sortOrder && (
|
||||
<p className="text-sm text-red-600">{getErrorMessage(form.formState.errors.sortOrder)}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 활성 상태 (수정 시에만) */}
|
||||
{editingCode && (
|
||||
{isEditing && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="isActive"
|
||||
checked={formData.isActive}
|
||||
onCheckedChange={(checked) => handleChange("isActive", checked)}
|
||||
disabled={loading}
|
||||
checked={form.watch("isActive") === "Y"}
|
||||
onCheckedChange={(checked) => form.setValue("isActive", checked ? "Y" : "N")}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<Label htmlFor="isActive">{"활성"}</Label>
|
||||
<Label htmlFor="isActive">{form.watch("isActive") === "Y" ? "활성" : "비활성"}</Label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 버튼 */}
|
||||
<div className="flex justify-end space-x-2 pt-4">
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={loading}>
|
||||
{"취소"}
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading || Object.keys(errors).length > 0}>
|
||||
{loading ? (
|
||||
<Button type="submit" disabled={isLoading || !form.formState.isValid}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<LoadingSpinner size="sm" className="mr-2" />
|
||||
{editingCode ? "수정 중..." : "등록 중..."}
|
||||
{isEditing ? "수정 중..." : "저장 중..."}
|
||||
</>
|
||||
) : editingCode ? (
|
||||
) : isEditing ? (
|
||||
"코드 수정"
|
||||
) : (
|
||||
"코드 등록"
|
||||
"코드 저장"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user