연쇄관계 관리

This commit is contained in:
kjs
2025-12-10 13:53:44 +09:00
parent ba817980f0
commit c71b958a05
20 changed files with 3313 additions and 35 deletions

View File

@@ -4,6 +4,7 @@ import { useCodeOptions, useTableCodeCategory } from "@/hooks/queries/useCodes";
import { cn } from "@/lib/registry/components/common/inputStyles";
import { useScreenContextOptional } from "@/contexts/ScreenContext";
import type { DataProvidable } from "@/types/data-transfer";
import { useCascadingDropdown } from "@/hooks/useCascadingDropdown";
interface Option {
value: string;
@@ -26,6 +27,7 @@ export interface SelectBasicComponentProps {
onDragEnd?: () => void;
value?: any; // 외부에서 전달받는 값
menuObjid?: number; // 🆕 메뉴 OBJID (코드 스코프용)
formData?: Record<string, any>; // 🆕 폼 데이터 (연쇄 드롭다운용)
[key: string]: any;
}
@@ -50,6 +52,7 @@ const SelectBasicComponent: React.FC<SelectBasicComponentProps> = ({
onDragEnd,
value: externalValue, // 명시적으로 value prop 받기
menuObjid, // 🆕 메뉴 OBJID
formData, // 🆕 폼 데이터 (연쇄 드롭다운용)
...props
}) => {
// 🆕 읽기전용/비활성화 상태 확인
@@ -151,6 +154,25 @@ const SelectBasicComponent: React.FC<SelectBasicComponentProps> = ({
const [categoryOptions, setCategoryOptions] = useState<Option[]>([]);
const [isLoadingCategories, setIsLoadingCategories] = useState(false);
// 🆕 연쇄 드롭다운 설정 확인
const cascadingRelationCode = config?.cascadingRelationCode || componentConfig?.cascadingRelationCode;
const cascadingRole = config?.cascadingRole || componentConfig?.cascadingRole || "child";
const cascadingParentField = config?.cascadingParentField || componentConfig?.cascadingParentField;
// 자식 역할일 때만 부모 값 필요
const parentValue = cascadingRole === "child" && cascadingParentField && formData
? formData[cascadingParentField]
: undefined;
// 🆕 연쇄 드롭다운 훅 사용 (역할에 따라 다른 옵션 로드)
const {
options: cascadingOptions,
loading: isLoadingCascading,
} = useCascadingDropdown({
relationCode: cascadingRelationCode,
role: cascadingRole, // 부모/자식 역할 전달
parentValue: parentValue,
});
useEffect(() => {
if (webType === "category" && component.tableName && component.columnName) {
console.log("🔍 [SelectBasic] 카테고리 값 로딩 시작:", {
@@ -301,12 +323,16 @@ const SelectBasicComponent: React.FC<SelectBasicComponentProps> = ({
// 선택된 값에 따른 라벨 업데이트
useEffect(() => {
const getAllOptions = () => {
const getAllOptionsForLabel = () => {
// 🆕 연쇄 드롭다운이 설정된 경우 연쇄 옵션만 사용
if (cascadingRelationCode) {
return cascadingOptions;
}
const configOptions = config.options || [];
return [...codeOptions, ...categoryOptions, ...configOptions];
};
const options = getAllOptions();
const options = getAllOptionsForLabel();
const selectedOption = options.find((option) => option.value === selectedValue);
// 🎯 코드 타입의 경우 코드값과 코드명을 모두 고려하여 라벨 찾기
@@ -327,7 +353,7 @@ const SelectBasicComponent: React.FC<SelectBasicComponentProps> = ({
if (newLabel !== selectedLabel) {
setSelectedLabel(newLabel);
}
}, [selectedValue, codeOptions, config.options]);
}, [selectedValue, codeOptions, config.options, cascadingOptions, cascadingRelationCode]);
// 클릭 이벤트 핸들러 (React Query로 간소화)
const handleToggle = () => {
@@ -378,6 +404,11 @@ const SelectBasicComponent: React.FC<SelectBasicComponentProps> = ({
// 모든 옵션 가져오기
const getAllOptions = () => {
// 🆕 연쇄 드롭다운이 설정된 경우 연쇄 옵션만 사용
if (cascadingRelationCode) {
return cascadingOptions;
}
const configOptions = config.options || [];
return [...codeOptions, ...categoryOptions, ...configOptions];
};

View File

@@ -1,15 +1,24 @@
"use client";
import React from "react";
import React, { useState, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Link2, ExternalLink } from "lucide-react";
import Link from "next/link";
import { SelectBasicConfig } from "./types";
import { cascadingRelationApi, CascadingRelation } from "@/lib/api/cascadingRelation";
export interface SelectBasicConfigPanelProps {
config: SelectBasicConfig;
onChange: (config: Partial<SelectBasicConfig>) => void;
/** 현재 화면의 모든 컴포넌트 목록 (부모 필드 자동 감지용) */
allComponents?: any[];
/** 현재 컴포넌트 정보 */
currentComponent?: any;
}
/**
@@ -19,20 +28,134 @@ export interface SelectBasicConfigPanelProps {
export const SelectBasicConfigPanel: React.FC<SelectBasicConfigPanelProps> = ({
config,
onChange,
allComponents = [],
currentComponent,
}) => {
// 연쇄 드롭다운 관련 상태
const [cascadingEnabled, setCascadingEnabled] = useState(!!config.cascadingRelationCode);
const [relationList, setRelationList] = useState<CascadingRelation[]>([]);
const [loadingRelations, setLoadingRelations] = useState(false);
// 연쇄 관계 목록 로드
useEffect(() => {
if (cascadingEnabled && relationList.length === 0) {
loadRelationList();
}
}, [cascadingEnabled]);
// config 변경 시 상태 동기화
useEffect(() => {
setCascadingEnabled(!!config.cascadingRelationCode);
}, [config.cascadingRelationCode]);
const loadRelationList = async () => {
setLoadingRelations(true);
try {
const response = await cascadingRelationApi.getList("Y");
if (response.success && response.data) {
setRelationList(response.data);
}
} catch (error) {
console.error("연쇄 관계 목록 로드 실패:", error);
} finally {
setLoadingRelations(false);
}
};
const handleChange = (key: keyof SelectBasicConfig, value: any) => {
// 기존 config와 병합하여 전체 객체 전달 (다른 속성 보호)
const newConfig = { ...config, [key]: value };
onChange(newConfig);
};
// 연쇄 드롭다운 토글
const handleCascadingToggle = (enabled: boolean) => {
setCascadingEnabled(enabled);
if (!enabled) {
// 비활성화 시 관계 설정 제거
const newConfig = {
...config,
cascadingRelationCode: undefined,
cascadingRole: undefined,
cascadingParentField: undefined,
};
onChange(newConfig);
} else {
loadRelationList();
}
};
// 🆕 같은 연쇄 관계의 부모 역할 컴포넌트 찾기
const findParentComponent = (relationCode: string) => {
console.log("🔍 findParentComponent 호출:", {
relationCode,
allComponentsLength: allComponents?.length,
currentComponentId: currentComponent?.id,
});
if (!allComponents || allComponents.length === 0) {
console.log("❌ allComponents가 비어있음");
return null;
}
// 모든 컴포넌트의 cascading 설정 확인
allComponents.forEach((comp: any) => {
const compConfig = comp.componentConfig || {};
if (compConfig.cascadingRelationCode) {
console.log("📦 컴포넌트 cascading 설정:", {
id: comp.id,
columnName: comp.columnName,
cascadingRelationCode: compConfig.cascadingRelationCode,
cascadingRole: compConfig.cascadingRole,
});
}
});
const found = allComponents.find((comp: any) => {
const compConfig = comp.componentConfig || {};
return (
comp.id !== currentComponent?.id && // 자기 자신 제외
compConfig.cascadingRelationCode === relationCode &&
compConfig.cascadingRole === "parent"
);
});
console.log("🔍 찾은 부모 컴포넌트:", found);
return found;
};
// 역할 변경 시 부모 필드 자동 감지
const handleRoleChange = (role: "parent" | "child") => {
let parentField = config.cascadingParentField;
// 자식 역할 선택 시 부모 필드 자동 감지
if (role === "child" && config.cascadingRelationCode) {
const parentComp = findParentComponent(config.cascadingRelationCode);
if (parentComp) {
parentField = parentComp.columnName;
console.log("🔗 부모 필드 자동 감지:", parentField);
}
}
const newConfig = {
...config,
cascadingRole: role,
// 부모 역할일 때는 부모 필드 불필요, 자식일 때는 자동 감지된 값 또는 기존 값
cascadingParentField: role === "parent" ? undefined : parentField,
};
onChange(newConfig);
};
// 선택된 관계 정보
const selectedRelation = relationList.find(r => r.relation_code === config.cascadingRelationCode);
return (
<div className="space-y-4">
<div className="text-sm font-medium">
select-basic
</div>
{/* select 관련 설정 */}
{/* select 관련 설정 */}
<div className="space-y-2">
<Label htmlFor="placeholder"></Label>
<Input
@@ -78,6 +201,179 @@ export const SelectBasicConfigPanel: React.FC<SelectBasicConfigPanelProps> = ({
onCheckedChange={(checked) => handleChange("multiple", checked)}
/>
</div>
{/* 연쇄 드롭다운 설정 */}
<div className="border-t pt-4 mt-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Link2 className="h-4 w-4" />
<Label className="text-sm font-medium"> </Label>
</div>
<Switch
checked={cascadingEnabled}
onCheckedChange={handleCascadingToggle}
/>
</div>
<p className="text-muted-foreground text-xs">
.
</p>
{cascadingEnabled && (
<div className="space-y-3 rounded-md border p-3 bg-muted/30">
{/* 관계 선택 */}
<div className="space-y-2">
<Label className="text-xs"> </Label>
<Select
value={config.cascadingRelationCode || ""}
onValueChange={(value) => handleChange("cascadingRelationCode", value || undefined)}
>
<SelectTrigger className="text-xs">
<SelectValue placeholder={loadingRelations ? "로딩 중..." : "관계 선택"} />
</SelectTrigger>
<SelectContent>
{relationList.map((relation) => (
<SelectItem key={relation.relation_code} value={relation.relation_code}>
<div className="flex flex-col">
<span>{relation.relation_name}</span>
<span className="text-muted-foreground text-xs">
{relation.parent_table} {relation.child_table}
</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 역할 선택 */}
{config.cascadingRelationCode && (
<div className="space-y-2">
<Label className="text-xs"> </Label>
<div className="flex gap-2">
<Button
type="button"
size="sm"
variant={config.cascadingRole === "parent" ? "default" : "outline"}
className="flex-1 text-xs"
onClick={() => handleRoleChange("parent")}
>
( )
</Button>
<Button
type="button"
size="sm"
variant={config.cascadingRole === "child" ? "default" : "outline"}
className="flex-1 text-xs"
onClick={() => handleRoleChange("child")}
>
( )
</Button>
</div>
<p className="text-muted-foreground text-xs">
{config.cascadingRole === "parent"
? "이 필드가 상위 선택 역할을 합니다. (예: 창고 선택)"
: config.cascadingRole === "child"
? "이 필드는 상위 필드 값에 따라 옵션이 변경됩니다. (예: 위치 선택)"
: "이 필드의 역할을 선택하세요."}
</p>
</div>
)}
{/* 부모 필드 설정 (자식 역할일 때만) */}
{config.cascadingRelationCode && config.cascadingRole === "child" && (
<div className="space-y-2">
<Label className="text-xs"> </Label>
{(() => {
const parentComp = findParentComponent(config.cascadingRelationCode);
const isAutoDetected = parentComp && config.cascadingParentField === parentComp.columnName;
return (
<>
<div className="flex gap-2 items-center">
<Input
value={config.cascadingParentField || ""}
onChange={(e) => handleChange("cascadingParentField", e.target.value || undefined)}
placeholder="예: warehouse_code"
className="text-xs flex-1"
/>
{parentComp && !isAutoDetected && (
<Button
type="button"
size="sm"
variant="outline"
className="text-xs shrink-0"
onClick={() => handleChange("cascadingParentField", parentComp.columnName)}
>
</Button>
)}
</div>
{isAutoDetected ? (
<p className="text-xs text-green-600">
: {parentComp.label || parentComp.columnName}
</p>
) : parentComp ? (
<p className="text-xs text-amber-600">
: {parentComp.columnName} ({parentComp.label || "라벨 없음"})
</p>
) : (
<p className="text-muted-foreground text-xs">
. .
</p>
)}
</>
);
})()}
</div>
)}
{/* 선택된 관계 정보 표시 */}
{selectedRelation && config.cascadingRole && (
<div className="bg-background space-y-1 rounded-md p-2 text-xs">
{config.cascadingRole === "parent" ? (
<>
<div className="font-medium text-blue-600"> ( )</div>
<div>
<span className="text-muted-foreground"> :</span>{" "}
<span className="font-medium">{selectedRelation.parent_table}</span>
</div>
<div>
<span className="text-muted-foreground"> :</span>{" "}
<span className="font-medium">{selectedRelation.parent_value_column}</span>
</div>
</>
) : (
<>
<div className="font-medium text-green-600"> ( )</div>
<div>
<span className="text-muted-foreground"> :</span>{" "}
<span className="font-medium">{selectedRelation.child_table}</span>
</div>
<div>
<span className="text-muted-foreground"> :</span>{" "}
<span className="font-medium">{selectedRelation.child_filter_column}</span>
</div>
<div>
<span className="text-muted-foreground"> :</span>{" "}
<span className="font-medium">{selectedRelation.child_value_column}</span>
</div>
</>
)}
</div>
)}
{/* 관계 관리 페이지 링크 */}
<div className="flex justify-end">
<Link href="/admin/cascading-relations" target="_blank">
<Button variant="link" size="sm" className="h-auto p-0 text-xs">
<ExternalLink className="mr-1 h-3 w-3" />
</Button>
</Link>
</div>
</div>
)}
</div>
</div>
);
};

View File

@@ -14,6 +14,14 @@ export interface SelectBasicConfig extends ComponentConfig {
// 코드 관련 설정
codeCategory?: string;
// 🆕 연쇄 드롭다운 설정
/** 연쇄 관계 코드 (관계 관리에서 정의한 코드) */
cascadingRelationCode?: string;
/** 연쇄 드롭다운 역할: parent(부모) 또는 child(자식) */
cascadingRole?: "parent" | "child";
/** 부모 필드명 (자식 역할일 때, 화면 내 부모 필드의 columnName) */
cascadingParentField?: string;
// 공통 설정
disabled?: boolean;
required?: boolean;