Merge branch 'main' of http://39.117.244.52:3000/kjs/ERP-node into feature/screen-management
This commit is contained in:
@@ -162,6 +162,11 @@ export function CanvasElement({
|
||||
// 요소 선택 처리
|
||||
const handleMouseDown = useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
// 모달이나 다이얼로그가 열려있으면 드래그 무시
|
||||
if (document.querySelector('[role="dialog"]') || document.querySelector('[role="alertdialog"]')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 닫기 버튼이나 리사이즈 핸들 클릭 시 무시
|
||||
if ((e.target as HTMLElement).closest(".element-close, .resize-handle")) {
|
||||
return;
|
||||
@@ -192,6 +197,11 @@ export function CanvasElement({
|
||||
// 리사이즈 핸들 마우스다운
|
||||
const handleResizeMouseDown = useCallback(
|
||||
(e: React.MouseEvent, handle: string) => {
|
||||
// 모달이나 다이얼로그가 열려있으면 리사이즈 무시
|
||||
if (document.querySelector('[role="dialog"]') || document.querySelector('[role="alertdialog"]')) {
|
||||
return;
|
||||
}
|
||||
|
||||
e.stopPropagation();
|
||||
setIsResizing(true);
|
||||
setResizeStart({
|
||||
@@ -522,16 +532,15 @@ export function CanvasElement({
|
||||
<span className="text-sm font-bold text-gray-800">{element.customTitle || element.title}</span>
|
||||
<div className="flex gap-1">
|
||||
{/* 설정 버튼 (기사관리 위젯만 자체 설정 UI 사용) */}
|
||||
{onConfigure &&
|
||||
!(element.type === "widget" && element.subtype === "driver-management") && (
|
||||
<button
|
||||
className="hover:bg-accent0 flex h-6 w-6 items-center justify-center rounded text-gray-400 transition-colors duration-200 hover:text-white"
|
||||
onClick={() => onConfigure(element)}
|
||||
title="설정"
|
||||
>
|
||||
⚙️
|
||||
</button>
|
||||
)}
|
||||
{onConfigure && !(element.type === "widget" && element.subtype === "driver-management") && (
|
||||
<button
|
||||
className="hover:bg-accent0 flex h-6 w-6 items-center justify-center rounded text-gray-400 transition-colors duration-200 hover:text-white"
|
||||
onClick={() => onConfigure(element)}
|
||||
title="설정"
|
||||
>
|
||||
⚙️
|
||||
</button>
|
||||
)}
|
||||
{/* 삭제 버튼 */}
|
||||
<button
|
||||
className="element-close hover:bg-destructive/100 flex h-6 w-6 items-center justify-center rounded text-gray-400 transition-colors duration-200 hover:text-white"
|
||||
|
||||
@@ -111,60 +111,44 @@ export function QueryEditor({ dataSource, onDataSourceChange, onQueryTest }: Que
|
||||
// 샘플 쿼리 삽입
|
||||
const insertSampleQuery = useCallback((sampleType: string) => {
|
||||
const samples = {
|
||||
comparison: `-- 제품별 월별 매출 비교 (다중 시리즈)
|
||||
-- 갤럭시(Galaxy) vs 아이폰(iPhone) 매출 비교
|
||||
SELECT
|
||||
DATE_TRUNC('month', order_date) as month,
|
||||
SUM(CASE WHEN product_category = '갤럭시' THEN amount ELSE 0 END) as galaxy_sales,
|
||||
SUM(CASE WHEN product_category = '아이폰' THEN amount ELSE 0 END) as iphone_sales,
|
||||
SUM(CASE WHEN product_category = '기타' THEN amount ELSE 0 END) as other_sales
|
||||
FROM orders
|
||||
WHERE order_date >= CURRENT_DATE - INTERVAL '12 months'
|
||||
GROUP BY DATE_TRUNC('month', order_date)
|
||||
ORDER BY month;`,
|
||||
users: `SELECT
|
||||
dept_name as 부서명,
|
||||
COUNT(*) as 회원수
|
||||
FROM user_info
|
||||
WHERE dept_name IS NOT NULL
|
||||
GROUP BY dept_name
|
||||
ORDER BY 회원수 DESC`,
|
||||
|
||||
sales: `-- 월별 매출 데이터
|
||||
SELECT
|
||||
DATE_TRUNC('month', order_date) as month,
|
||||
SUM(total_amount) as sales,
|
||||
COUNT(*) as order_count
|
||||
FROM orders
|
||||
WHERE order_date >= CURRENT_DATE - INTERVAL '12 months'
|
||||
GROUP BY DATE_TRUNC('month', order_date)
|
||||
ORDER BY month;`,
|
||||
dept: `SELECT
|
||||
dept_code as 부서코드,
|
||||
dept_name as 부서명,
|
||||
location_name as 위치,
|
||||
TO_CHAR(regdate, 'YYYY-MM-DD') as 등록일
|
||||
FROM dept_info
|
||||
ORDER BY dept_code`,
|
||||
|
||||
users: `-- 사용자 가입 추이
|
||||
SELECT
|
||||
DATE_TRUNC('week', created_at) as week,
|
||||
COUNT(*) as new_users
|
||||
FROM users
|
||||
WHERE created_at >= CURRENT_DATE - INTERVAL '3 months'
|
||||
GROUP BY DATE_TRUNC('week', created_at)
|
||||
ORDER BY week;`,
|
||||
usersByDate: `SELECT
|
||||
DATE_TRUNC('month', regdate)::date as 월,
|
||||
COUNT(*) as 신규사용자수
|
||||
FROM user_info
|
||||
WHERE regdate >= CURRENT_DATE - INTERVAL '12 months'
|
||||
GROUP BY DATE_TRUNC('month', regdate)
|
||||
ORDER BY 월`,
|
||||
|
||||
products: `-- 상품별 판매량
|
||||
SELECT
|
||||
product_name,
|
||||
SUM(quantity) as total_sold,
|
||||
SUM(quantity * price) as revenue
|
||||
FROM order_items oi
|
||||
JOIN products p ON oi.product_id = p.id
|
||||
WHERE oi.created_at >= CURRENT_DATE - INTERVAL '1 month'
|
||||
GROUP BY product_name
|
||||
ORDER BY total_sold DESC
|
||||
LIMIT 10;`,
|
||||
usersByPosition: `SELECT
|
||||
position_name as 직급,
|
||||
COUNT(*) as 인원수
|
||||
FROM user_info
|
||||
WHERE position_name IS NOT NULL
|
||||
GROUP BY position_name
|
||||
ORDER BY 인원수 DESC`,
|
||||
|
||||
regional: `-- 지역별 매출 비교
|
||||
SELECT
|
||||
region as 지역,
|
||||
SUM(CASE WHEN quarter = 'Q1' THEN sales ELSE 0 END) as Q1,
|
||||
SUM(CASE WHEN quarter = 'Q2' THEN sales ELSE 0 END) as Q2,
|
||||
SUM(CASE WHEN quarter = 'Q3' THEN sales ELSE 0 END) as Q3,
|
||||
SUM(CASE WHEN quarter = 'Q4' THEN sales ELSE 0 END) as Q4
|
||||
FROM regional_sales
|
||||
WHERE year = EXTRACT(YEAR FROM CURRENT_DATE)
|
||||
GROUP BY region
|
||||
ORDER BY Q4 DESC;`,
|
||||
deptHierarchy: `SELECT
|
||||
COALESCE(parent_dept_code, '최상위') as 상위부서코드,
|
||||
COUNT(*) as 하위부서수
|
||||
FROM dept_info
|
||||
GROUP BY parent_dept_code
|
||||
ORDER BY 하위부서수 DESC`,
|
||||
};
|
||||
|
||||
setQuery(samples[sampleType as keyof typeof samples] || "");
|
||||
@@ -197,22 +181,22 @@ ORDER BY Q4 DESC;`,
|
||||
<Card className="p-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Label className="text-sm text-gray-600">샘플 쿼리:</Label>
|
||||
<Button variant="outline" size="sm" onClick={() => insertSampleQuery("comparison")}>
|
||||
<Code className="mr-2 h-3 w-3" />
|
||||
제품 비교
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => insertSampleQuery("regional")}>
|
||||
<Code className="mr-2 h-3 w-3" />
|
||||
지역별 비교
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => insertSampleQuery("sales")}>
|
||||
매출 데이터
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => insertSampleQuery("users")}>
|
||||
사용자 추이
|
||||
<Code className="mr-2 h-3 w-3" />
|
||||
부서별 사용자
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => insertSampleQuery("products")}>
|
||||
상품 판매량
|
||||
<Button variant="outline" size="sm" onClick={() => insertSampleQuery("dept")}>
|
||||
<Code className="mr-2 h-3 w-3" />
|
||||
부서 정보
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => insertSampleQuery("usersByDate")}>
|
||||
월별 가입 추이
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => insertSampleQuery("usersByPosition")}>
|
||||
직급별 분포
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => insertSampleQuery("deptHierarchy")}>
|
||||
부서 계층
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
@@ -315,13 +299,6 @@ ORDER BY Q4 DESC;`,
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 키보드 단축키 안내 */}
|
||||
<Card className="p-3">
|
||||
<div className="text-xs text-gray-600">
|
||||
<strong>단축키:</strong> Ctrl+Enter (쿼리 실행), Ctrl+/ (주석 토글)
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ export function DatabaseConfig({ dataSource, onChange }: DatabaseConfigProps) {
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="커넥션을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectContent className="z-[9999]">
|
||||
{connections.map((conn) => (
|
||||
<SelectItem key={conn.id} value={String(conn.id)}>
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Plus, Check } from "lucide-react";
|
||||
import YardLayoutList from "./yard-3d/YardLayoutList";
|
||||
import { Plus, Check, Trash2 } from "lucide-react";
|
||||
import YardLayoutCreateModal from "./yard-3d/YardLayoutCreateModal";
|
||||
import YardEditor from "./yard-3d/YardEditor";
|
||||
import Yard3DViewer from "./yard-3d/Yard3DViewer";
|
||||
@@ -16,6 +15,7 @@ interface YardLayout {
|
||||
name: string;
|
||||
description: string;
|
||||
placement_count: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ export default function YardManagement3DWidget({
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
||||
const [editingLayout, setEditingLayout] = useState<YardLayout | null>(null);
|
||||
const [deleteLayoutId, setDeleteLayoutId] = useState<number | null>(null);
|
||||
|
||||
// 레이아웃 목록 로드
|
||||
const loadLayouts = async () => {
|
||||
@@ -41,7 +42,7 @@ export default function YardManagement3DWidget({
|
||||
setIsLoading(true);
|
||||
const response = await yardLayoutApi.getAllLayouts();
|
||||
if (response.success) {
|
||||
setLayouts(response.data);
|
||||
setLayouts(response.data as YardLayout[]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("야드 레이아웃 목록 조회 실패:", error);
|
||||
@@ -67,13 +68,13 @@ export default function YardManagement3DWidget({
|
||||
};
|
||||
|
||||
// 새 레이아웃 생성
|
||||
const handleCreateLayout = async (name: string, description: string) => {
|
||||
const handleCreateLayout = async (name: string) => {
|
||||
try {
|
||||
const response = await yardLayoutApi.createLayout({ name, description });
|
||||
const response = await yardLayoutApi.createLayout({ name });
|
||||
if (response.success) {
|
||||
await loadLayouts();
|
||||
setIsCreateModalOpen(false);
|
||||
setEditingLayout(response.data);
|
||||
setEditingLayout(response.data as YardLayout);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("야드 레이아웃 생성 실패:", error);
|
||||
@@ -93,6 +94,26 @@ export default function YardManagement3DWidget({
|
||||
loadLayouts();
|
||||
};
|
||||
|
||||
// 레이아웃 삭제
|
||||
const handleDeleteLayout = async () => {
|
||||
if (!deleteLayoutId) return;
|
||||
|
||||
try {
|
||||
const response = await yardLayoutApi.deleteLayout(deleteLayoutId);
|
||||
if (response.success) {
|
||||
// 삭제된 레이아웃이 현재 선택된 레이아웃이면 설정 초기화
|
||||
if (config?.layoutId === deleteLayoutId && onConfigChange) {
|
||||
onConfigChange({ layoutId: 0, layoutName: "" });
|
||||
}
|
||||
await loadLayouts();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("레이아웃 삭제 실패:", error);
|
||||
} finally {
|
||||
setDeleteLayoutId(null);
|
||||
}
|
||||
};
|
||||
|
||||
// 편집 모드: 편집 중인 경우 YardEditor 표시
|
||||
if (isEditMode && editingLayout) {
|
||||
return (
|
||||
@@ -105,7 +126,7 @@ export default function YardManagement3DWidget({
|
||||
// 편집 모드: 레이아웃 선택 UI
|
||||
if (isEditMode) {
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col bg-white">
|
||||
<div className="widget-interactive-area flex h-full w-full flex-col bg-white">
|
||||
<div className="flex items-center justify-between border-b p-4">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-gray-700">야드 레이아웃 선택</h3>
|
||||
@@ -149,16 +170,29 @@ export default function YardManagement3DWidget({
|
||||
{layout.description && <p className="mt-1 text-xs text-gray-500">{layout.description}</p>}
|
||||
<div className="mt-2 text-xs text-gray-400">배치된 자재: {layout.placement_count}개</div>
|
||||
</button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setEditingLayout(layout);
|
||||
}}
|
||||
>
|
||||
편집
|
||||
</Button>
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setEditingLayout(layout);
|
||||
}}
|
||||
>
|
||||
편집
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-600 hover:bg-red-50"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setDeleteLayoutId(layout.id);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
@@ -172,6 +206,37 @@ export default function YardManagement3DWidget({
|
||||
onClose={() => setIsCreateModalOpen(false)}
|
||||
onCreate={handleCreateLayout}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 모달 */}
|
||||
<Dialog
|
||||
open={deleteLayoutId !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteLayoutId(null);
|
||||
}}
|
||||
>
|
||||
<DialogContent onPointerDown={(e) => e.stopPropagation()} className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>야드 레이아웃 삭제</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-gray-600">
|
||||
이 야드 레이아웃을 삭제하시겠습니까?
|
||||
<br />
|
||||
레이아웃 내의 모든 배치 정보도 함께 삭제됩니다.
|
||||
<br />
|
||||
<span className="font-semibold text-red-600">이 작업은 되돌릴 수 없습니다.</span>
|
||||
</p>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={() => setDeleteLayoutId(null)}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleDeleteLayout} className="bg-red-600 hover:bg-red-700">
|
||||
삭제
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -49,9 +49,6 @@ export default function MaterialEditPanel({ placement, onClose, onUpdate, onRemo
|
||||
useEffect(() => {
|
||||
if (placement) {
|
||||
setEditData({
|
||||
position_x: placement.position_x,
|
||||
position_y: placement.position_y,
|
||||
position_z: placement.position_z,
|
||||
size_x: placement.size_x,
|
||||
size_y: placement.size_y,
|
||||
size_z: placement.size_z,
|
||||
@@ -107,52 +104,6 @@ export default function MaterialEditPanel({ placement, onClose, onUpdate, onRemo
|
||||
<div className="space-y-3">
|
||||
<div className="text-xs font-medium text-gray-500">배치 정보 (편집 가능)</div>
|
||||
|
||||
{/* 3D 위치 */}
|
||||
<div>
|
||||
<Label className="text-xs">위치</Label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<Label htmlFor="edit-posX" className="text-xs text-gray-600">
|
||||
X
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-posX"
|
||||
type="number"
|
||||
value={editData.position_x ?? placement.position_x}
|
||||
onChange={(e) => setEditData({ ...editData, position_x: parseFloat(e.target.value) || 0 })}
|
||||
step="0.5"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="edit-posY" className="text-xs text-gray-600">
|
||||
Y
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-posY"
|
||||
type="number"
|
||||
value={editData.position_y ?? placement.position_y}
|
||||
onChange={(e) => setEditData({ ...editData, position_y: parseFloat(e.target.value) || 0 })}
|
||||
step="0.5"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="edit-posZ" className="text-xs text-gray-600">
|
||||
Z
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-posZ"
|
||||
type="number"
|
||||
value={editData.position_z ?? placement.position_z}
|
||||
onChange={(e) => setEditData({ ...editData, position_z: parseFloat(e.target.value) || 0 })}
|
||||
step="0.5"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 3D 크기 */}
|
||||
<div>
|
||||
<Label className="text-xs">크기</Label>
|
||||
@@ -167,7 +118,7 @@ export default function MaterialEditPanel({ placement, onClose, onUpdate, onRemo
|
||||
value={editData.size_x ?? placement.size_x}
|
||||
onChange={(e) => setEditData({ ...editData, size_x: parseFloat(e.target.value) || 1 })}
|
||||
min="1"
|
||||
step="0.5"
|
||||
step="1"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
@@ -181,7 +132,7 @@ export default function MaterialEditPanel({ placement, onClose, onUpdate, onRemo
|
||||
value={editData.size_y ?? placement.size_y}
|
||||
onChange={(e) => setEditData({ ...editData, size_y: parseFloat(e.target.value) || 1 })}
|
||||
min="1"
|
||||
step="0.5"
|
||||
step="1"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
@@ -195,7 +146,7 @@ export default function MaterialEditPanel({ placement, onClose, onUpdate, onRemo
|
||||
value={editData.size_z ?? placement.size_z}
|
||||
onChange={(e) => setEditData({ ...editData, size_z: parseFloat(e.target.value) || 1 })}
|
||||
min="1"
|
||||
step="0.5"
|
||||
step="1"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -7,11 +7,10 @@ import * as THREE from "three";
|
||||
|
||||
interface YardPlacement {
|
||||
id: number;
|
||||
external_material_id: string;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
material_code?: string | null;
|
||||
material_name?: string | null;
|
||||
quantity?: number | null;
|
||||
unit?: string | null;
|
||||
position_x: number;
|
||||
position_y: number;
|
||||
position_z: number;
|
||||
@@ -19,6 +18,9 @@ interface YardPlacement {
|
||||
size_y: number;
|
||||
size_z: number;
|
||||
color: string;
|
||||
data_source_type?: string | null;
|
||||
data_source_config?: any;
|
||||
data_binding?: any;
|
||||
}
|
||||
|
||||
interface Yard3DCanvasProps {
|
||||
@@ -159,6 +161,9 @@ function MaterialBox({
|
||||
}
|
||||
};
|
||||
|
||||
// 요소가 설정되었는지 확인
|
||||
const isConfigured = !!(placement.material_name && placement.quantity && placement.unit);
|
||||
|
||||
return (
|
||||
<Box
|
||||
ref={meshRef}
|
||||
@@ -168,7 +173,6 @@ function MaterialBox({
|
||||
e.stopPropagation();
|
||||
e.nativeEvent?.stopPropagation();
|
||||
e.nativeEvent?.stopImmediatePropagation();
|
||||
console.log("3D Box clicked:", placement.material_name);
|
||||
onClick();
|
||||
}}
|
||||
onPointerDown={handlePointerDown}
|
||||
@@ -188,10 +192,11 @@ function MaterialBox({
|
||||
>
|
||||
<meshStandardMaterial
|
||||
color={placement.color}
|
||||
opacity={isSelected ? 1 : 0.8}
|
||||
opacity={isConfigured ? (isSelected ? 1 : 0.8) : 0.5}
|
||||
transparent
|
||||
emissive={isSelected ? "#ffffff" : "#000000"}
|
||||
emissiveIntensity={isSelected ? 0.2 : 0}
|
||||
wireframe={!isConfigured}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -8,11 +8,10 @@ import { Loader2 } from "lucide-react";
|
||||
interface YardPlacement {
|
||||
id: number;
|
||||
yard_layout_id: number;
|
||||
external_material_id: string;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
material_code?: string | null;
|
||||
material_name?: string | null;
|
||||
quantity?: number | null;
|
||||
unit?: string | null;
|
||||
position_x: number;
|
||||
position_y: number;
|
||||
position_z: number;
|
||||
@@ -20,6 +19,9 @@ interface YardPlacement {
|
||||
size_y: number;
|
||||
size_z: number;
|
||||
color: string;
|
||||
data_source_type?: string | null;
|
||||
data_source_config?: any;
|
||||
data_binding?: any;
|
||||
status?: string;
|
||||
memo?: string;
|
||||
}
|
||||
@@ -130,7 +132,9 @@ export default function Yard3DViewer({ layoutId }: Yard3DViewerProps) {
|
||||
{selectedPlacement && (
|
||||
<div className="absolute top-4 right-4 z-50 w-64 rounded-lg border border-gray-300 bg-white p-4 shadow-xl">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold text-gray-800">자재 정보</h3>
|
||||
<h3 className="text-sm font-semibold text-gray-800">
|
||||
{selectedPlacement.material_name ? "자재 정보" : "미설정 요소"}
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedPlacement(null);
|
||||
@@ -141,19 +145,28 @@ export default function Yard3DViewer({ layoutId }: Yard3DViewerProps) {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<label className="text-xs font-medium text-gray-500">자재명</label>
|
||||
<div className="mt-1 text-sm font-semibold text-gray-900">{selectedPlacement.material_name}</div>
|
||||
</div>
|
||||
{selectedPlacement.material_name && selectedPlacement.quantity && selectedPlacement.unit ? (
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<label className="text-xs font-medium text-gray-500">자재명</label>
|
||||
<div className="mt-1 text-sm font-semibold text-gray-900">{selectedPlacement.material_name}</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-xs font-medium text-gray-500">수량</label>
|
||||
<div className="mt-1 text-sm font-semibold text-gray-900">
|
||||
{selectedPlacement.quantity} {selectedPlacement.unit}
|
||||
<div>
|
||||
<label className="text-xs font-medium text-gray-500">수량</label>
|
||||
<div className="mt-1 text-sm font-semibold text-gray-900">
|
||||
{selectedPlacement.quantity} {selectedPlacement.unit}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg bg-orange-50 p-3 text-center">
|
||||
<div className="mb-2 text-2xl">⚠️</div>
|
||||
<div className="text-sm font-medium text-orange-700">데이터 바인딩이</div>
|
||||
<div className="text-sm font-medium text-orange-700">설정되지 않았습니다</div>
|
||||
<div className="mt-2 text-xs text-orange-600">편집 모드에서 설정해주세요</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ArrowLeft, Save, Loader2, X } from "lucide-react";
|
||||
import { yardLayoutApi, materialApi } from "@/lib/api/yardLayoutApi";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ArrowLeft, Save, Loader2, Plus, Settings, Trash2 } from "lucide-react";
|
||||
import { yardLayoutApi } from "@/lib/api/yardLayoutApi";
|
||||
import dynamic from "next/dynamic";
|
||||
import { YardLayout, YardPlacement } from "./types";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
|
||||
const Yard3DCanvas = dynamic(() => import("./Yard3DCanvas"), {
|
||||
ssr: false,
|
||||
@@ -17,41 +18,11 @@ const Yard3DCanvas = dynamic(() => import("./Yard3DCanvas"), {
|
||||
),
|
||||
});
|
||||
|
||||
interface TempMaterial {
|
||||
id: number;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
category: string;
|
||||
unit: string;
|
||||
default_color: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface YardLayout {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
placement_count?: number;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface YardPlacement {
|
||||
id: number;
|
||||
yard_layout_id: number;
|
||||
external_material_id: string;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
position_x: number;
|
||||
position_y: number;
|
||||
position_z: number;
|
||||
size_x: number;
|
||||
size_y: number;
|
||||
size_z: number;
|
||||
color: string;
|
||||
memo?: string;
|
||||
}
|
||||
// 나중에 구현할 데이터 바인딩 패널
|
||||
const YardElementConfigPanel = dynamic(() => import("./YardElementConfigPanel"), {
|
||||
ssr: false,
|
||||
loading: () => <div>로딩 중...</div>,
|
||||
});
|
||||
|
||||
interface YardEditorProps {
|
||||
layout: YardLayout;
|
||||
@@ -60,76 +31,94 @@ interface YardEditorProps {
|
||||
|
||||
export default function YardEditor({ layout, onBack }: YardEditorProps) {
|
||||
const [placements, setPlacements] = useState<YardPlacement[]>([]);
|
||||
const [materials, setMaterials] = useState<TempMaterial[]>([]);
|
||||
const [selectedPlacement, setSelectedPlacement] = useState<YardPlacement | null>(null);
|
||||
const [selectedMaterial, setSelectedMaterial] = useState<TempMaterial | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [showConfigPanel, setShowConfigPanel] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// 배치 목록 & 자재 목록 로드
|
||||
// 배치 목록 로드
|
||||
useEffect(() => {
|
||||
const loadData = async () => {
|
||||
const loadPlacements = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const [placementsRes, materialsRes] = await Promise.all([
|
||||
yardLayoutApi.getPlacementsByLayoutId(layout.id),
|
||||
materialApi.getTempMaterials({ limit: 100 }),
|
||||
]);
|
||||
|
||||
if (placementsRes.success) {
|
||||
setPlacements(placementsRes.data);
|
||||
}
|
||||
if (materialsRes.success) {
|
||||
setMaterials(materialsRes.data);
|
||||
const response = await yardLayoutApi.getPlacementsByLayoutId(layout.id);
|
||||
if (response.success) {
|
||||
setPlacements(response.data as YardPlacement[]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("데이터 로드 실패:", error);
|
||||
console.error("배치 목록 로드 실패:", error);
|
||||
setError("배치 목록을 불러올 수 없습니다.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadData();
|
||||
loadPlacements();
|
||||
}, [layout.id]);
|
||||
|
||||
// 자재 클릭 → 배치 추가
|
||||
const handleMaterialClick = async (material: TempMaterial) => {
|
||||
// 이미 배치되었는지 확인
|
||||
const alreadyPlaced = placements.find((p) => p.material_code === material.material_code);
|
||||
if (alreadyPlaced) {
|
||||
alert("이미 배치된 자재입니다.");
|
||||
// 빈 요소 추가
|
||||
const handleAddElement = async () => {
|
||||
try {
|
||||
const newPlacementData = {
|
||||
position_x: 0,
|
||||
position_y: 0,
|
||||
position_z: 0,
|
||||
size_x: 5,
|
||||
size_y: 5,
|
||||
size_z: 5,
|
||||
color: "#9ca3af", // 회색 (미설정 상태)
|
||||
};
|
||||
|
||||
console.log("요소 추가 요청:", { layoutId: layout.id, data: newPlacementData });
|
||||
const response = await yardLayoutApi.addMaterialPlacement(layout.id, newPlacementData);
|
||||
console.log("요소 추가 응답:", response);
|
||||
|
||||
if (response.success) {
|
||||
const newPlacement = response.data as YardPlacement;
|
||||
setPlacements((prev) => [...prev, newPlacement]);
|
||||
setSelectedPlacement(newPlacement);
|
||||
setShowConfigPanel(true); // 자동으로 설정 패널 표시
|
||||
} else {
|
||||
console.error("요소 추가 실패 (응답):", response);
|
||||
setError(response.message || "요소 추가에 실패했습니다.");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("요소 추가 실패 (예외):", error);
|
||||
setError(`요소 추가에 실패했습니다: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
};
|
||||
|
||||
// 요소 선택 (3D 캔버스 또는 목록에서)
|
||||
const handleSelectPlacement = (placement: YardPlacement) => {
|
||||
setSelectedPlacement(placement);
|
||||
setShowConfigPanel(false); // 선택 시에는 설정 패널 닫기
|
||||
};
|
||||
|
||||
// 설정 버튼 클릭
|
||||
const handleConfigClick = (placement: YardPlacement) => {
|
||||
setSelectedPlacement(placement);
|
||||
setShowConfigPanel(true);
|
||||
};
|
||||
|
||||
// 요소 삭제
|
||||
const handleDeletePlacement = async (placementId: number) => {
|
||||
if (!confirm("이 요소를 삭제하시겠습니까?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedMaterial(material);
|
||||
|
||||
// 기본 위치에 배치
|
||||
const placementData = {
|
||||
external_material_id: `TEMP-${material.id}`,
|
||||
material_code: material.material_code,
|
||||
material_name: material.material_name,
|
||||
quantity: 1,
|
||||
unit: material.unit,
|
||||
position_x: 0,
|
||||
position_y: 0,
|
||||
position_z: 0,
|
||||
size_x: 5,
|
||||
size_y: 5,
|
||||
size_z: 5,
|
||||
color: material.default_color,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await yardLayoutApi.addMaterialPlacement(layout.id, placementData);
|
||||
const response = await yardLayoutApi.removePlacement(placementId);
|
||||
if (response.success) {
|
||||
setPlacements((prev) => [...prev, response.data]);
|
||||
setSelectedPlacement(response.data);
|
||||
setSelectedMaterial(null);
|
||||
setPlacements((prev) => prev.filter((p) => p.id !== placementId));
|
||||
if (selectedPlacement?.id === placementId) {
|
||||
setSelectedPlacement(null);
|
||||
setShowConfigPanel(false);
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error("자재 배치 실패:", error);
|
||||
alert("자재 배치에 실패했습니다.");
|
||||
} catch (error) {
|
||||
console.error("요소 삭제 실패:", error);
|
||||
setError("요소 삭제에 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -141,49 +130,13 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
|
||||
position_z: Math.round(position.z * 2) / 2,
|
||||
};
|
||||
|
||||
setPlacements((prev) =>
|
||||
prev.map((p) =>
|
||||
p.id === id
|
||||
? {
|
||||
...p,
|
||||
...updatedPosition,
|
||||
}
|
||||
: p,
|
||||
),
|
||||
);
|
||||
setPlacements((prev) => prev.map((p) => (p.id === id ? { ...p, ...updatedPosition } : p)));
|
||||
|
||||
// 선택된 자재도 업데이트
|
||||
if (selectedPlacement?.id === id) {
|
||||
setSelectedPlacement((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
...updatedPosition,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
setSelectedPlacement((prev) => (prev ? { ...prev, ...updatedPosition } : null));
|
||||
}
|
||||
};
|
||||
|
||||
// 자재 배치 해제
|
||||
const handlePlacementRemove = async (id: number) => {
|
||||
try {
|
||||
const response = await yardLayoutApi.removePlacement(id);
|
||||
if (response.success) {
|
||||
setPlacements((prev) => prev.filter((p) => p.id !== id));
|
||||
setSelectedPlacement(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("배치 해제 실패:", error);
|
||||
alert("배치 해제에 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
// 위치/크기/색상 업데이트
|
||||
const handlePlacementUpdate = (id: number, updates: Partial<YardPlacement>) => {
|
||||
setPlacements((prev) => prev.map((p) => (p.id === id ? { ...p, ...updates } : p)));
|
||||
};
|
||||
|
||||
// 저장
|
||||
const handleSave = async () => {
|
||||
setIsSaving(true);
|
||||
@@ -213,12 +166,51 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
|
||||
}
|
||||
};
|
||||
|
||||
// 필터링된 자재 목록
|
||||
const filteredMaterials = materials.filter(
|
||||
(m) =>
|
||||
m.material_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
m.material_code.toLowerCase().includes(searchTerm.toLowerCase()),
|
||||
);
|
||||
// 설정 패널에서 저장
|
||||
const handleSaveConfig = async (updatedData: Partial<YardPlacement>) => {
|
||||
if (!selectedPlacement) return;
|
||||
|
||||
try {
|
||||
const response = await yardLayoutApi.updatePlacement(selectedPlacement.id, updatedData);
|
||||
if (response.success) {
|
||||
const updated = response.data as YardPlacement;
|
||||
|
||||
// 현재 위치 정보를 유지하면서 업데이트
|
||||
setPlacements((prev) =>
|
||||
prev.map((p) => {
|
||||
if (p.id === updated.id) {
|
||||
// 현재 프론트엔드 상태의 위치를 유지
|
||||
return {
|
||||
...updated,
|
||||
position_x: p.position_x,
|
||||
position_y: p.position_y,
|
||||
position_z: p.position_z,
|
||||
};
|
||||
}
|
||||
return p;
|
||||
}),
|
||||
);
|
||||
|
||||
// 선택된 요소도 동일하게 업데이트
|
||||
setSelectedPlacement({
|
||||
...updated,
|
||||
position_x: selectedPlacement.position_x,
|
||||
position_y: selectedPlacement.position_y,
|
||||
position_z: selectedPlacement.position_z,
|
||||
});
|
||||
|
||||
setShowConfigPanel(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("설정 저장 실패:", error);
|
||||
setError("설정 저장에 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
// 요소가 설정되었는지 확인
|
||||
const isConfigured = (placement: YardPlacement): boolean => {
|
||||
return !!(placement.material_name && placement.quantity && placement.unit);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col bg-white">
|
||||
@@ -250,6 +242,14 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 에러 메시지 */}
|
||||
{error && (
|
||||
<Alert variant="destructive" className="m-4">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* 메인 컨텐츠 영역 */}
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* 좌측: 3D 캔버스 */}
|
||||
@@ -262,191 +262,104 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
|
||||
<Yard3DCanvas
|
||||
placements={placements}
|
||||
selectedPlacementId={selectedPlacement?.id || null}
|
||||
onPlacementClick={setSelectedPlacement}
|
||||
onPlacementClick={(placement) => handleSelectPlacement(placement as YardPlacement)}
|
||||
onPlacementDrag={handlePlacementDrag}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 우측: 자재 목록 또는 편집 패널 */}
|
||||
{/* 우측: 요소 목록 또는 설정 패널 */}
|
||||
<div className="w-80 border-l bg-white">
|
||||
{selectedPlacement ? (
|
||||
// 선택된 자재 편집 패널
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="flex items-center justify-between border-b p-4">
|
||||
<h3 className="text-sm font-semibold">자재 정보</h3>
|
||||
<Button variant="ghost" size="sm" onClick={() => setSelectedPlacement(null)}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-auto p-4">
|
||||
<div className="space-y-4">
|
||||
{/* 읽기 전용 정보 */}
|
||||
<div>
|
||||
<Label className="text-xs text-gray-500">자재 코드</Label>
|
||||
<div className="mt-1 text-sm font-medium">{selectedPlacement.material_code}</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs text-gray-500">자재명</Label>
|
||||
<div className="mt-1 text-sm font-medium">{selectedPlacement.material_name}</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs text-gray-500">수량 (변경 불가)</Label>
|
||||
<div className="mt-1 text-sm">
|
||||
{selectedPlacement.quantity} {selectedPlacement.unit}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 편집 가능 정보 */}
|
||||
<div className="space-y-3 border-t pt-4">
|
||||
<Label className="text-sm font-semibold">배치 정보</Label>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<Label className="text-xs">X</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.5"
|
||||
value={selectedPlacement.position_x}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
position_x: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Y</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.5"
|
||||
value={selectedPlacement.position_y}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
position_y: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Z</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.5"
|
||||
value={selectedPlacement.position_z}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
position_z: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<Label className="text-xs">너비</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={selectedPlacement.size_x}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
size_x: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">높이</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={selectedPlacement.size_y}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
size_y: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">깊이</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={selectedPlacement.size_z}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
size_z: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs">색상</Label>
|
||||
<Input
|
||||
type="color"
|
||||
value={selectedPlacement.color}
|
||||
onChange={(e) => handlePlacementUpdate(selectedPlacement.id, { color: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() => handlePlacementRemove(selectedPlacement.id)}
|
||||
>
|
||||
배치 해제
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{showConfigPanel && selectedPlacement ? (
|
||||
// 설정 패널
|
||||
<YardElementConfigPanel
|
||||
placement={selectedPlacement}
|
||||
onSave={handleSaveConfig}
|
||||
onCancel={() => setShowConfigPanel(false)}
|
||||
/>
|
||||
) : (
|
||||
// 자재 목록
|
||||
// 요소 목록
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="border-b p-4">
|
||||
<h3 className="mb-2 text-sm font-semibold">자재 목록</h3>
|
||||
<Input
|
||||
placeholder="자재 검색..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="text-sm"
|
||||
/>
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold">요소 목록</h3>
|
||||
<Button size="sm" onClick={handleAddElement}>
|
||||
<Plus className="mr-1 h-4 w-4" />
|
||||
요소 추가
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">총 {placements.length}개</p>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-auto">
|
||||
{filteredMaterials.length === 0 ? (
|
||||
<div className="flex-1 overflow-auto p-2">
|
||||
{placements.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center p-4 text-center text-sm text-gray-500">
|
||||
검색 결과가 없습니다
|
||||
요소가 없습니다.
|
||||
<br />
|
||||
{'위의 "요소 추가" 버튼을 클릭하세요.'}
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-2">
|
||||
{filteredMaterials.map((material) => {
|
||||
const isPlaced = placements.some((p) => p.material_code === material.material_code);
|
||||
<div className="space-y-2">
|
||||
{placements.map((placement) => {
|
||||
const configured = isConfigured(placement);
|
||||
const isSelected = selectedPlacement?.id === placement.id;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={material.id}
|
||||
onClick={() => !isPlaced && handleMaterialClick(material)}
|
||||
disabled={isPlaced}
|
||||
className={`mb-2 w-full rounded-lg border p-3 text-left transition-all ${
|
||||
isPlaced
|
||||
? "cursor-not-allowed border-gray-200 bg-gray-50 opacity-50"
|
||||
: "cursor-pointer border-gray-200 bg-white hover:border-blue-500 hover:shadow-sm"
|
||||
<div
|
||||
key={placement.id}
|
||||
className={`rounded-lg border p-3 transition-all ${
|
||||
isSelected
|
||||
? "border-blue-500 bg-blue-50"
|
||||
: configured
|
||||
? "border-gray-200 bg-white hover:border-gray-300"
|
||||
: "border-orange-200 bg-orange-50"
|
||||
}`}
|
||||
onClick={() => handleSelectPlacement(placement)}
|
||||
>
|
||||
<div className="mb-1 text-sm font-medium text-gray-900">{material.material_name}</div>
|
||||
<div className="text-xs text-gray-500">{material.material_code}</div>
|
||||
<div className="mt-1 text-xs text-gray-400">{material.category}</div>
|
||||
{isPlaced && <div className="mt-1 text-xs text-blue-600">배치됨</div>}
|
||||
</button>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1">
|
||||
{configured ? (
|
||||
<>
|
||||
<div className="text-sm font-medium text-gray-900">{placement.material_name}</div>
|
||||
<div className="mt-1 text-xs text-gray-500">
|
||||
수량: {placement.quantity} {placement.unit}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-sm font-medium text-orange-700">요소 #{placement.id}</div>
|
||||
<div className="mt-1 text-xs text-orange-600">데이터 바인딩 설정 필요</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleConfigClick(placement);
|
||||
}}
|
||||
>
|
||||
<Settings className="mr-1 h-3 w-3" />
|
||||
{configured ? "편집" : "설정"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-600 hover:bg-red-50"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleDeletePlacement(placement.id);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,554 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ArrowLeft, Loader2, Play } from "lucide-react";
|
||||
import { YardPlacement, YardDataSourceConfig, YardDataBinding, QueryResult } from "./types";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
import { dashboardApi } from "@/lib/api/dashboard";
|
||||
import { ExternalDbConnectionAPI, type ExternalDbConnection } from "@/lib/api/externalDbConnection";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
|
||||
interface YardElementConfigPanelProps {
|
||||
placement: YardPlacement;
|
||||
onSave: (updatedData: Partial<YardPlacement>) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export default function YardElementConfigPanel({ placement, onSave, onCancel }: YardElementConfigPanelProps) {
|
||||
// 데이터 소스 설정
|
||||
const [dataSourceType, setDataSourceType] = useState<"database" | "external_db" | "rest_api">(
|
||||
(placement.data_source_config?.type as "database" | "external_db" | "rest_api") || "database",
|
||||
);
|
||||
const [query, setQuery] = useState(placement.data_source_config?.query || "");
|
||||
const [externalConnectionId, setExternalConnectionId] = useState<string>(
|
||||
placement.data_source_config?.connectionId?.toString() || "",
|
||||
);
|
||||
const [externalConnections, setExternalConnections] = useState<ExternalDbConnection[]>([]);
|
||||
|
||||
// REST API 설정
|
||||
const [apiUrl, setApiUrl] = useState(placement.data_source_config?.url || "");
|
||||
const [apiMethod, setApiMethod] = useState<"GET" | "POST">(placement.data_source_config?.method || "GET");
|
||||
const [apiDataPath, setApiDataPath] = useState(placement.data_source_config?.dataPath || "");
|
||||
|
||||
// 쿼리 결과 및 매핑
|
||||
const [queryResult, setQueryResult] = useState<QueryResult | null>(null);
|
||||
const [isExecuting, setIsExecuting] = useState(false);
|
||||
const [selectedRowIndex, setSelectedRowIndex] = useState<number>(placement.data_binding?.selectedRowIndex ?? 0);
|
||||
const [materialNameField, setMaterialNameField] = useState(placement.data_binding?.materialNameField || "");
|
||||
const [quantityField, setQuantityField] = useState(placement.data_binding?.quantityField || "");
|
||||
const [unit, setUnit] = useState(placement.data_binding?.unit || "EA");
|
||||
|
||||
// 배치 설정
|
||||
const [color, setColor] = useState(placement.color || "#3b82f6");
|
||||
const [sizeX, setSizeX] = useState(placement.size_x);
|
||||
const [sizeY, setSizeY] = useState(placement.size_y);
|
||||
const [sizeZ, setSizeZ] = useState(placement.size_z);
|
||||
|
||||
// 에러 및 로딩
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
// 외부 DB 커넥션 목록 로드
|
||||
useEffect(() => {
|
||||
const loadConnections = async () => {
|
||||
try {
|
||||
const connections = await ExternalDbConnectionAPI.getConnections();
|
||||
setExternalConnections(connections || []);
|
||||
} catch (err) {
|
||||
console.error("외부 DB 커넥션 로드 실패:", err);
|
||||
}
|
||||
};
|
||||
|
||||
if (dataSourceType === "external_db") {
|
||||
loadConnections();
|
||||
}
|
||||
}, [dataSourceType]);
|
||||
|
||||
// 쿼리 실행
|
||||
const executeQuery = async () => {
|
||||
if (!query.trim()) {
|
||||
setError("쿼리를 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (dataSourceType === "external_db" && !externalConnectionId) {
|
||||
setError("외부 DB 커넥션을 선택해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsExecuting(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
let apiResult: { columns: string[]; rows: Record<string, unknown>[]; rowCount: number };
|
||||
|
||||
if (dataSourceType === "external_db" && externalConnectionId) {
|
||||
const result = await ExternalDbConnectionAPI.executeQuery(parseInt(externalConnectionId), query.trim());
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.message || "외부 DB 쿼리 실행에 실패했습니다.");
|
||||
}
|
||||
|
||||
apiResult = {
|
||||
columns: result.data?.[0] ? Object.keys(result.data[0]) : [],
|
||||
rows: result.data || [],
|
||||
rowCount: result.data?.length || 0,
|
||||
};
|
||||
} else {
|
||||
apiResult = await dashboardApi.executeQuery(query.trim());
|
||||
}
|
||||
|
||||
setQueryResult({
|
||||
columns: apiResult.columns,
|
||||
rows: apiResult.rows,
|
||||
totalRows: apiResult.rowCount,
|
||||
});
|
||||
|
||||
// 자동으로 첫 번째 필드 선택
|
||||
if (apiResult.columns.length > 0) {
|
||||
if (!materialNameField) setMaterialNameField(apiResult.columns[0]);
|
||||
if (!quantityField && apiResult.columns.length > 1) setQuantityField(apiResult.columns[1]);
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : "쿼리 실행 중 오류가 발생했습니다.";
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// REST API 호출
|
||||
const executeRestApi = async () => {
|
||||
if (!apiUrl.trim()) {
|
||||
setError("API URL을 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsExecuting(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(apiUrl, {
|
||||
method: apiMethod,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API 호출 실패: ${response.status}`);
|
||||
}
|
||||
|
||||
let data = await response.json();
|
||||
|
||||
// dataPath가 있으면 해당 경로의 데이터 추출
|
||||
if (apiDataPath) {
|
||||
const pathParts = apiDataPath.split(".");
|
||||
for (const part of pathParts) {
|
||||
data = data[part];
|
||||
}
|
||||
}
|
||||
|
||||
// 배열이 아니면 배열로 변환
|
||||
if (!Array.isArray(data)) {
|
||||
data = [data];
|
||||
}
|
||||
|
||||
const columns = data.length > 0 ? Object.keys(data[0]) : [];
|
||||
|
||||
setQueryResult({
|
||||
columns,
|
||||
rows: data,
|
||||
totalRows: data.length,
|
||||
});
|
||||
|
||||
// 자동으로 첫 번째 필드 선택
|
||||
if (columns.length > 0) {
|
||||
if (!materialNameField) setMaterialNameField(columns[0]);
|
||||
if (!quantityField && columns.length > 1) setQuantityField(columns[1]);
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : "API 호출 중 오류가 발생했습니다.";
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 저장
|
||||
const handleSave = async () => {
|
||||
// 검증
|
||||
if (!queryResult) {
|
||||
setError("먼저 데이터를 조회해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!materialNameField || !quantityField) {
|
||||
setError("자재명과 수량 필드를 선택해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!unit.trim()) {
|
||||
setError("단위를 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedRowIndex >= queryResult.rows.length) {
|
||||
setError("선택한 행이 유효하지 않습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
|
||||
try {
|
||||
const selectedRow = queryResult.rows[selectedRowIndex];
|
||||
const materialName = selectedRow[materialNameField];
|
||||
const quantity = selectedRow[quantityField];
|
||||
|
||||
const dataSourceConfig: YardDataSourceConfig = {
|
||||
type: dataSourceType,
|
||||
query: dataSourceType !== "rest_api" ? query : undefined,
|
||||
connectionId: dataSourceType === "external_db" ? parseInt(externalConnectionId) : undefined,
|
||||
url: dataSourceType === "rest_api" ? apiUrl : undefined,
|
||||
method: dataSourceType === "rest_api" ? apiMethod : undefined,
|
||||
dataPath: dataSourceType === "rest_api" && apiDataPath ? apiDataPath : undefined,
|
||||
};
|
||||
|
||||
const dataBinding: YardDataBinding = {
|
||||
selectedRowIndex,
|
||||
materialNameField,
|
||||
quantityField,
|
||||
unit: unit.trim(),
|
||||
};
|
||||
|
||||
const updatedData: Partial<YardPlacement> = {
|
||||
material_name: String(materialName),
|
||||
quantity: Number(quantity),
|
||||
unit: unit.trim(),
|
||||
color,
|
||||
size_x: sizeX,
|
||||
size_y: sizeY,
|
||||
size_z: sizeZ,
|
||||
data_source_type: dataSourceType,
|
||||
data_source_config: dataSourceConfig,
|
||||
data_binding: dataBinding,
|
||||
};
|
||||
|
||||
await onSave(updatedData);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : "저장 중 오류가 발생했습니다.";
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
{/* 헤더 */}
|
||||
<div className="flex items-center justify-between border-b p-4">
|
||||
<h3 className="text-sm font-semibold">데이터 바인딩 설정</h3>
|
||||
<Button variant="ghost" size="sm" onClick={onCancel}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
목록으로
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 에러 메시지 */}
|
||||
{error && (
|
||||
<Alert variant="destructive" className="m-4">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* 컨텐츠 */}
|
||||
<div className="flex-1 overflow-auto p-4">
|
||||
<div className="space-y-6">
|
||||
{/* 1단계: 데이터 소스 선택 */}
|
||||
<Card className="p-4">
|
||||
<h4 className="mb-3 text-sm font-semibold">1단계: 데이터 소스 선택</h4>
|
||||
|
||||
<RadioGroup
|
||||
value={dataSourceType}
|
||||
onValueChange={(value) => setDataSourceType(value as "database" | "external_db" | "rest_api")}
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="database" id="db" />
|
||||
<Label htmlFor="db">현재 DB</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="external_db" id="external" />
|
||||
<Label htmlFor="external">외부 DB</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="rest_api" id="api" />
|
||||
<Label htmlFor="api">REST API</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
|
||||
<div className="mt-4 space-y-3">
|
||||
{/* 현재 DB 또는 외부 DB */}
|
||||
{dataSourceType !== "rest_api" && (
|
||||
<>
|
||||
{dataSourceType === "external_db" && (
|
||||
<div>
|
||||
<Label className="text-xs">외부 DB 커넥션</Label>
|
||||
<Select value={externalConnectionId} onValueChange={setExternalConnectionId}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="커넥션 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="z-[9999]">
|
||||
{externalConnections.map((conn) => (
|
||||
<SelectItem key={conn.id} value={String(conn.id)}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{conn.connection_name}</span>
|
||||
<span className="text-xs text-gray-500">({conn.db_type.toUpperCase()})</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Label className="text-xs">SQL 쿼리</Label>
|
||||
<Textarea
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="SELECT material_name, quantity FROM inventory"
|
||||
className="mt-1 h-24 resize-none font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button onClick={executeQuery} disabled={isExecuting} size="sm" className="w-full">
|
||||
{isExecuting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
실행 중...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="mr-2 h-4 w-4" />
|
||||
실행
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* REST API */}
|
||||
{dataSourceType === "rest_api" && (
|
||||
<>
|
||||
<div>
|
||||
<Label className="text-xs">API URL</Label>
|
||||
<Input
|
||||
value={apiUrl}
|
||||
onChange={(e) => setApiUrl(e.target.value)}
|
||||
placeholder="https://api.example.com/materials"
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs">Method</Label>
|
||||
<Select value={apiMethod} onValueChange={(value) => setApiMethod(value as "GET" | "POST")}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="GET">GET</SelectItem>
|
||||
<SelectItem value="POST">POST</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs">데이터 경로 (옵션)</Label>
|
||||
<Input
|
||||
value={apiDataPath}
|
||||
onChange={(e) => setApiDataPath(e.target.value)}
|
||||
placeholder="data.items"
|
||||
className="mt-1"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">예: data.items (응답에서 배열이 있는 경로)</p>
|
||||
</div>
|
||||
|
||||
<Button onClick={executeRestApi} disabled={isExecuting} size="sm" className="w-full">
|
||||
{isExecuting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
호출 중...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="mr-2 h-4 w-4" />
|
||||
호출
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* 2단계: 쿼리 결과 및 필드 매핑 */}
|
||||
{queryResult && (
|
||||
<Card className="p-4">
|
||||
<h4 className="mb-3 text-sm font-semibold">2단계: 데이터 선택 및 필드 매핑</h4>
|
||||
|
||||
<div className="mb-3">
|
||||
<Label className="text-xs">쿼리 결과 ({queryResult.totalRows}행)</Label>
|
||||
<div className="mt-2 max-h-40 overflow-auto rounded border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-12">선택</TableHead>
|
||||
{queryResult.columns.map((col, idx) => (
|
||||
<TableHead key={idx}>{col}</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{queryResult.rows.slice(0, 10).map((row, idx) => (
|
||||
<TableRow
|
||||
key={idx}
|
||||
className={selectedRowIndex === idx ? "bg-blue-50" : ""}
|
||||
onClick={() => setSelectedRowIndex(idx)}
|
||||
>
|
||||
<TableCell>
|
||||
<input
|
||||
type="radio"
|
||||
checked={selectedRowIndex === idx}
|
||||
onChange={() => setSelectedRowIndex(idx)}
|
||||
/>
|
||||
</TableCell>
|
||||
{queryResult.columns.map((col, colIdx) => (
|
||||
<TableCell key={colIdx}>{String(row[col] ?? "")}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
{queryResult.rows.length > 10 && (
|
||||
<p className="mt-2 text-xs text-gray-500">... 및 {queryResult.rows.length - 10}개 더</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<Label className="text-xs">자재명 필드</Label>
|
||||
<Select value={materialNameField} onValueChange={setMaterialNameField}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="필드 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{queryResult.columns.map((col) => (
|
||||
<SelectItem key={col} value={col}>
|
||||
{col}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs">수량 필드</Label>
|
||||
<Select value={quantityField} onValueChange={setQuantityField}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="필드 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{queryResult.columns.map((col) => (
|
||||
<SelectItem key={col} value={col}>
|
||||
{col}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs">단위 입력</Label>
|
||||
<Input value={unit} onChange={(e) => setUnit(e.target.value)} placeholder="EA" className="mt-1" />
|
||||
<p className="mt-1 text-xs text-gray-500">예: EA, BOX, KG, M, L 등</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 3단계: 배치 설정 */}
|
||||
<Card className="p-4">
|
||||
<h4 className="mb-3 text-sm font-semibold">3단계: 배치 설정</h4>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<Label className="text-xs">색상</Label>
|
||||
<Input type="color" value={color} onChange={(e) => setColor(e.target.value)} className="mt-1" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs">크기</Label>
|
||||
<div className="mt-1 grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<Label className="text-xs">너비</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={sizeX}
|
||||
onChange={(e) => setSizeX(parseFloat(e.target.value) || 1)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">높이</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={sizeY}
|
||||
onChange={(e) => setSizeY(parseFloat(e.target.value) || 1)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">깊이</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={sizeZ}
|
||||
onChange={(e) => setSizeZ(parseFloat(e.target.value) || 1)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 하단 버튼 */}
|
||||
<div className="border-t p-4">
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={onCancel} className="flex-1">
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={isSaving || !queryResult} className="flex-1">
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
저장 중...
|
||||
</>
|
||||
) : (
|
||||
"저장"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,18 +12,17 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Loader2, AlertCircle } from "lucide-react";
|
||||
|
||||
interface YardLayoutCreateModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onCreate: (name: string, description: string) => Promise<void>;
|
||||
onCreate: (name: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export default function YardLayoutCreateModal({ isOpen, onClose, onCreate }: YardLayoutCreateModalProps) {
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
@@ -38,9 +37,8 @@ export default function YardLayoutCreateModal({ isOpen, onClose, onCreate }: Yar
|
||||
setError("");
|
||||
|
||||
try {
|
||||
await onCreate(name.trim(), description.trim());
|
||||
await onCreate(name.trim());
|
||||
setName("");
|
||||
setDescription("");
|
||||
} catch (error: any) {
|
||||
console.error("야드 생성 실패:", error);
|
||||
setError(error.message || "야드 생성에 실패했습니다");
|
||||
@@ -53,7 +51,6 @@ export default function YardLayoutCreateModal({ isOpen, onClose, onCreate }: Yar
|
||||
const handleClose = () => {
|
||||
if (isCreating) return;
|
||||
setName("");
|
||||
setDescription("");
|
||||
setError("");
|
||||
onClose();
|
||||
};
|
||||
@@ -68,14 +65,13 @@ export default function YardLayoutCreateModal({ isOpen, onClose, onCreate }: Yar
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleClose}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogContent className="sm:max-w-[500px]" onPointerDown={(e) => e.stopPropagation()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>새 야드 생성</DialogTitle>
|
||||
<DialogDescription>야드의 이름과 설명을 입력하세요</DialogDescription>
|
||||
<DialogDescription>야드 이름을 입력하세요</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{/* 야드 이름 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="yard-name">
|
||||
야드 이름 <span className="text-red-500">*</span>
|
||||
@@ -94,21 +90,12 @@ export default function YardLayoutCreateModal({ isOpen, onClose, onCreate }: Yar
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 설명 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="yard-description">설명</Label>
|
||||
<Textarea
|
||||
id="yard-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="야드에 대한 설명을 입력하세요 (선택사항)"
|
||||
rows={3}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 에러 메시지 */}
|
||||
{error && <div className="rounded-md bg-red-50 p-3 text-sm text-red-600">{error}</div>}
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
|
||||
86
frontend/components/admin/dashboard/widgets/yard-3d/types.ts
Normal file
86
frontend/components/admin/dashboard/widgets/yard-3d/types.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
// 야드 관리 3D - 타입 정의
|
||||
|
||||
import { ChartDataSource } from "../../types";
|
||||
|
||||
// 야드 레이아웃
|
||||
export interface YardLayout {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string;
|
||||
placement_count?: number;
|
||||
created_by?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
// 데이터 소스 설정
|
||||
export interface YardDataSourceConfig {
|
||||
type: "database" | "external_db" | "rest_api";
|
||||
|
||||
// type === 'database' (현재 DB)
|
||||
query?: string;
|
||||
|
||||
// type === 'external_db' (외부 DB)
|
||||
connectionId?: number;
|
||||
|
||||
// type === 'rest_api'
|
||||
url?: string;
|
||||
method?: "GET" | "POST";
|
||||
headers?: Record<string, string>;
|
||||
queryParams?: Record<string, string>;
|
||||
body?: string;
|
||||
dataPath?: string; // 응답에서 데이터 배열 경로
|
||||
}
|
||||
|
||||
// 데이터 바인딩 설정
|
||||
export interface YardDataBinding {
|
||||
// 데이터 소스의 특정 행 선택
|
||||
selectedRowIndex?: number;
|
||||
|
||||
// 필드 매핑 (데이터 소스에서 선택)
|
||||
materialNameField?: string; // 자재명이 들어있는 컬럼명
|
||||
quantityField?: string; // 수량이 들어있는 컬럼명
|
||||
|
||||
// 단위는 사용자가 직접 입력
|
||||
unit: string; // 예: "EA", "BOX", "KG", "M" 등
|
||||
}
|
||||
|
||||
// 자재 배치 정보
|
||||
export interface YardPlacement {
|
||||
id: number;
|
||||
yard_layout_id: number;
|
||||
material_code?: string | null;
|
||||
material_name?: string | null;
|
||||
quantity?: number | null;
|
||||
unit?: string | null;
|
||||
position_x: number;
|
||||
position_y: number;
|
||||
position_z: number;
|
||||
size_x: number;
|
||||
size_y: number;
|
||||
size_z: number;
|
||||
color: string;
|
||||
data_source_type?: string | null;
|
||||
data_source_config?: YardDataSourceConfig | null;
|
||||
data_binding?: YardDataBinding | null;
|
||||
memo?: string | null;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
// 쿼리 결과 (데이터 바인딩용)
|
||||
export interface QueryResult {
|
||||
columns: string[];
|
||||
rows: Record<string, any>[];
|
||||
totalRows: number;
|
||||
}
|
||||
|
||||
// 요소 설정 단계
|
||||
export type ConfigStep = "data-source" | "field-mapping" | "placement-settings";
|
||||
|
||||
// 설정 모달 props
|
||||
export interface YardElementConfigPanelProps {
|
||||
placement: YardPlacement;
|
||||
onSave: (updatedPlacement: Partial<YardPlacement>) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
}
|
||||
@@ -57,28 +57,3 @@ export const yardLayoutApi = {
|
||||
return apiCall("PUT", `/yard-layouts/${layoutId}/placements/batch`, { placements });
|
||||
},
|
||||
};
|
||||
|
||||
// 자재 관리 API
|
||||
export const materialApi = {
|
||||
// 임시 자재 마스터 목록 조회
|
||||
async getTempMaterials(params?: { search?: string; category?: string; page?: number; limit?: number }) {
|
||||
const queryParams = new URLSearchParams();
|
||||
if (params?.search) queryParams.append("search", params.search);
|
||||
if (params?.category) queryParams.append("category", params.category);
|
||||
if (params?.page) queryParams.append("page", params.page.toString());
|
||||
if (params?.limit) queryParams.append("limit", params.limit.toString());
|
||||
|
||||
const queryString = queryParams.toString();
|
||||
return apiCall("GET", `/materials/temp${queryString ? `?${queryString}` : ""}`);
|
||||
},
|
||||
|
||||
// 특정 자재 상세 조회
|
||||
async getTempMaterialByCode(code: string) {
|
||||
return apiCall("GET", `/materials/temp/${code}`);
|
||||
},
|
||||
|
||||
// 카테고리 목록 조회
|
||||
async getCategories() {
|
||||
return apiCall("GET", "/materials/temp/categories");
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user