86 lines
2.4 KiB
Dart
86 lines
2.4 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;
|
||
|
|
|
||
|
|
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();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<(bool success, String message)> approve(int requestId) async {
|
||
|
|
return _postAction('/api/device-checkout/approve', requestId);
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<(bool success, String message)> reject(int requestId) async {
|
||
|
|
return _postAction('/api/device-checkout/reject', requestId);
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<(bool success, String message)> _postAction(
|
||
|
|
String path,
|
||
|
|
int requestId,
|
||
|
|
) async {
|
||
|
|
_isWorking = true;
|
||
|
|
_safeNotify();
|
||
|
|
try {
|
||
|
|
final response = await http.post(
|
||
|
|
Uri.parse('$baseUrl$path'),
|
||
|
|
headers: {"Content-Type": "application/json"},
|
||
|
|
body: jsonEncode({"requestId": requestId}),
|
||
|
|
);
|
||
|
|
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();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|