59 lines
1.7 KiB
Dart
59 lines
1.7 KiB
Dart
import 'package:get/get.dart';
|
|
import '../../../core/network/dio_client.dart';
|
|
import '../../../core/utils/logger.dart';
|
|
|
|
class NotificationsController extends GetxController {
|
|
var notifications = <Map<String, dynamic>>[].obs;
|
|
var isLoading = true.obs;
|
|
var unreadCount = 0.obs;
|
|
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
fetchNotifications();
|
|
}
|
|
|
|
Future<void> fetchNotifications() async {
|
|
try {
|
|
isLoading.value = true;
|
|
final res = await DioClient().client.get('notifications');
|
|
if (res.data['success'] == true) {
|
|
final data = res.data['data'];
|
|
notifications.value = List<Map<String, dynamic>>.from(data['notifications'] ?? []);
|
|
unreadCount.value = data['unread_count'] ?? 0;
|
|
}
|
|
} catch (e) {
|
|
AppLogger.error('Failed to fetch notifications', e);
|
|
} finally {
|
|
isLoading.value = false;
|
|
}
|
|
}
|
|
|
|
Future<void> markAsRead(String id) async {
|
|
try {
|
|
await DioClient().client.post('notifications/read', data: {'id': id});
|
|
final idx = notifications.indexWhere((n) => n['id'] == id);
|
|
if (idx != -1) {
|
|
notifications[idx] = {...notifications[idx], 'is_read': 1};
|
|
notifications.refresh();
|
|
unreadCount.value = notifications.where((n) => n['is_read'] == 0).length;
|
|
}
|
|
} catch (e) {
|
|
AppLogger.error('Failed to mark as read', e);
|
|
}
|
|
}
|
|
|
|
Future<void> markAllRead() async {
|
|
try {
|
|
await DioClient().client.post('notifications/read', data: {'mark_all': true});
|
|
for (var i = 0; i < notifications.length; i++) {
|
|
notifications[i] = {...notifications[i], 'is_read': 1};
|
|
}
|
|
notifications.refresh();
|
|
unreadCount.value = 0;
|
|
} catch (e) {
|
|
AppLogger.error('Failed to mark all as read', e);
|
|
}
|
|
}
|
|
}
|