공통코드 계층구조 구현

This commit is contained in:
kjs
2025-12-23 09:31:18 +09:00
parent b85b888007
commit 5f406fbe88
32 changed files with 3673 additions and 478 deletions

View File

@@ -1,6 +1,6 @@
"use client";
import { useState } from "react";
import { useState, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
@@ -45,15 +45,124 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
const reorderCodesMutation = useReorderCodes();
// 드래그앤드롭을 위해 필터링된 코드 목록 사용
const { filteredItems: filteredCodes } = useSearchAndFilter(codes, {
const { filteredItems: filteredCodesRaw } = useSearchAndFilter(codes, {
searchFields: ["code_name", "code_value"],
});
// 계층 구조로 정렬 (부모 → 자식 순서)
const filteredCodes = useMemo(() => {
if (!filteredCodesRaw || filteredCodesRaw.length === 0) return [];
// 코드를 계층 순서로 정렬하는 함수
const sortHierarchically = (codes: CodeInfo[]): CodeInfo[] => {
const result: CodeInfo[] = [];
const codeMap = new Map<string, CodeInfo>();
const childrenMap = new Map<string, CodeInfo[]>();
// 코드 맵 생성
codes.forEach((code) => {
const codeValue = code.codeValue || code.code_value || "";
const parentValue = code.parentCodeValue || code.parent_code_value;
codeMap.set(codeValue, code);
if (parentValue) {
if (!childrenMap.has(parentValue)) {
childrenMap.set(parentValue, []);
}
childrenMap.get(parentValue)!.push(code);
}
});
// 재귀적으로 트리 구조 순회
const traverse = (parentValue: string | null, depth: number) => {
const children = parentValue
? childrenMap.get(parentValue) || []
: codes.filter((c) => !c.parentCodeValue && !c.parent_code_value);
// 정렬 순서로 정렬
children
.sort((a, b) => (a.sortOrder || a.sort_order || 0) - (b.sortOrder || b.sort_order || 0))
.forEach((code) => {
result.push(code);
const codeValue = code.codeValue || code.code_value || "";
traverse(codeValue, depth + 1);
});
};
traverse(null, 1);
// 트리에 포함되지 않은 코드들도 추가 (orphan 코드)
codes.forEach((code) => {
if (!result.includes(code)) {
result.push(code);
}
});
return result;
};
return sortHierarchically(filteredCodesRaw);
}, [filteredCodesRaw]);
// 모달 상태
const [showFormModal, setShowFormModal] = useState(false);
const [editingCode, setEditingCode] = useState<CodeInfo | null>(null);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [deletingCode, setDeletingCode] = useState<CodeInfo | null>(null);
const [defaultParentCode, setDefaultParentCode] = useState<string | undefined>(undefined);
// 트리 접기/펼치기 상태 (코드값 Set)
const [collapsedCodes, setCollapsedCodes] = useState<Set<string>>(new Set());
// 자식 정보 계산
const childrenMap = useMemo(() => {
const map = new Map<string, CodeInfo[]>();
codes.forEach((code) => {
const parentValue = code.parentCodeValue || code.parent_code_value;
if (parentValue) {
if (!map.has(parentValue)) {
map.set(parentValue, []);
}
map.get(parentValue)!.push(code);
}
});
return map;
}, [codes]);
// 접기/펼치기 토글
const toggleExpand = (codeValue: string) => {
setCollapsedCodes((prev) => {
const newSet = new Set(prev);
if (newSet.has(codeValue)) {
newSet.delete(codeValue);
} else {
newSet.add(codeValue);
}
return newSet;
});
};
// 특정 코드가 표시되어야 하는지 확인 (부모가 접혀있으면 숨김)
const isCodeVisible = (code: CodeInfo): boolean => {
const parentValue = code.parentCodeValue || code.parent_code_value;
if (!parentValue) return true; // 최상위 코드는 항상 표시
// 부모가 접혀있으면 숨김
if (collapsedCodes.has(parentValue)) return false;
// 부모의 부모도 확인 (재귀적으로)
const parentCode = codes.find((c) => (c.codeValue || c.code_value) === parentValue);
if (parentCode) {
return isCodeVisible(parentCode);
}
return true;
};
// 표시할 코드 목록 (접힌 상태 반영)
const visibleCodes = useMemo(() => {
return filteredCodes.filter(isCodeVisible);
}, [filteredCodes, collapsedCodes, codes]);
// 드래그 앤 드롭 훅 사용
const dragAndDrop = useDragAndDrop<CodeInfo>({
@@ -73,12 +182,21 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
// 새 코드 생성
const handleNewCode = () => {
setEditingCode(null);
setDefaultParentCode(undefined);
setShowFormModal(true);
};
// 코드 수정
const handleEditCode = (code: CodeInfo) => {
setEditingCode(code);
setDefaultParentCode(undefined);
setShowFormModal(true);
};
// 하위 코드 추가
const handleAddChild = (parentCode: CodeInfo) => {
setEditingCode(null);
setDefaultParentCode(parentCode.codeValue || parentCode.code_value || "");
setShowFormModal(true);
};
@@ -110,7 +228,7 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
if (!categoryCode) {
return (
<div className="flex h-96 items-center justify-center">
<p className="text-sm text-muted-foreground"> </p>
<p className="text-muted-foreground text-sm"> </p>
</div>
);
}
@@ -119,7 +237,7 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
return (
<div className="flex h-96 items-center justify-center">
<div className="text-center">
<p className="text-sm font-semibold text-destructive"> .</p>
<p className="text-destructive text-sm font-semibold"> .</p>
<Button variant="outline" onClick={() => window.location.reload()} className="mt-4 h-10 text-sm font-medium">
</Button>
@@ -135,7 +253,7 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
{/* 검색 + 버튼 */}
<div className="flex items-center gap-2">
<div className="relative w-full sm:w-[300px]">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Search className="text-muted-foreground absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2" />
<Input
placeholder="코드 검색..."
value={searchTerm}
@@ -156,9 +274,9 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
id="activeOnlyCodes"
checked={showActiveOnly}
onChange={(e) => setShowActiveOnly(e.target.checked)}
className="h-4 w-4 rounded border-input"
className="border-input h-4 w-4 rounded"
/>
<label htmlFor="activeOnlyCodes" className="text-sm text-muted-foreground">
<label htmlFor="activeOnlyCodes" className="text-muted-foreground text-sm">
</label>
</div>
@@ -170,9 +288,9 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
<div className="flex h-32 items-center justify-center">
<LoadingSpinner />
</div>
) : filteredCodes.length === 0 ? (
) : visibleCodes.length === 0 ? (
<div className="flex h-32 items-center justify-center">
<p className="text-sm text-muted-foreground">
<p className="text-muted-foreground text-sm">
{codes.length === 0 ? "코드가 없습니다." : "검색 결과가 없습니다."}
</p>
</div>
@@ -180,23 +298,35 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
<>
<DndContext {...dragAndDrop.dndContextProps}>
<SortableContext
items={filteredCodes.map((code) => code.codeValue || code.code_value)}
items={visibleCodes.map((code) => code.codeValue || code.code_value)}
strategy={verticalListSortingStrategy}
>
{filteredCodes.map((code, index) => (
<SortableCodeItem
key={`${code.codeValue || code.code_value}-${index}`}
code={code}
categoryCode={categoryCode}
onEdit={() => handleEditCode(code)}
onDelete={() => handleDeleteCode(code)}
/>
))}
{visibleCodes.map((code, index) => {
const codeValue = code.codeValue || code.code_value || "";
const children = childrenMap.get(codeValue) || [];
const hasChildren = children.length > 0;
const isExpanded = !collapsedCodes.has(codeValue);
return (
<SortableCodeItem
key={`${codeValue}-${index}`}
code={code}
categoryCode={categoryCode}
onEdit={() => handleEditCode(code)}
onDelete={() => handleDeleteCode(code)}
onAddChild={() => handleAddChild(code)}
hasChildren={hasChildren}
childCount={children.length}
isExpanded={isExpanded}
onToggleExpand={() => toggleExpand(codeValue)}
/>
);
})}
</SortableContext>
<DragOverlay dropAnimation={null}>
{dragAndDrop.activeItem ? (
<div className="cursor-grabbing rounded-lg border bg-card p-4 shadow-lg">
<div className="bg-card cursor-grabbing rounded-lg border p-4 shadow-lg">
{(() => {
const activeCode = dragAndDrop.activeItem;
if (!activeCode) return null;
@@ -204,24 +334,20 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
<div className="flex items-start justify-between">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h4 className="text-sm font-semibold">
{activeCode.codeName || activeCode.code_name}
</h4>
<h4 className="text-sm font-semibold">{activeCode.codeName || activeCode.code_name}</h4>
<Badge
variant={
activeCode.isActive === "Y" || activeCode.is_active === "Y"
? "default"
: "secondary"
activeCode.isActive === "Y" || activeCode.is_active === "Y" ? "default" : "secondary"
}
>
{activeCode.isActive === "Y" || activeCode.is_active === "Y" ? "활성" : "비활성"}
</Badge>
</div>
<p className="mt-1 text-xs text-muted-foreground">
<p className="text-muted-foreground mt-1 text-xs">
{activeCode.codeValue || activeCode.code_value}
</p>
{activeCode.description && (
<p className="mt-1 text-xs text-muted-foreground">{activeCode.description}</p>
<p className="text-muted-foreground mt-1 text-xs">{activeCode.description}</p>
)}
</div>
</div>
@@ -236,13 +362,13 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
{isFetchingNextPage && (
<div className="flex items-center justify-center py-4">
<LoadingSpinner size="sm" />
<span className="ml-2 text-sm text-muted-foreground"> ...</span>
<span className="text-muted-foreground ml-2 text-sm"> ...</span>
</div>
)}
{/* 모든 코드 로드 완료 메시지 */}
{!hasNextPage && codes.length > 0 && (
<div className="py-4 text-center text-sm text-muted-foreground"> .</div>
<div className="text-muted-foreground py-4 text-center text-sm"> .</div>
)}
</>
)}
@@ -255,10 +381,12 @@ export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
onClose={() => {
setShowFormModal(false);
setEditingCode(null);
setDefaultParentCode(undefined);
}}
categoryCode={categoryCode}
editingCode={editingCode}
codes={codes}
defaultParentCode={defaultParentCode}
/>
)}

View File

@@ -24,6 +24,7 @@ interface CodeFormModalProps {
categoryCode: string;
editingCode?: CodeInfo | null;
codes: CodeInfo[];
defaultParentCode?: string; // 하위 코드 추가 시 기본 부모 코드
}
// 에러 메시지를 안전하게 문자열로 변환하는 헬퍼 함수
@@ -33,28 +34,32 @@ const getErrorMessage = (error: FieldError | undefined): string => {
return error.message || "";
};
export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, codes }: CodeFormModalProps) {
// 코드값 자동 생성 함수 (UUID 기반 짧은 코드)
const generateCodeValue = (): string => {
const timestamp = Date.now().toString(36).toUpperCase();
const random = Math.random().toString(36).substring(2, 6).toUpperCase();
return `${timestamp}${random}`;
};
export function CodeFormModal({
isOpen,
onClose,
categoryCode,
editingCode,
codes,
defaultParentCode,
}: CodeFormModalProps) {
const createCodeMutation = useCreateCode();
const updateCodeMutation = useUpdateCode();
const isEditing = !!editingCode;
// 검증 상태 관리
// 검증 상태 관리 (코드명만 중복 검사)
const [validationStates, setValidationStates] = useState({
codeValue: { enabled: false, value: "" },
codeName: { enabled: false, value: "" },
codeNameEng: { enabled: false, value: "" },
});
// 중복 검사 훅들
const codeValueCheck = useCheckCodeDuplicate(
categoryCode,
"codeValue",
validationStates.codeValue.value,
isEditing ? editingCode?.codeValue || editingCode?.code_value : undefined,
validationStates.codeValue.enabled,
);
// 코드명 중복 검사
const codeNameCheck = useCheckCodeDuplicate(
categoryCode,
"codeName",
@@ -63,22 +68,11 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code
validationStates.codeName.enabled,
);
const codeNameEngCheck = useCheckCodeDuplicate(
categoryCode,
"codeNameEng",
validationStates.codeNameEng.value,
isEditing ? editingCode?.codeValue || editingCode?.code_value : undefined,
validationStates.codeNameEng.enabled,
);
// 중복 검사 결과 확인
const hasDuplicateErrors =
(codeValueCheck.data?.isDuplicate && validationStates.codeValue.enabled) ||
(codeNameCheck.data?.isDuplicate && validationStates.codeName.enabled) ||
(codeNameEngCheck.data?.isDuplicate && validationStates.codeNameEng.enabled);
const hasDuplicateErrors = codeNameCheck.data?.isDuplicate && validationStates.codeName.enabled;
// 중복 검사 로딩 중인지 확인
const isDuplicateChecking = codeValueCheck.isLoading || codeNameCheck.isLoading || codeNameEngCheck.isLoading;
const isDuplicateChecking = codeNameCheck.isLoading;
// 폼 스키마 선택 (생성/수정에 따라)
const schema = isEditing ? updateCodeSchema : createCodeSchema;
@@ -92,6 +86,7 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code
codeNameEng: "",
description: "",
sortOrder: 1,
parentCodeValue: "" as string | undefined,
...(isEditing && { isActive: "Y" as const }),
},
});
@@ -101,30 +96,40 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code
if (isOpen) {
if (isEditing && editingCode) {
// 수정 모드: 기존 데이터 로드 (codeValue는 표시용으로만 설정)
const parentValue = editingCode.parentCodeValue || editingCode.parent_code_value || "";
form.reset({
codeName: editingCode.codeName || editingCode.code_name,
codeNameEng: editingCode.codeNameEng || editingCode.code_name_eng || "",
description: editingCode.description || "",
sortOrder: editingCode.sortOrder || editingCode.sort_order,
isActive: (editingCode.isActive || editingCode.is_active) as "Y" | "N", // 타입 캐스팅
isActive: (editingCode.isActive || editingCode.is_active) as "Y" | "N",
parentCodeValue: parentValue,
});
// codeValue는 별도로 설정 (표시용)
form.setValue("codeValue" as any, editingCode.codeValue || editingCode.code_value);
} else {
// 새 코드 모드: 자동 순서 계산
const maxSortOrder = codes.length > 0 ? Math.max(...codes.map((c) => c.sortOrder || c.sort_order)) : 0;
const maxSortOrder = codes.length > 0 ? Math.max(...codes.map((c) => c.sortOrder || c.sort_order || 0)) : 0;
// 기본 부모 코드가 있으면 설정 (하위 코드 추가 시)
const parentValue = defaultParentCode || "";
// 코드값 자동 생성
const autoCodeValue = generateCodeValue();
form.reset({
codeValue: "",
codeValue: autoCodeValue,
codeName: "",
codeNameEng: "",
description: "",
sortOrder: maxSortOrder + 1,
parentCodeValue: parentValue,
});
}
}
}, [isOpen, isEditing, editingCode, codes]);
}, [isOpen, isEditing, editingCode, codes, defaultParentCode]);
const handleSubmit = form.handleSubmit(async (data) => {
try {
@@ -132,7 +137,7 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code
// 수정
await updateCodeMutation.mutateAsync({
categoryCode,
codeValue: editingCode.codeValue || editingCode.code_value,
codeValue: editingCode.codeValue || editingCode.code_value || "",
data: data as UpdateCodeData,
});
} else {
@@ -156,50 +161,38 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95vw] sm:max-w-[500px]">
<DialogHeader>
<DialogTitle className="text-base sm:text-lg">{isEditing ? "코드 수정" : "새 코드"}</DialogTitle>
<DialogTitle className="text-base sm:text-lg">
{isEditing ? "코드 수정" : defaultParentCode ? "하위 코드 추가" : "새 코드"}
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-3 sm:space-y-4">
{/* 코드값 */}
<div className="space-y-2">
<Label htmlFor="codeValue" className="text-xs sm:text-sm"> *</Label>
<Input
id="codeValue"
{...form.register("codeValue")}
disabled={isLoading || isEditing}
placeholder="코드값을 입력하세요"
className={(form.formState.errors as any)?.codeValue ? "h-8 text-xs sm:h-10 sm:text-sm border-destructive" : "h-8 text-xs sm:h-10 sm:text-sm"}
onBlur={(e) => {
const value = e.target.value.trim();
if (value && !isEditing) {
setValidationStates((prev) => ({
...prev,
codeValue: { enabled: true, value },
}));
}
}}
/>
{(form.formState.errors as any)?.codeValue && (
<p className="text-[10px] sm:text-xs text-destructive">{getErrorMessage((form.formState.errors as any)?.codeValue)}</p>
)}
{!isEditing && !(form.formState.errors as any)?.codeValue && (
<ValidationMessage
message={codeValueCheck.data?.message}
isValid={!codeValueCheck.data?.isDuplicate}
isLoading={codeValueCheck.isLoading}
/>
)}
</div>
{/* 코드값 (자동 생성, 수정 시에만 표시) */}
{isEditing && (
<div className="space-y-2">
<Label className="text-xs sm:text-sm"></Label>
<div className="bg-muted h-8 rounded-md border px-3 py-1.5 text-xs sm:h-10 sm:py-2 sm:text-sm">
{form.watch("codeValue")}
</div>
<p className="text-muted-foreground text-[10px] sm:text-xs"> </p>
</div>
)}
{/* 코드명 */}
<div className="space-y-2">
<Label htmlFor="codeName" className="text-xs sm:text-sm"> *</Label>
<Label htmlFor="codeName" className="text-xs sm:text-sm">
*
</Label>
<Input
id="codeName"
{...form.register("codeName")}
disabled={isLoading}
placeholder="코드명을 입력하세요"
className={form.formState.errors.codeName ? "h-8 text-xs sm:h-10 sm:text-sm border-destructive" : "h-8 text-xs sm:h-10 sm:text-sm"}
className={
form.formState.errors.codeName
? "border-destructive h-8 text-xs sm:h-10 sm:text-sm"
: "h-8 text-xs sm:h-10 sm:text-sm"
}
onBlur={(e) => {
const value = e.target.value.trim();
if (value) {
@@ -211,7 +204,9 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code
}}
/>
{form.formState.errors.codeName && (
<p className="text-[10px] sm:text-xs text-destructive">{getErrorMessage(form.formState.errors.codeName)}</p>
<p className="text-destructive text-[10px] sm:text-xs">
{getErrorMessage(form.formState.errors.codeName)}
</p>
)}
{!form.formState.errors.codeName && (
<ValidationMessage
@@ -222,66 +217,72 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code
)}
</div>
{/* 영문명 */}
{/* 영문명 (선택) */}
<div className="space-y-2">
<Label htmlFor="codeNameEng" className="text-xs sm:text-sm"> *</Label>
<Label htmlFor="codeNameEng" className="text-xs sm:text-sm">
</Label>
<Input
id="codeNameEng"
{...form.register("codeNameEng")}
disabled={isLoading}
placeholder="코드 영문명을 입력하세요"
className={form.formState.errors.codeNameEng ? "h-8 text-xs sm:h-10 sm:text-sm border-destructive" : "h-8 text-xs sm:h-10 sm:text-sm"}
onBlur={(e) => {
const value = e.target.value.trim();
if (value) {
setValidationStates((prev) => ({
...prev,
codeNameEng: { enabled: true, value },
}));
}
}}
placeholder="코드 영문명을 입력하세요 (선택사항)"
className="h-8 text-xs sm:h-10 sm:text-sm"
/>
{form.formState.errors.codeNameEng && (
<p className="text-[10px] sm:text-xs text-destructive">{getErrorMessage(form.formState.errors.codeNameEng)}</p>
)}
{!form.formState.errors.codeNameEng && (
<ValidationMessage
message={codeNameEngCheck.data?.message}
isValid={!codeNameEngCheck.data?.isDuplicate}
isLoading={codeNameEngCheck.isLoading}
/>
)}
</div>
{/* 설명 */}
{/* 설명 (선택) */}
<div className="space-y-2">
<Label htmlFor="description" className="text-xs sm:text-sm"> *</Label>
<Label htmlFor="description" className="text-xs sm:text-sm">
</Label>
<Textarea
id="description"
{...form.register("description")}
disabled={isLoading}
placeholder="설명을 입력하세요"
rows={3}
className={form.formState.errors.description ? "text-xs sm:text-sm border-destructive" : "text-xs sm:text-sm"}
placeholder="설명을 입력하세요 (선택사항)"
rows={2}
className="text-xs sm:text-sm"
/>
{form.formState.errors.description && (
<p className="text-[10px] sm:text-xs text-destructive">{getErrorMessage(form.formState.errors.description)}</p>
)}
</div>
{/* 부모 코드 표시 (하위 코드 추가 시에만 표시, 읽기 전용) */}
{defaultParentCode && (
<div className="space-y-2">
<Label className="text-xs sm:text-sm"> </Label>
<div className="bg-muted h-8 rounded-md border px-3 py-1.5 text-xs sm:h-10 sm:py-2 sm:text-sm">
{(() => {
const parentCode = codes.find((c) => (c.codeValue || c.code_value) === defaultParentCode);
return parentCode
? `${parentCode.codeName || parentCode.code_name} (${defaultParentCode})`
: defaultParentCode;
})()}
</div>
<p className="text-muted-foreground text-[10px] sm:text-xs"> </p>
</div>
)}
{/* 정렬 순서 */}
<div className="space-y-2">
<Label htmlFor="sortOrder" className="text-xs sm:text-sm"> </Label>
<Label htmlFor="sortOrder" className="text-xs sm:text-sm">
</Label>
<Input
id="sortOrder"
type="number"
{...form.register("sortOrder", { valueAsNumber: true })}
disabled={isLoading}
min={1}
className={form.formState.errors.sortOrder ? "h-8 text-xs sm:h-10 sm:text-sm border-destructive" : "h-8 text-xs sm:h-10 sm:text-sm"}
className={
form.formState.errors.sortOrder
? "border-destructive h-8 text-xs sm:h-10 sm:text-sm"
: "h-8 text-xs sm:h-10 sm:text-sm"
}
/>
{form.formState.errors.sortOrder && (
<p className="text-[10px] sm:text-xs text-destructive">{getErrorMessage(form.formState.errors.sortOrder)}</p>
<p className="text-destructive text-[10px] sm:text-xs">
{getErrorMessage(form.formState.errors.sortOrder)}
</p>
)}
</div>
@@ -295,16 +296,18 @@ export function CodeFormModal({ isOpen, onClose, categoryCode, editingCode, code
disabled={isLoading}
aria-label="활성 상태"
/>
<Label htmlFor="isActive" className="text-xs sm:text-sm">{form.watch("isActive") === "Y" ? "활성" : "비활성"}</Label>
<Label htmlFor="isActive" className="text-xs sm:text-sm">
{form.watch("isActive") === "Y" ? "활성" : "비활성"}
</Label>
</div>
)}
{/* 버튼 */}
<div className="flex gap-2 pt-4 sm:justify-end sm:gap-0">
<Button
type="button"
variant="outline"
onClick={onClose}
<Button
type="button"
variant="outline"
onClick={onClose}
disabled={isLoading}
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
>

View File

@@ -5,7 +5,7 @@ import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Edit, Trash2 } from "lucide-react";
import { Edit, Trash2, CornerDownRight, Plus, ChevronRight, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { useUpdateCode } from "@/hooks/queries/useCodes";
import type { CodeInfo } from "@/types/commonCode";
@@ -15,7 +15,13 @@ interface SortableCodeItemProps {
categoryCode: string;
onEdit: () => void;
onDelete: () => void;
onAddChild: () => void; // 하위 코드 추가
isDragOverlay?: boolean;
maxDepth?: number; // 최대 깊이 (기본값 3)
hasChildren?: boolean; // 자식이 있는지 여부
childCount?: number; // 자식 개수
isExpanded?: boolean; // 펼쳐진 상태
onToggleExpand?: () => void; // 접기/펼치기 토글
}
export function SortableCodeItem({
@@ -23,10 +29,16 @@ export function SortableCodeItem({
categoryCode,
onEdit,
onDelete,
onAddChild,
isDragOverlay = false,
maxDepth = 3,
hasChildren = false,
childCount = 0,
isExpanded = true,
onToggleExpand,
}: SortableCodeItemProps) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: code.codeValue || code.code_value,
id: code.codeValue || code.code_value || "",
disabled: isDragOverlay,
});
const updateCodeMutation = useUpdateCode();
@@ -39,7 +51,6 @@ export function SortableCodeItem({
// 활성/비활성 토글 핸들러
const handleToggleActive = async (checked: boolean) => {
try {
// codeValue 또는 code_value가 없으면 에러 처리
const codeValue = code.codeValue || code.code_value;
if (!codeValue) {
return;
@@ -61,73 +72,158 @@ export function SortableCodeItem({
}
};
// 계층구조 깊이에 따른 들여쓰기
const depth = code.depth || 1;
const indentLevel = (depth - 1) * 28; // 28px per level
const hasParent = !!(code.parentCodeValue || code.parent_code_value);
return (
<div
ref={setNodeRef}
style={style}
{...attributes}
{...listeners}
className={cn(
"group cursor-grab rounded-lg border bg-card p-4 shadow-sm transition-all hover:shadow-md",
isDragging && "cursor-grabbing opacity-50",
<div className="flex items-stretch">
{/* 계층구조 들여쓰기 영역 */}
{depth > 1 && (
<div
className="flex items-center justify-end pr-2"
style={{ width: `${indentLevel}px`, minWidth: `${indentLevel}px` }}
>
<CornerDownRight className="text-muted-foreground/50 h-4 w-4" />
</div>
)}
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h4 className="text-sm font-semibold">{code.codeName || code.code_name}</h4>
<Badge
variant={code.isActive === "Y" || code.is_active === "Y" ? "default" : "secondary"}
className={cn(
"cursor-pointer text-xs transition-colors",
updateCodeMutation.isPending && "cursor-not-allowed opacity-50",
<div
ref={setNodeRef}
style={style}
{...attributes}
{...listeners}
className={cn(
"group bg-card flex-1 cursor-grab rounded-lg border p-4 shadow-sm transition-all hover:shadow-md",
isDragging && "cursor-grabbing opacity-50",
depth === 1 && "border-l-primary border-l-4",
depth === 2 && "border-l-4 border-l-blue-400",
depth === 3 && "border-l-4 border-l-green-400",
)}
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
{/* 접기/펼치기 버튼 (자식이 있을 때만 표시) */}
{hasChildren && onToggleExpand && (
<button
type="button"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onToggleExpand();
}}
onPointerDown={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
className="text-muted-foreground hover:text-foreground -ml-1 flex h-5 w-5 items-center justify-center rounded transition-colors hover:bg-gray-100"
title={isExpanded ? "접기" : "펼치기"}
>
{isExpanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</button>
)}
<h4 className="text-sm font-semibold">{code.codeName || code.code_name}</h4>
{/* 접힌 상태에서 자식 개수 표시 */}
{hasChildren && !isExpanded && <span className="text-muted-foreground text-[10px]">({childCount})</span>}
{/* 깊이 표시 배지 */}
{depth === 1 && (
<Badge
variant="outline"
className="border-primary/30 bg-primary/10 text-primary px-1.5 py-0 text-[10px]"
>
</Badge>
)}
{depth === 2 && (
<Badge variant="outline" className="bg-blue-50 px-1.5 py-0 text-[10px] text-blue-600">
</Badge>
)}
{depth === 3 && (
<Badge variant="outline" className="bg-green-50 px-1.5 py-0 text-[10px] text-green-600">
</Badge>
)}
{depth > 3 && (
<Badge variant="outline" className="bg-muted px-1.5 py-0 text-[10px]">
{depth}
</Badge>
)}
<Badge
variant={code.isActive === "Y" || code.is_active === "Y" ? "default" : "secondary"}
className={cn(
"cursor-pointer text-xs transition-colors",
updateCodeMutation.isPending && "cursor-not-allowed opacity-50",
)}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
if (!updateCodeMutation.isPending) {
const isActive = code.isActive === "Y" || code.is_active === "Y";
handleToggleActive(!isActive);
}
}}
onPointerDown={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
>
{code.isActive === "Y" || code.is_active === "Y" ? "활성" : "비활성"}
</Badge>
</div>
<p className="text-muted-foreground mt-1 text-xs">{code.codeValue || code.code_value}</p>
{/* 부모 코드 표시 */}
{hasParent && (
<p className="text-muted-foreground mt-0.5 text-[10px]">
: {code.parentCodeValue || code.parent_code_value}
</p>
)}
{code.description && <p className="text-muted-foreground mt-1 text-xs">{code.description}</p>}
</div>
{/* 액션 버튼 */}
<div
className="flex items-center gap-1"
onPointerDown={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
>
{/* 하위 코드 추가 버튼 (최대 깊이 미만일 때만 표시) */}
{depth < maxDepth && (
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onAddChild();
}}
title="하위 코드 추가"
className="text-blue-600 hover:bg-blue-50 hover:text-blue-700"
>
<Plus className="h-3 w-3" />
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
if (!updateCodeMutation.isPending) {
const isActive = code.isActive === "Y" || code.is_active === "Y";
handleToggleActive(!isActive);
}
onEdit();
}}
onPointerDown={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
>
{code.isActive === "Y" || code.is_active === "Y" ? "활성" : "비활성"}
</Badge>
<Edit className="h-3 w-3" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelete();
}}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
<p className="mt-1 text-xs text-muted-foreground">{code.codeValue || code.code_value}</p>
{code.description && <p className="mt-1 text-xs text-muted-foreground">{code.description}</p>}
</div>
{/* 액션 버튼 */}
<div
className="flex items-center gap-1"
onPointerDown={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onEdit();
}}
>
<Edit className="h-3 w-3" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelete();
}}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
</div>