chpark-sync #425
File diff suppressed because it is too large
Load Diff
|
|
@ -10,3 +10,8 @@ BOOKING_DATA_SOURCE=file
|
|||
MAINTENANCE_DATA_SOURCE=memory
|
||||
DOCUMENT_DATA_SOURCE=memory
|
||||
|
||||
|
||||
# OpenWeatherMap API 키 추가 (실시간 날씨)
|
||||
# https://openweathermap.org/api 에서 무료 가입 후 발급
|
||||
OPENWEATHER_API_KEY=your_openweathermap_api_key_here
|
||||
|
||||
|
|
|
|||
|
|
@ -55,6 +55,8 @@ import riskAlertRoutes from "./routes/riskAlertRoutes"; // 리스크/알림 관
|
|||
import todoRoutes from "./routes/todoRoutes"; // To-Do 관리
|
||||
import bookingRoutes from "./routes/bookingRoutes"; // 예약 요청 관리
|
||||
import mapDataRoutes from "./routes/mapDataRoutes"; // 지도 데이터 관리
|
||||
import yardLayoutRoutes from "./routes/yardLayoutRoutes"; // 야드 관리 3D
|
||||
import materialRoutes from "./routes/materialRoutes"; // 자재 관리
|
||||
import { BatchSchedulerService } from "./services/batchSchedulerService";
|
||||
// import collectionRoutes from "./routes/collectionRoutes"; // 임시 주석
|
||||
// import batchRoutes from "./routes/batchRoutes"; // 임시 주석
|
||||
|
|
@ -204,6 +206,8 @@ app.use("/api/risk-alerts", riskAlertRoutes); // 리스크/알림 관리
|
|||
app.use("/api/todos", todoRoutes); // To-Do 관리
|
||||
app.use("/api/bookings", bookingRoutes); // 예약 요청 관리
|
||||
app.use("/api/map-data", mapDataRoutes); // 지도 데이터 조회
|
||||
app.use("/api/yard-layouts", yardLayoutRoutes); // 야드 관리 3D
|
||||
app.use("/api/materials", materialRoutes); // 자재 관리
|
||||
// app.use("/api/collections", collectionRoutes); // 임시 주석
|
||||
// app.use("/api/batch", batchRoutes); // 임시 주석
|
||||
// app.use('/api/users', userRoutes);
|
||||
|
|
@ -231,6 +235,14 @@ app.listen(PORT, HOST, async () => {
|
|||
logger.info(`🔗 Health check: http://${HOST}:${PORT}/health`);
|
||||
logger.info(`🌐 External access: http://39.117.244.52:${PORT}/health`);
|
||||
|
||||
// 대시보드 마이그레이션 실행
|
||||
try {
|
||||
const { runDashboardMigration } = await import("./database/runMigration");
|
||||
await runDashboardMigration();
|
||||
} catch (error) {
|
||||
logger.error(`❌ 대시보드 마이그레이션 실패:`, error);
|
||||
}
|
||||
|
||||
// 배치 스케줄러 초기화
|
||||
try {
|
||||
await BatchSchedulerService.initialize();
|
||||
|
|
@ -241,7 +253,9 @@ app.listen(PORT, HOST, async () => {
|
|||
|
||||
// 리스크/알림 자동 갱신 시작
|
||||
try {
|
||||
const { RiskAlertCacheService } = await import('./services/riskAlertCacheService');
|
||||
const { RiskAlertCacheService } = await import(
|
||||
"./services/riskAlertCacheService"
|
||||
);
|
||||
const cacheService = RiskAlertCacheService.getInstance();
|
||||
cacheService.startAutoRefresh();
|
||||
logger.info(`⏰ 리스크/알림 자동 갱신이 시작되었습니다. (10분 간격)`);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,68 @@
|
|||
import { Request, Response } from "express";
|
||||
import MaterialService from "../services/MaterialService";
|
||||
|
||||
export class MaterialController {
|
||||
// 임시 자재 마스터 목록 조회
|
||||
async getTempMaterials(req: Request, res: Response) {
|
||||
try {
|
||||
const { search, category, page, limit } = req.query;
|
||||
|
||||
const result = await MaterialService.getTempMaterials({
|
||||
search: search as string,
|
||||
category: category as string,
|
||||
page: page ? parseInt(page as string) : 1,
|
||||
limit: limit ? parseInt(limit as string) : 20,
|
||||
});
|
||||
|
||||
return res.json({ success: true, ...result });
|
||||
} catch (error: any) {
|
||||
console.error("Error fetching temp materials:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "자재 목록 조회 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 특정 자재 상세 조회
|
||||
async getTempMaterialByCode(req: Request, res: Response) {
|
||||
try {
|
||||
const { code } = req.params;
|
||||
const material = await MaterialService.getTempMaterialByCode(code);
|
||||
|
||||
if (!material) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: "자재를 찾을 수 없습니다.",
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({ success: true, data: material });
|
||||
} catch (error: any) {
|
||||
console.error("Error fetching temp material:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "자재 조회 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 카테고리 목록 조회
|
||||
async getCategories(req: Request, res: Response) {
|
||||
try {
|
||||
const categories = await MaterialService.getCategories();
|
||||
return res.json({ success: true, data: categories });
|
||||
} catch (error: any) {
|
||||
console.error("Error fetching categories:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "카테고리 목록 조회 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new MaterialController();
|
||||
|
|
@ -0,0 +1,299 @@
|
|||
import { Request, Response } from "express";
|
||||
import YardLayoutService from "../services/YardLayoutService";
|
||||
|
||||
export class YardLayoutController {
|
||||
// 모든 야드 레이아웃 목록 조회
|
||||
async getAllLayouts(req: Request, res: Response) {
|
||||
try {
|
||||
const layouts = await YardLayoutService.getAllLayouts();
|
||||
res.json({ success: true, data: layouts });
|
||||
} catch (error: any) {
|
||||
console.error("Error fetching yard layouts:", error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: "야드 레이아웃 목록 조회 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 특정 야드 레이아웃 상세 조회
|
||||
async getLayoutById(req: Request, res: Response) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const layout = await YardLayoutService.getLayoutById(parseInt(id));
|
||||
|
||||
if (!layout) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: "야드 레이아웃을 찾을 수 없습니다.",
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({ success: true, data: layout });
|
||||
} catch (error: any) {
|
||||
console.error("Error fetching yard layout:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "야드 레이아웃 조회 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 새 야드 레이아웃 생성
|
||||
async createLayout(req: Request, res: Response) {
|
||||
try {
|
||||
const { name, description } = req.body;
|
||||
|
||||
if (!name) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: "야드 이름은 필수입니다.",
|
||||
});
|
||||
}
|
||||
|
||||
const created_by = (req as any).user?.userId || "system";
|
||||
const layout = await YardLayoutService.createLayout({
|
||||
name,
|
||||
description,
|
||||
created_by,
|
||||
});
|
||||
|
||||
return res.status(201).json({ success: true, data: layout });
|
||||
} catch (error: any) {
|
||||
console.error("Error creating yard layout:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "야드 레이아웃 생성 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 야드 레이아웃 수정
|
||||
async updateLayout(req: Request, res: Response) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { name, description } = req.body;
|
||||
|
||||
const layout = await YardLayoutService.updateLayout(parseInt(id), {
|
||||
name,
|
||||
description,
|
||||
});
|
||||
|
||||
if (!layout) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: "야드 레이아웃을 찾을 수 없습니다.",
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({ success: true, data: layout });
|
||||
} catch (error: any) {
|
||||
console.error("Error updating yard layout:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "야드 레이아웃 수정 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 야드 레이아웃 삭제
|
||||
async deleteLayout(req: Request, res: Response) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const layout = await YardLayoutService.deleteLayout(parseInt(id));
|
||||
|
||||
if (!layout) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: "야드 레이아웃을 찾을 수 없습니다.",
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({
|
||||
success: true,
|
||||
message: "야드 레이아웃이 삭제되었습니다.",
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("Error deleting yard layout:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "야드 레이아웃 삭제 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 특정 야드의 모든 배치 자재 조회
|
||||
async getPlacementsByLayoutId(req: Request, res: Response) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const placements = await YardLayoutService.getPlacementsByLayoutId(
|
||||
parseInt(id)
|
||||
);
|
||||
|
||||
res.json({ success: true, data: placements });
|
||||
} catch (error: any) {
|
||||
console.error("Error fetching placements:", error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: "배치 자재 조회 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 야드에 자재 배치 추가
|
||||
async addMaterialPlacement(req: Request, res: Response) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const placementData = req.body;
|
||||
|
||||
if (!placementData.external_material_id || !placementData.material_code) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: "자재 정보가 필요합니다.",
|
||||
});
|
||||
}
|
||||
|
||||
const placement = await YardLayoutService.addMaterialPlacement(
|
||||
parseInt(id),
|
||||
placementData
|
||||
);
|
||||
|
||||
return res.status(201).json({ success: true, data: placement });
|
||||
} catch (error: any) {
|
||||
console.error("Error adding material placement:", error);
|
||||
|
||||
if (error.code === "23505") {
|
||||
// 유니크 제약 조건 위반
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: "이미 배치된 자재입니다.",
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "자재 배치 추가 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 배치 정보 수정
|
||||
async updatePlacement(req: Request, res: Response) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const placementData = req.body;
|
||||
|
||||
const placement = await YardLayoutService.updatePlacement(
|
||||
parseInt(id),
|
||||
placementData
|
||||
);
|
||||
|
||||
if (!placement) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: "배치 정보를 찾을 수 없습니다.",
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({ success: true, data: placement });
|
||||
} catch (error: any) {
|
||||
console.error("Error updating placement:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "배치 정보 수정 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 배치 해제
|
||||
async removePlacement(req: Request, res: Response) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const placement = await YardLayoutService.removePlacement(parseInt(id));
|
||||
|
||||
if (!placement) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: "배치 정보를 찾을 수 없습니다.",
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({ success: true, message: "배치가 해제되었습니다." });
|
||||
} catch (error: any) {
|
||||
console.error("Error removing placement:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "배치 해제 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 여러 배치 일괄 업데이트
|
||||
async batchUpdatePlacements(req: Request, res: Response) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { placements } = req.body;
|
||||
|
||||
if (!Array.isArray(placements) || placements.length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: "배치 목록이 필요합니다.",
|
||||
});
|
||||
}
|
||||
|
||||
const updatedPlacements = await YardLayoutService.batchUpdatePlacements(
|
||||
parseInt(id),
|
||||
placements
|
||||
);
|
||||
|
||||
return res.json({ success: true, data: updatedPlacements });
|
||||
} catch (error: any) {
|
||||
console.error("Error batch updating placements:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "배치 일괄 업데이트 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 야드 레이아웃 복제
|
||||
async duplicateLayout(req: Request, res: Response) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { name } = req.body;
|
||||
|
||||
if (!name) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: "새 야드 이름은 필수입니다.",
|
||||
});
|
||||
}
|
||||
|
||||
const layout = await YardLayoutService.duplicateLayout(
|
||||
parseInt(id),
|
||||
name
|
||||
);
|
||||
|
||||
return res.status(201).json({ success: true, data: layout });
|
||||
} catch (error: any) {
|
||||
console.error("Error duplicating yard layout:", error);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: "야드 레이아웃 복제 중 오류가 발생했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new YardLayoutController();
|
||||
|
|
@ -17,19 +17,54 @@ export class OpenApiProxyController {
|
|||
|
||||
console.log(`🌤️ 날씨 조회 요청: ${city}`);
|
||||
|
||||
// 기상청 API Hub 키 확인
|
||||
// 1순위: OpenWeatherMap API (실시간에 가까움, 10분마다 업데이트)
|
||||
const openWeatherKey = process.env.OPENWEATHER_API_KEY;
|
||||
if (openWeatherKey) {
|
||||
try {
|
||||
console.log(`🌍 OpenWeatherMap API 호출: ${city}`);
|
||||
const response = await axios.get('https://api.openweathermap.org/data/2.5/weather', {
|
||||
params: {
|
||||
q: `${city},KR`,
|
||||
appid: openWeatherKey,
|
||||
units: 'metric',
|
||||
lang: 'kr',
|
||||
},
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
const data = response.data;
|
||||
const weatherData = {
|
||||
city: data.name,
|
||||
country: data.sys.country,
|
||||
temperature: Math.round(data.main.temp),
|
||||
feelsLike: Math.round(data.main.feels_like),
|
||||
humidity: data.main.humidity,
|
||||
pressure: data.main.pressure,
|
||||
weatherMain: data.weather[0].main,
|
||||
weatherDescription: data.weather[0].description,
|
||||
weatherIcon: data.weather[0].icon,
|
||||
windSpeed: Math.round(data.wind.speed * 10) / 10,
|
||||
clouds: data.clouds.all,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
console.log(`✅ OpenWeatherMap 날씨 조회 성공: ${weatherData.city} ${weatherData.temperature}°C`);
|
||||
res.json({ success: true, data: weatherData });
|
||||
return;
|
||||
} catch (error) {
|
||||
console.warn('⚠️ OpenWeatherMap API 실패, 기상청 API로 폴백:', error instanceof Error ? error.message : error);
|
||||
}
|
||||
}
|
||||
|
||||
// 2순위: 기상청 API Hub (매시간 정시 데이터)
|
||||
const apiKey = process.env.KMA_API_KEY;
|
||||
|
||||
// API 키가 없으면 테스트 모드로 실시간 날씨 제공
|
||||
// API 키가 없으면 오류 반환
|
||||
if (!apiKey) {
|
||||
console.log('⚠️ 기상청 API 키가 없습니다. 테스트 데이터를 반환합니다.');
|
||||
|
||||
const regionCode = getKMARegionCode(city as string);
|
||||
const weatherData = generateRealisticWeatherData(regionCode?.name || (city as string));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: weatherData,
|
||||
console.log('⚠️ 기상청 API 키가 설정되지 않았습니다.');
|
||||
res.status(503).json({
|
||||
success: false,
|
||||
message: '기상청 API 키가 설정되지 않았습니다. 관리자에게 문의하세요.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
|
@ -48,32 +83,39 @@ export class OpenApiProxyController {
|
|||
// 기상청 API Hub 사용 (apihub.kma.go.kr)
|
||||
const now = new Date();
|
||||
|
||||
// 기상청 데이터는 매시간 정시(XX:00)에 발표되고 약 10분 후 조회 가능
|
||||
// 현재 시각이 XX:10 이전이면 이전 시간 데이터 조회
|
||||
const minute = now.getMinutes();
|
||||
let targetTime = new Date(now);
|
||||
// 한국 시간(KST = UTC+9)으로 변환
|
||||
const kstOffset = 9 * 60 * 60 * 1000; // 9시간을 밀리초로
|
||||
const kstNow = new Date(now.getTime() + kstOffset);
|
||||
|
||||
if (minute < 10) {
|
||||
// 아직 이번 시간 데이터가 업데이트되지 않음 → 이전 시간으로
|
||||
targetTime = new Date(now.getTime() - 60 * 60 * 1000);
|
||||
}
|
||||
// 기상청 지상관측 데이터는 매시간 정시(XX:00)에 발표
|
||||
// 가장 최근의 정시 데이터를 가져오기 위해 현재 시간의 정시로 설정
|
||||
const targetTime = new Date(kstNow);
|
||||
|
||||
// tm 파라미터: YYYYMMDDHH00 형식 (정시만 조회)
|
||||
const year = targetTime.getFullYear();
|
||||
const month = String(targetTime.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(targetTime.getDate()).padStart(2, '0');
|
||||
const hour = String(targetTime.getHours()).padStart(2, '0');
|
||||
const year = targetTime.getUTCFullYear();
|
||||
const month = String(targetTime.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(targetTime.getUTCDate()).padStart(2, '0');
|
||||
const hour = String(targetTime.getUTCHours()).padStart(2, '0');
|
||||
const tm = `${year}${month}${day}${hour}00`;
|
||||
|
||||
// 기상청 API Hub - 지상관측시간자료
|
||||
const url = 'https://apihub.kma.go.kr/api/typ01/url/kma_sfctm2.php';
|
||||
console.log(`🕐 현재 시각(KST): ${kstNow.toISOString().slice(0, 16).replace('T', ' ')}, 조회 시각: ${tm}`);
|
||||
|
||||
console.log(`📡 기상청 API Hub 호출: ${regionCode.name} (관측소: ${regionCode.stnId}, 시간: ${tm})`);
|
||||
// 기상청 API Hub - 지상관측시간자료 (시간 범위 조회로 최신 데이터 확보)
|
||||
// sfctm3: 시간 범위 조회 가능 (tm1~tm2)
|
||||
const url = 'https://apihub.kma.go.kr/api/typ01/url/kma_sfctm3.php';
|
||||
|
||||
// 최근 1시간 범위 조회 (현재 시간 - 1시간 ~ 현재 시간) - KST 기준
|
||||
const tm1Time = new Date(kstNow.getTime() - 60 * 60 * 1000); // 1시간 전
|
||||
const tm1 = `${tm1Time.getUTCFullYear()}${String(tm1Time.getUTCMonth() + 1).padStart(2, '0')}${String(tm1Time.getUTCDate()).padStart(2, '0')}${String(tm1Time.getUTCHours()).padStart(2, '0')}00`;
|
||||
const tm2 = tm; // 현재 시간
|
||||
|
||||
console.log(`📡 기상청 API Hub 호출: ${regionCode.name} (관측소: ${regionCode.stnId}, 기간: ${tm1}~${tm2})`);
|
||||
|
||||
const response = await axios.get(url, {
|
||||
params: {
|
||||
tm: tm,
|
||||
stn: 0, // 0 = 전체 관측소 데이터 조회
|
||||
tm1: tm1,
|
||||
tm2: tm2,
|
||||
stn: regionCode.stnId, // 특정 관측소만 조회
|
||||
authKey: apiKey,
|
||||
help: 0,
|
||||
disp: 1,
|
||||
|
|
@ -95,30 +137,36 @@ export class OpenApiProxyController {
|
|||
} catch (error: unknown) {
|
||||
console.error('❌ 날씨 조회 실패:', error);
|
||||
|
||||
// API 호출 실패 시 자동으로 테스트 모드로 전환
|
||||
// API 호출 실패 시 명확한 오류 메시지 반환
|
||||
if (axios.isAxiosError(error)) {
|
||||
const status = error.response?.status;
|
||||
|
||||
// 모든 오류 → 테스트 데이터 반환
|
||||
console.log('⚠️ API 오류 발생. 테스트 데이터를 반환합니다.');
|
||||
const { city = '서울' } = req.query;
|
||||
const regionCode = getKMARegionCode(city as string);
|
||||
const weatherData = generateRealisticWeatherData(regionCode?.name || (city as string));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: weatherData,
|
||||
});
|
||||
if (status === 401 || status === 403) {
|
||||
res.status(401).json({
|
||||
success: false,
|
||||
message: '기상청 API 인증에 실패했습니다. API 키를 확인하세요.',
|
||||
});
|
||||
} else if (status === 404) {
|
||||
res.status(404).json({
|
||||
success: false,
|
||||
message: '기상청 API에서 데이터를 찾을 수 없습니다.',
|
||||
});
|
||||
} else if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
|
||||
res.status(504).json({
|
||||
success: false,
|
||||
message: '기상청 API 연결 시간이 초과되었습니다. 잠시 후 다시 시도하세요.',
|
||||
});
|
||||
} else {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: '기상청 API 호출 중 오류가 발생했습니다.',
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// 예상치 못한 오류 → 테스트 데이터 반환
|
||||
console.log('⚠️ 예상치 못한 오류. 테스트 데이터를 반환합니다.');
|
||||
const { city = '서울' } = req.query;
|
||||
const regionCode = getKMARegionCode(city as string);
|
||||
const weatherData = generateRealisticWeatherData(regionCode?.name || (city as string));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: weatherData,
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: '날씨 정보를 가져오는 중 예상치 못한 오류가 발생했습니다.',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -169,15 +217,19 @@ export class OpenApiProxyController {
|
|||
} catch (error: unknown) {
|
||||
console.error('❌ 환율 조회 실패:', error);
|
||||
|
||||
// API 호출 실패 시 실제 근사값 반환
|
||||
console.log('⚠️ API 오류 발생. 근사값을 반환합니다.');
|
||||
const { base = 'KRW', target = 'USD' } = req.query;
|
||||
const approximateRate = generateRealisticExchangeRate(base as string, target as string);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: approximateRate,
|
||||
});
|
||||
// API 호출 실패 시 명확한 오류 메시지 반환
|
||||
if (axios.isAxiosError(error)) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: '환율 정보를 가져오는 중 오류가 발생했습니다.',
|
||||
error: error.message,
|
||||
});
|
||||
} else {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: '환율 정보를 가져오는 중 예상치 못한 오류가 발생했습니다.',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -605,19 +657,26 @@ function parseKMAHubWeatherData(data: any, regionCode: { name: string; stnId: st
|
|||
throw new Error('날씨 데이터를 파싱할 수 없습니다.');
|
||||
}
|
||||
|
||||
// 요청한 관측소(stnId)의 데이터 찾기
|
||||
const targetLine = lines.find((line: string) => {
|
||||
// 요청한 관측소(stnId)의 모든 데이터 찾기 (시간 범위 조회 시 여러 줄 반환됨)
|
||||
const targetLines = lines.filter((line: string) => {
|
||||
const cols = line.trim().split(/\s+/);
|
||||
return cols[1] === regionCode.stnId; // STN 컬럼 (인덱스 1)
|
||||
});
|
||||
|
||||
if (!targetLine) {
|
||||
if (targetLines.length === 0) {
|
||||
throw new Error(`${regionCode.name} 관측소 데이터를 찾을 수 없습니다.`);
|
||||
}
|
||||
|
||||
// 가장 최근 데이터 선택 (마지막 줄)
|
||||
const targetLine = targetLines[targetLines.length - 1];
|
||||
|
||||
// 데이터 라인 파싱 (공백으로 구분)
|
||||
const values = targetLine.trim().split(/\s+/);
|
||||
|
||||
// 관측 시각 로깅
|
||||
const obsTime = values[0]; // YYMMDDHHMI
|
||||
console.log(`🕐 관측 시각: ${obsTime} (${regionCode.name})`);
|
||||
|
||||
// 기상청 API Hub 데이터 형식 (실제 응답 기준):
|
||||
// [0]YYMMDDHHMI [1]STN [2]WD [3]WS [4]GST_WD [5]GST_WS [6]GST_TM [7]PA [8]PS [9]PT [10]PR [11]TA [12]TD [13]HM [14]PV [15]RN ...
|
||||
const temperature = parseFloat(values[11]) || 0; // TA: 기온 (인덱스 11)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,42 @@
|
|||
import { PostgreSQLService } from './PostgreSQLService';
|
||||
|
||||
/**
|
||||
* 데이터베이스 마이그레이션 실행
|
||||
* dashboard_elements 테이블에 custom_title, show_header 컬럼 추가
|
||||
*/
|
||||
export async function runDashboardMigration() {
|
||||
try {
|
||||
console.log('🔄 대시보드 마이그레이션 시작...');
|
||||
|
||||
// custom_title 컬럼 추가
|
||||
await PostgreSQLService.query(`
|
||||
ALTER TABLE dashboard_elements
|
||||
ADD COLUMN IF NOT EXISTS custom_title VARCHAR(255)
|
||||
`);
|
||||
console.log('✅ custom_title 컬럼 추가 완료');
|
||||
|
||||
// show_header 컬럼 추가
|
||||
await PostgreSQLService.query(`
|
||||
ALTER TABLE dashboard_elements
|
||||
ADD COLUMN IF NOT EXISTS show_header BOOLEAN DEFAULT true
|
||||
`);
|
||||
console.log('✅ show_header 컬럼 추가 완료');
|
||||
|
||||
// 기존 데이터 업데이트
|
||||
await PostgreSQLService.query(`
|
||||
UPDATE dashboard_elements
|
||||
SET show_header = true
|
||||
WHERE show_header IS NULL
|
||||
`);
|
||||
console.log('✅ 기존 데이터 업데이트 완료');
|
||||
|
||||
console.log('✅ 대시보드 마이그레이션 완료!');
|
||||
} catch (error) {
|
||||
console.error('❌ 대시보드 마이그레이션 실패:', error);
|
||||
// 이미 컬럼이 있는 경우는 무시
|
||||
if (error instanceof Error && error.message.includes('already exists')) {
|
||||
console.log('ℹ️ 컬럼이 이미 존재합니다.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import express from "express";
|
||||
import MaterialController from "../controllers/MaterialController";
|
||||
import { authenticateToken } from "../middleware/authMiddleware";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// 모든 라우트에 인증 미들웨어 적용
|
||||
router.use(authenticateToken);
|
||||
|
||||
// 임시 자재 마스터 관리
|
||||
router.get("/temp", MaterialController.getTempMaterials);
|
||||
router.get("/temp/categories", MaterialController.getCategories);
|
||||
router.get("/temp/:code", MaterialController.getTempMaterialByCode);
|
||||
|
||||
export default router;
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
import express from "express";
|
||||
import { query } from "../database/db";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* 차량 위치 자동 업데이트 API
|
||||
* - 모든 active/warning 상태 차량의 위치를 랜덤하게 조금씩 이동
|
||||
*/
|
||||
router.post("/move", async (req, res) => {
|
||||
try {
|
||||
// move_vehicles() 함수 실행
|
||||
await query("SELECT move_vehicles()");
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: "차량 위치가 업데이트되었습니다"
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("차량 위치 업데이트 오류:", error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: "차량 위치 업데이트 실패"
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 차량 위치 목록 조회
|
||||
*/
|
||||
router.get("/locations", async (req, res) => {
|
||||
try {
|
||||
const result = await query(`
|
||||
SELECT * FROM vehicle_locations
|
||||
ORDER BY last_update DESC
|
||||
`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: result.rows
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("차량 위치 조회 오류:", error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: "차량 위치 조회 실패"
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import express from "express";
|
||||
import YardLayoutController from "../controllers/YardLayoutController";
|
||||
import { authenticateToken } from "../middleware/authMiddleware";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// 모든 라우트에 인증 미들웨어 적용
|
||||
router.use(authenticateToken);
|
||||
|
||||
// 야드 레이아웃 관리
|
||||
router.get("/", YardLayoutController.getAllLayouts);
|
||||
router.get("/:id", YardLayoutController.getLayoutById);
|
||||
router.post("/", YardLayoutController.createLayout);
|
||||
router.put("/:id", YardLayoutController.updateLayout);
|
||||
router.delete("/:id", YardLayoutController.deleteLayout);
|
||||
router.post("/:id/duplicate", YardLayoutController.duplicateLayout);
|
||||
|
||||
// 자재 배치 관리
|
||||
router.get("/:id/placements", YardLayoutController.getPlacementsByLayoutId);
|
||||
router.post("/:id/placements", YardLayoutController.addMaterialPlacement);
|
||||
router.put("/:id/placements/batch", YardLayoutController.batchUpdatePlacements);
|
||||
|
||||
// 개별 배치 관리 (별도 경로)
|
||||
router.put("/placements/:id", YardLayoutController.updatePlacement);
|
||||
router.delete("/placements/:id", YardLayoutController.removePlacement);
|
||||
|
||||
export default router;
|
||||
|
|
@ -1,23 +1,25 @@
|
|||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { PostgreSQLService } from '../database/PostgreSQLService';
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { PostgreSQLService } from "../database/PostgreSQLService";
|
||||
import {
|
||||
Dashboard,
|
||||
DashboardElement,
|
||||
CreateDashboardRequest,
|
||||
UpdateDashboardRequest,
|
||||
DashboardListQuery
|
||||
} from '../types/dashboard';
|
||||
DashboardListQuery,
|
||||
} from "../types/dashboard";
|
||||
|
||||
/**
|
||||
* 대시보드 서비스 - Raw Query 방식
|
||||
* PostgreSQL 직접 연결을 통한 CRUD 작업
|
||||
*/
|
||||
export class DashboardService {
|
||||
|
||||
/**
|
||||
* 대시보드 생성
|
||||
*/
|
||||
static async createDashboard(data: CreateDashboardRequest, userId: string): Promise<Dashboard> {
|
||||
static async createDashboard(
|
||||
data: CreateDashboardRequest,
|
||||
userId: string
|
||||
): Promise<Dashboard> {
|
||||
const dashboardId = uuidv4();
|
||||
const now = new Date();
|
||||
|
||||
|
|
@ -25,23 +27,27 @@ export class DashboardService {
|
|||
// 트랜잭션으로 대시보드와 요소들을 함께 생성
|
||||
const result = await PostgreSQLService.transaction(async (client) => {
|
||||
// 1. 대시보드 메인 정보 저장
|
||||
await client.query(`
|
||||
await client.query(
|
||||
`
|
||||
INSERT INTO dashboards (
|
||||
id, title, description, is_public, created_by,
|
||||
created_at, updated_at, tags, category, view_count
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
`, [
|
||||
dashboardId,
|
||||
data.title,
|
||||
data.description || null,
|
||||
data.isPublic || false,
|
||||
userId,
|
||||
now,
|
||||
now,
|
||||
JSON.stringify(data.tags || []),
|
||||
data.category || null,
|
||||
0
|
||||
]);
|
||||
created_at, updated_at, tags, category, view_count, settings
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
`,
|
||||
[
|
||||
dashboardId,
|
||||
data.title,
|
||||
data.description || null,
|
||||
data.isPublic || false,
|
||||
userId,
|
||||
now,
|
||||
now,
|
||||
JSON.stringify(data.tags || []),
|
||||
data.category || null,
|
||||
0,
|
||||
JSON.stringify(data.settings || {}),
|
||||
]
|
||||
);
|
||||
|
||||
// 2. 대시보드 요소들 저장
|
||||
if (data.elements && data.elements.length > 0) {
|
||||
|
|
@ -49,30 +55,38 @@ export class DashboardService {
|
|||
const element = data.elements[i];
|
||||
const elementId = uuidv4(); // 항상 새로운 UUID 생성
|
||||
|
||||
await client.query(`
|
||||
await client.query(
|
||||
`
|
||||
INSERT INTO dashboard_elements (
|
||||
id, dashboard_id, element_type, element_subtype,
|
||||
position_x, position_y, width, height,
|
||||
title, content, data_source_config, chart_config,
|
||||
title, custom_title, show_header, content, data_source_config, chart_config,
|
||||
list_config, yard_config,
|
||||
display_order, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
|
||||
`, [
|
||||
elementId,
|
||||
dashboardId,
|
||||
element.type,
|
||||
element.subtype,
|
||||
element.position.x,
|
||||
element.position.y,
|
||||
element.size.width,
|
||||
element.size.height,
|
||||
element.title,
|
||||
element.content || null,
|
||||
JSON.stringify(element.dataSource || {}),
|
||||
JSON.stringify(element.chartConfig || {}),
|
||||
i,
|
||||
now,
|
||||
now
|
||||
]);
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
|
||||
`,
|
||||
[
|
||||
elementId,
|
||||
dashboardId,
|
||||
element.type,
|
||||
element.subtype,
|
||||
element.position.x,
|
||||
element.position.y,
|
||||
element.size.width,
|
||||
element.size.height,
|
||||
element.title,
|
||||
element.customTitle || null,
|
||||
element.showHeader !== false, // 기본값 true
|
||||
element.content || null,
|
||||
JSON.stringify(element.dataSource || {}),
|
||||
JSON.stringify(element.chartConfig || {}),
|
||||
JSON.stringify(element.listConfig || null),
|
||||
JSON.stringify(element.yardConfig || null),
|
||||
i,
|
||||
now,
|
||||
now,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -83,7 +97,7 @@ export class DashboardService {
|
|||
try {
|
||||
const dashboard = await this.getDashboardById(dashboardId, userId);
|
||||
if (!dashboard) {
|
||||
console.error('대시보드 생성은 성공했으나 조회에 실패:', dashboardId);
|
||||
console.error("대시보드 생성은 성공했으나 조회에 실패:", dashboardId);
|
||||
// 생성은 성공했으므로 기본 정보만이라도 반환
|
||||
return {
|
||||
id: dashboardId,
|
||||
|
|
@ -97,13 +111,13 @@ export class DashboardService {
|
|||
tags: data.tags || [],
|
||||
category: data.category,
|
||||
viewCount: 0,
|
||||
elements: data.elements || []
|
||||
elements: data.elements || [],
|
||||
};
|
||||
}
|
||||
|
||||
return dashboard;
|
||||
} catch (fetchError) {
|
||||
console.error('생성된 대시보드 조회 중 오류:', fetchError);
|
||||
console.error("생성된 대시보드 조회 중 오류:", fetchError);
|
||||
// 생성은 성공했으므로 기본 정보 반환
|
||||
return {
|
||||
id: dashboardId,
|
||||
|
|
@ -117,12 +131,11 @@ export class DashboardService {
|
|||
tags: data.tags || [],
|
||||
category: data.category,
|
||||
viewCount: 0,
|
||||
elements: data.elements || []
|
||||
elements: data.elements || [],
|
||||
};
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Dashboard creation error:', error);
|
||||
console.error("Dashboard creation error:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -137,29 +150,33 @@ export class DashboardService {
|
|||
search,
|
||||
category,
|
||||
isPublic,
|
||||
createdBy
|
||||
createdBy,
|
||||
} = query;
|
||||
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
try {
|
||||
// 기본 WHERE 조건
|
||||
let whereConditions = ['d.deleted_at IS NULL'];
|
||||
let whereConditions = ["d.deleted_at IS NULL"];
|
||||
let params: any[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
// 권한 필터링
|
||||
if (userId) {
|
||||
whereConditions.push(`(d.created_by = $${paramIndex} OR d.is_public = true)`);
|
||||
whereConditions.push(
|
||||
`(d.created_by = $${paramIndex} OR d.is_public = true)`
|
||||
);
|
||||
params.push(userId);
|
||||
paramIndex++;
|
||||
} else {
|
||||
whereConditions.push('d.is_public = true');
|
||||
whereConditions.push("d.is_public = true");
|
||||
}
|
||||
|
||||
// 검색 조건
|
||||
if (search) {
|
||||
whereConditions.push(`(d.title ILIKE $${paramIndex} OR d.description ILIKE $${paramIndex + 1})`);
|
||||
whereConditions.push(
|
||||
`(d.title ILIKE $${paramIndex} OR d.description ILIKE $${paramIndex + 1})`
|
||||
);
|
||||
params.push(`%${search}%`, `%${search}%`);
|
||||
paramIndex += 2;
|
||||
}
|
||||
|
|
@ -172,7 +189,7 @@ export class DashboardService {
|
|||
}
|
||||
|
||||
// 공개/비공개 필터
|
||||
if (typeof isPublic === 'boolean') {
|
||||
if (typeof isPublic === "boolean") {
|
||||
whereConditions.push(`d.is_public = $${paramIndex}`);
|
||||
params.push(isPublic);
|
||||
paramIndex++;
|
||||
|
|
@ -185,7 +202,7 @@ export class DashboardService {
|
|||
paramIndex++;
|
||||
}
|
||||
|
||||
const whereClause = whereConditions.join(' AND ');
|
||||
const whereClause = whereConditions.join(" AND ");
|
||||
|
||||
// 대시보드 목록 조회 (users 테이블 조인 제거)
|
||||
const dashboardQuery = `
|
||||
|
|
@ -212,10 +229,11 @@ export class DashboardService {
|
|||
LIMIT $${paramIndex} OFFSET $${paramIndex + 1}
|
||||
`;
|
||||
|
||||
const dashboardResult = await PostgreSQLService.query(
|
||||
dashboardQuery,
|
||||
[...params, limit, offset]
|
||||
);
|
||||
const dashboardResult = await PostgreSQLService.query(dashboardQuery, [
|
||||
...params,
|
||||
limit,
|
||||
offset,
|
||||
]);
|
||||
|
||||
// 전체 개수 조회
|
||||
const countQuery = `
|
||||
|
|
@ -225,7 +243,7 @@ export class DashboardService {
|
|||
`;
|
||||
|
||||
const countResult = await PostgreSQLService.query(countQuery, params);
|
||||
const total = parseInt(countResult.rows[0]?.total || '0');
|
||||
const total = parseInt(countResult.rows[0]?.total || "0");
|
||||
|
||||
return {
|
||||
dashboards: dashboardResult.rows.map((row: any) => ({
|
||||
|
|
@ -237,20 +255,20 @@ export class DashboardService {
|
|||
createdBy: row.created_by,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
tags: JSON.parse(row.tags || '[]'),
|
||||
tags: JSON.parse(row.tags || "[]"),
|
||||
category: row.category,
|
||||
viewCount: parseInt(row.view_count || '0'),
|
||||
elementsCount: parseInt(row.elements_count || '0')
|
||||
viewCount: parseInt(row.view_count || "0"),
|
||||
elementsCount: parseInt(row.elements_count || "0"),
|
||||
})),
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit)
|
||||
}
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Dashboard list error:', error);
|
||||
console.error("Dashboard list error:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -258,7 +276,10 @@ export class DashboardService {
|
|||
/**
|
||||
* 대시보드 상세 조회
|
||||
*/
|
||||
static async getDashboardById(dashboardId: string, userId?: string): Promise<Dashboard | null> {
|
||||
static async getDashboardById(
|
||||
dashboardId: string,
|
||||
userId?: string
|
||||
): Promise<Dashboard | null> {
|
||||
try {
|
||||
// 1. 대시보드 기본 정보 조회 (권한 체크 포함)
|
||||
let dashboardQuery: string;
|
||||
|
|
@ -282,7 +303,10 @@ export class DashboardService {
|
|||
dashboardParams = [dashboardId];
|
||||
}
|
||||
|
||||
const dashboardResult = await PostgreSQLService.query(dashboardQuery, dashboardParams);
|
||||
const dashboardResult = await PostgreSQLService.query(
|
||||
dashboardQuery,
|
||||
dashboardParams
|
||||
);
|
||||
|
||||
if (dashboardResult.rows.length === 0) {
|
||||
return null;
|
||||
|
|
@ -297,34 +321,42 @@ export class DashboardService {
|
|||
ORDER BY display_order ASC
|
||||
`;
|
||||
|
||||
const elementsResult = await PostgreSQLService.query(elementsQuery, [dashboardId]);
|
||||
const elementsResult = await PostgreSQLService.query(elementsQuery, [
|
||||
dashboardId,
|
||||
]);
|
||||
|
||||
// 3. 요소 데이터 변환
|
||||
console.log('📊 대시보드 요소 개수:', elementsResult.rows.length);
|
||||
|
||||
const elements: DashboardElement[] = elementsResult.rows.map((row: any, index: number) => {
|
||||
const element = {
|
||||
const elements: DashboardElement[] = elementsResult.rows.map(
|
||||
(row: any) => ({
|
||||
id: row.id,
|
||||
type: row.element_type,
|
||||
subtype: row.element_subtype,
|
||||
position: {
|
||||
x: row.position_x,
|
||||
y: row.position_y
|
||||
y: row.position_y,
|
||||
},
|
||||
size: {
|
||||
width: row.width,
|
||||
height: row.height
|
||||
height: row.height,
|
||||
},
|
||||
title: row.title,
|
||||
customTitle: row.custom_title || undefined,
|
||||
showHeader: row.show_header !== false, // 기본값 true
|
||||
content: row.content,
|
||||
dataSource: JSON.parse(row.data_source_config || '{}'),
|
||||
chartConfig: JSON.parse(row.chart_config || '{}')
|
||||
};
|
||||
|
||||
console.log(`📊 위젯 #${index + 1}: type="${element.type}", subtype="${element.subtype}", title="${element.title}"`);
|
||||
|
||||
return element;
|
||||
});
|
||||
dataSource: JSON.parse(row.data_source_config || "{}"),
|
||||
chartConfig: JSON.parse(row.chart_config || "{}"),
|
||||
listConfig: row.list_config
|
||||
? typeof row.list_config === "string"
|
||||
? JSON.parse(row.list_config)
|
||||
: row.list_config
|
||||
: undefined,
|
||||
yardConfig: row.yard_config
|
||||
? typeof row.yard_config === "string"
|
||||
? JSON.parse(row.yard_config)
|
||||
: row.yard_config
|
||||
: undefined,
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
id: dashboard.id,
|
||||
|
|
@ -335,13 +367,14 @@ export class DashboardService {
|
|||
createdBy: dashboard.created_by,
|
||||
createdAt: dashboard.created_at,
|
||||
updatedAt: dashboard.updated_at,
|
||||
tags: JSON.parse(dashboard.tags || '[]'),
|
||||
tags: JSON.parse(dashboard.tags || "[]"),
|
||||
category: dashboard.category,
|
||||
viewCount: parseInt(dashboard.view_count || '0'),
|
||||
elements
|
||||
viewCount: parseInt(dashboard.view_count || "0"),
|
||||
settings: dashboard.settings || undefined,
|
||||
elements,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Dashboard get error:', error);
|
||||
console.error("Dashboard get error:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -357,13 +390,16 @@ export class DashboardService {
|
|||
try {
|
||||
const result = await PostgreSQLService.transaction(async (client) => {
|
||||
// 권한 체크
|
||||
const authCheckResult = await client.query(`
|
||||
const authCheckResult = await client.query(
|
||||
`
|
||||
SELECT id FROM dashboards
|
||||
WHERE id = $1 AND created_by = $2 AND deleted_at IS NULL
|
||||
`, [dashboardId, userId]);
|
||||
`,
|
||||
[dashboardId, userId]
|
||||
);
|
||||
|
||||
if (authCheckResult.rows.length === 0) {
|
||||
throw new Error('대시보드를 찾을 수 없거나 수정 권한이 없습니다.');
|
||||
throw new Error("대시보드를 찾을 수 없거나 수정 권한이 없습니다.");
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
|
|
@ -398,6 +434,11 @@ export class DashboardService {
|
|||
updateParams.push(data.category);
|
||||
paramIndex++;
|
||||
}
|
||||
if (data.settings !== undefined) {
|
||||
updateFields.push(`settings = $${paramIndex}`);
|
||||
updateParams.push(JSON.stringify(data.settings));
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
updateFields.push(`updated_at = $${paramIndex}`);
|
||||
updateParams.push(now);
|
||||
|
|
@ -405,10 +446,11 @@ export class DashboardService {
|
|||
|
||||
updateParams.push(dashboardId);
|
||||
|
||||
if (updateFields.length > 1) { // updated_at 외에 다른 필드가 있는 경우
|
||||
if (updateFields.length > 1) {
|
||||
// updated_at 외에 다른 필드가 있는 경우
|
||||
const updateQuery = `
|
||||
UPDATE dashboards
|
||||
SET ${updateFields.join(', ')}
|
||||
SET ${updateFields.join(", ")}
|
||||
WHERE id = $${paramIndex}
|
||||
`;
|
||||
|
||||
|
|
@ -418,39 +460,50 @@ export class DashboardService {
|
|||
// 2. 요소 업데이트 (있는 경우)
|
||||
if (data.elements) {
|
||||
// 기존 요소들 삭제
|
||||
await client.query(`
|
||||
await client.query(
|
||||
`
|
||||
DELETE FROM dashboard_elements WHERE dashboard_id = $1
|
||||
`, [dashboardId]);
|
||||
`,
|
||||
[dashboardId]
|
||||
);
|
||||
|
||||
// 새 요소들 추가
|
||||
for (let i = 0; i < data.elements.length; i++) {
|
||||
const element = data.elements[i];
|
||||
const elementId = uuidv4();
|
||||
|
||||
await client.query(`
|
||||
await client.query(
|
||||
`
|
||||
INSERT INTO dashboard_elements (
|
||||
id, dashboard_id, element_type, element_subtype,
|
||||
position_x, position_y, width, height,
|
||||
title, content, data_source_config, chart_config,
|
||||
title, custom_title, show_header, content, data_source_config, chart_config,
|
||||
list_config, yard_config,
|
||||
display_order, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
|
||||
`, [
|
||||
elementId,
|
||||
dashboardId,
|
||||
element.type,
|
||||
element.subtype,
|
||||
element.position.x,
|
||||
element.position.y,
|
||||
element.size.width,
|
||||
element.size.height,
|
||||
element.title,
|
||||
element.content || null,
|
||||
JSON.stringify(element.dataSource || {}),
|
||||
JSON.stringify(element.chartConfig || {}),
|
||||
i,
|
||||
now,
|
||||
now
|
||||
]);
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
|
||||
`,
|
||||
[
|
||||
elementId,
|
||||
dashboardId,
|
||||
element.type,
|
||||
element.subtype,
|
||||
element.position.x,
|
||||
element.position.y,
|
||||
element.size.width,
|
||||
element.size.height,
|
||||
element.title,
|
||||
element.customTitle || null,
|
||||
element.showHeader !== false, // 기본값 true
|
||||
element.content || null,
|
||||
JSON.stringify(element.dataSource || {}),
|
||||
JSON.stringify(element.chartConfig || {}),
|
||||
JSON.stringify(element.listConfig || null),
|
||||
JSON.stringify(element.yardConfig || null),
|
||||
i,
|
||||
now,
|
||||
now,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -459,9 +512,8 @@ export class DashboardService {
|
|||
|
||||
// 업데이트된 대시보드 반환
|
||||
return await this.getDashboardById(dashboardId, userId);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Dashboard update error:', error);
|
||||
console.error("Dashboard update error:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -469,19 +521,25 @@ export class DashboardService {
|
|||
/**
|
||||
* 대시보드 삭제 (소프트 삭제)
|
||||
*/
|
||||
static async deleteDashboard(dashboardId: string, userId: string): Promise<boolean> {
|
||||
static async deleteDashboard(
|
||||
dashboardId: string,
|
||||
userId: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const now = new Date();
|
||||
|
||||
const result = await PostgreSQLService.query(`
|
||||
const result = await PostgreSQLService.query(
|
||||
`
|
||||
UPDATE dashboards
|
||||
SET deleted_at = $1, updated_at = $2
|
||||
WHERE id = $3 AND created_by = $4 AND deleted_at IS NULL
|
||||
`, [now, now, dashboardId, userId]);
|
||||
`,
|
||||
[now, now, dashboardId, userId]
|
||||
);
|
||||
|
||||
return (result.rowCount || 0) > 0;
|
||||
} catch (error) {
|
||||
console.error('Dashboard delete error:', error);
|
||||
console.error("Dashboard delete error:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -491,13 +549,16 @@ export class DashboardService {
|
|||
*/
|
||||
static async incrementViewCount(dashboardId: string): Promise<void> {
|
||||
try {
|
||||
await PostgreSQLService.query(`
|
||||
await PostgreSQLService.query(
|
||||
`
|
||||
UPDATE dashboards
|
||||
SET view_count = view_count + 1
|
||||
WHERE id = $1 AND deleted_at IS NULL
|
||||
`, [dashboardId]);
|
||||
`,
|
||||
[dashboardId]
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('View count increment error:', error);
|
||||
console.error("View count increment error:", error);
|
||||
// 조회수 증가 실패는 치명적이지 않으므로 에러를 던지지 않음
|
||||
}
|
||||
}
|
||||
|
|
@ -508,10 +569,11 @@ export class DashboardService {
|
|||
static async checkUserPermission(
|
||||
dashboardId: string,
|
||||
userId: string,
|
||||
requiredPermission: 'view' | 'edit' | 'admin' = 'view'
|
||||
requiredPermission: "view" | "edit" | "admin" = "view"
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const result = await PostgreSQLService.query(`
|
||||
const result = await PostgreSQLService.query(
|
||||
`
|
||||
SELECT
|
||||
CASE
|
||||
WHEN d.created_by = $2 THEN 'admin'
|
||||
|
|
@ -520,7 +582,9 @@ export class DashboardService {
|
|||
END as permission
|
||||
FROM dashboards d
|
||||
WHERE d.id = $1 AND d.deleted_at IS NULL
|
||||
`, [dashboardId, userId]);
|
||||
`,
|
||||
[dashboardId, userId]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return false;
|
||||
|
|
@ -529,13 +593,14 @@ export class DashboardService {
|
|||
const userPermission = result.rows[0].permission;
|
||||
|
||||
// 권한 레벨 체크
|
||||
const permissionLevels = { 'view': 1, 'edit': 2, 'admin': 3 };
|
||||
const userLevel = permissionLevels[userPermission as keyof typeof permissionLevels] || 0;
|
||||
const permissionLevels = { view: 1, edit: 2, admin: 3 };
|
||||
const userLevel =
|
||||
permissionLevels[userPermission as keyof typeof permissionLevels] || 0;
|
||||
const requiredLevel = permissionLevels[requiredPermission];
|
||||
|
||||
return userLevel >= requiredLevel;
|
||||
} catch (error) {
|
||||
console.error('Permission check error:', error);
|
||||
console.error("Permission check error:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,111 @@
|
|||
import { getPool } from "../database/db";
|
||||
|
||||
export class MaterialService {
|
||||
// 임시 자재 마스터 목록 조회
|
||||
async getTempMaterials(params: {
|
||||
search?: string;
|
||||
category?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}) {
|
||||
const { search, category, page = 1, limit = 20 } = params;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
let whereConditions: string[] = ["is_active = true"];
|
||||
const queryParams: any[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (search) {
|
||||
whereConditions.push(
|
||||
`(material_code ILIKE $${paramIndex} OR material_name ILIKE $${paramIndex})`
|
||||
);
|
||||
queryParams.push(`%${search}%`);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
if (category) {
|
||||
whereConditions.push(`category = $${paramIndex}`);
|
||||
queryParams.push(category);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
const whereClause =
|
||||
whereConditions.length > 0
|
||||
? `WHERE ${whereConditions.join(" AND ")}`
|
||||
: "";
|
||||
|
||||
const pool = getPool();
|
||||
|
||||
// 전체 개수 조회
|
||||
const countQuery = `SELECT COUNT(*) as total FROM temp_material_master ${whereClause}`;
|
||||
const countResult = await pool.query(countQuery, queryParams);
|
||||
const total = parseInt(countResult.rows[0].total);
|
||||
|
||||
// 데이터 조회
|
||||
const dataQuery = `
|
||||
SELECT
|
||||
id,
|
||||
material_code,
|
||||
material_name,
|
||||
category,
|
||||
unit,
|
||||
default_color,
|
||||
description,
|
||||
created_at
|
||||
FROM temp_material_master
|
||||
${whereClause}
|
||||
ORDER BY material_code ASC
|
||||
LIMIT $${paramIndex} OFFSET $${paramIndex + 1}
|
||||
`;
|
||||
|
||||
queryParams.push(limit, offset);
|
||||
const dataResult = await pool.query(dataQuery, queryParams);
|
||||
|
||||
return {
|
||||
data: dataResult.rows,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 특정 자재 상세 조회
|
||||
async getTempMaterialByCode(materialCode: string) {
|
||||
const query = `
|
||||
SELECT
|
||||
id,
|
||||
material_code,
|
||||
material_name,
|
||||
category,
|
||||
unit,
|
||||
default_color,
|
||||
description,
|
||||
created_at
|
||||
FROM temp_material_master
|
||||
WHERE material_code = $1 AND is_active = true
|
||||
`;
|
||||
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query, [materialCode]);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
// 카테고리 목록 조회
|
||||
async getCategories() {
|
||||
const query = `
|
||||
SELECT DISTINCT category
|
||||
FROM temp_material_master
|
||||
WHERE is_active = true AND category IS NOT NULL
|
||||
ORDER BY category ASC
|
||||
`;
|
||||
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query);
|
||||
return result.rows.map((row) => row.category);
|
||||
}
|
||||
}
|
||||
|
||||
export default new MaterialService();
|
||||
|
|
@ -0,0 +1,337 @@
|
|||
import { getPool } from "../database/db";
|
||||
|
||||
export class YardLayoutService {
|
||||
// 모든 야드 레이아웃 목록 조회
|
||||
async getAllLayouts() {
|
||||
const query = `
|
||||
SELECT
|
||||
yl.id,
|
||||
yl.name,
|
||||
yl.description,
|
||||
yl.created_by,
|
||||
yl.created_at,
|
||||
yl.updated_at,
|
||||
COUNT(ymp.id) as placement_count
|
||||
FROM yard_layout yl
|
||||
LEFT JOIN yard_material_placement ymp ON yl.id = ymp.yard_layout_id
|
||||
GROUP BY yl.id
|
||||
ORDER BY yl.updated_at DESC
|
||||
`;
|
||||
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
// 특정 야드 레이아웃 상세 조회
|
||||
async getLayoutById(id: number) {
|
||||
const query = `
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
created_by,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM yard_layout
|
||||
WHERE id = $1
|
||||
`;
|
||||
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query, [id]);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
// 새 야드 레이아웃 생성
|
||||
async createLayout(data: {
|
||||
name: string;
|
||||
description?: string;
|
||||
created_by?: string;
|
||||
}) {
|
||||
const query = `
|
||||
INSERT INTO yard_layout (name, description, created_by)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *
|
||||
`;
|
||||
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query, [
|
||||
data.name,
|
||||
data.description || null,
|
||||
data.created_by || null,
|
||||
]);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
// 야드 레이아웃 수정 (이름, 설명만)
|
||||
async updateLayout(
|
||||
id: number,
|
||||
data: { name?: string; description?: string }
|
||||
) {
|
||||
const query = `
|
||||
UPDATE yard_layout
|
||||
SET
|
||||
name = COALESCE($1, name),
|
||||
description = COALESCE($2, description),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $3
|
||||
RETURNING *
|
||||
`;
|
||||
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query, [
|
||||
data.name || null,
|
||||
data.description || null,
|
||||
id,
|
||||
]);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
// 야드 레이아웃 삭제
|
||||
async deleteLayout(id: number) {
|
||||
const query = `DELETE FROM yard_layout WHERE id = $1 RETURNING *`;
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query, [id]);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
// 특정 야드의 모든 배치 자재 조회
|
||||
async getPlacementsByLayoutId(layoutId: number) {
|
||||
const query = `
|
||||
SELECT
|
||||
id,
|
||||
yard_layout_id,
|
||||
external_material_id,
|
||||
material_code,
|
||||
material_name,
|
||||
quantity,
|
||||
unit,
|
||||
position_x,
|
||||
position_y,
|
||||
position_z,
|
||||
size_x,
|
||||
size_y,
|
||||
size_z,
|
||||
color,
|
||||
memo,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM yard_material_placement
|
||||
WHERE yard_layout_id = $1
|
||||
ORDER BY created_at ASC
|
||||
`;
|
||||
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query, [layoutId]);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
// 야드에 자재 배치 추가
|
||||
async addMaterialPlacement(layoutId: number, data: any) {
|
||||
const query = `
|
||||
INSERT INTO yard_material_placement (
|
||||
yard_layout_id,
|
||||
external_material_id,
|
||||
material_code,
|
||||
material_name,
|
||||
quantity,
|
||||
unit,
|
||||
position_x,
|
||||
position_y,
|
||||
position_z,
|
||||
size_x,
|
||||
size_y,
|
||||
size_z,
|
||||
color,
|
||||
memo
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
||||
RETURNING *
|
||||
`;
|
||||
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query, [
|
||||
layoutId,
|
||||
data.external_material_id,
|
||||
data.material_code,
|
||||
data.material_name,
|
||||
data.quantity,
|
||||
data.unit,
|
||||
data.position_x || 0,
|
||||
data.position_y || 0,
|
||||
data.position_z || 0,
|
||||
data.size_x || 5,
|
||||
data.size_y || 5,
|
||||
data.size_z || 5,
|
||||
data.color || "#3b82f6",
|
||||
data.memo || null,
|
||||
]);
|
||||
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
// 배치 정보 수정 (위치, 크기, 색상, 메모만)
|
||||
async updatePlacement(placementId: number, data: any) {
|
||||
const query = `
|
||||
UPDATE yard_material_placement
|
||||
SET
|
||||
position_x = COALESCE($1, position_x),
|
||||
position_y = COALESCE($2, position_y),
|
||||
position_z = COALESCE($3, position_z),
|
||||
size_x = COALESCE($4, size_x),
|
||||
size_y = COALESCE($5, size_y),
|
||||
size_z = COALESCE($6, size_z),
|
||||
color = COALESCE($7, color),
|
||||
memo = COALESCE($8, memo),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $9
|
||||
RETURNING *
|
||||
`;
|
||||
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query, [
|
||||
data.position_x,
|
||||
data.position_y,
|
||||
data.position_z,
|
||||
data.size_x,
|
||||
data.size_y,
|
||||
data.size_z,
|
||||
data.color,
|
||||
data.memo,
|
||||
placementId,
|
||||
]);
|
||||
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
// 배치 해제 (자재는 삭제되지 않음)
|
||||
async removePlacement(placementId: number) {
|
||||
const query = `DELETE FROM yard_material_placement WHERE id = $1 RETURNING *`;
|
||||
const pool = getPool();
|
||||
const result = await pool.query(query, [placementId]);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
// 여러 배치 일괄 업데이트
|
||||
async batchUpdatePlacements(layoutId: number, placements: any[]) {
|
||||
const pool = getPool();
|
||||
const client = await pool.connect();
|
||||
|
||||
try {
|
||||
await client.query("BEGIN");
|
||||
|
||||
const results = [];
|
||||
for (const placement of placements) {
|
||||
const query = `
|
||||
UPDATE yard_material_placement
|
||||
SET
|
||||
position_x = $1,
|
||||
position_y = $2,
|
||||
position_z = $3,
|
||||
size_x = $4,
|
||||
size_y = $5,
|
||||
size_z = $6,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $7 AND yard_layout_id = $8
|
||||
RETURNING *
|
||||
`;
|
||||
|
||||
const result = await client.query(query, [
|
||||
placement.position_x,
|
||||
placement.position_y,
|
||||
placement.position_z,
|
||||
placement.size_x,
|
||||
placement.size_y,
|
||||
placement.size_z,
|
||||
placement.id,
|
||||
layoutId,
|
||||
]);
|
||||
|
||||
if (result.rows[0]) {
|
||||
results.push(result.rows[0]);
|
||||
}
|
||||
}
|
||||
|
||||
await client.query("COMMIT");
|
||||
return results;
|
||||
} catch (error) {
|
||||
await client.query("ROLLBACK");
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
// 야드 레이아웃 복제
|
||||
async duplicateLayout(id: number, newName: string) {
|
||||
const pool = getPool();
|
||||
const client = await pool.connect();
|
||||
|
||||
try {
|
||||
await client.query("BEGIN");
|
||||
|
||||
// 원본 레이아웃 조회
|
||||
const layoutQuery = `SELECT * FROM yard_layout WHERE id = $1`;
|
||||
const layoutResult = await client.query(layoutQuery, [id]);
|
||||
const originalLayout = layoutResult.rows[0];
|
||||
|
||||
if (!originalLayout) {
|
||||
throw new Error("Layout not found");
|
||||
}
|
||||
|
||||
// 새 레이아웃 생성
|
||||
const newLayoutQuery = `
|
||||
INSERT INTO yard_layout (name, description, created_by)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *
|
||||
`;
|
||||
const newLayoutResult = await client.query(newLayoutQuery, [
|
||||
newName,
|
||||
originalLayout.description,
|
||||
originalLayout.created_by,
|
||||
]);
|
||||
const newLayout = newLayoutResult.rows[0];
|
||||
|
||||
// 배치 자재 복사
|
||||
const placementsQuery = `SELECT * FROM yard_material_placement WHERE yard_layout_id = $1`;
|
||||
const placementsResult = await client.query(placementsQuery, [id]);
|
||||
|
||||
for (const placement of placementsResult.rows) {
|
||||
await client.query(
|
||||
`
|
||||
INSERT INTO yard_material_placement (
|
||||
yard_layout_id, external_material_id, material_code, material_name,
|
||||
quantity, unit, position_x, position_y, position_z,
|
||||
size_x, size_y, size_z, color, memo
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
||||
`,
|
||||
[
|
||||
newLayout.id,
|
||||
placement.external_material_id,
|
||||
placement.material_code,
|
||||
placement.material_name,
|
||||
placement.quantity,
|
||||
placement.unit,
|
||||
placement.position_x,
|
||||
placement.position_y,
|
||||
placement.position_z,
|
||||
placement.size_x,
|
||||
placement.size_y,
|
||||
placement.size_z,
|
||||
placement.color,
|
||||
placement.memo,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
await client.query("COMMIT");
|
||||
return newLayout;
|
||||
} catch (error) {
|
||||
await client.query("ROLLBACK");
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new YardLayoutService();
|
||||
|
|
@ -25,8 +25,8 @@ export class RiskAlertService {
|
|||
const apiKey = process.env.KMA_API_KEY;
|
||||
|
||||
if (!apiKey) {
|
||||
console.log('⚠️ 기상청 API 키가 없습니다. 테스트 데이터를 반환합니다.');
|
||||
return this.generateDummyWeatherAlerts();
|
||||
console.log('⚠️ 기상청 API 키가 없습니다. 빈 데이터를 반환합니다.');
|
||||
return [];
|
||||
}
|
||||
|
||||
const alerts: Alert[] = [];
|
||||
|
|
@ -109,7 +109,7 @@ export class RiskAlertService {
|
|||
console.log(`✅ 총 ${alerts.length}건의 기상특보 감지`);
|
||||
} catch (warningError: any) {
|
||||
console.error('❌ 기상청 특보 API 오류:', warningError.message);
|
||||
return this.generateDummyWeatherAlerts();
|
||||
return [];
|
||||
}
|
||||
|
||||
// 특보가 없으면 빈 배열 반환 (0건)
|
||||
|
|
@ -120,8 +120,8 @@ export class RiskAlertService {
|
|||
return alerts;
|
||||
} catch (error: any) {
|
||||
console.error('❌ 기상청 특보 API 오류:', error.message);
|
||||
// API 오류 시 더미 데이터 반환
|
||||
return this.generateDummyWeatherAlerts();
|
||||
// API 오류 시 빈 배열 반환
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -237,9 +237,9 @@ export class RiskAlertService {
|
|||
console.error('❌ 한국도로공사 API 오류:', error.message);
|
||||
}
|
||||
|
||||
// 모든 API 실패 시 더미 데이터
|
||||
console.log('ℹ️ 모든 교통사고 API 실패. 더미 데이터를 반환합니다.');
|
||||
return this.generateDummyAccidentAlerts();
|
||||
// 모든 API 실패 시 빈 배열
|
||||
console.log('ℹ️ 모든 교통사고 API 실패. 빈 배열을 반환합니다.');
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -356,9 +356,9 @@ export class RiskAlertService {
|
|||
console.error('❌ 한국도로공사 API 오류:', error.message);
|
||||
}
|
||||
|
||||
// 모든 API 실패 시 더미 데이터
|
||||
console.log('ℹ️ 모든 도로공사 API 실패. 더미 데이터를 반환합니다.');
|
||||
return this.generateDummyRoadworkAlerts();
|
||||
// 모든 API 실패 시 빈 배열
|
||||
console.log('ℹ️ 모든 도로공사 API 실패. 빈 배열을 반환합니다.');
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -467,82 +467,5 @@ export class RiskAlertService {
|
|||
return 'low';
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 날씨 특보 더미 데이터
|
||||
*/
|
||||
private generateDummyWeatherAlerts(): Alert[] {
|
||||
return [
|
||||
{
|
||||
id: `weather-${Date.now()}-1`,
|
||||
type: 'weather',
|
||||
severity: 'high',
|
||||
title: '대설특보',
|
||||
location: '강원 영동지역',
|
||||
description: '시간당 2cm 이상 폭설. 차량 운행 주의',
|
||||
timestamp: new Date(Date.now() - 30 * 60000).toISOString(),
|
||||
},
|
||||
{
|
||||
id: `weather-${Date.now()}-2`,
|
||||
type: 'weather',
|
||||
severity: 'medium',
|
||||
title: '강풍특보',
|
||||
location: '남해안 전 지역',
|
||||
description: '순간 풍속 20m/s 이상. 고속도로 주행 주의',
|
||||
timestamp: new Date(Date.now() - 90 * 60000).toISOString(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 교통사고 더미 데이터
|
||||
*/
|
||||
private generateDummyAccidentAlerts(): Alert[] {
|
||||
return [
|
||||
{
|
||||
id: `accident-${Date.now()}-1`,
|
||||
type: 'accident',
|
||||
severity: 'high',
|
||||
title: '교통사고 발생',
|
||||
location: '경부고속도로 서울방향 189km',
|
||||
description: '3중 추돌사고로 2차로 통제 중. 우회 권장',
|
||||
timestamp: new Date(Date.now() - 10 * 60000).toISOString(),
|
||||
},
|
||||
{
|
||||
id: `accident-${Date.now()}-2`,
|
||||
type: 'accident',
|
||||
severity: 'medium',
|
||||
title: '사고 다발 지역',
|
||||
location: '영동고속도로 강릉방향 160km',
|
||||
description: '안개로 인한 가시거리 50m 이하. 서행 운전',
|
||||
timestamp: new Date(Date.now() - 60 * 60000).toISOString(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 도로공사 더미 데이터
|
||||
*/
|
||||
private generateDummyRoadworkAlerts(): Alert[] {
|
||||
return [
|
||||
{
|
||||
id: `construction-${Date.now()}-1`,
|
||||
type: 'construction',
|
||||
severity: 'medium',
|
||||
title: '도로 공사',
|
||||
location: '서울외곽순환 목동IC~화곡IC',
|
||||
description: '야간 공사로 1차로 통제 (22:00~06:00)',
|
||||
timestamp: new Date(Date.now() - 45 * 60000).toISOString(),
|
||||
},
|
||||
{
|
||||
id: `construction-${Date.now()}-2`,
|
||||
type: 'construction',
|
||||
severity: 'low',
|
||||
title: '도로 통제',
|
||||
location: '중부내륙고속도로 김천JC~현풍IC',
|
||||
description: '도로 유지보수 작업. 차량 속도 제한 60km/h',
|
||||
timestamp: new Date(Date.now() - 120 * 60000).toISOString(),
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@
|
|||
|
||||
export interface DashboardElement {
|
||||
id: string;
|
||||
type: 'chart' | 'widget';
|
||||
subtype: 'bar' | 'pie' | 'line' | 'exchange' | 'weather';
|
||||
type: "chart" | "widget";
|
||||
subtype: "bar" | "pie" | "line" | "exchange" | "weather";
|
||||
position: {
|
||||
x: number;
|
||||
y: number;
|
||||
|
|
@ -15,9 +15,11 @@ export interface DashboardElement {
|
|||
height: number;
|
||||
};
|
||||
title: string;
|
||||
customTitle?: string; // 사용자 정의 제목 (옵션)
|
||||
showHeader?: boolean; // 헤더 표시 여부 (기본값: true)
|
||||
content?: string;
|
||||
dataSource?: {
|
||||
type: 'api' | 'database' | 'static';
|
||||
type: "api" | "database" | "static";
|
||||
endpoint?: string;
|
||||
query?: string;
|
||||
refreshInterval?: number;
|
||||
|
|
@ -28,11 +30,21 @@ export interface DashboardElement {
|
|||
xAxis?: string;
|
||||
yAxis?: string;
|
||||
groupBy?: string;
|
||||
aggregation?: 'sum' | 'avg' | 'count' | 'max' | 'min';
|
||||
aggregation?: "sum" | "avg" | "count" | "max" | "min";
|
||||
colors?: string[];
|
||||
title?: string;
|
||||
showLegend?: boolean;
|
||||
};
|
||||
listConfig?: {
|
||||
columns?: any[];
|
||||
pagination?: any;
|
||||
viewMode?: string;
|
||||
cardColumns?: number;
|
||||
};
|
||||
yardConfig?: {
|
||||
layoutId: number;
|
||||
layoutName?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Dashboard {
|
||||
|
|
@ -48,6 +60,10 @@ export interface Dashboard {
|
|||
tags?: string[];
|
||||
category?: string;
|
||||
viewCount: number;
|
||||
settings?: {
|
||||
resolution?: string;
|
||||
backgroundColor?: string;
|
||||
};
|
||||
elements: DashboardElement[];
|
||||
}
|
||||
|
||||
|
|
@ -58,6 +74,10 @@ export interface CreateDashboardRequest {
|
|||
elements: DashboardElement[];
|
||||
tags?: string[];
|
||||
category?: string;
|
||||
settings?: {
|
||||
resolution?: string;
|
||||
backgroundColor?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface UpdateDashboardRequest {
|
||||
|
|
@ -67,6 +87,10 @@ export interface UpdateDashboardRequest {
|
|||
elements?: DashboardElement[];
|
||||
tags?: string[];
|
||||
category?: string;
|
||||
settings?: {
|
||||
resolution?: string;
|
||||
backgroundColor?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface DashboardListQuery {
|
||||
|
|
@ -83,7 +107,7 @@ export interface DashboardShare {
|
|||
dashboardId: string;
|
||||
sharedWithUser?: string;
|
||||
sharedWithRole?: string;
|
||||
permissionLevel: 'view' | 'edit' | 'admin';
|
||||
permissionLevel: "view" | "edit" | "admin";
|
||||
createdBy: string;
|
||||
createdAt: string;
|
||||
expiresAt?: string;
|
||||
|
|
|
|||
|
|
@ -15,7 +15,18 @@ import {
|
|||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Plus, Search, MoreVertical, Edit, Trash2, Copy, Eye } from "lucide-react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Plus, Search, MoreVertical, Edit, Trash2, Copy, CheckCircle2 } from "lucide-react";
|
||||
|
||||
/**
|
||||
* 대시보드 관리 페이지
|
||||
|
|
@ -29,6 +40,12 @@ export default function DashboardListPage() {
|
|||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// 모달 상태
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<{ id: string; title: string } | null>(null);
|
||||
const [successDialogOpen, setSuccessDialogOpen] = useState(false);
|
||||
const [successMessage, setSuccessMessage] = useState("");
|
||||
|
||||
// 대시보드 목록 로드
|
||||
const loadDashboards = async () => {
|
||||
try {
|
||||
|
|
@ -48,38 +65,51 @@ export default function DashboardListPage() {
|
|||
loadDashboards();
|
||||
}, [searchTerm]);
|
||||
|
||||
// 대시보드 삭제
|
||||
const handleDelete = async (id: string, title: string) => {
|
||||
if (!confirm(`"${title}" 대시보드를 삭제하시겠습니까?`)) {
|
||||
return;
|
||||
}
|
||||
// 대시보드 삭제 확인 모달 열기
|
||||
const handleDeleteClick = (id: string, title: string) => {
|
||||
setDeleteTarget({ id, title });
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
// 대시보드 삭제 실행
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!deleteTarget) return;
|
||||
|
||||
try {
|
||||
await dashboardApi.deleteDashboard(id);
|
||||
alert("대시보드가 삭제되었습니다.");
|
||||
await dashboardApi.deleteDashboard(deleteTarget.id);
|
||||
setDeleteDialogOpen(false);
|
||||
setDeleteTarget(null);
|
||||
setSuccessMessage("대시보드가 삭제되었습니다.");
|
||||
setSuccessDialogOpen(true);
|
||||
loadDashboards();
|
||||
} catch (err) {
|
||||
console.error("Failed to delete dashboard:", err);
|
||||
alert("대시보드 삭제에 실패했습니다.");
|
||||
setDeleteDialogOpen(false);
|
||||
setError("대시보드 삭제에 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
// 대시보드 복사
|
||||
const handleCopy = async (dashboard: Dashboard) => {
|
||||
try {
|
||||
// 전체 대시보드 정보(요소 포함)를 가져오기
|
||||
const fullDashboard = await dashboardApi.getDashboard(dashboard.id);
|
||||
|
||||
const newDashboard = await dashboardApi.createDashboard({
|
||||
title: `${dashboard.title} (복사본)`,
|
||||
description: dashboard.description,
|
||||
elements: dashboard.elements || [],
|
||||
title: `${fullDashboard.title} (복사본)`,
|
||||
description: fullDashboard.description,
|
||||
elements: fullDashboard.elements || [],
|
||||
isPublic: false,
|
||||
tags: dashboard.tags,
|
||||
category: dashboard.category,
|
||||
tags: fullDashboard.tags,
|
||||
category: fullDashboard.category,
|
||||
settings: (fullDashboard as any).settings, // 해상도와 배경색 설정도 복사
|
||||
});
|
||||
alert("대시보드가 복사되었습니다.");
|
||||
setSuccessMessage("대시보드가 복사되었습니다.");
|
||||
setSuccessDialogOpen(true);
|
||||
loadDashboards();
|
||||
} catch (err) {
|
||||
console.error("Failed to copy dashboard:", err);
|
||||
alert("대시보드 복사에 실패했습니다.");
|
||||
setError("대시보드 복사에 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -156,8 +186,6 @@ export default function DashboardListPage() {
|
|||
<TableRow>
|
||||
<TableHead>제목</TableHead>
|
||||
<TableHead>설명</TableHead>
|
||||
<TableHead>요소 수</TableHead>
|
||||
<TableHead>상태</TableHead>
|
||||
<TableHead>생성일</TableHead>
|
||||
<TableHead>수정일</TableHead>
|
||||
<TableHead className="w-[80px]">작업</TableHead>
|
||||
|
|
@ -166,29 +194,10 @@ export default function DashboardListPage() {
|
|||
<TableBody>
|
||||
{dashboards.map((dashboard) => (
|
||||
<TableRow key={dashboard.id} className="cursor-pointer hover:bg-gray-50">
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
{dashboard.title}
|
||||
{dashboard.isPublic && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
공개
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{dashboard.title}</TableCell>
|
||||
<TableCell className="max-w-md truncate text-sm text-gray-500">
|
||||
{dashboard.description || "-"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="secondary">{dashboard.elementsCount || 0}개</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{dashboard.isPublic ? (
|
||||
<Badge className="bg-green-100 text-green-800">공개</Badge>
|
||||
) : (
|
||||
<Badge variant="outline">비공개</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-gray-500">{formatDate(dashboard.createdAt)}</TableCell>
|
||||
<TableCell className="text-sm text-gray-500">{formatDate(dashboard.updatedAt)}</TableCell>
|
||||
<TableCell>
|
||||
|
|
@ -199,10 +208,6 @@ export default function DashboardListPage() {
|
|||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => router.push(`/dashboard/${dashboard.id}`)} className="gap-2">
|
||||
<Eye className="h-4 w-4" />
|
||||
보기
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => router.push(`/admin/dashboard/edit/${dashboard.id}`)}
|
||||
className="gap-2"
|
||||
|
|
@ -215,7 +220,7 @@ export default function DashboardListPage() {
|
|||
복사
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDelete(dashboard.id, dashboard.title)}
|
||||
onClick={() => handleDeleteClick(dashboard.id, dashboard.title)}
|
||||
className="gap-2 text-red-600 focus:text-red-600"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
|
|
@ -231,6 +236,41 @@ export default function DashboardListPage() {
|
|||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 삭제 확인 모달 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>대시보드 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{deleteTarget?.title}" 대시보드를 삭제하시겠습니까?
|
||||
<br />이 작업은 되돌릴 수 없습니다.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDeleteConfirm} className="bg-red-600 hover:bg-red-700">
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* 성공 모달 */}
|
||||
<Dialog open={successDialogOpen} onOpenChange={setSuccessDialogOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
|
||||
<CheckCircle2 className="h-6 w-6 text-green-600" />
|
||||
</div>
|
||||
<DialogTitle className="text-center">완료</DialogTitle>
|
||||
<DialogDescription className="text-center">{successMessage}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex justify-center pt-4">
|
||||
<Button onClick={() => setSuccessDialogOpen(false)}>확인</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,10 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
|
|||
title: string;
|
||||
description?: string;
|
||||
elements: DashboardElement[];
|
||||
settings?: {
|
||||
backgroundColor?: string;
|
||||
resolution?: string;
|
||||
};
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
} | null>(null);
|
||||
|
|
@ -101,8 +105,8 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
|
|||
|
||||
return (
|
||||
<div className="h-screen bg-gray-50">
|
||||
{/* 대시보드 헤더 */}
|
||||
<div className="border-b border-gray-200 bg-white px-6 py-4">
|
||||
{/* 대시보드 헤더 - 보기 모드에서는 숨김 */}
|
||||
{/* <div className="border-b border-gray-200 bg-white px-6 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-800">{dashboard.title}</h1>
|
||||
|
|
@ -110,7 +114,7 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
|
|||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
{/* 새로고침 버튼 */}
|
||||
{/* 새로고침 버튼 *\/}
|
||||
<button
|
||||
onClick={loadDashboard}
|
||||
className="rounded-lg border border-gray-300 px-3 py-2 text-gray-600 hover:bg-gray-50 hover:text-gray-800"
|
||||
|
|
@ -119,7 +123,7 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
|
|||
🔄
|
||||
</button>
|
||||
|
||||
{/* 전체화면 버튼 */}
|
||||
{/* 전체화면 버튼 *\/}
|
||||
<button
|
||||
onClick={() => {
|
||||
if (document.fullscreenElement) {
|
||||
|
|
@ -134,7 +138,7 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
|
|||
⛶
|
||||
</button>
|
||||
|
||||
{/* 편집 버튼 */}
|
||||
{/* 편집 버튼 *\/}
|
||||
<button
|
||||
onClick={() => {
|
||||
router.push(`/admin/dashboard?load=${resolvedParams.dashboardId}`);
|
||||
|
|
@ -146,18 +150,20 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* 메타 정보 */}
|
||||
{/* 메타 정보 *\/}
|
||||
<div className="mt-2 flex items-center gap-4 text-xs text-gray-500">
|
||||
<span>생성: {new Date(dashboard.createdAt).toLocaleString()}</span>
|
||||
<span>수정: {new Date(dashboard.updatedAt).toLocaleString()}</span>
|
||||
<span>요소: {dashboard.elements.length}개</span>
|
||||
</div>
|
||||
</div>
|
||||
</div> */}
|
||||
|
||||
{/* 대시보드 뷰어 */}
|
||||
<div className="h-[calc(100vh-120px)]">
|
||||
<DashboardViewer elements={dashboard.elements} dashboardId={dashboard.id} />
|
||||
</div>
|
||||
<DashboardViewer
|
||||
elements={dashboard.elements}
|
||||
dashboardId={dashboard.id}
|
||||
backgroundColor={dashboard.settings?.backgroundColor}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,12 +47,12 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
uiTexts,
|
||||
}) => {
|
||||
// console.log("🎯 MenuFormModal 렌더링 - Props:", {
|
||||
// isOpen,
|
||||
// menuId,
|
||||
// parentId,
|
||||
// menuType,
|
||||
// level,
|
||||
// parentCompanyCode,
|
||||
// isOpen,
|
||||
// menuId,
|
||||
// parentId,
|
||||
// menuType,
|
||||
// level,
|
||||
// parentCompanyCode,
|
||||
// });
|
||||
|
||||
// 다국어 텍스트 가져오기 함수
|
||||
|
|
@ -75,12 +75,18 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
});
|
||||
|
||||
// 화면 할당 관련 상태
|
||||
const [urlType, setUrlType] = useState<"direct" | "screen">("screen"); // URL 직접 입력 or 화면 할당 (기본값: 화면 할당)
|
||||
const [urlType, setUrlType] = useState<"direct" | "screen" | "dashboard">("screen"); // URL 직접 입력 or 화면 할당 or 대시보드 할당 (기본값: 화면 할당)
|
||||
const [selectedScreen, setSelectedScreen] = useState<ScreenDefinition | null>(null);
|
||||
const [screens, setScreens] = useState<ScreenDefinition[]>([]);
|
||||
const [screenSearchText, setScreenSearchText] = useState("");
|
||||
const [isScreenDropdownOpen, setIsScreenDropdownOpen] = useState(false);
|
||||
|
||||
// 대시보드 할당 관련 상태
|
||||
const [selectedDashboard, setSelectedDashboard] = useState<any | null>(null);
|
||||
const [dashboards, setDashboards] = useState<any[]>([]);
|
||||
const [dashboardSearchText, setDashboardSearchText] = useState("");
|
||||
const [isDashboardDropdownOpen, setIsDashboardDropdownOpen] = useState(false);
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [isEdit, setIsEdit] = useState(false);
|
||||
const [companies, setCompanies] = useState<Company[]>([]);
|
||||
|
|
@ -93,21 +99,6 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
try {
|
||||
const response = await screenApi.getScreens({ size: 1000 }); // 모든 화면 가져오기
|
||||
|
||||
// console.log("🔍 화면 목록 로드 디버깅:", {
|
||||
// totalScreens: response.data.length,
|
||||
// firstScreen: response.data[0],
|
||||
// firstScreenFields: response.data[0] ? Object.keys(response.data[0]) : [],
|
||||
// firstScreenValues: response.data[0] ? Object.values(response.data[0]) : [],
|
||||
// allScreenIds: response.data
|
||||
// .map((s) => ({
|
||||
// screenId: s.screenId,
|
||||
// legacyId: s.id,
|
||||
// name: s.screenName,
|
||||
// code: s.screenCode,
|
||||
// }))
|
||||
// .slice(0, 5), // 처음 5개만 출력
|
||||
// });
|
||||
|
||||
setScreens(response.data);
|
||||
console.log("✅ 화면 목록 로드 완료:", response.data.length);
|
||||
} catch (error) {
|
||||
|
|
@ -116,15 +107,28 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
}
|
||||
};
|
||||
|
||||
// 대시보드 목록 로드
|
||||
const loadDashboards = async () => {
|
||||
try {
|
||||
const { dashboardApi } = await import("@/lib/api/dashboard");
|
||||
const response = await dashboardApi.getMyDashboards();
|
||||
setDashboards(response.dashboards || []);
|
||||
console.log("✅ 대시보드 목록 로드 완료:", response.dashboards?.length || 0);
|
||||
} catch (error) {
|
||||
console.error("❌ 대시보드 목록 로드 실패:", error);
|
||||
toast.error("대시보드 목록을 불러오는데 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
// 화면 선택 시 URL 자동 설정
|
||||
const handleScreenSelect = (screen: ScreenDefinition) => {
|
||||
// console.log("🖥️ 화면 선택 디버깅:", {
|
||||
// screen,
|
||||
// screenId: screen.screenId,
|
||||
// screenIdType: typeof screen.screenId,
|
||||
// legacyId: screen.id,
|
||||
// allFields: Object.keys(screen),
|
||||
// screenValues: Object.values(screen),
|
||||
// screen,
|
||||
// screenId: screen.screenId,
|
||||
// screenIdType: typeof screen.screenId,
|
||||
// legacyId: screen.id,
|
||||
// allFields: Object.keys(screen),
|
||||
// screenValues: Object.values(screen),
|
||||
// });
|
||||
|
||||
// ScreenDefinition에서는 screenId 필드를 사용
|
||||
|
|
@ -155,24 +159,42 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
}));
|
||||
|
||||
// console.log("🖥️ 화면 선택 완료:", {
|
||||
// screenId: screen.screenId,
|
||||
// legacyId: screen.id,
|
||||
// actualScreenId,
|
||||
// screenName: screen.screenName,
|
||||
// menuType: menuType,
|
||||
// formDataMenuType: formData.menuType,
|
||||
// isAdminMenu,
|
||||
// generatedUrl: screenUrl,
|
||||
// screenId: screen.screenId,
|
||||
// legacyId: screen.id,
|
||||
// actualScreenId,
|
||||
// screenName: screen.screenName,
|
||||
// menuType: menuType,
|
||||
// formDataMenuType: formData.menuType,
|
||||
// isAdminMenu,
|
||||
// generatedUrl: screenUrl,
|
||||
// });
|
||||
};
|
||||
|
||||
// 대시보드 선택 시 URL 자동 설정
|
||||
const handleDashboardSelect = (dashboard: any) => {
|
||||
setSelectedDashboard(dashboard);
|
||||
setIsDashboardDropdownOpen(false);
|
||||
|
||||
// 대시보드 URL 생성
|
||||
let dashboardUrl = `/dashboard/${dashboard.id}`;
|
||||
|
||||
// 현재 메뉴 타입이 관리자인지 확인 (0 또는 "admin")
|
||||
const isAdminMenu = menuType === "0" || menuType === "admin" || formData.menuType === "0";
|
||||
if (isAdminMenu) {
|
||||
dashboardUrl += "?mode=admin";
|
||||
}
|
||||
|
||||
setFormData((prev) => ({ ...prev, menuUrl: dashboardUrl }));
|
||||
toast.success(`대시보드가 선택되었습니다: ${dashboard.title}`);
|
||||
};
|
||||
|
||||
// URL 타입 변경 시 처리
|
||||
const handleUrlTypeChange = (type: "direct" | "screen") => {
|
||||
const handleUrlTypeChange = (type: "direct" | "screen" | "dashboard") => {
|
||||
// console.log("🔄 URL 타입 변경:", {
|
||||
// from: urlType,
|
||||
// to: type,
|
||||
// currentSelectedScreen: selectedScreen?.screenName,
|
||||
// currentUrl: formData.menuUrl,
|
||||
// from: urlType,
|
||||
// to: type,
|
||||
// currentSelectedScreen: selectedScreen?.screenName,
|
||||
// currentUrl: formData.menuUrl,
|
||||
// });
|
||||
|
||||
setUrlType(type);
|
||||
|
|
@ -286,10 +308,10 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
const screenId = menuUrl.match(/\/screens\/(\d+)/)?.[1];
|
||||
if (screenId) {
|
||||
// console.log("🔍 기존 메뉴에서 화면 ID 추출:", {
|
||||
// menuUrl,
|
||||
// screenId,
|
||||
// hasAdminParam: menuUrl.includes("mode=admin"),
|
||||
// currentScreensCount: screens.length,
|
||||
// menuUrl,
|
||||
// screenId,
|
||||
// hasAdminParam: menuUrl.includes("mode=admin"),
|
||||
// currentScreensCount: screens.length,
|
||||
// });
|
||||
|
||||
// 화면 설정 함수
|
||||
|
|
@ -298,15 +320,15 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
if (screen) {
|
||||
setSelectedScreen(screen);
|
||||
// console.log("🖥️ 기존 메뉴의 할당된 화면 설정:", {
|
||||
// screen,
|
||||
// originalUrl: menuUrl,
|
||||
// hasAdminParam: menuUrl.includes("mode=admin"),
|
||||
// screen,
|
||||
// originalUrl: menuUrl,
|
||||
// hasAdminParam: menuUrl.includes("mode=admin"),
|
||||
// });
|
||||
return true;
|
||||
} else {
|
||||
// console.warn("⚠️ 해당 ID의 화면을 찾을 수 없음:", {
|
||||
// screenId,
|
||||
// availableScreens: screens.map((s) => ({ screenId: s.screenId, id: s.id, name: s.screenName })),
|
||||
// screenId,
|
||||
// availableScreens: screens.map((s) => ({ screenId: s.screenId, id: s.id, name: s.screenName })),
|
||||
// });
|
||||
return false;
|
||||
}
|
||||
|
|
@ -325,30 +347,34 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
}, 500);
|
||||
}
|
||||
}
|
||||
} else if (menuUrl.startsWith("/dashboard/")) {
|
||||
setUrlType("dashboard");
|
||||
setSelectedScreen(null);
|
||||
// 대시보드 ID 추출 및 선택은 useEffect에서 처리됨
|
||||
} else {
|
||||
setUrlType("direct");
|
||||
setSelectedScreen(null);
|
||||
}
|
||||
|
||||
// console.log("설정된 폼 데이터:", {
|
||||
// objid: menu.objid || menu.OBJID,
|
||||
// parentObjId: menu.parent_obj_id || menu.PARENT_OBJ_ID || "0",
|
||||
// menuNameKor: menu.menu_name_kor || menu.MENU_NAME_KOR || "",
|
||||
// menuUrl: menu.menu_url || menu.MENU_URL || "",
|
||||
// menuDesc: menu.menu_desc || menu.MENU_DESC || "",
|
||||
// seq: menu.seq || menu.SEQ || 1,
|
||||
// menuType: convertedMenuType,
|
||||
// status: convertedStatus,
|
||||
// companyCode: companyCode,
|
||||
// langKey: langKey,
|
||||
// objid: menu.objid || menu.OBJID,
|
||||
// parentObjId: menu.parent_obj_id || menu.PARENT_OBJ_ID || "0",
|
||||
// menuNameKor: menu.menu_name_kor || menu.MENU_NAME_KOR || "",
|
||||
// menuUrl: menu.menu_url || menu.MENU_URL || "",
|
||||
// menuDesc: menu.menu_desc || menu.MENU_DESC || "",
|
||||
// seq: menu.seq || menu.SEQ || 1,
|
||||
// menuType: convertedMenuType,
|
||||
// status: convertedStatus,
|
||||
// companyCode: companyCode,
|
||||
// langKey: langKey,
|
||||
// });
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error("메뉴 정보 로딩 오류:", error);
|
||||
// console.error("오류 상세 정보:", {
|
||||
// message: error?.message,
|
||||
// stack: error?.stack,
|
||||
// response: error?.response,
|
||||
// message: error?.message,
|
||||
// stack: error?.stack,
|
||||
// response: error?.response,
|
||||
// });
|
||||
toast.error(getText(MENU_MANAGEMENT_KEYS.MESSAGE_ERROR_LOAD_MENU_INFO));
|
||||
} finally {
|
||||
|
|
@ -391,11 +417,11 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
});
|
||||
|
||||
// console.log("메뉴 등록 기본값 설정:", {
|
||||
// parentObjId: parentId || "0",
|
||||
// menuType: defaultMenuType,
|
||||
// status: "ACTIVE",
|
||||
// companyCode: "",
|
||||
// langKey: "",
|
||||
// parentObjId: parentId || "0",
|
||||
// menuType: defaultMenuType,
|
||||
// status: "ACTIVE",
|
||||
// companyCode: "",
|
||||
// langKey: "",
|
||||
// });
|
||||
}
|
||||
}, [menuId, parentId, menuType]);
|
||||
|
|
@ -430,10 +456,11 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
}
|
||||
}, [isOpen, formData.companyCode]);
|
||||
|
||||
// 화면 목록 로드
|
||||
// 화면 목록 및 대시보드 목록 로드
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
loadScreens();
|
||||
loadDashboards();
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
|
|
@ -449,9 +476,9 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
if (screen) {
|
||||
setSelectedScreen(screen);
|
||||
// console.log("✅ 기존 메뉴의 할당된 화면 자동 설정 완료:", {
|
||||
// screenId,
|
||||
// screenName: screen.screenName,
|
||||
// menuUrl,
|
||||
// screenId,
|
||||
// screenName: screen.screenName,
|
||||
// menuUrl,
|
||||
// });
|
||||
}
|
||||
}
|
||||
|
|
@ -459,6 +486,23 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
}
|
||||
}, [screens, isEdit, formData.menuUrl, urlType, selectedScreen]);
|
||||
|
||||
// 대시보드 목록 로드 완료 후 기존 메뉴의 할당된 대시보드 설정
|
||||
useEffect(() => {
|
||||
if (dashboards.length > 0 && isEdit && formData.menuUrl && urlType === "dashboard") {
|
||||
const menuUrl = formData.menuUrl;
|
||||
if (menuUrl.startsWith("/dashboard/")) {
|
||||
const dashboardId = menuUrl.replace("/dashboard/", "");
|
||||
if (dashboardId && !selectedDashboard) {
|
||||
console.log("🔄 대시보드 목록 로드 완료 - 기존 할당 대시보드 자동 설정");
|
||||
const dashboard = dashboards.find((d) => d.id === dashboardId);
|
||||
if (dashboard) {
|
||||
setSelectedDashboard(dashboard);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [dashboards, isEdit, formData.menuUrl, urlType, selectedDashboard]);
|
||||
|
||||
// 드롭다운 외부 클릭 시 닫기
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
|
|
@ -471,9 +515,13 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
setIsScreenDropdownOpen(false);
|
||||
setScreenSearchText("");
|
||||
}
|
||||
if (!target.closest(".dashboard-dropdown")) {
|
||||
setIsDashboardDropdownOpen(false);
|
||||
setDashboardSearchText("");
|
||||
}
|
||||
};
|
||||
|
||||
if (isLangKeyDropdownOpen || isScreenDropdownOpen) {
|
||||
if (isLangKeyDropdownOpen || isScreenDropdownOpen || isDashboardDropdownOpen) {
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
}
|
||||
|
||||
|
|
@ -751,6 +799,12 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
화면 할당
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="dashboard" id="dashboard" />
|
||||
<Label htmlFor="dashboard" className="cursor-pointer">
|
||||
대시보드 할당
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="direct" id="direct" />
|
||||
<Label htmlFor="direct" className="cursor-pointer">
|
||||
|
|
@ -826,10 +880,91 @@ export const MenuFormModal: React.FC<MenuFormModalProps> = ({
|
|||
|
||||
{/* 선택된 화면 정보 표시 */}
|
||||
{selectedScreen && (
|
||||
<div className="rounded-md border bg-accent p-3">
|
||||
<div className="bg-accent rounded-md border p-3">
|
||||
<div className="text-sm font-medium text-blue-900">{selectedScreen.screenName}</div>
|
||||
<div className="text-xs text-primary">코드: {selectedScreen.screenCode}</div>
|
||||
<div className="text-xs text-primary">생성된 URL: {formData.menuUrl}</div>
|
||||
<div className="text-primary text-xs">코드: {selectedScreen.screenCode}</div>
|
||||
<div className="text-primary text-xs">생성된 URL: {formData.menuUrl}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 대시보드 할당 */}
|
||||
{urlType === "dashboard" && (
|
||||
<div className="space-y-2">
|
||||
{/* 대시보드 선택 드롭다운 */}
|
||||
<div className="relative">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="w-full justify-between"
|
||||
onClick={() => setIsDashboardDropdownOpen(!isDashboardDropdownOpen)}
|
||||
>
|
||||
<span className="truncate">{selectedDashboard ? selectedDashboard.title : "대시보드 선택"}</span>
|
||||
<ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
|
||||
{/* 드롭다운 메뉴 */}
|
||||
{isDashboardDropdownOpen && (
|
||||
<div className="dashboard-dropdown absolute z-50 mt-1 max-h-60 w-full overflow-hidden rounded-md border bg-white shadow-lg">
|
||||
{/* 검색창 */}
|
||||
<div className="border-b p-2">
|
||||
<div className="relative">
|
||||
<Search className="absolute top-2.5 left-2 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="대시보드 검색..."
|
||||
value={dashboardSearchText}
|
||||
onChange={(e) => setDashboardSearchText(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 대시보드 목록 */}
|
||||
<div className="max-h-48 overflow-y-auto">
|
||||
{dashboards
|
||||
.filter(
|
||||
(dashboard) =>
|
||||
dashboard.title.toLowerCase().includes(dashboardSearchText.toLowerCase()) ||
|
||||
(dashboard.description &&
|
||||
dashboard.description.toLowerCase().includes(dashboardSearchText.toLowerCase())),
|
||||
)
|
||||
.map((dashboard) => (
|
||||
<div
|
||||
key={dashboard.id}
|
||||
onClick={() => handleDashboardSelect(dashboard)}
|
||||
className="cursor-pointer border-b px-3 py-2 last:border-b-0 hover:bg-gray-100"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-medium">{dashboard.title}</div>
|
||||
{dashboard.description && (
|
||||
<div className="text-xs text-gray-500">{dashboard.description}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{dashboards.filter(
|
||||
(dashboard) =>
|
||||
dashboard.title.toLowerCase().includes(dashboardSearchText.toLowerCase()) ||
|
||||
(dashboard.description &&
|
||||
dashboard.description.toLowerCase().includes(dashboardSearchText.toLowerCase())),
|
||||
).length === 0 && <div className="px-3 py-2 text-sm text-gray-500">검색 결과가 없습니다.</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 선택된 대시보드 정보 표시 */}
|
||||
{selectedDashboard && (
|
||||
<div className="bg-accent rounded-md border p-3">
|
||||
<div className="text-sm font-medium text-blue-900">{selectedDashboard.title}</div>
|
||||
{selectedDashboard.description && (
|
||||
<div className="text-primary text-xs">설명: {selectedDashboard.description}</div>
|
||||
)}
|
||||
<div className="text-primary text-xs">생성된 URL: {formData.menuUrl}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -106,10 +106,17 @@ import { CalendarWidget } from "./widgets/CalendarWidget";
|
|||
import { DriverManagementWidget } from "./widgets/DriverManagementWidget";
|
||||
import { ListWidget } from "./widgets/ListWidget";
|
||||
|
||||
// 야드 관리 3D 위젯
|
||||
const YardManagement3DWidget = dynamic(() => import("./widgets/YardManagement3DWidget"), {
|
||||
ssr: false,
|
||||
loading: () => <div className="flex h-full items-center justify-center text-sm text-gray-500">로딩 중...</div>,
|
||||
});
|
||||
|
||||
interface CanvasElementProps {
|
||||
element: DashboardElement;
|
||||
isSelected: boolean;
|
||||
cellSize: number;
|
||||
canvasWidth?: number;
|
||||
onUpdate: (id: string, updates: Partial<DashboardElement>) => void;
|
||||
onRemove: (id: string) => void;
|
||||
onSelect: (id: string | null) => void;
|
||||
|
|
@ -126,6 +133,7 @@ export function CanvasElement({
|
|||
element,
|
||||
isSelected,
|
||||
cellSize,
|
||||
canvasWidth = 1560,
|
||||
onUpdate,
|
||||
onRemove,
|
||||
onSelect,
|
||||
|
|
@ -164,7 +172,11 @@ export function CanvasElement({
|
|||
return;
|
||||
}
|
||||
|
||||
onSelect(element.id);
|
||||
// 선택되지 않은 경우에만 선택 처리
|
||||
if (!isSelected) {
|
||||
onSelect(element.id);
|
||||
}
|
||||
|
||||
setIsDragging(true);
|
||||
setDragStart({
|
||||
x: e.clientX,
|
||||
|
|
@ -174,7 +186,7 @@ export function CanvasElement({
|
|||
});
|
||||
e.preventDefault();
|
||||
},
|
||||
[element.id, element.position.x, element.position.y, onSelect],
|
||||
[element.id, element.position.x, element.position.y, onSelect, isSelected],
|
||||
);
|
||||
|
||||
// 리사이즈 핸들 마우스다운
|
||||
|
|
@ -202,15 +214,30 @@ export function CanvasElement({
|
|||
const deltaX = e.clientX - dragStart.x;
|
||||
const deltaY = e.clientY - dragStart.y;
|
||||
|
||||
// 임시 위치 계산 (스냅 안 됨)
|
||||
// 임시 위치 계산
|
||||
let rawX = Math.max(0, dragStart.elementX + deltaX);
|
||||
const rawY = Math.max(0, dragStart.elementY + deltaY);
|
||||
|
||||
// X 좌표가 캔버스 너비를 벗어나지 않도록 제한
|
||||
const maxX = GRID_CONFIG.CANVAS_WIDTH - element.size.width;
|
||||
const maxX = canvasWidth - element.size.width;
|
||||
rawX = Math.min(rawX, maxX);
|
||||
|
||||
setTempPosition({ x: rawX, y: rawY });
|
||||
// 드래그 중 실시간 스냅 (마그네틱 스냅)
|
||||
const subGridSize = Math.floor(cellSize / 3);
|
||||
const gridSize = cellSize + 5; // GAP 포함한 실제 그리드 크기
|
||||
const magneticThreshold = 15; // 큰 그리드에 끌리는 거리 (px)
|
||||
|
||||
// X 좌표 스냅 (큰 그리드 우선, 없으면 서브그리드)
|
||||
const nearestGridX = Math.round(rawX / gridSize) * gridSize;
|
||||
const distToGridX = Math.abs(rawX - nearestGridX);
|
||||
const snappedX = distToGridX <= magneticThreshold ? nearestGridX : Math.round(rawX / subGridSize) * subGridSize;
|
||||
|
||||
// Y 좌표 스냅 (큰 그리드 우선, 없으면 서브그리드)
|
||||
const nearestGridY = Math.round(rawY / gridSize) * gridSize;
|
||||
const distToGridY = Math.abs(rawY - nearestGridY);
|
||||
const snappedY = distToGridY <= magneticThreshold ? nearestGridY : Math.round(rawY / subGridSize) * subGridSize;
|
||||
|
||||
setTempPosition({ x: snappedX, y: snappedY });
|
||||
} else if (isResizing) {
|
||||
const deltaX = e.clientX - resizeStart.x;
|
||||
const deltaY = e.clientY - resizeStart.y;
|
||||
|
|
@ -223,8 +250,8 @@ export function CanvasElement({
|
|||
// 최소 크기 설정: 달력은 2x3, 나머지는 2x2
|
||||
const minWidthCells = 2;
|
||||
const minHeightCells = element.type === "widget" && element.subtype === "calendar" ? 3 : 2;
|
||||
const minWidth = GRID_CONFIG.CELL_SIZE * minWidthCells;
|
||||
const minHeight = GRID_CONFIG.CELL_SIZE * minHeightCells;
|
||||
const minWidth = cellSize * minWidthCells;
|
||||
const minHeight = cellSize * minHeightCells;
|
||||
|
||||
switch (resizeStart.handle) {
|
||||
case "se": // 오른쪽 아래
|
||||
|
|
@ -250,49 +277,92 @@ export function CanvasElement({
|
|||
}
|
||||
|
||||
// 가로 너비가 캔버스를 벗어나지 않도록 제한
|
||||
const maxWidth = GRID_CONFIG.CANVAS_WIDTH - newX;
|
||||
const maxWidth = canvasWidth - newX;
|
||||
newWidth = Math.min(newWidth, maxWidth);
|
||||
|
||||
// 임시 크기/위치 저장 (스냅 안 됨)
|
||||
setTempPosition({ x: Math.max(0, newX), y: Math.max(0, newY) });
|
||||
setTempSize({ width: newWidth, height: newHeight });
|
||||
// 리사이즈 중 실시간 스냅 (마그네틱 스냅)
|
||||
const subGridSize = Math.floor(cellSize / 3);
|
||||
const gridSize = cellSize + 5; // GAP 포함한 실제 그리드 크기
|
||||
const magneticThreshold = 15;
|
||||
|
||||
// 위치 스냅
|
||||
const nearestGridX = Math.round(newX / gridSize) * gridSize;
|
||||
const distToGridX = Math.abs(newX - nearestGridX);
|
||||
const snappedX = distToGridX <= magneticThreshold ? nearestGridX : Math.round(newX / subGridSize) * subGridSize;
|
||||
|
||||
const nearestGridY = Math.round(newY / gridSize) * gridSize;
|
||||
const distToGridY = Math.abs(newY - nearestGridY);
|
||||
const snappedY = distToGridY <= magneticThreshold ? nearestGridY : Math.round(newY / subGridSize) * subGridSize;
|
||||
|
||||
// 크기 스냅 (그리드 칸 단위로 스냅하되, 마지막 GAP은 제외)
|
||||
// 예: 1칸 = cellSize, 2칸 = cellSize*2 + GAP, 3칸 = cellSize*3 + GAP*2
|
||||
const calculateGridWidth = (cells: number) => cells * cellSize + Math.max(0, cells - 1) * 5;
|
||||
|
||||
// 가장 가까운 그리드 칸 수 계산
|
||||
const nearestWidthCells = Math.round(newWidth / gridSize);
|
||||
const nearestGridWidth = calculateGridWidth(nearestWidthCells);
|
||||
const distToGridWidth = Math.abs(newWidth - nearestGridWidth);
|
||||
const snappedWidth =
|
||||
distToGridWidth <= magneticThreshold ? nearestGridWidth : Math.round(newWidth / subGridSize) * subGridSize;
|
||||
|
||||
const nearestHeightCells = Math.round(newHeight / gridSize);
|
||||
const nearestGridHeight = calculateGridWidth(nearestHeightCells);
|
||||
const distToGridHeight = Math.abs(newHeight - nearestGridHeight);
|
||||
const snappedHeight =
|
||||
distToGridHeight <= magneticThreshold ? nearestGridHeight : Math.round(newHeight / subGridSize) * subGridSize;
|
||||
|
||||
// 임시 크기/위치 저장 (스냅됨)
|
||||
setTempPosition({ x: Math.max(0, snappedX), y: Math.max(0, snappedY) });
|
||||
setTempSize({ width: snappedWidth, height: snappedHeight });
|
||||
}
|
||||
},
|
||||
[isDragging, isResizing, dragStart, resizeStart, element.size.width, element.type, element.subtype],
|
||||
[
|
||||
isDragging,
|
||||
isResizing,
|
||||
dragStart,
|
||||
resizeStart,
|
||||
element.size.width,
|
||||
element.type,
|
||||
element.subtype,
|
||||
canvasWidth,
|
||||
cellSize,
|
||||
],
|
||||
);
|
||||
|
||||
// 마우스 업 처리 (그리드 스냅 적용)
|
||||
// 마우스 업 처리 (이미 스냅된 위치 사용)
|
||||
const handleMouseUp = useCallback(() => {
|
||||
if (isDragging && tempPosition) {
|
||||
// 드래그 종료 시 그리드에 스냅 (동적 셀 크기 사용)
|
||||
let snappedX = snapToGrid(tempPosition.x, cellSize);
|
||||
const snappedY = snapToGrid(tempPosition.y, cellSize);
|
||||
// tempPosition은 이미 드래그 중에 마그네틱 스냅 적용됨
|
||||
// 다시 스냅하지 않고 그대로 사용!
|
||||
let finalX = tempPosition.x;
|
||||
const finalY = tempPosition.y;
|
||||
|
||||
// X 좌표가 캔버스 너비를 벗어나지 않도록 최종 제한
|
||||
const maxX = GRID_CONFIG.CANVAS_WIDTH - element.size.width;
|
||||
snappedX = Math.min(snappedX, maxX);
|
||||
const maxX = canvasWidth - element.size.width;
|
||||
finalX = Math.min(finalX, maxX);
|
||||
|
||||
onUpdate(element.id, {
|
||||
position: { x: snappedX, y: snappedY },
|
||||
position: { x: finalX, y: finalY },
|
||||
});
|
||||
|
||||
setTempPosition(null);
|
||||
}
|
||||
|
||||
if (isResizing && tempPosition && tempSize) {
|
||||
// 리사이즈 종료 시 그리드에 스냅 (동적 셀 크기 사용)
|
||||
const snappedX = snapToGrid(tempPosition.x, cellSize);
|
||||
const snappedY = snapToGrid(tempPosition.y, cellSize);
|
||||
let snappedWidth = snapSizeToGrid(tempSize.width, 2, cellSize);
|
||||
const snappedHeight = snapSizeToGrid(tempSize.height, 2, cellSize);
|
||||
// tempPosition과 tempSize는 이미 리사이즈 중에 마그네틱 스냅 적용됨
|
||||
// 다시 스냅하지 않고 그대로 사용!
|
||||
const finalX = tempPosition.x;
|
||||
const finalY = tempPosition.y;
|
||||
let finalWidth = tempSize.width;
|
||||
const finalHeight = tempSize.height;
|
||||
|
||||
// 가로 너비가 캔버스를 벗어나지 않도록 최종 제한
|
||||
const maxWidth = GRID_CONFIG.CANVAS_WIDTH - snappedX;
|
||||
snappedWidth = Math.min(snappedWidth, maxWidth);
|
||||
const maxWidth = canvasWidth - finalX;
|
||||
finalWidth = Math.min(finalWidth, maxWidth);
|
||||
|
||||
onUpdate(element.id, {
|
||||
position: { x: snappedX, y: snappedY },
|
||||
size: { width: snappedWidth, height: snappedHeight },
|
||||
position: { x: finalX, y: finalY },
|
||||
size: { width: finalWidth, height: finalHeight },
|
||||
});
|
||||
|
||||
setTempPosition(null);
|
||||
|
|
@ -301,7 +371,7 @@ export function CanvasElement({
|
|||
|
||||
setIsDragging(false);
|
||||
setIsResizing(false);
|
||||
}, [isDragging, isResizing, tempPosition, tempSize, element.id, element.size.width, onUpdate, cellSize]);
|
||||
}, [isDragging, isResizing, tempPosition, tempSize, element.id, element.size.width, onUpdate, cellSize, canvasWidth]);
|
||||
|
||||
// 전역 마우스 이벤트 등록
|
||||
React.useEffect(() => {
|
||||
|
|
@ -362,7 +432,7 @@ export function CanvasElement({
|
|||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Chart data loading error:", error);
|
||||
// console.error("Chart data loading error:", error);
|
||||
setChartData(null);
|
||||
} finally {
|
||||
setIsLoadingData(false);
|
||||
|
|
@ -449,14 +519,11 @@ export function CanvasElement({
|
|||
>
|
||||
{/* 헤더 */}
|
||||
<div className="flex cursor-move items-center justify-between border-b border-gray-200 bg-gray-50 p-3">
|
||||
<span className="text-sm font-bold text-gray-800">{element.title}</span>
|
||||
<span className="text-sm font-bold text-gray-800">{element.customTitle || element.title}</span>
|
||||
<div className="flex gap-1">
|
||||
{/* 설정 버튼 (시계, 달력, 기사관리 위젯은 자체 설정 UI 사용) */}
|
||||
{/* 설정 버튼 (기사관리 위젯만 자체 설정 UI 사용) */}
|
||||
{onConfigure &&
|
||||
!(
|
||||
element.type === "widget" &&
|
||||
(element.subtype === "clock" || element.subtype === "calendar" || element.subtype === "driver-management")
|
||||
) && (
|
||||
!(element.type === "widget" && element.subtype === "driver-management") && (
|
||||
<button
|
||||
className="hover:bg-accent0 flex h-6 w-6 items-center justify-center rounded text-gray-400 transition-colors duration-200 hover:text-white"
|
||||
onClick={() => onConfigure(element)}
|
||||
|
|
@ -545,12 +612,7 @@ export function CanvasElement({
|
|||
) : element.type === "widget" && element.subtype === "status-summary" ? (
|
||||
// 커스텀 상태 카드 - 범용 위젯
|
||||
<div className="widget-interactive-area h-full w-full">
|
||||
<StatusSummaryWidget
|
||||
element={element}
|
||||
title="상태 요약"
|
||||
icon="📊"
|
||||
bgGradient="from-slate-50 to-blue-50"
|
||||
/>
|
||||
<StatusSummaryWidget element={element} title="상태 요약" icon="📊" bgGradient="from-slate-50 to-blue-50" />
|
||||
</div>
|
||||
) : /* element.type === "widget" && element.subtype === "list-summary" ? (
|
||||
// 커스텀 목록 카드 - 범용 위젯 (다른 분 작업 중 - 임시 주석)
|
||||
|
|
@ -576,10 +638,10 @@ export function CanvasElement({
|
|||
icon="📊"
|
||||
bgGradient="from-slate-50 to-blue-50"
|
||||
statusConfig={{
|
||||
"배송중": { label: "배송중", color: "blue" },
|
||||
"완료": { label: "완료", color: "green" },
|
||||
"지연": { label: "지연", color: "red" },
|
||||
"픽업 대기": { label: "픽업 대기", color: "yellow" }
|
||||
배송중: { label: "배송중", color: "blue" },
|
||||
완료: { label: "완료", color: "green" },
|
||||
지연: { label: "지연", color: "red" },
|
||||
"픽업 대기": { label: "픽업 대기", color: "yellow" },
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
|
@ -648,10 +710,21 @@ export function CanvasElement({
|
|||
}}
|
||||
/>
|
||||
</div>
|
||||
) : element.type === "widget" && element.subtype === "yard-management-3d" ? (
|
||||
// 야드 관리 3D 위젯 렌더링
|
||||
<div className="widget-interactive-area h-full w-full">
|
||||
<YardManagement3DWidget
|
||||
isEditMode={true}
|
||||
config={element.yardConfig}
|
||||
onConfigChange={(newConfig) => {
|
||||
onUpdate(element.id, { yardConfig: newConfig });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : element.type === "widget" && element.subtype === "todo" ? (
|
||||
// To-Do 위젯 렌더링
|
||||
<div className="widget-interactive-area h-full w-full">
|
||||
<TodoWidget />
|
||||
<TodoWidget element={element} />
|
||||
</div>
|
||||
) : element.type === "widget" && element.subtype === "booking-alert" ? (
|
||||
// 예약 요청 알림 위젯 렌더링
|
||||
|
|
|
|||
|
|
@ -98,7 +98,7 @@ export function ChartConfigPanel({
|
|||
setDateColumns(schema.dateColumns);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("❌ 테이블 스키마 조회 실패:", error);
|
||||
// console.error("❌ 테이블 스키마 조회 실패:", error);
|
||||
// 실패 시 빈 배열 (날짜 필터 비활성화)
|
||||
setDateColumns([]);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
"use client";
|
||||
|
||||
import React, { forwardRef, useState, useCallback, useEffect } from "react";
|
||||
import React, { forwardRef, useState, useCallback, useMemo } from "react";
|
||||
import { DashboardElement, ElementType, ElementSubtype, DragData } from "./types";
|
||||
import { CanvasElement } from "./CanvasElement";
|
||||
import { GRID_CONFIG, snapToGrid } from "./gridUtils";
|
||||
import { GRID_CONFIG, snapToGrid, calculateGridConfig } from "./gridUtils";
|
||||
import { resolveAllCollisions } from "./collisionUtils";
|
||||
|
||||
interface DashboardCanvasProps {
|
||||
elements: DashboardElement[];
|
||||
|
|
@ -14,6 +15,8 @@ interface DashboardCanvasProps {
|
|||
onSelectElement: (id: string | null) => void;
|
||||
onConfigureElement?: (element: DashboardElement) => void;
|
||||
backgroundColor?: string;
|
||||
canvasWidth?: number;
|
||||
canvasHeight?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -34,11 +37,92 @@ export const DashboardCanvas = forwardRef<HTMLDivElement, DashboardCanvasProps>(
|
|||
onSelectElement,
|
||||
onConfigureElement,
|
||||
backgroundColor = "#f9fafb",
|
||||
canvasWidth = 1560,
|
||||
canvasHeight = 768,
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
|
||||
// 현재 캔버스 크기에 맞는 그리드 설정 계산
|
||||
const gridConfig = useMemo(() => calculateGridConfig(canvasWidth), [canvasWidth]);
|
||||
const cellSize = gridConfig.CELL_SIZE;
|
||||
|
||||
// 충돌 방지 기능이 포함된 업데이트 핸들러
|
||||
const handleUpdateWithCollisionDetection = useCallback(
|
||||
(id: string, updates: Partial<DashboardElement>) => {
|
||||
// position이나 size가 아닌 다른 속성 업데이트는 충돌 감지 없이 바로 처리
|
||||
if (!updates.position && !updates.size) {
|
||||
onUpdateElement(id, updates);
|
||||
return;
|
||||
}
|
||||
|
||||
// 업데이트할 요소 찾기
|
||||
const elementIndex = elements.findIndex((el) => el.id === id);
|
||||
if (elementIndex === -1) {
|
||||
onUpdateElement(id, updates);
|
||||
return;
|
||||
}
|
||||
|
||||
// position이나 size와 다른 속성이 함께 있으면 분리해서 처리
|
||||
const positionSizeUpdates: any = {};
|
||||
const otherUpdates: any = {};
|
||||
|
||||
Object.keys(updates).forEach((key) => {
|
||||
if (key === "position" || key === "size") {
|
||||
positionSizeUpdates[key] = (updates as any)[key];
|
||||
} else {
|
||||
otherUpdates[key] = (updates as any)[key];
|
||||
}
|
||||
});
|
||||
|
||||
// 다른 속성들은 먼저 바로 업데이트
|
||||
if (Object.keys(otherUpdates).length > 0) {
|
||||
onUpdateElement(id, otherUpdates);
|
||||
}
|
||||
|
||||
// position/size가 없으면 여기서 종료
|
||||
if (Object.keys(positionSizeUpdates).length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 임시로 업데이트된 요소 배열 생성
|
||||
const updatedElements = elements.map((el) =>
|
||||
el.id === id
|
||||
? {
|
||||
...el,
|
||||
...positionSizeUpdates,
|
||||
position: positionSizeUpdates.position || el.position,
|
||||
size: positionSizeUpdates.size || el.size,
|
||||
}
|
||||
: el,
|
||||
);
|
||||
|
||||
// 서브 그리드 크기 계산 (cellSize / 3)
|
||||
const subGridSize = Math.floor(cellSize / 3);
|
||||
|
||||
// 충돌 해결 (서브 그리드 단위로 스냅 및 충돌 감지)
|
||||
const resolvedElements = resolveAllCollisions(updatedElements, id, subGridSize, canvasWidth, cellSize);
|
||||
|
||||
// 변경된 요소들만 업데이트
|
||||
resolvedElements.forEach((resolvedEl, idx) => {
|
||||
const originalEl = elements[idx];
|
||||
if (
|
||||
resolvedEl.position.x !== originalEl.position.x ||
|
||||
resolvedEl.position.y !== originalEl.position.y ||
|
||||
resolvedEl.size.width !== originalEl.size.width ||
|
||||
resolvedEl.size.height !== originalEl.size.height
|
||||
) {
|
||||
onUpdateElement(resolvedEl.id, {
|
||||
position: resolvedEl.position,
|
||||
size: resolvedEl.size,
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
[elements, onUpdateElement, cellSize, canvasWidth],
|
||||
);
|
||||
|
||||
// 드래그 오버 처리
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
|
|
@ -71,20 +155,32 @@ export const DashboardCanvas = forwardRef<HTMLDivElement, DashboardCanvasProps>(
|
|||
const rawX = e.clientX - rect.left + (ref.current?.scrollLeft || 0);
|
||||
const rawY = e.clientY - rect.top + (ref.current?.scrollTop || 0);
|
||||
|
||||
// 그리드에 스냅 (고정 셀 크기 사용)
|
||||
let snappedX = snapToGrid(rawX, GRID_CONFIG.CELL_SIZE);
|
||||
const snappedY = snapToGrid(rawY, GRID_CONFIG.CELL_SIZE);
|
||||
// 마그네틱 스냅 (큰 그리드 우선, 없으면 서브그리드)
|
||||
const subGridSize = Math.floor(cellSize / 3);
|
||||
const gridSize = cellSize + 5; // GAP 포함한 실제 그리드 크기
|
||||
const magneticThreshold = 15;
|
||||
|
||||
// X 좌표 스냅
|
||||
const nearestGridX = Math.round(rawX / gridSize) * gridSize;
|
||||
const distToGridX = Math.abs(rawX - nearestGridX);
|
||||
let snappedX = distToGridX <= magneticThreshold ? nearestGridX : Math.round(rawX / subGridSize) * subGridSize;
|
||||
|
||||
// Y 좌표 스냅
|
||||
const nearestGridY = Math.round(rawY / gridSize) * gridSize;
|
||||
const distToGridY = Math.abs(rawY - nearestGridY);
|
||||
const snappedY =
|
||||
distToGridY <= magneticThreshold ? nearestGridY : Math.round(rawY / subGridSize) * subGridSize;
|
||||
|
||||
// X 좌표가 캔버스 너비를 벗어나지 않도록 제한
|
||||
const maxX = GRID_CONFIG.CANVAS_WIDTH - GRID_CONFIG.CELL_SIZE * 2; // 최소 2칸 너비 보장
|
||||
const maxX = canvasWidth - cellSize * 2; // 최소 2칸 너비 보장
|
||||
snappedX = Math.max(0, Math.min(snappedX, maxX));
|
||||
|
||||
onCreateElement(dragData.type, dragData.subtype, snappedX, snappedY);
|
||||
} catch (error) {
|
||||
// console.error('드롭 데이터 파싱 오류:', error);
|
||||
} catch {
|
||||
// 드롭 데이터 파싱 오류 무시
|
||||
}
|
||||
},
|
||||
[ref, onCreateElement],
|
||||
[ref, onCreateElement, canvasWidth, cellSize],
|
||||
);
|
||||
|
||||
// 캔버스 클릭 시 선택 해제
|
||||
|
|
@ -97,28 +193,25 @@ export const DashboardCanvas = forwardRef<HTMLDivElement, DashboardCanvasProps>(
|
|||
[onSelectElement],
|
||||
);
|
||||
|
||||
// 고정 그리드 크기
|
||||
const cellWithGap = GRID_CONFIG.CELL_SIZE + GRID_CONFIG.GAP;
|
||||
// 동적 그리드 크기 계산
|
||||
const cellWithGap = cellSize + GRID_CONFIG.GAP;
|
||||
const gridSize = `${cellWithGap}px ${cellWithGap}px`;
|
||||
|
||||
// 캔버스 높이를 요소들의 최대 y + height 기준으로 계산 (최소 화면 높이 보장)
|
||||
const minCanvasHeight = Math.max(
|
||||
typeof window !== "undefined" ? window.innerHeight : 800,
|
||||
...elements.map((el) => el.position.y + el.size.height + 100), // 하단 여백 100px
|
||||
);
|
||||
// 12개 컬럼 구분선 위치 계산
|
||||
const columnLines = Array.from({ length: GRID_CONFIG.COLUMNS + 1 }, (_, i) => i * cellWithGap);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={`relative rounded-lg shadow-inner ${isDragOver ? "bg-blue-50/50" : ""} `}
|
||||
className={`relative w-full rounded-lg shadow-inner ${isDragOver ? "bg-blue-50/50" : ""} `}
|
||||
style={{
|
||||
backgroundColor,
|
||||
width: `${GRID_CONFIG.CANVAS_WIDTH}px`,
|
||||
minHeight: `${minCanvasHeight}px`,
|
||||
// 12 컬럼 그리드 배경
|
||||
height: `${canvasHeight}px`,
|
||||
minHeight: `${canvasHeight}px`,
|
||||
// 세밀한 그리드 배경
|
||||
backgroundImage: `
|
||||
linear-gradient(rgba(59, 130, 246, 0.15) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(59, 130, 246, 0.15) 1px, transparent 1px)
|
||||
linear-gradient(rgba(59, 130, 246, 0.08) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(59, 130, 246, 0.08) 1px, transparent 1px)
|
||||
`,
|
||||
backgroundSize: gridSize,
|
||||
backgroundPosition: "0 0",
|
||||
|
|
@ -129,14 +222,34 @@ export const DashboardCanvas = forwardRef<HTMLDivElement, DashboardCanvasProps>(
|
|||
onDrop={handleDrop}
|
||||
onClick={handleCanvasClick}
|
||||
>
|
||||
{/* 12개 컬럼 메인 구분선 */}
|
||||
{columnLines.map((x, i) => (
|
||||
<div
|
||||
key={`col-${i}`}
|
||||
className="pointer-events-none absolute top-0 h-full"
|
||||
style={{
|
||||
left: `${x}px`,
|
||||
width: "2px",
|
||||
zIndex: 1,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{/* 배치된 요소들 렌더링 */}
|
||||
{elements.length === 0 && (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center text-gray-400">
|
||||
<div className="text-center">
|
||||
<div className="text-sm">상단 메뉴에서 차트나 위젯을 선택하세요</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{elements.map((element) => (
|
||||
<CanvasElement
|
||||
key={element.id}
|
||||
element={element}
|
||||
isSelected={selectedElement === element.id}
|
||||
cellSize={GRID_CONFIG.CELL_SIZE}
|
||||
onUpdate={onUpdateElement}
|
||||
cellSize={cellSize}
|
||||
canvasWidth={canvasWidth}
|
||||
onUpdate={handleUpdateWithCollisionDetection}
|
||||
onRemove={onRemoveElement}
|
||||
onSelect={onSelectElement}
|
||||
onConfigure={onConfigureElement}
|
||||
|
|
|
|||
|
|
@ -3,12 +3,28 @@
|
|||
import React, { useState, useRef, useCallback } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { DashboardCanvas } from "./DashboardCanvas";
|
||||
import { DashboardSidebar } from "./DashboardSidebar";
|
||||
import { DashboardToolbar } from "./DashboardToolbar";
|
||||
import { DashboardTopMenu } from "./DashboardTopMenu";
|
||||
import { ElementConfigModal } from "./ElementConfigModal";
|
||||
import { ListWidgetConfigModal } from "./widgets/ListWidgetConfigModal";
|
||||
import { DashboardSaveModal } from "./DashboardSaveModal";
|
||||
import { DashboardElement, ElementType, ElementSubtype } from "./types";
|
||||
import { GRID_CONFIG } from "./gridUtils";
|
||||
import { GRID_CONFIG, snapToGrid, snapSizeToGrid, calculateCellSize } from "./gridUtils";
|
||||
import { Resolution, RESOLUTIONS, detectScreenResolution } from "./ResolutionSelector";
|
||||
import { DashboardProvider } from "@/contexts/DashboardContext";
|
||||
import { useMenu } from "@/contexts/MenuContext";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CheckCircle2 } from "lucide-react";
|
||||
|
||||
interface DashboardDesignerProps {
|
||||
dashboardId?: string;
|
||||
|
|
@ -23,6 +39,7 @@ interface DashboardDesignerProps {
|
|||
*/
|
||||
export default function DashboardDesigner({ dashboardId: initialDashboardId }: DashboardDesignerProps = {}) {
|
||||
const router = useRouter();
|
||||
const { refreshMenus } = useMenu();
|
||||
const [elements, setElements] = useState<DashboardElement[]>([]);
|
||||
const [selectedElement, setSelectedElement] = useState<string | null>(null);
|
||||
const [elementCounter, setElementCounter] = useState(0);
|
||||
|
|
@ -33,6 +50,82 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
const [canvasBackgroundColor, setCanvasBackgroundColor] = useState<string>("#f9fafb");
|
||||
const canvasRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// 저장 모달 상태
|
||||
const [saveModalOpen, setSaveModalOpen] = useState(false);
|
||||
const [dashboardDescription, setDashboardDescription] = useState<string>("");
|
||||
const [successModalOpen, setSuccessModalOpen] = useState(false);
|
||||
const [clearConfirmOpen, setClearConfirmOpen] = useState(false);
|
||||
|
||||
// 화면 해상도 자동 감지
|
||||
const [screenResolution] = useState<Resolution>(() => detectScreenResolution());
|
||||
const [resolution, setResolution] = useState<Resolution>(screenResolution);
|
||||
|
||||
// resolution 변경 감지 및 요소 자동 조정
|
||||
const handleResolutionChange = useCallback(
|
||||
(newResolution: Resolution) => {
|
||||
setResolution((prev) => {
|
||||
// 이전 해상도와 새 해상도의 캔버스 너비 비율 계산
|
||||
const oldConfig = RESOLUTIONS[prev];
|
||||
const newConfig = RESOLUTIONS[newResolution];
|
||||
const widthRatio = newConfig.width / oldConfig.width;
|
||||
|
||||
// 요소들의 위치와 크기를 비율에 맞춰 조정
|
||||
if (widthRatio !== 1 && elements.length > 0) {
|
||||
// 새 해상도의 셀 크기 계산
|
||||
const newCellSize = calculateCellSize(newConfig.width);
|
||||
|
||||
const adjustedElements = elements.map((el) => {
|
||||
// 비율에 맞춰 조정 (X와 너비만)
|
||||
const scaledX = el.position.x * widthRatio;
|
||||
const scaledWidth = el.size.width * widthRatio;
|
||||
|
||||
// 그리드에 스냅 (X, Y, 너비, 높이 모두)
|
||||
const snappedX = snapToGrid(scaledX, newCellSize);
|
||||
const snappedY = snapToGrid(el.position.y, newCellSize);
|
||||
const snappedWidth = snapSizeToGrid(scaledWidth, 2, newCellSize);
|
||||
const snappedHeight = snapSizeToGrid(el.size.height, 2, newCellSize);
|
||||
|
||||
return {
|
||||
...el,
|
||||
position: {
|
||||
x: snappedX,
|
||||
y: snappedY,
|
||||
},
|
||||
size: {
|
||||
width: snappedWidth,
|
||||
height: snappedHeight,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
setElements(adjustedElements);
|
||||
}
|
||||
|
||||
return newResolution;
|
||||
});
|
||||
},
|
||||
[elements],
|
||||
);
|
||||
|
||||
// 현재 해상도 설정 (안전하게 기본값 제공)
|
||||
const canvasConfig = RESOLUTIONS[resolution] || RESOLUTIONS.fhd;
|
||||
|
||||
// 캔버스 높이 동적 계산 (요소들의 최하단 위치 기준)
|
||||
const calculateCanvasHeight = useCallback(() => {
|
||||
if (elements.length === 0) {
|
||||
return canvasConfig.height; // 기본 높이
|
||||
}
|
||||
|
||||
// 모든 요소의 최하단 y 좌표 계산
|
||||
const maxBottomY = Math.max(...elements.map((el) => el.position.y + el.size.height));
|
||||
|
||||
// 최소 높이는 기본 높이, 요소가 아래로 내려가면 자동으로 늘어남
|
||||
// 패딩 추가 (100px 여유)
|
||||
return Math.max(canvasConfig.height, maxBottomY + 100);
|
||||
}, [elements, canvasConfig.height]);
|
||||
|
||||
const dynamicCanvasHeight = calculateCanvasHeight();
|
||||
|
||||
// 대시보드 ID가 props로 전달되면 로드
|
||||
React.useEffect(() => {
|
||||
if (initialDashboardId) {
|
||||
|
|
@ -44,17 +137,23 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
const loadDashboard = async (id: string) => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// console.log('🔄 대시보드 로딩:', id);
|
||||
|
||||
const { dashboardApi } = await import("@/lib/api/dashboard");
|
||||
const dashboard = await dashboardApi.getDashboard(id);
|
||||
|
||||
// console.log('✅ 대시보드 로딩 완료:', dashboard);
|
||||
|
||||
// 대시보드 정보 설정
|
||||
setDashboardId(dashboard.id);
|
||||
setDashboardTitle(dashboard.title);
|
||||
|
||||
// 저장된 설정 복원
|
||||
const settings = (dashboard as { settings?: { resolution?: Resolution; backgroundColor?: string } }).settings;
|
||||
if (settings?.resolution) {
|
||||
setResolution(settings.resolution);
|
||||
}
|
||||
|
||||
if (settings?.backgroundColor) {
|
||||
setCanvasBackgroundColor(settings.backgroundColor);
|
||||
}
|
||||
|
||||
// 요소들 설정
|
||||
if (dashboard.elements && dashboard.elements.length > 0) {
|
||||
setElements(dashboard.elements);
|
||||
|
|
@ -71,7 +170,6 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
setElementCounter(maxId);
|
||||
}
|
||||
} catch (error) {
|
||||
// console.error('❌ 대시보드 로딩 오류:', error);
|
||||
alert(
|
||||
"대시보드를 불러오는 중 오류가 발생했습니다.\n\n" +
|
||||
(error instanceof Error ? error.message : "알 수 없는 오류"),
|
||||
|
|
@ -81,9 +179,15 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
}
|
||||
};
|
||||
|
||||
// 새로운 요소 생성 (고정 그리드 기반 기본 크기)
|
||||
// 새로운 요소 생성 (동적 그리드 기반 기본 크기)
|
||||
const createElement = useCallback(
|
||||
(type: ElementType, subtype: ElementSubtype, x: number, y: number) => {
|
||||
// 좌표 유효성 검사
|
||||
if (isNaN(x) || isNaN(y)) {
|
||||
// console.error("Invalid coordinates:", { x, y });
|
||||
return;
|
||||
}
|
||||
|
||||
// 기본 크기 설정
|
||||
let defaultCells = { width: 2, height: 2 }; // 기본 위젯 크기
|
||||
|
||||
|
|
@ -93,11 +197,26 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
defaultCells = { width: 2, height: 3 }; // 달력 최소 크기
|
||||
}
|
||||
|
||||
const cellWithGap = GRID_CONFIG.CELL_SIZE + GRID_CONFIG.GAP;
|
||||
// 현재 해상도에 맞는 셀 크기 계산
|
||||
const cellSize = Math.floor((canvasConfig.width + GRID_CONFIG.GAP) / GRID_CONFIG.COLUMNS) - GRID_CONFIG.GAP;
|
||||
const cellWithGap = cellSize + GRID_CONFIG.GAP;
|
||||
|
||||
const defaultWidth = defaultCells.width * cellWithGap - GRID_CONFIG.GAP;
|
||||
const defaultHeight = defaultCells.height * cellWithGap - GRID_CONFIG.GAP;
|
||||
|
||||
// 크기 유효성 검사
|
||||
if (isNaN(defaultWidth) || isNaN(defaultHeight) || defaultWidth <= 0 || defaultHeight <= 0) {
|
||||
// console.error("Invalid size calculated:", {
|
||||
// canvasConfig,
|
||||
// cellSize,
|
||||
// cellWithGap,
|
||||
// defaultCells,
|
||||
// defaultWidth,
|
||||
// defaultHeight,
|
||||
// });
|
||||
return;
|
||||
}
|
||||
|
||||
const newElement: DashboardElement = {
|
||||
id: `element-${elementCounter + 1}`,
|
||||
type,
|
||||
|
|
@ -112,7 +231,25 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
setElementCounter((prev) => prev + 1);
|
||||
setSelectedElement(newElement.id);
|
||||
},
|
||||
[elementCounter],
|
||||
[elementCounter, canvasConfig],
|
||||
);
|
||||
|
||||
// 메뉴에서 요소 추가 시 (캔버스 중앙에 배치)
|
||||
const addElementFromMenu = useCallback(
|
||||
(type: ElementType, subtype: ElementSubtype) => {
|
||||
// 캔버스 중앙 좌표 계산
|
||||
const centerX = Math.floor(canvasConfig.width / 2);
|
||||
const centerY = Math.floor(canvasConfig.height / 2);
|
||||
|
||||
// 좌표 유효성 확인
|
||||
if (isNaN(centerX) || isNaN(centerY)) {
|
||||
// console.error("Invalid canvas config:", canvasConfig);
|
||||
return;
|
||||
}
|
||||
|
||||
createElement(type, subtype, centerX, centerY);
|
||||
},
|
||||
[canvasConfig, createElement],
|
||||
);
|
||||
|
||||
// 요소 업데이트
|
||||
|
|
@ -131,13 +268,17 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
[selectedElement],
|
||||
);
|
||||
|
||||
// 전체 삭제
|
||||
// 전체 삭제 확인 모달 열기
|
||||
const clearCanvas = useCallback(() => {
|
||||
if (window.confirm("모든 요소를 삭제하시겠습니까?")) {
|
||||
setElements([]);
|
||||
setSelectedElement(null);
|
||||
setElementCounter(0);
|
||||
}
|
||||
setClearConfirmOpen(true);
|
||||
}, []);
|
||||
|
||||
// 실제 초기화 실행
|
||||
const handleClearConfirm = useCallback(() => {
|
||||
setElements([]);
|
||||
setSelectedElement(null);
|
||||
setElementCounter(0);
|
||||
setClearConfirmOpen(false);
|
||||
}, []);
|
||||
|
||||
// 요소 설정 모달 열기
|
||||
|
|
@ -169,67 +310,125 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
);
|
||||
|
||||
// 레이아웃 저장
|
||||
const saveLayout = useCallback(async () => {
|
||||
const saveLayout = useCallback(() => {
|
||||
if (elements.length === 0) {
|
||||
alert("저장할 요소가 없습니다. 차트나 위젯을 추가해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 실제 API 호출
|
||||
const { dashboardApi } = await import("@/lib/api/dashboard");
|
||||
// 저장 모달 열기
|
||||
setSaveModalOpen(true);
|
||||
}, [elements]);
|
||||
|
||||
const elementsData = elements.map((el) => ({
|
||||
id: el.id,
|
||||
type: el.type,
|
||||
subtype: el.subtype,
|
||||
position: el.position,
|
||||
size: el.size,
|
||||
title: el.title,
|
||||
content: el.content,
|
||||
dataSource: el.dataSource,
|
||||
chartConfig: el.chartConfig,
|
||||
}));
|
||||
// 저장 처리
|
||||
const handleSave = useCallback(
|
||||
async (data: {
|
||||
title: string;
|
||||
description: string;
|
||||
assignToMenu: boolean;
|
||||
menuType?: "admin" | "user";
|
||||
menuId?: string;
|
||||
}) => {
|
||||
try {
|
||||
const { dashboardApi } = await import("@/lib/api/dashboard");
|
||||
|
||||
let savedDashboard;
|
||||
const elementsData = elements.map((el) => ({
|
||||
id: el.id,
|
||||
type: el.type,
|
||||
subtype: el.subtype,
|
||||
position: el.position,
|
||||
size: el.size,
|
||||
title: el.title,
|
||||
customTitle: el.customTitle,
|
||||
showHeader: el.showHeader,
|
||||
content: el.content,
|
||||
dataSource: el.dataSource,
|
||||
chartConfig: el.chartConfig,
|
||||
listConfig: el.listConfig,
|
||||
yardConfig: el.yardConfig,
|
||||
}));
|
||||
|
||||
if (dashboardId) {
|
||||
// 기존 대시보드 업데이트
|
||||
savedDashboard = await dashboardApi.updateDashboard(dashboardId, {
|
||||
elements: elementsData,
|
||||
});
|
||||
let savedDashboard;
|
||||
|
||||
alert(`대시보드 "${savedDashboard.title}"이 업데이트되었습니다!`);
|
||||
if (dashboardId) {
|
||||
// 기존 대시보드 업데이트
|
||||
const updateData = {
|
||||
title: data.title,
|
||||
description: data.description || undefined,
|
||||
elements: elementsData,
|
||||
settings: {
|
||||
resolution,
|
||||
backgroundColor: canvasBackgroundColor,
|
||||
},
|
||||
};
|
||||
|
||||
// Next.js 라우터로 뷰어 페이지 이동
|
||||
router.push(`/dashboard/${savedDashboard.id}`);
|
||||
} else {
|
||||
// 새 대시보드 생성
|
||||
const title = prompt("대시보드 제목을 입력하세요:", "새 대시보드");
|
||||
if (!title) return;
|
||||
savedDashboard = await dashboardApi.updateDashboard(dashboardId, updateData);
|
||||
} else {
|
||||
// 새 대시보드 생성
|
||||
const dashboardData = {
|
||||
title: data.title,
|
||||
description: data.description || undefined,
|
||||
isPublic: false,
|
||||
elements: elementsData,
|
||||
settings: {
|
||||
resolution,
|
||||
backgroundColor: canvasBackgroundColor,
|
||||
},
|
||||
};
|
||||
|
||||
const description = prompt("대시보드 설명을 입력하세요 (선택사항):", "");
|
||||
|
||||
const dashboardData = {
|
||||
title,
|
||||
description: description || undefined,
|
||||
isPublic: false,
|
||||
elements: elementsData,
|
||||
};
|
||||
|
||||
savedDashboard = await dashboardApi.createDashboard(dashboardData);
|
||||
|
||||
const viewDashboard = confirm(`대시보드 "${title}"이 저장되었습니다!\n\n지금 확인해보시겠습니까?`);
|
||||
if (viewDashboard) {
|
||||
// Next.js 라우터로 뷰어 페이지 이동
|
||||
router.push(`/dashboard/${savedDashboard.id}`);
|
||||
savedDashboard = await dashboardApi.createDashboard(dashboardData);
|
||||
setDashboardId(savedDashboard.id);
|
||||
}
|
||||
|
||||
setDashboardTitle(savedDashboard.title);
|
||||
setDashboardDescription(data.description);
|
||||
|
||||
// 메뉴 할당 처리
|
||||
if (data.assignToMenu && data.menuId) {
|
||||
const { menuApi } = await import("@/lib/api/menu");
|
||||
|
||||
// 대시보드 URL 생성 (관리자 메뉴면 mode=admin 추가)
|
||||
let dashboardUrl = `/dashboard/${savedDashboard.id}`;
|
||||
if (data.menuType === "admin") {
|
||||
dashboardUrl += "?mode=admin";
|
||||
}
|
||||
|
||||
// 메뉴 정보 가져오기
|
||||
const menuResponse = await menuApi.getMenuInfo(data.menuId);
|
||||
|
||||
if (menuResponse.success && menuResponse.data) {
|
||||
const menu = menuResponse.data;
|
||||
|
||||
const updateData = {
|
||||
menuUrl: dashboardUrl,
|
||||
parentObjId: menu.parent_obj_id || menu.PARENT_OBJ_ID || "0",
|
||||
menuNameKor: menu.menu_name_kor || menu.MENU_NAME_KOR || "",
|
||||
menuDesc: menu.menu_desc || menu.MENU_DESC || "",
|
||||
seq: menu.seq || menu.SEQ || 1,
|
||||
menuType: menu.menu_type || menu.MENU_TYPE || "1",
|
||||
status: menu.status || menu.STATUS || "active",
|
||||
companyCode: menu.company_code || menu.COMPANY_CODE || "",
|
||||
langKey: menu.lang_key || menu.LANG_KEY || "",
|
||||
};
|
||||
|
||||
// 메뉴 URL 업데이트
|
||||
await menuApi.updateMenu(data.menuId, updateData);
|
||||
|
||||
// 메뉴 목록 새로고침
|
||||
await refreshMenus();
|
||||
}
|
||||
}
|
||||
|
||||
// 성공 모달 표시
|
||||
setSuccessModalOpen(true);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : "알 수 없는 오류";
|
||||
alert(`대시보드 저장 중 오류가 발생했습니다.\n\n오류: ${errorMessage}`);
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : "알 수 없는 오류";
|
||||
alert(`대시보드 저장 중 오류가 발생했습니다.\n\n오류: ${errorMessage}\n\n관리자에게 문의하세요.`);
|
||||
}
|
||||
}, [elements, dashboardId, router]);
|
||||
},
|
||||
[elements, dashboardId, resolution, canvasBackgroundColor, refreshMenus],
|
||||
);
|
||||
|
||||
// 로딩 중이면 로딩 화면 표시
|
||||
if (isLoading) {
|
||||
|
|
@ -245,63 +444,128 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full bg-gray-50">
|
||||
{/* 캔버스 영역 */}
|
||||
<div className="relative flex-1 overflow-auto border-r-2 border-gray-300 bg-gray-100">
|
||||
{/* 편집 중인 대시보드 표시 */}
|
||||
{dashboardTitle && (
|
||||
<div className="bg-accent0 absolute top-6 left-6 z-10 rounded-lg px-3 py-1 text-sm font-medium text-white shadow-lg">
|
||||
📝 편집 중: {dashboardTitle}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DashboardToolbar
|
||||
onClearCanvas={clearCanvas}
|
||||
<DashboardProvider>
|
||||
<div className="flex h-full flex-col bg-gray-50">
|
||||
{/* 상단 메뉴바 */}
|
||||
<DashboardTopMenu
|
||||
onSaveLayout={saveLayout}
|
||||
canvasBackgroundColor={canvasBackgroundColor}
|
||||
onCanvasBackgroundColorChange={setCanvasBackgroundColor}
|
||||
onClearCanvas={clearCanvas}
|
||||
dashboardTitle={dashboardTitle}
|
||||
onAddElement={addElementFromMenu}
|
||||
resolution={resolution}
|
||||
onResolutionChange={handleResolutionChange}
|
||||
currentScreenResolution={screenResolution}
|
||||
backgroundColor={canvasBackgroundColor}
|
||||
onBackgroundColorChange={setCanvasBackgroundColor}
|
||||
/>
|
||||
|
||||
{/* 캔버스 중앙 정렬 컨테이너 */}
|
||||
<div className="flex justify-center p-4">
|
||||
<DashboardCanvas
|
||||
ref={canvasRef}
|
||||
elements={elements}
|
||||
selectedElement={selectedElement}
|
||||
onCreateElement={createElement}
|
||||
onUpdateElement={updateElement}
|
||||
onRemoveElement={removeElement}
|
||||
onSelectElement={setSelectedElement}
|
||||
onConfigureElement={openConfigModal}
|
||||
backgroundColor={canvasBackgroundColor}
|
||||
/>
|
||||
{/* 캔버스 영역 - 해상도에 따른 크기, 중앙 정렬 */}
|
||||
{/* overflow-auto 제거 - 외부 페이지 스크롤 사용 */}
|
||||
<div className="flex flex-1 items-start justify-center bg-gray-100 p-8">
|
||||
<div
|
||||
className="relative shadow-2xl"
|
||||
style={{
|
||||
width: `${canvasConfig.width}px`,
|
||||
minHeight: `${canvasConfig.height}px`,
|
||||
}}
|
||||
>
|
||||
<DashboardCanvas
|
||||
ref={canvasRef}
|
||||
elements={elements}
|
||||
selectedElement={selectedElement}
|
||||
onCreateElement={createElement}
|
||||
onUpdateElement={updateElement}
|
||||
onRemoveElement={removeElement}
|
||||
onSelectElement={setSelectedElement}
|
||||
onConfigureElement={openConfigModal}
|
||||
backgroundColor={canvasBackgroundColor}
|
||||
canvasWidth={canvasConfig.width}
|
||||
canvasHeight={dynamicCanvasHeight}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 요소 설정 모달 */}
|
||||
{configModalElement && (
|
||||
<>
|
||||
{configModalElement.type === "widget" && configModalElement.subtype === "list" ? (
|
||||
<ListWidgetConfigModal
|
||||
element={configModalElement}
|
||||
isOpen={true}
|
||||
onClose={closeConfigModal}
|
||||
onSave={saveListWidgetConfig}
|
||||
/>
|
||||
) : (
|
||||
<ElementConfigModal
|
||||
element={configModalElement}
|
||||
isOpen={true}
|
||||
onClose={closeConfigModal}
|
||||
onSave={saveElementConfig}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 저장 모달 */}
|
||||
<DashboardSaveModal
|
||||
isOpen={saveModalOpen}
|
||||
onClose={() => setSaveModalOpen(false)}
|
||||
onSave={handleSave}
|
||||
initialTitle={dashboardTitle}
|
||||
initialDescription={dashboardDescription}
|
||||
isEditing={!!dashboardId}
|
||||
/>
|
||||
|
||||
{/* 저장 성공 모달 */}
|
||||
<Dialog
|
||||
open={successModalOpen}
|
||||
onOpenChange={() => {
|
||||
setSuccessModalOpen(false);
|
||||
router.push("/admin/dashboard");
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
|
||||
<CheckCircle2 className="h-6 w-6 text-green-600" />
|
||||
</div>
|
||||
<DialogTitle className="text-center">저장 완료</DialogTitle>
|
||||
<DialogDescription className="text-center">대시보드가 성공적으로 저장되었습니다.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex justify-center pt-4">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setSuccessModalOpen(false);
|
||||
router.push("/admin/dashboard");
|
||||
}}
|
||||
>
|
||||
확인
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* 초기화 확인 모달 */}
|
||||
<AlertDialog open={clearConfirmOpen} onOpenChange={setClearConfirmOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>캔버스 초기화</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
모든 요소가 삭제됩니다. 이 작업은 되돌릴 수 없습니다.
|
||||
<br />
|
||||
계속하시겠습니까?
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleClearConfirm} className="bg-red-600 hover:bg-red-700">
|
||||
초기화
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
|
||||
{/* 사이드바 */}
|
||||
<DashboardSidebar />
|
||||
|
||||
{/* 요소 설정 모달 */}
|
||||
{configModalElement && (
|
||||
<>
|
||||
{configModalElement.type === "widget" && configModalElement.subtype === "list" ? (
|
||||
<ListWidgetConfigModal
|
||||
element={configModalElement}
|
||||
isOpen={true}
|
||||
onClose={closeConfigModal}
|
||||
onSave={saveListWidgetConfig}
|
||||
/>
|
||||
) : (
|
||||
<ElementConfigModal
|
||||
element={configModalElement}
|
||||
isOpen={true}
|
||||
onClose={closeConfigModal}
|
||||
onSave={saveElementConfig}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DashboardProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -310,36 +574,60 @@ function getElementTitle(type: ElementType, subtype: ElementSubtype): string {
|
|||
if (type === "chart") {
|
||||
switch (subtype) {
|
||||
case "bar":
|
||||
return "📊 바 차트";
|
||||
return "바 차트";
|
||||
case "horizontal-bar":
|
||||
return "📊 수평 바 차트";
|
||||
return "수평 바 차트";
|
||||
case "stacked-bar":
|
||||
return "누적 바 차트";
|
||||
case "pie":
|
||||
return "🥧 원형 차트";
|
||||
return "원형 차트";
|
||||
case "donut":
|
||||
return "도넛 차트";
|
||||
case "line":
|
||||
return "📈 꺾은선 차트";
|
||||
return "꺾은선 차트";
|
||||
case "area":
|
||||
return "영역 차트";
|
||||
case "combo":
|
||||
return "콤보 차트";
|
||||
default:
|
||||
return "📊 차트";
|
||||
return "차트";
|
||||
}
|
||||
} else if (type === "widget") {
|
||||
switch (subtype) {
|
||||
case "exchange":
|
||||
return "💱 환율 위젯";
|
||||
return "환율 위젯";
|
||||
case "weather":
|
||||
return "☁️ 날씨 위젯";
|
||||
return "날씨 위젯";
|
||||
case "clock":
|
||||
return "⏰ 시계 위젯";
|
||||
return "시계 위젯";
|
||||
case "calculator":
|
||||
return "🧮 계산기 위젯";
|
||||
return "계산기 위젯";
|
||||
case "vehicle-map":
|
||||
return "🚚 차량 위치 지도";
|
||||
return "차량 위치 지도";
|
||||
case "calendar":
|
||||
return "📅 달력 위젯";
|
||||
return "달력 위젯";
|
||||
case "driver-management":
|
||||
return "🚚 기사 관리 위젯";
|
||||
return "기사 관리 위젯";
|
||||
case "list":
|
||||
return "📋 리스트 위젯";
|
||||
return "리스트 위젯";
|
||||
case "map-summary":
|
||||
return "커스텀 지도 카드";
|
||||
case "status-summary":
|
||||
return "커스텀 상태 카드";
|
||||
case "risk-alert":
|
||||
return "리스크 알림 위젯";
|
||||
case "todo":
|
||||
return "할 일 위젯";
|
||||
case "booking-alert":
|
||||
return "예약 알림 위젯";
|
||||
case "maintenance":
|
||||
return "정비 일정 위젯";
|
||||
case "document":
|
||||
return "문서 위젯";
|
||||
case "yard-management-3d":
|
||||
return "야드 관리 3D";
|
||||
default:
|
||||
return "🔧 위젯";
|
||||
return "위젯";
|
||||
}
|
||||
}
|
||||
return "요소";
|
||||
|
|
@ -378,6 +666,8 @@ function getElementContent(type: ElementType, subtype: ElementSubtype): string {
|
|||
return "driver-management";
|
||||
case "list":
|
||||
return "list-widget";
|
||||
case "yard-management-3d":
|
||||
return "yard-3d";
|
||||
default:
|
||||
return "위젯 내용이 여기에 표시됩니다";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,321 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectGroup,
|
||||
SelectLabel,
|
||||
} from "@/components/ui/select";
|
||||
import { Loader2, Save } from "lucide-react";
|
||||
import { menuApi } from "@/lib/api/menu";
|
||||
|
||||
interface MenuItem {
|
||||
id: string;
|
||||
name: string;
|
||||
url?: string;
|
||||
parent_id?: string;
|
||||
children?: MenuItem[];
|
||||
}
|
||||
|
||||
interface DashboardSaveModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (data: {
|
||||
title: string;
|
||||
description: string;
|
||||
assignToMenu: boolean;
|
||||
menuType?: "admin" | "user";
|
||||
menuId?: string;
|
||||
}) => Promise<void>;
|
||||
initialTitle?: string;
|
||||
initialDescription?: string;
|
||||
isEditing?: boolean;
|
||||
}
|
||||
|
||||
export function DashboardSaveModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
initialTitle = "",
|
||||
initialDescription = "",
|
||||
isEditing = false,
|
||||
}: DashboardSaveModalProps) {
|
||||
const [title, setTitle] = useState(initialTitle);
|
||||
const [description, setDescription] = useState(initialDescription);
|
||||
const [assignToMenu, setAssignToMenu] = useState(false);
|
||||
const [menuType, setMenuType] = useState<"admin" | "user">("admin");
|
||||
const [selectedMenuId, setSelectedMenuId] = useState<string>("");
|
||||
const [adminMenus, setAdminMenus] = useState<MenuItem[]>([]);
|
||||
const [userMenus, setUserMenus] = useState<MenuItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadingMenus, setLoadingMenus] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setTitle(initialTitle);
|
||||
setDescription(initialDescription);
|
||||
setAssignToMenu(false);
|
||||
setMenuType("admin");
|
||||
setSelectedMenuId("");
|
||||
loadMenus();
|
||||
}
|
||||
}, [isOpen, initialTitle, initialDescription]);
|
||||
|
||||
const loadMenus = async () => {
|
||||
setLoadingMenus(true);
|
||||
try {
|
||||
const [adminData, userData] = await Promise.all([menuApi.getAdminMenus(), menuApi.getUserMenus()]);
|
||||
|
||||
// API 응답이 배열인지 확인하고 처리
|
||||
const adminMenuList = Array.isArray(adminData) ? adminData : adminData?.data || [];
|
||||
const userMenuList = Array.isArray(userData) ? userData : userData?.data || [];
|
||||
|
||||
setAdminMenus(adminMenuList);
|
||||
setUserMenus(userMenuList);
|
||||
} catch (error) {
|
||||
// console.error("메뉴 목록 로드 실패:", error);
|
||||
setAdminMenus([]);
|
||||
setUserMenus([]);
|
||||
} finally {
|
||||
setLoadingMenus(false);
|
||||
}
|
||||
};
|
||||
|
||||
const flattenMenus = (
|
||||
menus: MenuItem[],
|
||||
prefix = "",
|
||||
parentPath = "",
|
||||
): { id: string; label: string; uniqueKey: string }[] => {
|
||||
if (!Array.isArray(menus)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const result: { id: string; label: string; uniqueKey: string }[] = [];
|
||||
menus.forEach((menu, index) => {
|
||||
// 메뉴 ID 추출 (objid 또는 id)
|
||||
const menuId = (menu as any).objid || menu.id || "";
|
||||
const uniqueKey = `${parentPath}-${menuId}-${index}`;
|
||||
|
||||
// 메뉴 이름 추출
|
||||
const menuName =
|
||||
menu.name ||
|
||||
(menu as any).menu_name_kor ||
|
||||
(menu as any).MENU_NAME_KOR ||
|
||||
(menu as any).menuNameKor ||
|
||||
(menu as any).title ||
|
||||
"이름없음";
|
||||
|
||||
// lev 필드로 레벨 확인 (lev > 1인 메뉴만 추가)
|
||||
const menuLevel = (menu as any).lev || 0;
|
||||
|
||||
if (menuLevel > 1) {
|
||||
result.push({
|
||||
id: menuId,
|
||||
label: prefix + menuName,
|
||||
uniqueKey,
|
||||
});
|
||||
}
|
||||
|
||||
// 하위 메뉴가 있으면 재귀 호출
|
||||
if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
|
||||
result.push(...flattenMenus(menu.children, prefix + menuName + " > ", uniqueKey));
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!title.trim()) {
|
||||
alert("대시보드 이름을 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (assignToMenu && !selectedMenuId) {
|
||||
alert("메뉴를 선택해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
await onSave({
|
||||
title: title.trim(),
|
||||
description: description.trim(),
|
||||
assignToMenu,
|
||||
menuType: assignToMenu ? menuType : undefined,
|
||||
menuId: assignToMenu ? selectedMenuId : undefined,
|
||||
});
|
||||
onClose();
|
||||
} catch (error) {
|
||||
// console.error("저장 실패:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const currentMenus = menuType === "admin" ? adminMenus : userMenus;
|
||||
const flatMenus = flattenMenus(currentMenus);
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEditing ? "대시보드 수정" : "대시보드 저장"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 py-4">
|
||||
{/* 대시보드 이름 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="title">
|
||||
대시보드 이름 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="예: 생산 현황 대시보드"
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 대시보드 설명 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">설명</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="대시보드에 대한 간단한 설명을 입력하세요"
|
||||
rows={3}
|
||||
className="w-full resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 구분선 */}
|
||||
<div className="border-t pt-4">
|
||||
<h3 className="mb-3 text-sm font-semibold">메뉴 할당</h3>
|
||||
|
||||
{/* 메뉴 할당 여부 */}
|
||||
<div className="space-y-4">
|
||||
<RadioGroup
|
||||
value={assignToMenu ? "yes" : "no"}
|
||||
onValueChange={(value) => setAssignToMenu(value === "yes")}
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="no" id="assign-no" />
|
||||
<Label htmlFor="assign-no" className="cursor-pointer">
|
||||
메뉴에 할당하지 않음
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="yes" id="assign-yes" />
|
||||
<Label htmlFor="assign-yes" className="cursor-pointer">
|
||||
메뉴에 할당
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
|
||||
{/* 메뉴 할당 옵션 */}
|
||||
{assignToMenu && (
|
||||
<div className="ml-6 space-y-4 border-l-2 border-gray-200 pl-4">
|
||||
{/* 메뉴 타입 선택 */}
|
||||
<div className="space-y-2">
|
||||
<Label>메뉴 타입</Label>
|
||||
<RadioGroup value={menuType} onValueChange={(value) => setMenuType(value as "admin" | "user")}>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="admin" id="menu-admin" />
|
||||
<Label htmlFor="menu-admin" className="cursor-pointer">
|
||||
관리자 메뉴
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="user" id="menu-user" />
|
||||
<Label htmlFor="menu-user" className="cursor-pointer">
|
||||
사용자 메뉴
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
{/* 메뉴 선택 */}
|
||||
<div className="space-y-2">
|
||||
<Label>메뉴 선택</Label>
|
||||
{loadingMenus ? (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-gray-400" />
|
||||
<span className="ml-2 text-sm text-gray-500">메뉴 목록 로딩 중...</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<Select value={selectedMenuId} onValueChange={setSelectedMenuId}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="메뉴를 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="z-[99999]">
|
||||
<SelectGroup>
|
||||
<SelectLabel>{menuType === "admin" ? "관리자 메뉴" : "사용자 메뉴"}</SelectLabel>
|
||||
{flatMenus.length === 0 ? (
|
||||
<div className="px-2 py-3 text-sm text-gray-500">사용 가능한 메뉴가 없습니다.</div>
|
||||
) : (
|
||||
flatMenus.map((menu) => (
|
||||
<SelectItem key={menu.uniqueKey} value={menu.id}>
|
||||
{menu.label}
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{selectedMenuId && (
|
||||
<div className="rounded-md bg-gray-50 p-2 text-sm text-gray-700">
|
||||
선택된 메뉴:{" "}
|
||||
<span className="font-medium">{flatMenus.find((m) => m.id === selectedMenuId)?.label}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{assignToMenu && selectedMenuId && (
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
선택한 메뉴의 URL이 이 대시보드로 자동 설정됩니다.
|
||||
{menuType === "admin" && " (관리자 모드 파라미터 포함)"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose} disabled={loading}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={loading}>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
저장 중...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
저장
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
|
@ -47,56 +47,48 @@ export function DashboardSidebar() {
|
|||
{expandedSections.charts && (
|
||||
<div className="space-y-2">
|
||||
<DraggableItem
|
||||
icon="📊"
|
||||
title="바 차트"
|
||||
type="chart"
|
||||
subtype="bar"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="📊"
|
||||
title="수평 바 차트"
|
||||
type="chart"
|
||||
subtype="horizontal-bar"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="📚"
|
||||
title="누적 바 차트"
|
||||
type="chart"
|
||||
subtype="stacked-bar"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="📈"
|
||||
title="꺾은선 차트"
|
||||
type="chart"
|
||||
subtype="line"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="📉"
|
||||
title="영역 차트"
|
||||
type="chart"
|
||||
subtype="area"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="🥧"
|
||||
title="원형 차트"
|
||||
type="chart"
|
||||
subtype="pie"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="🍩"
|
||||
title="도넛 차트"
|
||||
type="chart"
|
||||
subtype="donut"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="📊"
|
||||
title="콤보 차트"
|
||||
type="chart"
|
||||
subtype="combo"
|
||||
|
|
@ -123,64 +115,60 @@ export function DashboardSidebar() {
|
|||
{expandedSections.widgets && (
|
||||
<div className="space-y-2">
|
||||
<DraggableItem
|
||||
icon="💱"
|
||||
title="환율 위젯"
|
||||
type="widget"
|
||||
subtype="exchange"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="☁️"
|
||||
title="날씨 위젯"
|
||||
type="widget"
|
||||
subtype="weather"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="🧮"
|
||||
title="계산기 위젯"
|
||||
type="widget"
|
||||
subtype="calculator"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="⏰"
|
||||
title="시계 위젯"
|
||||
type="widget"
|
||||
subtype="clock"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="📍"
|
||||
title="커스텀 지도 카드"
|
||||
type="widget"
|
||||
subtype="map-summary"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
{/* 주석: 다른 분이 범용 리스트 작업 중 - 충돌 방지를 위해 임시 주석처리 */}
|
||||
{/* <DraggableItem
|
||||
icon="📋"
|
||||
title="커스텀 목록 카드"
|
||||
type="widget"
|
||||
subtype="list-summary"
|
||||
onDragStart={handleDragStart}
|
||||
/> */}
|
||||
<DraggableItem
|
||||
icon="⚠️"
|
||||
title="리스크/알림 위젯"
|
||||
type="widget"
|
||||
subtype="risk-alert"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="📅"
|
||||
title="To-Do / 긴급 지시"
|
||||
type="widget"
|
||||
subtype="todo"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
title="달력 위젯"
|
||||
type="widget"
|
||||
subtype="calendar"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="📊"
|
||||
title="커스텀 상태 카드"
|
||||
type="widget"
|
||||
subtype="status-summary"
|
||||
|
|
@ -207,14 +195,12 @@ export function DashboardSidebar() {
|
|||
{expandedSections.operations && (
|
||||
<div className="space-y-2">
|
||||
<DraggableItem
|
||||
icon="✅"
|
||||
title="To-Do / 긴급 지시"
|
||||
type="widget"
|
||||
subtype="todo"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="🔔"
|
||||
title="예약 요청 알림"
|
||||
type="widget"
|
||||
subtype="booking-alert"
|
||||
|
|
@ -222,14 +208,12 @@ export function DashboardSidebar() {
|
|||
/>
|
||||
{/* 정비 일정 관리 위젯 제거 - 커스텀 목록 카드로 대체 가능 */}
|
||||
<DraggableItem
|
||||
icon="📂"
|
||||
title="문서 다운로드"
|
||||
type="widget"
|
||||
subtype="document"
|
||||
onDragStart={handleDragStart}
|
||||
/>
|
||||
<DraggableItem
|
||||
icon="📋"
|
||||
title="리스트 위젯"
|
||||
type="widget"
|
||||
subtype="list"
|
||||
|
|
@ -243,7 +227,7 @@ export function DashboardSidebar() {
|
|||
}
|
||||
|
||||
interface DraggableItemProps {
|
||||
icon: string;
|
||||
icon?: string;
|
||||
title: string;
|
||||
type: ElementType;
|
||||
subtype: ElementSubtype;
|
||||
|
|
@ -254,7 +238,7 @@ interface DraggableItemProps {
|
|||
/**
|
||||
* 드래그 가능한 아이템 컴포넌트
|
||||
*/
|
||||
function DraggableItem({ icon, title, type, subtype, className = "", onDragStart }: DraggableItemProps) {
|
||||
function DraggableItem({ title, type, subtype, className = "", onDragStart }: DraggableItemProps) {
|
||||
return (
|
||||
<div
|
||||
draggable
|
||||
|
|
|
|||
|
|
@ -0,0 +1,227 @@
|
|||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Save, Trash2, Palette } from "lucide-react";
|
||||
import { ElementType, ElementSubtype } from "./types";
|
||||
import { ResolutionSelector, Resolution } from "./ResolutionSelector";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
|
||||
interface DashboardTopMenuProps {
|
||||
onSaveLayout: () => void;
|
||||
onClearCanvas: () => void;
|
||||
dashboardTitle?: string;
|
||||
onAddElement?: (type: ElementType, subtype: ElementSubtype) => void;
|
||||
resolution?: Resolution;
|
||||
onResolutionChange?: (resolution: Resolution) => void;
|
||||
currentScreenResolution?: Resolution;
|
||||
backgroundColor?: string;
|
||||
onBackgroundColorChange?: (color: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 대시보드 편집 화면 상단 메뉴바
|
||||
* - 차트/위젯 선택 (셀렉트박스)
|
||||
* - 저장/초기화 버튼
|
||||
*/
|
||||
export function DashboardTopMenu({
|
||||
onSaveLayout,
|
||||
onClearCanvas,
|
||||
dashboardTitle,
|
||||
onAddElement,
|
||||
resolution = "fhd",
|
||||
onResolutionChange,
|
||||
currentScreenResolution,
|
||||
backgroundColor = "#f9fafb",
|
||||
onBackgroundColorChange,
|
||||
}: DashboardTopMenuProps) {
|
||||
const [chartValue, setChartValue] = React.useState<string>("");
|
||||
const [widgetValue, setWidgetValue] = React.useState<string>("");
|
||||
|
||||
// 차트 선택 시 캔버스 중앙에 추가
|
||||
const handleChartSelect = (value: string) => {
|
||||
if (onAddElement) {
|
||||
onAddElement("chart", value as ElementSubtype);
|
||||
// 선택 후 즉시 리셋하여 같은 항목을 연속으로 선택 가능하게
|
||||
setTimeout(() => setChartValue(""), 0);
|
||||
}
|
||||
};
|
||||
|
||||
// 위젯 선택 시 캔버스 중앙에 추가
|
||||
const handleWidgetSelect = (value: string) => {
|
||||
if (onAddElement) {
|
||||
onAddElement("widget", value as ElementSubtype);
|
||||
// 선택 후 즉시 리셋하여 같은 항목을 연속으로 선택 가능하게
|
||||
setTimeout(() => setWidgetValue(""), 0);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-16 items-center justify-between border-b bg-white px-6 shadow-sm">
|
||||
{/* 좌측: 대시보드 제목 */}
|
||||
<div className="flex items-center gap-4">
|
||||
{dashboardTitle && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg font-semibold text-gray-900">{dashboardTitle}</span>
|
||||
<span className="rounded bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-700">편집 중</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 중앙: 해상도 선택 & 요소 추가 */}
|
||||
<div className="flex items-center gap-3">
|
||||
{/* 해상도 선택 */}
|
||||
{onResolutionChange && (
|
||||
<ResolutionSelector
|
||||
value={resolution}
|
||||
onChange={onResolutionChange}
|
||||
currentScreenResolution={currentScreenResolution}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="h-6 w-px bg-gray-300" />
|
||||
|
||||
{/* 배경색 선택 */}
|
||||
{onBackgroundColorChange && (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="gap-2">
|
||||
<Palette className="h-4 w-4" />
|
||||
<div className="h-4 w-4 rounded border border-gray-300" style={{ backgroundColor }} />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="z-[99999] w-64">
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="text-sm font-medium">캔버스 배경색</label>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
type="color"
|
||||
value={backgroundColor}
|
||||
onChange={(e) => onBackgroundColorChange(e.target.value)}
|
||||
className="h-10 w-20 cursor-pointer"
|
||||
/>
|
||||
<Input
|
||||
type="text"
|
||||
value={backgroundColor}
|
||||
onChange={(e) => onBackgroundColorChange(e.target.value)}
|
||||
placeholder="#f9fafb"
|
||||
className="flex-1"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-6 gap-2">
|
||||
{[
|
||||
"#ffffff",
|
||||
"#f9fafb",
|
||||
"#f3f4f6",
|
||||
"#e5e7eb",
|
||||
"#1f2937",
|
||||
"#111827",
|
||||
"#fef3c7",
|
||||
"#fde68a",
|
||||
"#dbeafe",
|
||||
"#bfdbfe",
|
||||
"#fecaca",
|
||||
"#fca5a5",
|
||||
].map((color) => (
|
||||
<button
|
||||
key={color}
|
||||
className="h-8 w-8 rounded border-2 transition-transform hover:scale-110"
|
||||
style={{
|
||||
backgroundColor: color,
|
||||
borderColor: backgroundColor === color ? "#3b82f6" : "#d1d5db",
|
||||
}}
|
||||
onClick={() => onBackgroundColorChange(color)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
|
||||
<div className="h-6 w-px bg-gray-300" />
|
||||
{/* 차트 선택 */}
|
||||
<Select value={chartValue} onValueChange={handleChartSelect}>
|
||||
<SelectTrigger className="w-[200px]">
|
||||
<SelectValue placeholder="차트 추가" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="z-[99999]">
|
||||
<SelectGroup>
|
||||
<SelectLabel>차트</SelectLabel>
|
||||
<SelectItem value="bar">바 차트</SelectItem>
|
||||
<SelectItem value="horizontal-bar">수평 바 차트</SelectItem>
|
||||
<SelectItem value="stacked-bar">누적 바 차트</SelectItem>
|
||||
<SelectItem value="line">꺾은선 차트</SelectItem>
|
||||
<SelectItem value="area">영역 차트</SelectItem>
|
||||
<SelectItem value="pie">원형 차트</SelectItem>
|
||||
<SelectItem value="donut">도넛 차트</SelectItem>
|
||||
<SelectItem value="combo">콤보 차트</SelectItem>
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 위젯 선택 */}
|
||||
<Select value={widgetValue} onValueChange={handleWidgetSelect}>
|
||||
<SelectTrigger className="w-[200px]">
|
||||
<SelectValue placeholder="위젯 추가" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="z-[99999]">
|
||||
<SelectGroup>
|
||||
<SelectLabel>데이터 위젯</SelectLabel>
|
||||
<SelectItem value="list">리스트 위젯</SelectItem>
|
||||
<SelectItem value="yard-management-3d">야드 관리 3D</SelectItem>
|
||||
{/* <SelectItem value="map">지도</SelectItem> */}
|
||||
<SelectItem value="map-summary">커스텀 지도 카드</SelectItem>
|
||||
{/* <SelectItem value="list-summary">커스텀 목록 카드</SelectItem> */}
|
||||
<SelectItem value="status-summary">커스텀 상태 카드</SelectItem>
|
||||
</SelectGroup>
|
||||
<SelectGroup>
|
||||
<SelectLabel>일반 위젯</SelectLabel>
|
||||
<SelectItem value="weather">날씨</SelectItem>
|
||||
<SelectItem value="exchange">환율</SelectItem>
|
||||
<SelectItem value="calculator">계산기</SelectItem>
|
||||
<SelectItem value="calendar">달력</SelectItem>
|
||||
<SelectItem value="clock">시계</SelectItem>
|
||||
<SelectItem value="todo">할 일</SelectItem>
|
||||
<SelectItem value="booking-alert">예약 알림</SelectItem>
|
||||
<SelectItem value="maintenance">정비 일정</SelectItem>
|
||||
<SelectItem value="document">문서</SelectItem>
|
||||
<SelectItem value="risk-alert">리스크 알림</SelectItem>
|
||||
</SelectGroup>
|
||||
{/* 범용 위젯으로 대체 가능하여 주석처리 */}
|
||||
{/* <SelectGroup>
|
||||
<SelectLabel>차량 관리</SelectLabel>
|
||||
<SelectItem value="vehicle-status">차량 상태</SelectItem>
|
||||
<SelectItem value="vehicle-list">차량 목록</SelectItem>
|
||||
<SelectItem value="vehicle-map">차량 위치</SelectItem>
|
||||
</SelectGroup> */}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 우측: 액션 버튼 */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={onClearCanvas} className="gap-2 text-red-600 hover:text-red-700">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
초기화
|
||||
</Button>
|
||||
<Button size="sm" onClick={onSaveLayout} className="gap-2">
|
||||
<Save className="h-4 w-4" />
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -32,6 +32,7 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
|
|||
const [queryResult, setQueryResult] = useState<QueryResult | null>(null);
|
||||
const [currentStep, setCurrentStep] = useState<1 | 2>(1);
|
||||
const [customTitle, setCustomTitle] = useState<string>(element.customTitle || "");
|
||||
const [showHeader, setShowHeader] = useState<boolean>(element.showHeader !== false);
|
||||
|
||||
// 차트 설정이 필요 없는 위젯 (쿼리/API만 필요)
|
||||
const isSimpleWidget =
|
||||
|
|
@ -97,7 +98,7 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
|
|||
setQueryResult(result);
|
||||
|
||||
// 쿼리가 변경되었으므로 차트 설정 초기화 (X/Y축 리셋)
|
||||
console.log("🔄 쿼리 변경 감지 - 차트 설정 초기화");
|
||||
// console.log("🔄 쿼리 변경 감지 - 차트 설정 초기화");
|
||||
setChartConfig({});
|
||||
}, []);
|
||||
|
||||
|
|
@ -122,22 +123,23 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
|
|||
dataSource,
|
||||
chartConfig,
|
||||
customTitle: customTitle.trim() || undefined, // 빈 문자열이면 undefined
|
||||
showHeader, // 헤더 표시 여부
|
||||
};
|
||||
|
||||
console.log(" 저장할 element:", updatedElement);
|
||||
// console.log(" 저장할 element:", updatedElement);
|
||||
|
||||
onSave(updatedElement);
|
||||
onClose();
|
||||
}, [element, dataSource, chartConfig, customTitle, onSave, onClose]);
|
||||
}, [element, dataSource, chartConfig, customTitle, showHeader, onSave, onClose]);
|
||||
|
||||
// 모달이 열려있지 않으면 렌더링하지 않음
|
||||
if (!isOpen) return null;
|
||||
|
||||
// 시계, 달력, 기사관리 위젯은 자체 설정 UI를 가지고 있으므로 모달 표시하지 않음
|
||||
if (
|
||||
element.type === "widget" &&
|
||||
(element.subtype === "clock" || element.subtype === "calendar" || element.subtype === "driver-management")
|
||||
) {
|
||||
// 시계, 달력, To-Do 위젯은 헤더 설정만 가능
|
||||
const isHeaderOnlyWidget = element.type === "widget" && (element.subtype === "clock" || element.subtype === "calendar" || element.subtype === "todo");
|
||||
|
||||
// 기사관리 위젯은 자체 설정 UI를 가지고 있으므로 모달 표시하지 않음
|
||||
if (element.type === "widget" && element.subtype === "driver-management") {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -153,7 +155,8 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
|
|||
// customTitle이 변경되었는지 확인
|
||||
const isTitleChanged = customTitle.trim() !== (element.customTitle || "");
|
||||
|
||||
const canSave = isTitleChanged || // 제목만 변경해도 저장 가능
|
||||
const canSave =
|
||||
isTitleChanged || // 제목만 변경해도 저장 가능
|
||||
(isSimpleWidget
|
||||
? // 간단한 위젯: 2단계에서 쿼리 테스트 후 저장 가능
|
||||
currentStep === 2 && queryResult && queryResult.rows.length > 0
|
||||
|
|
@ -204,24 +207,38 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
|
|||
|
||||
{/* 커스텀 제목 입력 */}
|
||||
<div className="mt-4">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
위젯 제목 (선택사항)
|
||||
</label>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-700">위젯 제목 (선택사항)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={customTitle}
|
||||
onChange={(e) => setCustomTitle(e.target.value)}
|
||||
placeholder={`예: 정비 일정 목록, 창고 위치 현황 등 (비워두면 자동 생성)`}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
onKeyDown={(e) => {
|
||||
// 모든 키보드 이벤트를 input 필드 내부에서만 처리
|
||||
e.stopPropagation();
|
||||
}}
|
||||
placeholder="예: 정비 일정 목록, 창고 위치 현황 등 (비워두면 자동 생성)"
|
||||
className="focus:border-primary focus:ring-primary w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:ring-1 focus:outline-none"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
💡 비워두면 테이블명으로 자동 생성됩니다 (예: "maintenance_schedules 목록")
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-gray-500">비워두면 테이블명으로 자동 생성됩니다 (예: "maintenance_schedules 목록")</p>
|
||||
</div>
|
||||
|
||||
{/* 헤더 표시 옵션 */}
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="showHeader"
|
||||
checked={showHeader}
|
||||
onChange={(e) => setShowHeader(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary"
|
||||
/>
|
||||
<label htmlFor="showHeader" className="text-sm font-medium text-gray-700">
|
||||
위젯 헤더 표시 (제목 + 새로고침 버튼)
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 진행 상황 표시 - 간단한 위젯은 표시 안 함 */}
|
||||
{!isSimpleWidget && (
|
||||
{/* 진행 상황 표시 - 간단한 위젯과 헤더 전용 위젯은 표시 안 함 */}
|
||||
{!isSimpleWidget && !isHeaderOnlyWidget && (
|
||||
<div className="border-b bg-gray-50 px-6 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-sm font-medium text-gray-700">
|
||||
|
|
@ -232,12 +249,13 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
|
|||
)}
|
||||
|
||||
{/* 단계별 내용 */}
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
{currentStep === 1 && (
|
||||
<DataSourceSelector dataSource={dataSource} onTypeChange={handleDataSourceTypeChange} />
|
||||
)}
|
||||
{!isHeaderOnlyWidget && (
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
{currentStep === 1 && (
|
||||
<DataSourceSelector dataSource={dataSource} onTypeChange={handleDataSourceTypeChange} />
|
||||
)}
|
||||
|
||||
{currentStep === 2 && (
|
||||
{currentStep === 2 && (
|
||||
<div className={`grid ${isSimpleWidget ? "grid-cols-1" : "grid-cols-2"} gap-6`}>
|
||||
{/* 왼쪽: 데이터 설정 */}
|
||||
<div className="space-y-6">
|
||||
|
|
@ -293,15 +311,16 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
|
|||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 모달 푸터 */}
|
||||
<div className="flex items-center justify-between border-t bg-gray-50 p-6">
|
||||
<div>{queryResult && <Badge variant="default">{queryResult.rows.length}개 데이터 로드됨</Badge>}</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
{!isSimpleWidget && currentStep > 1 && (
|
||||
{!isSimpleWidget && !isHeaderOnlyWidget && currentStep > 1 && (
|
||||
<Button variant="outline" onClick={handlePrev}>
|
||||
<ChevronLeft className="mr-2 h-4 w-4" />
|
||||
이전
|
||||
|
|
@ -310,14 +329,20 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
|
|||
<Button variant="outline" onClick={onClose}>
|
||||
취소
|
||||
</Button>
|
||||
{currentStep === 1 ? (
|
||||
// 1단계: 다음 버튼 (모든 타입 공통)
|
||||
{isHeaderOnlyWidget ? (
|
||||
// 헤더 전용 위젯: 바로 저장
|
||||
<Button onClick={handleSave}>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
저장
|
||||
</Button>
|
||||
) : currentStep === 1 ? (
|
||||
// 1단계: 다음 버튼
|
||||
<Button onClick={handleNext}>
|
||||
다음
|
||||
<ChevronRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
) : (
|
||||
// 2단계: 저장 버튼 (모든 타입 공통)
|
||||
// 2단계: 저장 버튼
|
||||
<Button onClick={handleSave} disabled={!canSave}>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
저장
|
||||
|
|
|
|||
|
|
@ -0,0 +1,210 @@
|
|||
"use client";
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { toast } from "sonner";
|
||||
import { menuApi, MenuItem } from "@/lib/api/menu";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
interface MenuAssignmentModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onConfirm: (assignToMenu: boolean, menuId?: string, menuType?: "0" | "1") => void;
|
||||
dashboardId: string;
|
||||
dashboardTitle: string;
|
||||
}
|
||||
|
||||
export const MenuAssignmentModal: React.FC<MenuAssignmentModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onConfirm,
|
||||
dashboardId,
|
||||
dashboardTitle,
|
||||
}) => {
|
||||
const [assignToMenu, setAssignToMenu] = useState<boolean>(false);
|
||||
const [selectedMenuId, setSelectedMenuId] = useState<string>("");
|
||||
const [selectedMenuType, setSelectedMenuType] = useState<"0" | "1">("0");
|
||||
const [adminMenus, setAdminMenus] = useState<MenuItem[]>([]);
|
||||
const [userMenus, setUserMenus] = useState<MenuItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
// 메뉴 목록 로드
|
||||
useEffect(() => {
|
||||
if (isOpen && assignToMenu) {
|
||||
loadMenus();
|
||||
}
|
||||
}, [isOpen, assignToMenu]);
|
||||
|
||||
const loadMenus = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const [adminResponse, userResponse] = await Promise.all([
|
||||
menuApi.getAdminMenus(), // 관리자 메뉴
|
||||
menuApi.getUserMenus(), // 사용자 메뉴
|
||||
]);
|
||||
|
||||
if (adminResponse.success) {
|
||||
setAdminMenus(adminResponse.data || []);
|
||||
}
|
||||
if (userResponse.success) {
|
||||
setUserMenus(userResponse.data || []);
|
||||
}
|
||||
} catch (error) {
|
||||
// console.error("메뉴 목록 로드 실패:", error);
|
||||
toast.error("메뉴 목록을 불러오는데 실패했습니다.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 메뉴 트리를 평탄화하여 Select 옵션으로 변환
|
||||
const flattenMenus = (menus: MenuItem[], level: number = 0): Array<{ id: string; name: string; level: number }> => {
|
||||
const result: Array<{ id: string; name: string; level: number }> = [];
|
||||
|
||||
menus.forEach((menu) => {
|
||||
const menuId = menu.objid || menu.OBJID || "";
|
||||
const menuName = menu.menu_name_kor || menu.MENU_NAME_KOR || "";
|
||||
const parentId = menu.parent_obj_id || menu.PARENT_OBJ_ID || "0";
|
||||
|
||||
// 메뉴 이름이 있고, 최상위가 아닌 경우에만 추가
|
||||
if (menuName && parentId !== "0") {
|
||||
result.push({
|
||||
id: menuId,
|
||||
name: " ".repeat(level) + menuName,
|
||||
level,
|
||||
});
|
||||
|
||||
// 하위 메뉴가 있으면 재귀 호출
|
||||
const children = menus.filter((m) => (m.parent_obj_id || m.PARENT_OBJ_ID) === menuId);
|
||||
if (children.length > 0) {
|
||||
result.push(...flattenMenus(children, level + 1));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const currentMenus = selectedMenuType === "0" ? adminMenus : userMenus;
|
||||
const flatMenus = flattenMenus(currentMenus);
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (assignToMenu && !selectedMenuId) {
|
||||
toast.error("메뉴를 선택해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
onConfirm(assignToMenu, selectedMenuId, selectedMenuType);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setAssignToMenu(false);
|
||||
setSelectedMenuId("");
|
||||
setSelectedMenuType("0");
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleClose}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>대시보드 저장 완료</DialogTitle>
|
||||
<DialogDescription>'{dashboardTitle}' 대시보드가 저장되었습니다.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-3">
|
||||
<Label>이 대시보드를 메뉴에 할당하시겠습니까?</Label>
|
||||
<RadioGroup
|
||||
value={assignToMenu ? "yes" : "no"}
|
||||
onValueChange={(value) => setAssignToMenu(value === "yes")}
|
||||
className="flex space-x-4"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="yes" id="yes" />
|
||||
<Label htmlFor="yes" className="cursor-pointer font-normal">
|
||||
예, 메뉴에 할당
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="no" id="no" />
|
||||
<Label htmlFor="no" className="cursor-pointer font-normal">
|
||||
아니오, 나중에
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
{assignToMenu && (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label>메뉴 타입</Label>
|
||||
<RadioGroup
|
||||
value={selectedMenuType}
|
||||
onValueChange={(value) => {
|
||||
setSelectedMenuType(value as "0" | "1");
|
||||
setSelectedMenuId(""); // 메뉴 타입 변경 시 선택 초기화
|
||||
}}
|
||||
className="flex space-x-4"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="0" id="admin" />
|
||||
<Label htmlFor="admin" className="cursor-pointer font-normal">
|
||||
관리자 메뉴
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="1" id="user" />
|
||||
<Label htmlFor="user" className="cursor-pointer font-normal">
|
||||
사용자 메뉴
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>할당할 메뉴 선택</Label>
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-gray-400" />
|
||||
</div>
|
||||
) : (
|
||||
<Select value={selectedMenuId} onValueChange={setSelectedMenuId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="메뉴를 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="max-h-[300px]">
|
||||
{flatMenus.map((menu) => (
|
||||
<SelectItem key={menu.id} value={menu.id}>
|
||||
{menu.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleConfirm}>{assignToMenu ? "메뉴에 할당하고 완료" : "완료"}</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
|
@ -35,9 +35,9 @@ export function QueryEditor({ dataSource, onDataSourceChange, onQueryTest }: Que
|
|||
|
||||
// 쿼리 실행
|
||||
const executeQuery = useCallback(async () => {
|
||||
console.log("🚀 executeQuery 호출됨!");
|
||||
console.log("📝 현재 쿼리:", query);
|
||||
console.log("✅ query.trim():", query.trim());
|
||||
// console.log("🚀 executeQuery 호출됨!");
|
||||
// console.log("📝 현재 쿼리:", query);
|
||||
// console.log("✅ query.trim():", query.trim());
|
||||
|
||||
if (!query.trim()) {
|
||||
setError("쿼리를 입력해주세요.");
|
||||
|
|
@ -47,13 +47,13 @@ export function QueryEditor({ dataSource, onDataSourceChange, onQueryTest }: Que
|
|||
// 외부 DB인 경우 커넥션 ID 확인
|
||||
if (dataSource?.connectionType === "external" && !dataSource?.externalConnectionId) {
|
||||
setError("외부 DB 커넥션을 선택해주세요.");
|
||||
console.log("❌ 쿼리가 비어있음!");
|
||||
// console.log("❌ 쿼리가 비어있음!");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsExecuting(true);
|
||||
setError(null);
|
||||
console.log("🔄 쿼리 실행 시작...");
|
||||
// console.log("🔄 쿼리 실행 시작...");
|
||||
|
||||
try {
|
||||
let apiResult: { columns: string[]; rows: any[]; rowCount: number };
|
||||
|
|
@ -247,7 +247,7 @@ ORDER BY Q4 DESC;`,
|
|||
<SelectTrigger className="w-32">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectContent className="z-[99999]">
|
||||
<SelectItem value="0">수동</SelectItem>
|
||||
<SelectItem value="10000">10초</SelectItem>
|
||||
<SelectItem value="30000">30초</SelectItem>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,122 @@
|
|||
"use client";
|
||||
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Monitor } from "lucide-react";
|
||||
|
||||
export type Resolution = "hd" | "fhd" | "qhd" | "uhd";
|
||||
|
||||
export interface ResolutionConfig {
|
||||
width: number;
|
||||
height: number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export const RESOLUTIONS: Record<Resolution, ResolutionConfig> = {
|
||||
hd: {
|
||||
width: 1280 - 360,
|
||||
height: 720 - 312,
|
||||
label: "HD (1280x720)",
|
||||
},
|
||||
fhd: {
|
||||
width: 1920 - 360,
|
||||
height: 1080 - 312,
|
||||
label: "Full HD (1920x1080)",
|
||||
},
|
||||
qhd: {
|
||||
width: 2560 - 360,
|
||||
height: 1440 - 312,
|
||||
label: "QHD (2560x1440)",
|
||||
},
|
||||
uhd: {
|
||||
width: 3840 - 360,
|
||||
height: 2160 - 312,
|
||||
label: "4K UHD (3840x2160)",
|
||||
},
|
||||
};
|
||||
|
||||
interface ResolutionSelectorProps {
|
||||
value: Resolution;
|
||||
onChange: (resolution: Resolution) => void;
|
||||
currentScreenResolution?: Resolution;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 화면 해상도 감지
|
||||
*/
|
||||
export function detectScreenResolution(): Resolution {
|
||||
if (typeof window === "undefined") return "fhd";
|
||||
|
||||
const width = window.screen.width;
|
||||
const height = window.screen.height;
|
||||
|
||||
// 화면 해상도에 따라 적절한 캔버스 해상도 반환
|
||||
if (width >= 3840 || height >= 2160) return "uhd";
|
||||
if (width >= 2560 || height >= 1440) return "qhd";
|
||||
if (width >= 1920 || height >= 1080) return "fhd";
|
||||
return "hd";
|
||||
}
|
||||
|
||||
/**
|
||||
* 해상도 선택 컴포넌트
|
||||
* - HD, Full HD, QHD, 4K UHD 지원
|
||||
* - 12칸 그리드 유지, 셀 크기만 변경
|
||||
* - 현재 화면 해상도 감지 및 경고 표시
|
||||
*/
|
||||
export function ResolutionSelector({ value, onChange, currentScreenResolution }: ResolutionSelectorProps) {
|
||||
const currentConfig = RESOLUTIONS[value];
|
||||
const screenConfig = currentScreenResolution ? RESOLUTIONS[currentScreenResolution] : null;
|
||||
|
||||
// 현재 선택된 해상도가 화면보다 큰지 확인
|
||||
const isTooLarge =
|
||||
screenConfig &&
|
||||
(currentConfig.width > screenConfig.width + 360 || currentConfig.height > screenConfig.height + 312);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Monitor className="h-4 w-4 text-gray-500" />
|
||||
<Select value={value} onValueChange={(v) => onChange(v as Resolution)}>
|
||||
<SelectTrigger className={`w-[180px] ${isTooLarge ? "border-orange-500" : ""}`}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="z-[99999]">
|
||||
<SelectGroup>
|
||||
<SelectLabel>캔버스 해상도</SelectLabel>
|
||||
<SelectItem value="hd">
|
||||
<div className="flex items-center gap-2">
|
||||
<span>HD</span>
|
||||
<span className="text-xs text-gray-500">1280x720</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="fhd">
|
||||
<div className="flex items-center gap-2">
|
||||
<span>Full HD</span>
|
||||
<span className="text-xs text-gray-500">1920x1080</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="qhd">
|
||||
<div className="flex items-center gap-2">
|
||||
<span>QHD</span>
|
||||
<span className="text-xs text-gray-500">2560x1440</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="uhd">
|
||||
<div className="flex items-center gap-2">
|
||||
<span>4K UHD</span>
|
||||
<span className="text-xs text-gray-500">3840x2160</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{isTooLarge && <span className="text-xs text-orange-600">⚠️ 현재 화면보다 큽니다</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,162 @@
|
|||
/**
|
||||
* 대시보드 위젯 충돌 감지 및 자동 재배치 유틸리티
|
||||
*/
|
||||
|
||||
import { DashboardElement } from "./types";
|
||||
|
||||
export interface Rectangle {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 두 사각형이 겹치는지 확인 (여유있는 충돌 감지)
|
||||
* @param rect1 첫 번째 사각형
|
||||
* @param rect2 두 번째 사각형
|
||||
* @param cellSize 한 그리드 칸의 크기 (기본: 130px)
|
||||
*/
|
||||
export function isColliding(rect1: Rectangle, rect2: Rectangle, cellSize: number = 130): boolean {
|
||||
// 겹친 영역 계산
|
||||
const overlapX = Math.max(
|
||||
0,
|
||||
Math.min(rect1.x + rect1.width, rect2.x + rect2.width) - Math.max(rect1.x, rect2.x)
|
||||
);
|
||||
const overlapY = Math.max(
|
||||
0,
|
||||
Math.min(rect1.y + rect1.height, rect2.y + rect2.height) - Math.max(rect1.y, rect2.y)
|
||||
);
|
||||
|
||||
// 큰 그리드의 절반(cellSize/2 ≈ 65px) 이상 겹쳐야 충돌로 간주
|
||||
const collisionThreshold = Math.floor(cellSize / 2);
|
||||
return overlapX >= collisionThreshold && overlapY >= collisionThreshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 위젯과 충돌하는 다른 위젯들을 찾기
|
||||
*/
|
||||
export function findCollisions(
|
||||
element: DashboardElement,
|
||||
allElements: DashboardElement[],
|
||||
cellSize: number = 130,
|
||||
excludeId?: string
|
||||
): DashboardElement[] {
|
||||
const elementRect: Rectangle = {
|
||||
x: element.position.x,
|
||||
y: element.position.y,
|
||||
width: element.size.width,
|
||||
height: element.size.height,
|
||||
};
|
||||
|
||||
return allElements.filter((other) => {
|
||||
if (other.id === element.id || other.id === excludeId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const otherRect: Rectangle = {
|
||||
x: other.position.x,
|
||||
y: other.position.y,
|
||||
width: other.size.width,
|
||||
height: other.size.height,
|
||||
};
|
||||
|
||||
return isColliding(elementRect, otherRect, cellSize);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 충돌을 해결하기 위해 위젯을 아래로 이동
|
||||
*/
|
||||
export function resolveCollisionVertically(
|
||||
movingElement: DashboardElement,
|
||||
collidingElement: DashboardElement,
|
||||
gridSize: number = 10
|
||||
): { x: number; y: number } {
|
||||
// 충돌하는 위젯 아래로 이동
|
||||
const newY = collidingElement.position.y + collidingElement.size.height + gridSize;
|
||||
|
||||
return {
|
||||
x: collidingElement.position.x,
|
||||
y: Math.round(newY / gridSize) * gridSize, // 그리드에 스냅
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 여러 위젯의 충돌을 재귀적으로 해결
|
||||
*/
|
||||
export function resolveAllCollisions(
|
||||
elements: DashboardElement[],
|
||||
movedElementId: string,
|
||||
subGridSize: number = 10,
|
||||
canvasWidth: number = 1560,
|
||||
cellSize: number = 130,
|
||||
maxIterations: number = 50
|
||||
): DashboardElement[] {
|
||||
let result = [...elements];
|
||||
let iterations = 0;
|
||||
|
||||
// 이동한 위젯부터 시작
|
||||
const movedIndex = result.findIndex((el) => el.id === movedElementId);
|
||||
if (movedIndex === -1) return result;
|
||||
|
||||
// Y 좌표로 정렬 (위에서 아래로 처리)
|
||||
const sortedIndices = result
|
||||
.map((el, idx) => ({ el, idx }))
|
||||
.sort((a, b) => a.el.position.y - b.el.position.y)
|
||||
.map((item) => item.idx);
|
||||
|
||||
while (iterations < maxIterations) {
|
||||
let hasCollision = false;
|
||||
|
||||
for (const idx of sortedIndices) {
|
||||
const element = result[idx];
|
||||
const collisions = findCollisions(element, result, cellSize);
|
||||
|
||||
if (collisions.length > 0) {
|
||||
hasCollision = true;
|
||||
|
||||
// 첫 번째 충돌만 처리 (가장 위에 있는 것)
|
||||
const collision = collisions.sort((a, b) => a.position.y - b.position.y)[0];
|
||||
|
||||
// 충돌하는 위젯을 아래로 이동
|
||||
const collisionIdx = result.findIndex((el) => el.id === collision.id);
|
||||
if (collisionIdx !== -1) {
|
||||
const newY = element.position.y + element.size.height + subGridSize;
|
||||
|
||||
result[collisionIdx] = {
|
||||
...result[collisionIdx],
|
||||
position: {
|
||||
...result[collisionIdx].position,
|
||||
y: Math.round(newY / subGridSize) * subGridSize,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasCollision) break;
|
||||
iterations++;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 위젯이 캔버스 경계를 벗어나지 않도록 제한
|
||||
*/
|
||||
export function constrainToCanvas(
|
||||
element: DashboardElement,
|
||||
canvasWidth: number,
|
||||
canvasHeight: number,
|
||||
gridSize: number = 10
|
||||
): { x: number; y: number } {
|
||||
const maxX = canvasWidth - element.size.width;
|
||||
const maxY = canvasHeight - element.size.height;
|
||||
|
||||
return {
|
||||
x: Math.max(0, Math.min(Math.round(element.position.x / gridSize) * gridSize, maxX)),
|
||||
y: Math.max(0, Math.min(Math.round(element.position.y / gridSize) * gridSize, maxY)),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -5,18 +5,46 @@
|
|||
* - 스냅 기능
|
||||
*/
|
||||
|
||||
// 그리드 설정 (고정 크기)
|
||||
// 기본 그리드 설정 (FHD 기준)
|
||||
export const GRID_CONFIG = {
|
||||
COLUMNS: 12,
|
||||
CELL_SIZE: 132, // 고정 셀 크기
|
||||
GAP: 8, // 셀 간격
|
||||
SNAP_THRESHOLD: 15, // 스냅 임계값 (px)
|
||||
COLUMNS: 12, // 모든 해상도에서 12칸 고정
|
||||
GAP: 5, // 셀 간격 고정
|
||||
SNAP_THRESHOLD: 10, // 스냅 임계값 (px)
|
||||
ELEMENT_PADDING: 4, // 요소 주위 여백 (px)
|
||||
CANVAS_WIDTH: 1682, // 고정 캔버스 너비 (실제 측정값)
|
||||
// 계산식: (132 + 8) × 12 - 8 = 1672px (그리드)
|
||||
// 추가 여백 10px 포함 = 1682px
|
||||
SUB_GRID_DIVISIONS: 5, // 각 그리드 칸을 5x5로 세분화 (세밀한 조정용)
|
||||
// CELL_SIZE와 CANVAS_WIDTH는 해상도에 따라 동적 계산
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 캔버스 너비에 맞춰 셀 크기 계산
|
||||
* 공식: (CELL_SIZE + GAP) * 12 - GAP = canvasWidth
|
||||
* CELL_SIZE = (canvasWidth + GAP) / 12 - GAP
|
||||
*/
|
||||
export function calculateCellSize(canvasWidth: number): number {
|
||||
return Math.floor((canvasWidth + GRID_CONFIG.GAP) / GRID_CONFIG.COLUMNS) - GRID_CONFIG.GAP;
|
||||
}
|
||||
|
||||
/**
|
||||
* 서브 그리드 크기 계산 (세밀한 조정용)
|
||||
*/
|
||||
export function calculateSubGridSize(cellSize: number): number {
|
||||
return Math.floor(cellSize / GRID_CONFIG.SUB_GRID_DIVISIONS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 해상도별 그리드 설정 계산
|
||||
*/
|
||||
export function calculateGridConfig(canvasWidth: number) {
|
||||
const cellSize = calculateCellSize(canvasWidth);
|
||||
const subGridSize = calculateSubGridSize(cellSize);
|
||||
return {
|
||||
...GRID_CONFIG,
|
||||
CELL_SIZE: cellSize,
|
||||
SUB_GRID_SIZE: subGridSize,
|
||||
CANVAS_WIDTH: canvasWidth,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 실제 그리드 셀 크기 계산 (gap 포함)
|
||||
*/
|
||||
|
|
@ -33,15 +61,18 @@ export const getCanvasWidth = () => {
|
|||
};
|
||||
|
||||
/**
|
||||
* 좌표를 가장 가까운 그리드 포인트로 스냅 (여백 포함)
|
||||
* 좌표를 서브 그리드에 스냅 (세밀한 조정 가능)
|
||||
* @param value - 스냅할 좌표값
|
||||
* @param cellSize - 셀 크기 (선택사항, 기본값은 GRID_CONFIG.CELL_SIZE)
|
||||
* @returns 스냅된 좌표값 (여백 포함)
|
||||
* @param subGridSize - 서브 그리드 크기 (선택사항, 기본값: cellSize/3 ≈ 43px)
|
||||
* @returns 스냅된 좌표값
|
||||
*/
|
||||
export const snapToGrid = (value: number, cellSize: number = GRID_CONFIG.CELL_SIZE): number => {
|
||||
const cellWithGap = cellSize + GRID_CONFIG.GAP;
|
||||
const gridIndex = Math.round(value / cellWithGap);
|
||||
return gridIndex * cellWithGap + GRID_CONFIG.ELEMENT_PADDING;
|
||||
export const snapToGrid = (value: number, subGridSize?: number): number => {
|
||||
// 서브 그리드 크기가 지정되지 않으면 기본 그리드 크기의 1/3 사용 (3x3 서브그리드)
|
||||
const snapSize = subGridSize ?? Math.floor(GRID_CONFIG.CELL_SIZE / 3);
|
||||
|
||||
// 서브 그리드 단위로 스냅
|
||||
const gridIndex = Math.round(value / snapSize);
|
||||
return gridIndex * snapSize;
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -35,7 +35,8 @@ export type ElementSubtype =
|
|||
| "booking-alert"
|
||||
| "maintenance"
|
||||
| "document"
|
||||
| "list"; // 위젯 타입
|
||||
| "list"
|
||||
| "yard-management-3d"; // 야드 관리 3D 위젯
|
||||
|
||||
export interface Position {
|
||||
x: number;
|
||||
|
|
@ -55,6 +56,7 @@ export interface DashboardElement {
|
|||
size: Size;
|
||||
title: string;
|
||||
customTitle?: string; // 사용자 정의 제목 (옵션)
|
||||
showHeader?: boolean; // 헤더 표시 여부 (기본값: true)
|
||||
content: string;
|
||||
dataSource?: ChartDataSource; // 데이터 소스 설정
|
||||
chartConfig?: ChartConfig; // 차트 설정
|
||||
|
|
@ -62,6 +64,7 @@ export interface DashboardElement {
|
|||
calendarConfig?: CalendarConfig; // 달력 설정
|
||||
driverManagementConfig?: DriverManagementConfig; // 기사 관리 설정
|
||||
listConfig?: ListWidgetConfig; // 리스트 위젯 설정
|
||||
yardConfig?: YardManagementConfig; // 야드 관리 3D 설정
|
||||
}
|
||||
|
||||
export interface DragData {
|
||||
|
|
@ -270,3 +273,9 @@ export interface ListColumn {
|
|||
align?: "left" | "center" | "right"; // 정렬
|
||||
visible?: boolean; // 표시 여부 (기본: true)
|
||||
}
|
||||
|
||||
// 야드 관리 3D 설정
|
||||
export interface YardManagementConfig {
|
||||
layoutId: number; // 선택된 야드 레이아웃 ID
|
||||
layoutName?: string; // 레이아웃 이름 (표시용)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import { generateCalendarDays, getMonthName, navigateMonth } from "./calendarUti
|
|||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Settings, ChevronLeft, ChevronRight, Calendar } from "lucide-react";
|
||||
import { useDashboard } from "@/contexts/DashboardContext";
|
||||
|
||||
interface CalendarWidgetProps {
|
||||
element: DashboardElement;
|
||||
|
|
@ -21,12 +22,20 @@ interface CalendarWidgetProps {
|
|||
* - 내장 설정 UI
|
||||
*/
|
||||
export function CalendarWidget({ element, onConfigUpdate }: CalendarWidgetProps) {
|
||||
// Context에서 선택된 날짜 관리
|
||||
const { selectedDate, setSelectedDate } = useDashboard();
|
||||
|
||||
// 현재 표시 중인 년/월
|
||||
const today = new Date();
|
||||
const [currentYear, setCurrentYear] = useState(today.getFullYear());
|
||||
const [currentMonth, setCurrentMonth] = useState(today.getMonth());
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
|
||||
// 날짜 클릭 핸들러
|
||||
const handleDateClick = (date: Date) => {
|
||||
setSelectedDate(date);
|
||||
};
|
||||
|
||||
// 기본 설정값
|
||||
const config = element.calendarConfig || {
|
||||
view: "month",
|
||||
|
|
@ -98,7 +107,15 @@ export function CalendarWidget({ element, onConfigUpdate }: CalendarWidgetProps)
|
|||
|
||||
{/* 달력 콘텐츠 */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{config.view === "month" && <MonthView days={calendarDays} config={config} isCompact={isCompact} />}
|
||||
{config.view === "month" && (
|
||||
<MonthView
|
||||
days={calendarDays}
|
||||
config={config}
|
||||
isCompact={isCompact}
|
||||
selectedDate={selectedDate}
|
||||
onDateClick={handleDateClick}
|
||||
/>
|
||||
)}
|
||||
{/* 추후 WeekView, DayView 추가 가능 */}
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -219,8 +219,9 @@ export function ListWidget({ element, onConfigUpdate }: ListWidgetProps) {
|
|||
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col p-4">
|
||||
{/* 제목 - 항상 표시 */}
|
||||
<div className="mb-4">
|
||||
<h3 className="text-sm font-semibold text-gray-700">{element.title}</h3>
|
||||
<h3 className="text-sm font-semibold text-gray-700">{element.customTitle || element.title}</h3>
|
||||
</div>
|
||||
|
||||
{/* 테이블 뷰 */}
|
||||
|
|
|
|||
|
|
@ -131,7 +131,7 @@ export function ListWidgetConfigModal({ isOpen, element, onClose, onSave }: List
|
|||
// 저장
|
||||
const handleSave = () => {
|
||||
onSave({
|
||||
title,
|
||||
customTitle: title,
|
||||
dataSource,
|
||||
listConfig,
|
||||
});
|
||||
|
|
@ -166,10 +166,19 @@ export function ListWidgetConfigModal({ isOpen, element, onClose, onSave }: List
|
|||
id="list-title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
// 모든 키보드 이벤트를 input 필드 내부에서만 처리
|
||||
e.stopPropagation();
|
||||
}}
|
||||
placeholder="예: 사용자 목록"
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 참고: 리스트 위젯은 제목이 항상 표시됩니다 */}
|
||||
<div className="rounded bg-blue-50 p-2 text-xs text-blue-700">
|
||||
💡 리스트 위젯은 제목이 항상 표시됩니다
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 진행 상태 표시 */}
|
||||
|
|
|
|||
|
|
@ -7,12 +7,14 @@ interface MonthViewProps {
|
|||
days: CalendarDay[];
|
||||
config: CalendarConfig;
|
||||
isCompact?: boolean; // 작은 크기 (2x2, 3x3)
|
||||
selectedDate?: Date | null; // 선택된 날짜
|
||||
onDateClick?: (date: Date) => void; // 날짜 클릭 핸들러
|
||||
}
|
||||
|
||||
/**
|
||||
* 월간 달력 뷰 컴포넌트
|
||||
*/
|
||||
export function MonthView({ days, config, isCompact = false }: MonthViewProps) {
|
||||
export function MonthView({ days, config, isCompact = false, selectedDate, onDateClick }: MonthViewProps) {
|
||||
const weekDayNames = getWeekDayNames(config.startWeekOn);
|
||||
|
||||
// 테마별 스타일
|
||||
|
|
@ -43,10 +45,27 @@ export function MonthView({ days, config, isCompact = false }: MonthViewProps) {
|
|||
|
||||
const themeStyles = getThemeStyles();
|
||||
|
||||
// 날짜가 선택된 날짜인지 확인
|
||||
const isSelected = (day: CalendarDay) => {
|
||||
if (!selectedDate || !day.isCurrentMonth) return false;
|
||||
return (
|
||||
selectedDate.getFullYear() === day.date.getFullYear() &&
|
||||
selectedDate.getMonth() === day.date.getMonth() &&
|
||||
selectedDate.getDate() === day.date.getDate()
|
||||
);
|
||||
};
|
||||
|
||||
// 날짜 클릭 핸들러
|
||||
const handleDayClick = (day: CalendarDay) => {
|
||||
if (!day.isCurrentMonth || !onDateClick) return;
|
||||
onDateClick(day.date);
|
||||
};
|
||||
|
||||
// 날짜 셀 스타일 클래스
|
||||
const getDayCellClass = (day: CalendarDay) => {
|
||||
const baseClass = "flex aspect-square items-center justify-center rounded-lg transition-colors";
|
||||
const sizeClass = isCompact ? "text-xs" : "text-sm";
|
||||
const cursorClass = day.isCurrentMonth ? "cursor-pointer" : "cursor-default";
|
||||
|
||||
let colorClass = "text-gray-700";
|
||||
|
||||
|
|
@ -54,6 +73,10 @@ export function MonthView({ days, config, isCompact = false }: MonthViewProps) {
|
|||
if (!day.isCurrentMonth) {
|
||||
colorClass = "text-gray-300";
|
||||
}
|
||||
// 선택된 날짜
|
||||
else if (isSelected(day)) {
|
||||
colorClass = "text-white font-bold";
|
||||
}
|
||||
// 오늘
|
||||
else if (config.highlightToday && day.isToday) {
|
||||
colorClass = "text-white font-bold";
|
||||
|
|
@ -67,9 +90,16 @@ export function MonthView({ days, config, isCompact = false }: MonthViewProps) {
|
|||
colorClass = "text-red-600";
|
||||
}
|
||||
|
||||
const bgClass = config.highlightToday && day.isToday ? "" : "hover:bg-gray-100";
|
||||
let bgClass = "";
|
||||
if (isSelected(day)) {
|
||||
bgClass = ""; // 선택된 날짜는 배경색이 style로 적용됨
|
||||
} else if (config.highlightToday && day.isToday) {
|
||||
bgClass = "";
|
||||
} else {
|
||||
bgClass = "hover:bg-gray-100";
|
||||
}
|
||||
|
||||
return `${baseClass} ${sizeClass} ${colorClass} ${bgClass}`;
|
||||
return `${baseClass} ${sizeClass} ${colorClass} ${bgClass} ${cursorClass}`;
|
||||
};
|
||||
|
||||
return (
|
||||
|
|
@ -97,9 +127,13 @@ export function MonthView({ days, config, isCompact = false }: MonthViewProps) {
|
|||
<div
|
||||
key={index}
|
||||
className={getDayCellClass(day)}
|
||||
onClick={() => handleDayClick(day)}
|
||||
style={{
|
||||
backgroundColor:
|
||||
config.highlightToday && day.isToday ? themeStyles.todayBg : undefined,
|
||||
backgroundColor: isSelected(day)
|
||||
? "#10b981" // 선택된 날짜는 초록색
|
||||
: config.highlightToday && day.isToday
|
||||
? themeStyles.todayBg
|
||||
: undefined,
|
||||
color:
|
||||
config.showHolidays && day.isHoliday && day.isCurrentMonth
|
||||
? themeStyles.holidayText
|
||||
|
|
|
|||
|
|
@ -0,0 +1,336 @@
|
|||
"use client";
|
||||
|
||||
import React, { useState, useCallback, useEffect } from "react";
|
||||
import { DashboardElement, ChartDataSource, QueryResult } from "../types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ChevronLeft, ChevronRight, Save, X } from "lucide-react";
|
||||
import { DataSourceSelector } from "../data-sources/DataSourceSelector";
|
||||
import { DatabaseConfig } from "../data-sources/DatabaseConfig";
|
||||
import { ApiConfig } from "../data-sources/ApiConfig";
|
||||
import { QueryEditor } from "../QueryEditor";
|
||||
|
||||
interface TodoWidgetConfigModalProps {
|
||||
isOpen: boolean;
|
||||
element: DashboardElement;
|
||||
onClose: () => void;
|
||||
onSave: (updates: Partial<DashboardElement>) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* To-Do 위젯 설정 모달
|
||||
* - 2단계 설정: 데이터 소스 → 쿼리 입력/테스트
|
||||
*/
|
||||
export function TodoWidgetConfigModal({ isOpen, element, onClose, onSave }: TodoWidgetConfigModalProps) {
|
||||
const [currentStep, setCurrentStep] = useState<1 | 2>(1);
|
||||
const [title, setTitle] = useState(element.title || "✅ To-Do / 긴급 지시");
|
||||
const [dataSource, setDataSource] = useState<ChartDataSource>(
|
||||
element.dataSource || { type: "database", connectionType: "current", refreshInterval: 0 },
|
||||
);
|
||||
const [queryResult, setQueryResult] = useState<QueryResult | null>(null);
|
||||
|
||||
// 모달 열릴 때 element에서 설정 로드
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setTitle(element.title || "✅ To-Do / 긴급 지시");
|
||||
if (element.dataSource) {
|
||||
setDataSource(element.dataSource);
|
||||
}
|
||||
setCurrentStep(1);
|
||||
}
|
||||
}, [isOpen, element.id]);
|
||||
|
||||
// 데이터 소스 타입 변경
|
||||
const handleDataSourceTypeChange = useCallback((type: "database" | "api") => {
|
||||
if (type === "database") {
|
||||
setDataSource((prev) => ({
|
||||
...prev,
|
||||
type: "database",
|
||||
connectionType: "current",
|
||||
}));
|
||||
} else {
|
||||
setDataSource((prev) => ({
|
||||
...prev,
|
||||
type: "api",
|
||||
method: "GET",
|
||||
}));
|
||||
}
|
||||
setQueryResult(null);
|
||||
}, []);
|
||||
|
||||
// 데이터 소스 업데이트
|
||||
const handleDataSourceUpdate = useCallback((updates: Partial<ChartDataSource>) => {
|
||||
setDataSource((prev) => ({ ...prev, ...updates }));
|
||||
}, []);
|
||||
|
||||
// 쿼리 실행 결과 처리
|
||||
const handleQueryTest = useCallback(
|
||||
(result: QueryResult) => {
|
||||
// console.log("🎯 TodoWidget - handleQueryTest 호출됨!");
|
||||
// console.log("📊 쿼리 결과:", result);
|
||||
// console.log("📝 rows 개수:", result.rows?.length);
|
||||
// console.log("❌ error:", result.error);
|
||||
setQueryResult(result);
|
||||
// console.log("✅ setQueryResult 호출 완료!");
|
||||
|
||||
// 강제 리렌더링 확인
|
||||
// setTimeout(() => {
|
||||
// console.log("🔄 1초 후 queryResult 상태:", result);
|
||||
// }, 1000);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// 저장
|
||||
const handleSave = useCallback(() => {
|
||||
if (!dataSource.query || !queryResult || queryResult.error) {
|
||||
alert("쿼리를 입력하고 테스트를 먼저 실행해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!queryResult.rows || queryResult.rows.length === 0) {
|
||||
alert("쿼리 결과가 없습니다. 데이터가 반환되는 쿼리를 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
onSave({
|
||||
title,
|
||||
dataSource,
|
||||
});
|
||||
|
||||
onClose();
|
||||
}, [title, dataSource, queryResult, onSave, onClose]);
|
||||
|
||||
// 다음 단계로
|
||||
const handleNext = useCallback(() => {
|
||||
if (currentStep === 1) {
|
||||
if (dataSource.type === "database") {
|
||||
if (!dataSource.connectionId && dataSource.connectionType === "external") {
|
||||
alert("외부 데이터베이스를 선택해주세요.");
|
||||
return;
|
||||
}
|
||||
} else if (dataSource.type === "api") {
|
||||
if (!dataSource.url) {
|
||||
alert("API URL을 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
setCurrentStep(2);
|
||||
}
|
||||
}, [currentStep, dataSource]);
|
||||
|
||||
// 이전 단계로
|
||||
const handlePrev = useCallback(() => {
|
||||
if (currentStep === 2) {
|
||||
setCurrentStep(1);
|
||||
}
|
||||
}, [currentStep]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50">
|
||||
<div className="relative flex h-[90vh] w-[90vw] max-w-6xl flex-col rounded-lg bg-white shadow-xl">
|
||||
{/* 헤더 */}
|
||||
<div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
|
||||
<div>
|
||||
<h2 className="text-xl font-bold text-gray-800">To-Do 위젯 설정</h2>
|
||||
<p className="mt-1 text-sm text-gray-500">
|
||||
데이터 소스와 쿼리를 설정하면 자동으로 To-Do 목록이 표시됩니다
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="rounded-lg p-2 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700"
|
||||
>
|
||||
<X className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 진행 상태 */}
|
||||
<div className="border-b border-gray-200 bg-gray-50 px-6 py-3">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className={`flex items-center gap-2 ${currentStep === 1 ? "text-primary" : "text-gray-400"}`}>
|
||||
<div
|
||||
className={`flex h-8 w-8 items-center justify-center rounded-full font-semibold ${
|
||||
currentStep === 1 ? "bg-primary text-white" : "bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
1
|
||||
</div>
|
||||
<span className="font-medium">데이터 소스 선택</span>
|
||||
</div>
|
||||
<ChevronRight className="h-4 w-4 text-gray-400" />
|
||||
<div className={`flex items-center gap-2 ${currentStep === 2 ? "text-primary" : "text-gray-400"}`}>
|
||||
<div
|
||||
className={`flex h-8 w-8 items-center justify-center rounded-full font-semibold ${
|
||||
currentStep === 2 ? "bg-primary text-white" : "bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
2
|
||||
</div>
|
||||
<span className="font-medium">쿼리 입력 및 테스트</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 본문 */}
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
{/* Step 1: 데이터 소스 선택 */}
|
||||
{currentStep === 1 && (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<Label className="text-base font-semibold">제목</Label>
|
||||
<Input
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="예: ✅ 오늘의 할 일"
|
||||
className="mt-2"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-base font-semibold">데이터 소스 타입</Label>
|
||||
<DataSourceSelector
|
||||
dataSource={dataSource}
|
||||
onTypeChange={handleDataSourceTypeChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{dataSource.type === "database" && (
|
||||
<DatabaseConfig dataSource={dataSource} onUpdate={handleDataSourceUpdate} />
|
||||
)}
|
||||
|
||||
{dataSource.type === "api" && <ApiConfig dataSource={dataSource} onUpdate={handleDataSourceUpdate} />}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Step 2: 쿼리 입력 및 테스트 */}
|
||||
{currentStep === 2 && (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<div className="mb-4 rounded-lg bg-blue-50 p-4">
|
||||
<h3 className="mb-2 font-semibold text-blue-900">💡 컬럼명 가이드</h3>
|
||||
<p className="mb-2 text-sm text-blue-700">
|
||||
쿼리 결과에 다음 컬럼명이 있으면 자동으로 To-Do 항목으로 변환됩니다:
|
||||
</p>
|
||||
<ul className="space-y-1 text-sm text-blue-600">
|
||||
<li>
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">id</code> - 고유 ID (없으면 자동 생성)
|
||||
</li>
|
||||
<li>
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">title</code>,{" "}
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">task</code>,{" "}
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">name</code> - 제목 (필수)
|
||||
</li>
|
||||
<li>
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">description</code>,{" "}
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">desc</code>,{" "}
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">content</code> - 상세 설명
|
||||
</li>
|
||||
<li>
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">priority</code> - 우선순위 (urgent, high,
|
||||
normal, low)
|
||||
</li>
|
||||
<li>
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">status</code> - 상태 (pending, in_progress,
|
||||
completed)
|
||||
</li>
|
||||
<li>
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">assigned_to</code>,{" "}
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">assignedTo</code>,{" "}
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">user</code> - 담당자
|
||||
</li>
|
||||
<li>
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">due_date</code>,{" "}
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">dueDate</code>,{" "}
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">deadline</code> - 마감일
|
||||
</li>
|
||||
<li>
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">is_urgent</code>,{" "}
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">isUrgent</code>,{" "}
|
||||
<code className="rounded bg-blue-100 px-1 py-0.5">urgent</code> - 긴급 여부
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<QueryEditor
|
||||
dataSource={dataSource}
|
||||
onDataSourceChange={handleDataSourceUpdate}
|
||||
onQueryTest={handleQueryTest}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 디버그: 항상 표시되는 테스트 메시지 */}
|
||||
<div className="mt-4 rounded-lg bg-yellow-50 border-2 border-yellow-500 p-4">
|
||||
<p className="text-sm font-bold text-yellow-900">
|
||||
🔍 디버그: queryResult 상태 = {queryResult ? "있음" : "없음"}
|
||||
</p>
|
||||
{queryResult && (
|
||||
<p className="text-xs text-yellow-700 mt-1">
|
||||
rows: {queryResult.rows?.length}개, error: {queryResult.error || "없음"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{queryResult && !queryResult.error && queryResult.rows && queryResult.rows.length > 0 && (
|
||||
<div className="mt-4 rounded-lg bg-green-50 border-2 border-green-500 p-4">
|
||||
<h3 className="mb-2 font-semibold text-green-900">✅ 쿼리 테스트 성공!</h3>
|
||||
<p className="text-sm text-green-700">
|
||||
총 <strong>{queryResult.rows.length}개</strong>의 To-Do 항목을 찾았습니다.
|
||||
</p>
|
||||
<div className="mt-3 rounded bg-white p-3">
|
||||
<p className="mb-2 text-xs font-semibold text-gray-600">첫 번째 데이터 미리보기:</p>
|
||||
<pre className="overflow-x-auto text-xs text-gray-700">
|
||||
{JSON.stringify(queryResult.rows[0], null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 하단 버튼 */}
|
||||
<div className="flex items-center justify-between border-t border-gray-200 px-6 py-4">
|
||||
<div>
|
||||
{currentStep > 1 && (
|
||||
<Button onClick={handlePrev} variant="outline">
|
||||
<ChevronLeft className="mr-1 h-4 w-4" />
|
||||
이전
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={onClose} variant="outline">
|
||||
취소
|
||||
</Button>
|
||||
|
||||
{currentStep < 2 ? (
|
||||
<Button onClick={handleNext}>
|
||||
다음
|
||||
<ChevronRight className="ml-1 h-4 w-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={(() => {
|
||||
const isDisabled = !queryResult || queryResult.error || !queryResult.rows || queryResult.rows.length === 0;
|
||||
// console.log("💾 저장 버튼 disabled:", isDisabled);
|
||||
// console.log("💾 queryResult:", queryResult);
|
||||
return isDisabled;
|
||||
})()}
|
||||
>
|
||||
<Save className="mr-1 h-4 w-4" />
|
||||
저장
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,198 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Plus, Check } from "lucide-react";
|
||||
import YardLayoutList from "./yard-3d/YardLayoutList";
|
||||
import YardLayoutCreateModal from "./yard-3d/YardLayoutCreateModal";
|
||||
import YardEditor from "./yard-3d/YardEditor";
|
||||
import Yard3DViewer from "./yard-3d/Yard3DViewer";
|
||||
import { yardLayoutApi } from "@/lib/api/yardLayoutApi";
|
||||
import type { YardManagementConfig } from "../types";
|
||||
|
||||
interface YardLayout {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
placement_count: number;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface YardManagement3DWidgetProps {
|
||||
isEditMode?: boolean;
|
||||
config?: YardManagementConfig;
|
||||
onConfigChange?: (config: YardManagementConfig) => void;
|
||||
}
|
||||
|
||||
export default function YardManagement3DWidget({
|
||||
isEditMode = false,
|
||||
config,
|
||||
onConfigChange,
|
||||
}: YardManagement3DWidgetProps) {
|
||||
const [layouts, setLayouts] = useState<YardLayout[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
||||
const [editingLayout, setEditingLayout] = useState<YardLayout | null>(null);
|
||||
|
||||
// 레이아웃 목록 로드
|
||||
const loadLayouts = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const response = await yardLayoutApi.getAllLayouts();
|
||||
if (response.success) {
|
||||
setLayouts(response.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("야드 레이아웃 목록 조회 실패:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (isEditMode) {
|
||||
loadLayouts();
|
||||
}
|
||||
}, [isEditMode]);
|
||||
|
||||
// 레이아웃 선택 (편집 모드에서만)
|
||||
const handleSelectLayout = (layout: YardLayout) => {
|
||||
if (onConfigChange) {
|
||||
onConfigChange({
|
||||
layoutId: layout.id,
|
||||
layoutName: layout.name,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// 새 레이아웃 생성
|
||||
const handleCreateLayout = async (name: string, description: string) => {
|
||||
try {
|
||||
const response = await yardLayoutApi.createLayout({ name, description });
|
||||
if (response.success) {
|
||||
await loadLayouts();
|
||||
setIsCreateModalOpen(false);
|
||||
setEditingLayout(response.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("야드 레이아웃 생성 실패:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// 편집 완료
|
||||
const handleEditComplete = () => {
|
||||
if (editingLayout && onConfigChange) {
|
||||
onConfigChange({
|
||||
layoutId: editingLayout.id,
|
||||
layoutName: editingLayout.name,
|
||||
});
|
||||
}
|
||||
setEditingLayout(null);
|
||||
loadLayouts();
|
||||
};
|
||||
|
||||
// 편집 모드: 편집 중인 경우 YardEditor 표시
|
||||
if (isEditMode && editingLayout) {
|
||||
return (
|
||||
<div className="h-full w-full">
|
||||
<YardEditor layout={editingLayout} onBack={handleEditComplete} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 편집 모드: 레이아웃 선택 UI
|
||||
if (isEditMode) {
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col bg-white">
|
||||
<div className="flex items-center justify-between border-b p-4">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-gray-700">야드 레이아웃 선택</h3>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
{config?.layoutName ? `선택됨: ${config.layoutName}` : "표시할 야드 레이아웃을 선택하세요"}
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setIsCreateModalOpen(true)} size="sm">
|
||||
<Plus className="mr-1 h-4 w-4" />새 야드 생성
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-auto p-4">
|
||||
{isLoading ? (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<div className="text-sm text-gray-500">로딩 중...</div>
|
||||
</div>
|
||||
) : layouts.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="mb-2 text-4xl">🏗️</div>
|
||||
<div className="text-sm text-gray-600">생성된 야드 레이아웃이 없습니다</div>
|
||||
<div className="mt-1 text-xs text-gray-400">먼저 야드 레이아웃을 생성하세요</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-3">
|
||||
{layouts.map((layout) => (
|
||||
<div
|
||||
key={layout.id}
|
||||
className={`rounded-lg border p-3 transition-all ${
|
||||
config?.layoutId === layout.id ? "border-blue-500 bg-blue-50" : "border-gray-200 bg-white"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<button onClick={() => handleSelectLayout(layout)} className="flex-1 text-left hover:opacity-80">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium text-gray-900">{layout.name}</span>
|
||||
{config?.layoutId === layout.id && <Check className="h-4 w-4 text-blue-600" />}
|
||||
</div>
|
||||
{layout.description && <p className="mt-1 text-xs text-gray-500">{layout.description}</p>}
|
||||
<div className="mt-2 text-xs text-gray-400">배치된 자재: {layout.placement_count}개</div>
|
||||
</button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setEditingLayout(layout);
|
||||
}}
|
||||
>
|
||||
편집
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 생성 모달 */}
|
||||
<YardLayoutCreateModal
|
||||
isOpen={isCreateModalOpen}
|
||||
onClose={() => setIsCreateModalOpen(false)}
|
||||
onCreate={handleCreateLayout}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 뷰 모드: 선택된 레이아웃의 3D 뷰어 표시
|
||||
if (!config?.layoutId) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center bg-gray-50">
|
||||
<div className="text-center">
|
||||
<div className="mb-2 text-4xl">🏗️</div>
|
||||
<div className="text-sm font-medium text-gray-600">야드 레이아웃이 설정되지 않았습니다</div>
|
||||
<div className="mt-1 text-xs text-gray-400">대시보드 편집에서 레이아웃을 선택하세요</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 선택된 레이아웃의 3D 뷰어 표시
|
||||
return (
|
||||
<div className="h-full w-full">
|
||||
<Yard3DViewer layoutId={config.layoutId} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,247 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
interface TempMaterial {
|
||||
id: number;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
category: string;
|
||||
unit: string;
|
||||
default_color: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface MaterialAddModalProps {
|
||||
isOpen: boolean;
|
||||
material: TempMaterial | null;
|
||||
onClose: () => void;
|
||||
onAdd: (placementData: any) => Promise<void>;
|
||||
}
|
||||
|
||||
export default function MaterialAddModal({ isOpen, material, onClose, onAdd }: MaterialAddModalProps) {
|
||||
const [quantity, setQuantity] = useState("1");
|
||||
const [positionX, setPositionX] = useState("0");
|
||||
const [positionY, setPositionY] = useState("0");
|
||||
const [positionZ, setPositionZ] = useState("0");
|
||||
const [sizeX, setSizeX] = useState("5");
|
||||
const [sizeY, setSizeY] = useState("5");
|
||||
const [sizeZ, setSizeZ] = useState("5");
|
||||
const [color, setColor] = useState("");
|
||||
const [isAdding, setIsAdding] = useState(false);
|
||||
|
||||
// 모달이 열릴 때 기본값 설정
|
||||
const handleOpen = (open: boolean) => {
|
||||
if (open && material) {
|
||||
setColor(material.default_color);
|
||||
setQuantity("1");
|
||||
setPositionX("0");
|
||||
setPositionY("0");
|
||||
setPositionZ("0");
|
||||
setSizeX("5");
|
||||
setSizeY("5");
|
||||
setSizeZ("5");
|
||||
}
|
||||
};
|
||||
|
||||
// 자재 추가
|
||||
const handleAdd = async () => {
|
||||
if (!material) return;
|
||||
|
||||
setIsAdding(true);
|
||||
try {
|
||||
await onAdd({
|
||||
external_material_id: `TEMP-${Date.now()}`,
|
||||
material_code: material.material_code,
|
||||
material_name: material.material_name,
|
||||
quantity: parseInt(quantity) || 1,
|
||||
unit: material.unit,
|
||||
position_x: parseFloat(positionX) || 0,
|
||||
position_y: parseFloat(positionY) || 0,
|
||||
position_z: parseFloat(positionZ) || 0,
|
||||
size_x: parseFloat(sizeX) || 5,
|
||||
size_y: parseFloat(sizeY) || 5,
|
||||
size_z: parseFloat(sizeZ) || 5,
|
||||
color: color || material.default_color,
|
||||
});
|
||||
onClose();
|
||||
} catch (error) {
|
||||
console.error("자재 추가 실패:", error);
|
||||
} finally {
|
||||
setIsAdding(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!material) return null;
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => {
|
||||
handleOpen(open);
|
||||
if (!open) onClose();
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>자재 배치 설정</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* 자재 정보 */}
|
||||
<div className="rounded-lg bg-gray-50 p-4">
|
||||
<div className="mb-2 text-sm font-medium text-gray-600">선택한 자재</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-10 w-10 rounded border" style={{ backgroundColor: material.default_color }} />
|
||||
<div>
|
||||
<div className="font-medium">{material.material_name}</div>
|
||||
<div className="text-sm text-gray-600">{material.material_code}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 수량 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="quantity">수량</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="quantity"
|
||||
type="number"
|
||||
value={quantity}
|
||||
onChange={(e) => setQuantity(e.target.value)}
|
||||
min="1"
|
||||
className="flex-1"
|
||||
/>
|
||||
<span className="text-sm text-gray-600">{material.unit}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 3D 위치 */}
|
||||
<div className="space-y-2">
|
||||
<Label>3D 위치</Label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<Label htmlFor="posX" className="text-xs text-gray-600">
|
||||
X (좌우)
|
||||
</Label>
|
||||
<Input
|
||||
id="posX"
|
||||
type="number"
|
||||
value={positionX}
|
||||
onChange={(e) => setPositionX(e.target.value)}
|
||||
step="0.5"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="posY" className="text-xs text-gray-600">
|
||||
Y (높이)
|
||||
</Label>
|
||||
<Input
|
||||
id="posY"
|
||||
type="number"
|
||||
value={positionY}
|
||||
onChange={(e) => setPositionY(e.target.value)}
|
||||
step="0.5"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="posZ" className="text-xs text-gray-600">
|
||||
Z (앞뒤)
|
||||
</Label>
|
||||
<Input
|
||||
id="posZ"
|
||||
type="number"
|
||||
value={positionZ}
|
||||
onChange={(e) => setPositionZ(e.target.value)}
|
||||
step="0.5"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 3D 크기 */}
|
||||
<div className="space-y-2">
|
||||
<Label>3D 크기</Label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<Label htmlFor="sizeX" className="text-xs text-gray-600">
|
||||
너비
|
||||
</Label>
|
||||
<Input
|
||||
id="sizeX"
|
||||
type="number"
|
||||
value={sizeX}
|
||||
onChange={(e) => setSizeX(e.target.value)}
|
||||
min="1"
|
||||
step="0.5"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="sizeY" className="text-xs text-gray-600">
|
||||
높이
|
||||
</Label>
|
||||
<Input
|
||||
id="sizeY"
|
||||
type="number"
|
||||
value={sizeY}
|
||||
onChange={(e) => setSizeY(e.target.value)}
|
||||
min="1"
|
||||
step="0.5"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="sizeZ" className="text-xs text-gray-600">
|
||||
깊이
|
||||
</Label>
|
||||
<Input
|
||||
id="sizeZ"
|
||||
type="number"
|
||||
value={sizeZ}
|
||||
onChange={(e) => setSizeZ(e.target.value)}
|
||||
min="1"
|
||||
step="0.5"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 색상 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="color">색상</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
id="color"
|
||||
type="color"
|
||||
value={color}
|
||||
onChange={(e) => setColor(e.target.value)}
|
||||
className="h-10 w-20 cursor-pointer rounded border"
|
||||
/>
|
||||
<Input value={color} onChange={(e) => setColor(e.target.value)} className="flex-1" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose} disabled={isAdding}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleAdd} disabled={isAdding}>
|
||||
{isAdding ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
추가 중...
|
||||
</>
|
||||
) : (
|
||||
"배치"
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,277 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Trash2 } from "lucide-react";
|
||||
|
||||
interface YardPlacement {
|
||||
id: number;
|
||||
external_material_id: string;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
position_x: number;
|
||||
position_y: number;
|
||||
position_z: number;
|
||||
size_x: number;
|
||||
size_y: number;
|
||||
size_z: number;
|
||||
color: string;
|
||||
memo?: string;
|
||||
}
|
||||
|
||||
interface MaterialEditPanelProps {
|
||||
placement: YardPlacement | null;
|
||||
onClose: () => void;
|
||||
onUpdate: (id: number, updates: Partial<YardPlacement>) => void;
|
||||
onRemove: (id: number) => void;
|
||||
}
|
||||
|
||||
export default function MaterialEditPanel({ placement, onClose, onUpdate, onRemove }: MaterialEditPanelProps) {
|
||||
const [editData, setEditData] = useState<Partial<YardPlacement>>({});
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
|
||||
|
||||
// placement 변경 시 editData 초기화
|
||||
useEffect(() => {
|
||||
if (placement) {
|
||||
setEditData({
|
||||
position_x: placement.position_x,
|
||||
position_y: placement.position_y,
|
||||
position_z: placement.position_z,
|
||||
size_x: placement.size_x,
|
||||
size_y: placement.size_y,
|
||||
size_z: placement.size_z,
|
||||
color: placement.color,
|
||||
memo: placement.memo,
|
||||
});
|
||||
}
|
||||
}, [placement]);
|
||||
|
||||
if (!placement) return null;
|
||||
|
||||
// 변경사항 적용
|
||||
const handleApply = () => {
|
||||
onUpdate(placement.id, editData);
|
||||
};
|
||||
|
||||
// 배치 해제
|
||||
const handleRemove = () => {
|
||||
onRemove(placement.id);
|
||||
setIsDeleteDialogOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-80 border-l bg-white p-4">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">자재 정보</h3>
|
||||
<Button variant="ghost" size="sm" onClick={onClose}>
|
||||
닫기
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* 읽기 전용 정보 */}
|
||||
<div className="space-y-3 rounded-lg bg-gray-50 p-3">
|
||||
<div className="text-xs font-medium text-gray-500">자재 정보 (읽기 전용)</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-600">자재 코드</div>
|
||||
<div className="mt-1 text-sm font-medium">{placement.material_code}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-600">자재 이름</div>
|
||||
<div className="mt-1 text-sm font-medium">{placement.material_name}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-600">수량</div>
|
||||
<div className="mt-1 text-sm font-medium">
|
||||
{placement.quantity} {placement.unit}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 배치 정보 (편집 가능) */}
|
||||
<div className="space-y-3">
|
||||
<div className="text-xs font-medium text-gray-500">배치 정보 (편집 가능)</div>
|
||||
|
||||
{/* 3D 위치 */}
|
||||
<div>
|
||||
<Label className="text-xs">위치</Label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<Label htmlFor="edit-posX" className="text-xs text-gray-600">
|
||||
X
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-posX"
|
||||
type="number"
|
||||
value={editData.position_x ?? placement.position_x}
|
||||
onChange={(e) => setEditData({ ...editData, position_x: parseFloat(e.target.value) || 0 })}
|
||||
step="0.5"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="edit-posY" className="text-xs text-gray-600">
|
||||
Y
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-posY"
|
||||
type="number"
|
||||
value={editData.position_y ?? placement.position_y}
|
||||
onChange={(e) => setEditData({ ...editData, position_y: parseFloat(e.target.value) || 0 })}
|
||||
step="0.5"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="edit-posZ" className="text-xs text-gray-600">
|
||||
Z
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-posZ"
|
||||
type="number"
|
||||
value={editData.position_z ?? placement.position_z}
|
||||
onChange={(e) => setEditData({ ...editData, position_z: parseFloat(e.target.value) || 0 })}
|
||||
step="0.5"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 3D 크기 */}
|
||||
<div>
|
||||
<Label className="text-xs">크기</Label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<Label htmlFor="edit-sizeX" className="text-xs text-gray-600">
|
||||
너비
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-sizeX"
|
||||
type="number"
|
||||
value={editData.size_x ?? placement.size_x}
|
||||
onChange={(e) => setEditData({ ...editData, size_x: parseFloat(e.target.value) || 1 })}
|
||||
min="1"
|
||||
step="0.5"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="edit-sizeY" className="text-xs text-gray-600">
|
||||
높이
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-sizeY"
|
||||
type="number"
|
||||
value={editData.size_y ?? placement.size_y}
|
||||
onChange={(e) => setEditData({ ...editData, size_y: parseFloat(e.target.value) || 1 })}
|
||||
min="1"
|
||||
step="0.5"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="edit-sizeZ" className="text-xs text-gray-600">
|
||||
깊이
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-sizeZ"
|
||||
type="number"
|
||||
value={editData.size_z ?? placement.size_z}
|
||||
onChange={(e) => setEditData({ ...editData, size_z: parseFloat(e.target.value) || 1 })}
|
||||
min="1"
|
||||
step="0.5"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 색상 */}
|
||||
<div>
|
||||
<Label htmlFor="edit-color" className="text-xs">
|
||||
색상
|
||||
</Label>
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<input
|
||||
id="edit-color"
|
||||
type="color"
|
||||
value={editData.color ?? placement.color}
|
||||
onChange={(e) => setEditData({ ...editData, color: e.target.value })}
|
||||
className="h-8 w-16 cursor-pointer rounded border"
|
||||
/>
|
||||
<Input
|
||||
value={editData.color ?? placement.color}
|
||||
onChange={(e) => setEditData({ ...editData, color: e.target.value })}
|
||||
className="h-8 flex-1 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 메모 */}
|
||||
<div>
|
||||
<Label htmlFor="edit-memo" className="text-xs">
|
||||
메모
|
||||
</Label>
|
||||
<Textarea
|
||||
id="edit-memo"
|
||||
value={editData.memo ?? placement.memo ?? ""}
|
||||
onChange={(e) => setEditData({ ...editData, memo: e.target.value })}
|
||||
placeholder="메모를 입력하세요"
|
||||
rows={3}
|
||||
className="text-xs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 적용 버튼 */}
|
||||
<Button onClick={handleApply} className="w-full" size="sm">
|
||||
변경사항 적용
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 배치 해제 */}
|
||||
<div className="border-t pt-4">
|
||||
<Button variant="destructive" onClick={() => setIsDeleteDialogOpen(true)} className="w-full" size="sm">
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
배치 해제
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 삭제 확인 모달 */}
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>배치 해제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
정말로 이 자재를 배치 해제하시겠습니까?
|
||||
<br />
|
||||
"{placement.material_name}" ({placement.quantity} {placement.unit})
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleRemove} className="bg-red-600 hover:bg-red-700">
|
||||
해제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,192 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Search, Loader2 } from "lucide-react";
|
||||
import { materialApi } from "@/lib/api/yardLayoutApi";
|
||||
|
||||
interface TempMaterial {
|
||||
id: number;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
category: string;
|
||||
unit: string;
|
||||
default_color: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface MaterialLibraryProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSelect: (material: TempMaterial) => void;
|
||||
}
|
||||
|
||||
export default function MaterialLibrary({ isOpen, onClose, onSelect }: MaterialLibraryProps) {
|
||||
const [materials, setMaterials] = useState<TempMaterial[]>([]);
|
||||
const [categories, setCategories] = useState<string[]>([]);
|
||||
const [searchText, setSearchText] = useState("");
|
||||
const [selectedCategory, setSelectedCategory] = useState<string>("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedMaterial, setSelectedMaterial] = useState<TempMaterial | null>(null);
|
||||
|
||||
// 자재 목록 로드
|
||||
const loadMaterials = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const [materialsResponse, categoriesResponse] = await Promise.all([
|
||||
materialApi.getTempMaterials({
|
||||
search: searchText || undefined,
|
||||
category: selectedCategory || undefined,
|
||||
page: 1,
|
||||
limit: 50,
|
||||
}),
|
||||
materialApi.getCategories(),
|
||||
]);
|
||||
|
||||
if (materialsResponse.success) {
|
||||
setMaterials(materialsResponse.data);
|
||||
}
|
||||
|
||||
if (categoriesResponse.success) {
|
||||
setCategories(categoriesResponse.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("자재 목록 조회 실패:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
loadMaterials();
|
||||
}
|
||||
}, [isOpen, searchText, selectedCategory]);
|
||||
|
||||
// 자재 선택 및 추가
|
||||
const handleSelectMaterial = () => {
|
||||
if (selectedMaterial) {
|
||||
onSelect(selectedMaterial);
|
||||
setSelectedMaterial(null);
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
// 모달 닫기
|
||||
const handleClose = () => {
|
||||
setSelectedMaterial(null);
|
||||
setSearchText("");
|
||||
setSelectedCategory("");
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleClose}>
|
||||
<DialogContent className="max-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>자재 선택</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* 검색 및 필터 */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<Input
|
||||
placeholder="자재 코드 또는 이름 검색..."
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
value={selectedCategory}
|
||||
onChange={(e) => setSelectedCategory(e.target.value)}
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">전체 카테고리</option>
|
||||
{categories.map((category) => (
|
||||
<option key={category} value={category}>
|
||||
{category}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* 자재 목록 */}
|
||||
{isLoading ? (
|
||||
<div className="flex h-64 items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-gray-400" />
|
||||
</div>
|
||||
) : materials.length === 0 ? (
|
||||
<div className="flex h-64 items-center justify-center text-gray-500">
|
||||
{searchText || selectedCategory ? "검색 결과가 없습니다" : "등록된 자재가 없습니다"}
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-h-96 overflow-auto rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[50px]">색상</TableHead>
|
||||
<TableHead>자재 코드</TableHead>
|
||||
<TableHead>자재 이름</TableHead>
|
||||
<TableHead>카테고리</TableHead>
|
||||
<TableHead>단위</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{materials.map((material) => (
|
||||
<TableRow
|
||||
key={material.id}
|
||||
className={`cursor-pointer ${
|
||||
selectedMaterial?.id === material.id ? "bg-blue-50" : "hover:bg-gray-50"
|
||||
}`}
|
||||
onClick={() => setSelectedMaterial(material)}
|
||||
>
|
||||
<TableCell>
|
||||
<div className="h-6 w-6 rounded border" style={{ backgroundColor: material.default_color }} />
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{material.material_code}</TableCell>
|
||||
<TableCell>{material.material_name}</TableCell>
|
||||
<TableCell>{material.category}</TableCell>
|
||||
<TableCell>{material.unit}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 선택된 자재 정보 */}
|
||||
{selectedMaterial && (
|
||||
<div className="rounded-lg bg-blue-50 p-4">
|
||||
<div className="mb-2 text-sm font-medium text-blue-900">선택된 자재</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-10 w-10 rounded border" style={{ backgroundColor: selectedMaterial.default_color }} />
|
||||
<div className="flex-1">
|
||||
<div className="font-medium">{selectedMaterial.material_name}</div>
|
||||
<div className="text-sm text-gray-600">{selectedMaterial.material_code}</div>
|
||||
</div>
|
||||
</div>
|
||||
{selectedMaterial.description && (
|
||||
<div className="mt-2 text-sm text-gray-600">{selectedMaterial.description}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSelectMaterial} disabled={!selectedMaterial}>
|
||||
선택
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,299 @@
|
|||
"use client";
|
||||
|
||||
import { Canvas, useThree } from "@react-three/fiber";
|
||||
import { OrbitControls, Grid, Box } from "@react-three/drei";
|
||||
import { Suspense, useRef, useState, useEffect } from "react";
|
||||
import * as THREE from "three";
|
||||
|
||||
interface YardPlacement {
|
||||
id: number;
|
||||
external_material_id: string;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
position_x: number;
|
||||
position_y: number;
|
||||
position_z: number;
|
||||
size_x: number;
|
||||
size_y: number;
|
||||
size_z: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
interface Yard3DCanvasProps {
|
||||
placements: YardPlacement[];
|
||||
selectedPlacementId: number | null;
|
||||
onPlacementClick: (placement: YardPlacement) => void;
|
||||
onPlacementDrag?: (id: number, position: { x: number; y: number; z: number }) => void;
|
||||
}
|
||||
|
||||
// 자재 박스 컴포넌트 (드래그 가능)
|
||||
function MaterialBox({
|
||||
placement,
|
||||
isSelected,
|
||||
onClick,
|
||||
onDrag,
|
||||
onDragStart,
|
||||
onDragEnd,
|
||||
}: {
|
||||
placement: YardPlacement;
|
||||
isSelected: boolean;
|
||||
onClick: () => void;
|
||||
onDrag?: (position: { x: number; y: number; z: number }) => void;
|
||||
onDragStart?: () => void;
|
||||
onDragEnd?: () => void;
|
||||
}) {
|
||||
const meshRef = useRef<THREE.Mesh>(null);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const dragStartPos = useRef<{ x: number; y: number; z: number }>({ x: 0, y: 0, z: 0 });
|
||||
const mouseStartPos = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
|
||||
const { camera, gl } = useThree();
|
||||
|
||||
// 드래그 중이 아닐 때 위치 업데이트
|
||||
useEffect(() => {
|
||||
if (!isDragging && meshRef.current) {
|
||||
meshRef.current.position.set(placement.position_x, placement.position_y, placement.position_z);
|
||||
}
|
||||
}, [placement.position_x, placement.position_y, placement.position_z, isDragging]);
|
||||
|
||||
// 전역 이벤트 리스너 등록
|
||||
useEffect(() => {
|
||||
const handleGlobalMouseMove = (e: MouseEvent) => {
|
||||
if (isDragging && onDrag && meshRef.current) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
// 마우스 이동 거리 계산 (픽셀)
|
||||
const deltaX = e.clientX - mouseStartPos.current.x;
|
||||
const deltaY = e.clientY - mouseStartPos.current.y;
|
||||
|
||||
// 카메라 거리를 고려한 스케일 팩터
|
||||
const distance = camera.position.distanceTo(meshRef.current.position);
|
||||
const scaleFactor = distance / 500; // 조정 가능한 값
|
||||
|
||||
// 카메라 방향 벡터
|
||||
const cameraDirection = new THREE.Vector3();
|
||||
camera.getWorldDirection(cameraDirection);
|
||||
|
||||
// 카메라의 우측 벡터 (X축 이동용)
|
||||
const right = new THREE.Vector3();
|
||||
right.crossVectors(camera.up, cameraDirection).normalize();
|
||||
|
||||
// 실제 3D 공간에서의 이동량 계산
|
||||
const moveRight = right.multiplyScalar(-deltaX * scaleFactor);
|
||||
const moveForward = new THREE.Vector3(-cameraDirection.x, 0, -cameraDirection.z)
|
||||
.normalize()
|
||||
.multiplyScalar(deltaY * scaleFactor);
|
||||
|
||||
// 최종 위치 계산
|
||||
const finalX = dragStartPos.current.x + moveRight.x + moveForward.x;
|
||||
const finalZ = dragStartPos.current.z + moveRight.z + moveForward.z;
|
||||
|
||||
// NaN 검증
|
||||
if (isNaN(finalX) || isNaN(finalZ)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 즉시 mesh 위치 업데이트 (부드러운 드래그)
|
||||
meshRef.current.position.set(finalX, dragStartPos.current.y, finalZ);
|
||||
|
||||
// 상태 업데이트 (저장용)
|
||||
onDrag({
|
||||
x: finalX,
|
||||
y: dragStartPos.current.y,
|
||||
z: finalZ,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleGlobalMouseUp = () => {
|
||||
if (isDragging) {
|
||||
setIsDragging(false);
|
||||
gl.domElement.style.cursor = isSelected ? "grab" : "pointer";
|
||||
if (onDragEnd) {
|
||||
onDragEnd();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (isDragging) {
|
||||
window.addEventListener("mousemove", handleGlobalMouseMove);
|
||||
window.addEventListener("mouseup", handleGlobalMouseUp);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("mousemove", handleGlobalMouseMove);
|
||||
window.removeEventListener("mouseup", handleGlobalMouseUp);
|
||||
};
|
||||
}
|
||||
}, [isDragging, onDrag, onDragEnd, camera, isSelected, gl.domElement]);
|
||||
|
||||
const handlePointerDown = (e: any) => {
|
||||
e.stopPropagation();
|
||||
|
||||
// 뷰어 모드(onDrag 없음)에서는 클릭만 처리
|
||||
if (!onDrag) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 편집 모드에서 선택되었고 드래그 가능한 경우
|
||||
if (isSelected && meshRef.current) {
|
||||
// 드래그 시작 시점의 자재 위치 저장 (숫자로 변환)
|
||||
dragStartPos.current = {
|
||||
x: Number(placement.position_x),
|
||||
y: Number(placement.position_y),
|
||||
z: Number(placement.position_z),
|
||||
};
|
||||
|
||||
// 마우스 시작 위치 저장
|
||||
mouseStartPos.current = {
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
};
|
||||
|
||||
setIsDragging(true);
|
||||
gl.domElement.style.cursor = "grabbing";
|
||||
if (onDragStart) {
|
||||
onDragStart();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
ref={meshRef}
|
||||
position={[placement.position_x, placement.position_y, placement.position_z]}
|
||||
args={[placement.size_x, placement.size_y, placement.size_z]}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.nativeEvent?.stopPropagation();
|
||||
e.nativeEvent?.stopImmediatePropagation();
|
||||
console.log("3D Box clicked:", placement.material_name);
|
||||
onClick();
|
||||
}}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerOver={() => {
|
||||
// 뷰어 모드(onDrag 없음)에서는 기본 커서, 편집 모드에서는 grab 커서
|
||||
if (onDrag) {
|
||||
gl.domElement.style.cursor = isSelected ? "grab" : "pointer";
|
||||
} else {
|
||||
gl.domElement.style.cursor = "pointer";
|
||||
}
|
||||
}}
|
||||
onPointerOut={() => {
|
||||
if (!isDragging) {
|
||||
gl.domElement.style.cursor = "default";
|
||||
}
|
||||
}}
|
||||
>
|
||||
<meshStandardMaterial
|
||||
color={placement.color}
|
||||
opacity={isSelected ? 1 : 0.8}
|
||||
transparent
|
||||
emissive={isSelected ? "#ffffff" : "#000000"}
|
||||
emissiveIntensity={isSelected ? 0.2 : 0}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// 3D 씬 컴포넌트
|
||||
function Scene({ placements, selectedPlacementId, onPlacementClick, onPlacementDrag }: Yard3DCanvasProps) {
|
||||
const [isDraggingAny, setIsDraggingAny] = useState(false);
|
||||
const orbitControlsRef = useRef<any>(null);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 조명 */}
|
||||
<ambientLight intensity={0.5} />
|
||||
<directionalLight position={[10, 10, 5]} intensity={1} />
|
||||
<directionalLight position={[-10, -10, -5]} intensity={0.3} />
|
||||
|
||||
{/* 바닥 그리드 */}
|
||||
<Grid
|
||||
args={[100, 100]}
|
||||
cellSize={5}
|
||||
cellThickness={0.5}
|
||||
cellColor="#6b7280"
|
||||
sectionSize={10}
|
||||
sectionThickness={1}
|
||||
sectionColor="#374151"
|
||||
fadeDistance={200}
|
||||
fadeStrength={1}
|
||||
followCamera={false}
|
||||
infiniteGrid={true}
|
||||
/>
|
||||
|
||||
{/* 자재 박스들 */}
|
||||
{placements.map((placement) => (
|
||||
<MaterialBox
|
||||
key={placement.id}
|
||||
placement={placement}
|
||||
isSelected={selectedPlacementId === placement.id}
|
||||
onClick={() => onPlacementClick(placement)}
|
||||
onDrag={onPlacementDrag ? (position) => onPlacementDrag(placement.id, position) : undefined}
|
||||
onDragStart={() => {
|
||||
setIsDraggingAny(true);
|
||||
if (orbitControlsRef.current) {
|
||||
orbitControlsRef.current.enabled = false;
|
||||
}
|
||||
}}
|
||||
onDragEnd={() => {
|
||||
setIsDraggingAny(false);
|
||||
if (orbitControlsRef.current) {
|
||||
orbitControlsRef.current.enabled = true;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* 카메라 컨트롤 */}
|
||||
<OrbitControls
|
||||
ref={orbitControlsRef}
|
||||
enablePan={true}
|
||||
enableZoom={true}
|
||||
enableRotate={true}
|
||||
minDistance={10}
|
||||
maxDistance={200}
|
||||
maxPolarAngle={Math.PI / 2}
|
||||
enabled={!isDraggingAny}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Yard3DCanvas({
|
||||
placements,
|
||||
selectedPlacementId,
|
||||
onPlacementClick,
|
||||
onPlacementDrag,
|
||||
}: Yard3DCanvasProps) {
|
||||
const handleCanvasClick = (e: any) => {
|
||||
// Canvas의 빈 공간을 클릭했을 때만 선택 해제
|
||||
// e.target이 canvas 엘리먼트인 경우
|
||||
if (e.target.tagName === "CANVAS") {
|
||||
onPlacementClick(null as any);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full w-full bg-gray-900" onClick={handleCanvasClick}>
|
||||
<Canvas
|
||||
camera={{
|
||||
position: [50, 30, 50],
|
||||
fov: 50,
|
||||
}}
|
||||
shadows
|
||||
>
|
||||
<Suspense fallback={null}>
|
||||
<Scene
|
||||
placements={placements}
|
||||
selectedPlacementId={selectedPlacementId}
|
||||
onPlacementClick={onPlacementClick}
|
||||
onPlacementDrag={onPlacementDrag}
|
||||
/>
|
||||
</Suspense>
|
||||
</Canvas>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,161 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Yard3DCanvas from "./Yard3DCanvas";
|
||||
import { yardLayoutApi } from "@/lib/api/yardLayoutApi";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
interface YardPlacement {
|
||||
id: number;
|
||||
yard_layout_id: number;
|
||||
external_material_id: string;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
position_x: number;
|
||||
position_y: number;
|
||||
position_z: number;
|
||||
size_x: number;
|
||||
size_y: number;
|
||||
size_z: number;
|
||||
color: string;
|
||||
status?: string;
|
||||
memo?: string;
|
||||
}
|
||||
|
||||
interface Yard3DViewerProps {
|
||||
layoutId: number;
|
||||
}
|
||||
|
||||
export default function Yard3DViewer({ layoutId }: Yard3DViewerProps) {
|
||||
const [placements, setPlacements] = useState<YardPlacement[]>([]);
|
||||
const [selectedPlacement, setSelectedPlacement] = useState<YardPlacement | null>(null);
|
||||
const [layoutName, setLayoutName] = useState<string>("");
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// 선택 변경 로그
|
||||
const handlePlacementClick = (placement: YardPlacement | null) => {
|
||||
console.log("Yard3DViewer - Placement clicked:", placement?.material_name);
|
||||
setSelectedPlacement(placement);
|
||||
};
|
||||
|
||||
// 선택 상태 변경 감지
|
||||
useEffect(() => {
|
||||
console.log("selectedPlacement changed:", selectedPlacement?.material_name);
|
||||
}, [selectedPlacement]);
|
||||
|
||||
// 야드 레이아웃 및 배치 데이터 로드
|
||||
useEffect(() => {
|
||||
const loadData = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
// 야드 레이아웃 정보 조회
|
||||
const layoutResponse = await yardLayoutApi.getLayoutById(layoutId);
|
||||
if (layoutResponse.success) {
|
||||
setLayoutName(layoutResponse.data.name);
|
||||
}
|
||||
|
||||
// 배치 데이터 조회
|
||||
const placementsResponse = await yardLayoutApi.getPlacementsByLayoutId(layoutId);
|
||||
if (placementsResponse.success) {
|
||||
setPlacements(placementsResponse.data);
|
||||
} else {
|
||||
setError("배치 데이터를 불러올 수 없습니다.");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("데이터 로드 실패:", err);
|
||||
setError("데이터를 불러오는 중 오류가 발생했습니다.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadData();
|
||||
}, [layoutId]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center bg-gray-50">
|
||||
<div className="text-center">
|
||||
<Loader2 className="mx-auto h-8 w-8 animate-spin text-blue-600" />
|
||||
<div className="mt-2 text-sm text-gray-600">3D 장면 로딩 중...</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center bg-gray-50">
|
||||
<div className="text-center">
|
||||
<div className="mb-2 text-4xl">⚠️</div>
|
||||
<div className="text-sm font-medium text-gray-600">{error}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (placements.length === 0) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center bg-gray-50">
|
||||
<div className="text-center">
|
||||
<div className="mb-2 text-4xl">📦</div>
|
||||
<div className="text-sm font-medium text-gray-600">배치된 자재가 없습니다</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative h-full w-full">
|
||||
{/* 3D 캔버스 */}
|
||||
<Yard3DCanvas
|
||||
placements={placements}
|
||||
selectedPlacementId={selectedPlacement?.id || null}
|
||||
onPlacementClick={handlePlacementClick}
|
||||
/>
|
||||
|
||||
{/* 야드 이름 (좌측 상단) */}
|
||||
{layoutName && (
|
||||
<div className="absolute top-4 left-4 z-50 rounded-lg border border-gray-300 bg-white px-4 py-2 shadow-lg">
|
||||
<h2 className="text-base font-bold text-gray-900">{layoutName}</h2>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 선택된 자재 정보 패널 (우측 상단) */}
|
||||
{selectedPlacement && (
|
||||
<div className="absolute top-4 right-4 z-50 w-64 rounded-lg border border-gray-300 bg-white p-4 shadow-xl">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold text-gray-800">자재 정보</h3>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedPlacement(null);
|
||||
}}
|
||||
className="rounded-full p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<label className="text-xs font-medium text-gray-500">자재명</label>
|
||||
<div className="mt-1 text-sm font-semibold text-gray-900">{selectedPlacement.material_name}</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-xs font-medium text-gray-500">수량</label>
|
||||
<div className="mt-1 text-sm font-semibold text-gray-900">
|
||||
{selectedPlacement.quantity} {selectedPlacement.unit}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,461 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ArrowLeft, Save, Loader2, X } from "lucide-react";
|
||||
import { yardLayoutApi, materialApi } from "@/lib/api/yardLayoutApi";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
const Yard3DCanvas = dynamic(() => import("./Yard3DCanvas"), {
|
||||
ssr: false,
|
||||
loading: () => (
|
||||
<div className="flex h-full items-center justify-center bg-gray-900">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-gray-400" />
|
||||
</div>
|
||||
),
|
||||
});
|
||||
|
||||
interface TempMaterial {
|
||||
id: number;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
category: string;
|
||||
unit: string;
|
||||
default_color: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface YardLayout {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
placement_count?: number;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface YardPlacement {
|
||||
id: number;
|
||||
yard_layout_id: number;
|
||||
external_material_id: string;
|
||||
material_code: string;
|
||||
material_name: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
position_x: number;
|
||||
position_y: number;
|
||||
position_z: number;
|
||||
size_x: number;
|
||||
size_y: number;
|
||||
size_z: number;
|
||||
color: string;
|
||||
memo?: string;
|
||||
}
|
||||
|
||||
interface YardEditorProps {
|
||||
layout: YardLayout;
|
||||
onBack: () => void;
|
||||
}
|
||||
|
||||
export default function YardEditor({ layout, onBack }: YardEditorProps) {
|
||||
const [placements, setPlacements] = useState<YardPlacement[]>([]);
|
||||
const [materials, setMaterials] = useState<TempMaterial[]>([]);
|
||||
const [selectedPlacement, setSelectedPlacement] = useState<YardPlacement | null>(null);
|
||||
const [selectedMaterial, setSelectedMaterial] = useState<TempMaterial | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
|
||||
// 배치 목록 & 자재 목록 로드
|
||||
useEffect(() => {
|
||||
const loadData = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const [placementsRes, materialsRes] = await Promise.all([
|
||||
yardLayoutApi.getPlacementsByLayoutId(layout.id),
|
||||
materialApi.getTempMaterials({ limit: 100 }),
|
||||
]);
|
||||
|
||||
if (placementsRes.success) {
|
||||
setPlacements(placementsRes.data);
|
||||
}
|
||||
if (materialsRes.success) {
|
||||
setMaterials(materialsRes.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("데이터 로드 실패:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadData();
|
||||
}, [layout.id]);
|
||||
|
||||
// 자재 클릭 → 배치 추가
|
||||
const handleMaterialClick = async (material: TempMaterial) => {
|
||||
// 이미 배치되었는지 확인
|
||||
const alreadyPlaced = placements.find((p) => p.material_code === material.material_code);
|
||||
if (alreadyPlaced) {
|
||||
alert("이미 배치된 자재입니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedMaterial(material);
|
||||
|
||||
// 기본 위치에 배치
|
||||
const placementData = {
|
||||
external_material_id: `TEMP-${material.id}`,
|
||||
material_code: material.material_code,
|
||||
material_name: material.material_name,
|
||||
quantity: 1,
|
||||
unit: material.unit,
|
||||
position_x: 0,
|
||||
position_y: 0,
|
||||
position_z: 0,
|
||||
size_x: 5,
|
||||
size_y: 5,
|
||||
size_z: 5,
|
||||
color: material.default_color,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await yardLayoutApi.addMaterialPlacement(layout.id, placementData);
|
||||
if (response.success) {
|
||||
setPlacements((prev) => [...prev, response.data]);
|
||||
setSelectedPlacement(response.data);
|
||||
setSelectedMaterial(null);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error("자재 배치 실패:", error);
|
||||
alert("자재 배치에 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
// 자재 드래그 (3D 캔버스에서)
|
||||
const handlePlacementDrag = (id: number, position: { x: number; y: number; z: number }) => {
|
||||
const updatedPosition = {
|
||||
position_x: Math.round(position.x * 2) / 2,
|
||||
position_y: position.y,
|
||||
position_z: Math.round(position.z * 2) / 2,
|
||||
};
|
||||
|
||||
setPlacements((prev) =>
|
||||
prev.map((p) =>
|
||||
p.id === id
|
||||
? {
|
||||
...p,
|
||||
...updatedPosition,
|
||||
}
|
||||
: p,
|
||||
),
|
||||
);
|
||||
|
||||
// 선택된 자재도 업데이트
|
||||
if (selectedPlacement?.id === id) {
|
||||
setSelectedPlacement((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
...updatedPosition,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// 자재 배치 해제
|
||||
const handlePlacementRemove = async (id: number) => {
|
||||
try {
|
||||
const response = await yardLayoutApi.removePlacement(id);
|
||||
if (response.success) {
|
||||
setPlacements((prev) => prev.filter((p) => p.id !== id));
|
||||
setSelectedPlacement(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("배치 해제 실패:", error);
|
||||
alert("배치 해제에 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
// 위치/크기/색상 업데이트
|
||||
const handlePlacementUpdate = (id: number, updates: Partial<YardPlacement>) => {
|
||||
setPlacements((prev) => prev.map((p) => (p.id === id ? { ...p, ...updates } : p)));
|
||||
};
|
||||
|
||||
// 저장
|
||||
const handleSave = async () => {
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const response = await yardLayoutApi.batchUpdatePlacements(
|
||||
layout.id,
|
||||
placements.map((p) => ({
|
||||
id: p.id,
|
||||
position_x: p.position_x,
|
||||
position_y: p.position_y,
|
||||
position_z: p.position_z,
|
||||
size_x: p.size_x,
|
||||
size_y: p.size_y,
|
||||
size_z: p.size_z,
|
||||
color: p.color,
|
||||
})),
|
||||
);
|
||||
|
||||
if (response.success) {
|
||||
alert("저장되었습니다");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("저장 실패:", error);
|
||||
alert("저장에 실패했습니다");
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 필터링된 자재 목록
|
||||
const filteredMaterials = materials.filter(
|
||||
(m) =>
|
||||
m.material_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
m.material_code.toLowerCase().includes(searchTerm.toLowerCase()),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col bg-white">
|
||||
{/* 상단 툴바 */}
|
||||
<div className="flex items-center justify-between border-b p-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="sm" onClick={onBack}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
목록으로
|
||||
</Button>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">{layout.name}</h2>
|
||||
{layout.description && <p className="text-sm text-gray-500">{layout.description}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button size="sm" onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
저장 중...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
저장
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 메인 컨텐츠 영역 */}
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* 좌측: 3D 캔버스 */}
|
||||
<div className="flex-1">
|
||||
{isLoading ? (
|
||||
<div className="flex h-full items-center justify-center bg-gray-50">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-gray-400" />
|
||||
</div>
|
||||
) : (
|
||||
<Yard3DCanvas
|
||||
placements={placements}
|
||||
selectedPlacementId={selectedPlacement?.id || null}
|
||||
onPlacementClick={setSelectedPlacement}
|
||||
onPlacementDrag={handlePlacementDrag}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 우측: 자재 목록 또는 편집 패널 */}
|
||||
<div className="w-80 border-l bg-white">
|
||||
{selectedPlacement ? (
|
||||
// 선택된 자재 편집 패널
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="flex items-center justify-between border-b p-4">
|
||||
<h3 className="text-sm font-semibold">자재 정보</h3>
|
||||
<Button variant="ghost" size="sm" onClick={() => setSelectedPlacement(null)}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-auto p-4">
|
||||
<div className="space-y-4">
|
||||
{/* 읽기 전용 정보 */}
|
||||
<div>
|
||||
<Label className="text-xs text-gray-500">자재 코드</Label>
|
||||
<div className="mt-1 text-sm font-medium">{selectedPlacement.material_code}</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs text-gray-500">자재명</Label>
|
||||
<div className="mt-1 text-sm font-medium">{selectedPlacement.material_name}</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs text-gray-500">수량 (변경 불가)</Label>
|
||||
<div className="mt-1 text-sm">
|
||||
{selectedPlacement.quantity} {selectedPlacement.unit}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 편집 가능 정보 */}
|
||||
<div className="space-y-3 border-t pt-4">
|
||||
<Label className="text-sm font-semibold">배치 정보</Label>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<Label className="text-xs">X</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.5"
|
||||
value={selectedPlacement.position_x}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
position_x: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Y</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.5"
|
||||
value={selectedPlacement.position_y}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
position_y: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Z</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.5"
|
||||
value={selectedPlacement.position_z}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
position_z: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<Label className="text-xs">너비</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={selectedPlacement.size_x}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
size_x: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">높이</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={selectedPlacement.size_y}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
size_y: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">깊이</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={selectedPlacement.size_z}
|
||||
onChange={(e) =>
|
||||
handlePlacementUpdate(selectedPlacement.id, {
|
||||
size_z: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs">색상</Label>
|
||||
<Input
|
||||
type="color"
|
||||
value={selectedPlacement.color}
|
||||
onChange={(e) => handlePlacementUpdate(selectedPlacement.id, { color: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() => handlePlacementRemove(selectedPlacement.id)}
|
||||
>
|
||||
배치 해제
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
// 자재 목록
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="border-b p-4">
|
||||
<h3 className="mb-2 text-sm font-semibold">자재 목록</h3>
|
||||
<Input
|
||||
placeholder="자재 검색..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-auto">
|
||||
{filteredMaterials.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center p-4 text-center text-sm text-gray-500">
|
||||
검색 결과가 없습니다
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-2">
|
||||
{filteredMaterials.map((material) => {
|
||||
const isPlaced = placements.some((p) => p.material_code === material.material_code);
|
||||
return (
|
||||
<button
|
||||
key={material.id}
|
||||
onClick={() => !isPlaced && handleMaterialClick(material)}
|
||||
disabled={isPlaced}
|
||||
className={`mb-2 w-full rounded-lg border p-3 text-left transition-all ${
|
||||
isPlaced
|
||||
? "cursor-not-allowed border-gray-200 bg-gray-50 opacity-50"
|
||||
: "cursor-pointer border-gray-200 bg-white hover:border-blue-500 hover:shadow-sm"
|
||||
}`}
|
||||
>
|
||||
<div className="mb-1 text-sm font-medium text-gray-900">{material.material_name}</div>
|
||||
<div className="text-xs text-gray-500">{material.material_code}</div>
|
||||
<div className="mt-1 text-xs text-gray-400">{material.category}</div>
|
||||
{isPlaced && <div className="mt-1 text-xs text-blue-600">배치됨</div>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
interface YardLayoutCreateModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onCreate: (name: string, description: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export default function YardLayoutCreateModal({ isOpen, onClose, onCreate }: YardLayoutCreateModalProps) {
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
// 생성 실행
|
||||
const handleCreate = async () => {
|
||||
if (!name.trim()) {
|
||||
setError("야드 이름을 입력하세요");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreating(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
await onCreate(name.trim(), description.trim());
|
||||
setName("");
|
||||
setDescription("");
|
||||
} catch (error: any) {
|
||||
console.error("야드 생성 실패:", error);
|
||||
setError(error.message || "야드 생성에 실패했습니다");
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 모달 닫기
|
||||
const handleClose = () => {
|
||||
if (isCreating) return;
|
||||
setName("");
|
||||
setDescription("");
|
||||
setError("");
|
||||
onClose();
|
||||
};
|
||||
|
||||
// Enter 키 처리
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleCreate();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleClose}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>새 야드 생성</DialogTitle>
|
||||
<DialogDescription>야드의 이름과 설명을 입력하세요</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{/* 야드 이름 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="yard-name">
|
||||
야드 이름 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="yard-name"
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
setError("");
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="예: A구역, 1번 야드"
|
||||
disabled={isCreating}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 설명 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="yard-description">설명</Label>
|
||||
<Textarea
|
||||
id="yard-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="야드에 대한 설명을 입력하세요 (선택사항)"
|
||||
rows={3}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 에러 메시지 */}
|
||||
{error && <div className="rounded-md bg-red-50 p-3 text-sm text-red-600">{error}</div>}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleClose} disabled={isCreating}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleCreate} disabled={!name.trim() || isCreating}>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
생성 중...
|
||||
</>
|
||||
) : (
|
||||
"생성"
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,277 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Search, MoreVertical, Loader2 } from "lucide-react";
|
||||
|
||||
interface YardLayout {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
placement_count: number;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface YardLayoutListProps {
|
||||
layouts: YardLayout[];
|
||||
isLoading: boolean;
|
||||
onSelect: (layout: YardLayout) => void;
|
||||
onDelete: (id: number) => Promise<void>;
|
||||
onDuplicate: (id: number, newName: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export default function YardLayoutList({ layouts, isLoading, onSelect, onDelete, onDuplicate }: YardLayoutListProps) {
|
||||
const [searchText, setSearchText] = useState("");
|
||||
const [sortOrder, setSortOrder] = useState<"recent" | "name">("recent");
|
||||
const [deleteTarget, setDeleteTarget] = useState<YardLayout | null>(null);
|
||||
const [duplicateTarget, setDuplicateTarget] = useState<YardLayout | null>(null);
|
||||
const [duplicateName, setDuplicateName] = useState("");
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isDuplicating, setIsDuplicating] = useState(false);
|
||||
|
||||
// 검색 필터링
|
||||
const filteredLayouts = layouts.filter((layout) => {
|
||||
if (!searchText) return true;
|
||||
return (
|
||||
layout.name.toLowerCase().includes(searchText.toLowerCase()) ||
|
||||
layout.description?.toLowerCase().includes(searchText.toLowerCase())
|
||||
);
|
||||
});
|
||||
|
||||
// 정렬
|
||||
const sortedLayouts = [...filteredLayouts].sort((a, b) => {
|
||||
if (sortOrder === "recent") {
|
||||
return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime();
|
||||
} else {
|
||||
return a.name.localeCompare(b.name);
|
||||
}
|
||||
});
|
||||
|
||||
// 날짜 포맷팅
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleString("ko-KR", {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
};
|
||||
|
||||
// 삭제 확인
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!deleteTarget) return;
|
||||
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
await onDelete(deleteTarget.id);
|
||||
setDeleteTarget(null);
|
||||
} catch (error) {
|
||||
console.error("삭제 실패:", error);
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 복제 실행
|
||||
const handleDuplicateConfirm = async () => {
|
||||
if (!duplicateTarget || !duplicateName.trim()) return;
|
||||
|
||||
setIsDuplicating(true);
|
||||
try {
|
||||
await onDuplicate(duplicateTarget.id, duplicateName);
|
||||
setDuplicateTarget(null);
|
||||
setDuplicateName("");
|
||||
} catch (error) {
|
||||
console.error("복제 실패:", error);
|
||||
} finally {
|
||||
setIsDuplicating(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 복제 모달 열기
|
||||
const handleDuplicateClick = (layout: YardLayout) => {
|
||||
setDuplicateTarget(layout);
|
||||
setDuplicateName(`${layout.name} (복사본)`);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-gray-400" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col space-y-4">
|
||||
{/* 검색 및 정렬 */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<Input
|
||||
placeholder="야드 이름 또는 설명 검색..."
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
value={sortOrder}
|
||||
onChange={(e) => setSortOrder(e.target.value as "recent" | "name")}
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="recent">최근 수정순</option>
|
||||
<option value="name">이름순</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* 테이블 */}
|
||||
{sortedLayouts.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="text-center text-gray-500">
|
||||
{searchText ? "검색 결과가 없습니다" : "등록된 야드가 없습니다"}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 overflow-auto rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>야드명</TableHead>
|
||||
<TableHead>설명</TableHead>
|
||||
<TableHead className="text-center">배치 자재</TableHead>
|
||||
<TableHead>최종 수정</TableHead>
|
||||
<TableHead className="w-[80px] text-center">작업</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sortedLayouts.map((layout) => (
|
||||
<TableRow key={layout.id} className="cursor-pointer hover:bg-gray-50" onClick={() => onSelect(layout)}>
|
||||
<TableCell className="font-medium">{layout.name}</TableCell>
|
||||
<TableCell className="text-gray-600">{layout.description || "-"}</TableCell>
|
||||
<TableCell className="text-center">{layout.placement_count}개</TableCell>
|
||||
<TableCell className="text-sm text-gray-500">{formatDate(layout.updated_at)}</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => onSelect(layout)}>편집</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleDuplicateClick(layout)}>복제</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setDeleteTarget(layout)} className="text-red-600">
|
||||
삭제
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 총 개수 */}
|
||||
<div className="text-sm text-gray-500">총 {sortedLayouts.length}개</div>
|
||||
|
||||
{/* 삭제 확인 모달 */}
|
||||
<AlertDialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>야드 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
정말로 "{deleteTarget?.name}" 야드를 삭제하시겠습니까?
|
||||
<br />
|
||||
배치된 자재 정보도 함께 삭제됩니다.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteConfirm}
|
||||
disabled={isDeleting}
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
삭제 중...
|
||||
</>
|
||||
) : (
|
||||
"삭제"
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* 복제 모달 */}
|
||||
<Dialog open={!!duplicateTarget} onOpenChange={() => setDuplicateTarget(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>야드 복제</DialogTitle>
|
||||
<DialogDescription>새로운 야드의 이름을 입력하세요</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="duplicate-name">야드 이름</Label>
|
||||
<Input
|
||||
id="duplicate-name"
|
||||
value={duplicateName}
|
||||
onChange={(e) => setDuplicateName(e.target.value)}
|
||||
placeholder="야드 이름을 입력하세요"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDuplicateTarget(null)} disabled={isDuplicating}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleDuplicateConfirm} disabled={!duplicateName.trim() || isDuplicating}>
|
||||
{isDuplicating ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
복제 중...
|
||||
</>
|
||||
) : (
|
||||
"복제"
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,12 +1,13 @@
|
|||
"use client";
|
||||
|
||||
import React, { useState, useEffect, useCallback } from "react";
|
||||
import React, { useState, useEffect, useCallback, useMemo } from "react";
|
||||
import { DashboardElement, QueryResult } from "@/components/admin/dashboard/types";
|
||||
import { ChartRenderer } from "@/components/admin/dashboard/charts/ChartRenderer";
|
||||
import { DashboardProvider } from "@/contexts/DashboardContext";
|
||||
import { RESOLUTIONS, Resolution } from "@/components/admin/dashboard/ResolutionSelector";
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
// 위젯 동적 import - 모든 위젯
|
||||
const ListSummaryWidget = dynamic(() => import("./widgets/ListSummaryWidget"), { ssr: false });
|
||||
const MapSummaryWidget = dynamic(() => import("./widgets/MapSummaryWidget"), { ssr: false });
|
||||
const StatusSummaryWidget = dynamic(() => import("./widgets/StatusSummaryWidget"), { ssr: false });
|
||||
const RiskAlertWidget = dynamic(() => import("./widgets/RiskAlertWidget"), { ssr: false });
|
||||
|
|
@ -25,7 +26,22 @@ const DocumentWidget = dynamic(() => import("./widgets/DocumentWidget"), { ssr:
|
|||
const BookingAlertWidget = dynamic(() => import("./widgets/BookingAlertWidget"), { ssr: false });
|
||||
const MaintenanceWidget = dynamic(() => import("./widgets/MaintenanceWidget"), { ssr: false });
|
||||
const CalculatorWidget = dynamic(() => import("./widgets/CalculatorWidget"), { ssr: false });
|
||||
const CalendarWidget = dynamic(() => import("@/components/admin/dashboard/widgets/CalendarWidget").then(mod => ({ default: mod.CalendarWidget })), { ssr: false });
|
||||
const CalendarWidget = dynamic(
|
||||
() => import("@/components/admin/dashboard/widgets/CalendarWidget").then((mod) => ({ default: mod.CalendarWidget })),
|
||||
{ ssr: false },
|
||||
);
|
||||
const ClockWidget = dynamic(
|
||||
() => import("@/components/admin/dashboard/widgets/ClockWidget").then((mod) => ({ default: mod.ClockWidget })),
|
||||
{ ssr: false },
|
||||
);
|
||||
const ListWidget = dynamic(
|
||||
() => import("@/components/admin/dashboard/widgets/ListWidget").then((mod) => ({ default: mod.ListWidget })),
|
||||
{ ssr: false },
|
||||
);
|
||||
|
||||
const YardManagement3DWidget = dynamic(() => import("@/components/admin/dashboard/widgets/YardManagement3DWidget"), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* 위젯 렌더링 함수 - DashboardSidebar의 모든 subtype 처리
|
||||
|
|
@ -43,18 +59,9 @@ function renderWidget(element: DashboardElement) {
|
|||
case "calculator":
|
||||
return <CalculatorWidget element={element} />;
|
||||
case "clock":
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-blue-400 to-purple-600 p-4 text-white">
|
||||
<div className="text-center">
|
||||
<div className="mb-2 text-3xl">⏰</div>
|
||||
<div className="text-sm">시계 위젯 (개발 예정)</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return <ClockWidget element={element} />;
|
||||
case "map-summary":
|
||||
return <MapSummaryWidget element={element} />;
|
||||
case "list-summary":
|
||||
return <ListSummaryWidget element={element} />;
|
||||
case "risk-alert":
|
||||
return <RiskAlertWidget element={element} />;
|
||||
case "calendar":
|
||||
|
|
@ -68,31 +75,34 @@ function renderWidget(element: DashboardElement) {
|
|||
case "booking-alert":
|
||||
return <BookingAlertWidget element={element} />;
|
||||
case "maintenance":
|
||||
return <MaintenanceWidget element={element} />;
|
||||
return <MaintenanceWidget />;
|
||||
case "document":
|
||||
return <DocumentWidget element={element} />;
|
||||
case "list":
|
||||
return <ListSummaryWidget element={element} />;
|
||||
return <ListWidget element={element} />;
|
||||
|
||||
case "yard-management-3d":
|
||||
return <YardManagement3DWidget isEditMode={false} config={element.yardConfig} />;
|
||||
|
||||
// === 차량 관련 (추가 위젯) ===
|
||||
case "vehicle-status":
|
||||
return <VehicleStatusWidget />;
|
||||
return <VehicleStatusWidget element={element} />;
|
||||
case "vehicle-list":
|
||||
return <VehicleListWidget />;
|
||||
return <VehicleListWidget element={element} />;
|
||||
case "vehicle-map":
|
||||
return <VehicleMapOnlyWidget element={element} />;
|
||||
|
||||
// === 배송 관련 (추가 위젯) ===
|
||||
case "delivery-status":
|
||||
return <DeliveryStatusWidget />;
|
||||
return <DeliveryStatusWidget element={element} />;
|
||||
case "delivery-status-summary":
|
||||
return <DeliveryStatusSummaryWidget />;
|
||||
return <DeliveryStatusSummaryWidget element={element} />;
|
||||
case "delivery-today-stats":
|
||||
return <DeliveryTodayStatsWidget />;
|
||||
return <DeliveryTodayStatsWidget element={element} />;
|
||||
case "cargo-list":
|
||||
return <CargoListWidget />;
|
||||
return <CargoListWidget element={element} />;
|
||||
case "customer-issues":
|
||||
return <CustomerIssuesWidget />;
|
||||
return <CustomerIssuesWidget element={element} />;
|
||||
|
||||
// === 기본 fallback ===
|
||||
default:
|
||||
|
|
@ -109,20 +119,41 @@ function renderWidget(element: DashboardElement) {
|
|||
|
||||
interface DashboardViewerProps {
|
||||
elements: DashboardElement[];
|
||||
dashboardId: string;
|
||||
dashboardId?: string;
|
||||
refreshInterval?: number; // 전체 대시보드 새로고침 간격 (ms)
|
||||
backgroundColor?: string; // 배경색
|
||||
resolution?: string; // 대시보드 해상도
|
||||
}
|
||||
|
||||
/**
|
||||
* 대시보드 뷰어 컴포넌트
|
||||
* - 저장된 대시보드를 읽기 전용으로 표시
|
||||
* - 실시간 데이터 업데이트
|
||||
* - 반응형 레이아웃
|
||||
* - 편집 화면과 동일한 레이아웃 (중앙 정렬, 고정 크기)
|
||||
*/
|
||||
export function DashboardViewer({ elements, dashboardId, refreshInterval }: DashboardViewerProps) {
|
||||
export function DashboardViewer({
|
||||
elements,
|
||||
dashboardId,
|
||||
refreshInterval,
|
||||
backgroundColor = "#f9fafb",
|
||||
resolution = "fhd",
|
||||
}: DashboardViewerProps) {
|
||||
const [elementData, setElementData] = useState<Record<string, QueryResult>>({});
|
||||
const [loadingElements, setLoadingElements] = useState<Set<string>>(new Set());
|
||||
const [lastRefresh, setLastRefresh] = useState<Date>(new Date());
|
||||
|
||||
// 캔버스 설정 계산
|
||||
const canvasConfig = useMemo(() => {
|
||||
return RESOLUTIONS[resolution as Resolution] || RESOLUTIONS.fhd;
|
||||
}, [resolution]);
|
||||
|
||||
// 캔버스 높이 동적 계산
|
||||
const canvasHeight = useMemo(() => {
|
||||
if (elements.length === 0) {
|
||||
return canvasConfig.height;
|
||||
}
|
||||
const maxBottomY = Math.max(...elements.map((el) => el.position.y + el.size.height));
|
||||
return Math.max(canvasConfig.height, maxBottomY + 100);
|
||||
}, [elements, canvasConfig.height]);
|
||||
|
||||
// 개별 요소 데이터 로딩
|
||||
const loadElementData = useCallback(async (element: DashboardElement) => {
|
||||
|
|
@ -176,7 +207,7 @@ export function DashboardViewer({ elements, dashboardId, refreshInterval }: Dash
|
|||
[element.id]: data,
|
||||
}));
|
||||
}
|
||||
} catch (error) {
|
||||
} catch {
|
||||
// 에러 발생 시 무시 (차트는 빈 상태로 표시됨)
|
||||
} finally {
|
||||
setLoadingElements((prev) => {
|
||||
|
|
@ -189,8 +220,6 @@ export function DashboardViewer({ elements, dashboardId, refreshInterval }: Dash
|
|||
|
||||
// 모든 요소 데이터 로딩
|
||||
const loadAllData = useCallback(async () => {
|
||||
setLastRefresh(new Date());
|
||||
|
||||
const chartElements = elements.filter((el) => el.type === "chart" && el.dataSource?.query);
|
||||
|
||||
// 병렬로 모든 차트 데이터 로딩
|
||||
|
|
@ -226,28 +255,32 @@ export function DashboardViewer({ elements, dashboardId, refreshInterval }: Dash
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="relative h-full w-full overflow-auto bg-gray-100">
|
||||
{/* 새로고침 상태 표시 */}
|
||||
<div className="text-muted-foreground absolute top-4 right-4 z-10 rounded-lg bg-white px-3 py-2 text-xs shadow-sm">
|
||||
마지막 업데이트: {lastRefresh.toLocaleTimeString()}
|
||||
{Array.from(loadingElements).length > 0 && (
|
||||
<span className="text-primary ml-2">({Array.from(loadingElements).length}개 로딩 중...)</span>
|
||||
)}
|
||||
<DashboardProvider>
|
||||
{/* overflow-auto 제거 - 외부 페이지 스크롤 사용 */}
|
||||
<div className="flex h-full items-start justify-center bg-gray-100 p-8">
|
||||
{/* 고정 크기 캔버스 (편집 화면과 동일한 레이아웃) */}
|
||||
<div
|
||||
className="relative overflow-hidden rounded-lg"
|
||||
style={{
|
||||
width: `${canvasConfig.width}px`,
|
||||
minHeight: `${canvasConfig.height}px`,
|
||||
height: `${canvasHeight}px`,
|
||||
backgroundColor: backgroundColor,
|
||||
}}
|
||||
>
|
||||
{/* 대시보드 요소들 */}
|
||||
{elements.map((element) => (
|
||||
<ViewerElement
|
||||
key={element.id}
|
||||
element={element}
|
||||
data={elementData[element.id]}
|
||||
isLoading={loadingElements.has(element.id)}
|
||||
onRefresh={() => loadElementData(element)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 대시보드 요소들 */}
|
||||
<div className="relative" style={{ minHeight: "100%" }}>
|
||||
{elements.map((element) => (
|
||||
<ViewerElement
|
||||
key={element.id}
|
||||
element={element}
|
||||
data={elementData[element.id]}
|
||||
isLoading={loadingElements.has(element.id)}
|
||||
onRefresh={() => loadElementData(element)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</DashboardProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -276,16 +309,18 @@ function ViewerElement({ element, data, isLoading, onRefresh }: ViewerElementPro
|
|||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
>
|
||||
{/* 헤더 */}
|
||||
<div className="flex items-center justify-between border-b border-gray-200 bg-gray-50 px-4 py-3">
|
||||
<h3 className="text-sm font-semibold text-gray-800">{element.title}</h3>
|
||||
{/* 헤더 (showHeader가 false가 아닐 때만 표시) */}
|
||||
{element.showHeader !== false && (
|
||||
<div className="flex items-center justify-between border-b border-gray-200 bg-gray-50 px-4 py-3">
|
||||
<h3 className="text-sm font-semibold text-gray-800">{element.customTitle || element.title}</h3>
|
||||
|
||||
{/* 새로고침 버튼 (호버 시에만 표시) */}
|
||||
{isHovered && (
|
||||
{/* 새로고침 버튼 (항상 렌더링하되 opacity로 제어) */}
|
||||
<button
|
||||
onClick={onRefresh}
|
||||
disabled={isLoading}
|
||||
className="hover:text-muted-foreground text-gray-400 disabled:opacity-50"
|
||||
className={`hover:text-muted-foreground text-gray-400 transition-opacity disabled:opacity-50 ${
|
||||
isHovered ? "opacity-100" : "opacity-0"
|
||||
}`}
|
||||
title="새로고침"
|
||||
>
|
||||
{isLoading ? (
|
||||
|
|
@ -294,14 +329,16 @@ function ViewerElement({ element, data, isLoading, onRefresh }: ViewerElementPro
|
|||
"🔄"
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 내용 */}
|
||||
<div className="h-[calc(100%-57px)]">
|
||||
<div className={element.showHeader !== false ? "h-[calc(100%-57px)]" : "h-full"}>
|
||||
{element.type === "chart" ? (
|
||||
<ChartRenderer element={element} data={data} width={element.size.width} height={element.size.height - 57} />
|
||||
) : renderWidget(element)}
|
||||
) : (
|
||||
renderWidget(element)
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 로딩 오버레이 */}
|
||||
|
|
@ -316,87 +353,3 @@ function ViewerElement({ element, data, isLoading, onRefresh }: ViewerElementPro
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 샘플 쿼리 결과 생성 함수 (뷰어용)
|
||||
*/
|
||||
function generateSampleQueryResult(query: string, chartType: string): QueryResult {
|
||||
// 시간에 따라 약간씩 다른 데이터 생성 (실시간 업데이트 시뮬레이션)
|
||||
const timeVariation = Math.sin(Date.now() / 10000) * 0.1 + 1;
|
||||
|
||||
const isMonthly = query.toLowerCase().includes("month");
|
||||
const isSales = query.toLowerCase().includes("sales") || query.toLowerCase().includes("매출");
|
||||
const isUsers = query.toLowerCase().includes("users") || query.toLowerCase().includes("사용자");
|
||||
const isProducts = query.toLowerCase().includes("product") || query.toLowerCase().includes("상품");
|
||||
const isWeekly = query.toLowerCase().includes("week");
|
||||
|
||||
let columns: string[];
|
||||
let rows: Record<string, any>[];
|
||||
|
||||
if (isMonthly && isSales) {
|
||||
columns = ["month", "sales", "order_count"];
|
||||
rows = [
|
||||
{ month: "2024-01", sales: Math.round(1200000 * timeVariation), order_count: Math.round(45 * timeVariation) },
|
||||
{ month: "2024-02", sales: Math.round(1350000 * timeVariation), order_count: Math.round(52 * timeVariation) },
|
||||
{ month: "2024-03", sales: Math.round(1180000 * timeVariation), order_count: Math.round(41 * timeVariation) },
|
||||
{ month: "2024-04", sales: Math.round(1420000 * timeVariation), order_count: Math.round(58 * timeVariation) },
|
||||
{ month: "2024-05", sales: Math.round(1680000 * timeVariation), order_count: Math.round(67 * timeVariation) },
|
||||
{ month: "2024-06", sales: Math.round(1540000 * timeVariation), order_count: Math.round(61 * timeVariation) },
|
||||
];
|
||||
} else if (isWeekly && isUsers) {
|
||||
columns = ["week", "new_users"];
|
||||
rows = [
|
||||
{ week: "2024-W10", new_users: Math.round(23 * timeVariation) },
|
||||
{ week: "2024-W11", new_users: Math.round(31 * timeVariation) },
|
||||
{ week: "2024-W12", new_users: Math.round(28 * timeVariation) },
|
||||
{ week: "2024-W13", new_users: Math.round(35 * timeVariation) },
|
||||
{ week: "2024-W14", new_users: Math.round(42 * timeVariation) },
|
||||
{ week: "2024-W15", new_users: Math.round(38 * timeVariation) },
|
||||
];
|
||||
} else if (isProducts) {
|
||||
columns = ["product_name", "total_sold", "revenue"];
|
||||
rows = [
|
||||
{
|
||||
product_name: "스마트폰",
|
||||
total_sold: Math.round(156 * timeVariation),
|
||||
revenue: Math.round(234000000 * timeVariation),
|
||||
},
|
||||
{
|
||||
product_name: "노트북",
|
||||
total_sold: Math.round(89 * timeVariation),
|
||||
revenue: Math.round(178000000 * timeVariation),
|
||||
},
|
||||
{
|
||||
product_name: "태블릿",
|
||||
total_sold: Math.round(134 * timeVariation),
|
||||
revenue: Math.round(67000000 * timeVariation),
|
||||
},
|
||||
{
|
||||
product_name: "이어폰",
|
||||
total_sold: Math.round(267 * timeVariation),
|
||||
revenue: Math.round(26700000 * timeVariation),
|
||||
},
|
||||
{
|
||||
product_name: "스마트워치",
|
||||
total_sold: Math.round(98 * timeVariation),
|
||||
revenue: Math.round(49000000 * timeVariation),
|
||||
},
|
||||
];
|
||||
} else {
|
||||
columns = ["category", "value", "count"];
|
||||
rows = [
|
||||
{ category: "A", value: Math.round(100 * timeVariation), count: Math.round(10 * timeVariation) },
|
||||
{ category: "B", value: Math.round(150 * timeVariation), count: Math.round(15 * timeVariation) },
|
||||
{ category: "C", value: Math.round(120 * timeVariation), count: Math.round(12 * timeVariation) },
|
||||
{ category: "D", value: Math.round(180 * timeVariation), count: Math.round(18 * timeVariation) },
|
||||
{ category: "E", value: Math.round(90 * timeVariation), count: Math.round(9 * timeVariation) },
|
||||
];
|
||||
}
|
||||
|
||||
return {
|
||||
columns,
|
||||
rows,
|
||||
totalRows: rows.length,
|
||||
executionTime: Math.floor(Math.random() * 100) + 50,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -161,7 +161,7 @@ export default function BookingAlertWidget({ element }: BookingAlertWidgetProps)
|
|||
<div className="border-b border-gray-200 bg-white px-4 py-3">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-lg font-bold text-gray-800">🔔 {element?.customTitle || "예약 요청 알림"}</h3>
|
||||
<h3 className="text-lg font-bold text-gray-800">{element?.customTitle || "예약 요청 알림"}</h3>
|
||||
{newCount > 0 && (
|
||||
<span className="flex h-6 w-6 items-center justify-center rounded-full bg-red-500 text-xs font-bold text-white">
|
||||
{newCount}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
* - 대시보드 위젯으로 사용 가능
|
||||
*/
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DashboardElement } from '@/components/admin/dashboard/types';
|
||||
|
||||
|
|
@ -117,11 +117,62 @@ export default function CalculatorWidget({ element, className = '' }: Calculator
|
|||
setDisplay(String(value / 100));
|
||||
};
|
||||
|
||||
// 키보드 입력 처리
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
const key = event.key;
|
||||
|
||||
// 숫자 키 (0-9)
|
||||
if (/^[0-9]$/.test(key)) {
|
||||
event.preventDefault();
|
||||
handleNumber(key);
|
||||
}
|
||||
// 연산자 키
|
||||
else if (key === '+' || key === '-' || key === '*' || key === '/') {
|
||||
event.preventDefault();
|
||||
handleOperation(key);
|
||||
}
|
||||
// 소수점
|
||||
else if (key === '.') {
|
||||
event.preventDefault();
|
||||
handleDecimal();
|
||||
}
|
||||
// Enter 또는 = (계산)
|
||||
else if (key === 'Enter' || key === '=') {
|
||||
event.preventDefault();
|
||||
handleEquals();
|
||||
}
|
||||
// Escape 또는 c (초기화)
|
||||
else if (key === 'Escape' || key.toLowerCase() === 'c') {
|
||||
event.preventDefault();
|
||||
handleClear();
|
||||
}
|
||||
// Backspace (지우기)
|
||||
else if (key === 'Backspace') {
|
||||
event.preventDefault();
|
||||
handleBackspace();
|
||||
}
|
||||
// % (퍼센트)
|
||||
else if (key === '%') {
|
||||
event.preventDefault();
|
||||
handlePercent();
|
||||
}
|
||||
};
|
||||
|
||||
// 이벤트 리스너 등록
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
|
||||
// 클린업
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [display, previousValue, operation, waitingForOperand]);
|
||||
|
||||
return (
|
||||
<div className={`h-full w-full p-3 bg-gradient-to-br from-slate-50 to-gray-100 ${className}`}>
|
||||
<div className="h-full flex flex-col gap-2">
|
||||
{/* 제목 */}
|
||||
<h3 className="text-base font-semibold text-gray-900 text-center">🧮 {element?.customTitle || "계산기"}</h3>
|
||||
<h3 className="text-base font-semibold text-gray-900 text-center">{element?.customTitle || "계산기"}</h3>
|
||||
|
||||
{/* 디스플레이 */}
|
||||
<div className="bg-white border-2 border-gray-200 rounded-lg p-4 shadow-inner min-h-[80px]">
|
||||
|
|
|
|||
|
|
@ -150,7 +150,7 @@ export default function CustomerIssuesWidget({ element }: CustomerIssuesWidgetPr
|
|||
<div className="flex h-full flex-col overflow-hidden bg-background p-4">
|
||||
{/* 헤더 */}
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-foreground">⚠️ 고객 클레임/이슈</h3>
|
||||
<h3 className="text-lg font-semibold text-foreground">고객 클레임/이슈</h3>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="rounded-full p-1 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
||||
|
|
|
|||
|
|
@ -130,7 +130,7 @@ export default function DeliveryTodayStatsWidget({ element }: DeliveryTodayStats
|
|||
<div className="flex h-full flex-col overflow-hidden bg-white p-4">
|
||||
{/* 헤더 */}
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-gray-800">📅 오늘 처리 현황</h3>
|
||||
<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"
|
||||
|
|
|
|||
|
|
@ -132,7 +132,7 @@ export default function DocumentWidget({ element }: DocumentWidgetProps) {
|
|||
{/* 헤더 */}
|
||||
<div className="border-b border-gray-200 bg-white px-4 py-3">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h3 className="text-lg font-bold text-gray-800">📂 {element?.customTitle || "문서 관리"}</h3>
|
||||
<h3 className="text-lg font-bold text-gray-800">{element?.customTitle || "문서 관리"}</h3>
|
||||
<button className="rounded-lg bg-primary px-3 py-1.5 text-sm text-white transition-colors hover:bg-primary/90">
|
||||
+ 업로드
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -135,11 +135,11 @@ export default function ExchangeWidget({
|
|||
const hasError = error || !exchangeRate;
|
||||
|
||||
return (
|
||||
<div className="h-full bg-gradient-to-br from-green-50 to-emerald-50 rounded-lg border p-4">
|
||||
<div className="h-full bg-gradient-to-br from-green-50 to-emerald-50 rounded-lg border p-4 @container">
|
||||
{/* 헤더 */}
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex-1">
|
||||
<h3 className="text-base font-semibold text-gray-900 mb-1">💱 {element?.customTitle || "환율"}</h3>
|
||||
<h3 className="text-base font-semibold text-gray-900 mb-1">{element?.customTitle || "환율"}</h3>
|
||||
<p className="text-xs text-gray-500">
|
||||
{lastUpdated
|
||||
? `업데이트: ${lastUpdated.toLocaleTimeString('ko-KR', {
|
||||
|
|
@ -160,10 +160,10 @@ export default function ExchangeWidget({
|
|||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 통화 선택 */}
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
{/* 통화 선택 - 반응형 (좁을 때 세로 배치) */}
|
||||
<div className="flex @[300px]:flex-row flex-col items-center gap-2 mb-3">
|
||||
<Select value={base} onValueChange={setBase}>
|
||||
<SelectTrigger className="flex-1 bg-white h-8 text-xs">
|
||||
<SelectTrigger className="w-full @[300px]:flex-1 bg-white h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
|
|
@ -179,13 +179,13 @@ export default function ExchangeWidget({
|
|||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleSwap}
|
||||
className="h-8 w-8 p-0 rounded-full hover:bg-white"
|
||||
className="h-8 w-8 p-0 rounded-full hover:bg-white @[300px]:rotate-0 rotate-90"
|
||||
>
|
||||
<ArrowRightLeft className="h-3 w-3" />
|
||||
</Button>
|
||||
|
||||
<Select value={target} onValueChange={setTarget}>
|
||||
<SelectTrigger className="flex-1 bg-white h-8 text-xs">
|
||||
<SelectTrigger className="w-full @[300px]:flex-1 bg-white h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
|
|
|
|||
|
|
@ -158,7 +158,7 @@ export default function MapSummaryWidget({ element }: MapSummaryWidgetProps) {
|
|||
{/* 헤더 */}
|
||||
<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">📍 {displayTitle}</h3>
|
||||
<h3 className="text-sm font-bold text-gray-900">{displayTitle}</h3>
|
||||
{element?.dataSource?.query ? (
|
||||
<p className="text-xs text-gray-500">총 {markers.length.toLocaleString()}개 마커</p>
|
||||
) : (
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
"use client";
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Plus, Check, X, Clock, AlertCircle, GripVertical, ChevronDown } from "lucide-react";
|
||||
import { Plus, Check, X, Clock, AlertCircle, GripVertical, ChevronDown, Calendar as CalendarIcon } from "lucide-react";
|
||||
import { DashboardElement } from "@/components/admin/dashboard/types";
|
||||
import { useDashboard } from "@/contexts/DashboardContext";
|
||||
|
||||
interface TodoItem {
|
||||
id: string;
|
||||
|
|
@ -33,6 +34,9 @@ interface TodoWidgetProps {
|
|||
}
|
||||
|
||||
export default function TodoWidget({ element }: TodoWidgetProps) {
|
||||
// Context에서 선택된 날짜 가져오기
|
||||
const { selectedDate } = useDashboard();
|
||||
|
||||
const [todos, setTodos] = useState<TodoItem[]>([]);
|
||||
const [stats, setStats] = useState<TodoStats | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
|
@ -51,22 +55,85 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
|
|||
fetchTodos();
|
||||
const interval = setInterval(fetchTodos, 30000); // 30초마다 갱신
|
||||
return () => clearInterval(interval);
|
||||
}, [filter]);
|
||||
}, [filter, selectedDate]); // selectedDate도 의존성에 추가
|
||||
|
||||
const fetchTodos = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem("authToken");
|
||||
const filterParam = filter !== "all" ? `?status=${filter}` : "";
|
||||
const response = await fetch(`http://localhost:9771/api/todos${filterParam}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
const userLang = localStorage.getItem("userLang") || "KR";
|
||||
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
setTodos(result.data || []);
|
||||
setStats(result.stats);
|
||||
// 외부 DB 조회 (dataSource가 설정된 경우)
|
||||
if (element?.dataSource?.query) {
|
||||
// console.log("🔍 TodoWidget - 외부 DB 조회 시작");
|
||||
// console.log("📝 Query:", element.dataSource.query);
|
||||
// console.log("🔗 ConnectionId:", element.dataSource.externalConnectionId);
|
||||
// console.log("🔗 ConnectionType:", element.dataSource.connectionType);
|
||||
|
||||
// 현재 DB vs 외부 DB 분기
|
||||
const apiUrl = element.dataSource.connectionType === "external" && element.dataSource.externalConnectionId
|
||||
? `http://localhost:9771/api/external-db/query?userLang=${userLang}`
|
||||
: `http://localhost:9771/api/dashboards/execute-query?userLang=${userLang}`;
|
||||
|
||||
const requestBody = element.dataSource.connectionType === "external" && element.dataSource.externalConnectionId
|
||||
? {
|
||||
connectionId: parseInt(element.dataSource.externalConnectionId),
|
||||
query: element.dataSource.query,
|
||||
}
|
||||
: {
|
||||
query: element.dataSource.query,
|
||||
};
|
||||
|
||||
// console.log("🌐 API URL:", apiUrl);
|
||||
// console.log("📦 Request Body:", requestBody);
|
||||
|
||||
const response = await fetch(apiUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
// console.log("📡 Response status:", response.status);
|
||||
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
// console.log("✅ API 응답:", result);
|
||||
// console.log("📦 result.data:", result.data);
|
||||
// console.log("📦 result.data.rows:", result.data?.rows);
|
||||
|
||||
// API 응답 형식에 따라 데이터 추출
|
||||
const rows = result.data?.rows || result.data || [];
|
||||
// console.log("📊 추출된 rows:", rows);
|
||||
|
||||
const externalTodos = mapExternalDataToTodos(rows);
|
||||
// console.log("📋 변환된 Todos:", externalTodos);
|
||||
// console.log("📋 변환된 Todos 개수:", externalTodos.length);
|
||||
|
||||
setTodos(externalTodos);
|
||||
setStats(calculateStatsFromTodos(externalTodos));
|
||||
|
||||
// console.log("✅ setTodos, setStats 호출 완료!");
|
||||
} else {
|
||||
const errorText = await response.text();
|
||||
// console.error("❌ API 오류:", errorText);
|
||||
}
|
||||
}
|
||||
// 내장 API 조회 (기본)
|
||||
else {
|
||||
const filterParam = filter !== "all" ? `?status=${filter}` : "";
|
||||
const response = await fetch(`http://localhost:9771/api/todos${filterParam}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
setTodos(result.data || []);
|
||||
setStats(result.stats);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// console.error("To-Do 로딩 오류:", error);
|
||||
|
|
@ -75,8 +142,48 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
|
|||
}
|
||||
};
|
||||
|
||||
// 외부 DB 데이터를 TodoItem 형식으로 변환
|
||||
const mapExternalDataToTodos = (data: any[]): TodoItem[] => {
|
||||
return data.map((row, index) => ({
|
||||
id: row.id || `todo-${index}`,
|
||||
title: row.title || row.task || row.name || "제목 없음",
|
||||
description: row.description || row.desc || row.content,
|
||||
priority: row.priority || "normal",
|
||||
status: row.status || "pending",
|
||||
assignedTo: row.assigned_to || row.assignedTo || row.user,
|
||||
dueDate: row.due_date || row.dueDate || row.deadline,
|
||||
createdAt: row.created_at || row.createdAt || new Date().toISOString(),
|
||||
updatedAt: row.updated_at || row.updatedAt || new Date().toISOString(),
|
||||
completedAt: row.completed_at || row.completedAt,
|
||||
isUrgent: row.is_urgent || row.isUrgent || row.urgent || false,
|
||||
order: row.display_order || row.order || index,
|
||||
}));
|
||||
};
|
||||
|
||||
// Todo 배열로부터 통계 계산
|
||||
const calculateStatsFromTodos = (todoList: TodoItem[]): TodoStats => {
|
||||
return {
|
||||
total: todoList.length,
|
||||
pending: todoList.filter((t) => t.status === "pending").length,
|
||||
inProgress: todoList.filter((t) => t.status === "in_progress").length,
|
||||
completed: todoList.filter((t) => t.status === "completed").length,
|
||||
urgent: todoList.filter((t) => t.isUrgent).length,
|
||||
overdue: todoList.filter((t) => {
|
||||
if (!t.dueDate) return false;
|
||||
return new Date(t.dueDate) < new Date() && t.status !== "completed";
|
||||
}).length,
|
||||
};
|
||||
};
|
||||
|
||||
// 외부 DB 조회 여부 확인
|
||||
const isExternalData = !!element?.dataSource?.query;
|
||||
|
||||
const handleAddTodo = async () => {
|
||||
if (!newTodo.title.trim()) return;
|
||||
if (isExternalData) {
|
||||
alert("외부 데이터베이스 조회 모드에서는 추가할 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem("authToken");
|
||||
|
|
@ -185,6 +292,27 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
|
|||
return "⚠️ 오늘 마감";
|
||||
};
|
||||
|
||||
// 선택된 날짜로 필터링
|
||||
const filteredTodos = selectedDate
|
||||
? todos.filter((todo) => {
|
||||
if (!todo.dueDate) return false;
|
||||
const todoDate = new Date(todo.dueDate);
|
||||
return (
|
||||
todoDate.getFullYear() === selectedDate.getFullYear() &&
|
||||
todoDate.getMonth() === selectedDate.getMonth() &&
|
||||
todoDate.getDate() === selectedDate.getDate()
|
||||
);
|
||||
})
|
||||
: todos;
|
||||
|
||||
const formatSelectedDate = () => {
|
||||
if (!selectedDate) return null;
|
||||
const year = selectedDate.getFullYear();
|
||||
const month = selectedDate.getMonth() + 1;
|
||||
const day = selectedDate.getDate();
|
||||
return `${year}년 ${month}월 ${day}일`;
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
|
|
@ -195,59 +323,71 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
|
|||
|
||||
return (
|
||||
<div className="flex h-full flex-col bg-gradient-to-br from-slate-50 to-blue-50">
|
||||
{/* 헤더 */}
|
||||
<div className="border-b border-gray-200 bg-white px-4 py-3">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h3 className="text-lg font-bold text-gray-800">✅ {element?.customTitle || "To-Do / 긴급 지시"}</h3>
|
||||
<button
|
||||
onClick={() => setShowAddForm(!showAddForm)}
|
||||
className="flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-sm text-white transition-colors hover:bg-primary/90"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
추가
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 통계 */}
|
||||
{stats && (
|
||||
<div className="grid grid-cols-4 gap-2 text-xs">
|
||||
<div className="rounded bg-blue-50 px-2 py-1.5 text-center">
|
||||
<div className="font-bold text-blue-700">{stats.pending}</div>
|
||||
<div className="text-blue-600">대기</div>
|
||||
</div>
|
||||
<div className="rounded bg-amber-50 px-2 py-1.5 text-center">
|
||||
<div className="font-bold text-amber-700">{stats.inProgress}</div>
|
||||
<div className="text-amber-600">진행중</div>
|
||||
</div>
|
||||
<div className="rounded bg-red-50 px-2 py-1.5 text-center">
|
||||
<div className="font-bold text-red-700">{stats.urgent}</div>
|
||||
<div className="text-red-600">긴급</div>
|
||||
</div>
|
||||
<div className="rounded bg-rose-50 px-2 py-1.5 text-center">
|
||||
<div className="font-bold text-rose-700">{stats.overdue}</div>
|
||||
<div className="text-rose-600">지연</div>
|
||||
</div>
|
||||
{/* 제목 - 항상 표시 */}
|
||||
<div className="border-b border-gray-200 bg-white px-4 py-2">
|
||||
<h3 className="text-lg font-bold text-gray-800">{element?.customTitle || "To-Do / 긴급 지시"}</h3>
|
||||
{selectedDate && (
|
||||
<div className="mt-1 flex items-center gap-1 text-xs text-green-600">
|
||||
<CalendarIcon className="h-3 w-3" />
|
||||
<span className="font-semibold">{formatSelectedDate()} 할일</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 필터 */}
|
||||
<div className="mt-3 flex gap-2">
|
||||
{(["all", "pending", "in_progress", "completed"] as const).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
onClick={() => setFilter(f)}
|
||||
className={`rounded px-3 py-1 text-xs font-medium transition-colors ${
|
||||
filter === f
|
||||
? "bg-primary text-white"
|
||||
: "bg-gray-100 text-gray-600 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
{f === "all" ? "전체" : f === "pending" ? "대기" : f === "in_progress" ? "진행중" : "완료"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 헤더 (추가 버튼, 통계, 필터) - showHeader가 false일 때만 숨김 */}
|
||||
{element?.showHeader !== false && (
|
||||
<div className="border-b border-gray-200 bg-white px-4 py-3">
|
||||
<div className="mb-3 flex items-center justify-end">
|
||||
<button
|
||||
onClick={() => setShowAddForm(!showAddForm)}
|
||||
className="flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-sm text-white transition-colors hover:bg-primary/90"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
추가
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 통계 */}
|
||||
{stats && (
|
||||
<div className="grid grid-cols-4 gap-2 text-xs mb-3">
|
||||
<div className="rounded bg-blue-50 px-2 py-1.5 text-center">
|
||||
<div className="font-bold text-blue-700">{stats.pending}</div>
|
||||
<div className="text-blue-600">대기</div>
|
||||
</div>
|
||||
<div className="rounded bg-amber-50 px-2 py-1.5 text-center">
|
||||
<div className="font-bold text-amber-700">{stats.inProgress}</div>
|
||||
<div className="text-amber-600">진행중</div>
|
||||
</div>
|
||||
<div className="rounded bg-red-50 px-2 py-1.5 text-center">
|
||||
<div className="font-bold text-red-700">{stats.urgent}</div>
|
||||
<div className="text-red-600">긴급</div>
|
||||
</div>
|
||||
<div className="rounded bg-rose-50 px-2 py-1.5 text-center">
|
||||
<div className="font-bold text-rose-700">{stats.overdue}</div>
|
||||
<div className="text-rose-600">지연</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 필터 */}
|
||||
<div className="flex gap-2">
|
||||
{(["all", "pending", "in_progress", "completed"] as const).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
onClick={() => setFilter(f)}
|
||||
className={`rounded px-3 py-1 text-xs font-medium transition-colors ${
|
||||
filter === f
|
||||
? "bg-primary text-white"
|
||||
: "bg-gray-100 text-gray-600 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
{f === "all" ? "전체" : f === "pending" ? "대기" : f === "in_progress" ? "진행중" : "완료"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 추가 폼 */}
|
||||
{showAddForm && (
|
||||
<div className="border-b border-gray-200 bg-white p-4">
|
||||
|
|
@ -315,16 +455,16 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
|
|||
|
||||
{/* To-Do 리스트 */}
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
{todos.length === 0 ? (
|
||||
{filteredTodos.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-gray-400">
|
||||
<div className="text-center">
|
||||
<div className="mb-2 text-4xl">📝</div>
|
||||
<div>할 일이 없습니다</div>
|
||||
<div>{selectedDate ? `${formatSelectedDate()} 할 일이 없습니다` : "할 일이 없습니다"}</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{todos.map((todo) => (
|
||||
{filteredTodos.map((todo) => (
|
||||
<div
|
||||
key={todo.id}
|
||||
className={`group relative rounded-lg border-2 bg-white p-3 shadow-sm transition-all hover:shadow-md ${
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ export default function VehicleListWidget({ element, refreshInterval = 30000 }:
|
|||
{/* 헤더 */}
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900">📋 차량 목록</h3>
|
||||
<h3 className="text-lg font-bold text-gray-900">차량 목록</h3>
|
||||
<p className="text-xs text-gray-500">마지막 업데이트: {lastUpdate.toLocaleTimeString("ko-KR")}</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={loadVehicles} disabled={isLoading} className="h-8 w-8 p-0">
|
||||
|
|
|
|||
|
|
@ -280,9 +280,12 @@ export default function WeatherWidget({
|
|||
if (loading && !weather) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-50 rounded-lg border p-6">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<RefreshCw className="h-8 w-8 animate-spin text-blue-500" />
|
||||
<p className="text-sm text-gray-600">날씨 정보 불러오는 중...</p>
|
||||
<div className="text-center">
|
||||
<p className="text-sm font-semibold text-gray-800 mb-1">실제 기상청 API 연결 중...</p>
|
||||
<p className="text-xs text-gray-500">실시간 관측 데이터를 가져오고 있습니다</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -290,10 +293,27 @@ export default function WeatherWidget({
|
|||
|
||||
// 에러 상태
|
||||
if (error || !weather) {
|
||||
const isTestMode = error?.includes('API 키가 설정되지 않았습니다');
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center bg-gradient-to-br from-red-50 to-orange-50 rounded-lg border p-6">
|
||||
<div className={`flex h-full flex-col items-center justify-center rounded-lg border p-6 ${
|
||||
isTestMode
|
||||
? 'bg-gradient-to-br from-yellow-50 to-orange-50'
|
||||
: 'bg-gradient-to-br from-red-50 to-orange-50'
|
||||
}`}>
|
||||
<Cloud className="h-12 w-12 text-gray-400 mb-2" />
|
||||
<p className="text-sm text-gray-600 text-center mb-3">{error || '날씨 정보를 불러올 수 없습니다.'}</p>
|
||||
<div className="text-center mb-3">
|
||||
<p className="text-sm font-semibold text-gray-800 mb-1">
|
||||
{isTestMode ? '⚠️ 테스트 모드' : '❌ 연결 실패'}
|
||||
</p>
|
||||
<p className="text-xs text-gray-600">
|
||||
{error || '날씨 정보를 불러올 수 없습니다.'}
|
||||
</p>
|
||||
{isTestMode && (
|
||||
<p className="text-xs text-yellow-700 mt-2">
|
||||
임시 데이터가 표시됩니다
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
|
|
|
|||
|
|
@ -457,7 +457,7 @@ function AppLayoutInner({ children }: AppLayoutProps) {
|
|||
</aside>
|
||||
|
||||
{/* 가운데 컨텐츠 영역 - overflow 문제 해결 */}
|
||||
<main className="min-w-0 flex-1 overflow-auto bg-white">{children}</main>
|
||||
<main className="min-w-0 flex-1 bg-white">{children}</main>
|
||||
</div>
|
||||
|
||||
{/* 프로필 수정 모달 */}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,34 @@
|
|||
"use client";
|
||||
|
||||
import React, { createContext, useContext, useState, ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* 대시보드 위젯 간 데이터 공유를 위한 Context
|
||||
* - 달력에서 날짜 선택 시 할일/긴급지시 위젯에 전달
|
||||
*/
|
||||
|
||||
interface DashboardContextType {
|
||||
selectedDate: Date | null;
|
||||
setSelectedDate: (date: Date | null) => void;
|
||||
}
|
||||
|
||||
const DashboardContext = createContext<DashboardContextType | undefined>(undefined);
|
||||
|
||||
export function DashboardProvider({ children }: { children: ReactNode }) {
|
||||
const [selectedDate, setSelectedDate] = useState<Date | null>(null);
|
||||
|
||||
return (
|
||||
<DashboardContext.Provider value={{ selectedDate, setSelectedDate }}>
|
||||
{children}
|
||||
</DashboardContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useDashboard() {
|
||||
const context = useContext(DashboardContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("useDashboard must be used within a DashboardProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
|
|
@ -78,6 +78,10 @@ export interface Dashboard {
|
|||
elementsCount?: number;
|
||||
creatorName?: string;
|
||||
elements?: DashboardElement[];
|
||||
settings?: {
|
||||
resolution?: string;
|
||||
backgroundColor?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CreateDashboardRequest {
|
||||
|
|
@ -87,6 +91,10 @@ export interface CreateDashboardRequest {
|
|||
elements: DashboardElement[];
|
||||
tags?: string[];
|
||||
category?: string;
|
||||
settings?: {
|
||||
resolution?: string;
|
||||
backgroundColor?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface DashboardListQuery {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,84 @@
|
|||
import { apiCall } from "./client";
|
||||
|
||||
// 야드 레이아웃 관리 API
|
||||
export const yardLayoutApi = {
|
||||
// 모든 야드 레이아웃 목록 조회
|
||||
async getAllLayouts() {
|
||||
return apiCall("GET", "/yard-layouts");
|
||||
},
|
||||
|
||||
// 특정 야드 레이아웃 상세 조회
|
||||
async getLayoutById(id: number) {
|
||||
return apiCall("GET", `/yard-layouts/${id}`);
|
||||
},
|
||||
|
||||
// 새 야드 레이아웃 생성
|
||||
async createLayout(data: { name: string; description?: string }) {
|
||||
return apiCall("POST", "/yard-layouts", data);
|
||||
},
|
||||
|
||||
// 야드 레이아웃 수정
|
||||
async updateLayout(id: number, data: { name?: string; description?: string }) {
|
||||
return apiCall("PUT", `/yard-layouts/${id}`, data);
|
||||
},
|
||||
|
||||
// 야드 레이아웃 삭제
|
||||
async deleteLayout(id: number) {
|
||||
return apiCall("DELETE", `/yard-layouts/${id}`);
|
||||
},
|
||||
|
||||
// 야드 레이아웃 복제
|
||||
async duplicateLayout(id: number, name: string) {
|
||||
return apiCall("POST", `/yard-layouts/${id}/duplicate`, { name });
|
||||
},
|
||||
|
||||
// 특정 야드의 배치 자재 목록 조회
|
||||
async getPlacementsByLayoutId(layoutId: number) {
|
||||
return apiCall("GET", `/yard-layouts/${layoutId}/placements`);
|
||||
},
|
||||
|
||||
// 야드에 자재 배치 추가
|
||||
async addMaterialPlacement(layoutId: number, data: any) {
|
||||
return apiCall("POST", `/yard-layouts/${layoutId}/placements`, data);
|
||||
},
|
||||
|
||||
// 배치 정보 수정
|
||||
async updatePlacement(placementId: number, data: any) {
|
||||
return apiCall("PUT", `/yard-layouts/placements/${placementId}`, data);
|
||||
},
|
||||
|
||||
// 배치 해제
|
||||
async removePlacement(placementId: number) {
|
||||
return apiCall("DELETE", `/yard-layouts/placements/${placementId}`);
|
||||
},
|
||||
|
||||
// 여러 배치 일괄 업데이트
|
||||
async batchUpdatePlacements(layoutId: number, placements: any[]) {
|
||||
return apiCall("PUT", `/yard-layouts/${layoutId}/placements/batch`, { placements });
|
||||
},
|
||||
};
|
||||
|
||||
// 자재 관리 API
|
||||
export const materialApi = {
|
||||
// 임시 자재 마스터 목록 조회
|
||||
async getTempMaterials(params?: { search?: string; category?: string; page?: number; limit?: number }) {
|
||||
const queryParams = new URLSearchParams();
|
||||
if (params?.search) queryParams.append("search", params.search);
|
||||
if (params?.category) queryParams.append("category", params.category);
|
||||
if (params?.page) queryParams.append("page", params.page.toString());
|
||||
if (params?.limit) queryParams.append("limit", params.limit.toString());
|
||||
|
||||
const queryString = queryParams.toString();
|
||||
return apiCall("GET", `/materials/temp${queryString ? `?${queryString}` : ""}`);
|
||||
},
|
||||
|
||||
// 특정 자재 상세 조회
|
||||
async getTempMaterialByCode(code: string) {
|
||||
return apiCall("GET", `/materials/temp/${code}`);
|
||||
},
|
||||
|
||||
// 카테고리 목록 조회
|
||||
async getCategories() {
|
||||
return apiCall("GET", "/materials/temp/categories");
|
||||
},
|
||||
};
|
||||
|
|
@ -30,11 +30,14 @@
|
|||
"@radix-ui/react-slot": "^1.2.3",
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@react-three/drei": "^10.7.6",
|
||||
"@react-three/fiber": "^9.4.0",
|
||||
"@tanstack/react-query": "^5.86.0",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@types/d3": "^7.4.3",
|
||||
"@types/leaflet": "^1.9.21",
|
||||
"@types/react-window": "^1.8.8",
|
||||
"@types/three": "^0.180.0",
|
||||
"@xyflow/react": "^12.8.4",
|
||||
"axios": "^1.11.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
|
|
@ -64,6 +67,7 @@
|
|||
"sheetjs-style": "^0.15.8",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"three": "^0.180.0",
|
||||
"uuid": "^13.0.0",
|
||||
"xlsx": "^0.18.5",
|
||||
"zod": "^4.1.5"
|
||||
|
|
@ -280,6 +284,12 @@
|
|||
"integrity": "sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@dimforge/rapier3d-compat": {
|
||||
"version": "0.12.0",
|
||||
"resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
|
||||
"integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||
|
|
@ -1100,6 +1110,24 @@
|
|||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@mediapipe/tasks-vision": {
|
||||
"version": "0.10.17",
|
||||
"resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-0.10.17.tgz",
|
||||
"integrity": "sha512-CZWV/q6TTe8ta61cZXjfnnHsfWIdFhms03M9T7Cnd5y2mdpylJM0rF1qRq+wsQVRMLz1OYPVEBU9ph2Bx8cxrg==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@monogrid/gainmap-js": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@monogrid/gainmap-js/-/gainmap-js-3.1.0.tgz",
|
||||
"integrity": "sha512-Obb0/gEd/HReTlg8ttaYk+0m62gQJmCblMOjHSMHRrBP2zdfKMHLCRbh/6ex9fSUJMKdjjIEiohwkbGD3wj2Nw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"promise-worker-transferable": "^1.0.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">= 0.159.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/wasm-runtime": {
|
||||
"version": "0.2.12",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",
|
||||
|
|
@ -2495,6 +2523,160 @@
|
|||
"react-dom": "^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@react-three/drei": {
|
||||
"version": "10.7.6",
|
||||
"resolved": "https://registry.npmjs.org/@react-three/drei/-/drei-10.7.6.tgz",
|
||||
"integrity": "sha512-ZSFwRlRaa4zjtB7yHO6Q9xQGuyDCzE7whXBhum92JslcMRC3aouivp0rAzszcVymIoJx6PXmibyP+xr+zKdwLg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.26.0",
|
||||
"@mediapipe/tasks-vision": "0.10.17",
|
||||
"@monogrid/gainmap-js": "^3.0.6",
|
||||
"@use-gesture/react": "^10.3.1",
|
||||
"camera-controls": "^3.1.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"detect-gpu": "^5.0.56",
|
||||
"glsl-noise": "^0.0.0",
|
||||
"hls.js": "^1.5.17",
|
||||
"maath": "^0.10.8",
|
||||
"meshline": "^3.3.1",
|
||||
"stats-gl": "^2.2.8",
|
||||
"stats.js": "^0.17.0",
|
||||
"suspend-react": "^0.1.3",
|
||||
"three-mesh-bvh": "^0.8.3",
|
||||
"three-stdlib": "^2.35.6",
|
||||
"troika-three-text": "^0.52.4",
|
||||
"tunnel-rat": "^0.1.2",
|
||||
"use-sync-external-store": "^1.4.0",
|
||||
"utility-types": "^3.11.0",
|
||||
"zustand": "^5.0.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@react-three/fiber": "^9.0.0",
|
||||
"react": "^19",
|
||||
"react-dom": "^19",
|
||||
"three": ">=0.159"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@react-three/drei/node_modules/zustand": {
|
||||
"version": "5.0.8",
|
||||
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.8.tgz",
|
||||
"integrity": "sha512-gyPKpIaxY9XcO2vSMrLbiER7QMAMGOQZVRdJ6Zi782jkbzZygq5GI9nG8g+sMgitRtndwaBSl7uiqC49o1SSiw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.20.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=18.0.0",
|
||||
"immer": ">=9.0.6",
|
||||
"react": ">=18.0.0",
|
||||
"use-sync-external-store": ">=1.2.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"immer": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"use-sync-external-store": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@react-three/fiber": {
|
||||
"version": "9.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-9.4.0.tgz",
|
||||
"integrity": "sha512-k4iu1R6e5D54918V4sqmISUkI5OgTw3v7/sDRKEC632Wd5g2WBtUS5gyG63X0GJO/HZUj1tsjSXfyzwrUHZl1g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.17.8",
|
||||
"@types/react-reconciler": "^0.32.0",
|
||||
"@types/webxr": "*",
|
||||
"base64-js": "^1.5.1",
|
||||
"buffer": "^6.0.3",
|
||||
"its-fine": "^2.0.0",
|
||||
"react-reconciler": "^0.31.0",
|
||||
"react-use-measure": "^2.1.7",
|
||||
"scheduler": "^0.25.0",
|
||||
"suspend-react": "^0.1.3",
|
||||
"use-sync-external-store": "^1.4.0",
|
||||
"zustand": "^5.0.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"expo": ">=43.0",
|
||||
"expo-asset": ">=8.4",
|
||||
"expo-file-system": ">=11.0",
|
||||
"expo-gl": ">=11.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-native": ">=0.78",
|
||||
"three": ">=0.156"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"expo": {
|
||||
"optional": true
|
||||
},
|
||||
"expo-asset": {
|
||||
"optional": true
|
||||
},
|
||||
"expo-file-system": {
|
||||
"optional": true
|
||||
},
|
||||
"expo-gl": {
|
||||
"optional": true
|
||||
},
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
},
|
||||
"react-native": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@react-three/fiber/node_modules/scheduler": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.25.0.tgz",
|
||||
"integrity": "sha512-xFVuu11jh+xcO7JOAGJNOXld8/TcEHK/4CituBUeUb5hqxJLj9YuemAEuvm9gQ/+pgXYfbQuqAkiYu+u7YEsNA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@react-three/fiber/node_modules/zustand": {
|
||||
"version": "5.0.8",
|
||||
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.8.tgz",
|
||||
"integrity": "sha512-gyPKpIaxY9XcO2vSMrLbiER7QMAMGOQZVRdJ6Zi782jkbzZygq5GI9nG8g+sMgitRtndwaBSl7uiqC49o1SSiw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.20.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=18.0.0",
|
||||
"immer": ">=9.0.6",
|
||||
"react": ">=18.0.0",
|
||||
"use-sync-external-store": ">=1.2.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"immer": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"use-sync-external-store": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@reactflow/background": {
|
||||
"version": "11.3.9",
|
||||
"resolved": "https://registry.npmjs.org/@reactflow/background/-/background-11.3.9.tgz",
|
||||
|
|
@ -3022,6 +3204,12 @@
|
|||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
}
|
||||
},
|
||||
"node_modules/@tweenjs/tween.js": {
|
||||
"version": "23.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
|
||||
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@tybys/wasm-util": {
|
||||
"version": "0.10.1",
|
||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",
|
||||
|
|
@ -3286,6 +3474,12 @@
|
|||
"@types/d3-selection": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/draco3d": {
|
||||
"version": "1.4.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/draco3d/-/draco3d-1.4.10.tgz",
|
||||
"integrity": "sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/estree": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
|
||||
|
|
@ -3332,6 +3526,12 @@
|
|||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/offscreencanvas": {
|
||||
"version": "2019.7.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.3.tgz",
|
||||
"integrity": "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "19.1.13",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.13.tgz",
|
||||
|
|
@ -3351,6 +3551,15 @@
|
|||
"@types/react": "^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react-reconciler": {
|
||||
"version": "0.32.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.32.2.tgz",
|
||||
"integrity": "sha512-gjcm6O0aUknhYaogEl8t5pecPfiOTD8VQkbjOhgbZas/E6qGY+veW9iuJU/7p4Y1E0EuQ0mArga7VEOUWSlVRA==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@types/react": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react-window": {
|
||||
"version": "1.8.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/react-window/-/react-window-1.8.8.tgz",
|
||||
|
|
@ -3360,6 +3569,27 @@
|
|||
"@types/react": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/stats.js": {
|
||||
"version": "0.17.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
|
||||
"integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/three": {
|
||||
"version": "0.180.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/three/-/three-0.180.0.tgz",
|
||||
"integrity": "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dimforge/rapier3d-compat": "~0.12.0",
|
||||
"@tweenjs/tween.js": "~23.1.3",
|
||||
"@types/stats.js": "*",
|
||||
"@types/webxr": "*",
|
||||
"@webgpu/types": "*",
|
||||
"fflate": "~0.8.2",
|
||||
"meshoptimizer": "~0.22.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/trusted-types": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||
|
|
@ -3380,6 +3610,12 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/webxr": {
|
||||
"version": "0.5.24",
|
||||
"resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
|
||||
"integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||
"version": "8.44.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.44.1.tgz",
|
||||
|
|
@ -3937,6 +4173,30 @@
|
|||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@use-gesture/core": {
|
||||
"version": "10.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@use-gesture/core/-/core-10.3.1.tgz",
|
||||
"integrity": "sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@use-gesture/react": {
|
||||
"version": "10.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@use-gesture/react/-/react-10.3.1.tgz",
|
||||
"integrity": "sha512-Yy19y6O2GJq8f7CHf7L0nxL8bf4PZCPaVOCgJrusOeFHY1LvHgYXnmnXg6N5iwAnbgbZCDjo60SiM6IPJi9C5g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@use-gesture/core": "10.3.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">= 16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@webgpu/types": {
|
||||
"version": "0.1.66",
|
||||
"resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.66.tgz",
|
||||
"integrity": "sha512-YA2hLrwLpDsRueNDXIMqN9NTzD6bCDkuXbOSe0heS+f8YE8usA6Gbv1prj81pzVHrbaAma7zObnIC+I6/sXJgA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/@xmldom/xmldom": {
|
||||
"version": "0.8.11",
|
||||
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.11.tgz",
|
||||
|
|
@ -4384,6 +4644,30 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/c12": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/c12/-/c12-3.1.0.tgz",
|
||||
|
|
@ -4472,6 +4756,19 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/camera-controls": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/camera-controls/-/camera-controls-3.1.0.tgz",
|
||||
"integrity": "sha512-w5oULNpijgTRH0ARFJJ0R5ct1nUM3R3WP7/b8A6j9uTGpRfnsypc/RBMPQV8JQDPayUe37p/TZZY1PcUr4czOQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20.11.0",
|
||||
"npm": ">=10.8.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">=0.126.1"
|
||||
}
|
||||
},
|
||||
"node_modules/caniuse-lite": {
|
||||
"version": "1.0.30001745",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001745.tgz",
|
||||
|
|
@ -4718,11 +5015,28 @@
|
|||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-env": {
|
||||
"version": "7.0.3",
|
||||
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
|
||||
"integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cross-spawn": "^7.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"cross-env": "src/bin/cross-env.js",
|
||||
"cross-env-shell": "src/bin/cross-env-shell.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.14",
|
||||
"npm": ">=6",
|
||||
"yarn": ">=1"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"path-key": "^3.1.0",
|
||||
|
|
@ -5380,6 +5694,15 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/detect-gpu": {
|
||||
"version": "5.0.70",
|
||||
"resolved": "https://registry.npmjs.org/detect-gpu/-/detect-gpu-5.0.70.tgz",
|
||||
"integrity": "sha512-bqerEP1Ese6nt3rFkwPnGbsUF9a4q+gMmpTVVOEzoCyeCc+y7/RvJnQZJx1JwhgQI5Ntg0Kgat8Uu7XpBqnz1w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"webgl-constants": "^1.1.1"
|
||||
}
|
||||
},
|
||||
"node_modules/detect-libc": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.1.tgz",
|
||||
|
|
@ -5516,6 +5839,12 @@
|
|||
"url": "https://dotenvx.com"
|
||||
}
|
||||
},
|
||||
"node_modules/draco3d": {
|
||||
"version": "1.5.7",
|
||||
"resolved": "https://registry.npmjs.org/draco3d/-/draco3d-1.5.7.tgz",
|
||||
"integrity": "sha512-m6WCKt/erDXcw+70IJXnG7M3awwQPAsZvJGX5zY7beBqpELw6RDGkYVU0W43AFxye4pDZ5i2Lbyc/NNGqwjUVQ==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/duck": {
|
||||
"version": "0.1.12",
|
||||
"resolved": "https://registry.npmjs.org/duck/-/duck-0.1.12.tgz",
|
||||
|
|
@ -6374,6 +6703,12 @@
|
|||
"reusify": "^1.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/fflate": {
|
||||
"version": "0.8.2",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz",
|
||||
"integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/file-entry-cache": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
|
||||
|
|
@ -6677,6 +7012,12 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/glsl-noise": {
|
||||
"version": "0.0.0",
|
||||
"resolved": "https://registry.npmjs.org/glsl-noise/-/glsl-noise-0.0.0.tgz",
|
||||
"integrity": "sha512-b/ZCF6amfAUb7dJM/MxRs7AetQEahYzJ8PtgfrmEdtw6uyGOr+ZSGtgjFm6mfsBkxJ4d2W7kg+Nlqzqvn3Bc0w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/goober": {
|
||||
"version": "2.1.16",
|
||||
"resolved": "https://registry.npmjs.org/goober/-/goober-2.1.16.tgz",
|
||||
|
|
@ -6813,6 +7154,12 @@
|
|||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/hls.js": {
|
||||
"version": "1.6.13",
|
||||
"resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.6.13.tgz",
|
||||
"integrity": "sha512-hNEzjZNHf5bFrUNvdS4/1RjIanuJ6szpWNfTaX5I6WfGynWXGT7K/YQLYtemSvFExzeMdgdE4SsyVLJbd5PcZA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/hoist-non-react-statics": {
|
||||
"version": "3.3.2",
|
||||
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",
|
||||
|
|
@ -6872,6 +7219,26 @@
|
|||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
|
|
@ -7217,6 +7584,12 @@
|
|||
"integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/is-promise": {
|
||||
"version": "2.2.2",
|
||||
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz",
|
||||
"integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/is-regex": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",
|
||||
|
|
@ -7373,7 +7746,6 @@
|
|||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/isomorphic-dompurify": {
|
||||
|
|
@ -7407,6 +7779,27 @@
|
|||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/its-fine": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/its-fine/-/its-fine-2.0.0.tgz",
|
||||
"integrity": "sha512-KLViCmWx94zOvpLwSlsx6yOCeMhZYaxrJV87Po5k/FoZzcPSahvK5qJ7fYhS61sZi5ikmh2S3Hz55A2l3U69ng==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/react-reconciler": "^0.28.9"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/its-fine/node_modules/@types/react-reconciler": {
|
||||
"version": "0.28.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.28.9.tgz",
|
||||
"integrity": "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@types/react": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/jiti": {
|
||||
"version": "2.6.0",
|
||||
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.0.tgz",
|
||||
|
|
@ -7901,6 +8294,16 @@
|
|||
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/maath": {
|
||||
"version": "0.10.8",
|
||||
"resolved": "https://registry.npmjs.org/maath/-/maath-0.10.8.tgz",
|
||||
"integrity": "sha512-tRvbDF0Pgqz+9XUa4jjfgAQ8/aPKmQdWXilFu2tMy4GWj4NOsx99HlULO4IeREfbO3a0sA145DZYyvXPkybm0g==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@types/three": ">=0.134.0",
|
||||
"three": ">=0.134.0"
|
||||
}
|
||||
},
|
||||
"node_modules/magic-string": {
|
||||
"version": "0.30.19",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.19.tgz",
|
||||
|
|
@ -7969,6 +8372,21 @@
|
|||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/meshline": {
|
||||
"version": "3.3.1",
|
||||
"resolved": "https://registry.npmjs.org/meshline/-/meshline-3.3.1.tgz",
|
||||
"integrity": "sha512-/TQj+JdZkeSUOl5Mk2J7eLcYTLiQm2IDzmlSvYm7ov15anEcDJ92GHqqazxTSreeNgfnYu24kiEvvv0WlbCdFQ==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"three": ">=0.137"
|
||||
}
|
||||
},
|
||||
"node_modules/meshoptimizer": {
|
||||
"version": "0.22.0",
|
||||
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.22.0.tgz",
|
||||
"integrity": "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/micromatch": {
|
||||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
|
||||
|
|
@ -8468,7 +8886,6 @@
|
|||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
|
||||
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
|
|
@ -8564,6 +8981,12 @@
|
|||
"node": "^10 || ^12 || >=14"
|
||||
}
|
||||
},
|
||||
"node_modules/potpack": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/potpack/-/potpack-1.0.2.tgz",
|
||||
"integrity": "sha512-choctRBIV9EMT9WGAZHn3V7t0Z2pMQyl0EZE6pFc/6ml3ssw7Dlf/oAOvFwjm1HVsqfQN8GfeFyJ+d8tRzqueQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/prelude-ls": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
|
||||
|
|
@ -8734,6 +9157,16 @@
|
|||
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/promise-worker-transferable": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/promise-worker-transferable/-/promise-worker-transferable-1.0.4.tgz",
|
||||
"integrity": "sha512-bN+0ehEnrXfxV2ZQvU2PetO0n4gqBD4ulq3MI1WOPLgr7/Mg9yRQkX5+0v1vagr74ZTsl7XtzlaYDo2EuCeYJw==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"is-promise": "^2.1.0",
|
||||
"lie": "^3.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/prop-types": {
|
||||
"version": "15.8.1",
|
||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||
|
|
@ -8944,6 +9377,27 @@
|
|||
"react-dom": "^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-reconciler": {
|
||||
"version": "0.31.0",
|
||||
"resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.31.0.tgz",
|
||||
"integrity": "sha512-7Ob7Z+URmesIsIVRjnLoDGwBEG/tVitidU0nMsqX/eeJaLY89RISO/10ERe0MqmzuKUUB1rmY+h1itMbUHg9BQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"scheduler": "^0.25.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-reconciler/node_modules/scheduler": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.25.0.tgz",
|
||||
"integrity": "sha512-xFVuu11jh+xcO7JOAGJNOXld8/TcEHK/4CituBUeUb5hqxJLj9YuemAEuvm9gQ/+pgXYfbQuqAkiYu+u7YEsNA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/react-redux": {
|
||||
"version": "9.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
|
||||
|
|
@ -9046,6 +9500,21 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-use-measure": {
|
||||
"version": "2.1.7",
|
||||
"resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.7.tgz",
|
||||
"integrity": "sha512-KrvcAo13I/60HpwGO5jpW7E9DfusKyLPLvuHlUyP5zqnmAPhNc6qTRjUQrdTADl0lpPpDVU2/Gg51UlOGHXbdg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": ">=16.13",
|
||||
"react-dom": ">=16.13"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-window": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/react-window/-/react-window-2.1.1.tgz",
|
||||
|
|
@ -9510,7 +9979,6 @@
|
|||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"shebang-regex": "^3.0.0"
|
||||
|
|
@ -9523,7 +9991,6 @@
|
|||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
|
||||
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
|
|
@ -9674,6 +10141,32 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/stats-gl": {
|
||||
"version": "2.4.2",
|
||||
"resolved": "https://registry.npmjs.org/stats-gl/-/stats-gl-2.4.2.tgz",
|
||||
"integrity": "sha512-g5O9B0hm9CvnM36+v7SFl39T7hmAlv541tU81ME8YeSb3i1CIP5/QdDeSB3A0la0bKNHpxpwxOVRo2wFTYEosQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/three": "*",
|
||||
"three": "^0.170.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/three": "*",
|
||||
"three": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/stats-gl/node_modules/three": {
|
||||
"version": "0.170.0",
|
||||
"resolved": "https://registry.npmjs.org/three/-/three-0.170.0.tgz",
|
||||
"integrity": "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/stats.js": {
|
||||
"version": "0.17.0",
|
||||
"resolved": "https://registry.npmjs.org/stats.js/-/stats.js-0.17.0.tgz",
|
||||
"integrity": "sha512-hNKz8phvYLPEcRkeG1rsGmV5ChMjKDAWU7/OJJdDErPBNChQXxCo3WZurGpnWc6gZhAzEPFad1aVgyOANH1sMw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/stop-iteration-iterator": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz",
|
||||
|
|
@ -9882,6 +10375,15 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/suspend-react": {
|
||||
"version": "0.1.3",
|
||||
"resolved": "https://registry.npmjs.org/suspend-react/-/suspend-react-0.1.3.tgz",
|
||||
"integrity": "sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": ">=17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/symbol-tree": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
|
||||
|
|
@ -9952,6 +10454,44 @@
|
|||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/three": {
|
||||
"version": "0.180.0",
|
||||
"resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz",
|
||||
"integrity": "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/three-mesh-bvh": {
|
||||
"version": "0.8.3",
|
||||
"resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.8.3.tgz",
|
||||
"integrity": "sha512-4G5lBaF+g2auKX3P0yqx+MJC6oVt6sB5k+CchS6Ob0qvH0YIhuUk1eYr7ktsIpY+albCqE80/FVQGV190PmiAg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"three": ">= 0.159.0"
|
||||
}
|
||||
},
|
||||
"node_modules/three-stdlib": {
|
||||
"version": "2.36.0",
|
||||
"resolved": "https://registry.npmjs.org/three-stdlib/-/three-stdlib-2.36.0.tgz",
|
||||
"integrity": "sha512-kv0Byb++AXztEGsULgMAs8U2jgUdz6HPpAB/wDJnLiLlaWQX2APHhiTJIN7rqW+Of0eRgcp7jn05U1BsCP3xBA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/draco3d": "^1.4.0",
|
||||
"@types/offscreencanvas": "^2019.6.4",
|
||||
"@types/webxr": "^0.5.2",
|
||||
"draco3d": "^1.4.1",
|
||||
"fflate": "^0.6.9",
|
||||
"potpack": "^1.0.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">=0.128.0"
|
||||
}
|
||||
},
|
||||
"node_modules/three-stdlib/node_modules/fflate": {
|
||||
"version": "0.6.10",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.6.10.tgz",
|
||||
"integrity": "sha512-IQrh3lEPM93wVCEczc9SaAOvkmcoQn/G8Bo1e8ZPlY3X3bnAxWaBdvTdvM1hP62iZp0BXWDy4vTAy4fF0+Dlpg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tiny-invariant": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
|
||||
|
|
@ -10068,6 +10608,36 @@
|
|||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/troika-three-text": {
|
||||
"version": "0.52.4",
|
||||
"resolved": "https://registry.npmjs.org/troika-three-text/-/troika-three-text-0.52.4.tgz",
|
||||
"integrity": "sha512-V50EwcYGruV5rUZ9F4aNsrytGdKcXKALjEtQXIOBfhVoZU9VAqZNIoGQ3TMiooVqFAbR1w15T+f+8gkzoFzawg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bidi-js": "^1.0.2",
|
||||
"troika-three-utils": "^0.52.4",
|
||||
"troika-worker-utils": "^0.52.0",
|
||||
"webgl-sdf-generator": "1.1.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">=0.125.0"
|
||||
}
|
||||
},
|
||||
"node_modules/troika-three-utils": {
|
||||
"version": "0.52.4",
|
||||
"resolved": "https://registry.npmjs.org/troika-three-utils/-/troika-three-utils-0.52.4.tgz",
|
||||
"integrity": "sha512-NORAStSVa/BDiG52Mfudk4j1FG4jC4ILutB3foPnfGbOeIs9+G5vZLa0pnmnaftZUGm4UwSoqEpWdqvC7zms3A==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"three": ">=0.125.0"
|
||||
}
|
||||
},
|
||||
"node_modules/troika-worker-utils": {
|
||||
"version": "0.52.0",
|
||||
"resolved": "https://registry.npmjs.org/troika-worker-utils/-/troika-worker-utils-0.52.0.tgz",
|
||||
"integrity": "sha512-W1CpvTHykaPH5brv5VHLfQo9D1OYuo0cSBEUQFFT/nBUzM8iD6Lq2/tgG/f1OelbAS1WtaTPQzE5uM49egnngw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ts-api-utils": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz",
|
||||
|
|
@ -10100,6 +10670,15 @@
|
|||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/tunnel-rat": {
|
||||
"version": "0.1.2",
|
||||
"resolved": "https://registry.npmjs.org/tunnel-rat/-/tunnel-rat-0.1.2.tgz",
|
||||
"integrity": "sha512-lR5VHmkPhzdhrM092lI2nACsLO4QubF0/yoOhzX7c+wIpbN1GjHNzCc91QlpxBi+cnx8vVJ+Ur6vL5cEoQPFpQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"zustand": "^4.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/tw-animate-css": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/tw-animate-css/-/tw-animate-css-1.4.0.tgz",
|
||||
|
|
@ -10350,6 +10929,15 @@
|
|||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/utility-types": {
|
||||
"version": "3.11.0",
|
||||
"resolved": "https://registry.npmjs.org/utility-types/-/utility-types-3.11.0.tgz",
|
||||
"integrity": "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/uuid": {
|
||||
"version": "13.0.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz",
|
||||
|
|
@ -10397,6 +10985,17 @@
|
|||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/webgl-constants": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/webgl-constants/-/webgl-constants-1.1.1.tgz",
|
||||
"integrity": "sha512-LkBXKjU5r9vAW7Gcu3T5u+5cvSvh5WwINdr0C+9jpzVB41cjQAP5ePArDtk/WHYdVj0GefCgM73BA7FlIiNtdg=="
|
||||
},
|
||||
"node_modules/webgl-sdf-generator": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/webgl-sdf-generator/-/webgl-sdf-generator-1.1.1.tgz",
|
||||
"integrity": "sha512-9Z0JcMTFxeE+b2x1LJTdnaT8rT8aEp7MVxkNwoycNmJWwPdzoXzMh0BjJSh/AEFP+KPYZUli814h8bJZFIZ2jA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/webidl-conversions": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.0.tgz",
|
||||
|
|
@ -10444,7 +11043,6 @@
|
|||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"isexe": "^2.0.0"
|
||||
|
|
|
|||
|
|
@ -38,11 +38,14 @@
|
|||
"@radix-ui/react-slot": "^1.2.3",
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@react-three/drei": "^10.7.6",
|
||||
"@react-three/fiber": "^9.4.0",
|
||||
"@tanstack/react-query": "^5.86.0",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@types/d3": "^7.4.3",
|
||||
"@types/leaflet": "^1.9.21",
|
||||
"@types/react-window": "^1.8.8",
|
||||
"@types/three": "^0.180.0",
|
||||
"@xyflow/react": "^12.8.4",
|
||||
"axios": "^1.11.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
|
|
@ -72,6 +75,7 @@
|
|||
"sheetjs-style": "^0.15.8",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"three": "^0.180.0",
|
||||
"uuid": "^13.0.0",
|
||||
"xlsx": "^0.18.5",
|
||||
"zod": "^4.1.5"
|
||||
|
|
|
|||
Loading…
Reference in New Issue