사용하지 않는 파일 정리 전 백업 (Phase 10 완료 후 상태)

This commit is contained in:
JiWoong Sul
2025-08-29 15:11:59 +09:00
parent a740ff10c8
commit d916b281a7
333 changed files with 53617 additions and 22574 deletions

View File

@@ -0,0 +1,299 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../../data/models/maintenance_dto.dart';
class MaintenanceCalendar extends StatefulWidget {
final List<MaintenanceDto> maintenances;
final Function(DateTime)? onDateSelected;
const MaintenanceCalendar({
super.key,
required this.maintenances,
this.onDateSelected,
});
@override
State<MaintenanceCalendar> createState() => _MaintenanceCalendarState();
}
class _MaintenanceCalendarState extends State<MaintenanceCalendar> {
late DateTime _selectedMonth;
DateTime? _selectedDate;
@override
void initState() {
super.initState();
_selectedMonth = DateTime.now();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
_buildMonthSelector(),
Expanded(
child: _buildCalendarGrid(),
),
],
);
}
Widget _buildMonthSelector() {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withValues(alpha: 0.1),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: const Icon(Icons.chevron_left),
onPressed: () {
setState(() {
_selectedMonth = DateTime(
_selectedMonth.year,
_selectedMonth.month - 1,
);
});
},
),
Text(
DateFormat('yyyy년 MM월').format(_selectedMonth),
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
IconButton(
icon: const Icon(Icons.chevron_right),
onPressed: () {
setState(() {
_selectedMonth = DateTime(
_selectedMonth.year,
_selectedMonth.month + 1,
);
});
},
),
],
),
);
}
Widget _buildCalendarGrid() {
final firstDay = DateTime(_selectedMonth.year, _selectedMonth.month, 1);
final lastDay = DateTime(_selectedMonth.year, _selectedMonth.month + 1, 0);
final startWeekday = firstDay.weekday % 7; // 일요일 = 0
// 달력 셀 생성
final days = <Widget>[];
// 요일 헤더
const weekdays = ['', '', '', '', '', '', ''];
for (int i = 0; i < 7; i++) {
days.add(
Container(
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
weekdays[i],
style: TextStyle(
fontWeight: FontWeight.bold,
color: i == 0 ? Colors.red : (i == 6 ? Colors.blue : Colors.black),
),
),
),
);
}
// 이전 달 빈 칸
for (int i = 0; i < startWeekday; i++) {
days.add(Container());
}
// 현재 달 날짜
for (int day = 1; day <= lastDay.day; day++) {
final date = DateTime(_selectedMonth.year, _selectedMonth.month, day);
final dayMaintenances = _getMaintenancesForDate(date);
final isToday = _isToday(date);
final isSelected = _selectedDate != null && _isSameDay(date, _selectedDate!);
final isWeekend = date.weekday == DateTime.sunday || date.weekday == DateTime.saturday;
days.add(
InkWell(
onTap: () {
setState(() {
_selectedDate = date;
});
if (widget.onDateSelected != null && dayMaintenances.isNotEmpty) {
widget.onDateSelected!(date);
}
},
child: Container(
margin: const EdgeInsets.all(2),
decoration: BoxDecoration(
color: isSelected
? Theme.of(context).primaryColor.withValues(alpha: 0.2)
: isToday
? Colors.blue.withValues(alpha: 0.1)
: Colors.transparent,
border: Border.all(
color: isSelected
? Theme.of(context).primaryColor
: isToday
? Colors.blue
: Colors.transparent,
width: isSelected || isToday ? 2 : 1,
),
borderRadius: BorderRadius.circular(8),
),
child: Stack(
children: [
// 날짜 숫자
Positioned(
top: 8,
left: 8,
child: Text(
day.toString(),
style: TextStyle(
fontWeight: isToday ? FontWeight.bold : FontWeight.normal,
color: isWeekend
? (date.weekday == DateTime.sunday ? Colors.red : Colors.blue)
: Colors.black,
),
),
),
// 유지보수 표시
if (dayMaintenances.isNotEmpty)
Positioned(
bottom: 4,
left: 4,
right: 4,
child: Column(
children: dayMaintenances.take(3).map((m) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 1),
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
decoration: BoxDecoration(
color: _getMaintenanceColor(m),
borderRadius: BorderRadius.circular(4),
),
child: Text(
'#${m.equipmentHistoryId}',
style: const TextStyle(
fontSize: 10,
color: Colors.white,
),
overflow: TextOverflow.ellipsis,
),
);
}).toList(),
),
),
// 더 많은 일정이 있을 때
if (dayMaintenances.length > 3)
Positioned(
bottom: 2,
right: 2,
child: Container(
padding: const EdgeInsets.all(2),
decoration: BoxDecoration(
color: Colors.grey[600],
shape: BoxShape.circle,
),
child: Text(
'+${dayMaintenances.length - 3}',
style: const TextStyle(
fontSize: 8,
color: Colors.white,
),
),
),
),
],
),
),
),
);
}
return Container(
padding: const EdgeInsets.all(16),
child: GridView.count(
crossAxisCount: 7,
childAspectRatio: 1.2,
children: days,
),
);
}
List<MaintenanceDto> _getMaintenancesForDate(DateTime date) {
return widget.maintenances.where((m) {
// nextMaintenanceDate 필드가 백엔드에 없으므로 startedAt~endedAt 기간으로 확인
final targetDate = DateTime(date.year, date.month, date.day);
final startDate = DateTime(m.startedAt.year, m.startedAt.month, m.startedAt.day);
final endDate = DateTime(m.endedAt.year, m.endedAt.month, m.endedAt.day);
return (targetDate.isAfter(startDate) || targetDate.isAtSameMomentAs(startDate)) &&
(targetDate.isBefore(endDate) || targetDate.isAtSameMomentAs(endDate));
}).toList();
}
bool _isSameDay(DateTime date1, DateTime date2) {
return date1.year == date2.year &&
date1.month == date2.month &&
date1.day == date2.day;
}
bool _isToday(DateTime date) {
final now = DateTime.now();
return _isSameDay(date, now);
}
Color _getMaintenanceColor(MaintenanceDto maintenance) {
// status 필드가 백엔드에 없으므로 날짜 기반으로 상태 계산
final now = DateTime.now();
String status;
if (maintenance.isDeleted ?? false) {
status = 'cancelled';
} else if (maintenance.startedAt.isAfter(now)) {
status = 'scheduled';
} else if (maintenance.endedAt.isBefore(now)) {
status = 'overdue';
} else {
status = 'in_progress';
}
switch (status.toLowerCase()) {
case 'overdue':
return Colors.red;
case 'scheduled':
case 'upcoming':
// nextMaintenanceDate 필드가 없으므로 startedAt 기반으로 계산
final daysUntil = maintenance.startedAt.difference(DateTime.now()).inDays;
if (daysUntil <= 7) {
return Colors.orange;
} else if (daysUntil <= 30) {
return Colors.yellow[700]!;
}
return Colors.blue;
case 'inprogress':
case 'ongoing':
return Colors.purple;
case 'completed':
return Colors.green;
default:
return Colors.grey;
}
}
}

View File

@@ -0,0 +1,496 @@
import 'package:flutter/material.dart';
import '../../../data/models/maintenance_dto.dart';
import '../../../domain/usecases/maintenance_usecase.dart';
import '../../../utils/constants.dart';
/// 유지보수 컨트롤러 (백엔드 실제 스키마 기반)
class MaintenanceController extends ChangeNotifier {
final MaintenanceUseCase _maintenanceUseCase;
// 상태 관리 (단순화)
List<MaintenanceDto> _maintenances = [];
bool _isLoading = false;
String? _error;
// 페이지네이션
int _currentPage = 1;
int _totalCount = 0;
static const int _pageSize = PaginationConstants.defaultPageSize;
// 필터 (백엔드 실제 필드만)
String? _maintenanceType;
int? _equipmentHistoryId;
// 선택된 유지보수
MaintenanceDto? _selectedMaintenance;
// Getters (단순화)
List<MaintenanceDto> get maintenances => _maintenances;
bool get isLoading => _isLoading;
String? get error => _error;
int get currentPage => _currentPage;
int get totalPages => (_totalCount / _pageSize).ceil();
int get totalCount => _totalCount;
MaintenanceDto? get selectedMaintenance => _selectedMaintenance;
MaintenanceController({required MaintenanceUseCase maintenanceUseCase})
: _maintenanceUseCase = maintenanceUseCase;
// 유지보수 목록 로드 (백엔드 단순 구조)
Future<void> loadMaintenances({bool refresh = false}) async {
if (refresh) {
_currentPage = 1;
_maintenances.clear();
}
_isLoading = true;
_error = null;
notifyListeners();
try {
final response = await _maintenanceUseCase.getMaintenances(
page: _currentPage,
pageSize: _pageSize,
equipmentHistoryId: _equipmentHistoryId,
maintenanceType: _maintenanceType,
);
// response는 List<MaintenanceDto> 타입 (단순한 배열)
final maintenanceList = response as List<MaintenanceDto>;
if (refresh) {
_maintenances = maintenanceList;
} else {
_maintenances.addAll(maintenanceList);
}
_totalCount = maintenanceList.length;
notifyListeners();
} catch (e) {
_error = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
// 특정 장비 이력의 유지보수 로드
Future<void> loadMaintenancesByEquipmentHistory(int equipmentHistoryId) async {
_isLoading = true;
_error = null;
_equipmentHistoryId = equipmentHistoryId;
notifyListeners();
try {
_maintenances = await _maintenanceUseCase.getMaintenancesByEquipmentHistory(
equipmentHistoryId,
);
notifyListeners();
} catch (e) {
_error = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
// 간단한 통계 (백엔드 데이터 기반)
int get totalMaintenances => _maintenances.length;
int get activeMaintenances => _maintenances.where((m) => !(m.isDeleted ?? false)).length;
int get completedMaintenances => _maintenances.where((m) => m.endedAt != null && m.endedAt!.isBefore(DateTime.now())).length;
// 유지보수 생성 (백엔드 실제 스키마)
Future<bool> createMaintenance({
required int equipmentHistoryId,
required DateTime startedAt,
required DateTime endedAt,
required int periodMonth,
required String maintenanceType,
}) async {
_isLoading = true;
_error = null;
notifyListeners();
try {
final maintenance = await _maintenanceUseCase.createMaintenance(
MaintenanceRequestDto(
equipmentHistoryId: equipmentHistoryId,
startedAt: startedAt,
endedAt: endedAt,
periodMonth: periodMonth,
maintenanceType: maintenanceType,
),
);
_maintenances.insert(0, maintenance);
_totalCount++;
notifyListeners();
return true;
} catch (e) {
_error = '유지보수 등록 실패: ${e.toString()}';
return false;
} finally {
_isLoading = false;
notifyListeners();
}
}
// 유지보수 수정 (백엔드 실제 스키마)
Future<bool> updateMaintenance({
required int id,
DateTime? startedAt,
DateTime? endedAt,
int? periodMonth,
String? maintenanceType,
}) async {
_isLoading = true;
_error = null;
notifyListeners();
try {
final updatedMaintenance = await _maintenanceUseCase.updateMaintenance(
id,
MaintenanceUpdateRequestDto(
startedAt: startedAt,
endedAt: endedAt,
periodMonth: periodMonth,
maintenanceType: maintenanceType,
),
);
final index = _maintenances.indexWhere((m) => m.id == id);
if (index != -1) {
_maintenances[index] = updatedMaintenance;
}
if (_selectedMaintenance != null && _selectedMaintenance!.id == id) {
_selectedMaintenance = updatedMaintenance;
}
notifyListeners();
return true;
} catch (e) {
_error = '유지보수 수정 실패: ${e.toString()}';
return false;
} finally {
_isLoading = false;
notifyListeners();
}
}
// 유지보수 삭제 (백엔드 실제 구조)
Future<bool> deleteMaintenance(int id) async {
_isLoading = true;
_error = null;
notifyListeners();
try {
await _maintenanceUseCase.deleteMaintenance(id);
_maintenances.removeWhere((m) => m.id == id);
_totalCount--;
if (_selectedMaintenance != null && _selectedMaintenance!.id == id) {
_selectedMaintenance = null;
}
notifyListeners();
return true;
} catch (e) {
_error = '유지보수 삭제 실패: ${e.toString()}';
return false;
} finally {
_isLoading = false;
notifyListeners();
}
}
// 유지보수 상세 조회
Future<MaintenanceDto?> getMaintenanceDetail(int id) async {
try {
return await _maintenanceUseCase.getMaintenance(id);
} catch (e) {
_error = '유지보수 상세 조회 실패: ${e.toString()}';
return null;
}
}
// 유지보수 선택
void selectMaintenance(MaintenanceDto? maintenance) {
_selectedMaintenance = maintenance;
notifyListeners();
}
// 장비 이력별 유지보수 설정
void setEquipmentHistoryFilter(int equipmentHistoryId) {
_equipmentHistoryId = equipmentHistoryId;
loadMaintenances(refresh: true);
}
// 필터 설정
void setMaintenanceType(String? type) {
if (_maintenanceType != type) {
_maintenanceType = type;
loadMaintenances(refresh: true);
}
}
// 필터 초기화
void clearFilters() {
_maintenanceType = null;
_equipmentHistoryId = null;
loadMaintenances(refresh: true);
}
// 페이지 변경
void goToPage(int page) {
if (page >= 1 && page <= totalPages) {
_currentPage = page;
loadMaintenances();
}
}
void nextPage() {
if (_currentPage < totalPages) {
_currentPage++;
loadMaintenances();
}
}
void previousPage() {
if (_currentPage > 1) {
_currentPage--;
loadMaintenances();
}
}
// 오류 초기화
void clearError() {
_error = null;
notifyListeners();
}
// 유지보수 상태 표시명 (UI 호환성)
String getMaintenanceStatusDisplayName(String status) {
switch (status.toLowerCase()) {
case '예정':
case 'scheduled':
return '예정';
case '진행중':
case 'in_progress':
return '진행중';
case '완료':
case 'completed':
return '완료';
case '취소':
case 'cancelled':
return '취소';
default:
return status;
}
}
// 유지보수 상태 간단 판단 (백엔드 데이터 기반)
String getMaintenanceStatus(MaintenanceDto maintenance) {
final now = DateTime.now();
if (maintenance.isDeleted ?? false) return '취소';
if (maintenance.startedAt.isAfter(now)) return '예정';
if (maintenance.endedAt != null && maintenance.endedAt!.isBefore(now)) return '완료';
return '진행중';
}
// ================== 누락된 메서드들 추가 ==================
// 추가된 필드들
List<MaintenanceDto> _upcomingAlerts = [];
List<MaintenanceDto> _overdueAlerts = [];
Map<String, dynamic> _statistics = {};
String _searchQuery = '';
String _currentSortField = '';
bool _isAscending = true;
// 추가 Getters
List<MaintenanceDto> get upcomingAlerts => _upcomingAlerts;
List<MaintenanceDto> get overdueAlerts => _overdueAlerts;
Map<String, dynamic> get statistics => _statistics;
int get upcomingCount => _upcomingAlerts.length;
int get overdueCount => _overdueAlerts.length;
// ID로 유지보수 조회 (호환성)
Future<MaintenanceDto?> getMaintenanceById(int id) async {
return await getMaintenanceDetail(id);
}
// 알람 로드 (백엔드 스키마 기반)
Future<void> loadAlerts() async {
_isLoading = true;
notifyListeners();
try {
final now = DateTime.now();
// 예정된 유지보수 (시작일이 미래인 것)
_upcomingAlerts = _maintenances.where((maintenance) {
return maintenance.startedAt.isAfter(now) &&
!(maintenance.isDeleted ?? false);
}).take(10).toList();
// 연체된 유지보수 (종료일이 과거이고 아직 완료되지 않은 것)
_overdueAlerts = _maintenances.where((maintenance) {
return maintenance.endedAt.isBefore(now) &&
maintenance.startedAt.isBefore(now) &&
!(maintenance.isDeleted ?? false);
}).take(10).toList();
notifyListeners();
} catch (e) {
_error = '알람 로드 실패: ${e.toString()}';
} finally {
_isLoading = false;
notifyListeners();
}
}
// 통계 로드 (백엔드 데이터 기반)
Future<void> loadStatistics() async {
_isLoading = true;
notifyListeners();
try {
final now = DateTime.now();
final scheduled = _maintenances.where((m) =>
m.startedAt.isAfter(now) && !(m.isDeleted ?? false)).length;
final inProgress = _maintenances.where((m) =>
m.startedAt.isBefore(now) && m.endedAt.isAfter(now) && !(m.isDeleted ?? false)).length;
final completed = _maintenances.where((m) =>
m.endedAt.isBefore(now) && !(m.isDeleted ?? false)).length;
final cancelled = _maintenances.where((m) =>
m.isDeleted ?? false).length;
_statistics = {
'total': _maintenances.length,
'scheduled': scheduled,
'inProgress': inProgress,
'completed': completed,
'cancelled': cancelled,
'upcoming': upcomingCount,
'overdue': overdueCount,
};
notifyListeners();
} catch (e) {
_error = '통계 로드 실패: ${e.toString()}';
} finally {
_isLoading = false;
notifyListeners();
}
}
// 검색 쿼리 설정
void setSearchQuery(String query) {
if (_searchQuery != query) {
_searchQuery = query;
// TODO: 실제 검색 구현 시 백엔드 API 호출 필요
loadMaintenances(refresh: true);
}
}
// 유지보수 필터 설정 (호환성)
void setMaintenanceFilter(String? type) {
setMaintenanceType(type);
}
// 정렬 설정
void setSorting(String field, bool ascending) {
if (_currentSortField != field || _isAscending != ascending) {
_currentSortField = field;
_isAscending = ascending;
// 클라이언트 사이드 정렬 (백엔드 정렬 API가 없는 경우)
_maintenances.sort((a, b) {
dynamic valueA, valueB;
switch (field) {
case 'startedAt':
valueA = a.startedAt;
valueB = b.startedAt;
break;
case 'endedAt':
valueA = a.endedAt;
valueB = b.endedAt;
break;
case 'maintenanceType':
valueA = a.maintenanceType;
valueB = b.maintenanceType;
break;
case 'periodMonth':
valueA = a.periodMonth;
valueB = b.periodMonth;
break;
default:
valueA = a.id;
valueB = b.id;
}
if (valueA == null && valueB == null) return 0;
if (valueA == null) return ascending ? -1 : 1;
if (valueB == null) return ascending ? 1 : -1;
final comparison = valueA.compareTo(valueB);
return ascending ? comparison : -comparison;
});
notifyListeners();
}
}
// 유지보수 일정 조회 (백엔드 스키마 기반)
List<MaintenanceDto> getScheduleForMaintenance(DateTime date) {
return _maintenances.where((maintenance) {
final startDate = DateTime(
maintenance.startedAt.year,
maintenance.startedAt.month,
maintenance.startedAt.day,
);
final endDate = DateTime(
maintenance.endedAt.year,
maintenance.endedAt.month,
maintenance.endedAt.day,
);
final targetDate = DateTime(date.year, date.month, date.day);
return (targetDate.isAfter(startDate) || targetDate.isAtSameMomentAs(startDate)) &&
(targetDate.isBefore(endDate) || targetDate.isAtSameMomentAs(endDate)) &&
!(maintenance.isDeleted ?? false);
}).toList();
}
// 초기화 (백엔드 실제 구조)
void reset() {
_maintenances.clear();
_selectedMaintenance = null;
_currentPage = 1;
_totalCount = 0;
_maintenanceType = null;
_equipmentHistoryId = null;
_error = null;
_isLoading = false;
_upcomingAlerts.clear();
_overdueAlerts.clear();
_statistics.clear();
_searchQuery = '';
_currentSortField = '';
_isAscending = true;
notifyListeners();
}
@override
void dispose() {
reset();
super.dispose();
}
}

View File

@@ -0,0 +1,748 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../../data/models/maintenance_dto.dart';
import '../../domain/entities/maintenance_schedule.dart';
import 'controllers/maintenance_controller.dart';
import 'maintenance_form_dialog.dart';
class MaintenanceAlertDashboard extends StatefulWidget {
const MaintenanceAlertDashboard({super.key});
@override
State<MaintenanceAlertDashboard> createState() => _MaintenanceAlertDashboardState();
}
class _MaintenanceAlertDashboardState extends State<MaintenanceAlertDashboard> {
@override
void initState() {
super.initState();
// 초기 데이터 로드
WidgetsBinding.instance.addPostFrameCallback((_) {
final controller = context.read<MaintenanceController>();
controller.loadAlerts();
controller.loadStatistics();
controller.loadMaintenances(refresh: true);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[100],
body: Consumer<MaintenanceController>(
builder: (context, controller, child) {
if (controller.isLoading && controller.upcomingAlerts.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
return RefreshIndicator(
onRefresh: () async {
await controller.loadAlerts();
await controller.loadStatistics();
},
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildHeader(controller),
const SizedBox(height: 24),
_buildStatisticsSummary(controller),
const SizedBox(height: 24),
_buildAlertSections(controller),
const SizedBox(height: 24),
_buildQuickActions(controller),
],
),
),
);
},
),
);
}
Widget _buildHeader(MaintenanceController controller) {
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Theme.of(context).primaryColor, Theme.of(context).primaryColor.withValues(alpha: 0.8)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Theme.of(context).primaryColor.withValues(alpha: 0.3),
blurRadius: 10,
offset: const Offset(0, 4),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'유지보수 알림 대시보드',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
const SizedBox(height: 4),
Text(
'${DateFormat('yyyy년 MM월 dd일').format(DateTime.now())} 기준',
style: TextStyle(
fontSize: 14,
color: Colors.white.withValues(alpha: 0.9),
),
),
],
),
IconButton(
icon: const Icon(Icons.refresh, color: Colors.white),
onPressed: () {
controller.loadAlerts();
controller.loadStatistics();
},
tooltip: '새로고침',
),
],
),
const SizedBox(height: 16),
Row(
children: [
_buildHeaderStat(
Icons.warning_amber,
'긴급',
controller.overdueAlerts.length.toString(),
Colors.red[300]!,
),
const SizedBox(width: 16),
_buildHeaderStat(
Icons.schedule,
'예정',
controller.upcomingAlerts.length.toString(),
Colors.orange[300]!,
),
const SizedBox(width: 16),
_buildHeaderStat(
Icons.check_circle,
'완료',
(controller.statistics['activeCount'] ?? 0).toString(),
Colors.green[300]!,
),
],
),
],
),
);
}
Widget _buildHeaderStat(IconData icon, String label, String value, Color color) {
return Expanded(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Icon(icon, color: color, size: 24),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
fontSize: 12,
color: Colors.white.withValues(alpha: 0.9),
),
),
Text(
value,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
],
),
),
);
}
Widget _buildStatisticsSummary(MaintenanceController controller) {
final stats = controller.statistics;
if (stats == null) return const SizedBox.shrink();
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withValues(alpha: 0.1),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'이번 달 통계',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: _buildStatCard(
'총 유지보수',
(stats['totalCount'] ?? 0).toString(),
Icons.build_circle,
Colors.blue,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildStatCard(
'예정',
(stats['totalCount'] ?? 0).toString(),
Icons.schedule,
Colors.orange,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildStatCard(
'완료',
(stats['activeCount'] ?? 0).toString(),
Icons.check_circle,
Colors.green,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildStatCard(
'총 비용',
'${NumberFormat('#,###').format(stats['totalCost'] ?? 0)}',
Icons.attach_money,
Colors.purple,
),
),
],
),
const SizedBox(height: 16),
LinearProgressIndicator(
value: (stats['totalCount'] ?? 0) > 0 ? (stats['activeCount'] ?? 0) / (stats['totalCount'] ?? 0) : 0,
backgroundColor: Colors.grey[300],
valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor),
),
const SizedBox(height: 8),
Text(
'완료율: ${(stats['totalCount'] ?? 0) > 0 ? (((stats['activeCount'] ?? 0) / (stats['totalCount'] ?? 1)) * 100).toStringAsFixed(1) : 0}%',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
),
),
],
),
);
}
Widget _buildStatCard(String title, String value, IconData icon, Color color) {
return Column(
children: [
Icon(icon, color: color, size: 32),
const SizedBox(height: 8),
Text(
value,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: color,
),
),
const SizedBox(height: 4),
Text(
title,
style: TextStyle(
fontSize: 12,
color: Colors.grey[600],
),
),
],
);
}
Widget _buildAlertSections(MaintenanceController controller) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 지연된 유지보수
if (controller.overdueAlerts.isNotEmpty) ...[
_buildAlertSection(
'⚠️ 지연된 유지보수',
controller.overdueAlerts,
Colors.red,
true,
),
const SizedBox(height: 20),
],
// 예정된 유지보수
if (controller.upcomingAlerts.isNotEmpty) ...[
_buildAlertSection(
'📅 예정된 유지보수',
controller.upcomingAlerts,
Colors.orange,
false,
),
],
// 알림이 없는 경우
if (controller.overdueAlerts.isEmpty && controller.upcomingAlerts.isEmpty)
Center(
child: Container(
padding: const EdgeInsets.all(40),
child: Column(
children: [
Icon(Icons.check_circle_outline, size: 64, color: Colors.green[400]),
const SizedBox(height: 16),
Text(
'모든 유지보수가 정상입니다',
style: TextStyle(
fontSize: 18,
color: Colors.grey[600],
),
),
],
),
),
),
],
);
}
Widget _buildAlertSection(
String title,
List<MaintenanceDto> alerts,
Color color,
bool isOverdue,
) {
// 우선순위별로 정렬
final sortedAlerts = List<MaintenanceDto>.from(alerts)
..sort((a, b) {
// MaintenanceDto에는 priority와 daysUntilDue가 없으므로 등록일순으로 정렬
if (a.registeredAt != null && b.registeredAt != null) {
return b.registeredAt!.compareTo(a.registeredAt!);
}
return 0;
});
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withValues(alpha: 0.1),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.1),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
title,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: color,
),
),
Chip(
label: Text(
'${alerts.length}',
style: const TextStyle(color: Colors.white, fontSize: 12),
),
backgroundColor: color,
padding: const EdgeInsets.symmetric(horizontal: 8),
),
],
),
),
ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: sortedAlerts.length > 5 ? 5 : sortedAlerts.length,
separatorBuilder: (context, index) => const Divider(height: 1),
itemBuilder: (context, index) {
final alert = sortedAlerts[index];
return _buildAlertCard(alert, isOverdue);
},
),
if (sortedAlerts.length > 5)
Container(
padding: const EdgeInsets.all(12),
child: Center(
child: TextButton(
onPressed: () => _showAllAlerts(context, sortedAlerts, title),
child: Text('${sortedAlerts.length - 5}개 더 보기'),
),
),
),
],
),
);
}
Widget _buildAlertCard(MaintenanceDto alert, bool isOverdue) {
// MaintenanceDto 필드에 맞게 수정
final typeColor = alert.maintenanceType == 'O' ? Colors.blue : Colors.green;
final typeIcon = alert.maintenanceType == 'O' ? Icons.build : Icons.computer;
// 예상 마감일 계산 (startedAt + periodMonth)
DateTime? scheduledDate;
int daysUntil = 0;
if (alert.startedAt != null && alert.periodMonth != null) {
scheduledDate = DateTime(alert.startedAt!.year, alert.startedAt!.month + alert.periodMonth!, alert.startedAt!.day);
daysUntil = scheduledDate.difference(DateTime.now()).inDays;
}
return ListTile(
leading: CircleAvatar(
backgroundColor: typeColor.withValues(alpha: 0.2),
child: Icon(typeIcon, color: typeColor, size: 20),
),
title: Text(
'Equipment History #${alert.equipmentHistoryId}',
style: const TextStyle(fontWeight: FontWeight.w500),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 4),
if (scheduledDate != null)
Text(
isOverdue
? '${daysUntil.abs()}일 지연'
: '${daysUntil}일 후 예정',
style: TextStyle(
color: isOverdue ? Colors.red : Colors.orange,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 2),
if (scheduledDate != null)
Text(
'예정일: ${DateFormat('yyyy-MM-dd').format(scheduledDate)}',
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
if (alert.periodMonth != null)
Text(
'주기: ${alert.periodMonth}개월',
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
],
),
trailing: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Chip(
label: Text(
alert.maintenanceType == 'O' ? '현장' : '원격',
style: const TextStyle(fontSize: 11, color: Colors.white),
),
backgroundColor: typeColor,
padding: EdgeInsets.zero,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
const SizedBox(height: 4),
Text(
'비용: 미지원',
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
],
),
onTap: () => _showMaintenanceDetails(alert.id!),
);
}
Widget _buildQuickActions(MaintenanceController controller) {
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withValues(alpha: 0.1),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'빠른 작업',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: _buildActionButton(
'새 유지보수 등록',
Icons.add_circle,
Colors.blue,
() => _showCreateMaintenanceDialog(),
),
),
const SizedBox(width: 12),
Expanded(
child: _buildActionButton(
'일정 보기',
Icons.calendar_month,
Colors.green,
() => Navigator.pushNamed(context, '/maintenance/schedule'),
),
),
],
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: _buildActionButton(
'보고서 생성',
Icons.description,
Colors.orange,
() => _generateReport(controller),
),
),
const SizedBox(width: 12),
Expanded(
child: _buildActionButton(
'엑셀 내보내기',
Icons.file_download,
Colors.purple,
() => _exportToExcel(controller),
),
),
],
),
],
),
);
}
Widget _buildActionButton(
String label,
IconData icon,
Color color,
VoidCallback onPressed,
) {
return ElevatedButton.icon(
onPressed: onPressed,
icon: Icon(icon, size: 20),
label: Text(label),
style: ElevatedButton.styleFrom(
backgroundColor: color,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
);
}
Color _getPriorityColor(AlertPriority priority) {
switch (priority) {
case AlertPriority.critical:
return Colors.red;
case AlertPriority.high:
return Colors.orange;
case AlertPriority.medium:
return Colors.yellow[700]!;
case AlertPriority.low:
return Colors.blue;
}
}
IconData _getPriorityIcon(AlertPriority priority) {
switch (priority) {
case AlertPriority.critical:
return Icons.error;
case AlertPriority.high:
return Icons.warning;
case AlertPriority.medium:
return Icons.info;
case AlertPriority.low:
return Icons.info_outline;
}
}
String _getPriorityLabel(AlertPriority priority) {
switch (priority) {
case AlertPriority.critical:
return '긴급';
case AlertPriority.high:
return '높음';
case AlertPriority.medium:
return '보통';
case AlertPriority.low:
return '낮음';
}
}
int _getPriorityOrder(AlertPriority priority) {
switch (priority) {
case AlertPriority.critical:
return 4;
case AlertPriority.high:
return 3;
case AlertPriority.medium:
return 2;
case AlertPriority.low:
return 1;
}
}
void _showAllAlerts(BuildContext context, List<MaintenanceDto> alerts, String title) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => DraggableScrollableSheet(
initialChildSize: 0.7,
minChildSize: 0.5,
maxChildSize: 0.95,
expand: false,
builder: (context, scrollController) => Container(
padding: const EdgeInsets.all(16),
child: Column(
children: [
Text(
title,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 16),
Expanded(
child: ListView.separated(
controller: scrollController,
itemCount: alerts.length,
separatorBuilder: (context, index) => const Divider(),
itemBuilder: (context, index) {
final alert = alerts[index];
return _buildAlertCard(alert, title.contains('지연'));
},
),
),
],
),
),
),
);
}
void _showMaintenanceDetails(int maintenanceId) {
final controller = context.read<MaintenanceController>();
final maintenance = controller.maintenances.firstWhere(
(m) => m.id == maintenanceId,
orElse: () => MaintenanceDto(
equipmentHistoryId: 0,
startedAt: DateTime.now(),
endedAt: DateTime.now(),
periodMonth: 0,
maintenanceType: 'O',
registeredAt: DateTime.now(),
),
);
if (maintenance.id != 0) {
showDialog(
context: context,
builder: (context) => MaintenanceFormDialog(maintenance: maintenance),
).then((result) {
if (result == true) {
controller.loadAlerts();
controller.loadMaintenances(refresh: true);
}
});
}
}
void _showCreateMaintenanceDialog() {
showDialog(
context: context,
builder: (context) => const MaintenanceFormDialog(),
).then((result) {
if (result == true) {
final controller = context.read<MaintenanceController>();
controller.loadAlerts();
controller.loadMaintenances(refresh: true);
}
});
}
void _generateReport(MaintenanceController controller) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('보고서 생성 기능은 준비 중입니다'),
backgroundColor: Colors.orange,
),
);
}
void _exportToExcel(MaintenanceController controller) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('엑셀 내보내기 기능은 준비 중입니다'),
backgroundColor: Colors.purple,
),
);
}
}

View File

@@ -0,0 +1,358 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../../data/models/maintenance_dto.dart';
import '../../data/models/equipment_history_dto.dart';
import '../equipment/controllers/equipment_history_controller.dart';
import 'controllers/maintenance_controller.dart';
class MaintenanceFormDialog extends StatefulWidget {
final MaintenanceDto? maintenance;
const MaintenanceFormDialog({
super.key,
this.maintenance,
});
@override
State<MaintenanceFormDialog> createState() => _MaintenanceFormDialogState();
}
class _MaintenanceFormDialogState extends State<MaintenanceFormDialog> {
final _formKey = GlobalKey<FormState>();
late final TextEditingController _periodController;
int? _selectedEquipmentHistoryId;
String _maintenanceType = 'O'; // O: Onsite, R: Remote
DateTime _startDate = DateTime.now();
DateTime? _endDate;
List<EquipmentHistoryDto> _equipmentHistories = [];
bool _isLoadingHistories = false;
@override
void initState() {
super.initState();
// 컨트롤러 초기화 - 백엔드 스키마 기준
_periodController = TextEditingController(
text: widget.maintenance?.periodMonth?.toString() ?? '12',
);
// 기존 데이터 설정
if (widget.maintenance != null) {
_selectedEquipmentHistoryId = widget.maintenance!.equipmentHistoryId;
_maintenanceType = widget.maintenance!.maintenanceType ?? 'O';
if (widget.maintenance!.startedAt != null) {
_startDate = widget.maintenance!.startedAt!;
}
if (widget.maintenance!.endedAt != null) {
_endDate = widget.maintenance!.endedAt!;
}
}
// Equipment History 목록 로드
_loadEquipmentHistories();
}
@override
void dispose() {
_periodController.dispose();
super.dispose();
}
void _loadEquipmentHistories() async {
setState(() {
_isLoadingHistories = true;
});
try {
final controller = context.read<EquipmentHistoryController>();
await controller.loadHistory(refresh: true);
setState(() {
_equipmentHistories = controller.historyList;
_isLoadingHistories = false;
});
} catch (e) {
setState(() {
_isLoadingHistories = false;
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('장비 이력 로드 실패: $e')),
);
}
}
}
// _calculateNextDate 메서드 제거 - 백엔드에 nextMaintenanceDate 필드 없음
@override
Widget build(BuildContext context) {
final isEditMode = widget.maintenance != null;
return AlertDialog(
title: Text(isEditMode ? '유지보수 수정' : '유지보수 등록'),
content: SizedBox(
width: MediaQuery.of(context).size.width * 0.6,
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Equipment History 선택
_buildEquipmentHistorySelector(),
const SizedBox(height: 16),
// 유지보수 타입
_buildMaintenanceTypeSelector(),
const SizedBox(height: 16),
// 시작일 및 주기
Row(
children: [
Expanded(
child: _buildDateField(
'시작일',
_startDate,
(date) => setState(() => _startDate = date),
),
),
const SizedBox(width: 16),
Expanded(
child: TextFormField(
controller: _periodController,
decoration: const InputDecoration(
labelText: '주기 (개월)',
suffixText: '개월',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(2),
],
validator: (value) {
if (value == null || value.isEmpty) {
return '주기를 입력해주세요';
}
final period = int.tryParse(value);
if (period == null || period <= 0 || period > 60) {
return '1-60 사이의 값을 입력해주세요';
}
return null;
},
),
),
],
),
const SizedBox(height: 16),
// nextMaintenanceDate 필드가 백엔드에 없으므로 제거
const SizedBox(height: 16),
// cost 필드와 totalCount 필드가 백엔드에 없으므로 제거
const SizedBox(height: 16),
// 업체 정보와 연락처 필드가 백엔드에 없으므로 제거
const SizedBox(height: 16),
// 메모 필드가 백엔드에 없으므로 제거
const SizedBox(height: 16),
// isActive 필드가 백엔드에 없으므로 제거 (백엔드에는 isDeleted만 있음)
],
),
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('취소'),
),
Consumer<MaintenanceController>(
builder: (context, controller, child) {
return ElevatedButton(
onPressed: controller.isLoading ? null : _submit,
child: controller.isLoading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(isEditMode ? '수정' : '등록'),
);
},
),
],
);
}
Widget _buildEquipmentHistorySelector() {
if (_isLoadingHistories) {
return const Center(child: CircularProgressIndicator());
}
return DropdownButtonFormField<int>(
value: _selectedEquipmentHistoryId,
decoration: const InputDecoration(
labelText: '장비 이력 선택',
border: OutlineInputBorder(),
),
items: _equipmentHistories.map((history) {
final equipment = history.equipment;
return DropdownMenuItem(
value: history.id,
child: Text(
'${equipment?.serialNumber ?? "Unknown"} - '
'${equipment?.serialNumber ?? "No Serial"} '
'(${history.transactionType == "I" ? "입고" : "출고"})',
),
);
}).toList(),
onChanged: widget.maintenance == null
? (value) => setState(() => _selectedEquipmentHistoryId = value)
: null, // 수정 모드에서는 변경 불가
validator: (value) {
if (value == null) {
return '장비 이력을 선택해주세요';
}
return null;
},
);
}
Widget _buildMaintenanceTypeSelector() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'유지보수 타입',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: RadioListTile<String>(
title: const Text('현장 (Onsite)'),
value: 'O',
groupValue: _maintenanceType,
onChanged: (value) {
setState(() {
_maintenanceType = value!;
});
},
contentPadding: EdgeInsets.zero,
),
),
Expanded(
child: RadioListTile<String>(
title: const Text('원격 (Remote)'),
value: 'R',
groupValue: _maintenanceType,
onChanged: (value) {
setState(() {
_maintenanceType = value!;
});
},
contentPadding: EdgeInsets.zero,
),
),
],
),
],
);
}
Widget _buildDateField(
String label,
DateTime value,
Function(DateTime) onChanged,
) {
return InkWell(
onTap: () async {
final picked = await showDatePicker(
context: context,
initialDate: value,
firstDate: DateTime(2020),
lastDate: DateTime(2030),
);
if (picked != null) {
onChanged(picked);
// _calculateNextDate() 메서드 제거 - 백엔드에 nextMaintenanceDate 필드 없음
}
},
child: InputDecorator(
decoration: InputDecoration(
labelText: label,
border: const OutlineInputBorder(),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(DateFormat('yyyy-MM-dd').format(value)),
const Icon(Icons.calendar_today, size: 20),
],
),
),
);
}
void _submit() async {
if (!_formKey.currentState!.validate()) return;
final controller = context.read<MaintenanceController>();
bool success;
if (widget.maintenance != null) {
// 수정 - MaintenanceUpdateRequestDto 사용
final request = MaintenanceUpdateRequestDto(
startedAt: _startDate,
endedAt: _endDate,
periodMonth: int.tryParse(_periodController.text),
maintenanceType: _maintenanceType,
);
success = await controller.updateMaintenance(
id: widget.maintenance!.id!,
startedAt: _startDate,
endedAt: _endDate,
periodMonth: int.tryParse(_periodController.text),
maintenanceType: _maintenanceType,
);
} else {
// 생성 - named 파라미터로 직접 전달
success = await controller.createMaintenance(
equipmentHistoryId: _selectedEquipmentHistoryId!,
startedAt: _startDate,
endedAt: _endDate ?? DateTime.now().add(const Duration(days: 30)), // 기본값: 30일 후
periodMonth: int.tryParse(_periodController.text) ?? 1,
maintenanceType: _maintenanceType,
);
}
if (success && mounted) {
Navigator.of(context).pop(true);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(widget.maintenance != null ? '유지보수가 수정되었습니다' : '유지보수가 등록되었습니다'),
backgroundColor: Colors.green,
),
);
} else if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(controller.error ?? '오류가 발생했습니다'),
backgroundColor: Colors.red,
),
);
}
}
}

View File

@@ -0,0 +1,904 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../../data/models/maintenance_dto.dart';
import 'controllers/maintenance_controller.dart';
class MaintenanceHistoryScreen extends StatefulWidget {
const MaintenanceHistoryScreen({super.key});
@override
State<MaintenanceHistoryScreen> createState() => _MaintenanceHistoryScreenState();
}
class _MaintenanceHistoryScreenState extends State<MaintenanceHistoryScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
DateTimeRange? _selectedDateRange;
String _viewMode = 'timeline'; // timeline, table, analytics
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
// 초기 데이터 로드
WidgetsBinding.instance.addPostFrameCallback((_) {
final controller = context.read<MaintenanceController>();
controller.loadMaintenances(refresh: true);
});
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[100],
body: Column(
children: [
_buildHeader(),
_buildViewModeSelector(),
Expanded(
child: Consumer<MaintenanceController>(
builder: (context, controller, child) {
if (controller.isLoading && controller.maintenances.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (controller.error != null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 64, color: Colors.red),
const SizedBox(height: 16),
Text(controller.error!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => controller.loadMaintenances(refresh: true),
child: const Text('다시 시도'),
),
],
),
);
}
final completedMaintenances = controller.maintenances
.where((m) => m.endedAt != null)
.toList();
if (completedMaintenances.isEmpty) {
return _buildEmptyState();
}
switch (_viewMode) {
case 'timeline':
return _buildTimelineView(completedMaintenances);
case 'table':
return _buildTableView(completedMaintenances);
case 'analytics':
return _buildAnalyticsView(completedMaintenances, controller);
default:
return _buildTimelineView(completedMaintenances);
}
},
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: _exportHistory,
tooltip: '엑셀 내보내기',
child: const Icon(Icons.file_download),
),
);
}
Widget _buildHeader() {
return Container(
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withValues(alpha: 0.1),
spreadRadius: 1,
blurRadius: 3,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'유지보수 이력',
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Consumer<MaintenanceController>(
builder: (context, controller, child) {
final completedCount = controller.maintenances
.where((m) => m.endedAt != null)
.length;
return Text(
'완료된 유지보수: $completedCount건',
style: TextStyle(color: Colors.grey[600]),
);
},
),
],
),
Row(
children: [
TextButton.icon(
onPressed: _selectDateRange,
icon: const Icon(Icons.date_range),
label: Text(
_selectedDateRange != null
? '${DateFormat('yyyy.MM.dd').format(_selectedDateRange!.start)} - ${DateFormat('yyyy.MM.dd').format(_selectedDateRange!.end)}'
: '기간 선택',
),
),
if (_selectedDateRange != null)
IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
setState(() {
_selectedDateRange = null;
});
context.read<MaintenanceController>().loadMaintenances(refresh: true);
},
tooltip: '필터 초기화',
),
],
),
],
),
const SizedBox(height: 16),
_buildSummaryCards(),
],
),
);
}
Widget _buildSummaryCards() {
return Consumer<MaintenanceController>(
builder: (context, controller, child) {
final completedMaintenances = controller.maintenances
.where((m) => m.endedAt != null)
.toList();
// 백엔드에 cost 필드가 없으므로 다른 통계 사용
final thisMonthCompleted = completedMaintenances.where((m) {
final now = DateTime.now();
if (m.registeredAt == null) return false;
final registeredDate = m.registeredAt!;
return registeredDate.year == now.year && registeredDate.month == now.month;
}).length;
final avgPeriod = completedMaintenances.isNotEmpty
? (completedMaintenances.map((m) => m.periodMonth ?? 0).reduce((a, b) => a + b) / completedMaintenances.length).toStringAsFixed(1)
: '0';
final onsiteCount = completedMaintenances.where((m) => m.maintenanceType == 'O').length;
return Row(
children: [
Expanded(
child: _buildSummaryCard(
'총 완료 건수',
completedMaintenances.length.toString(),
Icons.check_circle,
Colors.green,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildSummaryCard(
'이번 달 완료',
thisMonthCompleted.toString(),
Icons.calendar_today,
Colors.blue,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildSummaryCard(
'평균 주기',
'${avgPeriod}개월',
Icons.schedule,
Colors.orange,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildSummaryCard(
'현장 유지보수',
'$onsiteCount건',
Icons.location_on,
Colors.purple,
),
),
],
);
},
);
}
Widget _buildSummaryCard(String title, String value, IconData icon, Color color) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, color: color, size: 24),
const SizedBox(height: 8),
Text(
title,
style: TextStyle(
fontSize: 12,
color: Colors.grey[600],
),
),
const SizedBox(height: 4),
Text(
value,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: color,
),
),
],
),
);
}
Widget _buildViewModeSelector() {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
decoration: BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(color: Colors.grey[300]!),
),
),
child: Row(
children: [
_buildViewModeButton('timeline', Icons.timeline, '타임라인'),
const SizedBox(width: 12),
_buildViewModeButton('table', Icons.table_chart, '테이블'),
const SizedBox(width: 12),
_buildViewModeButton('analytics', Icons.analytics, '분석'),
],
),
);
}
Widget _buildViewModeButton(String mode, IconData icon, String label) {
final isSelected = _viewMode == mode;
return Expanded(
child: InkWell(
onTap: () => setState(() => _viewMode = mode),
child: Container(
padding: const EdgeInsets.symmetric(vertical: 12),
decoration: BoxDecoration(
color: isSelected ? Theme.of(context).primaryColor : Colors.grey[100],
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
icon,
size: 20,
color: isSelected ? Colors.white : Colors.grey[600],
),
const SizedBox(width: 8),
Text(
label,
style: TextStyle(
color: isSelected ? Colors.white : Colors.grey[600],
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
),
),
],
),
),
),
);
}
Widget _buildEmptyState() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.history, size: 64, color: Colors.grey[400]),
const SizedBox(height: 16),
Text(
'완료된 유지보수가 없습니다',
style: TextStyle(
fontSize: 18,
color: Colors.grey[600],
),
),
],
),
);
}
Widget _buildTimelineView(List<MaintenanceDto> maintenances) {
// 날짜별로 그룹화 (endedAt 기준)
final groupedByDate = <String, List<MaintenanceDto>>{};
for (final maintenance in maintenances) {
if (maintenance.endedAt == null) continue;
final endedDate = maintenance.endedAt!;
final dateKey = DateFormat('yyyy-MM-dd').format(endedDate);
groupedByDate.putIfAbsent(dateKey, () => []).add(maintenance);
}
final sortedDates = groupedByDate.keys.toList()
..sort((a, b) => b.compareTo(a)); // 최신순 정렬
return ListView.builder(
padding: const EdgeInsets.all(24),
itemCount: sortedDates.length,
itemBuilder: (context, index) {
final date = sortedDates[index];
final dayMaintenances = groupedByDate[date]!;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(20),
),
child: Text(
DateFormat('yyyy년 MM월 dd일').format(DateTime.parse(date)),
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(height: 12),
...dayMaintenances.map((m) => _buildTimelineItem(m)),
const SizedBox(height: 24),
],
);
},
);
}
Widget _buildTimelineItem(MaintenanceDto maintenance) {
return Container(
margin: const EdgeInsets.only(left: 20, bottom: 12),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.grey.withValues(alpha: 0.1),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
border: Border(
left: BorderSide(
color: Theme.of(context).primaryColor,
width: 3,
),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Equipment History #${maintenance.equipmentHistoryId}',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
Text(
maintenance.endedAt != null
? DateFormat('HH:mm').format(maintenance.endedAt!)
: '',
style: TextStyle(
color: Colors.grey[600],
fontSize: 14,
),
),
],
),
const SizedBox(height: 8),
Row(
children: [
Chip(
label: Text(
maintenance.maintenanceType == 'O' ? '현장' : '원격',
style: const TextStyle(fontSize: 12),
),
backgroundColor: Colors.grey[200],
padding: EdgeInsets.zero,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
const SizedBox(width: 8),
Text(
'${maintenance.periodMonth ?? 0}개월 주기',
style: TextStyle(
color: Colors.grey[700],
fontWeight: FontWeight.w500,
),
),
],
),
const SizedBox(height: 8),
Row(
children: [
Icon(Icons.date_range, size: 16, color: Colors.grey[600]),
const SizedBox(width: 4),
Text(
'시작: ${maintenance.startedAt ?? 'N/A'}',
style: TextStyle(color: Colors.grey[600]),
),
],
),
if (maintenance.endedAt != null) ...[
const SizedBox(height: 4),
Row(
children: [
Icon(Icons.check_circle, size: 16, color: Colors.green),
const SizedBox(width: 4),
Text(
'완료: ${maintenance.endedAt}',
style: TextStyle(color: Colors.green),
),
],
),
],
],
),
);
}
Widget _buildTableView(List<MaintenanceDto> maintenances) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: DataTable(
columns: const [
DataColumn(label: Text('시작일')),
DataColumn(label: Text('완료일')),
DataColumn(label: Text('장비 이력 ID')),
DataColumn(label: Text('유형')),
DataColumn(label: Text('주기(개월)')),
DataColumn(label: Text('등록일')),
DataColumn(label: Text('작업')),
],
rows: maintenances.map((m) {
return DataRow(
cells: [
DataCell(Text(m.startedAt != null ? DateFormat('yyyy-MM-dd').format(m.startedAt!) : '-')),
DataCell(Text(m.endedAt != null ? DateFormat('yyyy-MM-dd').format(m.endedAt!) : '-')),
DataCell(Text('#${m.equipmentHistoryId}')),
DataCell(Text(m.maintenanceType == 'O' ? '현장' : '원격')),
DataCell(Text('${m.periodMonth ?? 0}')),
DataCell(Text(m.registeredAt != null ? DateFormat('yyyy-MM-dd').format(m.registeredAt!) : '-')),
DataCell(
IconButton(
icon: const Icon(Icons.visibility, size: 20),
onPressed: () => _showMaintenanceDetails(m),
),
),
],
);
}).toList(),
),
),
);
}
Widget _buildAnalyticsView(List<MaintenanceDto> maintenances, MaintenanceController controller) {
// 월별 비용 계산
final monthlyCosts = <String, double>{};
final typeDistribution = <String, int>{};
final vendorCosts = <String, double>{};
for (final m in maintenances) {
// 월별 비용
if (m.updatedAt == null) continue;
final updatedDate = m.updatedAt!;
final monthKey = DateFormat('yyyy-MM').format(updatedDate);
// cost 필드가 백엔드에 없으므로 비용 계산 제거
monthlyCosts[monthKey] = (monthlyCosts[monthKey] ?? 0.0) + 0.0;
// 유형별 분포
final typeKey = m.maintenanceType == 'O' ? '현장' : '원격';
typeDistribution[typeKey] = (typeDistribution[typeKey] ?? 0) + 1;
// 업체별 비용 (description 필드도 백엔드에 없으므로 maintenanceType 사용)
final vendorKey = m.maintenanceType == 'O' ? '현장유지보수' : '원격유지보수';
vendorCosts[vendorKey] = (vendorCosts[vendorKey] ?? 0) + 1; // 건수로 대체
}
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 월별 비용 추이
_buildAnalyticsSection(
'월별 비용 추이',
Icons.show_chart,
_buildMonthlyChart(monthlyCosts),
),
const SizedBox(height: 24),
// 유형별 분포
_buildAnalyticsSection(
'유지보수 유형 분포',
Icons.pie_chart,
_buildTypeDistribution(typeDistribution),
),
const SizedBox(height: 24),
// 업체별 비용
_buildAnalyticsSection(
'업체별 비용 현황',
Icons.business,
_buildVendorCosts(vendorCosts),
),
const SizedBox(height: 24),
// 통계 요약
_buildStatisticsSummary(maintenances),
],
),
);
}
Widget _buildAnalyticsSection(String title, IconData icon, Widget content) {
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withValues(alpha: 0.1),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(icon, color: Theme.of(context).primaryColor),
const SizedBox(width: 8),
Text(
title,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 16),
content,
],
),
);
}
Widget _buildMonthlyChart(Map<String, double> monthlyCosts) {
final sortedMonths = monthlyCosts.keys.toList()..sort();
return Column(
children: sortedMonths.map((month) {
final cost = monthlyCosts[month]!;
final maxCost = monthlyCosts.values.reduce((a, b) => a > b ? a : b);
final ratio = cost / maxCost;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
SizedBox(
width: 60,
child: Text(
month,
style: const TextStyle(fontSize: 12),
),
),
Expanded(
child: Stack(
children: [
Container(
height: 30,
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(4),
),
),
FractionallySizedBox(
widthFactor: ratio,
child: Container(
height: 30,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(4),
),
),
),
],
),
),
const SizedBox(width: 8),
Text(
'${NumberFormat('#,###').format(cost)}',
style: const TextStyle(fontSize: 12),
),
],
),
);
}).toList(),
);
}
Widget _buildTypeDistribution(Map<String, int> typeDistribution) {
final total = typeDistribution.values.fold<int>(0, (sum, count) => sum + count);
return Row(
children: typeDistribution.entries.map((entry) {
final percentage = (entry.value / total * 100).toStringAsFixed(1);
return Expanded(
child: Container(
padding: const EdgeInsets.all(16),
margin: const EdgeInsets.only(right: 8),
decoration: BoxDecoration(
color: entry.key == '현장' ? Colors.blue[50] : Colors.green[50],
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: entry.key == '현장' ? Colors.blue : Colors.green,
),
),
child: Column(
children: [
Icon(
entry.key == '현장' ? Icons.location_on : Icons.computer,
color: entry.key == '현장' ? Colors.blue : Colors.green,
size: 32,
),
const SizedBox(height: 8),
Text(
entry.key,
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
Text(
'${entry.value}',
style: const TextStyle(fontSize: 18),
),
Text(
'$percentage%',
style: TextStyle(
color: Colors.grey[600],
fontSize: 12,
),
),
],
),
),
);
}).toList(),
);
}
Widget _buildVendorCosts(Map<String, double> vendorCosts) {
final sortedVendors = vendorCosts.entries.toList()
..sort((a, b) => b.value.compareTo(a.value));
return Column(
children: sortedVendors.take(5).map((entry) {
return ListTile(
leading: CircleAvatar(
child: Text(entry.key.substring(0, 1).toUpperCase()),
),
title: Text(entry.key),
trailing: Text(
'${NumberFormat('#,###').format(entry.value)}',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
);
}).toList(),
);
}
Widget _buildStatisticsSummary(List<MaintenanceDto> maintenances) {
// 비용 대신 유지보수 기간 통계로 대체 (백엔드에 cost 필드 없음)
final totalMaintenances = maintenances.length;
final avgPeriod = maintenances.isNotEmpty
? maintenances.map((m) => m.periodMonth).reduce((a, b) => a + b) / maintenances.length
: 0.0;
final maxPeriod = maintenances.isNotEmpty
? maintenances.map((m) => m.periodMonth).reduce((a, b) => a > b ? a : b).toDouble()
: 0.0;
final minPeriod = maintenances.isNotEmpty
? maintenances.map((m) => m.periodMonth).reduce((a, b) => a < b ? a : b).toDouble()
: 0.0;
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Theme.of(context).primaryColor,
Theme.of(context).primaryColor.withValues(alpha: 0.8),
],
),
borderRadius: BorderRadius.circular(12),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'통계 요약',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_buildStatItem('총 건수', '${totalMaintenances}'),
_buildStatItem('평균 기간', '${avgPeriod.toStringAsFixed(1)}개월'),
_buildStatItem('최대 기간', '${maxPeriod.toInt()}개월'),
_buildStatItem('최소 기간', '${minPeriod.toInt()}개월'),
],
),
],
),
);
}
Widget _buildStatItem(String label, String value) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 12,
),
),
const SizedBox(height: 4),
Text(
value,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
],
);
}
void _selectDateRange() async {
final picked = await showDateRangePicker(
context: context,
firstDate: DateTime(2020),
lastDate: DateTime.now(),
initialDateRange: _selectedDateRange,
);
if (picked != null) {
setState(() {
_selectedDateRange = picked;
});
// 날짜 범위로 필터링
// TODO: 백엔드 API가 날짜 범위 필터를 지원하면 구현
}
}
void _showMaintenanceDetails(MaintenanceDto maintenance) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('유지보수 상세 정보'),
content: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_buildDetailRow('장비 이력 ID', '#${maintenance.equipmentHistoryId}'),
_buildDetailRow('유지보수 유형', maintenance.maintenanceType == 'O' ? '현장' : '원격'),
_buildDetailRow('시작일', maintenance.startedAt != null ? DateFormat('yyyy-MM-dd').format(maintenance.startedAt!) : 'N/A'),
_buildDetailRow('완료일', maintenance.endedAt != null ? DateFormat('yyyy-MM-dd').format(maintenance.endedAt!) : 'N/A'),
_buildDetailRow('주기', '${maintenance.periodMonth ?? 0}개월'),
_buildDetailRow('등록일', maintenance.registeredAt != null ? DateFormat('yyyy-MM-dd').format(maintenance.registeredAt!) : 'N/A'),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('닫기'),
),
],
),
);
}
Widget _buildDetailRow(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 120,
child: Text(
label,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
child: Text(value),
),
],
),
);
}
void _exportHistory() {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('엑셀 내보내기 기능은 준비 중입니다'),
backgroundColor: Colors.orange,
),
);
}
}

View File

@@ -0,0 +1,705 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../../data/models/maintenance_dto.dart';
import '../../domain/entities/maintenance_schedule.dart';
import 'controllers/maintenance_controller.dart';
import 'maintenance_form_dialog.dart';
import 'components/maintenance_calendar.dart';
class MaintenanceScheduleScreen extends StatefulWidget {
const MaintenanceScheduleScreen({super.key});
@override
State<MaintenanceScheduleScreen> createState() =>
_MaintenanceScheduleScreenState();
}
class _MaintenanceScheduleScreenState extends State<MaintenanceScheduleScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
bool _isCalendarView = false;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
// 초기 데이터 로드
WidgetsBinding.instance.addPostFrameCallback((_) {
final controller = context.read<MaintenanceController>();
controller.loadMaintenances(refresh: true);
controller.loadAlerts();
controller.loadStatistics();
});
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[100],
body: Column(
children: [
_buildHeader(),
_buildFilterBar(),
Expanded(
child: Consumer<MaintenanceController>(
builder: (context, controller, child) {
if (controller.isLoading && controller.maintenances.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (controller.error != null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'오류 발생',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 8),
Text(controller.error!),
const SizedBox(height: 16),
ElevatedButton(
onPressed:
() => controller.loadMaintenances(refresh: true),
child: const Text('다시 시도'),
),
],
),
);
}
return _isCalendarView
? MaintenanceCalendar(
maintenances: controller.maintenances,
onDateSelected: (date) {
// 날짜 선택시 해당 날짜의 유지보수 표시
_showMaintenancesForDate(date, controller.maintenances);
},
)
: _buildListView(controller);
},
),
),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: _showCreateMaintenanceDialog,
icon: const Icon(Icons.add),
label: const Text('유지보수 등록'),
backgroundColor: Theme.of(context).primaryColor,
),
);
}
Widget _buildHeader() {
return Container(
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withValues(alpha: 0.1),
spreadRadius: 1,
blurRadius: 3,
offset: const Offset(0, 2),
),
],
),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'유지보수 일정 관리',
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Consumer<MaintenanceController>(
builder: (context, controller, child) {
return Text(
'${controller.totalCount}건 | '
'예정 ${controller.upcomingCount}건 | '
'지연 ${controller.overdueCount}',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.grey[600],
),
);
},
),
],
),
Row(
children: [
IconButton(
icon: Icon(
_isCalendarView ? Icons.list : Icons.calendar_month,
),
onPressed: () {
setState(() {
_isCalendarView = !_isCalendarView;
});
},
tooltip: _isCalendarView ? '리스트 보기' : '캘린더 보기',
),
const SizedBox(width: 8),
IconButton(
icon: const Icon(Icons.refresh),
onPressed: () {
context.read<MaintenanceController>().loadMaintenances(
refresh: true,
);
},
tooltip: '새로고침',
),
],
),
],
),
const SizedBox(height: 16),
_buildStatisticsCards(),
],
),
);
}
Widget _buildStatisticsCards() {
return Consumer<MaintenanceController>(
builder: (context, controller, child) {
final stats = controller.statistics;
if (stats == null) return const SizedBox.shrink();
return Row(
children: [
Expanded(
child: _buildStatCard(
'전체 유지보수',
(stats['total'] ?? 0).toString(),
Icons.build_circle,
Colors.blue,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildStatCard(
'예정된 항목',
(stats['upcoming'] ?? 0).toString(),
Icons.schedule,
Colors.orange,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildStatCard(
'지연된 항목',
(stats['overdue'] ?? 0).toString(),
Icons.warning,
Colors.red,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildStatCard(
'진행 중',
(stats['inProgress'] ?? 0).toString(),
Icons.schedule_outlined,
Colors.green,
),
),
],
);
},
);
}
Widget _buildStatCard(
String title,
String value,
IconData icon,
Color color,
) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Icon(icon, color: color, size: 32),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
const SizedBox(height: 4),
Text(
value,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: color,
),
),
],
),
),
],
),
);
}
Widget _buildFilterBar() {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
decoration: BoxDecoration(
color: Colors.white,
border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
),
child: Row(
children: [
Expanded(
child: TextField(
decoration: InputDecoration(
hintText: '장비명, 일련번호로 검색',
prefixIcon: const Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide(color: Colors.grey[300]!),
),
contentPadding: const EdgeInsets.symmetric(horizontal: 16),
),
onChanged: (value) {
context.read<MaintenanceController>().setSearchQuery(value);
},
),
),
const SizedBox(width: 12),
PopupMenuButton<String>(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300]!),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: const [
Icon(Icons.filter_list),
SizedBox(width: 8),
Text('상태 필터'),
],
),
),
onSelected: (status) {
context.read<MaintenanceController>().setMaintenanceFilter(status);
},
itemBuilder:
(context) => [
const PopupMenuItem(value: null, child: Text('전체')),
const PopupMenuItem(
value: 'active',
child: Text('진행중 (시작됨, 완료되지 않음)'),
),
const PopupMenuItem(
value: 'completed',
child: Text('완료됨'),
),
const PopupMenuItem(
value: 'upcoming',
child: Text('예정됨'),
),
],
),
const SizedBox(width: 12),
PopupMenuButton<String>(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300]!),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: const [
Icon(Icons.sort),
SizedBox(width: 8),
Text('정렬'),
],
),
),
onSelected: (value) {
final parts = value.split('_');
context.read<MaintenanceController>().setSorting(
parts[0],
parts[1] == 'asc',
);
},
itemBuilder:
(context) => [
const PopupMenuItem(
value: 'started_at_asc',
child: Text('시작일 오름차순'),
),
const PopupMenuItem(
value: 'started_at_desc',
child: Text('시작일 내림차순'),
),
const PopupMenuItem(
value: 'registered_at_desc',
child: Text('최신 등록순'),
),
const PopupMenuItem(
value: 'period_month_desc',
child: Text('주기 긴 순'),
),
],
),
],
),
);
}
Widget _buildListView(MaintenanceController controller) {
if (controller.maintenances.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.build_circle_outlined,
size: 64,
color: Colors.grey[400],
),
const SizedBox(height: 16),
Text(
'등록된 유지보수가 없습니다',
style: Theme.of(
context,
).textTheme.titleLarge?.copyWith(color: Colors.grey[600]),
),
const SizedBox(height: 8),
Text('새로운 유지보수를 등록해주세요', style: TextStyle(color: Colors.grey[500])),
],
),
);
}
return ListView.builder(
padding: const EdgeInsets.all(24),
itemCount: controller.maintenances.length,
itemBuilder: (context, index) {
final maintenance = controller.maintenances[index];
return _buildMaintenanceCard(maintenance);
},
);
}
Widget _buildMaintenanceCard(MaintenanceDto maintenance) {
final schedule = context
.read<MaintenanceController>()
.getScheduleForMaintenance(maintenance.startedAt);
// generateAlert is not available, using null for now
final alert = null; // schedule?.generateAlert();
return Card(
margin: const EdgeInsets.only(bottom: 12),
child: InkWell(
onTap: () => _showMaintenanceDetails(maintenance),
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
_buildStatusChip(maintenance),
const SizedBox(width: 8),
_buildTypeChip(maintenance.maintenanceType),
const SizedBox(width: 8),
if (alert != null) _buildAlertChip(alert),
const Spacer(),
PopupMenuButton<String>(
onSelected:
(value) => _handleMaintenanceAction(value, maintenance),
itemBuilder:
(context) => [
const PopupMenuItem(value: 'edit', child: Text('수정')),
const PopupMenuItem(
value: 'toggle',
child: Text('상태 변경'),
),
const PopupMenuItem(
value: 'delete',
child: Text('삭제'),
),
],
),
],
),
const SizedBox(height: 12),
Text(
'Equipment History #${maintenance.equipmentHistoryId}',
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Row(
children: [
Icon(Icons.calendar_today, size: 16, color: Colors.grey[600]),
const SizedBox(width: 4),
Text(
'시작일: ${maintenance.startedAt ?? "미정"}',
style: TextStyle(color: Colors.grey[600]),
),
const SizedBox(width: 16),
Icon(Icons.check_circle, size: 16, color: Colors.grey[600]),
const SizedBox(width: 4),
Text(
'완료일: ${maintenance.endedAt ?? "미완료"}',
style: TextStyle(color: Colors.grey[600]),
),
],
),
const SizedBox(height: 8),
Row(
children: [
Icon(Icons.repeat, size: 16, color: Colors.grey[600]),
const SizedBox(width: 4),
Text(
'주기: ${maintenance.periodMonth ?? 0}개월',
style: TextStyle(color: Colors.grey[600]),
),
const SizedBox(width: 16),
Icon(Icons.settings, size: 16, color: Colors.grey[600]),
const SizedBox(width: 4),
Text(
'유형: ${maintenance.maintenanceType == 'O' ? '현장' : '원격'}',
style: TextStyle(color: Colors.grey[600]),
),
],
),
const SizedBox(height: 8),
Row(
children: [
Icon(Icons.schedule, size: 16, color: Colors.grey[600]),
const SizedBox(width: 4),
Text(
'등록일: ${DateFormat('yyyy-MM-dd').format(maintenance.registeredAt)}',
style: TextStyle(color: Colors.grey[600]),
),
],
),
],
),
),
),
);
}
Widget _buildStatusChip(MaintenanceDto maintenance) {
Color color;
String label;
// 백엔드 스키마 기준으로 상태 판단
if (maintenance.endedAt != null) {
// 완료됨
color = Colors.green;
label = '완료';
} else if (maintenance.startedAt != null) {
// 시작됐지만 완료되지 않음 (진행중)
color = Colors.orange;
label = '진행중';
} else {
// 아직 시작되지 않음 (예정)
color = Colors.blue;
label = '예정';
}
return Chip(
label: Text(label, style: const TextStyle(fontSize: 12)),
backgroundColor: color.withValues(alpha: 0.2),
side: BorderSide(color: color),
padding: const EdgeInsets.symmetric(horizontal: 8),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
}
Widget _buildTypeChip(String type) {
return Chip(
label: Text(
type == 'O' ? '현장' : '원격',
style: const TextStyle(fontSize: 12),
),
backgroundColor: Colors.grey[200],
padding: const EdgeInsets.symmetric(horizontal: 8),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
}
Widget _buildAlertChip(MaintenanceAlert alert) {
Color color;
switch (alert.priority) {
case AlertPriority.critical:
color = Colors.red;
break;
case AlertPriority.high:
color = Colors.orange;
break;
case AlertPriority.medium:
color = Colors.yellow[700]!;
break;
case AlertPriority.low:
color = Colors.blue;
break;
}
return Chip(
label: Text(
'${alert.daysUntilDue < 0 ? "지연 " : ""}${alert.daysUntilDue.abs()}',
style: TextStyle(fontSize: 12, color: Colors.white),
),
backgroundColor: color,
padding: const EdgeInsets.symmetric(horizontal: 8),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
}
void _showCreateMaintenanceDialog() {
showDialog(
context: context,
builder: (context) => const MaintenanceFormDialog(),
).then((result) {
if (result == true) {
context.read<MaintenanceController>().loadMaintenances(refresh: true);
}
});
}
void _showMaintenanceDetails(MaintenanceDto maintenance) {
showDialog(
context: context,
builder: (context) => MaintenanceFormDialog(maintenance: maintenance),
).then((result) {
if (result == true) {
context.read<MaintenanceController>().loadMaintenances(refresh: true);
}
});
}
void _handleMaintenanceAction(
String action,
MaintenanceDto maintenance,
) async {
final controller = context.read<MaintenanceController>();
switch (action) {
case 'edit':
_showMaintenanceDetails(maintenance);
break;
case 'toggle':
// TODO: 백엔드 스키마에 맞는 상태 변경 로직 구현 필요
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('상태 변경 기능은 준비 중입니다')),
);
break;
case 'delete':
final confirm = await showDialog<bool>(
context: context,
builder:
(context) => AlertDialog(
title: const Text('유지보수 삭제'),
content: const Text('정말로 이 유지보수를 삭제하시겠습니까?'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('취소'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text(
'삭제',
style: TextStyle(color: Colors.red),
),
),
],
),
);
if (confirm == true && maintenance.id != null) {
await controller.deleteMaintenance(maintenance.id!);
}
break;
}
}
void _showMaintenancesForDate(
DateTime date,
List<MaintenanceDto> maintenances,
) {
final dateMaintenances =
maintenances.where((m) {
// nextMaintenanceDate 필드가 백엔드에 없으므로 startedAt~endedAt 기간으로 확인
final targetDate = DateTime(date.year, date.month, date.day);
final startDate = DateTime(m.startedAt.year, m.startedAt.month, m.startedAt.day);
final endDate = DateTime(m.endedAt.year, m.endedAt.month, m.endedAt.day);
return (targetDate.isAfter(startDate) || targetDate.isAtSameMomentAs(startDate)) &&
(targetDate.isBefore(endDate) || targetDate.isAtSameMomentAs(endDate));
}).toList();
if (dateMaintenances.isEmpty) return;
showModalBottomSheet(
context: context,
builder:
(context) => Container(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${DateFormat('yyyy년 MM월 dd일').format(date)} 유지보수',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 16),
...dateMaintenances.map(
(m) => ListTile(
title: Text('Equipment History #${m.equipmentHistoryId}'),
subtitle: Text(
'${m.maintenanceType == "O" ? "현장" : "원격"} | ${m.periodMonth}개월 주기',
),
trailing: Text(
'${DateFormat('yyyy-MM-dd').format(m.endedAt)}', // 종료일로 대체
),
onTap: () {
Navigator.of(context).pop();
_showMaintenanceDetails(m);
},
),
),
],
),
),
);
}
}