기존엔 "많은 시간요청 학생" 팝업에서만 2시간 기준으로 걸러냈는데, 메인 목록 카드 자체에도 (대기중/승인/거절 등 상태 무관하게) 빨간 테두리를 씌워서 바로 눈에 띄게 함. 기준을 2시간 → 1시간 59분(119분)으로 낮춰서 두 기능이 같은 기준을 쓰도록 통일. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
181 lines
6.0 KiB
Dart
181 lines
6.0 KiB
Dart
// 📋 선생님용 "스마트기기 반출 대장" 화면의 기능(서버 통신/상태) 담당 컨트롤러.
|
|
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import '../config.dart';
|
|
|
|
class DeviceCheckoutLedgerController extends ChangeNotifier {
|
|
List<dynamic> _requests = [];
|
|
bool _isLoading = true;
|
|
bool _isWorking = false;
|
|
Timer? _timer;
|
|
bool _disposed = false;
|
|
|
|
List<dynamic> get requests => _requests;
|
|
bool get isLoading => _isLoading;
|
|
bool get isWorking => _isWorking;
|
|
|
|
// 🚨 [장시간 요청 기준] 1시간 59분(119분) 이상이면 "많은 시간요청"으로 본다.
|
|
static const int longRequestMinutes = 119;
|
|
|
|
int? _durationMinutes(dynamic request) {
|
|
try {
|
|
final start = DateTime.parse(request['requestedStart']);
|
|
final end = DateTime.parse(request['requestedEnd']);
|
|
final minutes = end.difference(start).inMinutes;
|
|
return minutes > 0 ? minutes : null;
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// ⏰ 요청 시간이 얼마나 되는지(시간 단위). 형식이 이상하면 null.
|
|
double? durationHours(dynamic request) {
|
|
final minutes = _durationMinutes(request);
|
|
return minutes == null ? null : minutes / 60.0;
|
|
}
|
|
|
|
/// 🚨 [장시간 요청 감지] 1시간 59분 넘게 신청했는지. 상태(대기/승인 등)와 무관하게 판단한다 -
|
|
/// 목록 카드에 빨간 테두리를 씌우는 데 쓴다.
|
|
bool isLongRequest(dynamic request) {
|
|
final minutes = _durationMinutes(request);
|
|
return minutes != null && minutes >= longRequestMinutes;
|
|
}
|
|
|
|
/// 학생이 시간을 비정상적으로 길게 적어냈을 수 있으니, 아직 대기 중인 장시간 요청만
|
|
/// 따로 모아서 전체 승인 전에 훑어볼 수 있게 한다.
|
|
List<dynamic> get longPendingRequests => _requests
|
|
.where((r) => r['status'] == 'PENDING' && isLongRequest(r))
|
|
.toList();
|
|
|
|
void _safeNotify() {
|
|
if (!_disposed) notifyListeners();
|
|
}
|
|
|
|
void init() {
|
|
fetchAll();
|
|
_timer = Timer.periodic(const Duration(seconds: 5), (_) => fetchAll());
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_disposed = true;
|
|
_timer?.cancel();
|
|
super.dispose();
|
|
}
|
|
|
|
Future<void> fetchAll() async {
|
|
try {
|
|
final response = await http.get(
|
|
Uri.parse('$baseUrl/api/device-checkout/list'),
|
|
);
|
|
if (response.statusCode == 200) {
|
|
final data = jsonDecode(utf8.decode(response.bodyBytes));
|
|
_requests = data['requests'] ?? [];
|
|
}
|
|
} catch (_) {
|
|
// 새로고침 실패는 조용히 무시하고 마지막으로 받아온 목록을 유지한다.
|
|
} finally {
|
|
_isLoading = false;
|
|
_safeNotify();
|
|
}
|
|
}
|
|
|
|
// ✅ 승인 시 승인한 선생님 계정을 함께 보낸다 (대장에 "OOO 선생님이 허용했습니다" 표시 +
|
|
// 미반납 알림을 그 선생님에게만 보내기 위함).
|
|
Future<(bool success, String message)> approve(
|
|
int requestId, {
|
|
required String teacherId,
|
|
required String teacherName,
|
|
}) async {
|
|
return _postAction('/api/device-checkout/approve', {
|
|
"requestId": requestId,
|
|
"teacherId": teacherId,
|
|
"teacherName": teacherName,
|
|
});
|
|
}
|
|
|
|
// 🙌 [전체 학생 허용] 대기 중인 요청을 한 명씩 누르기 귀찮을 때, 한 번에 전부 승인한다.
|
|
// 서버에 일괄 승인 API가 따로 없어서, 대기 중인 요청마다 승인 요청을 순서대로 보낸다.
|
|
Future<(bool success, String message)> approveAllPending({
|
|
required String teacherId,
|
|
required String teacherName,
|
|
}) async {
|
|
final pendingIds = _requests
|
|
.where((r) => r['status'] == 'PENDING')
|
|
.map<int>((r) => r['id'] as int)
|
|
.toList();
|
|
if (pendingIds.isEmpty) {
|
|
return (true, '승인 대기 중인 요청이 없습니다.');
|
|
}
|
|
|
|
_isWorking = true;
|
|
_safeNotify();
|
|
int successCount = 0;
|
|
for (final id in pendingIds) {
|
|
try {
|
|
final response = await http.post(
|
|
Uri.parse('$baseUrl/api/device-checkout/approve'),
|
|
headers: {"Content-Type": "application/json"},
|
|
body: jsonEncode({
|
|
"requestId": id,
|
|
"teacherId": teacherId,
|
|
"teacherName": teacherName,
|
|
}),
|
|
);
|
|
final result = jsonDecode(utf8.decode(response.bodyBytes));
|
|
if (response.statusCode == 200 && result['status'] == 'success') {
|
|
successCount++;
|
|
}
|
|
} catch (_) {
|
|
// 개별 요청 실패는 건너뛰고 나머지는 계속 진행한다.
|
|
}
|
|
}
|
|
await fetchAll();
|
|
_isWorking = false;
|
|
_safeNotify();
|
|
|
|
final allOk = successCount == pendingIds.length;
|
|
return (
|
|
allOk,
|
|
'${pendingIds.length}건 중 $successCount건 승인 완료${allOk ? '' : ' (일부 실패)'}',
|
|
);
|
|
}
|
|
|
|
Future<(bool success, String message)> reject(int requestId) async {
|
|
return _postAction('/api/device-checkout/reject', {"requestId": requestId});
|
|
}
|
|
|
|
// 🖐️ [하드웨어 자동 감지 전까지 임시] 선생님이 기기를 실제로 돌려받았을 때 누르는 버튼.
|
|
Future<(bool success, String message)> confirmReturn(int requestId) async {
|
|
return _postAction('/api/device-checkout/return', {"requestId": requestId});
|
|
}
|
|
|
|
Future<(bool success, String message)> _postAction(
|
|
String path,
|
|
Map<String, dynamic> body,
|
|
) async {
|
|
_isWorking = true;
|
|
_safeNotify();
|
|
try {
|
|
final response = await http.post(
|
|
Uri.parse('$baseUrl$path'),
|
|
headers: {"Content-Type": "application/json"},
|
|
body: jsonEncode(body),
|
|
);
|
|
final result = jsonDecode(utf8.decode(response.bodyBytes));
|
|
if (response.statusCode == 200 && result['status'] == 'success') {
|
|
await fetchAll();
|
|
return (true, '${result['message'] ?? '처리되었습니다.'}');
|
|
}
|
|
return (false, '${result['message'] ?? '처리 실패'}');
|
|
} catch (e) {
|
|
return (false, '네트워크 에러: $e');
|
|
} finally {
|
|
_isWorking = false;
|
|
_safeNotify();
|
|
}
|
|
}
|
|
}
|