chpark-sync #425

Merged
kjs merged 293 commits from chpark-sync into main 2026-03-23 09:36:36 +09:00
44 changed files with 4383 additions and 797 deletions
Showing only changes of commit ab48e93487 - Show all commits

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

@ -0,0 +1,426 @@
# 야드 관리 3D - 데이터 바인딩 시스템 재설계
## 1. 개요
### 현재 방식의 문제점
- 고정된 임시 자재 마스터(`temp_material_master`) 테이블에 의존
- 실제 외부 시스템의 자재 데이터와 연동 불가
- 자재 목록이 제한적이고 유연성 부족
- 사용자가 직접 데이터를 선택하거나 입력할 수 없음
### 새로운 방식의 목표
- 차트/리스트 위젯과 동일한 데이터 소스 선택 방식 적용
- DB 커넥션 또는 REST API를 통해 실제 자재 데이터 연동
- 사용자가 자재명, 수량 등을 직접 매핑 및 입력 가능
- 설정되지 않은 요소는 뷰어에서 명확히 표시
---
## 2. 핵심 변경사항
### 2.1 요소(Element) 개념 도입
- 기존: 자재 목록에서 클릭 → 즉시 배치
- 변경: [+ 요소 추가] 버튼 클릭 → 3D 캔버스에 즉시 빈 요소 배치 → 우측 패널이 데이터 바인딩 설정 화면으로 전환
### 2.2 데이터 소스 선택
- 현재 DB (내부 PostgreSQL)
- 외부 DB 커넥션
- REST API
### 2.3 데이터 매핑
- 자재명 필드 선택 (데이터 소스에서)
- 수량 필드 선택 (데이터 소스에서)
- 단위 직접 입력 (예: EA, BOX, KG 등)
- 색상 선택
---
## 3. 데이터베이스 스키마 변경
### 3.1 기존 테이블 수정: `yard_material_placement`
```sql
-- 기존 컬럼 변경
ALTER TABLE yard_material_placement
-- 기존 컬럼 제거 (외부 자재 ID 관련)
DROP COLUMN IF EXISTS external_material_id,
-- 데이터 소스 정보 추가
ADD COLUMN data_source_type VARCHAR(20), -- 'database', 'external_db', 'rest_api'
ADD COLUMN data_source_config JSONB, -- 데이터 소스 설정
-- 데이터 바인딩 정보 추가
ADD COLUMN data_binding JSONB, -- 필드 매핑 정보
-- 자재 정보를 NULL 허용으로 변경 (설정 전에는 NULL)
ALTER COLUMN material_code DROP NOT NULL,
ALTER COLUMN material_name DROP NOT NULL,
ALTER COLUMN quantity DROP NOT NULL;
```
### 3.2 data_source_config 구조
```typescript
interface DataSourceConfig {
type: "database" | "external_db" | "rest_api";
// type === 'database' (현재 DB)
query?: string;
// type === 'external_db' (외부 DB)
connectionId?: number;
query?: string;
// type === 'rest_api'
url?: string;
method?: "GET" | "POST";
headers?: Record<string, string>;
queryParams?: Record<string, string>;
body?: string;
dataPath?: string; // 응답에서 데이터 배열 경로 (예: "data.items")
}
```
### 3.3 data_binding 구조
```typescript
interface DataBinding {
// 데이터 소스의 특정 행 선택
selectedRowIndex?: number;
// 필드 매핑 (데이터 소스에서 선택)
materialNameField?: string; // 자재명이 들어있는 컬럼명
quantityField?: string; // 수량이 들어있는 컬럼명
// 단위는 사용자가 직접 입력
unit: string; // 예: "EA", "BOX", "KG", "M" 등
}
```
---
## 4. UI/UX 설계
### 4.1 편집 모드 (YardEditor)
```
┌─────────────────────────────────────────────────────────────┐
│ [← 목록으로] 야드명: A구역 [저장] │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────────┐ ┌──────────────────────────┐│
│ │ │ │ ││
│ │ │ │ [+ 요소 추가] ││
│ │ │ │ ││
│ │ 3D 캔버스 │ │ ┌────────────────────┐ ││
│ │ │ │ │ □ 요소 1 │ ││
│ │ │ │ │ 자재: 철판 A │ ││
│ │ │ │ │ 수량: 50 EA │ ││
│ │ │ │ │ [편집] [삭제] │ ││
│ │ │ │ └────────────────────┘ ││
│ │ │ │ ││
│ │ │ │ ┌────────────────────┐ ││
│ │ │ │ │ □ 요소 2 (미설정) │ ││
│ │ │ │ │ 데이터 바인딩 │ ││
│ │ │ │ │ 설정 필요 │ ││
│ │ │ │ │ [설정] [삭제] │ ││
│ │ │ │ └────────────────────┘ ││
│ │ │ │ ││
│ └───────────────────────────┘ └──────────────────────────┘│
│ │
└─────────────────────────────────────────────────────────────┘
```
#### 4.1.1 요소 목록 (우측 패널)
- **[+ 요소 추가]** 버튼: 새 요소 생성
- **요소 카드**:
- 설정 완료: 자재명, 수량 표시 + [편집] [삭제] 버튼
- 미설정: "데이터 바인딩 설정 필요" + [설정] [삭제] 버튼
#### 4.1.2 요소 추가 흐름
```
1. [+ 요소 추가] 클릭
2. 3D 캔버스의 기본 위치(0,0,0)에 회색 반투명 박스로 빈 요소 즉시 배치
3. 요소가 자동 선택됨
4. 우측 패널이 "데이터 바인딩 설정" 화면으로 자동 전환
(요소 목록에서 [설정] 버튼을 클릭해도 동일한 화면)
```
### 4.2 데이터 바인딩 설정 패널 (우측)
**[+ 요소 추가] 버튼 클릭 시 또는 [설정] 버튼 클릭 시 우측 패널이 아래와 같이 변경됩니다:**
```
┌──────────────────────────────────────┐
│ 데이터 바인딩 설정 [← 목록]│
├──────────────────────────────────────┤
│ │
│ ┌─ 1단계: 데이터 소스 선택 ─────────────────────────┐ │
│ │ │ │
│ │ ○ 현재 DB ○ 외부 DB ○ REST API │ │
│ │ │ │
│ │ [현재 DB 선택 시] │ │
│ │ ┌────────────────────────────────────────────┐ │ │
│ │ │ SELECT material_name, quantity, unit │ │ │
│ │ │ FROM inventory │ │ │
│ │ │ WHERE status = 'available' │ │ │
│ │ └────────────────────────────────────────────┘ │ │
│ │ [실행] 버튼 │ │
│ │ │ │
│ │ [외부 DB 선택 시] │ │
│ │ - 외부 커넥션 선택 드롭다운 │ │
│ │ - SQL 쿼리 입력 │ │
│ │ - [실행] 버튼 │ │
│ │ │ │
│ │ [REST API 선택 시] │ │
│ │ - URL 입력 │ │
│ │ - Method 선택 (GET/POST) │ │
│ │ - Headers, Query Params 설정 │ │
│ │ - [실행] 버튼 │ │
│ │ │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ ┌─ 2단계: 쿼리 결과 및 필드 매핑 ──────────────────────┐ │
│ │ │ │
│ │ 쿼리 결과 (5행): │ │
│ │ ┌────────────────────────────────────────────┐ │ │
│ │ │ material_name │ quantity │ status │ │ │
│ │ │ 철판 A │ 50 │ available │ ○ │ │
│ │ │ 강관 파이프 │ 100 │ available │ ○ │ │
│ │ │ 볼트 세트 │ 500 │ in_stock │ ○ │ │
│ │ └────────────────────────────────────────────┘ │ │
│ │ │ │
│ │ 필드 매핑: │ │
│ │ 자재명: [material_name ▼] │ │
│ │ 수량: [quantity ▼] │ │
│ │ │ │
│ │ 단위 입력: │ │
│ │ 단위: [EA_____________] │ │
│ │ (예: EA, BOX, KG, M, L 등) │ │
│ │ │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ ┌─ 3단계: 배치 설정 ──────────────────────────────────┐ │
│ │ │ │
│ │ 색상: [🎨 #3b82f6] │ │
│ │ │ │
│ │ 크기: │ │
│ │ 너비: [5] 높이: [5] 깊이: [5] │ │
│ │ │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ [← 목록으로] [저장] │
└──────────────────────────────────────┘
```
**참고:**
- [← 목록으로] 버튼: 요소 목록 화면으로 돌아갑니다
- [저장] 버튼: 데이터 바인딩 설정을 저장하고 요소 목록 화면으로 돌아갑니다
- 저장하지 않고 나가면 요소는 "미설정" 상태로 남습니다
### 4.3 뷰어 모드 (Yard3DViewer)
#### 4.3.1 설정된 요소
- 정상적으로 3D 박스 렌더링
- 클릭 시 자재명, 수량 정보 표시
#### 4.3.2 미설정 요소
```
┌─────────────────────┐
│ │
│ ⚠️ │
│ │
│ 설정되지 않은 │
│ 요소입니다 │
│ │
└─────────────────────┘
```
- 반투명 회색 박스로 표시
- 클릭 시 "데이터 바인딩이 설정되지 않았습니다" 메시지
---
## 5. 구현 단계
### Phase 1: 데이터베이스 스키마 변경
- [ ] `yard_material_placement` 테이블 수정
- [ ] 마이그레이션 스크립트 작성
- [ ] 기존 데이터 호환성 처리
### Phase 2: 백엔드 API 수정
- [ ] `YardLayoutService.ts` 수정
- `addMaterialPlacement`: 데이터 소스/바인딩 정보 저장
- `updatePlacement`: 데이터 바인딩 업데이트
- `getPlacementsByLayoutId`: 새 필드 포함하여 조회
- [ ] 데이터 소스 실행 로직 추가
- DB 쿼리 실행
- 외부 DB 쿼리 실행
- REST API 호출
### Phase 3: 프론트엔드 타입 정의
- [ ] `types.ts`에 새로운 인터페이스 추가
- `YardElementDataSource`
- `YardElementDataBinding`
- `YardPlacement` 업데이트
### Phase 4: 요소 추가 및 관리
- [ ] `YardEditor.tsx` 수정
- [+ 요소 추가] 버튼 구현
- 빈 요소 생성 로직 (즉시 3D 캔버스에 배치)
- 요소 추가 시 자동으로 해당 요소 선택
- 우측 패널 상태 관리 (요소 목록 ↔ 데이터 바인딩 설정)
- 요소 목록 UI
- 설정/미설정 상태 구분 표시
### Phase 5: 데이터 바인딩 패널
- [ ] `YardElementConfigPanel.tsx` 생성 (우측 패널 컴포넌트)
- [← 목록으로] 버튼으로 요소 목록으로 복귀
- 1단계: 데이터 소스 선택 (DatabaseConfig, ExternalDbConfig, RestApiConfig 재사용)
- 2단계: 쿼리 결과 테이블 + 행 선택 + 필드 매핑
- 자재명 필드 선택 (드롭다운)
- 수량 필드 선택 (드롭다운)
- 단위 직접 입력 (Input)
- 3단계: 배치 설정 (색상, 크기)
- [저장] 버튼으로 설정 저장 및 목록으로 복귀
### Phase 6: 3D 캔버스 렌더링 수정
- [ ] `Yard3DCanvas.tsx` 수정
- 설정된 요소: 기존 렌더링
- 미설정 요소: 회색 반투명 박스 + 경고 아이콘
### Phase 7: 뷰어 모드 수정
- [ ] `Yard3DViewer.tsx` 수정
- 미설정 요소 감지
- 미설정 요소 클릭 시 안내 메시지
### Phase 8: 임시 테이블 제거
- [ ] `temp_material_master` 테이블 삭제
- [ ] 관련 API 및 UI 코드 정리
---
## 6. 데이터 구조 예시
### 6.1 데이터 소스 + 필드 매핑 사용
```json
{
"id": 1,
"yard_layout_id": 1,
"material_code": null,
"material_name": "철판 A타입",
"quantity": 50,
"unit": "EA",
"data_source_type": "database",
"data_source_config": {
"type": "database",
"query": "SELECT material_name, quantity FROM inventory WHERE material_id = 'MAT-001'"
},
"data_binding": {
"selectedRowIndex": 0,
"materialNameField": "material_name",
"quantityField": "quantity",
"unit": "EA"
},
"position_x": 10,
"position_y": 0,
"position_z": 10,
"size_x": 5,
"size_y": 5,
"size_z": 5,
"color": "#ef4444"
}
```
### 6.2 미설정 요소
```json
{
"id": 3,
"yard_layout_id": 1,
"material_code": null,
"material_name": null,
"quantity": null,
"unit": null,
"data_source_type": null,
"data_source_config": null,
"data_binding": null,
"position_x": 30,
"position_y": 0,
"position_z": 30,
"size_x": 5,
"size_y": 5,
"size_z": 5,
"color": "#9ca3af"
}
```
---
## 7. 장점
1. **유연성**: 다양한 데이터 소스 지원 (내부 DB, 외부 DB, REST API)
2. **실시간성**: 실제 시스템의 자재 데이터와 연동 가능
3. **일관성**: 차트/리스트 위젯과 동일한 데이터 소스 선택 방식
4. **사용자 경험**: 데이터 매핑 방식 선택 가능 (자동/수동)
5. **확장성**: 새로운 데이터 소스 타입 추가 용이
6. **명확성**: 미설정 요소를 시각적으로 구분
---
## 8. 마이그레이션 전략
### 8.1 기존 데이터 처리
- 기존 `temp_material_master` 기반 배치 데이터를 수동 입력 모드로 전환
- `external_material_id``data_binding.mode = 'manual'`로 변환
### 8.2 단계적 전환
1. 새 스키마 적용 (기존 컬럼 유지)
2. 새 UI/로직 구현 및 테스트
3. 기존 데이터 마이그레이션
4. 임시 테이블 및 구 코드 제거
---
## 9. 기술 스택
- **백엔드**: PostgreSQL JSONB, Node.js/TypeScript
- **프론트엔드**: React, TypeScript, Shadcn UI
- **3D 렌더링**: React Three Fiber, Three.js
- **데이터 소스**: 기존 `DatabaseConfig`, `ExternalDbConfig`, `RestApiConfig` 컴포넌트 재사용
---
## 10. 예상 개발 기간
- Phase 1-2 (DB/백엔드): 1일
- Phase 3-4 (프론트엔드 구조): 1일
- Phase 5 (데이터 바인딩 모달): 2일
- Phase 6-7 (3D 렌더링/뷰어): 1일
- Phase 8 (정리 및 테스트): 0.5일
**총 예상 기간: 약 5.5일**

View File

@ -1 +1,54 @@
[]
[
{
"id": "e5bb334c-d58a-4068-ad77-2607a41f4675",
"title": "ㅁㄴㅇㄹ",
"description": "ㅁㄴㅇㄹ",
"priority": "normal",
"status": "pending",
"assignedTo": "",
"dueDate": "2025-10-20T18:17",
"createdAt": "2025-10-20T06:15:49.610Z",
"updatedAt": "2025-10-20T06:15:49.610Z",
"isUrgent": false,
"order": 0
},
{
"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

@ -56,7 +56,7 @@ import todoRoutes from "./routes/todoRoutes"; // To-Do 관리
import bookingRoutes from "./routes/bookingRoutes"; // 예약 요청 관리
import mapDataRoutes from "./routes/mapDataRoutes"; // 지도 데이터 관리
import yardLayoutRoutes from "./routes/yardLayoutRoutes"; // 야드 관리 3D
import materialRoutes from "./routes/materialRoutes"; // 자재 관리
import workHistoryRoutes from "./routes/workHistoryRoutes"; // 작업 이력 관리
import { BatchSchedulerService } from "./services/batchSchedulerService";
// import collectionRoutes from "./routes/collectionRoutes"; // 임시 주석
// import batchRoutes from "./routes/batchRoutes"; // 임시 주석
@ -207,7 +207,7 @@ app.use("/api/todos", todoRoutes); // To-Do 관리
app.use("/api/bookings", bookingRoutes); // 예약 요청 관리
app.use("/api/map-data", mapDataRoutes); // 지도 데이터 조회
app.use("/api/yard-layouts", yardLayoutRoutes); // 야드 관리 3D
app.use("/api/materials", materialRoutes); // 자재 관리
app.use("/api/work-history", workHistoryRoutes); // 작업 이력 관리
// app.use("/api/collections", collectionRoutes); // 임시 주석
// app.use("/api/batch", batchRoutes); // 임시 주석
// app.use('/api/users', userRoutes);

View File

@ -1,68 +0,0 @@
import { Request, Response } from "express";
import MaterialService from "../services/MaterialService";
export class MaterialController {
// 임시 자재 마스터 목록 조회
async getTempMaterials(req: Request, res: Response) {
try {
const { search, category, page, limit } = req.query;
const result = await MaterialService.getTempMaterials({
search: search as string,
category: category as string,
page: page ? parseInt(page as string) : 1,
limit: limit ? parseInt(limit as string) : 20,
});
return res.json({ success: true, ...result });
} catch (error: any) {
console.error("Error fetching temp materials:", error);
return res.status(500).json({
success: false,
message: "자재 목록 조회 중 오류가 발생했습니다.",
error: error.message,
});
}
}
// 특정 자재 상세 조회
async getTempMaterialByCode(req: Request, res: Response) {
try {
const { code } = req.params;
const material = await MaterialService.getTempMaterialByCode(code);
if (!material) {
return res.status(404).json({
success: false,
message: "자재를 찾을 수 없습니다.",
});
}
return res.json({ success: true, data: material });
} catch (error: any) {
console.error("Error fetching temp material:", error);
return res.status(500).json({
success: false,
message: "자재 조회 중 오류가 발생했습니다.",
error: error.message,
});
}
}
// 카테고리 목록 조회
async getCategories(req: Request, res: Response) {
try {
const categories = await MaterialService.getCategories();
return res.json({ success: true, data: categories });
} catch (error: any) {
console.error("Error fetching categories:", error);
return res.status(500).json({
success: false,
message: "카테고리 목록 조회 중 오류가 발생했습니다.",
error: error.message,
});
}
}
}
export default new MaterialController();

View File

@ -146,18 +146,14 @@ export class YardLayoutController {
}
}
// 야드에 자재 배치 추가
// 야드에 자재 배치 추가 (빈 요소 또는 설정된 요소)
async addMaterialPlacement(req: Request, res: Response) {
try {
const { id } = req.params;
const placementData = req.body;
if (!placementData.external_material_id || !placementData.material_code) {
return res.status(400).json({
success: false,
message: "자재 정보가 필요합니다.",
});
}
// 데이터 바인딩 재설계 후 material_code와 external_material_id는 선택사항
// 빈 요소를 추가할 수 있어야 함
const placement = await YardLayoutService.addMaterialPlacement(
parseInt(id),

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

@ -1,15 +0,0 @@
import express from "express";
import MaterialController from "../controllers/MaterialController";
import { authenticateToken } from "../middleware/authMiddleware";
const router = express.Router();
// 모든 라우트에 인증 미들웨어 적용
router.use(authenticateToken);
// 임시 자재 마스터 관리
router.get("/temp", MaterialController.getTempMaterials);
router.get("/temp/categories", MaterialController.getCategories);
router.get("/temp/:code", MaterialController.getTempMaterialByCode);
export default router;

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

@ -1,111 +0,0 @@
import { getPool } from "../database/db";
export class MaterialService {
// 임시 자재 마스터 목록 조회
async getTempMaterials(params: {
search?: string;
category?: string;
page?: number;
limit?: number;
}) {
const { search, category, page = 1, limit = 20 } = params;
const offset = (page - 1) * limit;
let whereConditions: string[] = ["is_active = true"];
const queryParams: any[] = [];
let paramIndex = 1;
if (search) {
whereConditions.push(
`(material_code ILIKE $${paramIndex} OR material_name ILIKE $${paramIndex})`
);
queryParams.push(`%${search}%`);
paramIndex++;
}
if (category) {
whereConditions.push(`category = $${paramIndex}`);
queryParams.push(category);
paramIndex++;
}
const whereClause =
whereConditions.length > 0
? `WHERE ${whereConditions.join(" AND ")}`
: "";
const pool = getPool();
// 전체 개수 조회
const countQuery = `SELECT COUNT(*) as total FROM temp_material_master ${whereClause}`;
const countResult = await pool.query(countQuery, queryParams);
const total = parseInt(countResult.rows[0].total);
// 데이터 조회
const dataQuery = `
SELECT
id,
material_code,
material_name,
category,
unit,
default_color,
description,
created_at
FROM temp_material_master
${whereClause}
ORDER BY material_code ASC
LIMIT $${paramIndex} OFFSET $${paramIndex + 1}
`;
queryParams.push(limit, offset);
const dataResult = await pool.query(dataQuery, queryParams);
return {
data: dataResult.rows,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit),
},
};
}
// 특정 자재 상세 조회
async getTempMaterialByCode(materialCode: string) {
const query = `
SELECT
id,
material_code,
material_name,
category,
unit,
default_color,
description,
created_at
FROM temp_material_master
WHERE material_code = $1 AND is_active = true
`;
const pool = getPool();
const result = await pool.query(query, [materialCode]);
return result.rows[0] || null;
}
// 카테고리 목록 조회
async getCategories() {
const query = `
SELECT DISTINCT category
FROM temp_material_master
WHERE is_active = true AND category IS NOT NULL
ORDER BY category ASC
`;
const pool = getPool();
const result = await pool.query(query);
return result.rows.map((row) => row.category);
}
}
export default new MaterialService();

View File

@ -101,7 +101,6 @@ export class YardLayoutService {
SELECT
id,
yard_layout_id,
external_material_id,
material_code,
material_name,
quantity,
@ -113,6 +112,9 @@ export class YardLayoutService {
size_y,
size_z,
color,
data_source_type,
data_source_config,
data_binding,
memo,
created_at,
updated_at
@ -126,12 +128,11 @@ export class YardLayoutService {
return result.rows;
}
// 야드에 자재 배치 추가
// 야드에 자재 배치 추가 (빈 요소 또는 설정된 요소)
async addMaterialPlacement(layoutId: number, data: any) {
const query = `
INSERT INTO yard_material_placement (
yard_layout_id,
external_material_id,
material_code,
material_name,
quantity,
@ -143,60 +144,114 @@ export class YardLayoutService {
size_y,
size_z,
color,
data_source_type,
data_source_config,
data_binding,
memo
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
RETURNING *
`;
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.external_material_id,
data.material_code,
data.material_name,
data.quantity,
data.unit,
data.position_x || 0,
data.position_y || 0,
data.position_z || 0,
data.size_x || 5,
data.size_y || 5,
data.size_z || 5,
data.color || "#3b82f6",
data.material_code || null,
data.material_name || null,
safeParseInt(data.quantity, null),
data.unit || null,
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,
data.data_binding ? JSON.stringify(data.data_binding) : null,
data.memo || null,
]);
return result.rows[0];
}
// 배치 정보 수정 (위치, 크기, 색상, 메모만)
// 배치 정보 수정 (위치, 크기, 색상, 데이터 바인딩 등)
async updatePlacement(placementId: number, data: any) {
const query = `
UPDATE yard_material_placement
SET
position_x = COALESCE($1, position_x),
position_y = COALESCE($2, position_y),
position_z = COALESCE($3, position_z),
size_x = COALESCE($4, size_x),
size_y = COALESCE($5, size_y),
size_z = COALESCE($6, size_z),
color = COALESCE($7, color),
memo = COALESCE($8, memo),
material_code = COALESCE($1, material_code),
material_name = COALESCE($2, material_name),
quantity = COALESCE($3, quantity),
unit = COALESCE($4, unit),
position_x = COALESCE($5, position_x),
position_y = COALESCE($6, position_y),
position_z = COALESCE($7, position_z),
size_x = COALESCE($8, size_x),
size_y = COALESCE($9, size_y),
size_z = COALESCE($10, size_z),
color = COALESCE($11, color),
data_source_type = COALESCE($12, data_source_type),
data_source_config = COALESCE($13, data_source_config),
data_binding = COALESCE($14, data_binding),
memo = COALESCE($15, memo),
updated_at = CURRENT_TIMESTAMP
WHERE id = $9
WHERE id = $16
RETURNING *
`;
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.position_x,
data.position_y,
data.position_z,
data.size_x,
data.size_y,
data.size_z,
data.color,
data.memo,
data.material_code !== undefined ? data.material_code : null,
data.material_name !== undefined ? data.material_name : null,
data.quantity !== undefined ? safeParseInt(data.quantity) : null,
data.unit !== undefined ? data.unit : 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
? JSON.stringify(data.data_source_config)
: null,
data.data_binding !== undefined
? JSON.stringify(data.data_binding)
: null,
data.memo !== undefined ? data.memo : null,
placementId,
]);
@ -230,8 +285,9 @@ export class YardLayoutService {
size_x = $4,
size_y = $5,
size_z = $6,
color = $7,
updated_at = CURRENT_TIMESTAMP
WHERE id = $7 AND yard_layout_id = $8
WHERE id = $8 AND yard_layout_id = $9
RETURNING *
`;
@ -242,6 +298,7 @@ export class YardLayoutService {
placement.size_x,
placement.size_y,
placement.size_z,
placement.color,
placement.id,
layoutId,
]);
@ -299,14 +356,14 @@ export class YardLayoutService {
await client.query(
`
INSERT INTO yard_material_placement (
yard_layout_id, external_material_id, material_code, material_name,
yard_layout_id, material_code, material_name,
quantity, unit, position_x, position_y, position_z,
size_x, size_y, size_z, color, memo
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
size_x, size_y, size_z, color,
data_source_type, data_source_config, data_binding, memo
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
`,
[
newLayout.id,
placement.external_material_id,
placement.material_code,
placement.material_name,
placement.quantity,
@ -318,6 +375,9 @@ export class YardLayoutService {
placement.size_y,
placement.size_z,
placement.color,
placement.data_source_type,
placement.data_source_config,
placement.data_binding,
placement.memo,
]
);

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) {
@ -163,6 +164,7 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
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,
@ -163,7 +177,7 @@ export function CanvasElement({
const handleMouseDown = useCallback(
(e: React.MouseEvent) => {
// 모달이나 다이얼로그가 열려있으면 드래그 무시
if (document.querySelector('[role="dialog"]')) {
if (document.querySelector('[role="dialog"]') || document.querySelector('[role="alertdialog"]')) {
return;
}
@ -198,7 +212,7 @@ export function CanvasElement({
const handleResizeMouseDown = useCallback(
(e: React.MouseEvent, handle: string) => {
// 모달이나 다이얼로그가 열려있으면 리사이즈 무시
if (document.querySelector('[role="dialog"]')) {
if (document.querySelector('[role="dialog"]') || document.querySelector('[role="alertdialog"]')) {
return;
}
@ -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 좌표 스냅
@ -197,6 +196,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,7 +353,16 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
try {
const { dashboardApi } = await import("@/lib/api/dashboard");
const elementsData = elements.map((el) => ({
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,
@ -346,7 +376,8 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
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

@ -219,6 +219,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> */}

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") {
@ -155,10 +173,14 @@ 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");
// 그리드 라인
if (config.showGrid !== false) {
// Y축 그리기 (값 표시 제거)
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);
}
.call(d3.axisLeft(yScale).tickFormat(() => ""))
.style("font-size", "12px");
// 그리드 라인 제거됨
// 색상 팔레트
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");
// 그리드 라인
if (config.showGrid !== false) {
// Y축 그리기 (값 표시 제거)
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);
}
.call(d3.axisLeft(yScale).tickFormat(() => ""))
.style("font-size", "12px");
// 그리드 라인 제거됨
// 색상 팔레트
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,12 +95,11 @@ export function ListWidgetConfigModal({ isOpen, element, onClose, onSave }: List
}, []);
// 쿼리 실행 결과 처리
const handleQueryTest = useCallback(
(result: QueryResult) => {
const handleQueryTest = useCallback((result: QueryResult) => {
setQueryResult(result);
// 자동 모드이고 기존 컬럼이 없을 때만 자동 생성
if (listConfig.columnMode === "auto" && result.columns.length > 0 && listConfig.columns.length === 0) {
// 쿼리 실행할 때마다 컬럼 초기화 후 자동 생성
if (result.columns.length > 0) {
const autoColumns: ListColumn[] = result.columns.map((col, idx) => ({
id: `col_${idx}`,
label: col,
@ -110,9 +109,7 @@ export function ListWidgetConfigModal({ isOpen, element, onClose, onSave }: List
}));
setListConfig((prev) => ({ ...prev, columns: autoColumns }));
}
},
[listConfig.columnMode, listConfig.columns.length],
);
}, []);
// 다음 단계
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

@ -3,8 +3,7 @@
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Plus, Check } from "lucide-react";
import YardLayoutList from "./yard-3d/YardLayoutList";
import { Plus, Check, Trash2 } from "lucide-react";
import YardLayoutCreateModal from "./yard-3d/YardLayoutCreateModal";
import YardEditor from "./yard-3d/YardEditor";
import Yard3DViewer from "./yard-3d/Yard3DViewer";
@ -16,6 +15,7 @@ interface YardLayout {
name: string;
description: string;
placement_count: number;
created_at: string;
updated_at: string;
}
@ -34,6 +34,7 @@ export default function YardManagement3DWidget({
const [isLoading, setIsLoading] = useState(true);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const [editingLayout, setEditingLayout] = useState<YardLayout | null>(null);
const [deleteLayoutId, setDeleteLayoutId] = useState<number | null>(null);
// 레이아웃 목록 로드
const loadLayouts = async () => {
@ -41,7 +42,7 @@ export default function YardManagement3DWidget({
setIsLoading(true);
const response = await yardLayoutApi.getAllLayouts();
if (response.success) {
setLayouts(response.data);
setLayouts(response.data as YardLayout[]);
}
} catch (error) {
console.error("야드 레이아웃 목록 조회 실패:", error);
@ -56,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) {
@ -73,7 +85,7 @@ export default function YardManagement3DWidget({
if (response.success) {
await loadLayouts();
setIsCreateModalOpen(false);
setEditingLayout(response.data);
setEditingLayout(response.data as YardLayout);
}
} catch (error) {
console.error("야드 레이아웃 생성 실패:", error);
@ -93,6 +105,26 @@ export default function YardManagement3DWidget({
loadLayouts();
};
// 레이아웃 삭제
const handleDeleteLayout = async () => {
if (!deleteLayoutId) return;
try {
const response = await yardLayoutApi.deleteLayout(deleteLayoutId);
if (response.success) {
// 삭제된 레이아웃이 현재 선택된 레이아웃이면 설정 초기화
if (config?.layoutId === deleteLayoutId && onConfigChange) {
onConfigChange({ layoutId: 0, layoutName: "" });
}
await loadLayouts();
}
} catch (error) {
console.error("레이아웃 삭제 실패:", error);
} finally {
setDeleteLayoutId(null);
}
};
// 편집 모드: 편집 중인 경우 YardEditor 표시
if (isEditMode && editingLayout) {
return (
@ -149,6 +181,7 @@ export default function YardManagement3DWidget({
{layout.description && <p className="mt-1 text-xs text-gray-500">{layout.description}</p>}
<div className="mt-2 text-xs text-gray-400"> : {layout.placement_count}</div>
</button>
<div className="flex gap-1">
<Button
variant="outline"
size="sm"
@ -159,6 +192,18 @@ export default function YardManagement3DWidget({
>
</Button>
<Button
variant="outline"
size="sm"
className="text-red-600 hover:bg-red-50"
onClick={(e) => {
e.stopPropagation();
setDeleteLayoutId(layout.id);
}}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</div>
))}
@ -172,18 +217,53 @@ export default function YardManagement3DWidget({
onClose={() => setIsCreateModalOpen(false)}
onCreate={handleCreateLayout}
/>
{/* 삭제 확인 모달 */}
<Dialog
open={deleteLayoutId !== null}
onOpenChange={(open) => {
if (!open) setDeleteLayoutId(null);
}}
>
<DialogContent onPointerDown={(e) => e.stopPropagation()} className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle> </DialogTitle>
</DialogHeader>
<div className="space-y-4">
<p className="text-sm text-gray-600">
?
<br />
.
<br />
<span className="font-semibold text-red-600"> .</span>
</p>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setDeleteLayoutId(null)}>
</Button>
<Button onClick={handleDeleteLayout} className="bg-red-600 hover:bg-red-700">
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
);
}
// 뷰 모드: 선택된 레이아웃의 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

@ -7,11 +7,10 @@ import * as THREE from "three";
interface YardPlacement {
id: number;
external_material_id: string;
material_code: string;
material_name: string;
quantity: number;
unit: string;
material_code?: string | null;
material_name?: string | null;
quantity?: number | null;
unit?: string | null;
position_x: number;
position_y: number;
position_z: number;
@ -19,6 +18,9 @@ interface YardPlacement {
size_y: number;
size_z: number;
color: string;
data_source_type?: string | null;
data_source_config?: any;
data_binding?: any;
}
interface Yard3DCanvasProps {
@ -159,6 +161,9 @@ function MaterialBox({
}
};
// 요소가 설정되었는지 확인
const isConfigured = !!(placement.material_name && placement.quantity && placement.unit);
return (
<Box
ref={meshRef}
@ -168,7 +173,6 @@ function MaterialBox({
e.stopPropagation();
e.nativeEvent?.stopPropagation();
e.nativeEvent?.stopImmediatePropagation();
console.log("3D Box clicked:", placement.material_name);
onClick();
}}
onPointerDown={handlePointerDown}
@ -188,10 +192,11 @@ function MaterialBox({
>
<meshStandardMaterial
color={placement.color}
opacity={isSelected ? 1 : 0.8}
opacity={isConfigured ? (isSelected ? 1 : 0.8) : 0.5}
transparent
emissive={isSelected ? "#ffffff" : "#000000"}
emissiveIntensity={isSelected ? 0.2 : 0}
wireframe={!isConfigured}
/>
</Box>
);

View File

@ -8,11 +8,10 @@ import { Loader2 } from "lucide-react";
interface YardPlacement {
id: number;
yard_layout_id: number;
external_material_id: string;
material_code: string;
material_name: string;
quantity: number;
unit: string;
material_code?: string | null;
material_name?: string | null;
quantity?: number | null;
unit?: string | null;
position_x: number;
position_y: number;
position_z: number;
@ -20,6 +19,9 @@ interface YardPlacement {
size_y: number;
size_z: number;
color: string;
data_source_type?: string | null;
data_source_config?: any;
data_binding?: any;
status?: string;
memo?: string;
}
@ -130,7 +132,9 @@ export default function Yard3DViewer({ layoutId }: Yard3DViewerProps) {
{selectedPlacement && (
<div className="absolute top-4 right-4 z-50 w-64 rounded-lg border border-gray-300 bg-white p-4 shadow-xl">
<div className="mb-3 flex items-center justify-between">
<h3 className="text-sm font-semibold text-gray-800"> </h3>
<h3 className="text-sm font-semibold text-gray-800">
{selectedPlacement.material_name ? "자재 정보" : "미설정 요소"}
</h3>
<button
onClick={() => {
setSelectedPlacement(null);
@ -141,6 +145,7 @@ export default function Yard3DViewer({ layoutId }: Yard3DViewerProps) {
</button>
</div>
{selectedPlacement.material_name && selectedPlacement.quantity && selectedPlacement.unit ? (
<div className="space-y-2">
<div>
<label className="text-xs font-medium text-gray-500"></label>
@ -154,6 +159,14 @@ export default function Yard3DViewer({ layoutId }: Yard3DViewerProps) {
</div>
</div>
</div>
) : (
<div className="rounded-lg bg-orange-50 p-3 text-center">
<div className="mb-2 text-2xl"></div>
<div className="text-sm font-medium text-orange-700"> </div>
<div className="text-sm font-medium text-orange-700"> </div>
<div className="mt-2 text-xs text-orange-600"> </div>
</div>
)}
</div>
)}
</div>

View File

@ -2,11 +2,15 @@
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Save, Loader2, X } from "lucide-react";
import { yardLayoutApi, materialApi } from "@/lib/api/yardLayoutApi";
import { 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, 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";
import dynamic from "next/dynamic";
const Yard3DCanvas = dynamic(() => import("./Yard3DCanvas"), {
ssr: false,
@ -17,41 +21,11 @@ const Yard3DCanvas = dynamic(() => import("./Yard3DCanvas"), {
),
});
interface TempMaterial {
id: number;
material_code: string;
material_name: string;
category: string;
unit: string;
default_color: string;
description: string;
}
interface YardLayout {
id: number;
name: string;
description: string;
placement_count?: number;
updated_at: string;
}
interface YardPlacement {
id: number;
yard_layout_id: number;
external_material_id: string;
material_code: string;
material_name: string;
quantity: number;
unit: string;
position_x: number;
position_y: number;
position_z: number;
size_x: number;
size_y: number;
size_z: number;
color: string;
memo?: string;
}
// 나중에 구현할 데이터 바인딩 패널
const YardElementConfigPanel = dynamic(() => import("./YardElementConfigPanel"), {
ssr: false,
loading: () => <div> ...</div>,
});
interface YardEditorProps {
layout: YardLayout;
@ -60,94 +34,112 @@ interface YardEditorProps {
export default function YardEditor({ layout, onBack }: YardEditorProps) {
const [placements, setPlacements] = useState<YardPlacement[]>([]);
const [materials, setMaterials] = useState<TempMaterial[]>([]);
const [originalPlacements, setOriginalPlacements] = useState<YardPlacement[]>([]); // 원본 데이터 보관
const [selectedPlacement, setSelectedPlacement] = useState<YardPlacement | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const [editValues, setEditValues] = useState({
size_x: 5,
size_y: 5,
size_z: 5,
color: "#3b82f6",
});
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(() => {
const loadData = async () => {
const loadPlacements = async () => {
try {
setIsLoading(true);
const [placementsRes, materialsRes] = await Promise.all([
yardLayoutApi.getPlacementsByLayoutId(layout.id),
materialApi.getTempMaterials({ limit: 100 }),
]);
if (placementsRes.success) {
setPlacements(placementsRes.data as YardPlacement[]);
}
if (materialsRes.success) {
setMaterials(materialsRes.data as TempMaterial[]);
const response = await yardLayoutApi.getPlacementsByLayoutId(layout.id);
if (response.success) {
const loadedData = response.data as YardPlacement[];
setPlacements(loadedData);
setOriginalPlacements(JSON.parse(JSON.stringify(loadedData))); // 깊은 복사
}
} catch (error) {
console.error("데이터 로드 실패:", error);
console.error("배치 목록 로드 실패:", error);
setError("배치 목록을 불러올 수 없습니다.");
} finally {
setIsLoading(false);
}
};
loadData();
loadPlacements();
}, [layout.id]);
// selectedPlacement 변경 시 editValues 업데이트
useEffect(() => {
if (selectedPlacement) {
setEditValues({
size_x: selectedPlacement.size_x,
size_y: selectedPlacement.size_y,
size_z: selectedPlacement.size_z,
color: selectedPlacement.color,
});
}
}, [selectedPlacement]);
// 자재 클릭 → 배치 추가
const handleMaterialClick = async (material: TempMaterial) => {
// 이미 배치되었는지 확인
const alreadyPlaced = placements.find((p) => p.material_code === material.material_code);
if (alreadyPlaced) {
alert("이미 배치된 자재입니다.");
return;
}
// 기본 위치에 배치
const placementData = {
external_material_id: `TEMP-${material.id}`,
material_code: material.material_code,
material_name: material.material_name,
quantity: 1,
unit: material.unit,
// 빈 요소 추가 (로컬 상태에만 추가, 저장 시 서버에 반영)
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: 0,
position_y: 2.5,
position_z: 0,
size_x: 5,
size_y: 5,
size_z: 5,
color: material.default_color,
color: "#9ca3af",
data_source_type: null,
data_source_config: null,
data_binding: null,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
try {
const response = await yardLayoutApi.addMaterialPlacement(layout.id, placementData);
if (response.success) {
setPlacements((prev) => [...prev, response.data as YardPlacement]);
setSelectedPlacement(response.data as YardPlacement);
}
} catch (error) {
console.error("자재 배치 실패:", error);
alert("자재 배치에 실패했습니다.");
}
setPlacements((prev) => [...prev, newPlacement]);
setSelectedPlacement(newPlacement);
setShowConfigPanel(true);
setHasUnsavedChanges(true);
setNextPlacementId((prev) => prev - 1); // 다음 임시 ID
};
// 자재 드래그 (3D 캔버스에서)
// 요소 선택 (3D 캔버스 또는 목록에서)
const handleSelectPlacement = (placement: YardPlacement) => {
setSelectedPlacement(placement);
setShowConfigPanel(false); // 선택 시에는 설정 패널 닫기
};
// 설정 버튼 클릭
const handleConfigClick = (placement: YardPlacement) => {
setSelectedPlacement(placement);
setShowConfigPanel(true);
};
// 요소 삭제 확인 Dialog 열기
const handleDeletePlacement = (placementId: number) => {
setDeleteConfirmDialog({ open: true, placementId });
};
// 요소 삭제 확정 (로컬 상태에서만 삭제, 저장 시 서버에 반영)
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,
@ -155,85 +147,157 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
position_z: Math.round(position.z * 2) / 2,
};
setPlacements((prev) =>
prev.map((p) =>
p.id === id
? {
...p,
...updatedPosition,
}
: p,
),
);
setPlacements((prev) => prev.map((p) => (p.id === id ? { ...p, ...updatedPosition } : p)));
// 선택된 자재도 업데이트
if (selectedPlacement?.id === id) {
setSelectedPlacement((prev) =>
prev
? {
...prev,
...updatedPosition,
}
: null,
);
setSelectedPlacement((prev) => (prev ? { ...prev, ...updatedPosition } : null));
}
setHasUnsavedChanges(true);
};
// 자재 배치 해제
const handlePlacementRemove = async (id: number): Promise<void> => {
try {
const response = await yardLayoutApi.removePlacement(id);
if (response.success) {
setPlacements((prev) => prev.filter((p) => p.id !== id));
setSelectedPlacement(null);
}
} catch (error) {
console.error("배치 해제 실패:", error);
alert("배치 해제에 실패했습니다.");
}
};
// 위치/크기/색상 업데이트
const handlePlacementUpdate = (id: number, updates: Partial<YardPlacement>) => {
setPlacements((prev) => prev.map((p) => (p.id === id ? { ...p, ...updates } : p)));
};
// 저장
// 전체 저장 (신규/수정/삭제 모두 처리)
const handleSave = async () => {
setIsSaving(true);
try {
const response = await yardLayoutApi.batchUpdatePlacements(
layout.id,
placements.map((p) => ({
id: p.id,
position_x: p.position_x,
position_y: p.position_y,
position_z: p.position_z,
size_x: p.size_x,
size_y: p.size_y,
size_z: p.size_z,
color: p.color,
})),
);
// 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) {
alert("저장되었습니다");
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) {
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 filteredMaterials = materials.filter(
(m) =>
m.material_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
m.material_code.toLowerCase().includes(searchTerm.toLowerCase()),
// 설정 패널에서 데이터 업데이트 (로컬 상태에만 반영, 서버 저장 안함)
const handleSaveConfig = (updatedData: Partial<YardPlacement>) => {
if (!selectedPlacement) return;
// 로컬 상태만 업데이트
setPlacements((prev) =>
prev.map((p) => {
if (p.id === selectedPlacement.id) {
return { ...p, ...updatedData };
}
return p;
}),
);
// 선택된 요소도 업데이트
setSelectedPlacement((prev) => (prev ? { ...prev, ...updatedData } : null));
setShowConfigPanel(false);
setHasUnsavedChanges(true);
};
// 요소가 설정되었는지 확인
const isConfigured = (placement: YardPlacement): boolean => {
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">
{/* 상단 툴바 */}
@ -243,13 +307,20 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
<ArrowLeft className="mr-2 h-4 w-4" />
</Button>
<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}>
<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" />
@ -263,6 +334,15 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
)}
</Button>
</div>
</div>
{/* 에러 메시지 */}
{error && (
<Alert variant="destructive" className="m-4">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 메인 컨텐츠 영역 */}
<div className="flex flex-1 overflow-hidden">
@ -276,152 +356,104 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
<Yard3DCanvas
placements={placements}
selectedPlacementId={selectedPlacement?.id || null}
onPlacementClick={(placement) => setSelectedPlacement(placement as YardPlacement)}
onPlacementClick={(placement) => handleSelectPlacement(placement as YardPlacement)}
onPlacementDrag={handlePlacementDrag}
/>
)}
</div>
{/* 우측: 자재 목록 또는 편집 패널 */}
{/* 우측: 요소 목록 또는 설정 패널 */}
<div className="w-80 border-l bg-white">
{selectedPlacement ? (
// 선택된 자재 편집 패널
<div className="flex h-full flex-col">
<div className="flex items-center justify-between border-b p-4">
<h3 className="text-sm font-semibold"> </h3>
<Button variant="ghost" size="sm" onClick={() => setSelectedPlacement(null)}>
<X className="h-4 w-4" />
</Button>
</div>
<div className="flex-1 overflow-auto p-4">
<div className="space-y-4">
{/* 읽기 전용 정보 */}
<div>
<Label className="text-xs text-gray-500"> </Label>
<div className="mt-1 text-sm font-medium">{selectedPlacement.material_code}</div>
</div>
<div>
<Label className="text-xs text-gray-500"></Label>
<div className="mt-1 text-sm font-medium">{selectedPlacement.material_name}</div>
</div>
<div>
<Label className="text-xs text-gray-500"> ( )</Label>
<div className="mt-1 text-sm">
{selectedPlacement.quantity} {selectedPlacement.unit}
</div>
</div>
{/* 편집 가능 정보 */}
<div className="space-y-3 border-t pt-4">
<Label className="text-sm font-semibold"> </Label>
<div className="grid grid-cols-3 gap-2">
<div>
<Label className="text-xs"></Label>
<Input
type="number"
step="1"
value={editValues.size_x}
onChange={(e) => {
const newValue = parseFloat(e.target.value) || 1;
setEditValues((prev) => ({ ...prev, size_x: newValue }));
handlePlacementUpdate(selectedPlacement.id, { size_x: newValue });
}}
{showConfigPanel && selectedPlacement ? (
// 설정 패널
<YardElementConfigPanel
placement={selectedPlacement}
onSave={handleSaveConfig}
onCancel={() => setShowConfigPanel(false)}
/>
</div>
<div>
<Label className="text-xs"></Label>
<Input
type="number"
step="1"
value={editValues.size_y}
onChange={(e) => {
const newValue = parseFloat(e.target.value) || 1;
setEditValues((prev) => ({ ...prev, size_y: newValue }));
handlePlacementUpdate(selectedPlacement.id, { size_y: newValue });
}}
/>
</div>
<div>
<Label className="text-xs"></Label>
<Input
type="number"
step="1"
value={editValues.size_z}
onChange={(e) => {
const newValue = parseFloat(e.target.value) || 1;
setEditValues((prev) => ({ ...prev, size_z: newValue }));
handlePlacementUpdate(selectedPlacement.id, { size_z: newValue });
}}
/>
</div>
</div>
<div>
<Label className="text-xs"></Label>
<Input
type="color"
value={editValues.color}
onChange={(e) => {
setEditValues((prev) => ({ ...prev, color: e.target.value }));
handlePlacementUpdate(selectedPlacement.id, { color: e.target.value });
}}
/>
</div>
</div>
<Button
variant="destructive"
size="sm"
className="w-full"
onClick={() => handlePlacementRemove(selectedPlacement.id)}
>
</Button>
</div>
</div>
</div>
) : (
// 자재 목록
// 요소 목록
<div className="flex h-full flex-col">
<div className="border-b p-4">
<h3 className="mb-2 text-sm font-semibold"> </h3>
<Input
placeholder="자재 검색..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="text-sm"
/>
<div className="mb-3 flex items-center justify-between">
<h3 className="text-sm font-semibold"> </h3>
<Button size="sm" onClick={handleAddElement}>
<Plus className="mr-1 h-4 w-4" />
</Button>
</div>
<p className="text-xs text-gray-500"> {placements.length}</p>
</div>
<div className="flex-1 overflow-auto">
{filteredMaterials.length === 0 ? (
<div className="flex-1 overflow-auto p-2">
{placements.length === 0 ? (
<div className="flex h-full items-center justify-center p-4 text-center text-sm text-gray-500">
.
<br />
{'위의 "요소 추가" 버튼을 클릭하세요.'}
</div>
) : (
<div className="p-2">
{filteredMaterials.map((material) => {
const isPlaced = placements.some((p) => p.material_code === material.material_code);
<div className="space-y-2">
{placements.map((placement) => {
const configured = isConfigured(placement);
const isSelected = selectedPlacement?.id === placement.id;
return (
<button
key={material.id}
onClick={() => !isPlaced && handleMaterialClick(material)}
disabled={isPlaced}
className={`mb-2 w-full rounded-lg border p-3 text-left transition-all ${
isPlaced
? "cursor-not-allowed border-gray-200 bg-gray-50 opacity-50"
: "cursor-pointer border-gray-200 bg-white hover:border-blue-500 hover:shadow-sm"
<div
key={placement.id}
className={`rounded-lg border p-3 transition-all ${
isSelected
? "border-blue-500 bg-blue-50"
: configured
? "border-gray-200 bg-white hover:border-gray-300"
: "border-orange-200 bg-orange-50"
}`}
onClick={() => handleSelectPlacement(placement)}
>
<div className="mb-1 text-sm font-medium text-gray-900">{material.material_name}</div>
<div className="text-xs text-gray-500">{material.material_code}</div>
<div className="mt-1 text-xs text-gray-400">{material.category}</div>
{isPlaced && <div className="mt-1 text-xs text-blue-600"></div>}
</button>
<div className="flex items-start justify-between">
<div className="flex-1">
{configured ? (
<>
<div className="text-sm font-medium text-gray-900">{placement.material_name}</div>
<div className="mt-1 text-xs text-gray-500">
: {placement.quantity} {placement.unit}
</div>
</>
) : (
<>
<div className="text-sm font-medium text-orange-700"> #{placement.id}</div>
<div className="mt-1 text-xs text-orange-600"> </div>
</>
)}
</div>
</div>
<div className="mt-2 flex gap-1">
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={(e) => {
e.stopPropagation();
handleConfigClick(placement);
}}
>
<Settings className="mr-1 h-3 w-3" />
{configured ? "편집" : "설정"}
</Button>
<Button
variant="outline"
size="sm"
className="text-red-600 hover:bg-red-50"
onClick={(e) => {
e.stopPropagation();
handleDeletePlacement(placement.id);
}}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
);
})}
</div>
@ -431,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

@ -0,0 +1,537 @@
"use client";
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ArrowLeft, Loader2, Play } from "lucide-react";
import { YardPlacement, YardDataSourceConfig, YardDataBinding, QueryResult } from "./types";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { AlertCircle } from "lucide-react";
import { dashboardApi } from "@/lib/api/dashboard";
import { ExternalDbConnectionAPI, type ExternalDbConnection } from "@/lib/api/externalDbConnection";
import { Textarea } from "@/components/ui/textarea";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
interface YardElementConfigPanelProps {
placement: YardPlacement;
onSave: (updatedData: Partial<YardPlacement>) => void; // Promise 제거 (즉시 로컬 상태 업데이트)
onCancel: () => void;
}
export default function YardElementConfigPanel({ placement, onSave, onCancel }: YardElementConfigPanelProps) {
// 데이터 소스 설정
const [dataSourceType, setDataSourceType] = useState<"database" | "external_db" | "rest_api">(
(placement.data_source_config?.type as "database" | "external_db" | "rest_api") || "database",
);
const [query, setQuery] = useState(placement.data_source_config?.query || "");
const [externalConnectionId, setExternalConnectionId] = useState<string>(
placement.data_source_config?.connectionId?.toString() || "",
);
const [externalConnections, setExternalConnections] = useState<ExternalDbConnection[]>([]);
// REST API 설정
const [apiUrl, setApiUrl] = useState(placement.data_source_config?.url || "");
const [apiMethod, setApiMethod] = useState<"GET" | "POST">(placement.data_source_config?.method || "GET");
const [apiDataPath, setApiDataPath] = useState(placement.data_source_config?.dataPath || "");
// 쿼리 결과 및 매핑
const [queryResult, setQueryResult] = useState<QueryResult | null>(null);
const [isExecuting, setIsExecuting] = useState(false);
const [selectedRowIndex, setSelectedRowIndex] = useState<number>(placement.data_binding?.selectedRowIndex ?? 0);
const [materialNameField, setMaterialNameField] = useState(placement.data_binding?.materialNameField || "");
const [quantityField, setQuantityField] = useState(placement.data_binding?.quantityField || "");
const [unit, setUnit] = useState(placement.data_binding?.unit || "EA");
// 배치 설정
const [color, setColor] = useState(placement.color || "#3b82f6");
const [sizeX, setSizeX] = useState(placement.size_x);
const [sizeY, setSizeY] = useState(placement.size_y);
const [sizeZ, setSizeZ] = useState(placement.size_z);
// 에러
const [error, setError] = useState<string | null>(null);
// 외부 DB 커넥션 목록 로드
useEffect(() => {
const loadConnections = async () => {
try {
const connections = await ExternalDbConnectionAPI.getConnections();
setExternalConnections(connections || []);
} catch (err) {
console.error("외부 DB 커넥션 로드 실패:", err);
}
};
if (dataSourceType === "external_db") {
loadConnections();
}
}, [dataSourceType]);
// 쿼리 실행
const executeQuery = async () => {
if (!query.trim()) {
setError("쿼리를 입력해주세요.");
return;
}
if (dataSourceType === "external_db" && !externalConnectionId) {
setError("외부 DB 커넥션을 선택해주세요.");
return;
}
setIsExecuting(true);
setError(null);
try {
let apiResult: { columns: string[]; rows: Record<string, unknown>[]; rowCount: number };
if (dataSourceType === "external_db" && externalConnectionId) {
const result = await ExternalDbConnectionAPI.executeQuery(parseInt(externalConnectionId), query.trim());
if (!result.success) {
throw new Error(result.message || "외부 DB 쿼리 실행에 실패했습니다.");
}
apiResult = {
columns: result.data?.[0] ? Object.keys(result.data[0]) : [],
rows: result.data || [],
rowCount: result.data?.length || 0,
};
} else {
apiResult = await dashboardApi.executeQuery(query.trim());
}
setQueryResult({
columns: apiResult.columns,
rows: apiResult.rows,
totalRows: apiResult.rowCount,
});
// 자동으로 첫 번째 필드 선택
if (apiResult.columns.length > 0) {
if (!materialNameField) setMaterialNameField(apiResult.columns[0]);
if (!quantityField && apiResult.columns.length > 1) setQuantityField(apiResult.columns[1]);
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : "쿼리 실행 중 오류가 발생했습니다.";
setError(errorMessage);
} finally {
setIsExecuting(false);
}
};
// REST API 호출
const executeRestApi = async () => {
if (!apiUrl.trim()) {
setError("API URL을 입력해주세요.");
return;
}
setIsExecuting(true);
setError(null);
try {
const response = await fetch(apiUrl, {
method: apiMethod,
});
if (!response.ok) {
throw new Error(`API 호출 실패: ${response.status}`);
}
let data = await response.json();
// dataPath가 있으면 해당 경로의 데이터 추출
if (apiDataPath) {
const pathParts = apiDataPath.split(".");
for (const part of pathParts) {
data = data[part];
}
}
// 배열이 아니면 배열로 변환
if (!Array.isArray(data)) {
data = [data];
}
const columns = data.length > 0 ? Object.keys(data[0]) : [];
setQueryResult({
columns,
rows: data,
totalRows: data.length,
});
// 자동으로 첫 번째 필드 선택
if (columns.length > 0) {
if (!materialNameField) setMaterialNameField(columns[0]);
if (!quantityField && columns.length > 1) setQuantityField(columns[1]);
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : "API 호출 중 오류가 발생했습니다.";
setError(errorMessage);
} finally {
setIsExecuting(false);
}
};
// 적용 (로컬 상태만 업데이트, 서버 저장은 나중에 일괄 처리)
const handleApply = () => {
// 검증
if (!queryResult) {
setError("먼저 데이터를 조회해주세요.");
return;
}
if (!materialNameField || !quantityField) {
setError("자재명과 수량 필드를 선택해주세요.");
return;
}
if (!unit.trim()) {
setError("단위를 입력해주세요.");
return;
}
if (selectedRowIndex >= queryResult.rows.length) {
setError("선택한 행이 유효하지 않습니다.");
return;
}
const selectedRow = queryResult.rows[selectedRowIndex];
const materialName = selectedRow[materialNameField];
const quantity = selectedRow[quantityField];
const dataSourceConfig: YardDataSourceConfig = {
type: dataSourceType,
query: dataSourceType !== "rest_api" ? query : undefined,
connectionId: dataSourceType === "external_db" ? parseInt(externalConnectionId) : undefined,
url: dataSourceType === "rest_api" ? apiUrl : undefined,
method: dataSourceType === "rest_api" ? apiMethod : undefined,
dataPath: dataSourceType === "rest_api" && apiDataPath ? apiDataPath : undefined,
};
const dataBinding: YardDataBinding = {
selectedRowIndex,
materialNameField,
quantityField,
unit: unit.trim(),
};
const updatedData: Partial<YardPlacement> = {
material_name: String(materialName),
quantity: Number(quantity),
unit: unit.trim(),
color,
size_x: sizeX,
size_y: sizeY,
size_z: sizeZ,
data_source_type: dataSourceType,
data_source_config: dataSourceConfig,
data_binding: dataBinding,
};
onSave(updatedData); // 동기적으로 즉시 로컬 상태 업데이트
};
return (
<div className="flex h-full flex-col">
{/* 헤더 */}
<div className="flex items-center justify-between border-b p-4">
<h3 className="text-sm font-semibold"> </h3>
<Button variant="ghost" size="sm" onClick={onCancel}>
<ArrowLeft className="mr-2 h-4 w-4" />
</Button>
</div>
{/* 에러 메시지 */}
{error && (
<Alert variant="destructive" className="m-4">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 컨텐츠 */}
<div className="flex-1 overflow-auto p-4">
<div className="space-y-6">
{/* 1단계: 데이터 소스 선택 */}
<Card className="p-4">
<h4 className="mb-3 text-sm font-semibold">1단계: 데이터 </h4>
<RadioGroup
value={dataSourceType}
onValueChange={(value) => setDataSourceType(value as "database" | "external_db" | "rest_api")}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="database" id="db" />
<Label htmlFor="db"> DB</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="external_db" id="external" />
<Label htmlFor="external"> DB</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="rest_api" id="api" />
<Label htmlFor="api">REST API</Label>
</div>
</RadioGroup>
<div className="mt-4 space-y-3">
{/* 현재 DB 또는 외부 DB */}
{dataSourceType !== "rest_api" && (
<>
{dataSourceType === "external_db" && (
<div>
<Label className="text-xs"> DB </Label>
<Select value={externalConnectionId} onValueChange={setExternalConnectionId}>
<SelectTrigger className="mt-1">
<SelectValue placeholder="커넥션 선택" />
</SelectTrigger>
<SelectContent className="z-[9999]">
{externalConnections.map((conn) => (
<SelectItem key={conn.id} value={String(conn.id)}>
<div className="flex items-center gap-2">
<span className="font-medium">{conn.connection_name}</span>
<span className="text-xs text-gray-500">({conn.db_type.toUpperCase()})</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
<div>
<Label className="text-xs">SQL </Label>
<Textarea
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="SELECT material_name, quantity FROM inventory"
className="mt-1 h-24 resize-none font-mono text-xs"
/>
</div>
<Button onClick={executeQuery} disabled={isExecuting} size="sm" className="w-full">
{isExecuting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : (
<>
<Play className="mr-2 h-4 w-4" />
</>
)}
</Button>
</>
)}
{/* REST API */}
{dataSourceType === "rest_api" && (
<>
<div>
<Label className="text-xs">API URL</Label>
<Input
value={apiUrl}
onChange={(e) => setApiUrl(e.target.value)}
placeholder="https://api.example.com/materials"
className="mt-1"
/>
</div>
<div>
<Label className="text-xs">Method</Label>
<Select value={apiMethod} onValueChange={(value) => setApiMethod(value as "GET" | "POST")}>
<SelectTrigger className="mt-1">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="GET">GET</SelectItem>
<SelectItem value="POST">POST</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs"> ()</Label>
<Input
value={apiDataPath}
onChange={(e) => setApiDataPath(e.target.value)}
placeholder="data.items"
className="mt-1"
/>
<p className="mt-1 text-xs text-gray-500">: data.items ( )</p>
</div>
<Button onClick={executeRestApi} disabled={isExecuting} size="sm" className="w-full">
{isExecuting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : (
<>
<Play className="mr-2 h-4 w-4" />
</>
)}
</Button>
</>
)}
</div>
</Card>
{/* 2단계: 쿼리 결과 및 필드 매핑 */}
{queryResult && (
<Card className="p-4">
<h4 className="mb-3 text-sm font-semibold">2단계: 데이터 </h4>
<div className="mb-3">
<Label className="text-xs"> ({queryResult.totalRows})</Label>
<div className="mt-2 max-h-40 overflow-auto rounded border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-12"></TableHead>
{queryResult.columns.map((col, idx) => (
<TableHead key={idx}>{col}</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{queryResult.rows.slice(0, 10).map((row, idx) => (
<TableRow
key={idx}
className={selectedRowIndex === idx ? "bg-blue-50" : ""}
onClick={() => setSelectedRowIndex(idx)}
>
<TableCell>
<input
type="radio"
checked={selectedRowIndex === idx}
onChange={() => setSelectedRowIndex(idx)}
/>
</TableCell>
{queryResult.columns.map((col, colIdx) => (
<TableCell key={colIdx}>{String(row[col] ?? "")}</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
{queryResult.rows.length > 10 && (
<p className="mt-2 text-xs text-gray-500">... {queryResult.rows.length - 10} </p>
)}
</div>
<div className="space-y-3">
<div>
<Label className="text-xs"> </Label>
<Select value={materialNameField} onValueChange={setMaterialNameField}>
<SelectTrigger className="mt-1">
<SelectValue placeholder="필드 선택" />
</SelectTrigger>
<SelectContent>
{queryResult.columns.map((col) => (
<SelectItem key={col} value={col}>
{col}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs"> </Label>
<Select value={quantityField} onValueChange={setQuantityField}>
<SelectTrigger className="mt-1">
<SelectValue placeholder="필드 선택" />
</SelectTrigger>
<SelectContent>
{queryResult.columns.map((col) => (
<SelectItem key={col} value={col}>
{col}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs"> </Label>
<Input value={unit} onChange={(e) => setUnit(e.target.value)} placeholder="EA" className="mt-1" />
<p className="mt-1 text-xs text-gray-500">: EA, BOX, KG, M, L </p>
</div>
</div>
</Card>
)}
{/* 3단계: 배치 설정 */}
<Card className="p-4">
<h4 className="mb-3 text-sm font-semibold">3단계: 배치 </h4>
<div className="space-y-3">
<div>
<Label className="text-xs"></Label>
<Input type="color" value={color} onChange={(e) => setColor(e.target.value)} className="mt-1" />
</div>
<div>
<Label className="text-xs"></Label>
<div className="mt-1 grid grid-cols-3 gap-2">
<div>
<Label className="text-xs"></Label>
<Input
type="number"
step="1"
value={sizeX}
onChange={(e) => setSizeX(parseFloat(e.target.value) || 1)}
/>
</div>
<div>
<Label className="text-xs"></Label>
<Input
type="number"
step="1"
value={sizeY}
onChange={(e) => setSizeY(parseFloat(e.target.value) || 1)}
/>
</div>
<div>
<Label className="text-xs"></Label>
<Input
type="number"
step="1"
value={sizeZ}
onChange={(e) => setSizeZ(parseFloat(e.target.value) || 1)}
/>
</div>
</div>
</div>
</div>
</Card>
</div>
</div>
{/* 하단 버튼 */}
<div className="border-t p-4">
<div className="flex gap-2">
<Button variant="outline" onClick={onCancel} className="flex-1">
</Button>
<Button onClick={handleApply} disabled={!queryResult} className="flex-1">
</Button>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,86 @@
// 야드 관리 3D - 타입 정의
import { ChartDataSource } from "../../types";
// 야드 레이아웃
export interface YardLayout {
id: number;
name: string;
description?: string;
placement_count?: number;
created_by?: string;
created_at: string;
updated_at: string;
}
// 데이터 소스 설정
export interface YardDataSourceConfig {
type: "database" | "external_db" | "rest_api";
// type === 'database' (현재 DB)
query?: string;
// type === 'external_db' (외부 DB)
connectionId?: number;
// type === 'rest_api'
url?: string;
method?: "GET" | "POST";
headers?: Record<string, string>;
queryParams?: Record<string, string>;
body?: string;
dataPath?: string; // 응답에서 데이터 배열 경로
}
// 데이터 바인딩 설정
export interface YardDataBinding {
// 데이터 소스의 특정 행 선택
selectedRowIndex?: number;
// 필드 매핑 (데이터 소스에서 선택)
materialNameField?: string; // 자재명이 들어있는 컬럼명
quantityField?: string; // 수량이 들어있는 컬럼명
// 단위는 사용자가 직접 입력
unit: string; // 예: "EA", "BOX", "KG", "M" 등
}
// 자재 배치 정보
export interface YardPlacement {
id: number;
yard_layout_id: number;
material_code?: string | null;
material_name?: string | null;
quantity?: number | null;
unit?: string | null;
position_x: number;
position_y: number;
position_z: number;
size_x: number;
size_y: number;
size_z: number;
color: string;
data_source_type?: string | null;
data_source_config?: YardDataSourceConfig | null;
data_binding?: YardDataBinding | null;
memo?: string | null;
created_at?: string;
updated_at?: string;
}
// 쿼리 결과 (데이터 바인딩용)
export interface QueryResult {
columns: string[];
rows: Record<string, any>[];
totalRows: number;
}
// 요소 설정 단계
export type ConfigStep = "data-source" | "field-mapping" | "placement-settings";
// 설정 모달 props
export interface YardElementConfigPanelProps {
placement: YardPlacement;
onSave: (updatedPlacement: Partial<YardPlacement>) => Promise<void>;
onCancel: () => void;
}

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,22 @@ 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":
return <CustomStatsWidget element={element} />;
// === 차량 관련 (추가 위젯) ===
case "vehicle-status":
return <VehicleStatusWidget element={element} />;
@ -256,11 +278,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,505 @@
/**
*
* -
* - , ,
* - , , ,
*/
"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) {
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[]>([]); // 선택된 통계 라벨
// localStorage 키 생성 (위젯별로 고유하게)
const storageKey = `custom-stats-widget-${element?.id || "default"}`;
// 초기 로드 시 저장된 설정 불러오기
React.useEffect(() => {
const saved = localStorage.getItem(storageKey);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedStats(parsed);
} catch (e) {
console.error("설정 로드 실패:", e);
}
}
}, [storageKey]);
// 데이터 로드
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([]);
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 columnConfig: {
[key: string]: {
keywords: string[];
unit: string;
color: string;
icon: string;
useAvg?: boolean;
koreanLabel?: string; // 한글 라벨
};
} = {
// 무게/중량
weight: {
keywords: ["weight", "cargo_weight", "total_weight", "tonnage"],
unit: "톤",
color: "green",
icon: "⚖️",
koreanLabel: "총 운송량"
},
// 거리
distance: {
keywords: ["distance", "total_distance"],
unit: "km",
color: "blue",
icon: "🛣️",
koreanLabel: "누적 거리"
},
// 시간/기간
time: {
keywords: ["time", "duration", "delivery_time", "delivery_duration"],
unit: "분",
color: "orange",
icon: "⏱️",
useAvg: true,
koreanLabel: "평균 배송시간"
},
// 수량/개수
quantity: {
keywords: ["quantity", "qty", "amount"],
unit: "개",
color: "purple",
icon: "📦",
koreanLabel: "총 수량"
},
// 금액/가격
price: {
keywords: ["price", "cost", "fee"],
unit: "원",
color: "yellow",
icon: "💰",
koreanLabel: "총 금액"
},
// 비율/퍼센트
rate: {
keywords: ["rate", "ratio", "percent", "efficiency"],
unit: "%",
color: "cyan",
icon: "📈",
useAvg: true,
koreanLabel: "평균 비율"
},
// 처리량
throughput: {
keywords: ["throughput", "output", "production"],
unit: "개",
color: "pink",
icon: "⚡",
koreanLabel: "총 처리량"
},
// 재고
stock: {
keywords: ["stock", "inventory"],
unit: "개",
color: "teal",
icon: "📦",
koreanLabel: "재고 수량"
},
// 설비/장비
equipment: {
keywords: ["equipment", "facility", "machine"],
unit: "대",
color: "gray",
icon: "🏭",
koreanLabel: "가동 설비"
},
};
// 4. 각 숫자 컬럼을 통계 카드로 변환
Object.entries(numericColumns).forEach(([key, stats]) => {
let label = key;
let unit = "";
let color = "gray";
let icon = "📊";
let useAvg = false;
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;
useAvg = config.useAvg || false;
matchedConfig = config;
// 한글 라벨 사용 또는 자동 변환
label = config.koreanLabel || key
.replace(/_/g, " ")
.replace(/([A-Z])/g, " $1")
.trim();
break;
}
}
// 매칭되지 않은 경우 기본 라벨 생성
if (!matchedConfig) {
label = key
.replace(/_/g, " ")
.replace(/([A-Z])/g, " $1")
.trim()
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
}
// 합계 또는 평균 선택
const value = useAvg ? stats.avg : 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: "승인률",
};
Object.keys(firstRow).forEach((key) => {
const lowerKey = key.toLowerCase();
const matchedKey = Object.keys(booleanMapping).find((k) => lowerKey.includes(k));
if (matchedKey) {
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: booleanMapping[matchedKey],
value: rate,
unit: "%",
color: "purple",
icon: "✅",
});
}
}
});
setAllStats(statsItems);
// 초기에는 모든 통계 표시 (최대 6개)
if (selectedStats.length === 0) {
setStats(statsItems.slice(0, 6));
setSelectedStats(statsItems.slice(0, 6).map((s) => s.label));
} else {
// 선택된 통계만 표시
const filtered = statsItems.filter((s) => selectedStats.includes(s.label));
setStats(filtered);
}
} 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]);
// 색상 매핑
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) => {
if (prev.includes(label)) {
return prev.filter((l) => l !== label);
} else {
return [...prev, label];
}
});
};
const handleApplySettings = () => {
const filtered = allStats.filter((s) => selectedStats.includes(s.label));
setStats(filtered);
setShowSettings(false);
// localStorage에 설정 저장
localStorage.setItem(storageKey, JSON.stringify(selectedStats));
};
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={() => 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.icon} {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) => (
<label
key={index}
className="flex cursor-pointer items-center gap-3 rounded-lg border p-3 hover:bg-gray-50"
>
<input
type="checkbox"
checked={selectedStats.includes(stat.label)}
onChange={() => handleToggleStat(stat.label)}
className="h-5 w-5"
/>
<span className="text-xl">{stat.icon}</span>
<div className="flex-1">
<div className="font-medium">{stat.label}</div>
<div className="text-sm text-gray-500">: {stat.unit}</div>
</div>
</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={() => setShowSettings(false)}
className="rounded-lg border px-4 py-2 hover:bg-gray-50"
>
</button>
</div>
</div>
</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,6 +329,8 @@ 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">
<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">
@ -333,20 +339,21 @@ export default function TodoWidget({ element }: TodoWidgetProps) {
</div>
)}
</div>
{/* 헤더 (추가 버튼, 통계, 필터) - showHeader가 false일 때만 숨김 */}
{element?.showHeader !== false && (
<div className="border-b border-gray-200 bg-white px-4 py-3">
<div className="mb-3 flex items-center justify-end">
{/* 추가 버튼 - 항상 표시 */}
<button
onClick={() => setShowAddForm(!showAddForm)}
className="flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-sm text-white transition-colors hover:bg-primary/90"
title="할 일 추가"
>
<Plus className="h-4 w-4" />
</button>
</div>
</div>
{/* 헤더 (통계, 필터) - showHeader가 false일 때만 숨김 */}
{element?.showHeader !== false && (
<div className="border-b border-gray-200 bg-white px-4 py-3">
{/* 통계 */}
{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

@ -57,28 +57,3 @@ export const yardLayoutApi = {
return apiCall("PUT", `/yard-layouts/${layoutId}/placements/batch`, { placements });
},
};
// 자재 관리 API
export const materialApi = {
// 임시 자재 마스터 목록 조회
async getTempMaterials(params?: { search?: string; category?: string; page?: number; limit?: number }) {
const queryParams = new URLSearchParams();
if (params?.search) queryParams.append("search", params.search);
if (params?.category) queryParams.append("category", params.category);
if (params?.page) queryParams.append("page", params.page.toString());
if (params?.limit) queryParams.append("limit", params.limit.toString());
const queryString = queryParams.toString();
return apiCall("GET", `/materials/temp${queryString ? `?${queryString}` : ""}`);
},
// 특정 자재 상세 조회
async getTempMaterialByCode(code: string) {
return apiCall("GET", `/materials/temp/${code}`);
},
// 카테고리 목록 조회
async getCategories() {
return apiCall("GET", "/materials/temp/categories");
},
};

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',
};