made chnages into attendence screen

This commit is contained in:
Vaibhav Surve 2025-05-06 17:47:43 +05:30
parent dd31cdafd0
commit defd753ab0
4 changed files with 625 additions and 438 deletions

View File

@ -3,6 +3,7 @@ import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:geolocator/geolocator.dart'; import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:logger/logger.dart';
import 'package:marco/helpers/services/api_service.dart'; import 'package:marco/helpers/services/api_service.dart';
import 'package:marco/model/attendance_model.dart'; import 'package:marco/model/attendance_model.dart';
@ -12,8 +13,6 @@ import 'package:marco/model/attendance_log_model.dart';
import 'package:marco/model/regularization_log_model.dart'; import 'package:marco/model/regularization_log_model.dart';
import 'package:marco/model/attendance_log_view_model.dart'; import 'package:marco/model/attendance_log_view_model.dart';
import 'package:logger/logger.dart';
final Logger log = Logger(); final Logger log = Logger();
class AttendanceController extends GetxController { class AttendanceController extends GetxController {
@ -30,6 +29,7 @@ class AttendanceController extends GetxController {
List<AttendanceLogViewModel> attendenceLogsView = []; List<AttendanceLogViewModel> attendenceLogsView = [];
RxBool isLoading = false.obs; RxBool isLoading = false.obs;
RxMap<String, RxBool> uploadingStates = <String, RxBool>{}.obs;
@override @override
void onInit() { void onInit() {
@ -88,8 +88,13 @@ class AttendanceController extends GetxController {
if (response != null) { if (response != null) {
employees = response.map((json) => EmployeeModel.fromJson(json)).toList(); employees = response.map((json) => EmployeeModel.fromJson(json)).toList();
log.i(
"Employees fetched: ${employees.length} employees for project $projectId"); // Initialize per-employee uploading state
for (var emp in employees) {
uploadingStates[emp.id] = false.obs;
}
log.i("Employees fetched: ${employees.length} employees for project $projectId");
update(); update();
} else { } else {
log.e("Failed to fetch employees for project $projectId"); log.e("Failed to fetch employees for project $projectId");
@ -105,6 +110,8 @@ class AttendanceController extends GetxController {
bool imageCapture = true, bool imageCapture = true,
}) async { }) async {
try { try {
uploadingStates[employeeId]?.value = true;
XFile? image; XFile? image;
if (imageCapture) { if (imageCapture) {
image = await ImagePicker().pickImage( image = await ImagePicker().pickImage(
@ -113,6 +120,7 @@ class AttendanceController extends GetxController {
); );
if (image == null) { if (image == null) {
log.w("Image capture cancelled."); log.w("Image capture cancelled.");
uploadingStates[employeeId]?.value = false;
return false; return false;
} }
} }
@ -143,6 +151,8 @@ class AttendanceController extends GetxController {
} catch (e, stacktrace) { } catch (e, stacktrace) {
log.e("Error uploading attendance", error: e, stackTrace: stacktrace); log.e("Error uploading attendance", error: e, stackTrace: stacktrace);
return false; return false;
} finally {
uploadingStates[employeeId]?.value = false;
} }
} }
@ -212,8 +222,21 @@ class AttendanceController extends GetxController {
groupedLogs[checkInDate]!.add(logItem); groupedLogs[checkInDate]!.add(logItem);
} }
log.i("Logs grouped by check-in date."); // Sort by date descending
return groupedLogs; 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);
log.i("Logs grouped and sorted by check-in date.");
return sortedMap;
} }
Future<void> fetchRegularizationLogs( Future<void> fetchRegularizationLogs(
@ -228,9 +251,8 @@ class AttendanceController extends GetxController {
isLoading.value = false; isLoading.value = false;
if (response != null) { if (response != null) {
regularizationLogs = response regularizationLogs =
.map((json) => RegularizationLogModel.fromJson(json)) response.map((json) => RegularizationLogModel.fromJson(json)).toList();
.toList();
log.i("Regularization logs fetched: ${regularizationLogs.length}"); log.i("Regularization logs fetched: ${regularizationLogs.length}");
update(); update();
} else { } else {
@ -246,9 +268,8 @@ class AttendanceController extends GetxController {
isLoading.value = false; isLoading.value = false;
if (response != null) { if (response != null) {
attendenceLogsView = response attendenceLogsView =
.map((json) => AttendanceLogViewModel.fromJson(json)) response.map((json) => AttendanceLogViewModel.fromJson(json)).toList();
.toList();
log.i("Attendance log view fetched for ID: $id"); log.i("Attendance log view fetched for ID: $id");
update(); update();
} else { } else {

View File

@ -4,7 +4,7 @@ import 'package:flutter/material.dart';
class ButtonActions { class ButtonActions {
static const String checkIn = "Check In"; static const String checkIn = "Check In";
static const String checkOut = "Check Out"; static const String checkOut = "Check Out";
static const String requestRegularize = " Request Regularize"; static const String requestRegularize = "Regularize";
static const String rejected = "Rejected"; static const String rejected = "Rejected";
static const String approved = "Approved"; static const String approved = "Approved";
static const String requested = "Requested"; static const String requested = "Requested";

View File

@ -1,3 +1,4 @@
import 'dart:math' as math;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:marco/helpers/widgets/my_spacing.dart'; import 'package:marco/helpers/widgets/my_spacing.dart';
import 'package:marco/helpers/widgets/my_text.dart'; import 'package:marco/helpers/widgets/my_text.dart';
@ -9,18 +10,22 @@ class MyPaginatedTable extends StatefulWidget {
final List<DataRow> rows; final List<DataRow> rows;
final double columnSpacing; final double columnSpacing;
final double horizontalMargin; final double horizontalMargin;
final bool isLoading;
final Widget? footer;
const MyPaginatedTable({ const MyPaginatedTable({
super.key, super.key,
this.title, this.title,
required this.columns, required this.columns,
required this.rows, required this.rows,
this.columnSpacing = 23, this.columnSpacing = 20,
this.horizontalMargin = 35, this.horizontalMargin = 0,
this.isLoading = false,
this.footer,
}); });
@override @override
_MyPaginatedTableState createState() => _MyPaginatedTableState(); State<MyPaginatedTable> createState() => _MyPaginatedTableState();
} }
class _MyPaginatedTableState extends State<MyPaginatedTable> { class _MyPaginatedTableState extends State<MyPaginatedTable> {
@ -29,22 +34,30 @@ class _MyPaginatedTableState extends State<MyPaginatedTable> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final visibleRows = widget.rows.skip(_start).take(_rowsPerPage).toList();
final totalRows = widget.rows.length; final totalRows = widget.rows.length;
final totalPages = (totalRows / _rowsPerPage).ceil(); final totalPages = (totalRows / _rowsPerPage).ceil();
final currentPage = (_start / _rowsPerPage).ceil() + 1; final currentPage = (_start ~/ _rowsPerPage) + 1;
final visibleRows = widget.rows.skip(_start).take(_rowsPerPage).toList();
if (widget.isLoading) {
return const Center(child: CircularProgressIndicator());
}
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
if (widget.title != null) if (widget.title != null)
Padding( Padding(
padding: MySpacing.xy(8, 6), // Using standard spacing for title padding: MySpacing.xy(8, 6),
child: MyText.titleMedium(widget.title!, fontWeight: 600, fontSize: 20), child: MyText.titleMedium(
widget.title!,
fontWeight: 600,
fontSize: 20,
),
), ),
if (widget.rows.isEmpty) if (widget.rows.isEmpty)
Padding( Padding(
padding: MySpacing.all(16), // Standard padding for empty state padding: MySpacing.all(16),
child: MyText.bodySmall('No data available'), child: MyText.bodySmall('No data available'),
), ),
if (widget.rows.isNotEmpty) if (widget.rows.isNotEmpty)
@ -53,63 +66,75 @@ class _MyPaginatedTableState extends State<MyPaginatedTable> {
final spacing = _calculateSmartSpacing(constraints.maxWidth); final spacing = _calculateSmartSpacing(constraints.maxWidth);
return SingleChildScrollView( return SingleChildScrollView(
scrollDirection: Axis.horizontal, scrollDirection: Axis.horizontal,
child: MyContainer.bordered( child: ConstrainedBox(
borderColor: Colors.black.withAlpha(40), constraints: BoxConstraints(minWidth: constraints.maxWidth),
padding: EdgeInsets.zero, child: MyContainer.bordered(
child: DataTable( borderColor: Colors.black.withAlpha(40),
columns: widget.columns, padding: const EdgeInsets.all(10),
rows: visibleRows, child: DataTable(
columnSpacing: spacing, columns: widget.columns,
horizontalMargin: widget.horizontalMargin, rows: visibleRows,
columnSpacing: spacing,
horizontalMargin: widget.horizontalMargin,
headingRowHeight: 48,
dataRowHeight: 44,
),
), ),
), ),
); );
}, },
), ),
MySpacing.height(8), // Standard height spacing after table const SizedBox(height: 8),
PaginatedFooter( widget.footer ??
currentPage: currentPage, PaginatedFooter(
totalPages: totalPages, currentPage: currentPage,
onPrevious: () { totalPages: totalPages,
setState(() { totalRows: totalRows,
_start = (_start - _rowsPerPage).clamp(0, totalRows - _rowsPerPage); onPrevious: _handlePrevious,
}); onNext: _handleNext,
}, onPageChanged: _handlePageChanged,
onNext: () { onPageSizeChanged: _handlePageSizeChanged,
setState(() { ),
_start = (_start + _rowsPerPage).clamp(0, totalRows - _rowsPerPage);
});
},
onPageSizeChanged: (newRowsPerPage) {
setState(() {
_rowsPerPage = newRowsPerPage;
_start = 0;
});
},
),
], ],
); );
} }
void _handlePrevious() {
setState(() {
_start = (_start - _rowsPerPage)
.clamp(0, math.max(0, widget.rows.length - _rowsPerPage));
});
}
void _handleNext() {
setState(() {
_start = (_start + _rowsPerPage)
.clamp(0, math.max(0, widget.rows.length - _rowsPerPage));
});
}
void _handlePageChanged(int page) {
setState(() {
_start = (page - 1) * _rowsPerPage;
});
}
void _handlePageSizeChanged(int newRowsPerPage) {
setState(() {
_rowsPerPage = newRowsPerPage;
_start = 0;
});
}
double _calculateSmartSpacing(double maxWidth) { double _calculateSmartSpacing(double maxWidth) {
int columnCount = widget.columns.length; final columnCount = widget.columns.length;
double horizontalPadding = widget.horizontalMargin * 2; final horizontalPadding = widget.horizontalMargin * 2;
double availableWidth = maxWidth - horizontalPadding; final availableWidth = maxWidth - horizontalPadding;
// Desired min/max column spacing
const double minSpacing = 16; const double minSpacing = 16;
const double maxSpacing = 80; const double maxSpacing = 64;
// Total width assuming minimal spacing double spacing = (availableWidth / columnCount) - 40;
double minTotalWidth = (columnCount * minSpacing) + horizontalPadding;
if (minTotalWidth >= availableWidth) {
// Not enough room return minimal spacing
return minSpacing;
}
// Fit evenly within the available width
double spacing = (availableWidth / columnCount) - 40; // 40 for estimated cell content width
return spacing.clamp(minSpacing, maxSpacing); return spacing.clamp(minSpacing, maxSpacing);
} }
} }
@ -117,62 +142,102 @@ class _MyPaginatedTableState extends State<MyPaginatedTable> {
class PaginatedFooter extends StatelessWidget { class PaginatedFooter extends StatelessWidget {
final int currentPage; final int currentPage;
final int totalPages; final int totalPages;
final int totalRows;
final VoidCallback onPrevious; final VoidCallback onPrevious;
final VoidCallback onNext; final VoidCallback onNext;
final Function(int) onPageChanged;
final Function(int) onPageSizeChanged; final Function(int) onPageSizeChanged;
const PaginatedFooter({ const PaginatedFooter({
super.key,
required this.currentPage, required this.currentPage,
required this.totalPages, required this.totalPages,
required this.totalRows,
required this.onPrevious, required this.onPrevious,
required this.onNext, required this.onNext,
required this.onPageChanged,
required this.onPageSizeChanged, required this.onPageSizeChanged,
}); });
List<Widget> _buildPageButtons() {
List<Widget> pages = [];
void addPageButton(int page) {
pages.add(
Padding(
padding: const EdgeInsets.symmetric(horizontal: 2),
child: TextButton(
onPressed: () => onPageChanged(page),
style: TextButton.styleFrom(
backgroundColor: currentPage == page ? Colors.blue : null,
foregroundColor:
currentPage == page ? Colors.white : Colors.black,
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2),
minimumSize: const Size(32, 28),
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(12),
),
textStyle: const TextStyle(fontSize: 12),
),
child: Text('$page'),
),
),
);
}
if (totalPages <= 5) {
for (int i = 1; i <= totalPages; i++) {
addPageButton(i);
}
} else {
addPageButton(1);
if (currentPage > 3) {
pages.add(const Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Text('...'),
));
}
for (int i = math.max(2, currentPage - 1);
i <= math.min(totalPages - 1, currentPage + 1);
i++) {
addPageButton(i);
}
if (currentPage < totalPages - 2) {
pages.add(const Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Text('...'),
));
}
addPageButton(totalPages);
}
return pages;
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Padding( return Padding(
padding: MySpacing.x(16), // Standard horizontal spacing for footer padding: MySpacing.all(0),
child: SingleChildScrollView( child: Row(
scrollDirection: Axis.horizontal, mainAxisAlignment: MainAxisAlignment.end,
child: Row( children: [
mainAxisAlignment: MainAxisAlignment.end, IconButton(
children: [ onPressed: currentPage > 1 ? onPrevious : null,
if (currentPage > 1) icon: const Icon(Icons.chevron_left),
IconButton( tooltip: 'Previous',
onPressed: onPrevious, ),
icon: Icon(Icons.chevron_left), ..._buildPageButtons(),
), IconButton(
Text( onPressed: currentPage < totalPages ? onNext : null,
'Page $currentPage of $totalPages', icon: const Icon(Icons.chevron_right),
style: TextStyle( tooltip: 'Next',
fontSize: 16, ),
color: Theme.of(context).colorScheme.onBackground, ],
),
),
SizedBox(width: 8),
if (currentPage < totalPages)
IconButton(
onPressed: onNext,
icon: Icon(Icons.chevron_right),
),
SizedBox(width: 16),
PopupMenuButton<int>(
icon: Icon(Icons.more_vert),
onSelected: (value) {
onPageSizeChanged(value);
},
itemBuilder: (BuildContext context) {
return [5, 10, 20, 50].map((e) {
return PopupMenuItem<int>(
value: e,
child: Text('$e rows per page'),
);
}).toList();
},
),
],
),
), ),
); );
} }

View File

@ -241,7 +241,8 @@ class _AttendanceScreenState extends State<AttendanceScreen> with UIMixin {
Widget employeeListTab() { Widget employeeListTab() {
if (attendanceController.employees.isEmpty) { if (attendanceController.employees.isEmpty) {
return Center( return Center(
child: MyText.bodySmall("No Employees Found", fontWeight: 600), child: MyText.bodySmall("No Employees Assigned to This Project",
fontWeight: 600),
); );
} }
@ -273,62 +274,89 @@ class _AttendanceScreenState extends State<AttendanceScreen> with UIMixin {
), ),
), ),
DataCell( DataCell(
ElevatedButton( Obx(() {
onPressed: () async { final isUploading = attendanceController
if (attendanceController.selectedProjectId == null) { .uploadingStates[employee.employeeId]?.value ??
ScaffoldMessenger.of(context).showSnackBar( false;
const SnackBar( final controller = attendanceController;
content: Text("Please select a project first")), return SizedBox(
); width: 90,
return; height: 25,
} child: ElevatedButton(
onPressed: isUploading
? null
: () async {
controller.uploadingStates[employee.employeeId] =
RxBool(true);
if (controller.selectedProjectId == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Please select a project first")),
);
controller.uploadingStates[employee.employeeId] =
RxBool(false);
return;
}
final updatedAction =
(activity == 0 || activity == 4) ? 0 : 1;
final actionText = (updatedAction == 0)
? ButtonActions.checkIn
: ButtonActions.checkOut;
final success =
await controller.captureAndUploadAttendance(
employee.id,
employee.employeeId,
controller.selectedProjectId!,
comment: actionText,
action: updatedAction,
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(success
? 'Attendance marked successfully!'
: 'Image upload failed.'),
),
);
int updatedAction = (activity == 0 || activity == 4) ? 0 : 1; controller.uploadingStates[employee.employeeId] =
String actionText = (updatedAction == 0) RxBool(false);
? ButtonActions.checkIn
: ButtonActions.checkOut;
final success = if (success) {
await attendanceController.captureAndUploadAttendance( await Future.wait([
employee.id, controller.fetchEmployeesByProject(
employee.employeeId, controller.selectedProjectId!),
attendanceController.selectedProjectId!, controller.fetchAttendanceLogs(
comment: actionText, controller.selectedProjectId!),
action: updatedAction, controller.fetchProjectData(
); controller.selectedProjectId!),
]);
ScaffoldMessenger.of(context).showSnackBar( controller.update();
SnackBar( }
content: Text(success },
? 'Attendance marked successfully!' style: ElevatedButton.styleFrom(
: 'Image upload failed.'), backgroundColor: AttendanceActionColors.colors[buttonText],
textStyle: const TextStyle(fontSize: 12),
), ),
); child: isUploading
? const SizedBox(
if (success) { width: 16,
attendanceController.fetchEmployeesByProject( height: 16,
attendanceController.selectedProjectId!); child: CircularProgressIndicator(
attendanceController.fetchAttendanceLogs( strokeWidth: 2,
attendanceController.selectedProjectId!); valueColor:
attendanceController AlwaysStoppedAnimation<Color>(Colors.white),
.fetchProjectData(attendanceController.selectedProjectId!); ),
attendanceController.update(); )
} : Text(buttonText),
}, ),
style: ElevatedButton.styleFrom( );
backgroundColor: AttendanceActionColors.colors[buttonText], }),
padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 6),
minimumSize: const Size(60, 20),
textStyle: const TextStyle(fontSize: 12),
),
child: Text(buttonText),
),
), ),
]); ]);
}).toList(); }).toList();
return Padding( return Padding(
padding: const EdgeInsets.all(8.0), // You can adjust this as needed padding: const EdgeInsets.all(0.0),
child: SingleChildScrollView( child: SingleChildScrollView(
child: MyPaginatedTable( child: MyPaginatedTable(
columns: columns, columns: columns,
@ -360,10 +388,10 @@ class _AttendanceScreenState extends State<AttendanceScreen> with UIMixin {
// Add a row for the check-in date as a header // Add a row for the check-in date as a header
rows.add(DataRow(cells: [ rows.add(DataRow(cells: [
DataCell(MyText.bodyMedium(checkInDate, fontWeight: 600)), DataCell(MyText.bodyMedium(checkInDate, fontWeight: 600)),
DataCell(MyText.bodyMedium('')), // Placeholder for other columns DataCell(MyText.bodyMedium('')),
DataCell(MyText.bodyMedium('')), // Placeholder for other columns DataCell(MyText.bodyMedium('')),
DataCell(MyText.bodyMedium('')), // Placeholder for other columns DataCell(MyText.bodyMedium('')),
DataCell(MyText.bodyMedium('')), // Placeholder for other columns DataCell(MyText.bodyMedium('')),
])); ]));
// Add rows for each log in this group // Add rows for each log in this group
@ -385,12 +413,6 @@ class _AttendanceScreenState extends State<AttendanceScreen> with UIMixin {
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// MyText.bodyMedium(
// log.checkIn != null
// ? DateFormat('dd MMM yyyy').format(log.checkIn!)
// : '-',
// fontWeight: 600,
// ),
MyText.bodyMedium( MyText.bodyMedium(
log.checkIn != null log.checkIn != null
? DateFormat('hh:mm a').format(log.checkIn!) ? DateFormat('hh:mm a').format(log.checkIn!)
@ -405,12 +427,6 @@ class _AttendanceScreenState extends State<AttendanceScreen> with UIMixin {
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// MyText.bodyMedium(
// log.checkOut != null
// ? DateFormat('dd MMM yyyy').format(log.checkOut!)
// : '-',
// fontWeight: 600,
// ),
MyText.bodyMedium( MyText.bodyMedium(
log.checkOut != null log.checkOut != null
? DateFormat('hh:mm a').format(log.checkOut!) ? DateFormat('hh:mm a').format(log.checkOut!)
@ -427,6 +443,7 @@ class _AttendanceScreenState extends State<AttendanceScreen> with UIMixin {
await attendanceController.fetchLogsView(log.id.toString()); await attendanceController.fetchLogsView(log.id.toString());
showModalBottomSheet( showModalBottomSheet(
context: context, context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder( shape: const RoundedRectangleBorder(
borderRadius: borderRadius:
BorderRadius.vertical(top: Radius.circular(16)), BorderRadius.vertical(top: Radius.circular(16)),
@ -434,145 +451,167 @@ class _AttendanceScreenState extends State<AttendanceScreen> with UIMixin {
backgroundColor: Theme.of(context).cardColor, backgroundColor: Theme.of(context).cardColor,
builder: (context) { builder: (context) {
return Padding( return Padding(
padding: const EdgeInsets.all(16.0), padding: EdgeInsets.only(
child: Column( left: 16,
mainAxisSize: MainAxisSize.min, right: 16,
crossAxisAlignment: CrossAxisAlignment.start, top: 16,
children: [ bottom: MediaQuery.of(context).viewInsets.bottom + 16,
MyText.titleMedium("Attendance Log Details", ),
fontWeight: 700), child: SingleChildScrollView(
const SizedBox(height: 16), child: Column(
if (attendanceController mainAxisSize: MainAxisSize.min,
.attendenceLogsView.isNotEmpty) ...[ crossAxisAlignment: CrossAxisAlignment.start,
Row( children: [
mainAxisAlignment: MainAxisAlignment.spaceBetween, MyText.titleMedium("Attendance Log Details",
children: [ fontWeight: 700),
Expanded( const SizedBox(height: 16),
child: MyText.bodyMedium("Date", if (attendanceController
fontWeight: 600)), .attendenceLogsView.isNotEmpty) ...[
Expanded( Row(
child: MyText.bodyMedium("Time", mainAxisAlignment:
fontWeight: 600)), MainAxisAlignment.spaceBetween,
Expanded( children: [
child: MyText.bodyMedium("Description", Expanded(
fontWeight: 600)), child: MyText.bodyMedium("Date",
Expanded( fontWeight: 600)),
child: MyText.bodyMedium("Image", Expanded(
fontWeight: 600)), child: MyText.bodyMedium("Time",
], fontWeight: 600)),
), Expanded(
const Divider(thickness: 1, height: 24), child: MyText.bodyMedium("Description",
], fontWeight: 600)),
if (attendanceController Expanded(
.attendenceLogsView.isNotEmpty) child: MyText.bodyMedium("Image",
...attendanceController.attendenceLogsView fontWeight: 600)),
.map((log) => Row( ],
mainAxisAlignment: ),
MainAxisAlignment.spaceBetween, const Divider(thickness: 1, height: 24),
children: [ ],
Expanded( if (attendanceController
child: MyText.bodyMedium( .attendenceLogsView.isNotEmpty)
log.formattedDate ?? '-', ...attendanceController.attendenceLogsView
fontWeight: 600)), .map((log) => Padding(
Expanded( padding: const EdgeInsets.symmetric(
child: MyText.bodyMedium( vertical: 8.0),
log.formattedTime ?? '-', child: Row(
fontWeight: 600)), mainAxisAlignment:
Expanded( MainAxisAlignment.spaceBetween,
child: Row( children: [
children: [ Expanded(
if (log.latitude != null &&
log.longitude != null)
GestureDetector(
onTap: () async {
final url =
'https://www.google.com/maps/search/?api=1&query=${log.latitude},${log.longitude}';
if (await canLaunchUrl(
Uri.parse(url))) {
await launchUrl(
Uri.parse(url),
mode: LaunchMode
.externalApplication);
} else {
ScaffoldMessenger.of(
context)
.showSnackBar(
const SnackBar(
content: Text(
'Could not open Google Maps')),
);
}
},
child: const Padding(
padding: EdgeInsets.only(
right: 4.0),
child: Icon(
Icons.location_on,
size: 18,
color: Colors.blue),
),
),
Expanded(
child: MyText.bodyMedium( child: MyText.bodyMedium(
log.comment ?? '-', log.formattedDate ?? '-',
fontWeight: 600, fontWeight: 600)),
), Expanded(
), child: MyText.bodyMedium(
], log.formattedTime ?? '-',
), fontWeight: 600)),
), Expanded(
Expanded( child: Row(
child: GestureDetector( children: [
onTap: () { if (log.latitude != null &&
if (log.preSignedUrl != null) { log.longitude != null)
showDialog( GestureDetector(
context: context, onTap: () async {
builder: (_) => Dialog( final url =
child: Image.network( 'https://www.google.com/maps/search/?api=1&query=${log.latitude},${log.longitude}';
log.preSignedUrl!, if (await canLaunchUrl(
fit: BoxFit.cover, Uri.parse(url))) {
height: 400, await launchUrl(
errorBuilder: (context, Uri.parse(url),
error, stackTrace) { mode: LaunchMode
return Icon( .externalApplication);
Icons.broken_image, } else {
size: 50, ScaffoldMessenger.of(
color: Colors.grey); context)
.showSnackBar(
const SnackBar(
content: Text(
'Could not open Google Maps')),
);
}
}, },
child: const Padding(
padding:
EdgeInsets.only(
right: 4.0),
child: Icon(
Icons.location_on,
size: 18,
color: Colors.blue),
),
),
Expanded(
child: MyText.bodyMedium(
log.comment ?? '-',
fontWeight: 600,
), ),
), ),
); ],
} ),
}, ),
child: log.thumbPreSignedUrl != null Expanded(
? Image.network( child: GestureDetector(
log.thumbPreSignedUrl!, onTap: () {
height: 40, if (log.preSignedUrl !=
width: 40, null) {
fit: BoxFit.cover, showDialog(
errorBuilder: (context, context: context,
error, stackTrace) { builder: (_) => Dialog(
return Icon( child: Image.network(
Icons.broken_image, log.preSignedUrl!,
size: 40, fit: BoxFit.cover,
color: Colors.grey); height: 400,
}, errorBuilder:
) (context, error,
: Icon(Icons.broken_image, stackTrace) {
size: 40, return const Icon(
color: Colors.grey), Icons
), .broken_image,
size: 50,
color: Colors
.grey);
},
),
),
);
}
},
child: log.thumbPreSignedUrl !=
null
? Image.network(
log.thumbPreSignedUrl!,
height: 40,
width: 40,
fit: BoxFit.cover,
errorBuilder: (context,
error, stackTrace) {
return const Icon(
Icons
.broken_image,
size: 40,
color:
Colors.grey);
},
)
: const Icon(
Icons.broken_image,
size: 40,
color: Colors.grey),
),
),
],
), ),
], )),
)), const SizedBox(height: 16),
Align( Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: ElevatedButton( child: ElevatedButton(
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
child: const Text("Close"), child: const Text("Close"),
),
), ),
), ],
], ),
), ),
); );
}, },
@ -581,141 +620,205 @@ class _AttendanceScreenState extends State<AttendanceScreen> with UIMixin {
), ),
), ),
DataCell( DataCell(
ElevatedButton( Obx(() {
onPressed: (log.activity == 5 || // Check if any record for this employee is uploading
log.activity == 2 || // Add this condition for activity 2 final uniqueLogKey = '${log.employeeId}_${log.id}';
(log.activity == 4 && final isUploading =
!(log.checkOut != null && attendanceController.uploadingStates[uniqueLogKey]?.value ??
false;
// Check if both checkIn and checkOut exist and the date is yesterday
final isYesterday = log.checkIn != null &&
log.checkOut != null &&
DateUtils.isSameDay(log.checkIn!,
DateTime.now().subtract(Duration(days: 1))) &&
DateUtils.isSameDay(log.checkOut!,
DateTime.now().subtract(Duration(days: 1)));
return SizedBox(
width: 90,
height: 25,
child: ElevatedButton(
onPressed: isUploading ||
isYesterday ||
log.activity == 2 ||
log.activity == 5 ||
(log.activity == 4 &&
!(DateUtils.isSameDay(
log.checkIn ?? DateTime(2000),
DateTime.now())))
? null
: () async {
// Set the uploading state for the employee when the action starts
attendanceController.uploadingStates[uniqueLogKey] =
RxBool(true);
if (attendanceController.selectedProjectId == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Please select a project first"),
),
);
attendanceController.uploadingStates[uniqueLogKey] =
RxBool(false);
return;
}
// Existing logic for updating action
int updatedAction;
String actionText;
bool imageCapture = true;
if (log.activity == 0) {
updatedAction = 0;
actionText = "Check In";
} else if (log.activity == 1) {
DateTime currentDate = DateTime.now();
DateTime twoDaysAgo =
currentDate.subtract(Duration(days: 2));
if (log.checkOut == null &&
log.checkIn != null &&
log.checkIn!.isBefore(twoDaysAgo)) {
updatedAction = 2;
actionText = "Request Regularize";
imageCapture = false;
} else if (log.checkOut != null &&
log.checkOut!.isBefore(twoDaysAgo)) {
updatedAction = 2;
actionText = "Request Regularize";
} else {
updatedAction = 1;
actionText = "Check Out";
}
} else if (log.activity == 2) {
updatedAction = 2;
actionText = "Request Regularize";
} else if (log.activity == 4 &&
log.checkOut != null &&
log.checkIn != null && log.checkIn != null &&
DateTime.now().difference(log.checkIn!).inDays <= DateTime.now().difference(log.checkIn!).inDays <=
2))) 2) {
? null updatedAction = 0;
: () async { actionText = "Check In";
if (attendanceController.selectedProjectId == null) { } else {
ScaffoldMessenger.of(context).showSnackBar( updatedAction = 0;
const SnackBar( actionText = "Unknown Action";
content: Text("Please select a project first"), }
// Proceed with capturing and uploading attendance
final success = await attendanceController
.captureAndUploadAttendance(
log.id,
log.employeeId,
attendanceController.selectedProjectId!,
comment: actionText,
action: updatedAction,
imageCapture: imageCapture,
);
// Show result in SnackBar
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(success
? 'Attendance marked successfully!'
: 'Failed to mark attendance.'),
),
);
// Reset the uploading state after the action is complete
attendanceController.uploadingStates[uniqueLogKey] =
RxBool(false);
if (success) {
// Update the UI with the new data
attendanceController.fetchEmployeesByProject(
attendanceController.selectedProjectId!);
attendanceController.fetchAttendanceLogs(
attendanceController.selectedProjectId!);
await attendanceController.fetchRegularizationLogs(
attendanceController.selectedProjectId!);
await attendanceController.fetchProjectData(
attendanceController.selectedProjectId!);
attendanceController.update();
}
},
style: ElevatedButton.styleFrom(
backgroundColor: isYesterday
? Colors
.grey // Button color for the disabled state (Yesterday's date)
: (log.activity == 4 &&
log.checkOut != null &&
log.checkIn != null &&
DateTime.now()
.difference(log.checkIn!)
.inDays <=
2)
? Colors.green
: AttendanceActionColors.colors[(log.activity == 0)
? ButtonActions.checkIn
: ButtonActions.checkOut],
padding:
const EdgeInsets.symmetric(vertical: 4, horizontal: 6),
textStyle: const TextStyle(fontSize: 12),
),
child: isUploading
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor:
AlwaysStoppedAnimation<Color>(Colors.white),
), ),
); )
return; : Text(
} (log.activity == 5)
? ButtonActions.rejected
int updatedAction; : (log.activity == 4 &&
String actionText; log.checkOut != null &&
bool imageCapture = true; log.checkIn != null &&
if (log.activity == 0) { DateTime.now()
updatedAction = 0; .difference(log.checkIn!)
actionText = "Check In"; .inDays <=
} else if (log.activity == 1) { 2)
DateTime currentDate = DateTime.now(); ? ButtonActions.checkIn
DateTime twoDaysAgo = : (log.activity == 2)
currentDate.subtract(Duration(days: 2)); ? "Requested"
: (log.activity == 4)
if (log.checkOut == null && ? ButtonActions.approved
log.checkIn != null && : (log.activity == 0 &&
log.checkIn!.isBefore(twoDaysAgo)) { !(log.checkIn != null &&
updatedAction = 2; log.checkOut != null &&
actionText = "Request Regularize"; !DateUtils.isSameDay(
imageCapture = false; log.checkIn!,
} else if (log.checkOut != null && DateTime.now())))
log.checkOut!.isBefore(twoDaysAgo)) { ? ButtonActions.checkIn
updatedAction = 2; : (log.activity == 1 &&
actionText = "Request Regularize"; log.checkOut != null &&
} else { DateTime.now()
updatedAction = 1; .difference(
actionText = "Check Out"; log.checkOut!)
} .inDays <=
} else if (log.activity == 2) { 2)
updatedAction = 2; ? ButtonActions.checkOut
actionText = "Request Regularize"; : (log.activity == 2 ||
} else if (log.activity == 4 && (log.activity == 1 &&
log.checkOut != null && log.checkOut ==
log.checkIn != null && null &&
DateTime.now().difference(log.checkIn!).inDays <= 2) { log.checkIn !=
updatedAction = 0; null &&
actionText = "Check In"; log.checkIn!.isBefore(
} else { DateTime.now()
updatedAction = 0; .subtract(Duration(
actionText = "Unknown Action"; days:
} 2)))))
? ButtonActions
final success = .requestRegularize
await attendanceController.captureAndUploadAttendance( : ButtonActions.checkOut,
log.id,
log.employeeId,
attendanceController.selectedProjectId!,
comment: actionText,
action: updatedAction,
imageCapture: imageCapture,
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(success
? 'Attendance marked successfully!'
: 'Image upload failed.'),
), ),
); ),
);
if (success) { }),
attendanceController.fetchEmployeesByProject( )
attendanceController.selectedProjectId!);
attendanceController.fetchAttendanceLogs(
attendanceController.selectedProjectId!);
await attendanceController.fetchRegularizationLogs(
attendanceController.selectedProjectId!);
await attendanceController.fetchProjectData(
attendanceController.selectedProjectId!);
attendanceController.update();
}
},
style: ElevatedButton.styleFrom(
backgroundColor: (log.activity == 4 &&
log.checkOut != null &&
log.checkIn != null &&
DateTime.now().difference(log.checkIn!).inDays <= 2)
? Colors.green
: AttendanceActionColors.colors[(log.activity == 0)
? ButtonActions.checkIn
: ButtonActions.checkOut],
padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 6),
minimumSize: const Size(60, 20),
textStyle: const TextStyle(fontSize: 12),
),
child: Text(
(log.activity == 5)
? ButtonActions.rejected
: (log.activity == 4 &&
log.checkOut != null &&
log.checkIn != null &&
DateTime.now().difference(log.checkIn!).inDays <= 2)
? ButtonActions.checkIn
: (log.activity == 2) // Change text when activity is 2
? "Requested"
: (log.activity == 4)
? ButtonActions.approved
: (log.activity == 0)
? ButtonActions.checkIn
: (log.activity == 1 &&
log.checkOut != null &&
DateTime.now()
.difference(log.checkOut!)
.inDays <=
2)
? ButtonActions.checkOut
: (log.activity == 2 ||
(log.activity == 1 &&
log.checkOut == null &&
log.checkIn != null &&
log.checkIn!.isBefore(
DateTime.now().subtract(
Duration(
days: 2)))))
? ButtonActions.requestRegularize
: ButtonActions.checkOut,
),
),
),
])); ]));
} }
}); });
@ -749,7 +852,6 @@ class _AttendanceScreenState extends State<AttendanceScreen> with UIMixin {
child: MyPaginatedTable( child: MyPaginatedTable(
columns: columns, columns: columns,
rows: rows, rows: rows,
columnSpacing: 8.0,
), ),
), ),
], ],
@ -951,7 +1053,6 @@ class _AttendanceScreenState extends State<AttendanceScreen> with UIMixin {
Expanded( Expanded(
child: SingleChildScrollView( child: SingleChildScrollView(
child: MyPaginatedTable( child: MyPaginatedTable(
// Use MyPaginatedTable here for pagination
columns: columns, columns: columns,
rows: rows, rows: rows,
columnSpacing: 15.0, columnSpacing: 15.0,