기존엔 전체 승인이 장시간 요청도 구분 없이 다 승인해버렸음. 이제 1시간 59분 넘는 요청은 자동으로 빼고 대기중 상태로 남겨서, "많은 시간요청 학생" 목록에서 따로 검토 후 개별 승인/거절하게 함. 확인 다이얼로그에도 몇 건이 승인되고 몇 건이 제외되는지 미리 보여줌. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
197 lines
6.8 KiB
Dart
197 lines
6.8 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,
|
|
});
|
|
}
|
|
|
|
/// 🙌 [전체 학생 허용] 대상이 될 요청 id 목록 (대기 중이면서 장시간 요청은 아닌 것만).
|
|
/// 확인 다이얼로그에서 몇 건이 승인되고 몇 건이 제외되는지 미리 보여주는 데 쓴다.
|
|
List<int> get autoApprovableIds => _requests
|
|
.where((r) => r['status'] == 'PENDING' && !isLongRequest(r))
|
|
.map<int>((r) => r['id'] as int)
|
|
.toList();
|
|
|
|
// 🙌 [전체 학생 허용] 대기 중인 요청을 한 명씩 누르기 귀찮을 때, 한 번에 전부 승인한다.
|
|
// 단, 1시간 59분 넘는 장시간 요청은 자동으로 제외하고 대기중 상태로 남겨서,
|
|
// "많은 시간요청 학생" 목록에서 따로 검토/승인하게 한다.
|
|
// 서버에 일괄 승인 API가 따로 없어서, 대상 요청마다 승인 요청을 순서대로 보낸다.
|
|
Future<(bool success, String message)> approveAllPending({
|
|
required String teacherId,
|
|
required String teacherName,
|
|
}) async {
|
|
final targetIds = autoApprovableIds;
|
|
final excludedCount = longPendingRequests.length;
|
|
|
|
if (targetIds.isEmpty) {
|
|
return (
|
|
true,
|
|
excludedCount > 0
|
|
? '장시간 요청 $excludedCount건을 제외하면 승인할 대기 요청이 없습니다.'
|
|
: '승인 대기 중인 요청이 없습니다.',
|
|
);
|
|
}
|
|
|
|
_isWorking = true;
|
|
_safeNotify();
|
|
int successCount = 0;
|
|
for (final id in targetIds) {
|
|
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 == targetIds.length;
|
|
final excludedNote = excludedCount > 0
|
|
? ' (장시간 요청 $excludedCount건은 제외 - 대기중으로 남음)'
|
|
: '';
|
|
return (
|
|
allOk,
|
|
'${targetIds.length}건 중 $successCount건 승인 완료${allOk ? '' : ' (일부 실패)'}$excludedNote',
|
|
);
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|
|
}
|