78 lines
2.2 KiB
Dart
78 lines
2.2 KiB
Dart
import 'package:get/get.dart';
|
|
import 'package:dio/dio.dart';
|
|
import '../../../core/storage/secure_storage.dart';
|
|
import '../../../core/utils/app_snackbar.dart';
|
|
import '../../../core/utils/logger.dart';
|
|
import '../../../app/routes/app_pages.dart';
|
|
|
|
class DashboardController extends GetxController {
|
|
final SecureStorage _storage = SecureStorage();
|
|
final Dio _dio = Dio(BaseOptions(
|
|
baseUrl: 'https://musadaq.intaleqapp.com/api/v1',
|
|
connectTimeout: const Duration(seconds: 15),
|
|
receiveTimeout: const Duration(seconds: 15),
|
|
responseType: ResponseType.json,
|
|
));
|
|
|
|
var isLoading = true.obs;
|
|
var stats = {}.obs;
|
|
var recentActivities = [].obs;
|
|
var userRole = ''.obs;
|
|
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
_loadDashboardData();
|
|
}
|
|
|
|
|
|
|
|
Future<void> _loadDashboardData() async {
|
|
try {
|
|
isLoading.value = true;
|
|
final token = await _storage.getToken();
|
|
|
|
if (token == null || token.isEmpty) {
|
|
Get.offAllNamed(AppRoutes.PHONE_INPUT);
|
|
return;
|
|
}
|
|
|
|
_dio.options.headers['Authorization'] = 'Bearer $token';
|
|
|
|
// Fetch Stats
|
|
final statsResponse = await _dio.get('/dashboard/stats');
|
|
if (statsResponse.data['success'] == true) {
|
|
stats.value = statsResponse.data['data'];
|
|
userRole.value = statsResponse.data['data']['role'] ?? '';
|
|
}
|
|
|
|
// Fetch Recent Activity
|
|
final activityResponse = await _dio.get('/dashboard/recent-activity');
|
|
if (activityResponse.data['success'] == true) {
|
|
recentActivities.value = activityResponse.data['data'];
|
|
}
|
|
} on DioException catch (e) {
|
|
AppLogger.error('Dashboard Data Fetch Error', e);
|
|
if (e.response?.statusCode == 401 || e.response?.statusCode == 403) {
|
|
await logout();
|
|
} else {
|
|
AppSnackbar.showError(
|
|
'خطأ', 'فشل في جلب البيانات. الرجاء التحقق من اتصالك بالإنترنت.');
|
|
}
|
|
} catch (e) {
|
|
AppLogger.error('Unexpected error fetching dashboard', e);
|
|
} finally {
|
|
isLoading.value = false;
|
|
}
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
await _storage.clearAll();
|
|
Get.offAllNamed(AppRoutes.PHONE_INPUT);
|
|
}
|
|
|
|
void refreshData() {
|
|
_loadDashboardData();
|
|
}
|
|
}
|