feat: Enhance AttendanceLogViewButton with state management and improved log display

This commit is contained in:
Vaibhav Surve 2025-09-25 14:42:22 +05:30
parent 7c21324b42
commit 98612db7b5
2 changed files with 335 additions and 188 deletions

View File

@ -1,57 +1,114 @@
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
class AttendanceLogViewModel { class Employee {
final DateTime? activityTime; final String id;
final String? imageUrl; final String firstName;
final String? comment; final String lastName;
final String? thumbPreSignedUrl; final String? photo;
final String? preSignedUrl; final String jobRoleId;
final String? longitude; final String jobRoleName;
final String? latitude;
final int? activity;
AttendanceLogViewModel({ Employee({
this.activityTime, required this.id,
this.imageUrl, required this.firstName,
this.comment, required this.lastName,
this.thumbPreSignedUrl, this.photo,
this.preSignedUrl, required this.jobRoleId,
this.longitude, required this.jobRoleName,
this.latitude,
required this.activity,
}); });
factory AttendanceLogViewModel.fromJson(Map<String, dynamic> json) { factory Employee.fromJson(Map<String, dynamic> json) {
return AttendanceLogViewModel( return Employee(
activityTime: json['activityTime'] != null id: json['id'],
? DateTime.tryParse(json['activityTime']) firstName: json['firstName'] ?? '',
: null, lastName: json['lastName'] ?? '',
imageUrl: json['imageUrl']?.toString(), photo: json['photo']?.toString(),
comment: json['comment']?.toString(), jobRoleId: json['jobRoleId'] ?? '',
thumbPreSignedUrl: json['thumbPreSignedUrl']?.toString(), jobRoleName: json['jobRoleName'] ?? '',
preSignedUrl: json['preSignedUrl']?.toString(),
longitude: json['longitude']?.toString(),
latitude: json['latitude']?.toString(),
activity: json['activity'] ?? 0,
); );
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {
'activityTime': activityTime?.toIso8601String(), 'id': id,
'imageUrl': imageUrl, 'firstName': firstName,
'lastName': lastName,
'photo': photo,
'jobRoleId': jobRoleId,
'jobRoleName': jobRoleName,
};
}
}
class AttendanceLogViewModel {
final String id;
final String? comment;
final Employee employee;
final DateTime? activityTime;
final int activity;
final String? photo;
final String? thumbPreSignedUrl;
final String? preSignedUrl;
final String? longitude;
final String? latitude;
final DateTime? updatedOn;
final Employee? updatedByEmployee;
final String? documentId;
AttendanceLogViewModel({
required this.id,
this.comment,
required this.employee,
this.activityTime,
required this.activity,
this.photo,
this.thumbPreSignedUrl,
this.preSignedUrl,
this.longitude,
this.latitude,
this.updatedOn,
this.updatedByEmployee,
this.documentId,
});
factory AttendanceLogViewModel.fromJson(Map<String, dynamic> json) {
return AttendanceLogViewModel(
id: json['id'],
comment: json['comment']?.toString(),
employee: Employee.fromJson(json['employee']),
activityTime: json['activityTime'] != null ? DateTime.tryParse(json['activityTime']) : null,
activity: json['activity'] ?? 0,
photo: json['photo']?.toString(),
thumbPreSignedUrl: json['thumbPreSignedUrl']?.toString(),
preSignedUrl: json['preSignedUrl']?.toString(),
longitude: json['longitude']?.toString(),
latitude: json['latitude']?.toString(),
updatedOn: json['updatedOn'] != null ? DateTime.tryParse(json['updatedOn']) : null,
updatedByEmployee: json['updatedByEmployee'] != null ? Employee.fromJson(json['updatedByEmployee']) : null,
documentId: json['documentId']?.toString(),
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'comment': comment, 'comment': comment,
'employee': employee.toJson(),
'activityTime': activityTime?.toIso8601String(),
'activity': activity,
'photo': photo,
'thumbPreSignedUrl': thumbPreSignedUrl, 'thumbPreSignedUrl': thumbPreSignedUrl,
'preSignedUrl': preSignedUrl, 'preSignedUrl': preSignedUrl,
'longitude': longitude, 'longitude': longitude,
'latitude': latitude, 'latitude': latitude,
'activity': activity, 'updatedOn': updatedOn?.toIso8601String(),
'updatedByEmployee': updatedByEmployee?.toJson(),
'documentId': documentId,
}; };
} }
String? get formattedDate => activityTime != null String? get formattedDate =>
? DateFormat('yyyy-MM-dd').format(activityTime!) activityTime != null ? DateFormat('yyyy-MM-dd').format(activityTime!) : null;
: null;
String? get formattedTime => String? get formattedTime =>
activityTime != null ? DateFormat('hh:mm a').format(activityTime!) : null; activityTime != null ? DateFormat('hh:mm a').format(activityTime!) : null;

View File

@ -2,16 +2,24 @@ import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
import 'package:marco/helpers/widgets/my_text.dart'; import 'package:marco/helpers/widgets/my_text.dart';
import 'package:marco/helpers/utils/base_bottom_sheet.dart'; import 'package:marco/helpers/utils/base_bottom_sheet.dart';
import 'package:marco/helpers/utils/date_time_utils.dart';
class AttendanceLogViewButton extends StatelessWidget { class AttendanceLogViewButton extends StatefulWidget {
final dynamic employee; final dynamic employee;
final dynamic attendanceController; final dynamic attendanceController;
const AttendanceLogViewButton({ const AttendanceLogViewButton({
Key? key, Key? key,
required this.employee, required this.employee,
required this.attendanceController, required this.attendanceController,
}) : super(key: key); }) : super(key: key);
@override
State<AttendanceLogViewButton> createState() =>
_AttendanceLogViewButtonState();
}
class _AttendanceLogViewButtonState extends State<AttendanceLogViewButton> {
Future<void> _openGoogleMaps( Future<void> _openGoogleMaps(
BuildContext context, double lat, double lon) async { BuildContext context, double lat, double lon) async {
final url = 'https://www.google.com/maps/search/?api=1&query=$lat,$lon'; final url = 'https://www.google.com/maps/search/?api=1&query=$lat,$lon';
@ -48,7 +56,8 @@ class AttendanceLogViewButton extends StatelessWidget {
} }
void _showLogsBottomSheet(BuildContext context) async { void _showLogsBottomSheet(BuildContext context) async {
await attendanceController.fetchLogsView(employee.id.toString()); await widget.attendanceController
.fetchLogsView(widget.employee.id.toString());
showModalBottomSheet( showModalBottomSheet(
context: context, context: context,
@ -57,157 +66,238 @@ class AttendanceLogViewButton extends StatelessWidget {
borderRadius: BorderRadius.vertical(top: Radius.circular(16)), borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
), ),
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
builder: (context) => BaseBottomSheet( builder: (context) {
title: "Attendance Log", Map<int, bool> expandedDescription = {};
onCancel: () => Navigator.pop(context),
onSubmit: () => Navigator.pop(context), return BaseBottomSheet(
showButtons: false, title: "Attendance Log",
child: attendanceController.attendenceLogsView.isEmpty onCancel: () => Navigator.pop(context),
? Padding( onSubmit: () => Navigator.pop(context),
padding: const EdgeInsets.symmetric(vertical: 24.0), showButtons: false,
child: Column( child: widget.attendanceController.attendenceLogsView.isEmpty
children: const [ ? Padding(
Icon(Icons.info_outline, size: 40, color: Colors.grey), padding: const EdgeInsets.symmetric(vertical: 24.0),
SizedBox(height: 8), child: Column(
Text("No attendance logs available."), children: [
], Icon(Icons.info_outline, size: 40, color: Colors.grey),
), SizedBox(height: 8),
) MyText.bodySmall("No attendance logs available."),
: ListView.separated( ],
shrinkWrap: true, ),
physics: const NeverScrollableScrollPhysics(), )
itemCount: attendanceController.attendenceLogsView.length, : StatefulBuilder(
separatorBuilder: (_, __) => const SizedBox(height: 16), builder: (context, setStateSB) {
itemBuilder: (_, index) { return ListView.separated(
final log = attendanceController.attendenceLogsView[index]; shrinkWrap: true,
return Container( physics: const NeverScrollableScrollPhysics(),
decoration: BoxDecoration( itemCount:
color: Theme.of(context).colorScheme.surfaceVariant, widget.attendanceController.attendenceLogsView.length,
borderRadius: BorderRadius.circular(12), separatorBuilder: (_, __) => const SizedBox(height: 16),
boxShadow: [ itemBuilder: (_, index) {
BoxShadow( final log = widget
color: Colors.black.withOpacity(0.05), .attendanceController.attendenceLogsView[index];
blurRadius: 6,
offset: const Offset(0, 2), return Container(
) decoration: BoxDecoration(
], color: Theme.of(context).colorScheme.surfaceVariant,
), borderRadius: BorderRadius.circular(12),
padding: const EdgeInsets.all(8), boxShadow: [
child: Column( BoxShadow(
crossAxisAlignment: CrossAxisAlignment.start, color: Colors.black.withOpacity(0.05),
children: [ blurRadius: 6,
Row( offset: const Offset(0, 2),
crossAxisAlignment: CrossAxisAlignment.center, )
children: [ ],
Expanded( ),
flex: 3, padding: const EdgeInsets.all(12),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Header: Icon + Date + Time
Row(
children: [ children: [
Row( _getLogIcon(log),
children: [ const SizedBox(width: 12),
_getLogIcon(log), MyText.bodyLarge(
const SizedBox(width: 10), (log.formattedDate != null &&
Column( log.formattedDate!.isNotEmpty)
crossAxisAlignment: ? DateTimeUtils.convertUtcToLocal(
CrossAxisAlignment.start, log.formattedDate!,
children: [ format: 'd MMM yyyy',
MyText.bodyLarge( )
log.formattedDate ?? '-', : '-',
fontWeight: 600, fontWeight: 600,
),
MyText.bodySmall(
"Time: ${log.formattedTime ?? '-'}",
color: Colors.grey[700],
),
],
),
],
), ),
const SizedBox(height: 12), const SizedBox(width: 12),
Row( MyText.bodySmall(
crossAxisAlignment: log.formattedTime != null
CrossAxisAlignment.start, ? "Time: ${log.formattedTime}"
children: [ : "",
if (log.latitude != null && color: Colors.grey[700],
log.longitude != null)
GestureDetector(
onTap: () {
final lat = double.tryParse(
log.latitude.toString()) ??
0.0;
final lon = double.tryParse(
log.longitude.toString()) ??
0.0;
if (lat >= -90 &&
lat <= 90 &&
lon >= -180 &&
lon <= 180) {
_openGoogleMaps(
context, lat, lon);
} else {
ScaffoldMessenger.of(context)
.showSnackBar(
const SnackBar(
content: Text(
'Invalid location coordinates')),
);
}
},
child: const Padding(
padding:
EdgeInsets.only(right: 8.0),
child: Icon(Icons.location_on,
size: 18, color: Colors.blue),
),
),
Expanded(
child: MyText.bodyMedium(
log.comment?.isNotEmpty == true
? log.comment
: "No description provided",
fontWeight: 500,
),
),
],
), ),
], ],
), ),
), const SizedBox(height: 12),
const SizedBox(width: 16), const Divider(height: 1, color: Colors.grey),
if (log.thumbPreSignedUrl != null) // Middle Row: Image + Text (Done by, Description & Location)
GestureDetector( Row(
onTap: () { crossAxisAlignment: CrossAxisAlignment.start,
if (log.preSignedUrl != null) { children: [
_showImageDialog( // Image Column
context, log.preSignedUrl!); if (log.thumbPreSignedUrl != null)
} GestureDetector(
}, onTap: () {
child: ClipRRect( if (log.preSignedUrl != null) {
borderRadius: BorderRadius.circular(8), _showImageDialog(
child: Image.network( context, log.preSignedUrl!);
log.thumbPreSignedUrl!, }
height: 60, },
width: 60, child: ClipRRect(
fit: BoxFit.cover, borderRadius: BorderRadius.circular(8),
errorBuilder: (context, error, stackTrace) { child: Image.network(
return const Icon(Icons.broken_image, log.thumbPreSignedUrl!,
size: 20, color: Colors.grey); height: 60,
}, width: 60,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) =>
const Icon(Icons.broken_image,
size: 40, color: Colors.grey),
),
),
),
if (log.thumbPreSignedUrl != null)
const SizedBox(width: 12),
// Text Column
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
// Done by
if (log.updatedByEmployee != null)
MyText.bodySmall(
"By: ${log.updatedByEmployee!.firstName} ${log.updatedByEmployee!.lastName}",
color: Colors.grey[700],
),
const SizedBox(height: 8),
// Location
if (log.latitude != null &&
log.longitude != null)
Row(
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
GestureDetector(
onTap: () {
final lat = double.tryParse(
log.latitude
.toString()) ??
0.0;
final lon = double.tryParse(
log.longitude
.toString()) ??
0.0;
if (lat >= -90 &&
lat <= 90 &&
lon >= -180 &&
lon <= 180) {
_openGoogleMaps(
context, lat, lon);
} else {
ScaffoldMessenger.of(
context)
.showSnackBar(
SnackBar(
content: MyText.bodySmall(
"Invalid location coordinates")),
);
}
},
child: Row(
children: [
Icon(Icons.location_on,
size: 16,
color: Colors.blue),
SizedBox(width: 4),
MyText.bodySmall(
"View Location",
color: Colors.blue,
decoration:
TextDecoration.underline,
),
],
),
),
],
),
const SizedBox(height: 8),
// Description with label and more/less using MyText
if (log.comment != null &&
log.comment!.isNotEmpty)
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
MyText.bodySmall(
"Description: ${log.comment!}",
maxLines: expandedDescription[
index] ==
true
? null
: 2,
overflow: expandedDescription[
index] ==
true
? TextOverflow.visible
: TextOverflow.ellipsis,
),
if (log.comment!.length > 100)
GestureDetector(
onTap: () {
setStateSB(() {
expandedDescription[
index] =
!(expandedDescription[
index] ==
true);
});
},
child: MyText.bodySmall(
expandedDescription[
index] ==
true
? "less"
: "more",
color: Colors.blue,
fontWeight: 600,
),
),
],
)
else
MyText.bodySmall(
"Description: No description provided",
fontWeight: 700,
),
],
),
), ),
), ],
) ),
else ],
const Icon(Icons.broken_image, ),
size: 20, color: Colors.grey), );
], },
), );
], },
), ),
); );
}, },
),
),
); );
} }
@ -218,16 +308,16 @@ class AttendanceLogViewButton extends StatelessWidget {
child: ElevatedButton( child: ElevatedButton(
onPressed: () => _showLogsBottomSheet(context), onPressed: () => _showLogsBottomSheet(context),
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Colors.indigo, backgroundColor: Colors.indigo,
textStyle: const TextStyle(fontSize: 12), textStyle: const TextStyle(fontSize: 12),
padding: const EdgeInsets.symmetric(horizontal: 12), padding: const EdgeInsets.symmetric(horizontal: 12),
), ),
child: const FittedBox( child: FittedBox(
fit: BoxFit.scaleDown, fit: BoxFit.scaleDown,
child: Text( child: MyText.bodySmall(
"View", "View",
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: Colors.white), color: Colors.white,
), ),
), ),
), ),
@ -248,7 +338,7 @@ class AttendanceLogViewButton extends StatelessWidget {
final today = DateTime(now.year, now.month, now.day); final today = DateTime(now.year, now.month, now.day);
final logDay = DateTime(logDate.year, logDate.month, logDate.day); final logDay = DateTime(logDate.year, logDate.month, logDate.day);
final yesterday = today.subtract(Duration(days: 1)); final yesterday = today.subtract(const Duration(days: 1));
isTodayOrYesterday = (logDay == today) || (logDay == yesterday); isTodayOrYesterday = (logDay == today) || (logDay == yesterday);
} }