Merge branch 'main' of http://39.117.244.52:3000/kjs/ERP-node into feature/screen-management

This commit is contained in:
kjs 2025-10-20 17:51:36 +09:00
commit 876e3bfa05
36 changed files with 3406 additions and 435 deletions

150
WORK_HISTORY_SETUP.md Normal file
View File

@ -0,0 +1,150 @@
# 작업 이력 관리 시스템 설치 가이드
## 📋 개요
작업 이력 관리 시스템이 추가되었습니다. 입고/출고/이송/정비 작업을 관리하고 통계를 확인할 수 있습니다.
## 🚀 설치 방법
### 1. 데이터베이스 마이그레이션 실행
PostgreSQL 데이터베이스에 작업 이력 테이블을 생성해야 합니다.
```bash
# 방법 1: psql 명령어 사용 (로컬 PostgreSQL)
psql -U postgres -d plm -f db/migrations/20241020_create_work_history.sql
# 방법 2: Docker 컨테이너 사용
docker exec -i <DB_CONTAINER_NAME> psql -U postgres -d plm < db/migrations/20241020_create_work_history.sql
# 방법 3: pgAdmin 또는 DBeaver 사용
# db/migrations/20241020_create_work_history.sql 파일을 열어서 실행
```
### 2. 백엔드 재시작
```bash
cd backend-node
npm run dev
```
### 3. 프론트엔드 확인
대시보드 편집 화면에서 다음 위젯들을 추가할 수 있습니다:
- **작업 이력**: 작업 목록을 테이블 형식으로 표시
- **운송 통계**: 오늘 작업, 총 운송량, 정시 도착률 등 통계 표시
## 📊 주요 기능
### 작업 이력 위젯
- 작업 번호, 일시, 유형, 차량, 경로, 화물, 중량, 상태 표시
- 유형별 필터링 (입고/출고/이송/정비)
- 상태별 필터링 (대기/진행중/완료/취소)
- 실시간 자동 새로고침
### 운송 통계 위젯
- 오늘 작업 건수 및 완료율
- 총 운송량 (톤)
- 누적 거리 (km)
- 정시 도착률 (%)
- 작업 유형별 분포 차트
## 🔧 API 엔드포인트
### 작업 이력 관리
- `GET /api/work-history` - 작업 이력 목록 조회
- `GET /api/work-history/:id` - 작업 이력 단건 조회
- `POST /api/work-history` - 작업 이력 생성
- `PUT /api/work-history/:id` - 작업 이력 수정
- `DELETE /api/work-history/:id` - 작업 이력 삭제
### 통계 및 분석
- `GET /api/work-history/stats` - 작업 이력 통계
- `GET /api/work-history/trend?months=6` - 월별 추이
- `GET /api/work-history/routes?limit=5` - 주요 운송 경로
## 📝 샘플 데이터
마이그레이션 실행 시 자동으로 4건의 샘플 데이터가 생성됩니다:
1. 입고 작업 (완료)
2. 출고 작업 (진행중)
3. 이송 작업 (대기)
4. 정비 작업 (완료)
## 🎯 사용 방법
### 1. 대시보드에 위젯 추가
1. 대시보드 편집 모드로 이동
2. 상단 메뉴에서 "위젯 추가" 선택
3. "작업 이력" 또는 "운송 통계" 선택
4. 원하는 위치에 배치
5. 저장
### 2. 작업 이력 필터링
- 유형 선택: 전체/입고/출고/이송/정비
- 상태 선택: 전체/대기/진행중/완료/취소
- 새로고침 버튼으로 수동 갱신
### 3. 통계 확인
운송 통계 위젯에서 다음 정보를 확인할 수 있습니다:
- 오늘 작업 건수
- 완료율
- 총 운송량
- 정시 도착률
- 작업 유형별 분포
## 🔍 문제 해결
### 데이터가 표시되지 않는 경우
1. 데이터베이스 마이그레이션이 실행되었는지 확인
2. 백엔드 서버가 실행 중인지 확인
3. 브라우저 콘솔에서 API 에러 확인
### API 에러가 발생하는 경우
```bash
# 백엔드 로그 확인
cd backend-node
npm run dev
```
### 위젯이 표시되지 않는 경우
1. 프론트엔드 재시작
2. 브라우저 캐시 삭제
3. 페이지 새로고침
## 📚 관련 파일
### 백엔드
- `backend-node/src/types/workHistory.ts` - 타입 정의
- `backend-node/src/services/workHistoryService.ts` - 비즈니스 로직
- `backend-node/src/controllers/workHistoryController.ts` - API 컨트롤러
- `backend-node/src/routes/workHistoryRoutes.ts` - 라우트 정의
### 프론트엔드
- `frontend/types/workHistory.ts` - 타입 정의
- `frontend/components/dashboard/widgets/WorkHistoryWidget.tsx` - 작업 이력 위젯
- `frontend/components/dashboard/widgets/TransportStatsWidget.tsx` - 운송 통계 위젯
### 데이터베이스
- `db/migrations/20241020_create_work_history.sql` - 테이블 생성 스크립트
## 🎉 완료!
작업 이력 관리 시스템이 성공적으로 설치되었습니다!

View File

@ -1 +1,55 @@
[]
[
{
"id": "e5bb334c-d58a-4068-ad77-2607a41f4675",
"title": "ㅁㄴㅇㄹ",
"description": "ㅁㄴㅇㄹ",
"priority": "normal",
"status": "completed",
"assignedTo": "",
"dueDate": "2025-10-20T18:17",
"createdAt": "2025-10-20T06:15:49.610Z",
"updatedAt": "2025-10-20T07:36:06.370Z",
"isUrgent": false,
"order": 0,
"completedAt": "2025-10-20T07:36:06.370Z"
},
{
"id": "334be17c-7776-47e8-89ec-4b57c4a34bcd",
"title": "연동되어주겠니?",
"description": "",
"priority": "normal",
"status": "pending",
"assignedTo": "",
"dueDate": "",
"createdAt": "2025-10-20T06:20:06.343Z",
"updatedAt": "2025-10-20T06:20:06.343Z",
"isUrgent": false,
"order": 1
},
{
"id": "f85b81de-fcbd-4858-8973-247d9d6e70ed",
"title": "연동되어주겠니?11",
"description": "ㄴㅇㄹ",
"priority": "normal",
"status": "pending",
"assignedTo": "",
"dueDate": "2025-10-20T17:22",
"createdAt": "2025-10-20T06:20:53.818Z",
"updatedAt": "2025-10-20T06:20:53.818Z",
"isUrgent": false,
"order": 2
},
{
"id": "58d2b26f-5197-4df1-b5d4-724a72ee1d05",
"title": "연동되어주려무니",
"description": "ㅁㄴㅇㄹ",
"priority": "normal",
"status": "pending",
"assignedTo": "",
"dueDate": "2025-10-21T15:21",
"createdAt": "2025-10-20T06:21:19.817Z",
"updatedAt": "2025-10-20T06:21:19.817Z",
"isUrgent": false,
"order": 3
}
]

View File

@ -59,6 +59,7 @@ import yardLayoutRoutes from "./routes/yardLayoutRoutes"; // 야드 관리 3D
//import materialRoutes from "./routes/materialRoutes"; // 자재 관리
import flowRoutes from "./routes/flowRoutes"; // 플로우 관리
import flowExternalDbConnectionRoutes from "./routes/flowExternalDbConnectionRoutes"; // 플로우 전용 외부 DB 연결
import workHistoryRoutes from "./routes/workHistoryRoutes"; // 작업 이력 관리
import { BatchSchedulerService } from "./services/batchSchedulerService";
// import collectionRoutes from "./routes/collectionRoutes"; // 임시 주석
// import batchRoutes from "./routes/batchRoutes"; // 임시 주석
@ -212,6 +213,7 @@ app.use("/api/yard-layouts", yardLayoutRoutes); // 야드 관리 3D
// app.use("/api/materials", materialRoutes); // 자재 관리 (임시 주석)
app.use("/api/flow-external-db", flowExternalDbConnectionRoutes); // 플로우 전용 외부 DB 연결
app.use("/api/flow", flowRoutes); // 플로우 관리 (마지막에 등록하여 다른 라우트와 충돌 방지)
app.use("/api/work-history", workHistoryRoutes); // 작업 이력 관리
// app.use("/api/collections", collectionRoutes); // 임시 주석
// app.use("/api/batch", batchRoutes); // 임시 주석
// app.use('/api/users', userRoutes);

View File

@ -0,0 +1,199 @@
/**
*
*/
import { Request, Response } from 'express';
import * as workHistoryService from '../services/workHistoryService';
import { CreateWorkHistoryDto, UpdateWorkHistoryDto, WorkHistoryFilters } from '../types/workHistory';
/**
*
*/
export async function getWorkHistories(req: Request, res: Response): Promise<void> {
try {
const filters: WorkHistoryFilters = {
work_type: req.query.work_type as any,
status: req.query.status as any,
vehicle_number: req.query.vehicle_number as string,
driver_name: req.query.driver_name as string,
start_date: req.query.start_date ? new Date(req.query.start_date as string) : undefined,
end_date: req.query.end_date ? new Date(req.query.end_date as string) : undefined,
search: req.query.search as string,
};
const histories = await workHistoryService.getWorkHistories(filters);
res.json({
success: true,
data: histories,
});
} catch (error) {
console.error('작업 이력 목록 조회 실패:', error);
res.status(500).json({
success: false,
message: '작업 이력 목록 조회에 실패했습니다',
error: error instanceof Error ? error.message : String(error),
});
}
}
/**
*
*/
export async function getWorkHistoryById(req: Request, res: Response): Promise<void> {
try {
const id = parseInt(req.params.id);
const history = await workHistoryService.getWorkHistoryById(id);
if (!history) {
res.status(404).json({
success: false,
message: '작업 이력을 찾을 수 없습니다',
});
return;
}
res.json({
success: true,
data: history,
});
} catch (error) {
console.error('작업 이력 조회 실패:', error);
res.status(500).json({
success: false,
message: '작업 이력 조회에 실패했습니다',
error: error instanceof Error ? error.message : String(error),
});
}
}
/**
*
*/
export async function createWorkHistory(req: Request, res: Response): Promise<void> {
try {
const data: CreateWorkHistoryDto = req.body;
const history = await workHistoryService.createWorkHistory(data);
res.status(201).json({
success: true,
data: history,
message: '작업 이력이 생성되었습니다',
});
} catch (error) {
console.error('작업 이력 생성 실패:', error);
res.status(500).json({
success: false,
message: '작업 이력 생성에 실패했습니다',
error: error instanceof Error ? error.message : String(error),
});
}
}
/**
*
*/
export async function updateWorkHistory(req: Request, res: Response): Promise<void> {
try {
const id = parseInt(req.params.id);
const data: UpdateWorkHistoryDto = req.body;
const history = await workHistoryService.updateWorkHistory(id, data);
res.json({
success: true,
data: history,
message: '작업 이력이 수정되었습니다',
});
} catch (error) {
console.error('작업 이력 수정 실패:', error);
res.status(500).json({
success: false,
message: '작업 이력 수정에 실패했습니다',
error: error instanceof Error ? error.message : String(error),
});
}
}
/**
*
*/
export async function deleteWorkHistory(req: Request, res: Response): Promise<void> {
try {
const id = parseInt(req.params.id);
await workHistoryService.deleteWorkHistory(id);
res.json({
success: true,
message: '작업 이력이 삭제되었습니다',
});
} catch (error) {
console.error('작업 이력 삭제 실패:', error);
res.status(500).json({
success: false,
message: '작업 이력 삭제에 실패했습니다',
error: error instanceof Error ? error.message : String(error),
});
}
}
/**
*
*/
export async function getWorkHistoryStats(req: Request, res: Response): Promise<void> {
try {
const stats = await workHistoryService.getWorkHistoryStats();
res.json({
success: true,
data: stats,
});
} catch (error) {
console.error('작업 이력 통계 조회 실패:', error);
res.status(500).json({
success: false,
message: '작업 이력 통계 조회에 실패했습니다',
error: error instanceof Error ? error.message : String(error),
});
}
}
/**
*
*/
export async function getMonthlyTrend(req: Request, res: Response): Promise<void> {
try {
const months = parseInt(req.query.months as string) || 6;
const trend = await workHistoryService.getMonthlyTrend(months);
res.json({
success: true,
data: trend,
});
} catch (error) {
console.error('월별 추이 조회 실패:', error);
res.status(500).json({
success: false,
message: '월별 추이 조회에 실패했습니다',
error: error instanceof Error ? error.message : String(error),
});
}
}
/**
*
*/
export async function getTopRoutes(req: Request, res: Response): Promise<void> {
try {
const limit = parseInt(req.query.limit as string) || 5;
const routes = await workHistoryService.getTopRoutes(limit);
res.json({
success: true,
data: routes,
});
} catch (error) {
console.error('주요 운송 경로 조회 실패:', error);
res.status(500).json({
success: false,
message: '주요 운송 경로 조회에 실패했습니다',
error: error instanceof Error ? error.message : String(error),
});
}
}

View File

@ -0,0 +1,35 @@
/**
*
*/
import express from 'express';
import * as workHistoryController from '../controllers/workHistoryController';
const router = express.Router();
// 작업 이력 목록 조회
router.get('/', workHistoryController.getWorkHistories);
// 작업 이력 통계 조회
router.get('/stats', workHistoryController.getWorkHistoryStats);
// 월별 추이 조회
router.get('/trend', workHistoryController.getMonthlyTrend);
// 주요 운송 경로 조회
router.get('/routes', workHistoryController.getTopRoutes);
// 작업 이력 단건 조회
router.get('/:id', workHistoryController.getWorkHistoryById);
// 작업 이력 생성
router.post('/', workHistoryController.createWorkHistory);
// 작업 이력 수정
router.put('/:id', workHistoryController.updateWorkHistory);
// 작업 이력 삭제
router.delete('/:id', workHistoryController.deleteWorkHistory);
export default router;

View File

@ -153,18 +153,35 @@ export class YardLayoutService {
`;
const pool = getPool();
// NaN 방지를 위한 안전한 변환 함수
const safeParseInt = (
value: any,
defaultValue: number | null = null
): number | null => {
if (!value && value !== 0) return defaultValue;
const parsed = parseInt(String(value), 10);
return isNaN(parsed) ? defaultValue : parsed;
};
const safeParseFloat = (value: any, defaultValue: number): number => {
if (!value && value !== 0) return defaultValue;
const parsed = parseFloat(String(value));
return isNaN(parsed) ? defaultValue : parsed;
};
const result = await pool.query(query, [
layoutId,
data.material_code || null,
data.material_name || null,
data.quantity || null,
safeParseInt(data.quantity, null),
data.unit || null,
data.position_x || 0,
data.position_y || 0,
data.position_z || 0,
data.size_x || 5,
data.size_y || 5,
data.size_z || 5,
safeParseFloat(data.position_x, 0),
safeParseFloat(data.position_y, 0),
safeParseFloat(data.position_z, 0),
safeParseFloat(data.size_x, 5),
safeParseFloat(data.size_y, 5),
safeParseFloat(data.size_z, 5),
data.color || "#9ca3af", // 미설정 시 회색
data.data_source_type || null,
data.data_source_config ? JSON.stringify(data.data_source_config) : null,
@ -201,17 +218,31 @@ export class YardLayoutService {
`;
const pool = getPool();
// NaN 방지를 위한 안전한 변환 함수
const safeParseInt = (value: any): number | null => {
if (value === null || value === undefined) return null;
const parsed = parseInt(String(value), 10);
return isNaN(parsed) ? null : parsed;
};
const safeParseFloat = (value: any): number | null => {
if (value === null || value === undefined) return null;
const parsed = parseFloat(String(value));
return isNaN(parsed) ? null : parsed;
};
const result = await pool.query(query, [
data.material_code !== undefined ? data.material_code : null,
data.material_name !== undefined ? data.material_name : null,
data.quantity !== undefined ? data.quantity : null,
data.quantity !== undefined ? safeParseInt(data.quantity) : null,
data.unit !== undefined ? data.unit : null,
data.position_x !== undefined ? data.position_x : null,
data.position_y !== undefined ? data.position_y : null,
data.position_z !== undefined ? data.position_z : null,
data.size_x !== undefined ? data.size_x : null,
data.size_y !== undefined ? data.size_y : null,
data.size_z !== undefined ? data.size_z : null,
data.position_x !== undefined ? safeParseFloat(data.position_x) : null,
data.position_y !== undefined ? safeParseFloat(data.position_y) : null,
data.position_z !== undefined ? safeParseFloat(data.position_z) : null,
data.size_x !== undefined ? safeParseFloat(data.size_x) : null,
data.size_y !== undefined ? safeParseFloat(data.size_y) : null,
data.size_z !== undefined ? safeParseFloat(data.size_z) : null,
data.color !== undefined ? data.color : null,
data.data_source_type !== undefined ? data.data_source_type : null,
data.data_source_config !== undefined

View File

@ -53,6 +53,8 @@ const ALLOWED_TABLES = [
"table_labels",
"column_labels",
"dynamic_form_data",
"work_history", // 작업 이력 테이블
"delivery_status", // 배송 현황 테이블
];
/**

View File

@ -0,0 +1,335 @@
/**
*
*/
import pool from '../database/db';
import {
WorkHistory,
CreateWorkHistoryDto,
UpdateWorkHistoryDto,
WorkHistoryFilters,
WorkHistoryStats,
MonthlyTrend,
TopRoute,
} from '../types/workHistory';
/**
*
*/
export async function getWorkHistories(filters?: WorkHistoryFilters): Promise<WorkHistory[]> {
try {
let query = `
SELECT * FROM work_history
WHERE deleted_at IS NULL
`;
const params: (string | Date)[] = [];
let paramIndex = 1;
// 필터 적용
if (filters?.work_type) {
query += ` AND work_type = $${paramIndex}`;
params.push(filters.work_type);
paramIndex++;
}
if (filters?.status) {
query += ` AND status = $${paramIndex}`;
params.push(filters.status);
paramIndex++;
}
if (filters?.vehicle_number) {
query += ` AND vehicle_number LIKE $${paramIndex}`;
params.push(`%${filters.vehicle_number}%`);
paramIndex++;
}
if (filters?.driver_name) {
query += ` AND driver_name LIKE $${paramIndex}`;
params.push(`%${filters.driver_name}%`);
paramIndex++;
}
if (filters?.start_date) {
query += ` AND work_date >= $${paramIndex}`;
params.push(filters.start_date);
paramIndex++;
}
if (filters?.end_date) {
query += ` AND work_date <= $${paramIndex}`;
params.push(filters.end_date);
paramIndex++;
}
if (filters?.search) {
query += ` AND (
work_number LIKE $${paramIndex} OR
vehicle_number LIKE $${paramIndex} OR
driver_name LIKE $${paramIndex} OR
cargo_name LIKE $${paramIndex}
)`;
params.push(`%${filters.search}%`);
paramIndex++;
}
query += ` ORDER BY work_date DESC`;
const result: any = await pool.query(query, params);
return result.rows;
} catch (error) {
console.error('작업 이력 조회 실패:', error);
throw error;
}
}
/**
*
*/
export async function getWorkHistoryById(id: number): Promise<WorkHistory | null> {
try {
const result: any = await pool.query(
'SELECT * FROM work_history WHERE id = $1 AND deleted_at IS NULL',
[id]
);
return result.rows[0] || null;
} catch (error) {
console.error('작업 이력 조회 실패:', error);
throw error;
}
}
/**
*
*/
export async function createWorkHistory(data: CreateWorkHistoryDto): Promise<WorkHistory> {
try {
const result: any = await pool.query(
`INSERT INTO work_history (
work_type, vehicle_number, driver_name, origin, destination,
cargo_name, cargo_weight, cargo_unit, distance, distance_unit,
status, scheduled_time, estimated_arrival, notes, created_by
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
RETURNING *`,
[
data.work_type,
data.vehicle_number,
data.driver_name,
data.origin,
data.destination,
data.cargo_name,
data.cargo_weight,
data.cargo_unit || 'ton',
data.distance,
data.distance_unit || 'km',
data.status || 'pending',
data.scheduled_time,
data.estimated_arrival,
data.notes,
data.created_by,
]
);
return result.rows[0];
} catch (error) {
console.error('작업 이력 생성 실패:', error);
throw error;
}
}
/**
*
*/
export async function updateWorkHistory(id: number, data: UpdateWorkHistoryDto): Promise<WorkHistory> {
try {
const fields: string[] = [];
const values: any[] = [];
let paramIndex = 1;
Object.entries(data).forEach(([key, value]) => {
if (value !== undefined) {
fields.push(`${key} = $${paramIndex}`);
values.push(value);
paramIndex++;
}
});
if (fields.length === 0) {
throw new Error('수정할 데이터가 없습니다');
}
values.push(id);
const query = `
UPDATE work_history
SET ${fields.join(', ')}
WHERE id = $${paramIndex} AND deleted_at IS NULL
RETURNING *
`;
const result: any = await pool.query(query, values);
if (result.rows.length === 0) {
throw new Error('작업 이력을 찾을 수 없습니다');
}
return result.rows[0];
} catch (error) {
console.error('작업 이력 수정 실패:', error);
throw error;
}
}
/**
* ( )
*/
export async function deleteWorkHistory(id: number): Promise<void> {
try {
const result: any = await pool.query(
'UPDATE work_history SET deleted_at = CURRENT_TIMESTAMP WHERE id = $1 AND deleted_at IS NULL',
[id]
);
if (result.rowCount === 0) {
throw new Error('작업 이력을 찾을 수 없습니다');
}
} catch (error) {
console.error('작업 이력 삭제 실패:', error);
throw error;
}
}
/**
*
*/
export async function getWorkHistoryStats(): Promise<WorkHistoryStats> {
try {
// 오늘 작업 통계
const todayResult: any = await pool.query(`
SELECT
COUNT(*) as today_total,
COUNT(*) FILTER (WHERE status = 'completed') as today_completed
FROM work_history
WHERE DATE(work_date) = CURRENT_DATE AND deleted_at IS NULL
`);
// 총 운송량 및 거리
const totalResult: any = await pool.query(`
SELECT
COALESCE(SUM(cargo_weight), 0) as total_weight,
COALESCE(SUM(distance), 0) as total_distance
FROM work_history
WHERE deleted_at IS NULL AND status = 'completed'
`);
// 정시 도착률
const onTimeResult: any = await pool.query(`
SELECT
COUNT(*) FILTER (WHERE is_on_time = true) * 100.0 / NULLIF(COUNT(*), 0) as on_time_rate
FROM work_history
WHERE deleted_at IS NULL
AND status = 'completed'
AND is_on_time IS NOT NULL
`);
// 작업 유형별 분포
const typeResult: any = await pool.query(`
SELECT
work_type,
COUNT(*) as count
FROM work_history
WHERE deleted_at IS NULL
GROUP BY work_type
`);
const typeDistribution = {
inbound: 0,
outbound: 0,
transfer: 0,
maintenance: 0,
};
typeResult.rows.forEach((row: any) => {
typeDistribution[row.work_type as keyof typeof typeDistribution] = parseInt(row.count);
});
return {
today_total: parseInt(todayResult.rows[0].today_total),
today_completed: parseInt(todayResult.rows[0].today_completed),
total_weight: parseFloat(totalResult.rows[0].total_weight),
total_distance: parseFloat(totalResult.rows[0].total_distance),
on_time_rate: parseFloat(onTimeResult.rows[0]?.on_time_rate || '0'),
type_distribution: typeDistribution,
};
} catch (error) {
console.error('작업 이력 통계 조회 실패:', error);
throw error;
}
}
/**
*
*/
export async function getMonthlyTrend(months: number = 6): Promise<MonthlyTrend[]> {
try {
const result: any = await pool.query(
`
SELECT
TO_CHAR(work_date, 'YYYY-MM') as month,
COUNT(*) as total,
COUNT(*) FILTER (WHERE status = 'completed') as completed,
COALESCE(SUM(cargo_weight), 0) as weight,
COALESCE(SUM(distance), 0) as distance
FROM work_history
WHERE deleted_at IS NULL
AND work_date >= CURRENT_DATE - INTERVAL '${months} months'
GROUP BY TO_CHAR(work_date, 'YYYY-MM')
ORDER BY month DESC
`,
[]
);
return result.rows.map((row: any) => ({
month: row.month,
total: parseInt(row.total),
completed: parseInt(row.completed),
weight: parseFloat(row.weight),
distance: parseFloat(row.distance),
}));
} catch (error) {
console.error('월별 추이 조회 실패:', error);
throw error;
}
}
/**
*
*/
export async function getTopRoutes(limit: number = 5): Promise<TopRoute[]> {
try {
const result: any = await pool.query(
`
SELECT
origin,
destination,
COUNT(*) as count,
COALESCE(SUM(cargo_weight), 0) as total_weight
FROM work_history
WHERE deleted_at IS NULL
AND origin IS NOT NULL
AND destination IS NOT NULL
AND work_type IN ('inbound', 'outbound', 'transfer')
GROUP BY origin, destination
ORDER BY count DESC
LIMIT $1
`,
[limit]
);
return result.rows.map((row: any) => ({
origin: row.origin,
destination: row.destination,
count: parseInt(row.count),
total_weight: parseFloat(row.total_weight),
}));
} catch (error) {
console.error('주요 운송 경로 조회 실패:', error);
throw error;
}
}

View File

@ -0,0 +1,114 @@
/**
*
*/
export type WorkType = 'inbound' | 'outbound' | 'transfer' | 'maintenance';
export type WorkStatus = 'pending' | 'in_progress' | 'completed' | 'cancelled';
export interface WorkHistory {
id: number;
work_number: string;
work_date: Date;
work_type: WorkType;
vehicle_number?: string;
driver_name?: string;
origin?: string;
destination?: string;
cargo_name?: string;
cargo_weight?: number;
cargo_unit?: string;
distance?: number;
distance_unit?: string;
status: WorkStatus;
scheduled_time?: Date;
start_time?: Date;
end_time?: Date;
estimated_arrival?: Date;
actual_arrival?: Date;
is_on_time?: boolean;
delay_reason?: string;
notes?: string;
created_by?: string;
created_at: Date;
updated_at: Date;
deleted_at?: Date;
}
export interface CreateWorkHistoryDto {
work_type: WorkType;
vehicle_number?: string;
driver_name?: string;
origin?: string;
destination?: string;
cargo_name?: string;
cargo_weight?: number;
cargo_unit?: string;
distance?: number;
distance_unit?: string;
status?: WorkStatus;
scheduled_time?: Date;
estimated_arrival?: Date;
notes?: string;
created_by?: string;
}
export interface UpdateWorkHistoryDto {
work_type?: WorkType;
vehicle_number?: string;
driver_name?: string;
origin?: string;
destination?: string;
cargo_name?: string;
cargo_weight?: number;
cargo_unit?: string;
distance?: number;
distance_unit?: string;
status?: WorkStatus;
scheduled_time?: Date;
start_time?: Date;
end_time?: Date;
estimated_arrival?: Date;
actual_arrival?: Date;
delay_reason?: string;
notes?: string;
}
export interface WorkHistoryFilters {
work_type?: WorkType;
status?: WorkStatus;
vehicle_number?: string;
driver_name?: string;
start_date?: Date;
end_date?: Date;
search?: string;
}
export interface WorkHistoryStats {
today_total: number;
today_completed: number;
total_weight: number;
total_distance: number;
on_time_rate: number;
type_distribution: {
inbound: number;
outbound: number;
transfer: number;
maintenance: number;
};
}
export interface MonthlyTrend {
month: string;
total: number;
completed: number;
weight: number;
distance: number;
}
export interface TopRoute {
origin: string;
destination: string;
count: number;
total_weight: number;
}

View File

@ -1,7 +1,6 @@
"use client";
import React, { useState, useEffect, use } from "react";
import { useRouter } from "next/navigation";
import { DashboardViewer } from "@/components/dashboard/DashboardViewer";
import { DashboardElement } from "@/components/admin/dashboard/types";
@ -18,7 +17,6 @@ interface DashboardViewPageProps {
* -
*/
export default function DashboardViewPage({ params }: DashboardViewPageProps) {
const router = useRouter();
const resolvedParams = use(params);
const [dashboard, setDashboard] = useState<{
id: string;
@ -35,12 +33,7 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// 대시보드 데이터 로딩
useEffect(() => {
loadDashboard();
}, [resolvedParams.dashboardId]);
const loadDashboard = async () => {
const loadDashboard = React.useCallback(async () => {
setIsLoading(true);
setError(null);
@ -50,13 +43,16 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
try {
const dashboardData = await dashboardApi.getDashboard(resolvedParams.dashboardId);
setDashboard(dashboardData);
setDashboard({
...dashboardData,
elements: dashboardData.elements || [],
});
} catch (apiError) {
console.warn("API 호출 실패, 로컬 스토리지 확인:", apiError);
// API 실패 시 로컬 스토리지에서 찾기
const savedDashboards = JSON.parse(localStorage.getItem("savedDashboards") || "[]");
const savedDashboard = savedDashboards.find((d: any) => d.id === resolvedParams.dashboardId);
const savedDashboard = savedDashboards.find((d: { id: string }) => d.id === resolvedParams.dashboardId);
if (savedDashboard) {
setDashboard(savedDashboard);
@ -72,7 +68,12 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
} finally {
setIsLoading(false);
}
};
}, [resolvedParams.dashboardId]);
// 대시보드 데이터 로딩
useEffect(() => {
loadDashboard();
}, [loadDashboard]);
// 로딩 상태
if (isLoading) {
@ -159,10 +160,11 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
</div> */}
{/* 대시보드 뷰어 */}
<DashboardViewer
elements={dashboard.elements}
<DashboardViewer
elements={dashboard.elements}
dashboardId={dashboard.id}
backgroundColor={dashboard.settings?.backgroundColor}
resolution={dashboard.settings?.resolution}
/>
</div>
);
@ -171,8 +173,33 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
/**
*
*/
function generateSampleDashboard(dashboardId: string) {
const dashboards: Record<string, any> = {
function generateSampleDashboard(dashboardId: string): {
id: string;
title: string;
description?: string;
elements: DashboardElement[];
settings?: {
backgroundColor?: string;
resolution?: string;
};
createdAt: string;
updatedAt: string;
} {
const dashboards: Record<
string,
{
id: string;
title: string;
description?: string;
elements: DashboardElement[];
settings?: {
backgroundColor?: string;
resolution?: string;
};
createdAt: string;
updatedAt: string;
}
> = {
"sales-overview": {
id: "sales-overview",
title: "📊 매출 현황 대시보드",

View File

@ -4,7 +4,7 @@ import React, { useState, useCallback, useRef, useEffect } from "react";
import dynamic from "next/dynamic";
import { DashboardElement, QueryResult } from "./types";
import { ChartRenderer } from "./charts/ChartRenderer";
import { snapToGrid, snapSizeToGrid, GRID_CONFIG } from "./gridUtils";
import { GRID_CONFIG } from "./gridUtils";
// 위젯 동적 임포트
const WeatherWidget = dynamic(() => import("@/components/dashboard/widgets/WeatherWidget"), {
@ -112,10 +112,23 @@ const YardManagement3DWidget = dynamic(() => import("./widgets/YardManagement3DW
loading: () => <div className="flex h-full items-center justify-center text-sm text-gray-500"> ...</div>,
});
// 작업 이력 위젯
const WorkHistoryWidget = dynamic(() => import("@/components/dashboard/widgets/WorkHistoryWidget"), {
ssr: false,
loading: () => <div className="flex h-full items-center justify-center text-sm text-gray-500"> ...</div>,
});
// 커스텀 통계 카드 위젯
const CustomStatsWidget = dynamic(() => import("@/components/dashboard/widgets/CustomStatsWidget"), {
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;
subGridSize: number;
canvasWidth?: number;
onUpdate: (id: string, updates: Partial<DashboardElement>) => void;
onRemove: (id: string) => void;
@ -133,6 +146,7 @@ export function CanvasElement({
element,
isSelected,
cellSize,
subGridSize,
canvasWidth = 1560,
onUpdate,
onRemove,
@ -233,7 +247,6 @@ export function CanvasElement({
rawX = Math.min(rawX, maxX);
// 드래그 중 실시간 스냅 (마그네틱 스냅)
const subGridSize = Math.floor(cellSize / 3);
const gridSize = cellSize + 5; // GAP 포함한 실제 그리드 크기
const magneticThreshold = 15; // 큰 그리드에 끌리는 거리 (px)
@ -291,7 +304,6 @@ export function CanvasElement({
newWidth = Math.min(newWidth, maxWidth);
// 리사이즈 중 실시간 스냅 (마그네틱 스냅)
const subGridSize = Math.floor(cellSize / 3);
const gridSize = cellSize + 5; // GAP 포함한 실제 그리드 크기
const magneticThreshold = 15;
@ -336,6 +348,7 @@ export function CanvasElement({
element.subtype,
canvasWidth,
cellSize,
subGridSize,
],
);
@ -726,10 +739,21 @@ export function CanvasElement({
isEditMode={true}
config={element.yardConfig}
onConfigChange={(newConfig) => {
// console.log("🏗️ 야드 설정 업데이트:", { elementId: element.id, newConfig });
onUpdate(element.id, { yardConfig: newConfig });
}}
/>
</div>
) : element.type === "widget" && element.subtype === "work-history" ? (
// 작업 이력 위젯 렌더링
<div className="h-full w-full">
<WorkHistoryWidget element={element} />
</div>
) : element.type === "widget" && element.subtype === "transport-stats" ? (
// 커스텀 통계 카드 위젯 렌더링
<div className="h-full w-full">
<CustomStatsWidget element={element} />
</div>
) : element.type === "widget" && element.subtype === "todo" ? (
// To-Do 위젯 렌더링
<div className="widget-interactive-area h-full w-full">

View File

@ -156,8 +156,7 @@ export const DashboardCanvas = forwardRef<HTMLDivElement, DashboardCanvasProps>(
const rawY = e.clientY - rect.top + (ref.current?.scrollTop || 0);
// 마그네틱 스냅 (큰 그리드 우선, 없으면 서브그리드)
const subGridSize = Math.floor(cellSize / 3);
const gridSize = cellSize + 5; // GAP 포함한 실제 그리드 크기
const gridSize = cellSize + GRID_CONFIG.GAP; // GAP 포함한 실제 그리드 크기
const magneticThreshold = 15;
// X 좌표 스냅
@ -196,6 +195,9 @@ export const DashboardCanvas = forwardRef<HTMLDivElement, DashboardCanvasProps>(
// 동적 그리드 크기 계산
const cellWithGap = cellSize + GRID_CONFIG.GAP;
const gridSize = `${cellWithGap}px ${cellWithGap}px`;
// 서브그리드 크기 계산 (gridConfig에서 정확하게 계산된 값 사용)
const subGridSize = gridConfig.SUB_GRID_SIZE;
// 12개 컬럼 구분선 위치 계산
const columnLines = Array.from({ length: GRID_CONFIG.COLUMNS + 1 }, (_, i) => i * cellWithGap);
@ -208,12 +210,12 @@ export const DashboardCanvas = forwardRef<HTMLDivElement, DashboardCanvasProps>(
backgroundColor,
height: `${canvasHeight}px`,
minHeight: `${canvasHeight}px`,
// 세밀한 그리드 배경
// 서브그리드 배경 (세밀한 점선)
backgroundImage: `
linear-gradient(rgba(59, 130, 246, 0.08) 1px, transparent 1px),
linear-gradient(90deg, rgba(59, 130, 246, 0.08) 1px, transparent 1px)
linear-gradient(rgba(59, 130, 246, 0.05) 1px, transparent 1px),
linear-gradient(90deg, rgba(59, 130, 246, 0.05) 1px, transparent 1px)
`,
backgroundSize: gridSize,
backgroundSize: `${subGridSize}px ${subGridSize}px`,
backgroundPosition: "0 0",
backgroundRepeat: "repeat",
}}
@ -229,8 +231,9 @@ export const DashboardCanvas = forwardRef<HTMLDivElement, DashboardCanvasProps>(
className="pointer-events-none absolute top-0 h-full"
style={{
left: `${x}px`,
width: "2px",
zIndex: 1,
width: "1px",
backgroundColor: i === 0 || i === GRID_CONFIG.COLUMNS ? "rgba(59, 130, 246, 0.3)" : "rgba(59, 130, 246, 0.15)",
zIndex: 0,
}}
/>
))}
@ -248,6 +251,7 @@ export const DashboardCanvas = forwardRef<HTMLDivElement, DashboardCanvasProps>(
element={element}
isSelected={selectedElement === element.id}
cellSize={cellSize}
subGridSize={subGridSize}
canvasWidth={canvasWidth}
onUpdate={handleUpdateWithCollisionDetection}
onRemove={onRemoveElement}

View File

@ -6,6 +6,7 @@ import { DashboardCanvas } from "./DashboardCanvas";
import { DashboardTopMenu } from "./DashboardTopMenu";
import { ElementConfigModal } from "./ElementConfigModal";
import { ListWidgetConfigModal } from "./widgets/ListWidgetConfigModal";
import { YardWidgetConfigModal } from "./widgets/YardWidgetConfigModal";
import { DashboardSaveModal } from "./DashboardSaveModal";
import { DashboardElement, ElementType, ElementSubtype } from "./types";
import { GRID_CONFIG, snapToGrid, snapSizeToGrid, calculateCellSize } from "./gridUtils";
@ -140,18 +141,38 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
const { dashboardApi } = await import("@/lib/api/dashboard");
const dashboard = await dashboardApi.getDashboard(id);
console.log("📊 대시보드 로드:", {
id: dashboard.id,
title: dashboard.title,
settings: dashboard.settings,
settingsType: typeof dashboard.settings,
});
// 대시보드 정보 설정
setDashboardId(dashboard.id);
setDashboardTitle(dashboard.title);
// 저장된 설정 복원
const settings = (dashboard as { settings?: { resolution?: Resolution; backgroundColor?: string } }).settings;
console.log("🎨 설정 복원:", {
settings,
resolution: settings?.resolution,
backgroundColor: settings?.backgroundColor,
currentResolution: resolution,
});
if (settings?.resolution) {
setResolution(settings.resolution);
console.log("✅ Resolution 설정됨:", settings.resolution);
} else {
console.log("⚠️ Resolution 없음, 기본값 유지:", resolution);
}
if (settings?.backgroundColor) {
setCanvasBackgroundColor(settings.backgroundColor);
console.log("✅ BackgroundColor 설정됨:", settings.backgroundColor);
} else {
console.log("⚠️ BackgroundColor 없음, 기본값 유지:", canvasBackgroundColor);
}
// 요소들 설정
@ -332,21 +353,31 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
try {
const { dashboardApi } = await import("@/lib/api/dashboard");
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,
}));
const elementsData = elements.map((el) => {
// 야드 위젯인 경우 설정 로그 출력
// if (el.subtype === "yard-management-3d") {
// console.log("💾 야드 위젯 저장:", {
// id: el.id,
// yardConfig: el.yardConfig,
// hasLayoutId: !!el.yardConfig?.layoutId,
// });
// }
return {
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,
};
});
let savedDashboard;
@ -495,6 +526,13 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
onClose={closeConfigModal}
onSave={saveListWidgetConfig}
/>
) : configModalElement.type === "widget" && configModalElement.subtype === "yard-management-3d" ? (
<YardWidgetConfigModal
element={configModalElement}
isOpen={true}
onClose={closeConfigModal}
onSave={saveListWidgetConfig}
/>
) : (
<ElementConfigModal
element={configModalElement}
@ -626,6 +664,10 @@ function getElementTitle(type: ElementType, subtype: ElementSubtype): string {
return "문서 위젯";
case "yard-management-3d":
return "야드 관리 3D";
case "work-history":
return "작업 이력";
case "transport-stats":
return "커스텀 통계 카드";
default:
return "위젯";
}
@ -668,6 +710,10 @@ function getElementContent(type: ElementType, subtype: ElementSubtype): string {
return "list-widget";
case "yard-management-3d":
return "yard-3d";
case "work-history":
return "work-history";
case "transport-stats":
return "커스텀 통계 카드";
default:
return "위젯 내용이 여기에 표시됩니다";
}

View File

@ -183,6 +183,10 @@ export function DashboardSaveModal({
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
onKeyDown={(e) => {
// 모든 키보드 이벤트를 input 필드 내부에서만 처리
e.stopPropagation();
}}
placeholder="예: 생산 현황 대시보드"
className="w-full"
/>
@ -195,6 +199,10 @@ export function DashboardSaveModal({
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
onKeyDown={(e) => {
// 모든 키보드 이벤트를 textarea 내부에서만 처리
e.stopPropagation();
}}
placeholder="대시보드에 대한 간단한 설명을 입력하세요"
rows={3}
className="w-full resize-none"

View File

@ -200,12 +200,13 @@ export function DashboardSidebar() {
subtype="todo"
onDragStart={handleDragStart}
/>
<DraggableItem
{/* 예약알림 위젯 - 필요시 주석 해제 */}
{/* <DraggableItem
title="예약 요청 알림"
type="widget"
subtype="booking-alert"
onDragStart={handleDragStart}
/>
/> */}
{/* 정비 일정 관리 위젯 제거 - 커스텀 목록 카드로 대체 가능 */}
<DraggableItem
title="문서 다운로드"
@ -219,6 +220,18 @@ export function DashboardSidebar() {
subtype="list"
onDragStart={handleDragStart}
/>
<DraggableItem
title="작업 이력"
type="widget"
subtype="work-history"
onDragStart={handleDragStart}
/>
<DraggableItem
title="커스텀 통계 카드"
type="widget"
subtype="transport-stats"
onDragStart={handleDragStart}
/>
</div>
)}
</div>

View File

@ -182,6 +182,7 @@ export function DashboardTopMenu({
<SelectLabel> </SelectLabel>
<SelectItem value="list"> </SelectItem>
<SelectItem value="yard-management-3d"> 3D</SelectItem>
<SelectItem value="transport-stats"> </SelectItem>
{/* <SelectItem value="map">지도</SelectItem> */}
<SelectItem value="map-summary"> </SelectItem>
{/* <SelectItem value="list-summary">커스텀 목록 카드</SelectItem> */}
@ -195,7 +196,7 @@ export function DashboardTopMenu({
<SelectItem value="calendar"></SelectItem>
<SelectItem value="clock"></SelectItem>
<SelectItem value="todo"> </SelectItem>
<SelectItem value="booking-alert"> </SelectItem>
{/* <SelectItem value="booking-alert">예약 알림</SelectItem> */}
<SelectItem value="maintenance"> </SelectItem>
<SelectItem value="document"></SelectItem>
<SelectItem value="risk-alert"> </SelectItem>

View File

@ -36,6 +36,11 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
// 차트 설정이 필요 없는 위젯 (쿼리/API만 필요)
const isSimpleWidget =
element.subtype === "todo" || // To-Do 위젯
element.subtype === "booking-alert" || // 예약 알림 위젯
element.subtype === "maintenance" || // 정비 일정 위젯
element.subtype === "document" || // 문서 위젯
element.subtype === "risk-alert" || // 리스크 알림 위젯
element.subtype === "vehicle-status" ||
element.subtype === "vehicle-list" ||
element.subtype === "status-summary" || // 커스텀 상태 카드
@ -45,7 +50,15 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
element.subtype === "delivery-today-stats" ||
element.subtype === "cargo-list" ||
element.subtype === "customer-issues" ||
element.subtype === "driver-management";
element.subtype === "driver-management" ||
element.subtype === "work-history" || // 작업 이력 위젯 (쿼리 필요)
element.subtype === "transport-stats"; // 커스텀 통계 카드 위젯 (쿼리 필요)
// 자체 기능 위젯 (DB 연결 불필요, 헤더 설정만 가능)
const isSelfContainedWidget =
element.subtype === "weather" || // 날씨 위젯 (외부 API)
element.subtype === "exchange" || // 환율 위젯 (외부 API)
element.subtype === "calculator"; // 계산기 위젯 (자체 기능)
// 지도 위젯 (위도/경도 매핑 필요)
const isMapWidget = element.subtype === "vehicle-map" || element.subtype === "map-summary";
@ -59,6 +72,7 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
setQueryResult(null);
setCurrentStep(1);
setCustomTitle(element.customTitle || "");
setShowHeader(element.showHeader !== false); // showHeader 초기화
}
}, [isOpen, element]);
@ -135,8 +149,12 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
// 모달이 열려있지 않으면 렌더링하지 않음
if (!isOpen) return null;
// 시계, 달력, To-Do 위젯은 헤더 설정만 가능
const isHeaderOnlyWidget = element.type === "widget" && (element.subtype === "clock" || element.subtype === "calendar" || element.subtype === "todo");
// 시계, 달력, 날씨, 환율, 계산기 위젯은 헤더 설정만 가능
const isHeaderOnlyWidget =
element.type === "widget" &&
(element.subtype === "clock" ||
element.subtype === "calendar" ||
isSelfContainedWidget);
// 기사관리 위젯은 자체 설정 UI를 가지고 있으므로 모달 표시하지 않음
if (element.type === "widget" && element.subtype === "driver-management") {
@ -154,11 +172,15 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
// customTitle이 변경되었는지 확인
const isTitleChanged = customTitle.trim() !== (element.customTitle || "");
// showHeader가 변경되었는지 확인
const isHeaderChanged = showHeader !== (element.showHeader !== false);
const canSave =
isTitleChanged || // 제목만 변경해도 저장 가능
isHeaderChanged || // 헤더 표시 여부만 변경해도 저장 가능
(isSimpleWidget
? // 간단한 위젯: 2단계에서 쿼리 테스트 후 저장 가능
? // 간단한 위젯: 2단계에서 쿼리 테스트 후 저장 가능 (차트 설정 불필요)
currentStep === 2 && queryResult && queryResult.rows.length > 0
: isMapWidget
? // 지도 위젯: 위도/경도 매핑 필요
@ -184,7 +206,7 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 backdrop-blur-sm">
<div
className={`flex flex-col rounded-xl border bg-white shadow-2xl ${
currentStep === 1 ? "h-auto max-h-[70vh] w-full max-w-3xl" : "h-[85vh] w-full max-w-5xl"
currentStep === 1 && !isSimpleWidget ? "h-auto max-h-[70vh] w-full max-w-3xl" : "h-[85vh] w-full max-w-5xl"
}`}
>
{/* 모달 헤더 */}
@ -336,7 +358,7 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
</Button>
) : currentStep === 1 ? (
// 1단계: 다음 버튼
// 1단계: 다음 버튼 (차트 위젯, 간단한 위젯 모두)
<Button onClick={handleNext}>
<ChevronRight className="ml-2 h-4 w-4" />
@ -354,3 +376,4 @@ export function ElementConfigModal({ element, isOpen, onClose, onSave }: Element
</div>
);
}

View File

@ -208,6 +208,10 @@ ORDER BY 하위부서수 DESC`,
<Textarea
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
// 모든 키보드 이벤트를 textarea 내부에서만 처리
e.stopPropagation();
}}
placeholder="SELECT * FROM your_table WHERE condition = 'value';"
className="h-40 resize-none font-mono text-sm"
/>

View File

@ -32,11 +32,12 @@ export function BarChart({ data, config, width = 600, height = 400 }: BarChartPr
// X축 스케일 (카테고리)
const xScale = d3.scaleBand().domain(data.labels).range([0, chartWidth]).padding(0.2);
// Y축 스케일 (값)
const maxValue = d3.max(data.datasets.flatMap((ds) => ds.data)) || 0;
// Y축 스케일 (값) - 절대값 기준
const allValues = data.datasets.flatMap((ds) => ds.data);
const maxAbsValue = d3.max(allValues.map((v) => Math.abs(v))) || 0;
const yScale = d3
.scaleLinear()
.domain([0, maxValue * 1.1])
.domain([0, maxAbsValue * 1.1])
.range([chartHeight, 0])
.nice();
@ -49,23 +50,12 @@ export function BarChart({ data, config, width = 600, height = 400 }: BarChartPr
.style("text-anchor", "end")
.style("font-size", "12px");
// Y축 그리기
g.append("g").call(d3.axisLeft(yScale)).style("font-size", "12px");
// Y축 그리기 (값 표시 제거)
g.append("g")
.call(d3.axisLeft(yScale).tickFormat(() => ""))
.style("font-size", "12px");
// 그리드 라인
if (config.showGrid !== false) {
g.append("g")
.attr("class", "grid")
.call(
d3
.axisLeft(yScale)
.tickSize(-chartWidth)
.tickFormat(() => ""),
)
.style("stroke-dasharray", "3,3")
.style("stroke", "#e0e0e0")
.style("opacity", 0.5);
}
// 그리드 라인 제거됨
// 색상 팔레트
const colors = config.colors || ["#3B82F6", "#EF4444", "#10B981", "#F59E0B"];
@ -84,18 +74,48 @@ export function BarChart({ data, config, width = 600, height = 400 }: BarChartPr
.attr("y", chartHeight)
.attr("width", barWidth)
.attr("height", 0)
.attr("fill", dataset.color || colors[i % colors.length])
.attr("fill", (d) => {
// 음수면 빨간색 계열, 양수면 원래 색상
if (d < 0) {
return "#EF4444";
}
return dataset.color || colors[i % colors.length];
})
.attr("rx", 4);
// 애니메이션
// 애니메이션 - 절대값 기준으로 위쪽으로만 렌더링
if (config.enableAnimation !== false) {
bars
.transition()
.duration(config.animationDuration || 750)
.attr("y", (d) => yScale(d))
.attr("height", (d) => chartHeight - yScale(d));
.attr("y", (d) => yScale(Math.abs(d)))
.attr("height", (d) => chartHeight - yScale(Math.abs(d)));
} else {
bars.attr("y", (d) => yScale(d)).attr("height", (d) => chartHeight - yScale(d));
bars.attr("y", (d) => yScale(Math.abs(d))).attr("height", (d) => chartHeight - yScale(Math.abs(d)));
}
// 막대 위에 값 표시 (음수는 - 부호 포함)
const labels = g
.selectAll(`.label-${i}`)
.data(dataset.data)
.enter()
.append("text")
.attr("class", `label-${i}`)
.attr("x", (_, j) => (xScale(data.labels[j]) || 0) + barWidth * i + barWidth / 2)
.attr("y", (d) => yScale(Math.abs(d)) - 5)
.attr("text-anchor", "middle")
.style("font-size", "11px")
.style("font-weight", "500")
.style("fill", (d) => (d < 0 ? "#EF4444" : "#333"))
.text((d) => (d < 0 ? "-" : "") + Math.abs(d).toLocaleString());
// 애니메이션 (라벨)
if (config.enableAnimation !== false) {
labels
.style("opacity", 0)
.transition()
.duration(config.animationDuration || 750)
.style("opacity", 1);
}
// 툴팁

View File

@ -32,37 +32,25 @@ export function HorizontalBarChart({ data, config, width = 600, height = 400 }:
// Y축 스케일 (카테고리) - 수평이므로 Y축이 카테고리
const yScale = d3.scaleBand().domain(data.labels).range([0, chartHeight]).padding(0.2);
// X축 스케일 (값) - 수평이므로 X축이 값
const maxValue = d3.max(data.datasets.flatMap((ds) => ds.data)) || 0;
// X축 스케일 (값) - 수평이므로 X축이 값, 절대값 기준
const allValues = data.datasets.flatMap((ds) => ds.data);
const maxAbsValue = d3.max(allValues.map((v) => Math.abs(v))) || 0;
const xScale = d3
.scaleLinear()
.domain([0, maxValue * 1.1])
.domain([0, maxAbsValue * 1.1])
.range([0, chartWidth])
.nice();
// Y축 그리기 (카테고리)
g.append("g").call(d3.axisLeft(yScale)).style("font-size", "12px").selectAll("text").style("text-anchor", "end");
// X축 그리기 (값)
// X축 그리기 (값 표시 제거)
g.append("g")
.attr("transform", `translate(0,${chartHeight})`)
.call(d3.axisBottom(xScale))
.call(d3.axisBottom(xScale).tickFormat(() => ""))
.style("font-size", "12px");
// 그리드 라인
if (config.showGrid !== false) {
g.append("g")
.attr("class", "grid")
.call(
d3
.axisBottom(xScale)
.tickSize(chartHeight)
.tickFormat(() => ""),
)
.style("stroke-dasharray", "3,3")
.style("stroke", "#e0e0e0")
.style("opacity", 0.5);
}
// 그리드 라인 제거됨
// 색상 팔레트
const colors = config.colors || ["#3B82F6", "#EF4444", "#10B981", "#F59E0B"];
@ -81,17 +69,49 @@ export function HorizontalBarChart({ data, config, width = 600, height = 400 }:
.attr("y", (_, j) => (yScale(data.labels[j]) || 0) + barHeight * i)
.attr("width", 0)
.attr("height", barHeight)
.attr("fill", dataset.color || colors[i % colors.length])
.attr("fill", (d) => {
// 음수면 빨간색 계열, 양수면 원래 색상
if (d < 0) {
return "#EF4444";
}
return dataset.color || colors[i % colors.length];
})
.attr("ry", 4);
// 애니메이션
// 애니메이션 - 절대값 기준으로 오른쪽으로만 렌더링
if (config.enableAnimation !== false) {
bars
.transition()
.duration(config.animationDuration || 750)
.attr("width", (d) => xScale(d));
.attr("x", 0)
.attr("width", (d) => xScale(Math.abs(d)));
} else {
bars.attr("width", (d) => xScale(d));
bars.attr("x", 0).attr("width", (d) => xScale(Math.abs(d)));
}
// 막대 끝에 값 표시 (음수는 - 부호 포함)
const labels = g
.selectAll(`.label-${i}`)
.data(dataset.data)
.enter()
.append("text")
.attr("class", `label-${i}`)
.attr("x", (d) => xScale(Math.abs(d)) + 5)
.attr("y", (_, j) => (yScale(data.labels[j]) || 0) + barHeight * i + barHeight / 2)
.attr("text-anchor", "start")
.attr("dominant-baseline", "middle")
.style("font-size", "11px")
.style("font-weight", "500")
.style("fill", (d) => (d < 0 ? "#EF4444" : "#333"))
.text((d) => (d < 0 ? "-" : "") + Math.abs(d).toLocaleString());
// 애니메이션 (라벨)
if (config.enableAnimation !== false) {
labels
.style("opacity", 0)
.transition()
.duration(config.animationDuration || 750)
.style("opacity", 1);
}
// 툴팁

View File

@ -66,24 +66,12 @@ export function StackedBarChart({ data, config, width = 600, height = 400 }: Sta
.style("text-anchor", "end")
.style("font-size", "12px");
// Y축 그리기
const yAxis = config.stackMode === "percent" ? d3.axisLeft(yScale).tickFormat((d) => `${d}%`) : d3.axisLeft(yScale);
g.append("g").call(yAxis).style("font-size", "12px");
// Y축 그리기 (값 표시 제거)
g.append("g")
.call(d3.axisLeft(yScale).tickFormat(() => ""))
.style("font-size", "12px");
// 그리드 라인
if (config.showGrid !== false) {
g.append("g")
.attr("class", "grid")
.call(
d3
.axisLeft(yScale)
.tickSize(-chartWidth)
.tickFormat(() => ""),
)
.style("stroke-dasharray", "3,3")
.style("stroke", "#e0e0e0")
.style("opacity", 0.5);
}
// 그리드 라인 제거됨
// 색상 팔레트
const colors = config.colors || ["#3B82F6", "#EF4444", "#10B981", "#F59E0B"];
@ -131,6 +119,47 @@ export function StackedBarChart({ data, config, width = 600, height = 400 }: Sta
.attr("height", (d) => yScale(d[0] as number) - yScale(d[1] as number));
}
// 각 세그먼트에 값 표시
layers.each(function (layerData, layerIndex) {
d3.select(this)
.selectAll("text")
.data(layerData)
.enter()
.append("text")
.attr("x", (d) => (xScale((d.data as any).label) || 0) + xScale.bandwidth() / 2)
.attr("y", (d) => {
const segmentHeight = yScale(d[0] as number) - yScale(d[1] as number);
const segmentMiddle = yScale(d[1] as number) + segmentHeight / 2;
return segmentMiddle;
})
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.style("font-size", "11px")
.style("font-weight", "500")
.style("fill", "white")
.style("pointer-events", "none")
.text((d) => {
const value = (d[1] as number) - (d[0] as number);
if (config.stackMode === "percent") {
return value > 5 ? `${value.toFixed(0)}%` : "";
}
return value > 0 ? value.toLocaleString() : "";
})
.style("opacity", 0);
// 애니메이션 (라벨)
if (config.enableAnimation !== false) {
d3.select(this)
.selectAll("text")
.transition()
.delay(config.animationDuration || 750)
.duration(300)
.style("opacity", 1);
} else {
d3.select(this).selectAll("text").style("opacity", 1);
}
});
// 툴팁
if (config.showTooltip !== false) {
bars

View File

@ -36,7 +36,9 @@ export type ElementSubtype =
| "maintenance"
| "document"
| "list"
| "yard-management-3d"; // 야드 관리 3D 위젯
| "yard-management-3d" // 야드 관리 3D 위젯
| "work-history" // 작업 이력 위젯
| "transport-stats"; // 커스텀 통계 카드 위젯
export interface Position {
x: number;

View File

@ -95,24 +95,21 @@ export function ListWidgetConfigModal({ isOpen, element, onClose, onSave }: List
}, []);
// 쿼리 실행 결과 처리
const handleQueryTest = useCallback(
(result: QueryResult) => {
setQueryResult(result);
const handleQueryTest = useCallback((result: QueryResult) => {
setQueryResult(result);
// 자동 모드이고 기존 컬럼이 없을 때만 자동 생성
if (listConfig.columnMode === "auto" && result.columns.length > 0 && listConfig.columns.length === 0) {
const autoColumns: ListColumn[] = result.columns.map((col, idx) => ({
id: `col_${idx}`,
label: col,
field: col,
align: "left",
visible: true,
}));
setListConfig((prev) => ({ ...prev, columns: autoColumns }));
}
},
[listConfig.columnMode, listConfig.columns.length],
);
// 쿼리 실행할 때마다 컬럼 초기화 후 자동 생성
if (result.columns.length > 0) {
const autoColumns: ListColumn[] = result.columns.map((col, idx) => ({
id: `col_${idx}`,
label: col,
field: col,
align: "left",
visible: true,
}));
setListConfig((prev) => ({ ...prev, columns: autoColumns }));
}
}, []);
// 다음 단계
const handleNext = () => {
@ -176,9 +173,7 @@ export function ListWidgetConfigModal({ isOpen, element, onClose, onSave }: List
</div>
{/* 참고: 리스트 위젯은 제목이 항상 표시됩니다 */}
<div className="rounded bg-blue-50 p-2 text-xs text-blue-700">
💡
</div>
<div className="rounded bg-blue-50 p-2 text-xs text-blue-700">💡 </div>
</div>
{/* 진행 상태 표시 */}

View File

@ -57,6 +57,17 @@ export default function YardManagement3DWidget({
}
}, [isEditMode]);
// 레이아웃 목록이 로드되었고, 설정이 없으면 첫 번째 레이아웃 자동 선택
useEffect(() => {
if (isEditMode && layouts.length > 0 && !config?.layoutId && onConfigChange) {
// console.log("🔧 첫 번째 야드 레이아웃 자동 선택:", layouts[0]);
onConfigChange({
layoutId: layouts[0].id,
layoutName: layouts[0].name,
});
}
}, [isEditMode, layouts, config?.layoutId, onConfigChange]);
// 레이아웃 선택 (편집 모드에서만)
const handleSelectLayout = (layout: YardLayout) => {
if (onConfigChange) {
@ -243,12 +254,16 @@ export default function YardManagement3DWidget({
// 뷰 모드: 선택된 레이아웃의 3D 뷰어 표시
if (!config?.layoutId) {
console.warn("⚠️ 야드관리 위젯: layoutId가 설정되지 않음", { config, isEditMode });
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 className="mt-2 text-xs text-red-500">
디버그: config={JSON.stringify(config)}
</div>
</div>
</div>
);

View File

@ -0,0 +1,79 @@
"use client";
import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { DashboardElement } from "../types";
interface YardWidgetConfigModalProps {
element: DashboardElement;
isOpen: boolean;
onClose: () => void;
onSave: (updates: Partial<DashboardElement>) => void;
}
export function YardWidgetConfigModal({ element, isOpen, onClose, onSave }: YardWidgetConfigModalProps) {
const [customTitle, setCustomTitle] = useState(element.customTitle || "");
const [showHeader, setShowHeader] = useState(element.showHeader !== false);
useEffect(() => {
if (isOpen) {
setCustomTitle(element.customTitle || "");
setShowHeader(element.showHeader !== false);
}
}, [isOpen, element]);
const handleSave = () => {
onSave({
customTitle,
showHeader,
});
onClose();
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent onPointerDown={(e) => e.stopPropagation()} className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle> </DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
{/* 위젯 제목 */}
<div className="space-y-2">
<Label htmlFor="customTitle"> </Label>
<Input
id="customTitle"
value={customTitle}
onChange={(e) => setCustomTitle(e.target.value)}
placeholder="제목을 입력하세요 (비워두면 기본 제목 사용)"
/>
<p className="text-xs text-gray-500"> 제목: 야드 3D</p>
</div>
{/* 헤더 표시 여부 */}
<div className="flex items-center space-x-2">
<Checkbox
id="showHeader"
checked={showHeader}
onCheckedChange={(checked) => setShowHeader(checked === true)}
/>
<Label htmlFor="showHeader" className="cursor-pointer text-sm font-normal">
</Label>
</div>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={onClose}>
</Button>
<Button onClick={handleSave}></Button>
</div>
</DialogContent>
</Dialog>
);
}

View File

@ -1,6 +1,6 @@
"use client";
import React from "react";
import React, { useState } from "react";
import { ListColumn } from "../../types";
import { Card } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
@ -21,8 +21,12 @@ interface ColumnSelectorProps {
* -
* -
* - , ,
* -
*/
export function ColumnSelector({ availableColumns, selectedColumns, sampleData, onChange }: ColumnSelectorProps) {
const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
// 컬럼 선택/해제
const handleToggle = (field: string) => {
const exists = selectedColumns.find((col) => col.field === field);
@ -50,17 +54,53 @@ export function ColumnSelector({ availableColumns, selectedColumns, sampleData,
onChange(selectedColumns.map((col) => (col.field === field ? { ...col, align } : col)));
};
// 드래그 시작
const handleDragStart = (index: number) => {
setDraggedIndex(index);
};
// 드래그 오버 - 실시간으로 순서 변경하여 UI 업데이트
const handleDragOver = (e: React.DragEvent, hoverIndex: number) => {
e.preventDefault();
if (draggedIndex === null || draggedIndex === hoverIndex) return;
setDragOverIndex(hoverIndex);
const newColumns = [...selectedColumns];
const draggedItem = newColumns[draggedIndex];
newColumns.splice(draggedIndex, 1);
newColumns.splice(hoverIndex, 0, draggedItem);
setDraggedIndex(hoverIndex);
onChange(newColumns);
};
// 드롭
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setDraggedIndex(null);
setDragOverIndex(null);
};
// 드래그 종료
const handleDragEnd = () => {
setDraggedIndex(null);
setDragOverIndex(null);
};
return (
<Card className="p-4">
<div className="mb-4">
<h3 className="text-lg font-semibold text-gray-800"> </h3>
<p className="text-sm text-gray-600"> </p>
<p className="text-sm text-gray-600">
. .
</p>
</div>
<div className="space-y-3">
{availableColumns.map((field) => {
const selectedCol = selectedColumns.find((col) => col.field === field);
const isSelected = !!selectedCol;
{/* 선택된 컬럼을 먼저 순서대로 표시 */}
{selectedColumns.map((selectedCol, columnIndex) => {
const field = selectedCol.field;
const preview = sampleData[field];
const previewText =
preview !== undefined && preview !== null
@ -68,19 +108,36 @@ export function ColumnSelector({ availableColumns, selectedColumns, sampleData,
? JSON.stringify(preview).substring(0, 30)
: String(preview).substring(0, 30)
: "";
const isSelected = true;
const isDraggable = true;
return (
<div
key={field}
className={`rounded-lg border p-4 transition-colors ${
draggable={isDraggable}
onDragStart={(e) => {
if (isDraggable) {
handleDragStart(columnIndex);
e.currentTarget.style.cursor = "grabbing";
}
}}
onDragOver={(e) => isDraggable && handleDragOver(e, columnIndex)}
onDrop={handleDrop}
onDragEnd={(e) => {
handleDragEnd();
e.currentTarget.style.cursor = "grab";
}}
className={`rounded-lg border p-4 transition-all ${
isSelected ? "border-blue-300 bg-blue-50" : "border-gray-200"
} ${isDraggable ? "cursor-grab active:cursor-grabbing" : ""} ${
draggedIndex === columnIndex ? "opacity-50" : ""
}`}
>
<div className="mb-3 flex items-start gap-3">
<Checkbox checked={isSelected} onCheckedChange={() => handleToggle(field)} className="mt-1" />
<div className="flex-1">
<div className="flex items-center gap-2">
<GripVertical className="h-4 w-4 text-gray-400" />
<GripVertical className={`h-4 w-4 ${isDraggable ? "text-blue-500" : "text-gray-400"}`} />
<span className="font-medium text-gray-700">{field}</span>
{previewText && <span className="text-xs text-gray-500">(: {previewText})</span>}
</div>
@ -122,6 +179,36 @@ export function ColumnSelector({ availableColumns, selectedColumns, sampleData,
</div>
);
})}
{/* 선택되지 않은 컬럼들을 아래에 표시 */}
{availableColumns
.filter((field) => !selectedColumns.find((col) => col.field === field))
.map((field) => {
const preview = sampleData[field];
const previewText =
preview !== undefined && preview !== null
? typeof preview === "object"
? JSON.stringify(preview).substring(0, 30)
: String(preview).substring(0, 30)
: "";
const isSelected = false;
const isDraggable = false;
return (
<div key={field} className={`rounded-lg border border-gray-200 p-4 transition-all`}>
<div className="mb-3 flex items-start gap-3">
<Checkbox checked={false} onCheckedChange={() => handleToggle(field)} className="mt-1" />
<div className="flex-1">
<div className="flex items-center gap-2">
<GripVertical className="h-4 w-4 text-gray-400" />
<span className="font-medium text-gray-700">{field}</span>
{previewText && <span className="text-xs text-gray-500">(: {previewText})</span>}
</div>
</div>
</div>
</div>
);
})}
</div>
{selectedColumns.length === 0 && (

View File

@ -1,6 +1,6 @@
"use client";
import React from "react";
import React, { useState } from "react";
import { ListColumn } from "../../types";
import { Card } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
@ -19,8 +19,12 @@ interface ManualColumnEditorProps {
*
* - /
* -
* -
*/
export function ManualColumnEditor({ availableFields, columns, onChange }: ManualColumnEditorProps) {
const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
// 새 컬럼 추가
const handleAddColumn = () => {
const newCol: ListColumn = {
@ -43,12 +47,48 @@ export function ManualColumnEditor({ availableFields, columns, onChange }: Manua
onChange(columns.map((col) => (col.id === id ? { ...col, ...updates } : col)));
};
// 드래그 시작
const handleDragStart = (index: number) => {
setDraggedIndex(index);
};
// 드래그 오버 - 실시간으로 순서 변경하여 UI 업데이트
const handleDragOver = (e: React.DragEvent, hoverIndex: number) => {
e.preventDefault();
if (draggedIndex === null || draggedIndex === hoverIndex) return;
setDragOverIndex(hoverIndex);
const newColumns = [...columns];
const draggedItem = newColumns[draggedIndex];
newColumns.splice(draggedIndex, 1);
newColumns.splice(hoverIndex, 0, draggedItem);
setDraggedIndex(hoverIndex);
onChange(newColumns);
};
// 드롭
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setDraggedIndex(null);
setDragOverIndex(null);
};
// 드래그 종료
const handleDragEnd = () => {
setDraggedIndex(null);
setDragOverIndex(null);
};
return (
<Card className="p-4">
<div className="mb-4 flex items-center justify-between">
<div>
<h3 className="text-lg font-semibold text-gray-800"> </h3>
<p className="text-sm text-gray-600"> </p>
<p className="text-sm text-gray-600">
. .
</p>
</div>
<Button onClick={handleAddColumn} size="sm" className="gap-2">
<Plus className="h-4 w-4" />
@ -58,9 +98,25 @@ export function ManualColumnEditor({ availableFields, columns, onChange }: Manua
<div className="space-y-3">
{columns.map((col, index) => (
<div key={col.id} className="rounded-lg border border-gray-200 bg-gray-50 p-4">
<div
key={col.id}
draggable
onDragStart={(e) => {
handleDragStart(index);
e.currentTarget.style.cursor = "grabbing";
}}
onDragOver={(e) => handleDragOver(e, index)}
onDrop={handleDrop}
onDragEnd={(e) => {
handleDragEnd();
e.currentTarget.style.cursor = "grab";
}}
className={`cursor-grab rounded-lg border border-gray-200 bg-gray-50 p-4 transition-all active:cursor-grabbing ${
draggedIndex === index ? "opacity-50" : ""
}`}
>
<div className="mb-3 flex items-center gap-2">
<GripVertical className="h-4 w-4 text-gray-400" />
<GripVertical className="h-4 w-4 text-blue-500" />
<span className="font-medium text-gray-700"> {index + 1}</span>
<Button
onClick={() => handleRemove(col.id)}

View File

@ -2,12 +2,15 @@
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Save, Loader2, Plus, Settings, Trash2 } from "lucide-react";
import { ArrowLeft, Save, Loader2, Plus, Settings, Trash2, Edit2 } from "lucide-react";
import { yardLayoutApi } from "@/lib/api/yardLayoutApi";
import dynamic from "next/dynamic";
import { YardLayout, YardPlacement } from "./types";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { AlertCircle } from "lucide-react";
import { AlertCircle, CheckCircle } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
const Yard3DCanvas = dynamic(() => import("./Yard3DCanvas"), {
ssr: false,
@ -31,11 +34,27 @@ interface YardEditorProps {
export default function YardEditor({ layout, onBack }: YardEditorProps) {
const [placements, setPlacements] = useState<YardPlacement[]>([]);
const [originalPlacements, setOriginalPlacements] = useState<YardPlacement[]>([]); // 원본 데이터 보관
const [selectedPlacement, setSelectedPlacement] = useState<YardPlacement | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [showConfigPanel, setShowConfigPanel] = useState(false);
const [error, setError] = useState<string | null>(null);
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false); // 미저장 변경사항 추적
const [nextPlacementId, setNextPlacementId] = useState(-1); // 임시 ID (음수 사용)
const [saveResultDialog, setSaveResultDialog] = useState<{
open: boolean;
success: boolean;
message: string;
}>({ open: false, success: false, message: "" });
const [deleteConfirmDialog, setDeleteConfirmDialog] = useState<{
open: boolean;
placementId: number | null;
}>({ open: false, placementId: null });
const [editLayoutDialog, setEditLayoutDialog] = useState<{
open: boolean;
name: string;
}>({ open: false, name: "" });
// 배치 목록 로드
useEffect(() => {
@ -44,7 +63,9 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
setIsLoading(true);
const response = await yardLayoutApi.getPlacementsByLayoutId(layout.id);
if (response.success) {
setPlacements(response.data as YardPlacement[]);
const loadedData = response.data as YardPlacement[];
setPlacements(loadedData);
setOriginalPlacements(JSON.parse(JSON.stringify(loadedData))); // 깊은 복사
}
} catch (error) {
console.error("배치 목록 로드 실패:", error);
@ -57,36 +78,34 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
loadPlacements();
}, [layout.id]);
// 빈 요소 추가
const handleAddElement = async () => {
try {
const newPlacementData = {
position_x: 0,
position_y: 0,
position_z: 0,
size_x: 5,
size_y: 5,
size_z: 5,
color: "#9ca3af", // 회색 (미설정 상태)
};
// 빈 요소 추가 (로컬 상태에만 추가, 저장 시 서버에 반영)
const handleAddElement = () => {
const newPlacement: YardPlacement = {
id: nextPlacementId, // 임시 음수 ID
yard_layout_id: layout.id,
material_code: null,
material_name: null,
quantity: null,
unit: null,
position_x: 0,
position_y: 2.5,
position_z: 0,
size_x: 5,
size_y: 5,
size_z: 5,
color: "#9ca3af",
data_source_type: null,
data_source_config: null,
data_binding: null,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
console.log("요소 추가 요청:", { layoutId: layout.id, data: newPlacementData });
const response = await yardLayoutApi.addMaterialPlacement(layout.id, newPlacementData);
console.log("요소 추가 응답:", response);
if (response.success) {
const newPlacement = response.data as YardPlacement;
setPlacements((prev) => [...prev, newPlacement]);
setSelectedPlacement(newPlacement);
setShowConfigPanel(true); // 자동으로 설정 패널 표시
} else {
console.error("요소 추가 실패 (응답):", response);
setError(response.message || "요소 추가에 실패했습니다.");
}
} catch (error) {
console.error("요소 추가 실패 (예외):", error);
setError(`요소 추가에 실패했습니다: ${error instanceof Error ? error.message : String(error)}`);
}
setPlacements((prev) => [...prev, newPlacement]);
setSelectedPlacement(newPlacement);
setShowConfigPanel(true);
setHasUnsavedChanges(true);
setNextPlacementId((prev) => prev - 1); // 다음 임시 ID
};
// 요소 선택 (3D 캔버스 또는 목록에서)
@ -101,28 +120,26 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
setShowConfigPanel(true);
};
// 요소 삭제
const handleDeletePlacement = async (placementId: number) => {
if (!confirm("이 요소를 삭제하시겠습니까?")) {
return;
}
try {
const response = await yardLayoutApi.removePlacement(placementId);
if (response.success) {
setPlacements((prev) => prev.filter((p) => p.id !== placementId));
if (selectedPlacement?.id === placementId) {
setSelectedPlacement(null);
setShowConfigPanel(false);
}
}
} catch (error) {
console.error("요소 삭제 실패:", error);
setError("요소 삭제에 실패했습니다.");
}
// 요소 삭제 확인 Dialog 열기
const handleDeletePlacement = (placementId: number) => {
setDeleteConfirmDialog({ open: true, placementId });
};
// 자재 드래그 (3D 캔버스에서)
// 요소 삭제 확정 (로컬 상태에서만 삭제, 저장 시 서버에 반영)
const confirmDeletePlacement = () => {
const { placementId } = deleteConfirmDialog;
if (placementId === null) return;
setPlacements((prev) => prev.filter((p) => p.id !== placementId));
if (selectedPlacement?.id === placementId) {
setSelectedPlacement(null);
setShowConfigPanel(false);
}
setHasUnsavedChanges(true);
setDeleteConfirmDialog({ open: false, placementId: null });
};
// 자재 드래그 (3D 캔버스에서, 로컬 상태에만 반영)
const handlePlacementDrag = (id: number, position: { x: number; y: number; z: number }) => {
const updatedPosition = {
position_x: Math.round(position.x * 2) / 2,
@ -135,76 +152,119 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
if (selectedPlacement?.id === id) {
setSelectedPlacement((prev) => (prev ? { ...prev, ...updatedPosition } : null));
}
setHasUnsavedChanges(true);
};
// 저장
// 전체 저장 (신규/수정/삭제 모두 처리)
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,
})),
);
// 1. 삭제된 요소 처리 (원본에는 있지만 현재 state에 없는 경우)
const deletedIds = originalPlacements
.filter((orig) => !placements.find((p) => p.id === orig.id))
.map((p) => p.id);
for (const id of deletedIds) {
await yardLayoutApi.removePlacement(id);
}
// 2. 신규 추가 요소 처리 (ID가 음수인 경우)
const newPlacements = placements.filter((p) => p.id < 0);
const addedPlacements: YardPlacement[] = [];
for (const newPlacement of newPlacements) {
const response = await yardLayoutApi.addMaterialPlacement(layout.id, {
material_code: newPlacement.material_code,
material_name: newPlacement.material_name,
quantity: newPlacement.quantity,
unit: newPlacement.unit,
position_x: newPlacement.position_x,
position_y: newPlacement.position_y,
position_z: newPlacement.position_z,
size_x: newPlacement.size_x,
size_y: newPlacement.size_y,
size_z: newPlacement.size_z,
color: newPlacement.color,
data_source_type: newPlacement.data_source_type,
data_source_config: newPlacement.data_source_config,
data_binding: newPlacement.data_binding,
memo: newPlacement.memo,
});
if (response.success) {
addedPlacements.push(response.data as YardPlacement);
}
}
// 3. 기존 요소 수정 처리 (ID가 양수인 경우)
const existingPlacements = placements.filter((p) => p.id > 0);
for (const placement of existingPlacements) {
await yardLayoutApi.updatePlacement(placement.id, {
material_code: placement.material_code,
material_name: placement.material_name,
quantity: placement.quantity,
unit: placement.unit,
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,
data_source_type: placement.data_source_type,
data_source_config: placement.data_source_config,
data_binding: placement.data_binding,
memo: placement.memo,
});
}
// 4. 저장 성공 후 데이터 다시 로드
const response = await yardLayoutApi.getPlacementsByLayoutId(layout.id);
if (response.success) {
alert("저장되었습니다");
const loadedData = response.data as YardPlacement[];
setPlacements(loadedData);
setOriginalPlacements(JSON.parse(JSON.stringify(loadedData)));
setHasUnsavedChanges(false);
setSelectedPlacement(null);
setShowConfigPanel(false);
setSaveResultDialog({
open: true,
success: true,
message: "모든 변경사항이 성공적으로 저장되었습니다.",
});
}
} catch (error) {
console.error("저장 실패:", error);
alert("저장에 실패했습니다");
setSaveResultDialog({
open: true,
success: false,
message: `저장에 실패했습니다: ${error instanceof Error ? error.message : "알 수 없는 오류"}`,
});
} finally {
setIsSaving(false);
}
};
// 설정 패널에서 저장
const handleSaveConfig = async (updatedData: Partial<YardPlacement>) => {
// 설정 패널에서 데이터 업데이트 (로컬 상태에만 반영, 서버 저장 안함)
const handleSaveConfig = (updatedData: Partial<YardPlacement>) => {
if (!selectedPlacement) return;
try {
const response = await yardLayoutApi.updatePlacement(selectedPlacement.id, updatedData);
if (response.success) {
const updated = response.data as YardPlacement;
// 로컬 상태만 업데이트
setPlacements((prev) =>
prev.map((p) => {
if (p.id === selectedPlacement.id) {
return { ...p, ...updatedData };
}
return p;
}),
);
// 현재 위치 정보를 유지하면서 업데이트
setPlacements((prev) =>
prev.map((p) => {
if (p.id === updated.id) {
// 현재 프론트엔드 상태의 위치를 유지
return {
...updated,
position_x: p.position_x,
position_y: p.position_y,
position_z: p.position_z,
};
}
return p;
}),
);
// 선택된 요소도 동일하게 업데이트
setSelectedPlacement({
...updated,
position_x: selectedPlacement.position_x,
position_y: selectedPlacement.position_y,
position_z: selectedPlacement.position_z,
});
setShowConfigPanel(false);
}
} catch (error) {
console.error("설정 저장 실패:", error);
setError("설정 저장에 실패했습니다.");
}
// 선택된 요소도 업데이트
setSelectedPlacement((prev) => (prev ? { ...prev, ...updatedData } : null));
setShowConfigPanel(false);
setHasUnsavedChanges(true);
};
// 요소가 설정되었는지 확인
@ -212,6 +272,32 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
return !!(placement.material_name && placement.quantity && placement.unit);
};
// 레이아웃 편집 Dialog 열기
const handleEditLayout = () => {
setEditLayoutDialog({
open: true,
name: layout.name,
});
};
// 레이아웃 정보 저장
const handleSaveLayoutInfo = async () => {
try {
const response = await yardLayoutApi.updateLayout(layout.id, {
name: editLayoutDialog.name,
});
if (response.success) {
// 레이아웃 정보 업데이트
layout.name = editLayoutDialog.name;
setEditLayoutDialog({ open: false, name: "" });
}
} catch (error) {
console.error("레이아웃 정보 수정 실패:", error);
setError("레이아웃 정보 수정에 실패했습니다.");
}
};
return (
<div className="flex h-full flex-col bg-white">
{/* 상단 툴바 */}
@ -221,25 +307,33 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
<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 className="flex items-center gap-2">
<div>
<h2 className="text-lg font-semibold">{layout.name}</h2>
{layout.description && <p className="text-sm text-gray-500">{layout.description}</p>}
</div>
<Button variant="ghost" size="sm" onClick={handleEditLayout} className="h-8 w-8 p-0">
<Edit2 className="h-4 w-4 text-gray-500" />
</Button>
</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 className="flex items-center gap-2">
{hasUnsavedChanges && <span className="text-sm font-medium text-orange-600"> </span>}
<Button size="sm" onClick={handleSave} disabled={isSaving || !hasUnsavedChanges}>
{isSaving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : (
<>
<Save className="mr-2 h-4 w-4" />
</>
)}
</Button>
</div>
</div>
{/* 에러 메시지 */}
@ -369,6 +463,93 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
)}
</div>
</div>
{/* 저장 결과 Dialog */}
<Dialog open={saveResultDialog.open} onOpenChange={(open) => setSaveResultDialog((prev) => ({ ...prev, open }))}>
<DialogContent onPointerDown={(e) => e.stopPropagation()}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{saveResultDialog.success ? (
<>
<CheckCircle className="h-5 w-5 text-green-600" />
</>
) : (
<>
<AlertCircle className="h-5 w-5 text-red-600" />
</>
)}
</DialogTitle>
<DialogDescription className="pt-2">{saveResultDialog.message}</DialogDescription>
</DialogHeader>
<div className="flex justify-end">
<Button onClick={() => setSaveResultDialog((prev) => ({ ...prev, open: false }))}></Button>
</div>
</DialogContent>
</Dialog>
{/* 삭제 확인 Dialog */}
<Dialog
open={deleteConfirmDialog.open}
onOpenChange={(open) => !open && setDeleteConfirmDialog({ open: false, placementId: null })}
>
<DialogContent onPointerDown={(e) => e.stopPropagation()}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertCircle className="h-5 w-5 text-orange-600" />
</DialogTitle>
<DialogDescription className="pt-2">
?
<br />
<span className="font-semibold text-orange-600"> .</span>
</DialogDescription>
</DialogHeader>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setDeleteConfirmDialog({ open: false, placementId: null })}>
</Button>
<Button onClick={confirmDeletePlacement} className="bg-red-600 hover:bg-red-700">
</Button>
</div>
</DialogContent>
</Dialog>
{/* 레이아웃 편집 Dialog */}
<Dialog
open={editLayoutDialog.open}
onOpenChange={(open) => !open && setEditLayoutDialog({ open: false, name: "" })}
>
<DialogContent onPointerDown={(e) => e.stopPropagation()}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Edit2 className="h-5 w-5 text-blue-600" />
</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="layout-name"> </Label>
<Input
id="layout-name"
value={editLayoutDialog.name}
onChange={(e) => setEditLayoutDialog((prev) => ({ ...prev, name: e.target.value }))}
placeholder="레이아웃 이름을 입력하세요"
/>
</div>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setEditLayoutDialog({ open: false, name: "" })}>
</Button>
<Button onClick={handleSaveLayoutInfo} disabled={!editLayoutDialog.name.trim()}>
</Button>
</div>
</DialogContent>
</Dialog>
</div>
);
}

View File

@ -18,7 +18,7 @@ import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
interface YardElementConfigPanelProps {
placement: YardPlacement;
onSave: (updatedData: Partial<YardPlacement>) => Promise<void>;
onSave: (updatedData: Partial<YardPlacement>) => void; // Promise 제거 (즉시 로컬 상태 업데이트)
onCancel: () => void;
}
@ -52,9 +52,8 @@ export default function YardElementConfigPanel({ placement, onSave, onCancel }:
const [sizeY, setSizeY] = useState(placement.size_y);
const [sizeZ, setSizeZ] = useState(placement.size_z);
// 에러 및 로딩
// 에러
const [error, setError] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
// 외부 DB 커넥션 목록 로드
useEffect(() => {
@ -180,8 +179,8 @@ export default function YardElementConfigPanel({ placement, onSave, onCancel }:
}
};
// 저장
const handleSave = async () => {
// 적용 (로컬 상태만 업데이트, 서버 저장은 나중에 일괄 처리)
const handleApply = () => {
// 검증
if (!queryResult) {
setError("먼저 데이터를 조회해주세요.");
@ -203,49 +202,40 @@ export default function YardElementConfigPanel({ placement, onSave, onCancel }:
return;
}
setIsSaving(true);
const selectedRow = queryResult.rows[selectedRowIndex];
const materialName = selectedRow[materialNameField];
const quantity = selectedRow[quantityField];
try {
const selectedRow = queryResult.rows[selectedRowIndex];
const materialName = selectedRow[materialNameField];
const quantity = selectedRow[quantityField];
const dataSourceConfig: YardDataSourceConfig = {
type: dataSourceType,
query: dataSourceType !== "rest_api" ? query : undefined,
connectionId: dataSourceType === "external_db" ? parseInt(externalConnectionId) : undefined,
url: dataSourceType === "rest_api" ? apiUrl : undefined,
method: dataSourceType === "rest_api" ? apiMethod : undefined,
dataPath: dataSourceType === "rest_api" && apiDataPath ? apiDataPath : undefined,
};
const dataSourceConfig: YardDataSourceConfig = {
type: dataSourceType,
query: dataSourceType !== "rest_api" ? query : undefined,
connectionId: dataSourceType === "external_db" ? parseInt(externalConnectionId) : undefined,
url: dataSourceType === "rest_api" ? apiUrl : undefined,
method: dataSourceType === "rest_api" ? apiMethod : undefined,
dataPath: dataSourceType === "rest_api" && apiDataPath ? apiDataPath : undefined,
};
const dataBinding: YardDataBinding = {
selectedRowIndex,
materialNameField,
quantityField,
unit: unit.trim(),
};
const dataBinding: YardDataBinding = {
selectedRowIndex,
materialNameField,
quantityField,
unit: unit.trim(),
};
const updatedData: Partial<YardPlacement> = {
material_name: String(materialName),
quantity: Number(quantity),
unit: unit.trim(),
color,
size_x: sizeX,
size_y: sizeY,
size_z: sizeZ,
data_source_type: dataSourceType,
data_source_config: dataSourceConfig,
data_binding: dataBinding,
};
const updatedData: Partial<YardPlacement> = {
material_name: String(materialName),
quantity: Number(quantity),
unit: unit.trim(),
color,
size_x: sizeX,
size_y: sizeY,
size_z: sizeZ,
data_source_type: dataSourceType,
data_source_config: dataSourceConfig,
data_binding: dataBinding,
};
await onSave(updatedData);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : "저장 중 오류가 발생했습니다.";
setError(errorMessage);
} finally {
setIsSaving(false);
}
onSave(updatedData); // 동기적으로 즉시 로컬 상태 업데이트
};
return (
@ -537,15 +527,8 @@ export default function YardElementConfigPanel({ placement, onSave, onCancel }:
<Button variant="outline" onClick={onCancel} className="flex-1">
</Button>
<Button onClick={handleSave} disabled={isSaving || !queryResult} className="flex-1">
{isSaving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : (
"저장"
)}
<Button onClick={handleApply} disabled={!queryResult} className="flex-1">
</Button>
</div>
</div>

View File

@ -43,6 +43,14 @@ const YardManagement3DWidget = dynamic(() => import("@/components/admin/dashboar
ssr: false,
});
const WorkHistoryWidget = dynamic(() => import("./widgets/WorkHistoryWidget"), {
ssr: false,
});
const CustomStatsWidget = dynamic(() => import("./widgets/CustomStatsWidget"), {
ssr: false,
});
/**
* - DashboardSidebar의 subtype
* ViewerElement에서
@ -82,8 +90,28 @@ function renderWidget(element: DashboardElement) {
return <ListWidget element={element} />;
case "yard-management-3d":
// console.log("🏗️ 야드관리 위젯 렌더링:", {
// elementId: element.id,
// yardConfig: element.yardConfig,
// yardConfigType: typeof element.yardConfig,
// hasLayoutId: !!element.yardConfig?.layoutId,
// layoutId: element.yardConfig?.layoutId,
// layoutName: element.yardConfig?.layoutName,
// });
return <YardManagement3DWidget isEditMode={false} config={element.yardConfig} />;
case "work-history":
return <WorkHistoryWidget element={element} />;
case "transport-stats":
// console.log("📊 [DashboardViewer] CustomStatsWidget 렌더링:", {
// elementId: element.id,
// hasDataSource: !!element.dataSource,
// query: element.dataSource?.query?.substring(0, 50) + "...",
// dataSourceType: element.dataSource?.type,
// });
return <CustomStatsWidget element={element} />;
// === 차량 관련 (추가 위젯) ===
case "vehicle-status":
return <VehicleStatusWidget element={element} />;
@ -256,11 +284,11 @@ export function DashboardViewer({
return (
<DashboardProvider>
{/* overflow-auto 제거 - 외부 페이지 스크롤 사용 */}
<div className="flex h-full items-start justify-center bg-gray-100 p-8">
{/* 스크롤 가능한 컨테이너 */}
<div className="flex min-h-screen items-start justify-center bg-gray-100 p-8">
{/* 고정 크기 캔버스 (편집 화면과 동일한 레이아웃) */}
<div
className="relative overflow-hidden rounded-lg"
className="relative rounded-lg"
style={{
width: `${canvasConfig.width}px`,
minHeight: `${canvasConfig.height}px`,

View File

@ -0,0 +1,795 @@
/**
*
* -
* - , ,
* - , , ,
*/
"use client";
import React, { useState, useEffect } from "react";
import { DashboardElement } from "@/components/admin/dashboard/types";
interface CustomStatsWidgetProps {
element?: DashboardElement;
refreshInterval?: number;
}
interface StatItem {
label: string;
value: number;
unit: string;
color: string;
icon: string;
}
export default function CustomStatsWidget({ element, refreshInterval = 60000 }: CustomStatsWidgetProps) {
// console.log("🚀 CustomStatsWidget 마운트:", {
// elementId: element?.id,
// query: element?.dataSource?.query?.substring(0, 50) + "...",
// hasDataSource: !!element?.dataSource,
// });
const [allStats, setAllStats] = useState<StatItem[]>([]); // 모든 통계
const [stats, setStats] = useState<StatItem[]>([]); // 표시할 통계
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [showSettings, setShowSettings] = useState(false);
const [selectedStats, setSelectedStats] = useState<string[]>([]); // 선택된 통계 라벨
const selectedStatsRef = React.useRef<string[]>([]); // 현재 선택된 통계를 추적하는 ref
const isInitializedRef = React.useRef(false); // 초기화 여부 추적
const lastQueryRef = React.useRef<string>(""); // 마지막 쿼리 추적
// localStorage 키 생성 (쿼리 기반으로 고유하게 - 편집/보기 모드 공유)
const queryHash = element?.dataSource?.query
? btoa(element.dataSource.query) // 전체 쿼리를 base64로 인코딩
: "default";
const storageKey = `custom-stats-widget-${queryHash}`;
// console.log("🔑 storageKey:", storageKey, "(쿼리:", element?.dataSource?.query?.substring(0, 30) + "...)");
// 쿼리가 변경되면 초기화 상태 리셋
React.useEffect(() => {
const currentQuery = element?.dataSource?.query || "";
if (currentQuery !== lastQueryRef.current) {
isInitializedRef.current = false;
lastQueryRef.current = currentQuery;
}
}, [element?.dataSource?.query]);
// selectedStats 변경 시 ref 업데이트
React.useEffect(() => {
selectedStatsRef.current = selectedStats;
}, [selectedStats]);
// 데이터 로드
const loadData = React.useCallback(async () => {
try {
setIsLoading(true);
setError(null);
// 쿼리가 설정되어 있지 않으면 안내 메시지만 표시
if (!element?.dataSource?.query) {
setError("쿼리를 설정해주세요");
setIsLoading(false);
return;
}
// 쿼리 실행하여 통계 계산
const token = localStorage.getItem("authToken");
const response = await fetch("/api/dashboards/execute-query", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
query: element.dataSource.query,
connectionType: element.dataSource.connectionType || "current",
externalConnectionId: element.dataSource.externalConnectionId,
}),
});
if (!response.ok) throw new Error("데이터 로딩 실패");
const result = await response.json();
if (!result.success || !result.data?.rows) {
throw new Error(result.message || "데이터 로드 실패");
}
const data = result.data.rows || [];
if (data.length === 0) {
setStats([]);
return;
}
const firstRow = data[0];
const statsItems: StatItem[] = [];
// 1. 총 건수 (항상 표시)
statsItems.push({
label: "총 건수",
value: data.length,
unit: "건",
color: "indigo",
icon: "📊",
});
// 2. 모든 숫자 컬럼 자동 감지
const numericColumns: { [key: string]: { sum: number; avg: number; count: number } } = {};
Object.keys(firstRow).forEach((key) => {
const value = firstRow[key];
// 숫자로 변환 가능한 컬럼만 선택 (id, order 같은 식별자 제외)
if (
value !== null &&
!isNaN(parseFloat(value)) &&
!key.toLowerCase().includes("id") &&
!key.toLowerCase().includes("order") &&
key.toLowerCase() !== "id"
) {
const validValues = data
.map((item: any) => parseFloat(item[key]))
.filter((v: number) => !isNaN(v) && v !== 0);
if (validValues.length > 0) {
const sum = validValues.reduce((acc: number, v: number) => acc + v, 0);
numericColumns[key] = {
sum,
avg: sum / validValues.length,
count: validValues.length,
};
}
}
});
// 3. 컬럼명 한글 번역 매핑
const columnNameTranslation: { [key: string]: string } = {
// 일반
"id": "ID",
"name": "이름",
"title": "제목",
"description": "설명",
"status": "상태",
"type": "유형",
"category": "카테고리",
"date": "날짜",
"time": "시간",
"created_at": "생성일",
"updated_at": "수정일",
"deleted_at": "삭제일",
// 물류/운송
"tracking_number": "운송장 번호",
"customer": "고객",
"origin": "출발지",
"destination": "목적지",
"estimated_delivery": "예상 도착",
"actual_delivery": "실제 도착",
"delay_reason": "지연 사유",
"priority": "우선순위",
"cargo_weight": "화물 중량",
"total_weight": "총 중량",
"weight": "중량",
"distance": "거리",
"total_distance": "총 거리",
"delivery_time": "배송 시간",
"delivery_duration": "배송 소요시간",
"is_on_time": "정시 도착 여부",
"on_time": "정시",
// 수량/금액
"quantity": "수량",
"qty": "수량",
"amount": "금액",
"price": "가격",
"cost": "비용",
"fee": "수수료",
"total": "합계",
"sum": "총합",
// 비율/효율
"rate": "비율",
"ratio": "비율",
"percent": "퍼센트",
"percentage": "백분율",
"efficiency": "효율",
// 생산/처리
"throughput": "처리량",
"output": "산출량",
"production": "생산량",
"volume": "용량",
// 재고/설비
"stock": "재고",
"inventory": "재고",
"equipment": "설비",
"facility": "시설",
"machine": "기계",
// 평가
"score": "점수",
"rating": "평점",
"point": "점수",
"grade": "등급",
// 기타
"temperature": "온도",
"temp": "온도",
"speed": "속도",
"velocity": "속도",
"count": "개수",
"number": "번호",
};
// 4. 키워드 기반 자동 라벨링 및 단위 설정
const columnConfig: {
[key: string]: {
keywords: string[];
unit: string;
color: string;
icon: string;
aggregation: "sum" | "avg" | "max" | "min"; // 집계 방식
koreanLabel?: string; // 한글 라벨
};
} = {
// 무게/중량 - 합계
weight: {
keywords: ["weight", "cargo_weight", "total_weight", "tonnage", "ton"],
unit: "톤",
color: "green",
icon: "⚖️",
aggregation: "sum",
koreanLabel: "총 운송량"
},
// 거리 - 합계
distance: {
keywords: ["distance", "total_distance", "km", "kilometer"],
unit: "km",
color: "blue",
icon: "🛣️",
aggregation: "sum",
koreanLabel: "누적 거리"
},
// 시간/기간 - 평균
time: {
keywords: ["time", "duration", "delivery_time", "delivery_duration", "hour", "minute"],
unit: "분",
color: "orange",
icon: "⏱️",
aggregation: "avg",
koreanLabel: "평균 배송시간"
},
// 수량/개수 - 합계
quantity: {
keywords: ["quantity", "qty", "count", "number"],
unit: "개",
color: "purple",
icon: "📦",
aggregation: "sum",
koreanLabel: "총 수량"
},
// 금액/가격 - 합계
amount: {
keywords: ["amount", "price", "cost", "fee", "total", "sum"],
unit: "원",
color: "yellow",
icon: "💰",
aggregation: "sum",
koreanLabel: "총 금액"
},
// 비율/퍼센트 - 평균
rate: {
keywords: ["rate", "ratio", "percent", "efficiency", "%"],
unit: "%",
color: "cyan",
icon: "📈",
aggregation: "avg",
koreanLabel: "평균 비율"
},
// 처리량 - 합계
throughput: {
keywords: ["throughput", "output", "production", "volume"],
unit: "개",
color: "pink",
icon: "⚡",
aggregation: "sum",
koreanLabel: "총 처리량"
},
// 재고 - 평균 (현재 재고는 평균이 의미있음)
stock: {
keywords: ["stock", "inventory"],
unit: "개",
color: "teal",
icon: "📦",
aggregation: "avg",
koreanLabel: "평균 재고"
},
// 설비/장비 - 평균
equipment: {
keywords: ["equipment", "facility", "machine"],
unit: "대",
color: "gray",
icon: "🏭",
aggregation: "avg",
koreanLabel: "평균 가동 설비"
},
// 점수/평점 - 평균
score: {
keywords: ["score", "rating", "point", "grade"],
unit: "점",
color: "indigo",
icon: "⭐",
aggregation: "avg",
koreanLabel: "평균 점수"
},
// 온도 - 평균
temperature: {
keywords: ["temp", "temperature", "degree"],
unit: "°C",
color: "red",
icon: "🌡️",
aggregation: "avg",
koreanLabel: "평균 온도"
},
// 속도 - 평균
speed: {
keywords: ["speed", "velocity"],
unit: "km/h",
color: "blue",
icon: "🚀",
aggregation: "avg",
koreanLabel: "평균 속도"
},
};
// 4. 각 숫자 컬럼을 통계 카드로 변환
Object.entries(numericColumns).forEach(([key, stats]) => {
let label = key;
let unit = "";
let color = "gray";
let icon = "📊";
let aggregation: "sum" | "avg" | "max" | "min" = "sum"; // 기본값은 합계
let matchedConfig = null;
// 키워드 매칭으로 라벨, 단위, 색상, 집계방식 자동 설정
for (const [configKey, config] of Object.entries(columnConfig)) {
if (config.keywords.some((keyword) => key.toLowerCase().includes(keyword.toLowerCase()))) {
unit = config.unit;
color = config.color;
icon = config.icon;
aggregation = config.aggregation;
matchedConfig = config;
// 한글 라벨 사용 또는 자동 변환
if (config.koreanLabel) {
label = config.koreanLabel;
} else {
// 집계 방식에 따라 접두어 추가
const prefix = aggregation === "avg" ? "평균 " : aggregation === "sum" ? "총 " : "";
label = prefix + key
.replace(/_/g, " ")
.replace(/([A-Z])/g, " $1")
.trim();
}
break;
}
}
// 매칭되지 않은 경우 기본 라벨 생성
if (!matchedConfig) {
// 컬럼명 번역 시도
const translatedName = columnNameTranslation[key.toLowerCase()];
if (translatedName) {
// 번역된 이름이 있으면 사용
label = translatedName;
} else {
// 컬럼명에 avg, average, mean이 포함되면 평균으로 간주
if (key.toLowerCase().includes("avg") ||
key.toLowerCase().includes("average") ||
key.toLowerCase().includes("mean")) {
aggregation = "avg";
// 언더스코어로 분리된 각 단어 번역 시도
const cleanKey = key.replace(/avg|average|mean/gi, "").replace(/_/g, " ").trim();
const words = cleanKey.split(/[_\s]+/);
const translatedWords = words.map(word =>
columnNameTranslation[word.toLowerCase()] || word
);
label = "평균 " + translatedWords.join(" ");
}
// total, sum이 포함되면 합계로 간주
else if (key.toLowerCase().includes("total") || key.toLowerCase().includes("sum")) {
aggregation = "sum";
// 언더스코어로 분리된 각 단어 번역 시도
const cleanKey = key.replace(/total|sum/gi, "").replace(/_/g, " ").trim();
const words = cleanKey.split(/[_\s]+/);
const translatedWords = words.map(word =>
columnNameTranslation[word.toLowerCase()] || word
);
label = "총 " + translatedWords.join(" ");
}
// 기본값 - 각 단어별로 번역 시도
else {
const words = key.split(/[_\s]+/);
const translatedWords = words.map(word => {
const translated = columnNameTranslation[word.toLowerCase()];
if (translated) {
return translated;
}
// 번역이 없으면 첫 글자 대문자로
return word.charAt(0).toUpperCase() + word.slice(1);
});
label = translatedWords.join(" ");
}
}
}
// 집계 방식에 따라 값 선택
let value: number;
switch (aggregation) {
case "avg":
value = stats.avg;
break;
case "sum":
value = stats.sum;
break;
case "max":
value = Math.max(...data.map((item: any) => parseFloat(item[key]) || 0));
break;
case "min":
value = Math.min(...data.map((item: any) => parseFloat(item[key]) || 0));
break;
default:
value = stats.sum;
}
statsItems.push({
label,
value,
unit,
color,
icon,
});
});
// 5. Boolean 컬럼 비율 계산 (정시도착률, 성공률 등)
const booleanMapping: { [key: string]: string } = {
is_on_time: "정시 도착률",
on_time: "정시 도착률",
success: "성공률",
completed: "완료율",
delivered: "배송 완료율",
approved: "승인률",
};
const addedBooleanLabels = new Set<string>(); // 중복 방지
Object.keys(firstRow).forEach((key) => {
const lowerKey = key.toLowerCase();
const matchedKey = Object.keys(booleanMapping).find((k) => lowerKey.includes(k));
if (matchedKey) {
const label = booleanMapping[matchedKey];
// 이미 추가된 라벨이면 스킵
if (addedBooleanLabels.has(label)) {
return;
}
const validItems = data.filter((item: any) => item[key] !== null && item[key] !== undefined);
if (validItems.length > 0) {
const trueCount = validItems.filter((item: any) => {
const val = item[key];
return val === true || val === "true" || val === 1 || val === "1" || val === "Y";
}).length;
const rate = (trueCount / validItems.length) * 100;
statsItems.push({
label,
value: rate,
unit: "%",
color: "purple",
icon: "✅",
});
addedBooleanLabels.add(label);
}
}
});
// console.log("📊 생성된 통계 항목:", statsItems.map(s => s.label));
setAllStats(statsItems);
// 초기화가 아직 안됐으면 localStorage에서 설정 불러오기
if (!isInitializedRef.current) {
const saved = localStorage.getItem(storageKey);
// console.log("💾 저장된 설정:", saved);
if (saved) {
try {
const savedLabels = JSON.parse(saved);
// console.log("✅ 저장된 라벨:", savedLabels);
const filtered = statsItems.filter((s) => savedLabels.includes(s.label));
// console.log("🔍 필터링된 통계:", filtered.map(s => s.label));
// console.log(`📊 일치율: ${filtered.length}/${savedLabels.length} (${Math.round(filtered.length / savedLabels.length * 100)}%)`);
// 50% 이상 일치하면 저장된 설정 사용
const matchRate = filtered.length / savedLabels.length;
if (matchRate >= 0.5 && filtered.length > 0) {
setStats(filtered);
// 실제 표시되는 라벨로 업데이트
const actualLabels = filtered.map(s => s.label);
setSelectedStats(actualLabels);
selectedStatsRef.current = actualLabels;
// localStorage도 업데이트하여 다음에는 정확히 일치하도록
localStorage.setItem(storageKey, JSON.stringify(actualLabels));
// console.log(`✅ ${filtered.length}개 통계 표시 (저장된 설정 기반)`);
} else {
// 일치율이 낮으면 처음 6개 표시하고 localStorage 업데이트
// console.warn(`⚠️ 일치율 ${Math.round(matchRate * 100)}% - 기본값 사용`);
const defaultLabels = statsItems.slice(0, 6).map((s) => s.label);
setStats(statsItems.slice(0, 6));
setSelectedStats(defaultLabels);
selectedStatsRef.current = defaultLabels;
localStorage.setItem(storageKey, JSON.stringify(defaultLabels));
}
} catch (e) {
// console.error("❌ 설정 파싱 실패:", e);
const defaultLabels = statsItems.slice(0, 6).map((s) => s.label);
setStats(statsItems.slice(0, 6));
setSelectedStats(defaultLabels);
selectedStatsRef.current = defaultLabels;
}
} else {
// 저장된 설정이 없으면 처음 6개 표시
// console.log("🆕 저장된 설정 없음. 기본값 사용");
const defaultLabels = statsItems.slice(0, 6).map((s) => s.label);
setStats(statsItems.slice(0, 6));
setSelectedStats(defaultLabels);
selectedStatsRef.current = defaultLabels;
}
isInitializedRef.current = true;
} else {
// 이미 초기화됐으면 현재 선택된 통계 유지
const currentSelected = selectedStatsRef.current;
// console.log("🔄 현재 선택된 통계:", currentSelected);
if (currentSelected.length > 0) {
const filtered = statsItems.filter((s) => currentSelected.includes(s.label));
// console.log("🔍 필터링 결과:", filtered.map(s => s.label));
if (filtered.length > 0) {
setStats(filtered);
} else {
// console.warn("⚠️ 선택된 항목과 일치하는 통계가 없음");
setStats(statsItems.slice(0, 6));
}
}
}
} catch (err) {
// console.error("통계 로드 실패:", err);
setError(err instanceof Error ? err.message : "데이터를 불러올 수 없습니다");
} finally {
setIsLoading(false);
}
}, [element?.dataSource, storageKey]);
useEffect(() => {
loadData();
const interval = setInterval(loadData, refreshInterval);
return () => clearInterval(interval);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [refreshInterval, element?.dataSource]);
// 색상 매핑
const getColorClasses = (color: string) => {
const colorMap: { [key: string]: { bg: string; text: string } } = {
indigo: { bg: "bg-indigo-50", text: "text-indigo-600" },
green: { bg: "bg-green-50", text: "text-green-600" },
blue: { bg: "bg-blue-50", text: "text-blue-600" },
purple: { bg: "bg-purple-50", text: "text-purple-600" },
orange: { bg: "bg-orange-50", text: "text-orange-600" },
yellow: { bg: "bg-yellow-50", text: "text-yellow-600" },
cyan: { bg: "bg-cyan-50", text: "text-cyan-600" },
pink: { bg: "bg-pink-50", text: "text-pink-600" },
teal: { bg: "bg-teal-50", text: "text-teal-600" },
gray: { bg: "bg-gray-50", text: "text-gray-600" },
};
return colorMap[color] || colorMap.gray;
};
if (isLoading && stats.length === 0) {
return (
<div className="flex h-full items-center justify-center bg-gray-50">
<div className="text-center">
<div className="mx-auto h-8 w-8 animate-spin rounded-full border-4 border-blue-500 border-t-transparent" />
<div className="mt-2 text-sm text-gray-600"> ...</div>
</div>
</div>
);
}
if (error) {
return (
<div className="flex h-full items-center justify-center bg-gray-50 p-4">
<div className="text-center">
<div className="mb-2 text-4xl"></div>
<div className="text-sm font-medium text-gray-600">{error}</div>
{!element?.dataSource?.query && (
<div className="mt-2 text-xs text-gray-500"> </div>
)}
<button
onClick={loadData}
className="mt-3 rounded-lg bg-blue-500 px-4 py-2 text-sm text-white hover:bg-blue-600"
>
</button>
</div>
</div>
);
}
if (stats.length === 0) {
return (
<div className="flex h-full items-center justify-center bg-gray-50 p-4">
<div className="text-center">
<div className="mb-2 text-4xl">📊</div>
<div className="text-sm font-medium text-gray-600"> </div>
<div className="mt-2 text-xs text-gray-500"> </div>
</div>
</div>
);
}
const handleToggleStat = (label: string) => {
setSelectedStats((prev) => {
const newStats = prev.includes(label)
? prev.filter((l) => l !== label)
: [...prev, label];
// console.log("🔘 토글:", label, "→", newStats.length + "개 선택");
return newStats;
});
};
const handleApplySettings = () => {
// console.log("💾 설정 적용:", selectedStats);
// console.log("📊 전체 통계:", allStats.map(s => s.label));
const filtered = allStats.filter((s) => selectedStats.includes(s.label));
// console.log("✅ 필터링 결과:", filtered.map(s => s.label));
setStats(filtered);
selectedStatsRef.current = selectedStats; // ref도 업데이트
setShowSettings(false);
// localStorage에 설정 저장
localStorage.setItem(storageKey, JSON.stringify(selectedStats));
// console.log("💾 localStorage 저장 완료:", selectedStats.length + "개");
};
// 렌더링 시 상태 로그
// console.log("🎨 렌더링 - stats:", stats.map(s => s.label));
// console.log("🎨 렌더링 - selectedStats:", selectedStats);
// console.log("🎨 렌더링 - allStats:", allStats.map(s => s.label));
return (
<div className="relative flex h-full flex-col bg-white">
{/* 헤더 영역 */}
<div className="flex items-center justify-between border-b bg-gray-50 px-4 py-2">
<div className="flex items-center gap-2">
<span className="text-lg">📊</span>
<span className="text-sm font-medium text-gray-700"> </span>
<span className="text-xs text-gray-500">({stats.length} )</span>
</div>
<button
onClick={() => {
// 설정 모달 열 때 현재 표시 중인 통계로 동기화
const currentLabels = stats.map(s => s.label);
// console.log("⚙️ 설정 모달 열기 - 현재 표시 중:", currentLabels);
setSelectedStats(currentLabels);
setShowSettings(true);
}}
className="flex items-center gap-1 rounded-lg px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100"
title="표시할 통계 선택"
>
<span></span>
<span></span>
</button>
</div>
{/* 통계 카드 */}
<div className="flex flex-1 items-center justify-center p-6">
<div className="grid w-full gap-4" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))" }}>
{stats.map((stat, index) => {
const colors = getColorClasses(stat.color);
return (
<div key={index} className={`rounded-lg border ${colors.bg} p-4 text-center`}>
<div className="text-sm text-gray-600">
{stat.label}
</div>
<div className={`mt-2 text-3xl font-bold ${colors.text}`}>
{stat.value.toFixed(stat.unit === "%" || stat.unit === "분" ? 1 : 0).toLocaleString()}
<span className="ml-1 text-lg">{stat.unit}</span>
</div>
</div>
);
})}
</div>
</div>
{/* 설정 모달 */}
{showSettings && (
<div className="absolute inset-0 z-20 flex items-center justify-center bg-black/50">
<div className="max-h-[80%] w-[90%] max-w-md overflow-auto rounded-lg bg-white p-6 shadow-xl">
<div className="mb-4 flex items-center justify-between">
<h3 className="text-lg font-bold"> </h3>
<button onClick={() => setShowSettings(false)} className="text-2xl text-gray-500 hover:text-gray-700">
×
</button>
</div>
<div className="mb-4 text-sm text-gray-600">
( )
</div>
<div className="space-y-2">
{allStats.map((stat, index) => {
const isChecked = selectedStats.includes(stat.label);
return (
<label
key={index}
className={`flex cursor-pointer items-center gap-3 rounded-lg border p-3 transition-colors ${
isChecked ? "border-blue-500 bg-blue-50" : "hover:bg-gray-50"
}`}
>
<input
type="checkbox"
checked={isChecked}
onChange={() => {
// console.log("📋 체크박스 클릭:", stat.label, "현재:", isChecked);
handleToggleStat(stat.label);
}}
className="h-5 w-5"
/>
<div className="flex-1">
<div className="font-medium">{stat.label}</div>
<div className="text-sm text-gray-500">: {stat.unit}</div>
</div>
{isChecked && <span className="text-blue-600"></span>}
</label>
);
})}
</div>
<div className="mt-6 flex gap-2">
<button
onClick={handleApplySettings}
className="flex-1 rounded-lg bg-blue-500 py-2 text-white hover:bg-blue-600"
>
({selectedStats.length} )
</button>
<button
onClick={() => {
// console.log("❌ 설정 취소");
setShowSettings(false);
}}
className="rounded-lg border px-4 py-2 hover:bg-gray-50"
>
</button>
</div>
</div>
</div>
)}
</div>
);
}

View File

@ -89,34 +89,6 @@ export default function RiskAlertWidget({ element }: RiskAlertWidgetProps) {
// 필터링된 알림
const filteredAlerts = filter === "all" ? alerts : alerts.filter((alert) => alert.type === filter);
// 심각도별 색상
const getSeverityColor = (severity: string) => {
switch (severity) {
case "high":
return "border-red-500";
case "medium":
return "border-yellow-500";
case "low":
return "border-blue-500";
default:
return "border-gray-500";
}
};
// 심각도별 배지 색상
const getSeverityBadge = (severity: string) => {
switch (severity) {
case "high":
return "bg-red-100 text-red-700";
case "medium":
return "bg-yellow-100 text-yellow-700";
case "low":
return "bg-blue-100 text-blue-700";
default:
return "bg-gray-100 text-gray-700";
}
};
// 알림 타입별 아이콘
const getAlertIcon = (type: AlertType) => {
switch (type) {
@ -163,69 +135,75 @@ export default function RiskAlertWidget({ element }: RiskAlertWidgetProps) {
};
return (
<div className="flex h-full w-full flex-col gap-3 overflow-hidden bg-slate-50 p-3">
<div className="flex h-full w-full flex-col gap-4 overflow-hidden bg-background p-4">
{/* 헤더 */}
<div className="flex items-center justify-between">
<div className="flex items-center justify-between border-b pb-3">
<div className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-red-600" />
<h3 className="text-base font-semibold text-gray-900">{element?.customTitle || "리스크 / 알림"}</h3>
<AlertTriangle className="h-5 w-5 text-destructive" />
<h3 className="text-lg font-semibold">{element?.customTitle || "리스크 / 알림"}</h3>
{stats.high > 0 && (
<Badge className="bg-red-100 text-red-700 hover:bg-red-100"> {stats.high}</Badge>
<Badge variant="destructive"> {stats.high}</Badge>
)}
</div>
<div className="flex items-center gap-2">
{lastUpdated && newAlertIds.size > 0 && (
<Badge className="bg-blue-100 text-blue-700 text-xs animate-pulse">
<Badge variant="secondary" className="animate-pulse">
{newAlertIds.size}
</Badge>
)}
{lastUpdated && (
<span className="text-xs text-gray-500">
<span className="text-xs text-muted-foreground">
{lastUpdated.toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' })}
</span>
)}
<Button variant="ghost" size="sm" onClick={loadData} disabled={isRefreshing} className="h-8 px-2">
<Button variant="ghost" size="sm" onClick={loadData} disabled={isRefreshing}>
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
</Button>
</div>
</div>
{/* 통계 카드 */}
<div className="grid grid-cols-3 gap-2">
<div className="grid grid-cols-3 gap-3">
<Card
className={`cursor-pointer border-l-4 border-red-500 p-2 transition-colors hover:bg-gray-50 ${filter === "accident" ? "bg-gray-100" : ""}`}
className={`cursor-pointer p-3 transition-all hover:shadow-md ${
filter === "accident" ? "bg-red-50" : ""
}`}
onClick={() => setFilter(filter === "accident" ? "all" : "accident")}
>
<div className="text-xs text-gray-600"></div>
<div className="text-lg font-bold text-gray-900">{stats.accident}</div>
<div className="text-xs text-muted-foreground"></div>
<div className="text-2xl font-bold text-red-600">{stats.accident}</div>
</Card>
<Card
className={`cursor-pointer border-l-4 border-blue-500 p-2 transition-colors hover:bg-gray-50 ${filter === "weather" ? "bg-gray-100" : ""}`}
className={`cursor-pointer p-3 transition-all hover:shadow-md ${
filter === "weather" ? "bg-blue-50" : ""
}`}
onClick={() => setFilter(filter === "weather" ? "all" : "weather")}
>
<div className="text-xs text-gray-600"></div>
<div className="text-lg font-bold text-gray-900">{stats.weather}</div>
<div className="text-xs text-muted-foreground"></div>
<div className="text-2xl font-bold text-blue-600">{stats.weather}</div>
</Card>
<Card
className={`cursor-pointer border-l-4 border-yellow-500 p-2 transition-colors hover:bg-gray-50 ${filter === "construction" ? "bg-gray-100" : ""}`}
className={`cursor-pointer p-3 transition-all hover:shadow-md ${
filter === "construction" ? "bg-yellow-50" : ""
}`}
onClick={() => setFilter(filter === "construction" ? "all" : "construction")}
>
<div className="text-xs text-gray-600"></div>
<div className="text-lg font-bold text-gray-900">{stats.construction}</div>
<div className="text-xs text-muted-foreground"></div>
<div className="text-2xl font-bold text-yellow-600">{stats.construction}</div>
</Card>
</div>
{/* 필터 상태 표시 */}
{filter !== "all" && (
<div className="flex items-center gap-2">
<Badge variant="outline" className="text-xs">
<Badge variant="outline">
{getAlertTypeName(filter)}
</Badge>
<Button
variant="ghost"
variant="link"
size="sm"
onClick={() => setFilter("all")}
className="h-6 px-2 text-xs text-gray-600"
className="h-auto p-0 text-xs"
>
</Button>
@ -236,44 +214,44 @@ export default function RiskAlertWidget({ element }: RiskAlertWidgetProps) {
<div className="flex-1 space-y-2 overflow-y-auto">
{filteredAlerts.length === 0 ? (
<Card className="p-4 text-center">
<div className="text-sm text-gray-500"> </div>
<div className="text-sm text-muted-foreground"> </div>
</Card>
) : (
filteredAlerts.map((alert) => (
<Card
key={alert.id}
className={`border-l-4 p-3 transition-all duration-300 ${getSeverityColor(alert.severity)} ${
newAlertIds.has(alert.id) ? 'bg-blue-50/30 ring-1 ring-blue-200' : ''
className={`p-3 transition-all duration-300 ${
newAlertIds.has(alert.id) ? 'bg-accent ring-1 ring-primary' : ''
}`}
>
<div className="flex items-start justify-between gap-2">
<div className="flex items-start gap-2">
{getAlertIcon(alert.type)}
<div className="flex-1">
<div className="flex items-center gap-2">
<h4 className="text-sm font-semibold text-gray-900">{alert.title}</h4>
<div className="flex items-center gap-2 flex-wrap">
<h4 className="text-sm font-semibold">{alert.title}</h4>
{newAlertIds.has(alert.id) && (
<Badge className="bg-blue-100 text-blue-700 text-xs">
<Badge variant="secondary">
NEW
</Badge>
)}
<Badge className={`text-xs ${getSeverityBadge(alert.severity)}`}>
<Badge variant={alert.severity === "high" ? "destructive" : alert.severity === "medium" ? "default" : "secondary"}>
{alert.severity === "high" ? "긴급" : alert.severity === "medium" ? "주의" : "정보"}
</Badge>
</div>
<p className="mt-1 text-xs font-medium text-gray-700">{alert.location}</p>
<p className="mt-1 text-xs text-gray-600">{alert.description}</p>
<p className="mt-1 text-xs font-medium text-foreground">{alert.location}</p>
<p className="mt-1 text-xs text-muted-foreground">{alert.description}</p>
</div>
</div>
</div>
<div className="mt-2 text-right text-xs text-gray-500">{formatTime(alert.timestamp)}</div>
<div className="mt-2 text-right text-xs text-muted-foreground">{formatTime(alert.timestamp)}</div>
</Card>
))
)}
</div>
{/* 안내 메시지 */}
<div className="border-t border-gray-200 pt-2 text-center text-xs text-gray-500">
<div className="border-t pt-3 text-center text-xs text-muted-foreground">
💡 1
</div>
</div>

View File

@ -38,6 +38,7 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
const { selectedDate } = useDashboard();
const [todos, setTodos] = useState<TodoItem[]>([]);
const [internalTodos, setInternalTodos] = useState<TodoItem[]>([]); // 내장 API 투두
const [stats, setStats] = useState<TodoStats | null>(null);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<"all" | "pending" | "in_progress" | "completed">("all");
@ -62,6 +63,21 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
const token = localStorage.getItem("authToken");
const userLang = localStorage.getItem("userLang") || "KR";
// 내장 API 투두 항상 조회 (외부 DB 모드에서도)
const filterParam = filter !== "all" ? `?status=${filter}` : "";
const internalResponse = await fetch(`http://localhost:9771/api/todos${filterParam}`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
let internalData: TodoItem[] = [];
if (internalResponse.ok) {
const result = await internalResponse.json();
internalData = result.data || [];
setInternalTodos(internalData);
}
// 외부 DB 조회 (dataSource가 설정된 경우)
if (element?.dataSource?.query) {
// console.log("🔍 TodoWidget - 외부 DB 조회 시작");
@ -111,8 +127,10 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
// console.log("📋 변환된 Todos:", externalTodos);
// console.log("📋 변환된 Todos 개수:", externalTodos.length);
setTodos(externalTodos);
setStats(calculateStatsFromTodos(externalTodos));
// 외부 DB 데이터 + 내장 데이터 합치기
const mergedTodos = [...externalTodos, ...internalData];
setTodos(mergedTodos);
setStats(calculateStatsFromTodos(mergedTodos));
// console.log("✅ setTodos, setStats 호출 완료!");
} else {
@ -120,20 +138,10 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
// console.error("❌ API 오류:", errorText);
}
}
// 내장 API 조회 (기본)
// 내장 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);
}
setTodos(internalData);
setStats(calculateStatsFromTodos(internalData));
}
} catch (error) {
// console.error("To-Do 로딩 오류:", error);
@ -180,10 +188,6 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
const handleAddTodo = async () => {
if (!newTodo.title.trim()) return;
if (isExternalData) {
alert("외부 데이터베이스 조회 모드에서는 추가할 수 없습니다.");
return;
}
try {
const token = localStorage.getItem("authToken");
@ -325,28 +329,31 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
<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-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 className="flex items-center justify-between">
<div>
<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>
)}
{/* 추가 버튼 - 항상 표시 */}
<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"
title="할 일 추가"
>
<Plus className="h-4 w-4" />
</button>
</div>
</div>
{/* 헤더 (추가 버튼, 통계, 필터) - showHeader가 false일 때만 숨김 */}
{/* 헤더 (통계, 필터) - 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">
@ -390,19 +397,21 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
{/* 추가 폼 */}
{showAddForm && (
<div className="border-b border-gray-200 bg-white p-4">
<div className="max-h-[400px] overflow-y-auto border-b border-gray-200 bg-white p-4">
<div className="space-y-2">
<input
type="text"
placeholder="할 일 제목*"
value={newTodo.title}
onChange={(e) => setNewTodo({ ...newTodo, title: e.target.value })}
onKeyDown={(e) => e.stopPropagation()}
className="w-full rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none"
/>
<textarea
placeholder="상세 설명 (선택)"
value={newTodo.description}
onChange={(e) => setNewTodo({ ...newTodo, description: e.target.value })}
onKeyDown={(e) => e.stopPropagation()}
className="w-full rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none"
rows={2}
/>
@ -454,7 +463,7 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
)}
{/* To-Do 리스트 */}
<div className="flex-1 overflow-y-auto p-4">
<div className="flex-1 overflow-y-auto p-4 min-h-0">
{filteredTodos.length === 0 ? (
<div className="flex h-full items-center justify-center text-gray-400">
<div className="text-center">

View File

@ -0,0 +1,314 @@
/**
*
* - ()
* - (km)
* - (%)
* -
*/
"use client";
import { useState, useEffect } from "react";
import { DashboardElement } from "@/components/admin/dashboard/types";
interface TransportStatsWidgetProps {
element?: DashboardElement;
refreshInterval?: number;
}
interface StatItem {
label: string;
value: number;
unit: string;
color: string;
icon?: string;
}
interface StatsData {
total_count: number;
total_weight: number;
total_distance: number;
on_time_rate: number;
avg_delivery_time: number;
[key: string]: number; // 동적 속성 추가
}
export default function TransportStatsWidget({ element, refreshInterval = 60000 }: TransportStatsWidgetProps) {
const [stats, setStats] = useState<StatItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// 데이터 로드
const loadData = async () => {
try {
setIsLoading(true);
setError(null);
// 쿼리가 설정되어 있지 않으면 안내 메시지만 표시
if (!element?.dataSource?.query) {
setError("쿼리를 설정해주세요");
setIsLoading(false);
return;
}
// 쿼리 실행하여 통계 계산
const token = localStorage.getItem("authToken");
const response = await fetch("/api/dashboards/execute-query", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
query: element.dataSource.query,
connectionType: element.dataSource.connectionType || "current",
externalConnectionId: element.dataSource.externalConnectionId,
}),
});
if (!response.ok) throw new Error("데이터 로딩 실패");
const result = await response.json();
if (!result.success || !result.data?.rows) {
throw new Error(result.message || "데이터 로드 실패");
}
const data = result.data.rows || [];
if (data.length === 0) {
setStats({ total_count: 0, total_weight: 0, total_distance: 0, on_time_rate: 0, avg_delivery_time: 0 });
return;
}
// 자동으로 숫자 컬럼 감지 및 합계 계산
const firstRow = data[0];
const numericColumns: { [key: string]: number } = {};
// 모든 컬럼을 순회하며 숫자 컬럼 찾기
Object.keys(firstRow).forEach((key) => {
const value = firstRow[key];
// 숫자로 변환 가능한 컬럼만 선택
if (value !== null && !isNaN(parseFloat(value))) {
numericColumns[key] = data.reduce((sum: number, item: any) => {
return sum + (parseFloat(item[key]) || 0);
}, 0);
}
});
// 특정 키워드를 포함한 컬럼 자동 매핑
const weightKeys = ["weight", "cargo_weight", "total_weight", "중량", "무게"];
const distanceKeys = ["distance", "total_distance", "거리", "주행거리"];
const onTimeKeys = ["is_on_time", "on_time", "onTime", "정시", "정시도착"];
const deliveryTimeKeys = ["delivery_duration", "delivery_time", "duration", "배송시간", "소요시간", "배송소요시간"];
// 총 운송량 찾기
let total_weight = 0;
for (const key of Object.keys(numericColumns)) {
if (weightKeys.some((keyword) => key.toLowerCase().includes(keyword.toLowerCase()))) {
total_weight = numericColumns[key];
break;
}
}
// 누적 거리 찾기
let total_distance = 0;
for (const key of Object.keys(numericColumns)) {
if (distanceKeys.some((keyword) => key.toLowerCase().includes(keyword.toLowerCase()))) {
total_distance = numericColumns[key];
break;
}
}
// 정시 도착률 계산
let on_time_rate = 0;
for (const key of Object.keys(firstRow)) {
if (onTimeKeys.some((keyword) => key.toLowerCase().includes(keyword.toLowerCase()))) {
const onTimeItems = data.filter((item: any) => {
const onTime = item[key];
return onTime !== null && onTime !== undefined;
});
if (onTimeItems.length > 0) {
const onTimeCount = onTimeItems.filter((item: any) => {
const onTime = item[key];
return onTime === true || onTime === "true" || onTime === 1 || onTime === "1";
}).length;
on_time_rate = (onTimeCount / onTimeItems.length) * 100;
}
break;
}
}
// 평균 배송시간 계산
let avg_delivery_time = 0;
// 1. 먼저 배송시간 컬럼이 있는지 확인
let foundTimeColumn = false;
for (const key of Object.keys(numericColumns)) {
if (deliveryTimeKeys.some((keyword) => key.toLowerCase().includes(keyword.toLowerCase()))) {
const validItems = data.filter((item: any) => {
const time = parseFloat(item[key]);
return !isNaN(time) && time > 0;
});
if (validItems.length > 0) {
const totalTime = validItems.reduce((sum: number, item: any) => {
return sum + parseFloat(item[key]);
}, 0);
avg_delivery_time = totalTime / validItems.length;
foundTimeColumn = true;
}
break;
}
}
// 2. 배송시간 컬럼이 없으면 날짜 컬럼에서 자동 계산
if (!foundTimeColumn) {
const startTimeKeys = ["created_at", "start_time", "departure_time", "출발시간", "시작시간"];
const endTimeKeys = ["actual_delivery", "end_time", "arrival_time", "도착시간", "완료시간", "estimated_delivery"];
let startKey = null;
let endKey = null;
// 시작 시간 컬럼 찾기
for (const key of Object.keys(firstRow)) {
if (startTimeKeys.some((keyword) => key.toLowerCase().includes(keyword.toLowerCase()))) {
startKey = key;
break;
}
}
// 종료 시간 컬럼 찾기
for (const key of Object.keys(firstRow)) {
if (endTimeKeys.some((keyword) => key.toLowerCase().includes(keyword.toLowerCase()))) {
endKey = key;
break;
}
}
// 두 컬럼이 모두 있으면 시간 차이 계산
if (startKey && endKey) {
const validItems = data.filter((item: any) => {
return item[startKey] && item[endKey];
});
if (validItems.length > 0) {
const totalMinutes = validItems.reduce((sum: number, item: any) => {
const start = new Date(item[startKey]).getTime();
const end = new Date(item[endKey]).getTime();
const diffMinutes = (end - start) / (1000 * 60); // 밀리초 -> 분
return sum + (diffMinutes > 0 ? diffMinutes : 0);
}, 0);
avg_delivery_time = totalMinutes / validItems.length;
}
}
}
const calculatedStats: StatsData = {
total_count: data.length, // 총 건수
total_weight,
total_distance,
on_time_rate,
avg_delivery_time,
};
setStats(calculatedStats);
} catch (err) {
console.error("통계 로드 실패:", err);
setError(err instanceof Error ? err.message : "데이터를 불러올 수 없습니다");
} finally {
setIsLoading(false);
}
};
useEffect(() => {
loadData();
const interval = setInterval(loadData, refreshInterval);
return () => clearInterval(interval);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [refreshInterval, element?.dataSource]);
if (isLoading && !stats) {
return (
<div className="flex h-full items-center justify-center bg-gray-50">
<div className="text-center">
<div className="mx-auto h-8 w-8 animate-spin rounded-full border-4 border-blue-500 border-t-transparent" />
<div className="mt-2 text-sm text-gray-600"> ...</div>
</div>
</div>
);
}
if (error || !stats) {
return (
<div className="flex h-full items-center justify-center bg-gray-50 p-4">
<div className="text-center">
<div className="mb-2 text-4xl"></div>
<div className="text-sm font-medium text-gray-600">{error || "데이터 없음"}</div>
{!element?.dataSource?.query && (
<div className="mt-2 text-xs text-gray-500"> </div>
)}
<button
onClick={loadData}
className="mt-3 rounded-lg bg-blue-500 px-4 py-2 text-sm text-white hover:bg-blue-600"
>
</button>
</div>
</div>
);
}
return (
<div className="flex h-full items-center justify-center bg-white p-6">
<div className="grid w-full gap-4" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))" }}>
{/* 총 건수 */}
<div className="rounded-lg border bg-indigo-50 p-4 text-center">
<div className="text-sm text-gray-600"> </div>
<div className="mt-2 text-3xl font-bold text-indigo-600">
{stats.total_count.toLocaleString()}
<span className="ml-1 text-lg"></span>
</div>
</div>
{/* 총 운송량 */}
<div className="rounded-lg border bg-green-50 p-4 text-center">
<div className="text-sm text-gray-600"> </div>
<div className="mt-2 text-3xl font-bold text-green-600">
{stats.total_weight.toFixed(1)}
<span className="ml-1 text-lg"></span>
</div>
</div>
{/* 누적 거리 */}
<div className="rounded-lg border bg-blue-50 p-4 text-center">
<div className="text-sm text-gray-600"> </div>
<div className="mt-2 text-3xl font-bold text-blue-600">
{stats.total_distance.toFixed(1)}
<span className="ml-1 text-lg">km</span>
</div>
</div>
{/* 정시 도착률 */}
<div className="rounded-lg border bg-purple-50 p-4 text-center">
<div className="text-sm text-gray-600"> </div>
<div className="mt-2 text-3xl font-bold text-purple-600">
{stats.on_time_rate.toFixed(1)}
<span className="ml-1 text-lg">%</span>
</div>
</div>
{/* 평균 배송시간 */}
<div className="rounded-lg border bg-orange-50 p-4 text-center">
<div className="text-sm text-gray-600"> </div>
<div className="mt-2 text-3xl font-bold text-orange-600">
{stats.avg_delivery_time.toFixed(1)}
<span className="ml-1 text-lg"></span>
</div>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,222 @@
/**
*
* -
* -
* -
* -
*/
"use client";
import { useState, useEffect } from "react";
import { DashboardElement } from "@/components/admin/dashboard/types";
import {
WORK_TYPE_LABELS,
WORK_STATUS_LABELS,
WORK_STATUS_COLORS,
WorkType,
WorkStatus,
} from "@/types/workHistory";
interface WorkHistoryWidgetProps {
element: DashboardElement;
refreshInterval?: number;
}
export default function WorkHistoryWidget({ element, refreshInterval = 60000 }: WorkHistoryWidgetProps) {
const [data, setData] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedType, setSelectedType] = useState<WorkType | "all">("all");
const [selectedStatus, setSelectedStatus] = useState<WorkStatus | "all">("all");
// 데이터 로드
const loadData = async () => {
try {
setIsLoading(true);
setError(null);
// 쿼리가 설정되어 있으면 쿼리 실행
if (element.dataSource?.query) {
const token = localStorage.getItem("authToken");
const response = await fetch("/api/dashboards/execute-query", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
query: element.dataSource.query,
connectionType: element.dataSource.connectionType || "current",
connectionId: element.dataSource.connectionId,
}),
});
if (!response.ok) throw new Error("데이터 로딩 실패");
const result = await response.json();
if (result.success && result.data?.rows) {
setData(result.data.rows);
} else {
throw new Error(result.message || "데이터 로드 실패");
}
} else {
// 쿼리 미설정 시 안내 메시지
setError("쿼리를 설정해주세요");
setData([]);
}
} catch (err) {
console.error("작업 이력 로드 실패:", err);
setError(err instanceof Error ? err.message : "데이터를 불러올 수 없습니다");
} finally {
setIsLoading(false);
}
};
useEffect(() => {
loadData();
const interval = setInterval(loadData, refreshInterval);
return () => clearInterval(interval);
}, [selectedType, selectedStatus, refreshInterval, element.dataSource]);
if (isLoading && data.length === 0) {
return (
<div className="flex h-full items-center justify-center bg-gray-50">
<div className="text-center">
<div className="mx-auto h-8 w-8 animate-spin rounded-full border-4 border-blue-500 border-t-transparent" />
<div className="mt-2 text-sm text-gray-600"> ...</div>
</div>
</div>
);
}
if (error) {
return (
<div className="flex h-full items-center justify-center bg-gray-50 p-4">
<div className="text-center">
<div className="mb-2 text-4xl"></div>
<div className="text-sm font-medium text-gray-600">{error}</div>
{!element.dataSource?.query && (
<div className="mt-2 text-xs text-gray-500">
</div>
)}
<button
onClick={loadData}
className="mt-3 rounded-lg bg-blue-500 px-4 py-2 text-sm text-white hover:bg-blue-600"
>
</button>
</div>
</div>
);
}
return (
<div className="flex h-full flex-col bg-white">
{/* 필터 */}
<div className="flex gap-2 border-b p-3">
<select
value={selectedType}
onChange={(e) => setSelectedType(e.target.value as WorkType | "all")}
className="rounded border px-2 py-1 text-sm"
>
<option value="all"> </option>
<option value="inbound"></option>
<option value="outbound"></option>
<option value="transfer"></option>
<option value="maintenance"></option>
</select>
<select
value={selectedStatus}
onChange={(e) => setSelectedStatus(e.target.value as WorkStatus | "all")}
className="rounded border px-2 py-1 text-sm"
>
<option value="all"> </option>
<option value="pending"></option>
<option value="in_progress"></option>
<option value="completed"></option>
<option value="cancelled"></option>
</select>
<button
onClick={loadData}
className="ml-auto rounded bg-blue-500 px-3 py-1 text-sm text-white hover:bg-blue-600"
>
🔄
</button>
</div>
{/* 테이블 */}
<div className="flex-1 overflow-auto">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-gray-50 text-left">
<tr>
<th className="border-b px-3 py-2 font-medium"></th>
<th className="border-b px-3 py-2 font-medium"></th>
<th className="border-b px-3 py-2 font-medium"></th>
<th className="border-b px-3 py-2 font-medium"></th>
<th className="border-b px-3 py-2 font-medium"></th>
<th className="border-b px-3 py-2 font-medium"></th>
<th className="border-b px-3 py-2 font-medium"></th>
<th className="border-b px-3 py-2 font-medium"></th>
</tr>
</thead>
<tbody>
{data.length === 0 ? (
<tr>
<td colSpan={8} className="py-8 text-center text-gray-500">
</td>
</tr>
) : (
data
.filter((item) => selectedType === "all" || item.work_type === selectedType)
.filter((item) => selectedStatus === "all" || item.status === selectedStatus)
.map((item, index) => (
<tr key={item.id || index} className="border-b hover:bg-gray-50">
<td className="px-3 py-2 font-mono text-xs">{item.work_number}</td>
<td className="px-3 py-2">
{item.work_date
? new Date(item.work_date).toLocaleString("ko-KR", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
})
: "-"}
</td>
<td className="px-3 py-2">
<span className="rounded bg-blue-100 px-2 py-1 text-xs font-medium text-blue-800">
{WORK_TYPE_LABELS[item.work_type as WorkType] || item.work_type}
</span>
</td>
<td className="px-3 py-2">{item.vehicle_number || "-"}</td>
<td className="px-3 py-2 text-xs">
{item.origin && item.destination ? `${item.origin}${item.destination}` : "-"}
</td>
<td className="px-3 py-2">{item.cargo_name || "-"}</td>
<td className="px-3 py-2">
{item.cargo_weight ? `${item.cargo_weight} ${item.cargo_unit || "ton"}` : "-"}
</td>
<td className="px-3 py-2">
<span
className={`rounded px-2 py-1 text-xs font-medium ${WORK_STATUS_COLORS[item.status as WorkStatus] || "bg-gray-100 text-gray-800"}`}
>
{WORK_STATUS_LABELS[item.status as WorkStatus] || item.status}
</span>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* 푸터 */}
<div className="border-t bg-gray-50 px-3 py-2 text-xs text-gray-600"> {data.length}</div>
</div>
);
}

View File

@ -0,0 +1,86 @@
/**
* ()
*/
export type WorkType = 'inbound' | 'outbound' | 'transfer' | 'maintenance';
export type WorkStatus = 'pending' | 'in_progress' | 'completed' | 'cancelled';
export interface WorkHistory {
id: number;
work_number: string;
work_date: string;
work_type: WorkType;
vehicle_number?: string;
driver_name?: string;
origin?: string;
destination?: string;
cargo_name?: string;
cargo_weight?: number;
cargo_unit?: string;
distance?: number;
distance_unit?: string;
status: WorkStatus;
scheduled_time?: string;
start_time?: string;
end_time?: string;
estimated_arrival?: string;
actual_arrival?: string;
is_on_time?: boolean;
delay_reason?: string;
notes?: string;
created_by?: string;
created_at: string;
updated_at: string;
}
export interface WorkHistoryStats {
today_total: number;
today_completed: number;
total_weight: number;
total_distance: number;
on_time_rate: number;
type_distribution: {
inbound: number;
outbound: number;
transfer: number;
maintenance: number;
};
}
export interface MonthlyTrend {
month: string;
total: number;
completed: number;
weight: number;
distance: number;
}
export interface TopRoute {
origin: string;
destination: string;
count: number;
total_weight: number;
}
// 한글 라벨
export const WORK_TYPE_LABELS: Record<WorkType, string> = {
inbound: '입고',
outbound: '출고',
transfer: '이송',
maintenance: '정비',
};
export const WORK_STATUS_LABELS: Record<WorkStatus, string> = {
pending: '대기',
in_progress: '진행중',
completed: '완료',
cancelled: '취소',
};
export const WORK_STATUS_COLORS: Record<WorkStatus, string> = {
pending: 'bg-gray-100 text-gray-800',
in_progress: 'bg-blue-100 text-blue-800',
completed: 'bg-green-100 text-green-800',
cancelled: 'bg-red-100 text-red-800',
};