사이드바 방식으로 변경
This commit is contained in:
parent
85987af65e
commit
01ebb2550c
|
|
@ -5,8 +5,6 @@ import { useRouter } from "next/navigation";
|
|||
import { DashboardCanvas } from "./DashboardCanvas";
|
||||
import { DashboardTopMenu } from "./DashboardTopMenu";
|
||||
import { ElementConfigSidebar } from "./ElementConfigSidebar";
|
||||
import { ListWidgetConfigModal } from "./widgets/ListWidgetConfigModal";
|
||||
import { YardWidgetConfigModal } from "./widgets/YardWidgetConfigModal";
|
||||
import { DashboardSaveModal } from "./DashboardSaveModal";
|
||||
import { DashboardElement, ElementType, ElementSubtype } from "./types";
|
||||
import { GRID_CONFIG, snapToGrid, snapSizeToGrid, calculateCellSize } from "./gridUtils";
|
||||
|
|
@ -293,8 +291,13 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
if (selectedElement === id) {
|
||||
setSelectedElement(null);
|
||||
}
|
||||
// 삭제된 요소의 사이드바가 열려있으면 닫기
|
||||
if (sidebarElement?.id === id) {
|
||||
setSidebarOpen(false);
|
||||
setSidebarElement(null);
|
||||
}
|
||||
},
|
||||
[selectedElement],
|
||||
[selectedElement, sidebarElement],
|
||||
);
|
||||
|
||||
// 키보드 단축키 핸들러들
|
||||
|
|
@ -568,14 +571,8 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
// 선택된 요소 찾아서 사이드바 열기
|
||||
const element = elements.find((el) => el.id === id);
|
||||
if (element) {
|
||||
// 리스트/야드 위젯은 별도 모달 사용
|
||||
if (element.subtype === "list" || element.subtype === "yard-management-3d") {
|
||||
setSidebarElement(element);
|
||||
setSidebarOpen(false);
|
||||
} else {
|
||||
setSidebarElement(element);
|
||||
setSidebarOpen(true);
|
||||
}
|
||||
setSidebarElement(element);
|
||||
setSidebarOpen(true);
|
||||
}
|
||||
}}
|
||||
onSelectMultiple={(ids) => {
|
||||
|
|
@ -592,7 +589,7 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* 요소 설정 사이드바 */}
|
||||
{/* 요소 설정 사이드바 (리스트/야드 위젯 포함) */}
|
||||
<ElementConfigSidebar
|
||||
element={sidebarElement}
|
||||
isOpen={sidebarOpen}
|
||||
|
|
@ -600,32 +597,6 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
onApply={handleApplySidebar}
|
||||
/>
|
||||
|
||||
{/* 리스트 위젯 전용 모달 */}
|
||||
{sidebarElement && sidebarElement.subtype === "list" && (
|
||||
<ListWidgetConfigModal
|
||||
element={sidebarElement}
|
||||
isOpen={true}
|
||||
onClose={() => {
|
||||
setSidebarElement(null);
|
||||
setSelectedElement(null);
|
||||
}}
|
||||
onSave={saveWidgetConfig}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 야드 위젯 전용 모달 */}
|
||||
{sidebarElement && sidebarElement.subtype === "yard-management-3d" && (
|
||||
<YardWidgetConfigModal
|
||||
element={sidebarElement}
|
||||
isOpen={true}
|
||||
onClose={() => {
|
||||
setSidebarElement(null);
|
||||
setSelectedElement(null);
|
||||
}}
|
||||
onSave={saveWidgetConfig}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 저장 모달 */}
|
||||
<DashboardSaveModal
|
||||
isOpen={saveModalOpen}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@ import { ChartConfigPanel } from "./ChartConfigPanel";
|
|||
import { VehicleMapConfigPanel } from "./VehicleMapConfigPanel";
|
||||
import { DatabaseConfig } from "./data-sources/DatabaseConfig";
|
||||
import { ApiConfig } from "./data-sources/ApiConfig";
|
||||
import { ListWidgetConfigSidebar } from "./widgets/ListWidgetConfigSidebar";
|
||||
import { YardWidgetConfigModal } from "./widgets/YardWidgetConfigModal";
|
||||
import { X } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
|
|
@ -115,6 +117,34 @@ export function ElementConfigSidebar({ element, isOpen, onClose, onApply }: Elem
|
|||
// 요소가 없으면 렌더링하지 않음
|
||||
if (!element) return null;
|
||||
|
||||
// 리스트 위젯은 별도 사이드바로 처리
|
||||
if (element.subtype === "list") {
|
||||
return (
|
||||
<ListWidgetConfigSidebar
|
||||
element={element}
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
onApply={(updatedElement) => {
|
||||
onApply(updatedElement);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// 야드 위젯은 별도 모달로 처리
|
||||
if (element.subtype === "yard-management-3d") {
|
||||
return (
|
||||
<YardWidgetConfigModal
|
||||
element={element}
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
onSave={(updatedElement) => {
|
||||
onApply({ ...element, ...updatedElement });
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// 차트 설정이 필요 없는 위젯 (쿼리/API만 필요)
|
||||
const isSimpleWidget =
|
||||
element.subtype === "todo" ||
|
||||
|
|
|
|||
|
|
@ -29,13 +29,13 @@ export function VehicleMapConfigPanel({ config, queryResult, onConfigChange }: V
|
|||
const sampleData = queryResult?.rows?.[0] || {};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-lg font-semibold text-gray-800">🗺️ 지도 설정</h4>
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-xs font-semibold text-gray-800">🗺️ 지도 설정</h4>
|
||||
|
||||
{/* 쿼리 결과가 없을 때 */}
|
||||
{!queryResult && (
|
||||
<div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
|
||||
<div className="text-yellow-800 text-sm">
|
||||
<div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
|
||||
<div className="text-yellow-800 text-xs">
|
||||
💡 먼저 SQL 쿼리를 실행하여 데이터를 가져온 후 지도를 설정할 수 있습니다.
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -45,27 +45,27 @@ export function VehicleMapConfigPanel({ config, queryResult, onConfigChange }: V
|
|||
{queryResult && (
|
||||
<>
|
||||
{/* 지도 제목 */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">지도 제목</label>
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-xs font-medium text-gray-700">지도 제목</label>
|
||||
<input
|
||||
type="text"
|
||||
value={currentConfig.title || ''}
|
||||
onChange={(e) => updateConfig({ title: e.target.value })}
|
||||
placeholder="차량 위치 지도"
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
|
||||
className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-xs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 위도 컬럼 설정 */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-xs font-medium text-gray-700">
|
||||
위도 컬럼 (Latitude)
|
||||
<span className="text-red-500 ml-1">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={currentConfig.latitudeColumn || ''}
|
||||
onChange={(e) => updateConfig({ latitudeColumn: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
|
||||
className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-xs"
|
||||
>
|
||||
<option value="">선택하세요</option>
|
||||
{availableColumns.map((col) => (
|
||||
|
|
@ -77,15 +77,15 @@ export function VehicleMapConfigPanel({ config, queryResult, onConfigChange }: V
|
|||
</div>
|
||||
|
||||
{/* 경도 컬럼 설정 */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-xs font-medium text-gray-700">
|
||||
경도 컬럼 (Longitude)
|
||||
<span className="text-red-500 ml-1">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={currentConfig.longitudeColumn || ''}
|
||||
onChange={(e) => updateConfig({ longitudeColumn: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
|
||||
className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-xs"
|
||||
>
|
||||
<option value="">선택하세요</option>
|
||||
{availableColumns.map((col) => (
|
||||
|
|
@ -97,14 +97,14 @@ export function VehicleMapConfigPanel({ config, queryResult, onConfigChange }: V
|
|||
</div>
|
||||
|
||||
{/* 라벨 컬럼 (선택사항) */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-xs font-medium text-gray-700">
|
||||
라벨 컬럼 (마커 표시명)
|
||||
</label>
|
||||
<select
|
||||
value={currentConfig.labelColumn || ''}
|
||||
onChange={(e) => updateConfig({ labelColumn: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
|
||||
className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-xs"
|
||||
>
|
||||
<option value="">선택하세요 (선택사항)</option>
|
||||
{availableColumns.map((col) => (
|
||||
|
|
@ -116,14 +116,14 @@ export function VehicleMapConfigPanel({ config, queryResult, onConfigChange }: V
|
|||
</div>
|
||||
|
||||
{/* 상태 컬럼 (선택사항) */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-xs font-medium text-gray-700">
|
||||
상태 컬럼 (마커 색상)
|
||||
</label>
|
||||
<select
|
||||
value={currentConfig.statusColumn || ''}
|
||||
onChange={(e) => updateConfig({ statusColumn: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
|
||||
className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-xs"
|
||||
>
|
||||
<option value="">선택하세요 (선택사항)</option>
|
||||
{availableColumns.map((col) => (
|
||||
|
|
@ -136,7 +136,7 @@ export function VehicleMapConfigPanel({ config, queryResult, onConfigChange }: V
|
|||
|
||||
{/* 설정 미리보기 */}
|
||||
<div className="p-3 bg-gray-50 rounded-lg">
|
||||
<div className="text-sm font-medium text-gray-700 mb-2">📋 설정 미리보기</div>
|
||||
<div className="text-xs font-medium text-gray-700 mb-2">📋 설정 미리보기</div>
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
<div><strong>위도:</strong> {currentConfig.latitudeColumn || '미설정'}</div>
|
||||
<div><strong>경도:</strong> {currentConfig.longitudeColumn || '미설정'}</div>
|
||||
|
|
@ -149,7 +149,7 @@ export function VehicleMapConfigPanel({ config, queryResult, onConfigChange }: V
|
|||
{/* 필수 필드 확인 */}
|
||||
{(!currentConfig.latitudeColumn || !currentConfig.longitudeColumn) && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg">
|
||||
<div className="text-red-800 text-sm">
|
||||
<div className="text-red-800 text-xs">
|
||||
⚠️ 위도와 경도 컬럼을 반드시 선택해야 지도에 표시할 수 있습니다.
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,14 +1,13 @@
|
|||
"use client";
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { DashboardElement, QueryResult, ListWidgetConfig } from "../types";
|
||||
import { DashboardElement, QueryResult, ListColumn } from "../types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Card } from "@/components/ui/card";
|
||||
|
||||
interface ListWidgetProps {
|
||||
element: DashboardElement;
|
||||
onConfigUpdate?: (config: Partial<DashboardElement>) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -17,7 +16,7 @@ interface ListWidgetProps {
|
|||
* - 테이블 형태로 데이터 표시
|
||||
* - 페이지네이션, 정렬, 검색 기능
|
||||
*/
|
||||
export function ListWidget({ element, onConfigUpdate }: ListWidgetProps) {
|
||||
export function ListWidget({ element }: ListWidgetProps) {
|
||||
const [data, setData] = useState<QueryResult | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
|
@ -53,7 +52,7 @@ export function ListWidget({ element, onConfigUpdate }: ListWidgetProps) {
|
|||
if (element.dataSource.queryParams) {
|
||||
Object.entries(element.dataSource.queryParams).forEach(([key, value]) => {
|
||||
if (key && value) {
|
||||
params.append(key, value);
|
||||
params.append(key, String(value));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -114,13 +113,19 @@ export function ListWidget({ element, onConfigUpdate }: ListWidgetProps) {
|
|||
parseInt(element.dataSource.externalConnectionId),
|
||||
element.dataSource.query,
|
||||
);
|
||||
if (!externalResult.success) {
|
||||
if (!externalResult.success || !externalResult.data) {
|
||||
throw new Error(externalResult.message || "외부 DB 쿼리 실행 실패");
|
||||
}
|
||||
|
||||
const resultData = externalResult.data as unknown as {
|
||||
columns: string[];
|
||||
rows: Record<string, unknown>[];
|
||||
rowCount: number;
|
||||
};
|
||||
queryResult = {
|
||||
columns: externalResult.data.columns,
|
||||
rows: externalResult.data.rows,
|
||||
totalRows: externalResult.data.rowCount,
|
||||
columns: resultData.columns,
|
||||
rows: resultData.rows,
|
||||
totalRows: resultData.rowCount,
|
||||
executionTime: 0,
|
||||
};
|
||||
} else {
|
||||
|
|
@ -154,13 +159,7 @@ export function ListWidget({ element, onConfigUpdate }: ListWidgetProps) {
|
|||
const interval = setInterval(loadData, refreshInterval);
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
}, [
|
||||
element.dataSource?.query,
|
||||
element.dataSource?.connectionType,
|
||||
element.dataSource?.externalConnectionId,
|
||||
element.dataSource?.endpoint,
|
||||
element.dataSource?.refreshInterval,
|
||||
]);
|
||||
}, [element.dataSource]);
|
||||
|
||||
// 로딩 중
|
||||
if (isLoading) {
|
||||
|
|
@ -192,23 +191,22 @@ export function ListWidget({ element, onConfigUpdate }: ListWidgetProps) {
|
|||
return (
|
||||
<div className="flex h-full w-full flex-col items-center justify-center gap-4 p-4">
|
||||
<div className="text-center">
|
||||
<div className="mb-2 text-4xl">📋</div>
|
||||
<div className="text-sm font-medium text-gray-700">리스트를 설정하세요</div>
|
||||
<div className="mt-1 text-xs text-gray-500">⚙️ 버튼을 클릭하여 데이터 소스와 컬럼을 설정해주세요</div>
|
||||
<div className="mt-1 text-xs text-gray-500">데이터와 컬럼을 설정해주세요</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 컬럼 설정이 없으면 자동으로 모든 컬럼 표시
|
||||
const displayColumns =
|
||||
const displayColumns: ListColumn[] =
|
||||
config.columns.length > 0
|
||||
? config.columns
|
||||
: data.columns.map((col) => ({
|
||||
id: col,
|
||||
name: col,
|
||||
dataKey: col,
|
||||
label: col,
|
||||
field: col,
|
||||
visible: true,
|
||||
align: "left" as const,
|
||||
}));
|
||||
|
||||
// 페이지네이션
|
||||
|
|
@ -239,7 +237,7 @@ export function ListWidget({ element, onConfigUpdate }: ListWidgetProps) {
|
|||
className={col.align === "center" ? "text-center" : col.align === "right" ? "text-right" : ""}
|
||||
style={{ width: col.width ? `${col.width}px` : undefined }}
|
||||
>
|
||||
{col.label || col.name}
|
||||
{col.label}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
|
|
@ -265,7 +263,7 @@ export function ListWidget({ element, onConfigUpdate }: ListWidgetProps) {
|
|||
key={col.id}
|
||||
className={col.align === "center" ? "text-center" : col.align === "right" ? "text-right" : ""}
|
||||
>
|
||||
{String(row[col.dataKey || col.field] ?? "")}
|
||||
{String(row[col.field] ?? "")}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
|
|
@ -295,11 +293,11 @@ export function ListWidget({ element, onConfigUpdate }: ListWidgetProps) {
|
|||
.filter((col) => col.visible)
|
||||
.map((col) => (
|
||||
<div key={col.id}>
|
||||
<div className="text-xs font-medium text-gray-500">{col.label || col.name}</div>
|
||||
<div className="text-xs font-medium text-gray-500">{col.label}</div>
|
||||
<div
|
||||
className={`font-medium text-gray-900 ${col.align === "center" ? "text-center" : col.align === "right" ? "text-right" : ""}`}
|
||||
>
|
||||
{String(row[col.dataKey || col.field] ?? "")}
|
||||
{String(row[col.field] ?? "")}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,298 @@
|
|||
"use client";
|
||||
|
||||
import React, { useState, useCallback, useEffect } from "react";
|
||||
import { DashboardElement, ChartDataSource, QueryResult, ListWidgetConfig } from "../types";
|
||||
import { X } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { DatabaseConfig } from "../data-sources/DatabaseConfig";
|
||||
import { ApiConfig } from "../data-sources/ApiConfig";
|
||||
import { QueryEditor } from "../QueryEditor";
|
||||
import { ColumnSelector } from "./list-widget/ColumnSelector";
|
||||
import { ManualColumnEditor } from "./list-widget/ManualColumnEditor";
|
||||
import { ListTableOptions } from "./list-widget/ListTableOptions";
|
||||
|
||||
interface ListWidgetConfigSidebarProps {
|
||||
element: DashboardElement;
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onApply: (element: DashboardElement) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 리스트 위젯 설정 사이드바
|
||||
*/
|
||||
export function ListWidgetConfigSidebar({ element, isOpen, onClose, onApply }: ListWidgetConfigSidebarProps) {
|
||||
const [title, setTitle] = useState(element.title || "📋 리스트");
|
||||
const [dataSource, setDataSource] = useState<ChartDataSource>(
|
||||
element.dataSource || { type: "database", connectionType: "current", refreshInterval: 0 },
|
||||
);
|
||||
const [queryResult, setQueryResult] = useState<QueryResult | null>(null);
|
||||
const [listConfig, setListConfig] = useState<ListWidgetConfig>(
|
||||
element.listConfig || {
|
||||
columnMode: "auto",
|
||||
viewMode: "table",
|
||||
columns: [],
|
||||
pageSize: 10,
|
||||
enablePagination: true,
|
||||
showHeader: true,
|
||||
stripedRows: true,
|
||||
compactMode: false,
|
||||
cardColumns: 3,
|
||||
},
|
||||
);
|
||||
|
||||
// 사이드바 열릴 때 초기화
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setTitle(element.title || "📋 리스트");
|
||||
if (element.dataSource) {
|
||||
setDataSource(element.dataSource);
|
||||
}
|
||||
if (element.listConfig) {
|
||||
setListConfig(element.listConfig);
|
||||
}
|
||||
}
|
||||
}, [isOpen, element]);
|
||||
|
||||
// Esc 키로 닫기
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleEsc = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleEsc);
|
||||
return () => window.removeEventListener("keydown", handleEsc);
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
// 데이터 소스 타입 변경
|
||||
const handleDataSourceTypeChange = useCallback((type: "database" | "api") => {
|
||||
if (type === "database") {
|
||||
setDataSource({
|
||||
type: "database",
|
||||
connectionType: "current",
|
||||
refreshInterval: 0,
|
||||
});
|
||||
} else {
|
||||
setDataSource({
|
||||
type: "api",
|
||||
method: "GET",
|
||||
refreshInterval: 0,
|
||||
});
|
||||
}
|
||||
setQueryResult(null);
|
||||
}, []);
|
||||
|
||||
// 데이터 소스 업데이트
|
||||
const handleDataSourceUpdate = useCallback((updates: Partial<ChartDataSource>) => {
|
||||
setDataSource((prev) => ({ ...prev, ...updates }));
|
||||
}, []);
|
||||
|
||||
// 쿼리 실행 결과 처리
|
||||
const handleQueryTest = useCallback((result: QueryResult) => {
|
||||
setQueryResult(result);
|
||||
|
||||
// 자동 모드인 경우: 쿼리 결과의 컬럼을 자동으로 listConfig.columns에 반영
|
||||
setListConfig((prev) => {
|
||||
if (prev.columnMode === "auto") {
|
||||
return {
|
||||
...prev,
|
||||
columns: result.columns.map((col, idx) => ({
|
||||
id: `col_${idx}`,
|
||||
key: col,
|
||||
label: col,
|
||||
visible: true,
|
||||
width: "auto",
|
||||
align: "left",
|
||||
})),
|
||||
};
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 컬럼 설정 변경
|
||||
const handleListConfigChange = useCallback((updates: Partial<ListWidgetConfig>) => {
|
||||
setListConfig((prev) => ({ ...prev, ...updates }));
|
||||
}, []);
|
||||
|
||||
// 적용
|
||||
const handleApply = useCallback(() => {
|
||||
const updatedElement: DashboardElement = {
|
||||
...element,
|
||||
title,
|
||||
dataSource,
|
||||
listConfig,
|
||||
};
|
||||
|
||||
onApply(updatedElement);
|
||||
}, [element, title, dataSource, listConfig, onApply]);
|
||||
|
||||
// 저장 가능 여부
|
||||
const canApply = queryResult && queryResult.rows.length > 0 && listConfig.columns.length > 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"fixed top-14 left-0 z-[100] flex h-[calc(100vh-3.5rem)] w-80 flex-col bg-gray-50 transition-transform duration-300 ease-in-out",
|
||||
isOpen ? "translate-x-0" : "translate-x-[-100%]",
|
||||
)}
|
||||
>
|
||||
{/* 헤더 */}
|
||||
<div className="flex items-center justify-between bg-white px-3 py-2 shadow-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-primary/10 flex h-6 w-6 items-center justify-center rounded">
|
||||
<span className="text-primary text-xs font-bold">📋</span>
|
||||
</div>
|
||||
<span className="text-xs font-semibold text-gray-900">리스트 위젯 설정</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="flex h-6 w-6 items-center justify-center rounded transition-colors hover:bg-gray-100"
|
||||
>
|
||||
<X className="h-3.5 w-3.5 text-gray-500" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 본문: 스크롤 가능 영역 */}
|
||||
<div className="flex-1 overflow-y-auto p-3">
|
||||
{/* 기본 설정 */}
|
||||
<div className="mb-3 rounded-lg bg-white p-3 shadow-sm">
|
||||
<div className="mb-2 text-[10px] font-semibold tracking-wide text-gray-500 uppercase">기본 설정</div>
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
onKeyDown={(e) => e.stopPropagation()}
|
||||
placeholder="리스트 이름"
|
||||
className="focus:border-primary focus:ring-primary/20 h-8 w-full rounded border border-gray-200 bg-gray-50 px-2 text-xs placeholder:text-gray-400 focus:bg-white focus:ring-1 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 데이터 소스 */}
|
||||
<div className="rounded-lg bg-white p-3 shadow-sm">
|
||||
<div className="mb-2 text-[10px] font-semibold tracking-wide text-gray-500 uppercase">데이터 소스</div>
|
||||
|
||||
<Tabs
|
||||
defaultValue={dataSource.type}
|
||||
onValueChange={(value) => handleDataSourceTypeChange(value as "database" | "api")}
|
||||
className="w-full"
|
||||
>
|
||||
<TabsList className="grid h-7 w-full grid-cols-2 bg-gray-100 p-0.5">
|
||||
<TabsTrigger
|
||||
value="database"
|
||||
className="h-6 rounded text-[11px] data-[state=active]:bg-white data-[state=active]:shadow-sm"
|
||||
>
|
||||
데이터베이스
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="api"
|
||||
className="h-6 rounded text-[11px] data-[state=active]:bg-white data-[state=active]:shadow-sm"
|
||||
>
|
||||
REST API
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="database" className="mt-2 space-y-2">
|
||||
<DatabaseConfig dataSource={dataSource} onChange={handleDataSourceUpdate} />
|
||||
<QueryEditor
|
||||
dataSource={dataSource}
|
||||
onDataSourceChange={handleDataSourceUpdate}
|
||||
onQueryTest={handleQueryTest}
|
||||
/>
|
||||
|
||||
{/* 컬럼 설정 */}
|
||||
{queryResult && queryResult.rows.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<div className="mb-2 text-[10px] font-semibold tracking-wide text-gray-500 uppercase">컬럼 설정</div>
|
||||
{listConfig.columnMode === "auto" ? (
|
||||
<ColumnSelector
|
||||
queryResult={queryResult}
|
||||
config={listConfig}
|
||||
onConfigChange={handleListConfigChange}
|
||||
/>
|
||||
) : (
|
||||
<ManualColumnEditor config={listConfig} onConfigChange={handleListConfigChange} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 테이블 옵션 */}
|
||||
{queryResult && queryResult.rows.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<div className="mb-2 text-[10px] font-semibold tracking-wide text-gray-500 uppercase">
|
||||
테이블 옵션
|
||||
</div>
|
||||
<ListTableOptions config={listConfig} onConfigChange={handleListConfigChange} />
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="api" className="mt-2 space-y-2">
|
||||
<ApiConfig dataSource={dataSource} onChange={handleDataSourceUpdate} onTestResult={handleQueryTest} />
|
||||
|
||||
{/* 컬럼 설정 */}
|
||||
{queryResult && queryResult.rows.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<div className="mb-2 text-[10px] font-semibold tracking-wide text-gray-500 uppercase">컬럼 설정</div>
|
||||
{listConfig.columnMode === "auto" ? (
|
||||
<ColumnSelector
|
||||
queryResult={queryResult}
|
||||
config={listConfig}
|
||||
onConfigChange={handleListConfigChange}
|
||||
/>
|
||||
) : (
|
||||
<ManualColumnEditor config={listConfig} onConfigChange={handleListConfigChange} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 테이블 옵션 */}
|
||||
{queryResult && queryResult.rows.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<div className="mb-2 text-[10px] font-semibold tracking-wide text-gray-500 uppercase">
|
||||
테이블 옵션
|
||||
</div>
|
||||
<ListTableOptions config={listConfig} onConfigChange={handleListConfigChange} />
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* 데이터 로드 상태 */}
|
||||
{queryResult && (
|
||||
<div className="mt-2 flex items-center gap-1.5 rounded bg-green-50 px-2 py-1">
|
||||
<div className="h-1.5 w-1.5 rounded-full bg-green-500" />
|
||||
<span className="text-[10px] font-medium text-green-700">{queryResult.rows.length}개 데이터 로드됨</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 푸터: 적용 버튼 */}
|
||||
<div className="flex gap-2 bg-white p-2 shadow-[0_-2px_8px_rgba(0,0,0,0.05)]">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="flex-1 rounded bg-gray-100 py-2 text-xs font-medium text-gray-700 transition-colors hover:bg-gray-200"
|
||||
>
|
||||
취소
|
||||
</button>
|
||||
<button
|
||||
onClick={handleApply}
|
||||
disabled={!canApply}
|
||||
className="bg-primary hover:bg-primary/90 flex-1 rounded py-2 text-xs font-medium text-white transition-colors disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
적용
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -31,7 +31,7 @@ export default function CargoListWidget({ element }: CargoListWidgetProps) {
|
|||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
|
||||
|
||||
// 자동 새로고침 (30초마다)
|
||||
const interval = setInterval(loadData, 30000);
|
||||
return () => clearInterval(interval);
|
||||
|
|
@ -63,11 +63,11 @@ export default function CargoListWidget({ element }: CargoListWidgetProps) {
|
|||
if (!response.ok) throw new Error("데이터 로딩 실패");
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
|
||||
if (result.success && result.data?.rows) {
|
||||
setCargoList(result.data.rows);
|
||||
}
|
||||
|
||||
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "데이터 로딩 실패");
|
||||
|
|
@ -78,7 +78,7 @@ export default function CargoListWidget({ element }: CargoListWidgetProps) {
|
|||
|
||||
const getStatusBadge = (status: string) => {
|
||||
const statusLower = status?.toLowerCase() || "";
|
||||
|
||||
|
||||
if (statusLower.includes("배송중") || statusLower.includes("delivering")) {
|
||||
return "bg-primary text-primary-foreground";
|
||||
} else if (statusLower.includes("완료") || statusLower.includes("delivered")) {
|
||||
|
|
@ -93,11 +93,11 @@ export default function CargoListWidget({ element }: CargoListWidgetProps) {
|
|||
|
||||
const filteredList = cargoList.filter((cargo) => {
|
||||
if (!searchTerm) return true;
|
||||
|
||||
|
||||
const trackingNum = cargo.tracking_number || cargo.trackingNumber || "";
|
||||
const customerName = cargo.customer_name || cargo.customerName || "";
|
||||
const destination = cargo.destination || "";
|
||||
|
||||
|
||||
const searchLower = searchTerm.toLowerCase();
|
||||
return (
|
||||
trackingNum.toLowerCase().includes(searchLower) ||
|
||||
|
|
@ -111,7 +111,7 @@ export default function CargoListWidget({ element }: CargoListWidgetProps) {
|
|||
<div className="flex h-full items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="border-primary mx-auto h-8 w-8 animate-spin rounded-full border-2 border-t-transparent" />
|
||||
<p className="mt-2 text-sm text-muted-foreground">데이터 로딩 중...</p>
|
||||
<p className="text-muted-foreground mt-2 text-sm">데이터 로딩 중...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -120,11 +120,11 @@ export default function CargoListWidget({ element }: CargoListWidgetProps) {
|
|||
if (error) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<div className="text-center text-destructive">
|
||||
<div className="text-destructive text-center">
|
||||
<p className="text-sm">⚠️ {error}</p>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="mt-2 rounded-md bg-destructive/10 px-3 py-1 text-xs hover:bg-destructive/20"
|
||||
className="bg-destructive/10 hover:bg-destructive/20 mt-2 rounded-md px-3 py-1 text-xs"
|
||||
>
|
||||
다시 시도
|
||||
</button>
|
||||
|
|
@ -136,29 +136,29 @@ export default function CargoListWidget({ element }: CargoListWidgetProps) {
|
|||
if (!element?.dataSource?.query) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<div className="text-center text-muted-foreground">
|
||||
<p className="text-sm">⚙️ 톱니바퀴를 클릭하여 데이터를 연결하세요</p>
|
||||
<div className="text-muted-foreground text-center">
|
||||
<p className="text-sm">데이터를 연결하세요</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col overflow-hidden bg-background p-4">
|
||||
<div className="bg-background flex h-full flex-col overflow-hidden p-4">
|
||||
{/* 헤더 */}
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-foreground">📦 화물 목록</h3>
|
||||
<h3 className="text-foreground text-lg font-semibold">📦 화물 목록</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="검색..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="rounded-md border border-input bg-background px-3 py-1 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
className="border-input bg-background placeholder:text-muted-foreground focus:ring-ring rounded-md border px-3 py-1 text-sm focus:ring-2 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="rounded-full p-1 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
||||
className="text-muted-foreground hover:bg-accent hover:text-accent-foreground rounded-full p-1"
|
||||
title="새로고침"
|
||||
>
|
||||
🔄
|
||||
|
|
@ -167,47 +167,38 @@ export default function CargoListWidget({ element }: CargoListWidgetProps) {
|
|||
</div>
|
||||
|
||||
{/* 총 건수 */}
|
||||
<div className="mb-3 text-sm text-muted-foreground">
|
||||
총 <span className="font-semibold text-foreground">{filteredList.length}</span>건
|
||||
<div className="text-muted-foreground mb-3 text-sm">
|
||||
총 <span className="text-foreground font-semibold">{filteredList.length}</span>건
|
||||
</div>
|
||||
|
||||
{/* 테이블 */}
|
||||
<div className="flex-1 overflow-auto rounded-md border border-border">
|
||||
<div className="border-border flex-1 overflow-auto rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/50 text-muted-foreground">
|
||||
<tr>
|
||||
<th className="border-b border-border p-2 text-left font-medium">운송장번호</th>
|
||||
<th className="border-b border-border p-2 text-left font-medium">고객명</th>
|
||||
<th className="border-b border-border p-2 text-left font-medium">목적지</th>
|
||||
<th className="border-b border-border p-2 text-left font-medium">무게(kg)</th>
|
||||
<th className="border-b border-border p-2 text-left font-medium">상태</th>
|
||||
<th className="border-border border-b p-2 text-left font-medium">운송장번호</th>
|
||||
<th className="border-border border-b p-2 text-left font-medium">고객명</th>
|
||||
<th className="border-border border-b p-2 text-left font-medium">목적지</th>
|
||||
<th className="border-border border-b p-2 text-left font-medium">무게(kg)</th>
|
||||
<th className="border-border border-b p-2 text-left font-medium">상태</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filteredList.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="p-8 text-center text-muted-foreground">
|
||||
<td colSpan={5} className="text-muted-foreground p-8 text-center">
|
||||
{searchTerm ? "검색 결과가 없습니다" : "화물이 없습니다"}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredList.map((cargo, index) => (
|
||||
<tr
|
||||
key={cargo.id || index}
|
||||
className="border-b border-border hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<td className="p-2 font-medium text-foreground">
|
||||
<tr key={cargo.id || index} className="border-border hover:bg-muted/30 border-b transition-colors">
|
||||
<td className="text-foreground p-2 font-medium">
|
||||
{cargo.tracking_number || cargo.trackingNumber || "-"}
|
||||
</td>
|
||||
<td className="p-2 text-foreground">
|
||||
{cargo.customer_name || cargo.customerName || "-"}
|
||||
</td>
|
||||
<td className="p-2 text-muted-foreground">
|
||||
{cargo.destination || "-"}
|
||||
</td>
|
||||
<td className="p-2 text-right text-muted-foreground">
|
||||
{cargo.weight ? `${cargo.weight}kg` : "-"}
|
||||
</td>
|
||||
<td className="text-foreground p-2">{cargo.customer_name || cargo.customerName || "-"}</td>
|
||||
<td className="text-muted-foreground p-2">{cargo.destination || "-"}</td>
|
||||
<td className="text-muted-foreground p-2 text-right">{cargo.weight ? `${cargo.weight}kg` : "-"}</td>
|
||||
<td className="p-2">
|
||||
<span
|
||||
className={`inline-block rounded-full px-2 py-1 text-xs font-medium ${getStatusBadge(cargo.status || "")}`}
|
||||
|
|
@ -224,4 +215,3 @@ export default function CargoListWidget({ element }: CargoListWidgetProps) {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -41,11 +41,11 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
const lastQueryRef = React.useRef<string>(""); // 마지막 쿼리 추적
|
||||
|
||||
// localStorage 키 생성 (쿼리 기반으로 고유하게 - 편집/보기 모드 공유)
|
||||
const queryHash = element?.dataSource?.query
|
||||
const queryHash = element?.dataSource?.query
|
||||
? btoa(element.dataSource.query) // 전체 쿼리를 base64로 인코딩
|
||||
: "default";
|
||||
const storageKey = `custom-stats-widget-${queryHash}`;
|
||||
|
||||
|
||||
// console.log("🔑 storageKey:", storageKey, "(쿼리:", element?.dataSource?.query?.substring(0, 30) + "...)");
|
||||
|
||||
// 쿼리가 변경되면 초기화 상태 리셋
|
||||
|
|
@ -148,174 +148,174 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
// 3. 컬럼명 한글 번역 매핑
|
||||
const columnNameTranslation: { [key: string]: string } = {
|
||||
// 일반
|
||||
"id": "ID",
|
||||
"name": "이름",
|
||||
"title": "제목",
|
||||
"description": "설명",
|
||||
"status": "상태",
|
||||
"type": "유형",
|
||||
"category": "카테고리",
|
||||
"date": "날짜",
|
||||
"time": "시간",
|
||||
"created_at": "생성일",
|
||||
"updated_at": "수정일",
|
||||
"deleted_at": "삭제일",
|
||||
|
||||
id: "ID",
|
||||
name: "이름",
|
||||
title: "제목",
|
||||
description: "설명",
|
||||
status: "상태",
|
||||
type: "유형",
|
||||
category: "카테고리",
|
||||
date: "날짜",
|
||||
time: "시간",
|
||||
created_at: "생성일",
|
||||
updated_at: "수정일",
|
||||
deleted_at: "삭제일",
|
||||
|
||||
// 물류/운송
|
||||
"tracking_number": "운송장 번호",
|
||||
"customer": "고객",
|
||||
"origin": "출발지",
|
||||
"destination": "목적지",
|
||||
"estimated_delivery": "예상 도착",
|
||||
"actual_delivery": "실제 도착",
|
||||
"delay_reason": "지연 사유",
|
||||
"priority": "우선순위",
|
||||
"cargo_weight": "화물 중량",
|
||||
"total_weight": "총 중량",
|
||||
"weight": "중량",
|
||||
"distance": "거리",
|
||||
"total_distance": "총 거리",
|
||||
"delivery_time": "배송 시간",
|
||||
"delivery_duration": "배송 소요시간",
|
||||
"is_on_time": "정시 도착 여부",
|
||||
"on_time": "정시",
|
||||
|
||||
tracking_number: "운송장 번호",
|
||||
customer: "고객",
|
||||
origin: "출발지",
|
||||
destination: "목적지",
|
||||
estimated_delivery: "예상 도착",
|
||||
actual_delivery: "실제 도착",
|
||||
delay_reason: "지연 사유",
|
||||
priority: "우선순위",
|
||||
cargo_weight: "화물 중량",
|
||||
total_weight: "총 중량",
|
||||
weight: "중량",
|
||||
distance: "거리",
|
||||
total_distance: "총 거리",
|
||||
delivery_time: "배송 시간",
|
||||
delivery_duration: "배송 소요시간",
|
||||
is_on_time: "정시 도착 여부",
|
||||
on_time: "정시",
|
||||
|
||||
// 수량/금액
|
||||
"quantity": "수량",
|
||||
"qty": "수량",
|
||||
"amount": "금액",
|
||||
"price": "가격",
|
||||
"cost": "비용",
|
||||
"fee": "수수료",
|
||||
"total": "합계",
|
||||
"sum": "총합",
|
||||
|
||||
quantity: "수량",
|
||||
qty: "수량",
|
||||
amount: "금액",
|
||||
price: "가격",
|
||||
cost: "비용",
|
||||
fee: "수수료",
|
||||
total: "합계",
|
||||
sum: "총합",
|
||||
|
||||
// 비율/효율
|
||||
"rate": "비율",
|
||||
"ratio": "비율",
|
||||
"percent": "퍼센트",
|
||||
"percentage": "백분율",
|
||||
"efficiency": "효율",
|
||||
|
||||
rate: "비율",
|
||||
ratio: "비율",
|
||||
percent: "퍼센트",
|
||||
percentage: "백분율",
|
||||
efficiency: "효율",
|
||||
|
||||
// 생산/처리
|
||||
"throughput": "처리량",
|
||||
"output": "산출량",
|
||||
"production": "생산량",
|
||||
"volume": "용량",
|
||||
|
||||
throughput: "처리량",
|
||||
output: "산출량",
|
||||
production: "생산량",
|
||||
volume: "용량",
|
||||
|
||||
// 재고/설비
|
||||
"stock": "재고",
|
||||
"inventory": "재고",
|
||||
"equipment": "설비",
|
||||
"facility": "시설",
|
||||
"machine": "기계",
|
||||
|
||||
stock: "재고",
|
||||
inventory: "재고",
|
||||
equipment: "설비",
|
||||
facility: "시설",
|
||||
machine: "기계",
|
||||
|
||||
// 평가
|
||||
"score": "점수",
|
||||
"rating": "평점",
|
||||
"point": "점수",
|
||||
"grade": "등급",
|
||||
|
||||
score: "점수",
|
||||
rating: "평점",
|
||||
point: "점수",
|
||||
grade: "등급",
|
||||
|
||||
// 기타
|
||||
"temperature": "온도",
|
||||
"temp": "온도",
|
||||
"speed": "속도",
|
||||
"velocity": "속도",
|
||||
"count": "개수",
|
||||
"number": "번호",
|
||||
temperature: "온도",
|
||||
temp: "온도",
|
||||
speed: "속도",
|
||||
velocity: "속도",
|
||||
count: "개수",
|
||||
number: "번호",
|
||||
};
|
||||
|
||||
// 4. 키워드 기반 자동 라벨링 및 단위 설정
|
||||
const columnConfig: {
|
||||
[key: string]: {
|
||||
keywords: string[];
|
||||
unit: string;
|
||||
color: string;
|
||||
icon: string;
|
||||
[key: string]: {
|
||||
keywords: string[];
|
||||
unit: string;
|
||||
color: string;
|
||||
icon: string;
|
||||
aggregation: "sum" | "avg" | "max" | "min"; // 집계 방식
|
||||
koreanLabel?: string; // 한글 라벨
|
||||
};
|
||||
} = {
|
||||
// 무게/중량 - 합계
|
||||
weight: {
|
||||
keywords: ["weight", "cargo_weight", "total_weight", "tonnage", "ton"],
|
||||
unit: "톤",
|
||||
color: "green",
|
||||
weight: {
|
||||
keywords: ["weight", "cargo_weight", "total_weight", "tonnage", "ton"],
|
||||
unit: "톤",
|
||||
color: "green",
|
||||
icon: "⚖️",
|
||||
aggregation: "sum",
|
||||
koreanLabel: "총 운송량"
|
||||
koreanLabel: "총 운송량",
|
||||
},
|
||||
// 거리 - 합계
|
||||
distance: {
|
||||
keywords: ["distance", "total_distance", "km", "kilometer"],
|
||||
unit: "km",
|
||||
color: "blue",
|
||||
distance: {
|
||||
keywords: ["distance", "total_distance", "km", "kilometer"],
|
||||
unit: "km",
|
||||
color: "blue",
|
||||
icon: "🛣️",
|
||||
aggregation: "sum",
|
||||
koreanLabel: "누적 거리"
|
||||
koreanLabel: "누적 거리",
|
||||
},
|
||||
// 시간/기간 - 평균
|
||||
time: {
|
||||
keywords: ["time", "duration", "delivery_time", "delivery_duration", "hour", "minute"],
|
||||
unit: "분",
|
||||
color: "orange",
|
||||
icon: "⏱️",
|
||||
time: {
|
||||
keywords: ["time", "duration", "delivery_time", "delivery_duration", "hour", "minute"],
|
||||
unit: "분",
|
||||
color: "orange",
|
||||
icon: "⏱️",
|
||||
aggregation: "avg",
|
||||
koreanLabel: "평균 배송시간"
|
||||
koreanLabel: "평균 배송시간",
|
||||
},
|
||||
// 수량/개수 - 합계
|
||||
quantity: {
|
||||
keywords: ["quantity", "qty", "count", "number"],
|
||||
unit: "개",
|
||||
color: "purple",
|
||||
quantity: {
|
||||
keywords: ["quantity", "qty", "count", "number"],
|
||||
unit: "개",
|
||||
color: "purple",
|
||||
icon: "📦",
|
||||
aggregation: "sum",
|
||||
koreanLabel: "총 수량"
|
||||
koreanLabel: "총 수량",
|
||||
},
|
||||
// 금액/가격 - 합계
|
||||
amount: {
|
||||
keywords: ["amount", "price", "cost", "fee", "total", "sum"],
|
||||
unit: "원",
|
||||
color: "yellow",
|
||||
amount: {
|
||||
keywords: ["amount", "price", "cost", "fee", "total", "sum"],
|
||||
unit: "원",
|
||||
color: "yellow",
|
||||
icon: "💰",
|
||||
aggregation: "sum",
|
||||
koreanLabel: "총 금액"
|
||||
koreanLabel: "총 금액",
|
||||
},
|
||||
// 비율/퍼센트 - 평균
|
||||
rate: {
|
||||
keywords: ["rate", "ratio", "percent", "efficiency", "%"],
|
||||
unit: "%",
|
||||
color: "cyan",
|
||||
icon: "📈",
|
||||
rate: {
|
||||
keywords: ["rate", "ratio", "percent", "efficiency", "%"],
|
||||
unit: "%",
|
||||
color: "cyan",
|
||||
icon: "📈",
|
||||
aggregation: "avg",
|
||||
koreanLabel: "평균 비율"
|
||||
koreanLabel: "평균 비율",
|
||||
},
|
||||
// 처리량 - 합계
|
||||
throughput: {
|
||||
keywords: ["throughput", "output", "production", "volume"],
|
||||
unit: "개",
|
||||
color: "pink",
|
||||
throughput: {
|
||||
keywords: ["throughput", "output", "production", "volume"],
|
||||
unit: "개",
|
||||
color: "pink",
|
||||
icon: "⚡",
|
||||
aggregation: "sum",
|
||||
koreanLabel: "총 처리량"
|
||||
koreanLabel: "총 처리량",
|
||||
},
|
||||
// 재고 - 평균 (현재 재고는 평균이 의미있음)
|
||||
stock: {
|
||||
keywords: ["stock", "inventory"],
|
||||
unit: "개",
|
||||
color: "teal",
|
||||
stock: {
|
||||
keywords: ["stock", "inventory"],
|
||||
unit: "개",
|
||||
color: "teal",
|
||||
icon: "📦",
|
||||
aggregation: "avg",
|
||||
koreanLabel: "평균 재고"
|
||||
koreanLabel: "평균 재고",
|
||||
},
|
||||
// 설비/장비 - 평균
|
||||
equipment: {
|
||||
keywords: ["equipment", "facility", "machine"],
|
||||
unit: "대",
|
||||
color: "gray",
|
||||
equipment: {
|
||||
keywords: ["equipment", "facility", "machine"],
|
||||
unit: "대",
|
||||
color: "gray",
|
||||
icon: "🏭",
|
||||
aggregation: "avg",
|
||||
koreanLabel: "평균 가동 설비"
|
||||
koreanLabel: "평균 가동 설비",
|
||||
},
|
||||
// 점수/평점 - 평균
|
||||
score: {
|
||||
|
|
@ -324,7 +324,7 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
color: "indigo",
|
||||
icon: "⭐",
|
||||
aggregation: "avg",
|
||||
koreanLabel: "평균 점수"
|
||||
koreanLabel: "평균 점수",
|
||||
},
|
||||
// 온도 - 평균
|
||||
temperature: {
|
||||
|
|
@ -333,7 +333,7 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
color: "red",
|
||||
icon: "🌡️",
|
||||
aggregation: "avg",
|
||||
koreanLabel: "평균 온도"
|
||||
koreanLabel: "평균 온도",
|
||||
},
|
||||
// 속도 - 평균
|
||||
speed: {
|
||||
|
|
@ -342,7 +342,7 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
color: "blue",
|
||||
icon: "🚀",
|
||||
aggregation: "avg",
|
||||
koreanLabel: "평균 속도"
|
||||
koreanLabel: "평균 속도",
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -363,17 +363,19 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
icon = config.icon;
|
||||
aggregation = config.aggregation;
|
||||
matchedConfig = config;
|
||||
|
||||
|
||||
// 한글 라벨 사용 또는 자동 변환
|
||||
if (config.koreanLabel) {
|
||||
label = config.koreanLabel;
|
||||
} else {
|
||||
// 집계 방식에 따라 접두어 추가
|
||||
const prefix = aggregation === "avg" ? "평균 " : aggregation === "sum" ? "총 " : "";
|
||||
label = prefix + key
|
||||
.replace(/_/g, " ")
|
||||
.replace(/([A-Z])/g, " $1")
|
||||
.trim();
|
||||
label =
|
||||
prefix +
|
||||
key
|
||||
.replace(/_/g, " ")
|
||||
.replace(/([A-Z])/g, " $1")
|
||||
.trim();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
|
@ -383,41 +385,45 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
if (!matchedConfig) {
|
||||
// 컬럼명 번역 시도
|
||||
const translatedName = columnNameTranslation[key.toLowerCase()];
|
||||
|
||||
|
||||
if (translatedName) {
|
||||
// 번역된 이름이 있으면 사용
|
||||
label = translatedName;
|
||||
} else {
|
||||
// 컬럼명에 avg, average, mean이 포함되면 평균으로 간주
|
||||
if (key.toLowerCase().includes("avg") ||
|
||||
key.toLowerCase().includes("average") ||
|
||||
key.toLowerCase().includes("mean")) {
|
||||
if (
|
||||
key.toLowerCase().includes("avg") ||
|
||||
key.toLowerCase().includes("average") ||
|
||||
key.toLowerCase().includes("mean")
|
||||
) {
|
||||
aggregation = "avg";
|
||||
|
||||
|
||||
// 언더스코어로 분리된 각 단어 번역 시도
|
||||
const cleanKey = key.replace(/avg|average|mean/gi, "").replace(/_/g, " ").trim();
|
||||
const cleanKey = key
|
||||
.replace(/avg|average|mean/gi, "")
|
||||
.replace(/_/g, " ")
|
||||
.trim();
|
||||
const words = cleanKey.split(/[_\s]+/);
|
||||
const translatedWords = words.map(word =>
|
||||
columnNameTranslation[word.toLowerCase()] || word
|
||||
);
|
||||
const translatedWords = words.map((word) => columnNameTranslation[word.toLowerCase()] || word);
|
||||
label = "평균 " + translatedWords.join(" ");
|
||||
}
|
||||
}
|
||||
// total, sum이 포함되면 합계로 간주
|
||||
else if (key.toLowerCase().includes("total") || key.toLowerCase().includes("sum")) {
|
||||
aggregation = "sum";
|
||||
|
||||
|
||||
// 언더스코어로 분리된 각 단어 번역 시도
|
||||
const cleanKey = key.replace(/total|sum/gi, "").replace(/_/g, " ").trim();
|
||||
const cleanKey = key
|
||||
.replace(/total|sum/gi, "")
|
||||
.replace(/_/g, " ")
|
||||
.trim();
|
||||
const words = cleanKey.split(/[_\s]+/);
|
||||
const translatedWords = words.map(word =>
|
||||
columnNameTranslation[word.toLowerCase()] || word
|
||||
);
|
||||
const translatedWords = words.map((word) => columnNameTranslation[word.toLowerCase()] || word);
|
||||
label = "총 " + translatedWords.join(" ");
|
||||
}
|
||||
// 기본값 - 각 단어별로 번역 시도
|
||||
else {
|
||||
const words = key.split(/[_\s]+/);
|
||||
const translatedWords = words.map(word => {
|
||||
const translatedWords = words.map((word) => {
|
||||
const translated = columnNameTranslation[word.toLowerCase()];
|
||||
if (translated) {
|
||||
return translated;
|
||||
|
|
@ -473,25 +479,25 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
Object.keys(firstRow).forEach((key) => {
|
||||
const lowerKey = key.toLowerCase();
|
||||
const matchedKey = Object.keys(booleanMapping).find((k) => lowerKey.includes(k));
|
||||
|
||||
|
||||
if (matchedKey) {
|
||||
const label = booleanMapping[matchedKey];
|
||||
|
||||
|
||||
// 이미 추가된 라벨이면 스킵
|
||||
if (addedBooleanLabels.has(label)) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
const validItems = data.filter((item: any) => item[key] !== null && item[key] !== undefined);
|
||||
|
||||
|
||||
if (validItems.length > 0) {
|
||||
const trueCount = validItems.filter((item: any) => {
|
||||
const val = item[key];
|
||||
return val === true || val === "true" || val === 1 || val === "1" || val === "Y";
|
||||
}).length;
|
||||
|
||||
|
||||
const rate = (trueCount / validItems.length) * 100;
|
||||
|
||||
|
||||
statsItems.push({
|
||||
label,
|
||||
value: rate,
|
||||
|
|
@ -499,7 +505,7 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
color: "purple",
|
||||
icon: "✅",
|
||||
});
|
||||
|
||||
|
||||
addedBooleanLabels.add(label);
|
||||
}
|
||||
}
|
||||
|
|
@ -507,27 +513,27 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
|
||||
// console.log("📊 생성된 통계 항목:", statsItems.map(s => s.label));
|
||||
setAllStats(statsItems);
|
||||
|
||||
|
||||
// 초기화가 아직 안됐으면 localStorage에서 설정 불러오기
|
||||
if (!isInitializedRef.current) {
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
// console.log("💾 저장된 설정:", saved);
|
||||
|
||||
|
||||
if (saved) {
|
||||
try {
|
||||
const savedLabels = JSON.parse(saved);
|
||||
// console.log("✅ 저장된 라벨:", savedLabels);
|
||||
|
||||
|
||||
const filtered = statsItems.filter((s) => savedLabels.includes(s.label));
|
||||
// console.log("🔍 필터링된 통계:", filtered.map(s => s.label));
|
||||
// console.log(`📊 일치율: ${filtered.length}/${savedLabels.length} (${Math.round(filtered.length / savedLabels.length * 100)}%)`);
|
||||
|
||||
|
||||
// 50% 이상 일치하면 저장된 설정 사용
|
||||
const matchRate = filtered.length / savedLabels.length;
|
||||
if (matchRate >= 0.5 && filtered.length > 0) {
|
||||
setStats(filtered);
|
||||
// 실제 표시되는 라벨로 업데이트
|
||||
const actualLabels = filtered.map(s => s.label);
|
||||
const actualLabels = filtered.map((s) => s.label);
|
||||
setSelectedStats(actualLabels);
|
||||
selectedStatsRef.current = actualLabels;
|
||||
// localStorage도 업데이트하여 다음에는 정확히 일치하도록
|
||||
|
|
@ -562,11 +568,11 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
// 이미 초기화됐으면 현재 선택된 통계 유지
|
||||
const currentSelected = selectedStatsRef.current;
|
||||
// console.log("🔄 현재 선택된 통계:", currentSelected);
|
||||
|
||||
|
||||
if (currentSelected.length > 0) {
|
||||
const filtered = statsItems.filter((s) => currentSelected.includes(s.label));
|
||||
// console.log("🔍 필터링 결과:", filtered.map(s => s.label));
|
||||
|
||||
|
||||
if (filtered.length > 0) {
|
||||
setStats(filtered);
|
||||
} else {
|
||||
|
|
@ -624,9 +630,7 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
<div className="text-center">
|
||||
<div className="mb-2 text-4xl">⚠️</div>
|
||||
<div className="text-sm font-medium text-gray-600">{error}</div>
|
||||
{!element?.dataSource?.query && (
|
||||
<div className="mt-2 text-xs text-gray-500">톱니바퀴 아이콘을 클릭하여 쿼리를 설정하세요</div>
|
||||
)}
|
||||
{!element?.dataSource?.query && <div className="mt-2 text-xs text-gray-500">쿼리를 설정하세요</div>}
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="mt-3 rounded-lg bg-blue-500 px-4 py-2 text-sm text-white hover:bg-blue-600"
|
||||
|
|
@ -652,9 +656,7 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
|
||||
const handleToggleStat = (label: string) => {
|
||||
setSelectedStats((prev) => {
|
||||
const newStats = prev.includes(label)
|
||||
? prev.filter((l) => l !== label)
|
||||
: [...prev, label];
|
||||
const newStats = prev.includes(label) ? prev.filter((l) => l !== label) : [...prev, label];
|
||||
// console.log("🔘 토글:", label, "→", newStats.length + "개 선택");
|
||||
return newStats;
|
||||
});
|
||||
|
|
@ -663,14 +665,14 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
const handleApplySettings = () => {
|
||||
// console.log("💾 설정 적용:", selectedStats);
|
||||
// console.log("📊 전체 통계:", allStats.map(s => s.label));
|
||||
|
||||
|
||||
const filtered = allStats.filter((s) => selectedStats.includes(s.label));
|
||||
// console.log("✅ 필터링 결과:", filtered.map(s => s.label));
|
||||
|
||||
|
||||
setStats(filtered);
|
||||
selectedStatsRef.current = selectedStats; // ref도 업데이트
|
||||
setShowSettings(false);
|
||||
|
||||
|
||||
// localStorage에 설정 저장
|
||||
localStorage.setItem(storageKey, JSON.stringify(selectedStats));
|
||||
// console.log("💾 localStorage 저장 완료:", selectedStats.length + "개");
|
||||
|
|
@ -693,7 +695,7 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
<button
|
||||
onClick={() => {
|
||||
// 설정 모달 열 때 현재 표시 중인 통계로 동기화
|
||||
const currentLabels = stats.map(s => s.label);
|
||||
const currentLabels = stats.map((s) => s.label);
|
||||
// console.log("⚙️ 설정 모달 열기 - 현재 표시 중:", currentLabels);
|
||||
setSelectedStats(currentLabels);
|
||||
setShowSettings(true);
|
||||
|
|
@ -713,9 +715,7 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
const colors = getColorClasses(stat.color);
|
||||
return (
|
||||
<div key={index} className={`rounded-lg border ${colors.bg} p-4 text-center`}>
|
||||
<div className="text-sm text-gray-600">
|
||||
{stat.label}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">{stat.label}</div>
|
||||
<div className={`mt-2 text-3xl font-bold ${colors.text}`}>
|
||||
{stat.value.toFixed(stat.unit === "%" || stat.unit === "분" ? 1 : 0).toLocaleString()}
|
||||
<span className="ml-1 text-lg">{stat.unit}</span>
|
||||
|
|
@ -737,9 +737,7 @@ export default function CustomStatsWidget({ element, refreshInterval = 60000 }:
|
|||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mb-4 text-sm text-gray-600">
|
||||
표시하고 싶은 통계를 선택하세요 (최대 제한 없음)
|
||||
</div>
|
||||
<div className="mb-4 text-sm text-gray-600">표시하고 싶은 통계를 선택하세요 (최대 제한 없음)</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{allStats.map((stat, index) => {
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ export default function CustomerIssuesWidget({ element }: CustomerIssuesWidgetPr
|
|||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
|
||||
|
||||
// 자동 새로고침 (30초마다)
|
||||
const interval = setInterval(loadData, 30000);
|
||||
return () => clearInterval(interval);
|
||||
|
|
@ -65,11 +65,11 @@ export default function CustomerIssuesWidget({ element }: CustomerIssuesWidgetPr
|
|||
if (!response.ok) throw new Error("데이터 로딩 실패");
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
|
||||
if (result.success && result.data?.rows) {
|
||||
setIssues(result.data.rows);
|
||||
}
|
||||
|
||||
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "데이터 로딩 실패");
|
||||
|
|
@ -80,7 +80,7 @@ export default function CustomerIssuesWidget({ element }: CustomerIssuesWidgetPr
|
|||
|
||||
const getPriorityBadge = (priority: string) => {
|
||||
const priorityLower = priority?.toLowerCase() || "";
|
||||
|
||||
|
||||
if (priorityLower.includes("긴급") || priorityLower.includes("high") || priorityLower.includes("urgent")) {
|
||||
return "bg-destructive text-destructive-foreground";
|
||||
} else if (priorityLower.includes("보통") || priorityLower.includes("medium") || priorityLower.includes("normal")) {
|
||||
|
|
@ -93,7 +93,7 @@ export default function CustomerIssuesWidget({ element }: CustomerIssuesWidgetPr
|
|||
|
||||
const getStatusBadge = (status: string) => {
|
||||
const statusLower = status?.toLowerCase() || "";
|
||||
|
||||
|
||||
if (statusLower.includes("처리중") || statusLower.includes("processing") || statusLower.includes("pending")) {
|
||||
return "bg-primary text-primary-foreground";
|
||||
} else if (statusLower.includes("완료") || statusLower.includes("resolved") || statusLower.includes("closed")) {
|
||||
|
|
@ -102,19 +102,20 @@ export default function CustomerIssuesWidget({ element }: CustomerIssuesWidgetPr
|
|||
return "bg-muted text-muted-foreground";
|
||||
};
|
||||
|
||||
const filteredIssues = filterPriority === "all"
|
||||
? issues
|
||||
: issues.filter((issue) => {
|
||||
const priority = (issue.priority || "").toLowerCase();
|
||||
return priority.includes(filterPriority);
|
||||
});
|
||||
const filteredIssues =
|
||||
filterPriority === "all"
|
||||
? issues
|
||||
: issues.filter((issue) => {
|
||||
const priority = (issue.priority || "").toLowerCase();
|
||||
return priority.includes(filterPriority);
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="border-primary mx-auto h-8 w-8 animate-spin rounded-full border-2 border-t-transparent" />
|
||||
<p className="mt-2 text-sm text-muted-foreground">데이터 로딩 중...</p>
|
||||
<p className="text-muted-foreground mt-2 text-sm">데이터 로딩 중...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -123,11 +124,11 @@ export default function CustomerIssuesWidget({ element }: CustomerIssuesWidgetPr
|
|||
if (error) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<div className="text-center text-destructive">
|
||||
<div className="text-destructive text-center">
|
||||
<p className="text-sm">⚠️ {error}</p>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="mt-2 rounded-md bg-destructive/10 px-3 py-1 text-xs hover:bg-destructive/20"
|
||||
className="bg-destructive/10 hover:bg-destructive/20 mt-2 rounded-md px-3 py-1 text-xs"
|
||||
>
|
||||
다시 시도
|
||||
</button>
|
||||
|
|
@ -139,21 +140,21 @@ export default function CustomerIssuesWidget({ element }: CustomerIssuesWidgetPr
|
|||
if (!element?.dataSource?.query) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<div className="text-center text-muted-foreground">
|
||||
<p className="text-sm">⚙️ 톱니바퀴를 클릭하여 데이터를 연결하세요</p>
|
||||
<div className="text-muted-foreground text-center">
|
||||
<p className="text-sm">클릭하여 데이터를 연결하세요</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col overflow-hidden bg-background p-4">
|
||||
<div className="bg-background flex h-full flex-col overflow-hidden p-4">
|
||||
{/* 헤더 */}
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-foreground">고객 클레임/이슈</h3>
|
||||
<h3 className="text-foreground text-lg font-semibold">고객 클레임/이슈</h3>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="rounded-full p-1 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
||||
className="text-muted-foreground hover:bg-accent hover:text-accent-foreground rounded-full p-1"
|
||||
title="새로고침"
|
||||
>
|
||||
🔄
|
||||
|
|
@ -205,48 +206,48 @@ export default function CustomerIssuesWidget({ element }: CustomerIssuesWidgetPr
|
|||
</div>
|
||||
|
||||
{/* 총 건수 */}
|
||||
<div className="mb-3 text-sm text-muted-foreground">
|
||||
총 <span className="font-semibold text-foreground">{filteredIssues.length}</span>건
|
||||
<div className="text-muted-foreground mb-3 text-sm">
|
||||
총 <span className="text-foreground font-semibold">{filteredIssues.length}</span>건
|
||||
</div>
|
||||
|
||||
{/* 이슈 리스트 */}
|
||||
<div className="flex-1 space-y-2 overflow-auto">
|
||||
{filteredIssues.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-center text-muted-foreground">
|
||||
<div className="text-muted-foreground flex h-full items-center justify-center text-center">
|
||||
<p>이슈가 없습니다</p>
|
||||
</div>
|
||||
) : (
|
||||
filteredIssues.map((issue, index) => (
|
||||
<div
|
||||
key={issue.id || index}
|
||||
className="rounded-lg border border-border bg-card p-3 transition-all hover:shadow-md"
|
||||
className="border-border bg-card rounded-lg border p-3 transition-all hover:shadow-md"
|
||||
>
|
||||
<div className="mb-2 flex items-start justify-between">
|
||||
<div className="flex-1">
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<span className={`rounded-full px-2 py-0.5 text-xs font-medium ${getPriorityBadge(issue.priority || "")}`}>
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 text-xs font-medium ${getPriorityBadge(issue.priority || "")}`}
|
||||
>
|
||||
{issue.priority || "보통"}
|
||||
</span>
|
||||
<span className={`rounded-full px-2 py-0.5 text-xs font-medium ${getStatusBadge(issue.status || "")}`}>
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 text-xs font-medium ${getStatusBadge(issue.status || "")}`}
|
||||
>
|
||||
{issue.status || "처리중"}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{issue.issue_type || issue.issueType || "기타"}
|
||||
</p>
|
||||
<p className="text-foreground text-sm font-medium">{issue.issue_type || issue.issueType || "기타"}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mb-2 text-xs text-muted-foreground">
|
||||
|
||||
<p className="text-muted-foreground mb-2 text-xs">
|
||||
고객: {issue.customer_name || issue.customerName || "-"}
|
||||
</p>
|
||||
|
||||
<p className="text-xs text-muted-foreground line-clamp-2">
|
||||
{issue.description || "설명 없음"}
|
||||
</p>
|
||||
|
||||
|
||||
<p className="text-muted-foreground line-clamp-2 text-xs">{issue.description || "설명 없음"}</p>
|
||||
|
||||
{(issue.created_at || issue.createdAt) && (
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
<p className="text-muted-foreground mt-2 text-xs">
|
||||
{new Date(issue.created_at || issue.createdAt || "").toLocaleDateString("ko-KR")}
|
||||
</p>
|
||||
)}
|
||||
|
|
@ -257,4 +258,3 @@ export default function CustomerIssuesWidget({ element }: CustomerIssuesWidgetPr
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ export default function DeliveryStatusSummaryWidget({ element }: DeliveryStatusS
|
|||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
|
||||
|
||||
// 자동 새로고침 (30초마다)
|
||||
const interval = setInterval(loadData, 30000);
|
||||
return () => clearInterval(interval);
|
||||
|
|
@ -55,11 +55,11 @@ export default function DeliveryStatusSummaryWidget({ element }: DeliveryStatusS
|
|||
if (!response.ok) throw new Error("데이터 로딩 실패");
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
|
||||
// 데이터 처리
|
||||
if (result.success && result.data?.rows) {
|
||||
const rows = result.data.rows;
|
||||
|
||||
|
||||
// 상태별 카운트 계산
|
||||
const statusCounts = rows.reduce((acc: any, row: any) => {
|
||||
const status = row.status || "알 수 없음";
|
||||
|
|
@ -76,7 +76,7 @@ export default function DeliveryStatusSummaryWidget({ element }: DeliveryStatusS
|
|||
|
||||
setStatusData(formattedData);
|
||||
}
|
||||
|
||||
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "데이터 로딩 실패");
|
||||
|
|
@ -161,7 +161,7 @@ export default function DeliveryStatusSummaryWidget({ element }: DeliveryStatusS
|
|||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<div className="text-center text-gray-500">
|
||||
<p className="text-sm">⚙️ 톱니바퀴를 클릭하여 데이터를 연결하세요</p>
|
||||
<p className="text-sm">데이터를 연결하세요</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -183,7 +183,7 @@ export default function DeliveryStatusSummaryWidget({ element }: DeliveryStatusS
|
|||
</div>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="flex h-7 w-7 items-center justify-center rounded border border-border bg-white p-0 text-xs hover:bg-accent disabled:opacity-50"
|
||||
className="border-border hover:bg-accent flex h-7 w-7 items-center justify-center rounded border bg-white p-0 text-xs disabled:opacity-50"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "⏳" : "🔄"}
|
||||
|
|
@ -211,4 +211,3 @@ export default function DeliveryStatusSummaryWidget({ element }: DeliveryStatusS
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ export default function DeliveryTodayStatsWidget({ element }: DeliveryTodayStats
|
|||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
|
||||
|
||||
// 자동 새로고침 (30초마다)
|
||||
const interval = setInterval(loadData, 30000);
|
||||
return () => clearInterval(interval);
|
||||
|
|
@ -56,7 +56,7 @@ export default function DeliveryTodayStatsWidget({ element }: DeliveryTodayStats
|
|||
if (!response.ok) throw new Error("데이터 로딩 실패");
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
|
||||
// 데이터 처리
|
||||
if (result.success && result.data?.rows) {
|
||||
const rows = result.data.rows;
|
||||
|
|
@ -80,7 +80,7 @@ export default function DeliveryTodayStatsWidget({ element }: DeliveryTodayStats
|
|||
delivered: deliveredToday,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "데이터 로딩 실패");
|
||||
|
|
@ -120,7 +120,7 @@ export default function DeliveryTodayStatsWidget({ element }: DeliveryTodayStats
|
|||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<div className="text-center text-gray-500">
|
||||
<p className="text-sm">⚙️ 톱니바퀴를 클릭하여 데이터를 연결하세요</p>
|
||||
<p className="text-sm">데이터를 연결하세요</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -131,11 +131,7 @@ export default function DeliveryTodayStatsWidget({ element }: DeliveryTodayStats
|
|||
{/* 헤더 */}
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-gray-800">오늘 처리 현황</h3>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="rounded-full p-1 text-gray-500 hover:bg-gray-100"
|
||||
title="새로고침"
|
||||
>
|
||||
<button onClick={loadData} className="rounded-full p-1 text-gray-500 hover:bg-gray-100" title="새로고침">
|
||||
🔄
|
||||
</button>
|
||||
</div>
|
||||
|
|
@ -161,4 +157,3 @@ export default function DeliveryTodayStatsWidget({ element }: DeliveryTodayStats
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -22,66 +22,66 @@ interface ColumnInfo {
|
|||
const translateColumnName = (colName: string): string => {
|
||||
const columnTranslations: { [key: string]: string } = {
|
||||
// 공통
|
||||
"id": "ID",
|
||||
"name": "이름",
|
||||
"status": "상태",
|
||||
"created_at": "생성일",
|
||||
"updated_at": "수정일",
|
||||
"created_date": "생성일",
|
||||
"updated_date": "수정일",
|
||||
|
||||
// 기사 관련
|
||||
"driver_id": "기사ID",
|
||||
"phone": "전화번호",
|
||||
"license_number": "면허번호",
|
||||
"vehicle_id": "차량ID",
|
||||
"current_location": "현재위치",
|
||||
"rating": "평점",
|
||||
"total_deliveries": "총배송건수",
|
||||
"average_delivery_time": "평균배송시간",
|
||||
"total_distance": "총운행거리",
|
||||
"join_date": "가입일",
|
||||
"last_active": "마지막활동",
|
||||
|
||||
id: "ID",
|
||||
name: "이름",
|
||||
status: "상태",
|
||||
created_at: "생성일",
|
||||
updated_at: "수정일",
|
||||
created_date: "생성일",
|
||||
updated_date: "수정일",
|
||||
|
||||
// 기사 관련
|
||||
driver_id: "기사ID",
|
||||
phone: "전화번호",
|
||||
license_number: "면허번호",
|
||||
vehicle_id: "차량ID",
|
||||
current_location: "현재위치",
|
||||
rating: "평점",
|
||||
total_deliveries: "총배송건수",
|
||||
average_delivery_time: "평균배송시간",
|
||||
total_distance: "총운행거리",
|
||||
join_date: "가입일",
|
||||
last_active: "마지막활동",
|
||||
|
||||
// 차량 관련
|
||||
"vehicle_number": "차량번호",
|
||||
"model": "모델",
|
||||
"year": "연식",
|
||||
"color": "색상",
|
||||
"type": "종류",
|
||||
|
||||
vehicle_number: "차량번호",
|
||||
model: "모델",
|
||||
year: "연식",
|
||||
color: "색상",
|
||||
type: "종류",
|
||||
|
||||
// 배송 관련
|
||||
"delivery_id": "배송ID",
|
||||
"order_id": "주문ID",
|
||||
"customer_name": "고객명",
|
||||
"address": "주소",
|
||||
"delivery_date": "배송일",
|
||||
"estimated_time": "예상시간",
|
||||
|
||||
delivery_id: "배송ID",
|
||||
order_id: "주문ID",
|
||||
customer_name: "고객명",
|
||||
address: "주소",
|
||||
delivery_date: "배송일",
|
||||
estimated_time: "예상시간",
|
||||
|
||||
// 제품 관련
|
||||
"product_id": "제품ID",
|
||||
"product_name": "제품명",
|
||||
"price": "가격",
|
||||
"stock": "재고",
|
||||
"category": "카테고리",
|
||||
"description": "설명",
|
||||
|
||||
product_id: "제품ID",
|
||||
product_name: "제품명",
|
||||
price: "가격",
|
||||
stock: "재고",
|
||||
category: "카테고리",
|
||||
description: "설명",
|
||||
|
||||
// 주문 관련
|
||||
"order_date": "주문일",
|
||||
"quantity": "수량",
|
||||
"total_amount": "총금액",
|
||||
"payment_status": "결제상태",
|
||||
|
||||
order_date: "주문일",
|
||||
quantity: "수량",
|
||||
total_amount: "총금액",
|
||||
payment_status: "결제상태",
|
||||
|
||||
// 고객 관련
|
||||
"customer_id": "고객ID",
|
||||
"email": "이메일",
|
||||
"company": "회사",
|
||||
"department": "부서",
|
||||
customer_id: "고객ID",
|
||||
email: "이메일",
|
||||
company: "회사",
|
||||
department: "부서",
|
||||
};
|
||||
|
||||
return columnTranslations[colName.toLowerCase()] ||
|
||||
columnTranslations[colName.replace(/_/g, '').toLowerCase()] ||
|
||||
colName;
|
||||
|
||||
return (
|
||||
columnTranslations[colName.toLowerCase()] || columnTranslations[colName.replace(/_/g, "").toLowerCase()] || colName
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -99,7 +99,7 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
|
||||
|
||||
// 자동 새로고침 (30초마다)
|
||||
const interval = setInterval(loadData, 30000);
|
||||
return () => clearInterval(interval);
|
||||
|
|
@ -126,7 +126,7 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
setLoading(true);
|
||||
const extractedTableName = extractTableName(element.dataSource.query);
|
||||
setTableName(extractedTableName);
|
||||
|
||||
|
||||
const token = localStorage.getItem("authToken");
|
||||
const response = await fetch("/api/dashboards/execute-query", {
|
||||
method: "POST",
|
||||
|
|
@ -144,10 +144,10 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
if (!response.ok) throw new Error("데이터 로딩 실패");
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
|
||||
if (result.success && result.data?.rows) {
|
||||
const rows = result.data.rows;
|
||||
|
||||
|
||||
// 컬럼 정보 추출 (한글 번역 적용)
|
||||
if (rows.length > 0) {
|
||||
const cols: ColumnInfo[] = Object.keys(rows[0]).map((key) => ({
|
||||
|
|
@ -156,10 +156,10 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
}));
|
||||
setColumns(cols);
|
||||
}
|
||||
|
||||
|
||||
setData(rows);
|
||||
}
|
||||
|
||||
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "데이터 로딩 실패");
|
||||
|
|
@ -171,34 +171,30 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
// 테이블 이름 한글 번역
|
||||
const translateTableName = (name: string): string => {
|
||||
const tableTranslations: { [key: string]: string } = {
|
||||
"drivers": "기사",
|
||||
"driver": "기사",
|
||||
"vehicles": "차량",
|
||||
"vehicle": "차량",
|
||||
"products": "제품",
|
||||
"product": "제품",
|
||||
"orders": "주문",
|
||||
"order": "주문",
|
||||
"customers": "고객",
|
||||
"customer": "고객",
|
||||
"deliveries": "배송",
|
||||
"delivery": "배송",
|
||||
"users": "사용자",
|
||||
"user": "사용자",
|
||||
drivers: "기사",
|
||||
driver: "기사",
|
||||
vehicles: "차량",
|
||||
vehicle: "차량",
|
||||
products: "제품",
|
||||
product: "제품",
|
||||
orders: "주문",
|
||||
order: "주문",
|
||||
customers: "고객",
|
||||
customer: "고객",
|
||||
deliveries: "배송",
|
||||
delivery: "배송",
|
||||
users: "사용자",
|
||||
user: "사용자",
|
||||
};
|
||||
|
||||
return tableTranslations[name.toLowerCase()] ||
|
||||
tableTranslations[name.replace(/_/g, '').toLowerCase()] ||
|
||||
name;
|
||||
|
||||
return tableTranslations[name.toLowerCase()] || tableTranslations[name.replace(/_/g, "").toLowerCase()] || name;
|
||||
};
|
||||
|
||||
const displayTitle = tableName ? `${translateTableName(tableName)} 목록` : "데이터 목록";
|
||||
|
||||
// 검색 필터링
|
||||
const filteredData = data.filter((row) =>
|
||||
Object.values(row).some((value) =>
|
||||
String(value).toLowerCase().includes(searchTerm.toLowerCase())
|
||||
)
|
||||
Object.values(row).some((value) => String(value).toLowerCase().includes(searchTerm.toLowerCase())),
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
|
|
@ -244,8 +240,6 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
</ul>
|
||||
</div>
|
||||
<div className="mt-2 rounded-lg bg-blue-50 p-2 text-[10px] text-blue-700">
|
||||
<p className="font-medium">⚙️ 설정 방법</p>
|
||||
<p className="mt-0.5">우측 상단 톱니바퀴 버튼을 클릭하여</p>
|
||||
<p>SQL 쿼리를 입력하고 저장하세요</p>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -263,7 +257,7 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
</div>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="flex h-7 w-7 items-center justify-center rounded border border-border bg-white p-0 text-xs hover:bg-accent disabled:opacity-50"
|
||||
className="border-border hover:bg-accent flex h-7 w-7 items-center justify-center rounded border bg-white p-0 text-xs disabled:opacity-50"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "⏳" : "🔄"}
|
||||
|
|
@ -278,7 +272,7 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
placeholder="검색..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full rounded border border-gray-300 px-2 py-1 text-xs focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
className="focus:border-primary focus:ring-primary w-full rounded border border-gray-300 px-2 py-1 text-xs focus:ring-1 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -290,10 +284,7 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
<thead className="sticky top-0 bg-gray-100">
|
||||
<tr>
|
||||
{columns.map((col) => (
|
||||
<th
|
||||
key={col.key}
|
||||
className="border border-gray-300 px-2 py-1 text-left font-semibold text-gray-700"
|
||||
>
|
||||
<th key={col.key} className="border border-gray-300 px-2 py-1 text-left font-semibold text-gray-700">
|
||||
{col.label}
|
||||
</th>
|
||||
))}
|
||||
|
|
@ -303,10 +294,7 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
{filteredData.map((row, idx) => (
|
||||
<tr key={idx} className="hover:bg-gray-50">
|
||||
{columns.map((col) => (
|
||||
<td
|
||||
key={col.key}
|
||||
className="border border-gray-300 px-2 py-1 text-gray-800"
|
||||
>
|
||||
<td key={col.key} className="border border-gray-300 px-2 py-1 text-gray-800">
|
||||
{String(row[col.key] || "")}
|
||||
</td>
|
||||
))}
|
||||
|
|
@ -323,4 +311,3 @@ export default function ListSummaryWidget({ element }: ListSummaryWidgetProps) {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -39,23 +39,21 @@ interface MarkerData {
|
|||
// 테이블명 한글 번역
|
||||
const translateTableName = (name: string): string => {
|
||||
const tableTranslations: { [key: string]: string } = {
|
||||
"vehicle_locations": "차량",
|
||||
"vehicles": "차량",
|
||||
"warehouses": "창고",
|
||||
"warehouse": "창고",
|
||||
"customers": "고객",
|
||||
"customer": "고객",
|
||||
"deliveries": "배송",
|
||||
"delivery": "배송",
|
||||
"drivers": "기사",
|
||||
"driver": "기사",
|
||||
"stores": "매장",
|
||||
"store": "매장",
|
||||
vehicle_locations: "차량",
|
||||
vehicles: "차량",
|
||||
warehouses: "창고",
|
||||
warehouse: "창고",
|
||||
customers: "고객",
|
||||
customer: "고객",
|
||||
deliveries: "배송",
|
||||
delivery: "배송",
|
||||
drivers: "기사",
|
||||
driver: "기사",
|
||||
stores: "매장",
|
||||
store: "매장",
|
||||
};
|
||||
|
||||
return tableTranslations[name.toLowerCase()] ||
|
||||
tableTranslations[name.replace(/_/g, '').toLowerCase()] ||
|
||||
name;
|
||||
|
||||
return tableTranslations[name.toLowerCase()] || tableTranslations[name.replace(/_/g, "").toLowerCase()] || name;
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -74,14 +72,14 @@ export default function MapSummaryWidget({ element }: MapSummaryWidgetProps) {
|
|||
if (element?.dataSource?.query) {
|
||||
loadMapData();
|
||||
}
|
||||
|
||||
|
||||
// 자동 새로고침 (30초마다)
|
||||
const interval = setInterval(() => {
|
||||
if (element?.dataSource?.query) {
|
||||
loadMapData();
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [element]);
|
||||
|
||||
|
|
@ -124,7 +122,7 @@ export default function MapSummaryWidget({ element }: MapSummaryWidgetProps) {
|
|||
|
||||
if (result.success && result.data?.rows) {
|
||||
const rows = result.data.rows;
|
||||
|
||||
|
||||
// 위도/경도 컬럼 찾기
|
||||
const latCol = element.chartConfig?.latitudeColumn || "latitude";
|
||||
const lngCol = element.chartConfig?.longitudeColumn || "longitude";
|
||||
|
|
@ -162,12 +160,12 @@ export default function MapSummaryWidget({ element }: MapSummaryWidgetProps) {
|
|||
{element?.dataSource?.query ? (
|
||||
<p className="text-xs text-gray-500">총 {markers.length.toLocaleString()}개 마커</p>
|
||||
) : (
|
||||
<p className="text-xs text-orange-500">⚙️ 톱니바퀴 버튼을 눌러 데이터를 연결하세요</p>
|
||||
<p className="text-xs text-orange-500">데이터를 연결하세요</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={loadMapData}
|
||||
className="flex h-7 w-7 items-center justify-center rounded border border-border bg-white p-0 text-xs hover:bg-accent disabled:opacity-50"
|
||||
className="border-border hover:bg-accent flex h-7 w-7 items-center justify-center rounded border bg-white p-0 text-xs disabled:opacity-50"
|
||||
disabled={loading || !element?.dataSource?.query}
|
||||
>
|
||||
{loading ? "⏳" : "🔄"}
|
||||
|
|
@ -182,7 +180,7 @@ export default function MapSummaryWidget({ element }: MapSummaryWidgetProps) {
|
|||
)}
|
||||
|
||||
{/* 지도 (항상 표시) */}
|
||||
<div className="relative flex-1 rounded border border-gray-300 bg-white overflow-hidden z-0">
|
||||
<div className="relative z-0 flex-1 overflow-hidden rounded border border-gray-300 bg-white">
|
||||
<MapContainer
|
||||
key={`map-${element.id}`}
|
||||
center={[36.5, 127.5]}
|
||||
|
|
|
|||
|
|
@ -21,109 +21,109 @@ interface StatusConfig {
|
|||
// 영어 상태명 → 한글 자동 변환
|
||||
const statusTranslations: { [key: string]: string } = {
|
||||
// 배송 관련
|
||||
"delayed": "지연",
|
||||
"pickup_waiting": "픽업 대기",
|
||||
"in_transit": "배송 중",
|
||||
"delivered": "배송완료",
|
||||
"pending": "대기중",
|
||||
"processing": "처리중",
|
||||
"completed": "완료",
|
||||
"cancelled": "취소됨",
|
||||
"failed": "실패",
|
||||
|
||||
delayed: "지연",
|
||||
pickup_waiting: "픽업 대기",
|
||||
in_transit: "배송 중",
|
||||
delivered: "배송완료",
|
||||
pending: "대기중",
|
||||
processing: "처리중",
|
||||
completed: "완료",
|
||||
cancelled: "취소됨",
|
||||
failed: "실패",
|
||||
|
||||
// 일반 상태
|
||||
"active": "활성",
|
||||
"inactive": "비활성",
|
||||
"enabled": "사용중",
|
||||
"disabled": "사용안함",
|
||||
"online": "온라인",
|
||||
"offline": "오프라인",
|
||||
"available": "사용가능",
|
||||
"unavailable": "사용불가",
|
||||
|
||||
active: "활성",
|
||||
inactive: "비활성",
|
||||
enabled: "사용중",
|
||||
disabled: "사용안함",
|
||||
online: "온라인",
|
||||
offline: "오프라인",
|
||||
available: "사용가능",
|
||||
unavailable: "사용불가",
|
||||
|
||||
// 승인 관련
|
||||
"approved": "승인됨",
|
||||
"rejected": "거절됨",
|
||||
"waiting": "대기중",
|
||||
|
||||
approved: "승인됨",
|
||||
rejected: "거절됨",
|
||||
waiting: "대기중",
|
||||
|
||||
// 차량 관련
|
||||
"driving": "운행중",
|
||||
"parked": "주차",
|
||||
"maintenance": "정비중",
|
||||
|
||||
driving: "운행중",
|
||||
parked: "주차",
|
||||
maintenance: "정비중",
|
||||
|
||||
// 기사 관련 (존중하는 표현)
|
||||
"waiting": "대기중",
|
||||
"resting": "휴식중",
|
||||
"unavailable": "운행불가",
|
||||
|
||||
waiting: "대기중",
|
||||
resting: "휴식중",
|
||||
unavailable: "운행불가",
|
||||
|
||||
// 기사 평가
|
||||
"excellent": "우수",
|
||||
"good": "양호",
|
||||
"average": "보통",
|
||||
"poor": "미흡",
|
||||
|
||||
excellent: "우수",
|
||||
good: "양호",
|
||||
average: "보통",
|
||||
poor: "미흡",
|
||||
|
||||
// 기사 경력
|
||||
"veteran": "베테랑",
|
||||
"experienced": "숙련",
|
||||
"intermediate": "중급",
|
||||
"beginner": "초급",
|
||||
veteran: "베테랑",
|
||||
experienced: "숙련",
|
||||
intermediate: "중급",
|
||||
beginner: "초급",
|
||||
};
|
||||
|
||||
// 영어 테이블명 → 한글 자동 변환
|
||||
const tableTranslations: { [key: string]: string } = {
|
||||
// 배송/물류 관련
|
||||
"deliveries": "배송",
|
||||
"delivery": "배송",
|
||||
"shipments": "출하",
|
||||
"shipment": "출하",
|
||||
"orders": "주문",
|
||||
"order": "주문",
|
||||
"cargo": "화물",
|
||||
"cargos": "화물",
|
||||
"packages": "소포",
|
||||
"package": "소포",
|
||||
|
||||
deliveries: "배송",
|
||||
delivery: "배송",
|
||||
shipments: "출하",
|
||||
shipment: "출하",
|
||||
orders: "주문",
|
||||
order: "주문",
|
||||
cargo: "화물",
|
||||
cargos: "화물",
|
||||
packages: "소포",
|
||||
package: "소포",
|
||||
|
||||
// 차량 관련
|
||||
"vehicles": "차량",
|
||||
"vehicle": "차량",
|
||||
"vehicle_locations": "차량위치",
|
||||
"vehicle_status": "차량상태",
|
||||
"drivers": "기사",
|
||||
"driver": "기사",
|
||||
|
||||
vehicles: "차량",
|
||||
vehicle: "차량",
|
||||
vehicle_locations: "차량위치",
|
||||
vehicle_status: "차량상태",
|
||||
drivers: "기사",
|
||||
driver: "기사",
|
||||
|
||||
// 사용자/고객 관련
|
||||
"users": "사용자",
|
||||
"user": "사용자",
|
||||
"customers": "고객",
|
||||
"customer": "고객",
|
||||
"members": "회원",
|
||||
"member": "회원",
|
||||
|
||||
users: "사용자",
|
||||
user: "사용자",
|
||||
customers: "고객",
|
||||
customer: "고객",
|
||||
members: "회원",
|
||||
member: "회원",
|
||||
|
||||
// 제품/재고 관련
|
||||
"products": "제품",
|
||||
"product": "제품",
|
||||
"items": "항목",
|
||||
"item": "항목",
|
||||
"inventory": "재고",
|
||||
"stock": "재고",
|
||||
|
||||
products: "제품",
|
||||
product: "제품",
|
||||
items: "항목",
|
||||
item: "항목",
|
||||
inventory: "재고",
|
||||
stock: "재고",
|
||||
|
||||
// 업무 관련
|
||||
"tasks": "작업",
|
||||
"task": "작업",
|
||||
"projects": "프로젝트",
|
||||
"project": "프로젝트",
|
||||
"issues": "이슈",
|
||||
"issue": "이슈",
|
||||
"tickets": "티켓",
|
||||
"ticket": "티켓",
|
||||
|
||||
tasks: "작업",
|
||||
task: "작업",
|
||||
projects: "프로젝트",
|
||||
project: "프로젝트",
|
||||
issues: "이슈",
|
||||
issue: "이슈",
|
||||
tickets: "티켓",
|
||||
ticket: "티켓",
|
||||
|
||||
// 기타
|
||||
"logs": "로그",
|
||||
"log": "로그",
|
||||
"reports": "리포트",
|
||||
"report": "리포트",
|
||||
"alerts": "알림",
|
||||
"alert": "알림",
|
||||
logs: "로그",
|
||||
log: "로그",
|
||||
reports: "리포트",
|
||||
report: "리포트",
|
||||
alerts: "알림",
|
||||
alert: "알림",
|
||||
};
|
||||
|
||||
interface StatusData {
|
||||
|
|
@ -136,12 +136,12 @@ interface StatusData {
|
|||
* - 쿼리 결과를 상태별로 카운트해서 카드로 표시
|
||||
* - 색상과 라벨은 statusConfig로 커스터마이징 가능
|
||||
*/
|
||||
export default function StatusSummaryWidget({
|
||||
element,
|
||||
export default function StatusSummaryWidget({
|
||||
element,
|
||||
title = "상태 요약",
|
||||
icon = "📊",
|
||||
bgGradient = "from-slate-50 to-blue-50",
|
||||
statusConfig
|
||||
statusConfig,
|
||||
}: StatusSummaryWidgetProps) {
|
||||
const [statusData, setStatusData] = useState<StatusData[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
|
@ -150,7 +150,7 @@ export default function StatusSummaryWidget({
|
|||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
|
||||
|
||||
// 자동 새로고침 (30초마다)
|
||||
const interval = setInterval(loadData, 30000);
|
||||
return () => clearInterval(interval);
|
||||
|
|
@ -178,7 +178,7 @@ export default function StatusSummaryWidget({
|
|||
setLoading(true);
|
||||
const extractedTableName = extractTableName(element.dataSource.query);
|
||||
setTableName(extractedTableName);
|
||||
|
||||
|
||||
const token = localStorage.getItem("authToken");
|
||||
const response = await fetch("/api/dashboards/execute-query", {
|
||||
method: "POST",
|
||||
|
|
@ -196,17 +196,17 @@ export default function StatusSummaryWidget({
|
|||
if (!response.ok) throw new Error("데이터 로딩 실패");
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
|
||||
// 데이터 처리
|
||||
if (result.success && result.data?.rows) {
|
||||
const rows = result.data.rows;
|
||||
|
||||
|
||||
// 상태별 카운트 계산
|
||||
const statusCounts: { [key: string]: number } = {};
|
||||
|
||||
|
||||
// GROUP BY 형식인지 확인
|
||||
const isGroupedData = rows.length > 0 && rows[0].count !== undefined;
|
||||
|
||||
|
||||
if (isGroupedData) {
|
||||
// GROUP BY 형식: SELECT status, COUNT(*) as count
|
||||
rows.forEach((row: any) => {
|
||||
|
|
@ -244,7 +244,7 @@ export default function StatusSummaryWidget({
|
|||
|
||||
setStatusData(formattedData);
|
||||
}
|
||||
|
||||
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "데이터 로딩 실패");
|
||||
|
|
@ -320,7 +320,6 @@ export default function StatusSummaryWidget({
|
|||
</div>
|
||||
<div className="mt-2 rounded-lg bg-blue-50 p-2 text-[10px] text-blue-700">
|
||||
<p className="font-medium">⚙️ 설정 방법</p>
|
||||
<p className="mt-0.5">우측 상단 톱니바퀴 버튼을 클릭하여</p>
|
||||
<p>SQL 쿼리를 입력하고 저장하세요</p>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -341,7 +340,7 @@ export default function StatusSummaryWidget({
|
|||
return tableTranslations[name.toLowerCase()];
|
||||
}
|
||||
// 언더스코어 제거하고 매칭 시도
|
||||
const nameWithoutUnderscore = name.replace(/_/g, '');
|
||||
const nameWithoutUnderscore = name.replace(/_/g, "");
|
||||
if (tableTranslations[nameWithoutUnderscore.toLowerCase()]) {
|
||||
return tableTranslations[nameWithoutUnderscore.toLowerCase()];
|
||||
}
|
||||
|
|
@ -357,7 +356,9 @@ export default function StatusSummaryWidget({
|
|||
{/* 헤더 */}
|
||||
<div className="mb-2 flex flex-shrink-0 items-center justify-between">
|
||||
<div className="flex-1">
|
||||
<h3 className="text-sm font-bold text-gray-900">{icon} {displayTitle}</h3>
|
||||
<h3 className="text-sm font-bold text-gray-900">
|
||||
{icon} {displayTitle}
|
||||
</h3>
|
||||
{totalCount > 0 ? (
|
||||
<p className="text-xs text-gray-500">총 {totalCount.toLocaleString()}건</p>
|
||||
) : (
|
||||
|
|
@ -366,7 +367,7 @@ export default function StatusSummaryWidget({
|
|||
</div>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="flex h-7 w-7 items-center justify-center rounded border border-border bg-white p-0 text-xs hover:bg-accent disabled:opacity-50"
|
||||
className="border-border hover:bg-accent flex h-7 w-7 items-center justify-center rounded border bg-white p-0 text-xs disabled:opacity-50"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "⏳" : "🔄"}
|
||||
|
|
@ -380,10 +381,7 @@ export default function StatusSummaryWidget({
|
|||
{statusData.map((item) => {
|
||||
const colors = getColorClasses(item.status);
|
||||
return (
|
||||
<div
|
||||
key={item.status}
|
||||
className="rounded border border-gray-200 bg-white p-1.5 shadow-sm"
|
||||
>
|
||||
<div key={item.status} className="rounded border border-gray-200 bg-white p-1.5 shadow-sm">
|
||||
<div className="mb-0.5 flex items-center gap-1">
|
||||
<div className={`h-1.5 w-1.5 rounded-full ${colors.dot}`}></div>
|
||||
<div className="text-xs font-medium text-gray-600">{item.status}</div>
|
||||
|
|
@ -397,4 +395,3 @@ export default function StatusSummaryWidget({
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -100,7 +100,14 @@ export default function TransportStatsWidget({ element, refreshInterval = 60000
|
|||
const weightKeys = ["weight", "cargo_weight", "total_weight", "중량", "무게"];
|
||||
const distanceKeys = ["distance", "total_distance", "거리", "주행거리"];
|
||||
const onTimeKeys = ["is_on_time", "on_time", "onTime", "정시", "정시도착"];
|
||||
const deliveryTimeKeys = ["delivery_duration", "delivery_time", "duration", "배송시간", "소요시간", "배송소요시간"];
|
||||
const deliveryTimeKeys = [
|
||||
"delivery_duration",
|
||||
"delivery_time",
|
||||
"duration",
|
||||
"배송시간",
|
||||
"소요시간",
|
||||
"배송소요시간",
|
||||
];
|
||||
|
||||
// 총 운송량 찾기
|
||||
let total_weight = 0;
|
||||
|
|
@ -143,7 +150,7 @@ export default function TransportStatsWidget({ element, refreshInterval = 60000
|
|||
|
||||
// 평균 배송시간 계산
|
||||
let avg_delivery_time = 0;
|
||||
|
||||
|
||||
// 1. 먼저 배송시간 컬럼이 있는지 확인
|
||||
let foundTimeColumn = false;
|
||||
for (const key of Object.keys(numericColumns)) {
|
||||
|
|
@ -167,7 +174,14 @@ export default function TransportStatsWidget({ element, refreshInterval = 60000
|
|||
// 2. 배송시간 컬럼이 없으면 날짜 컬럼에서 자동 계산
|
||||
if (!foundTimeColumn) {
|
||||
const startTimeKeys = ["created_at", "start_time", "departure_time", "출발시간", "시작시간"];
|
||||
const endTimeKeys = ["actual_delivery", "end_time", "arrival_time", "도착시간", "완료시간", "estimated_delivery"];
|
||||
const endTimeKeys = [
|
||||
"actual_delivery",
|
||||
"end_time",
|
||||
"arrival_time",
|
||||
"도착시간",
|
||||
"완료시간",
|
||||
"estimated_delivery",
|
||||
];
|
||||
|
||||
let startKey = null;
|
||||
let endKey = null;
|
||||
|
|
@ -247,9 +261,7 @@ export default function TransportStatsWidget({ element, refreshInterval = 60000
|
|||
<div className="text-center">
|
||||
<div className="mb-2 text-4xl">⚠️</div>
|
||||
<div className="text-sm font-medium text-gray-600">{error || "데이터 없음"}</div>
|
||||
{!element?.dataSource?.query && (
|
||||
<div className="mt-2 text-xs text-gray-500">톱니바퀴 아이콘을 클릭하여 쿼리를 설정하세요</div>
|
||||
)}
|
||||
{!element?.dataSource?.query && <div className="mt-2 text-xs text-gray-500">쿼리를 설정하세요</div>}
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="mt-3 rounded-lg bg-blue-500 px-4 py-2 text-sm text-white hover:bg-blue-600"
|
||||
|
|
|
|||
|
|
@ -123,7 +123,12 @@ export default function VehicleMapOnlyWidget({ element, refreshInterval = 30000
|
|||
loadVehicles();
|
||||
const interval = setInterval(loadVehicles, refreshInterval);
|
||||
return () => clearInterval(interval);
|
||||
}, [element?.dataSource?.query, element?.chartConfig?.latitudeColumn, element?.chartConfig?.longitudeColumn, refreshInterval]);
|
||||
}, [
|
||||
element?.dataSource?.query,
|
||||
element?.chartConfig?.latitudeColumn,
|
||||
element?.chartConfig?.longitudeColumn,
|
||||
refreshInterval,
|
||||
]);
|
||||
|
||||
// 쿼리 없으면 빈 지도만 표시 (안내 메시지 제거)
|
||||
|
||||
|
|
@ -172,7 +177,7 @@ export default function VehicleMapOnlyWidget({ element, refreshInterval = 30000
|
|||
|
||||
{/* 지도 영역 - 브이월드 타일맵 */}
|
||||
<div className="h-[calc(100%-60px)]">
|
||||
<div className="relative h-full overflow-hidden rounded-lg border-2 border-gray-300 bg-white z-0">
|
||||
<div className="relative z-0 h-full overflow-hidden rounded-lg border-2 border-gray-300 bg-white">
|
||||
<MapContainer
|
||||
key={`vehicle-map-${element.id}`}
|
||||
center={[36.5, 127.5]}
|
||||
|
|
@ -182,54 +187,54 @@ export default function VehicleMapOnlyWidget({ element, refreshInterval = 30000
|
|||
preferCanvas={true}
|
||||
className="z-0"
|
||||
>
|
||||
{/* 브이월드 타일맵 (HTTPS, 캐싱 적용) */}
|
||||
<TileLayer
|
||||
url={`https://api.vworld.kr/req/wmts/1.0.0/${VWORLD_API_KEY}/Base/{z}/{y}/{x}.png`}
|
||||
attribution='© <a href="https://www.vworld.kr">VWorld (국토교통부)</a>'
|
||||
maxZoom={19}
|
||||
minZoom={7}
|
||||
updateWhenIdle={true}
|
||||
updateWhenZooming={false}
|
||||
keepBuffer={2}
|
||||
/>
|
||||
{/* 브이월드 타일맵 (HTTPS, 캐싱 적용) */}
|
||||
<TileLayer
|
||||
url={`https://api.vworld.kr/req/wmts/1.0.0/${VWORLD_API_KEY}/Base/{z}/{y}/{x}.png`}
|
||||
attribution='© <a href="https://www.vworld.kr">VWorld (국토교통부)</a>'
|
||||
maxZoom={19}
|
||||
minZoom={7}
|
||||
updateWhenIdle={true}
|
||||
updateWhenZooming={false}
|
||||
keepBuffer={2}
|
||||
/>
|
||||
|
||||
{/* 차량 마커 */}
|
||||
{vehicles.map((vehicle) => (
|
||||
<React.Fragment key={vehicle.id}>
|
||||
<Circle
|
||||
center={[vehicle.lat, vehicle.lng]}
|
||||
radius={150}
|
||||
pathOptions={{
|
||||
color: getStatusColor(vehicle.status),
|
||||
fillColor: getStatusColor(vehicle.status),
|
||||
fillOpacity: 0.3,
|
||||
}}
|
||||
/>
|
||||
<Marker position={[vehicle.lat, vehicle.lng]}>
|
||||
<Popup>
|
||||
<div className="text-xs">
|
||||
<div className="mb-1 text-sm font-bold">{vehicle.name}</div>
|
||||
<div>
|
||||
<strong>기사:</strong> {vehicle.driver}
|
||||
</div>
|
||||
<div>
|
||||
<strong>상태:</strong> {getStatusText(vehicle.status)}
|
||||
</div>
|
||||
<div>
|
||||
<strong>속도:</strong> {vehicle.speed} km/h
|
||||
</div>
|
||||
<div>
|
||||
<strong>목적지:</strong> {vehicle.destination}
|
||||
</div>
|
||||
{/* 차량 마커 */}
|
||||
{vehicles.map((vehicle) => (
|
||||
<React.Fragment key={vehicle.id}>
|
||||
<Circle
|
||||
center={[vehicle.lat, vehicle.lng]}
|
||||
radius={150}
|
||||
pathOptions={{
|
||||
color: getStatusColor(vehicle.status),
|
||||
fillColor: getStatusColor(vehicle.status),
|
||||
fillOpacity: 0.3,
|
||||
}}
|
||||
/>
|
||||
<Marker position={[vehicle.lat, vehicle.lng]}>
|
||||
<Popup>
|
||||
<div className="text-xs">
|
||||
<div className="mb-1 text-sm font-bold">{vehicle.name}</div>
|
||||
<div>
|
||||
<strong>기사:</strong> {vehicle.driver}
|
||||
</div>
|
||||
</Popup>
|
||||
</Marker>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</MapContainer>
|
||||
<div>
|
||||
<strong>상태:</strong> {getStatusText(vehicle.status)}
|
||||
</div>
|
||||
<div>
|
||||
<strong>속도:</strong> {vehicle.speed} km/h
|
||||
</div>
|
||||
<div>
|
||||
<strong>목적지:</strong> {vehicle.destination}
|
||||
</div>
|
||||
</div>
|
||||
</Popup>
|
||||
</Marker>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</MapContainer>
|
||||
|
||||
{/* 지도 정보 */}
|
||||
<div className="absolute right-2 top-2 z-[1000] rounded-lg bg-white/90 p-2 shadow-lg backdrop-blur-sm">
|
||||
<div className="absolute top-2 right-2 z-[1000] rounded-lg bg-white/90 p-2 shadow-lg backdrop-blur-sm">
|
||||
<div className="text-xs text-gray-600">
|
||||
<div className="mb-1 font-semibold">🗺️ 브이월드 (VWorld)</div>
|
||||
<div className="text-xs">국토교통부 공식 지도</div>
|
||||
|
|
@ -241,9 +246,7 @@ export default function VehicleMapOnlyWidget({ element, refreshInterval = 30000
|
|||
{vehicles.length > 0 ? (
|
||||
<div className="text-xs font-semibold text-gray-900">총 {vehicles.length}대 모니터링 중</div>
|
||||
) : (
|
||||
<div className="text-xs text-gray-600">
|
||||
⚙️ 톱니바퀴 클릭하여 데이터 연결
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">데이터를 연결하세요</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -251,4 +254,3 @@ export default function VehicleMapOnlyWidget({ element, refreshInterval = 30000
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -10,13 +10,7 @@
|
|||
|
||||
import { useState, useEffect } from "react";
|
||||
import { DashboardElement } from "@/components/admin/dashboard/types";
|
||||
import {
|
||||
WORK_TYPE_LABELS,
|
||||
WORK_STATUS_LABELS,
|
||||
WORK_STATUS_COLORS,
|
||||
WorkType,
|
||||
WorkStatus,
|
||||
} from "@/types/workHistory";
|
||||
import { WORK_TYPE_LABELS, WORK_STATUS_LABELS, WORK_STATUS_COLORS, WorkType, WorkStatus } from "@/types/workHistory";
|
||||
|
||||
interface WorkHistoryWidgetProps {
|
||||
element: DashboardElement;
|
||||
|
|
@ -97,11 +91,7 @@ export default function WorkHistoryWidget({ element, refreshInterval = 60000 }:
|
|||
<div className="text-center">
|
||||
<div className="mb-2 text-4xl">⚠️</div>
|
||||
<div className="text-sm font-medium text-gray-600">{error}</div>
|
||||
{!element.dataSource?.query && (
|
||||
<div className="mt-2 text-xs text-gray-500">
|
||||
톱니바퀴 아이콘을 클릭하여 쿼리를 설정하세요
|
||||
</div>
|
||||
)}
|
||||
{!element.dataSource?.query && <div className="mt-2 text-xs text-gray-500">쿼리를 설정하세요</div>}
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="mt-3 rounded-lg bg-blue-500 px-4 py-2 text-sm text-white hover:bg-blue-600"
|
||||
|
|
|
|||
Loading…
Reference in New Issue