- Implemented ContactProfileResponse and related models for handling contact details. - Created ContactTagResponse and ContactTag models for managing contact tags. - Added DirectoryCommentResponse and DirectoryComment models for comment management. - Developed DirectoryFilterBottomSheet for filtering contacts. - Introduced OrganizationListModel for organization data handling. - Updated routes to include DirectoryMainScreen. - Enhanced DashboardScreen to navigate to the new directory page. - Created ContactDetailScreen for displaying detailed contact information. - Developed DirectoryMainScreen for managing and displaying contacts. - Added dependencies for font_awesome_flutter and flutter_html in pubspec.yaml.
295 lines
11 KiB
Dart
295 lines
11 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:flutter/material.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:image_picker/image_picker.dart';
|
|
import 'package:geolocator/geolocator.dart';
|
|
import 'package:intl/intl.dart';
|
|
import 'package:marco/helpers/services/app_logger.dart';
|
|
import 'package:marco/helpers/services/api_service.dart';
|
|
import 'package:marco/helpers/widgets/my_image_compressor.dart';
|
|
import 'package:marco/model/attendance_model.dart';
|
|
import 'package:marco/model/project_model.dart';
|
|
import 'package:marco/model/employee_model.dart';
|
|
import 'package:marco/model/attendance_log_model.dart';
|
|
import 'package:marco/model/regularization_log_model.dart';
|
|
import 'package:marco/model/attendance_log_view_model.dart';
|
|
import 'package:marco/controller/project_controller.dart';
|
|
|
|
class AttendanceController extends GetxController {
|
|
List<AttendanceModel> attendances = [];
|
|
List<ProjectModel> projects = [];
|
|
List<EmployeeModel> employees = [];
|
|
List<AttendanceLogModel> attendanceLogs = [];
|
|
List<RegularizationLogModel> regularizationLogs = [];
|
|
List<AttendanceLogViewModel> attendenceLogsView = [];
|
|
|
|
String selectedTab = 'Employee List';
|
|
|
|
DateTime? startDateAttendance;
|
|
DateTime? endDateAttendance;
|
|
|
|
RxBool isLoading = true.obs;
|
|
RxBool isLoadingProjects = true.obs;
|
|
RxBool isLoadingEmployees = true.obs;
|
|
RxBool isLoadingAttendanceLogs = true.obs;
|
|
RxBool isLoadingRegularizationLogs = true.obs;
|
|
RxBool isLoadingLogView = true.obs;
|
|
|
|
RxMap<String, RxBool> uploadingStates = <String, RxBool>{}.obs;
|
|
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
_initializeDefaults();
|
|
}
|
|
|
|
void _initializeDefaults() {
|
|
_setDefaultDateRange();
|
|
fetchProjects();
|
|
}
|
|
|
|
void _setDefaultDateRange() {
|
|
final today = DateTime.now();
|
|
startDateAttendance = today.subtract(const Duration(days: 7));
|
|
endDateAttendance = today.subtract(const Duration(days: 1));
|
|
logSafe("Default date range set: $startDateAttendance to $endDateAttendance");
|
|
}
|
|
|
|
Future<bool> _handleLocationPermission() async {
|
|
LocationPermission permission = await Geolocator.checkPermission();
|
|
if (permission == LocationPermission.denied) {
|
|
permission = await Geolocator.requestPermission();
|
|
if (permission == LocationPermission.denied) {
|
|
logSafe('Location permissions are denied', level: LogLevel.warning);
|
|
return false;
|
|
}
|
|
}
|
|
if (permission == LocationPermission.deniedForever) {
|
|
logSafe('Location permissions are permanently denied', level: LogLevel.error);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
Future<void> fetchProjects() async {
|
|
isLoadingProjects.value = true;
|
|
isLoading.value = true;
|
|
|
|
final response = await ApiService.getProjects();
|
|
if (response != null && response.isNotEmpty) {
|
|
projects = response.map((json) => ProjectModel.fromJson(json)).toList();
|
|
logSafe("Projects fetched: ${projects.length}");
|
|
} else {
|
|
logSafe("Failed to fetch projects or no projects available.", level: LogLevel.error);
|
|
projects = [];
|
|
}
|
|
|
|
isLoadingProjects.value = false;
|
|
isLoading.value = false;
|
|
update(['attendance_dashboard_controller']);
|
|
}
|
|
|
|
Future<void> loadAttendanceData(String projectId) async {
|
|
await fetchEmployeesByProject(projectId);
|
|
await fetchAttendanceLogs(projectId);
|
|
await fetchRegularizationLogs(projectId);
|
|
await fetchProjectData(projectId);
|
|
}
|
|
|
|
Future<void> fetchProjectData(String? projectId) async {
|
|
if (projectId == null) return;
|
|
isLoading.value = true;
|
|
await Future.wait([
|
|
fetchEmployeesByProject(projectId),
|
|
fetchAttendanceLogs(projectId, dateFrom: startDateAttendance, dateTo: endDateAttendance),
|
|
fetchRegularizationLogs(projectId),
|
|
]);
|
|
isLoading.value = false;
|
|
logSafe("Project data fetched for project ID: $projectId");
|
|
}
|
|
|
|
Future<void> fetchEmployeesByProject(String? projectId) async {
|
|
if (projectId == null) return;
|
|
isLoadingEmployees.value = true;
|
|
final response = await ApiService.getEmployeesByProject(projectId);
|
|
if (response != null) {
|
|
employees = response.map((json) => EmployeeModel.fromJson(json)).toList();
|
|
for (var emp in employees) {
|
|
uploadingStates[emp.id] = false.obs;
|
|
}
|
|
logSafe("Employees fetched: ${employees.length} for project $projectId");
|
|
update();
|
|
} else {
|
|
logSafe("Failed to fetch employees for project $projectId", level: LogLevel.error);
|
|
}
|
|
isLoadingEmployees.value = false;
|
|
}
|
|
|
|
Future<bool> captureAndUploadAttendance(
|
|
String id,
|
|
String employeeId,
|
|
String projectId, {
|
|
String comment = "Marked via mobile app",
|
|
required int action,
|
|
bool imageCapture = true,
|
|
String? markTime,
|
|
}) async {
|
|
try {
|
|
uploadingStates[employeeId]?.value = true;
|
|
XFile? image;
|
|
if (imageCapture) {
|
|
image = await ImagePicker().pickImage(source: ImageSource.camera, imageQuality: 80);
|
|
if (image == null) {
|
|
logSafe("Image capture cancelled.", level: LogLevel.warning);
|
|
return false;
|
|
}
|
|
final compressedBytes = await compressImageToUnder100KB(File(image.path));
|
|
if (compressedBytes == null) {
|
|
logSafe("Image compression failed.", level: LogLevel.error);
|
|
return false;
|
|
}
|
|
final compressedFile = await saveCompressedImageToFile(compressedBytes);
|
|
image = XFile(compressedFile.path);
|
|
}
|
|
final hasLocationPermission = await _handleLocationPermission();
|
|
if (!hasLocationPermission) return false;
|
|
final position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
|
|
final imageName = imageCapture ? ApiService.generateImageName(employeeId, employees.length + 1) : "";
|
|
|
|
final result = await ApiService.uploadAttendanceImage(
|
|
id, employeeId, image, position.latitude, position.longitude,
|
|
imageName: imageName, projectId: projectId, comment: comment,
|
|
action: action, imageCapture: imageCapture, markTime: markTime,
|
|
);
|
|
logSafe("Attendance uploaded for $employeeId, action: $action");
|
|
return result;
|
|
} catch (e, stacktrace) {
|
|
logSafe("Error uploading attendance", level: LogLevel.error, error: e, stackTrace: stacktrace);
|
|
return false;
|
|
} finally {
|
|
uploadingStates[employeeId]?.value = false;
|
|
}
|
|
}
|
|
|
|
Future<void> selectDateRangeForAttendance(BuildContext context, AttendanceController controller) async {
|
|
final today = DateTime.now();
|
|
final picked = await showDateRangePicker(
|
|
context: context,
|
|
firstDate: DateTime(2022),
|
|
lastDate: today.subtract(const Duration(days: 1)),
|
|
initialDateRange: DateTimeRange(
|
|
start: startDateAttendance ?? today.subtract(const Duration(days: 7)),
|
|
end: endDateAttendance ?? today.subtract(const Duration(days: 1)),
|
|
),
|
|
builder: (context, child) {
|
|
return Center(
|
|
child: SizedBox(
|
|
width: 400,
|
|
height: 500,
|
|
child: Theme(
|
|
data: Theme.of(context).copyWith(
|
|
colorScheme: ColorScheme.light(
|
|
primary: const Color.fromARGB(255, 95, 132, 255),
|
|
onPrimary: Colors.white,
|
|
onSurface: Colors.teal.shade800,
|
|
),
|
|
textButtonTheme: TextButtonThemeData(
|
|
style: TextButton.styleFrom(foregroundColor: Colors.teal),
|
|
),
|
|
dialogTheme: DialogThemeData(backgroundColor: Colors.white),
|
|
),
|
|
child: child!,
|
|
),
|
|
),
|
|
);
|
|
},
|
|
);
|
|
|
|
if (picked != null) {
|
|
startDateAttendance = picked.start;
|
|
endDateAttendance = picked.end;
|
|
logSafe("Date range selected: $startDateAttendance to $endDateAttendance");
|
|
await controller.fetchAttendanceLogs(
|
|
Get.find<ProjectController>().selectedProject?.id,
|
|
dateFrom: picked.start,
|
|
dateTo: picked.end,
|
|
);
|
|
}
|
|
}
|
|
|
|
Future<void> fetchAttendanceLogs(String? projectId, {DateTime? dateFrom, DateTime? dateTo}) async {
|
|
if (projectId == null) return;
|
|
isLoadingAttendanceLogs.value = true;
|
|
isLoading.value = true;
|
|
final response = await ApiService.getAttendanceLogs(projectId, dateFrom: dateFrom, dateTo: dateTo);
|
|
if (response != null) {
|
|
attendanceLogs = response.map((json) => AttendanceLogModel.fromJson(json)).toList();
|
|
logSafe("Attendance logs fetched: ${attendanceLogs.length}");
|
|
update();
|
|
} else {
|
|
logSafe("Failed to fetch attendance logs for project $projectId", level: LogLevel.error);
|
|
}
|
|
isLoadingAttendanceLogs.value = false;
|
|
isLoading.value = false;
|
|
}
|
|
|
|
Map<String, List<AttendanceLogModel>> groupLogsByCheckInDate() {
|
|
final groupedLogs = <String, List<AttendanceLogModel>>{};
|
|
for (var logItem in attendanceLogs) {
|
|
final checkInDate = logItem.checkIn != null
|
|
? DateFormat('dd MMM yyyy').format(logItem.checkIn!)
|
|
: 'Unknown';
|
|
groupedLogs.putIfAbsent(checkInDate, () => []);
|
|
groupedLogs[checkInDate]!.add(logItem);
|
|
}
|
|
final sortedEntries = groupedLogs.entries.toList()
|
|
..sort((a, b) {
|
|
if (a.key == 'Unknown') return 1;
|
|
if (b.key == 'Unknown') return -1;
|
|
final dateA = DateFormat('dd MMM yyyy').parse(a.key);
|
|
final dateB = DateFormat('dd MMM yyyy').parse(b.key);
|
|
return dateB.compareTo(dateA);
|
|
});
|
|
final sortedMap = Map<String, List<AttendanceLogModel>>.fromEntries(sortedEntries);
|
|
logSafe("Logs grouped and sorted by check-in date.");
|
|
return sortedMap;
|
|
}
|
|
|
|
Future<void> fetchRegularizationLogs(String? projectId, {DateTime? dateFrom, DateTime? dateTo}) async {
|
|
if (projectId == null) return;
|
|
isLoadingRegularizationLogs.value = true;
|
|
isLoading.value = true;
|
|
final response = await ApiService.getRegularizationLogs(projectId);
|
|
if (response != null) {
|
|
regularizationLogs = response.map((json) => RegularizationLogModel.fromJson(json)).toList();
|
|
logSafe("Regularization logs fetched: ${regularizationLogs.length}");
|
|
update();
|
|
} else {
|
|
logSafe("Failed to fetch regularization logs for project $projectId", level: LogLevel.error);
|
|
}
|
|
isLoadingRegularizationLogs.value = false;
|
|
isLoading.value = false;
|
|
}
|
|
|
|
Future<void> fetchLogsView(String? id) async {
|
|
if (id == null) return;
|
|
isLoadingLogView.value = true;
|
|
isLoading.value = true;
|
|
final response = await ApiService.getAttendanceLogView(id);
|
|
if (response != null) {
|
|
attendenceLogsView = response.map((json) => AttendanceLogViewModel.fromJson(json)).toList();
|
|
attendenceLogsView.sort((a, b) {
|
|
if (a.activityTime == null || b.activityTime == null) return 0;
|
|
return b.activityTime!.compareTo(a.activityTime!);
|
|
});
|
|
logSafe("Attendance log view fetched for ID: $id");
|
|
update();
|
|
} else {
|
|
logSafe("Failed to fetch attendance log view for ID $id", level: LogLevel.error);
|
|
}
|
|
isLoadingLogView.value = false;
|
|
isLoading.value = false;
|
|
}
|
|
}
|