MIF_E31231033/lib/services/notification_admin_service....

107 lines
3.0 KiB
Dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart';
import 'auth_service.dart';
class NotificationAdmin {
final int id;
final String title;
final String message;
final String createdAt;
final bool isRead;
final Map<String, dynamic>? extra;
NotificationAdmin({
required this.id,
required this.title,
required this.message,
required this.createdAt,
required this.isRead,
this.extra,
});
factory NotificationAdmin.fromJson(Map<String, dynamic> json) {
return NotificationAdmin(
id: json['id'],
title: json['title'] ?? '',
message: json['message'] ?? '',
createdAt: json['created_at'] ?? '',
isRead: json['is_read'] ?? false,
extra: json['extra'],
);
}
}
class NotificationAdminService {
static Future<List<NotificationAdmin>> getNotifications() async {
String? token = await AuthService.getToken();
final response = await http.get(
Uri.parse("${AuthService.baseUrl}/notifikasi"),
headers: {"Accept": "application/json", "Authorization": "Bearer $token"},
);
debugPrint("NOTIF STATUS: ${response.statusCode}");
debugPrint("NOTIF BODY: ${response.body}");
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final list = data['data'] as List;
return list.map((e) => NotificationAdmin.fromJson(e)).toList();
} else {
throw Exception('Gagal ambil notifikasi admin');
}
}
static Future<int> getUnreadCount() async {
String? token = await AuthService.getToken();
final response = await http.get(
Uri.parse("${AuthService.baseUrl}/notifikasi"),
headers: {"Accept": "application/json", "Authorization": "Bearer $token"},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
return data['unread_count'] ?? 0;
} else {
return 0;
}
}
static Future<void> markAsRead(int id) async {
String? token = await AuthService.getToken();
await http.put(
Uri.parse("${AuthService.baseUrl}/notifikasi/$id/read"),
headers: {"Accept": "application/json", "Authorization": "Bearer $token"},
);
}
static Future<void> markAllRead() async {
String? token = await AuthService.getToken();
await http.put(
Uri.parse("${AuthService.baseUrl}/notifikasi/read-all"),
headers: {"Accept": "application/json", "Authorization": "Bearer $token"},
);
}
static Future<void> deleteNotification(int id) async {
String? token = await AuthService.getToken();
await http.delete(
Uri.parse("${AuthService.baseUrl}/notifikasi/$id"),
headers: {"Accept": "application/json", "Authorization": "Bearer $token"},
);
}
static Future<void> deleteAllNotifications() async {
String? token = await AuthService.getToken();
await http.delete(
Uri.parse("${AuthService.baseUrl}/notifikasi"),
headers: {"Accept": "application/json", "Authorization": "Bearer $token"},
);
}
}