marco.pms.mobileapp/lib/helpers/services/permission_service.dart

69 lines
2.4 KiB
Dart

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:marco/model/user_permission.dart';
import 'package:marco/model/employee_info.dart';
import 'package:marco/model/projects_model.dart';
class PermissionService {
// Cache to store the fetched user profile data per token
static final Map<String, Map<String, dynamic>> _userDataCache = {};
// Method to fetch the user profile data (permissions, employee info, and projects)
static Future<Map<String, dynamic>> fetchAllUserData(String token) async {
// Check if the data for this token is already cached
if (_userDataCache.containsKey(token)) {
return _userDataCache[token]!;
}
try {
// Fetch data from the API
final response = await http.get(
Uri.parse('https://stageapi.marcoaiot.com/api/user/profile'),
headers: {'Authorization': 'Bearer $token'},
);
if (response.statusCode == 200) {
final data = json.decode(response.body)['data'];
// Parse and extract relevant information
final permissions = _parsePermissions(data['featurePermissions']);
final employeeInfo = _parseEmployeeInfo(data['employeeInfo']);
final projectsInfo = _parseProjectsInfo(data['projects']);
// Cache the processed data for later use
final allUserData = {
'permissions': permissions,
'employeeInfo': employeeInfo,
'projects': projectsInfo,
};
_userDataCache[token] = allUserData;
return allUserData;
} else {
final errorData = json.decode(response.body);
throw Exception('Failed to load data: ${errorData['message']}');
}
} catch (e) {
print('Error fetching user data: $e');
throw Exception('Error fetching user data: $e');
}
}
// Helper method to parse permissions from raw data
static List<UserPermission> _parsePermissions(List<dynamic> featurePermissions) {
return featurePermissions
.map<UserPermission>((id) => UserPermission.fromJson({'id': id}))
.toList();
}
// Helper method to parse employee info from raw data
static EmployeeInfo _parseEmployeeInfo(Map<String, dynamic> employeeData) {
return EmployeeInfo.fromJson(employeeData);
}
// Helper method to parse projects from raw data
static List<ProjectInfo> _parseProjectsInfo(List<dynamic> projectIds) {
return projectIds.map<ProjectInfo>((id) => ProjectInfo.fromJson(id)).toList();
}
}