Initial commit
This commit is contained in:
@@ -0,0 +1,185 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../models/office.dart';
|
||||
import '../../providers/profile_provider.dart';
|
||||
import '../../providers/tickets_provider.dart';
|
||||
import '../../widgets/responsive_body.dart';
|
||||
|
||||
class OfficesScreen extends ConsumerWidget {
|
||||
const OfficesScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isAdmin = ref.watch(isAdminProvider);
|
||||
final officesAsync = ref.watch(officesProvider);
|
||||
|
||||
return Scaffold(
|
||||
body: ResponsiveBody(
|
||||
maxWidth: 800,
|
||||
child: !isAdmin
|
||||
? const Center(child: Text('Admin access required.'))
|
||||
: officesAsync.when(
|
||||
data: (offices) {
|
||||
if (offices.isEmpty) {
|
||||
return const Center(child: Text('No offices found.'));
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16, bottom: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Office Management',
|
||||
style: Theme.of(context).textTheme.titleLarge
|
||||
?.copyWith(fontWeight: FontWeight.w700),
|
||||
),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: () => context.go('/settings/users'),
|
||||
icon: const Icon(Icons.group),
|
||||
label: const Text('User access'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView.separated(
|
||||
padding: const EdgeInsets.only(bottom: 24),
|
||||
itemCount: offices.length,
|
||||
separatorBuilder: (_, index) =>
|
||||
const SizedBox(height: 12),
|
||||
itemBuilder: (context, index) {
|
||||
final office = offices[index];
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.apartment_outlined),
|
||||
title: Text(office.name),
|
||||
trailing: Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
IconButton(
|
||||
tooltip: 'Edit',
|
||||
icon: const Icon(Icons.edit),
|
||||
onPressed: () => _showOfficeDialog(
|
||||
context,
|
||||
ref,
|
||||
office: office,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Delete',
|
||||
icon: const Icon(Icons.delete),
|
||||
onPressed: () =>
|
||||
_confirmDelete(context, ref, office),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, _) =>
|
||||
Center(child: Text('Failed to load offices: $error')),
|
||||
),
|
||||
),
|
||||
floatingActionButton: isAdmin
|
||||
? FloatingActionButton.extended(
|
||||
onPressed: () => _showOfficeDialog(context, ref),
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('New Office'),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showOfficeDialog(
|
||||
BuildContext context,
|
||||
WidgetRef ref, {
|
||||
Office? office,
|
||||
}) async {
|
||||
final nameController = TextEditingController(text: office?.name ?? '');
|
||||
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
return AlertDialog(
|
||||
title: Text(office == null ? 'Create Office' : 'Edit Office'),
|
||||
content: TextField(
|
||||
controller: nameController,
|
||||
decoration: const InputDecoration(labelText: 'Office name'),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final name = nameController.text.trim();
|
||||
if (name.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Name is required.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final controller = ref.read(officesControllerProvider);
|
||||
if (office == null) {
|
||||
await controller.createOffice(name: name);
|
||||
} else {
|
||||
await controller.updateOffice(id: office.id, name: name);
|
||||
}
|
||||
ref.invalidate(officesProvider);
|
||||
if (context.mounted) {
|
||||
Navigator.of(dialogContext).pop();
|
||||
}
|
||||
},
|
||||
child: Text(office == null ? 'Create' : 'Save'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _confirmDelete(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
Office office,
|
||||
) async {
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
return AlertDialog(
|
||||
title: const Text('Delete Office'),
|
||||
content: Text('Delete ${office.name}? This cannot be undone.'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
await ref
|
||||
.read(officesControllerProvider)
|
||||
.deleteOffice(id: office.id);
|
||||
ref.invalidate(officesProvider);
|
||||
if (context.mounted) {
|
||||
Navigator.of(dialogContext).pop();
|
||||
}
|
||||
},
|
||||
child: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,672 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../models/office.dart';
|
||||
import '../../models/profile.dart';
|
||||
import '../../models/ticket_message.dart';
|
||||
import '../../models/user_office.dart';
|
||||
import '../../providers/admin_user_provider.dart';
|
||||
import '../../providers/profile_provider.dart';
|
||||
import '../../providers/tickets_provider.dart';
|
||||
import '../../providers/user_offices_provider.dart';
|
||||
import '../../widgets/responsive_body.dart';
|
||||
|
||||
class UserManagementScreen extends ConsumerStatefulWidget {
|
||||
const UserManagementScreen({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<UserManagementScreen> createState() =>
|
||||
_UserManagementScreenState();
|
||||
}
|
||||
|
||||
class _UserManagementScreenState extends ConsumerState<UserManagementScreen> {
|
||||
static const List<String> _roles = [
|
||||
'standard',
|
||||
'dispatcher',
|
||||
'it_staff',
|
||||
'admin',
|
||||
];
|
||||
|
||||
final _fullNameController = TextEditingController();
|
||||
|
||||
String? _selectedUserId;
|
||||
String? _selectedRole;
|
||||
Set<String> _selectedOfficeIds = {};
|
||||
AdminUserStatus? _selectedStatus;
|
||||
bool _isSaving = false;
|
||||
bool _isStatusLoading = false;
|
||||
final Map<String, AdminUserStatus> _statusCache = {};
|
||||
final Set<String> _statusLoading = {};
|
||||
final Set<String> _statusErrors = {};
|
||||
Set<String> _prefetchedUserIds = {};
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_fullNameController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isAdmin = ref.watch(isAdminProvider);
|
||||
final profilesAsync = ref.watch(profilesProvider);
|
||||
final officesAsync = ref.watch(officesProvider);
|
||||
final assignmentsAsync = ref.watch(userOfficesProvider);
|
||||
final messagesAsync = ref.watch(ticketMessagesAllProvider);
|
||||
|
||||
return Scaffold(
|
||||
body: ResponsiveBody(
|
||||
maxWidth: 1080,
|
||||
child: !isAdmin
|
||||
? const Center(child: Text('Admin access required.'))
|
||||
: _buildContent(
|
||||
context,
|
||||
profilesAsync,
|
||||
officesAsync,
|
||||
assignmentsAsync,
|
||||
messagesAsync,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(
|
||||
BuildContext context,
|
||||
AsyncValue<List<Profile>> profilesAsync,
|
||||
AsyncValue<List<Office>> officesAsync,
|
||||
AsyncValue<List<UserOffice>> assignmentsAsync,
|
||||
AsyncValue<List<TicketMessage>> messagesAsync,
|
||||
) {
|
||||
if (profilesAsync.isLoading ||
|
||||
officesAsync.isLoading ||
|
||||
assignmentsAsync.isLoading ||
|
||||
messagesAsync.isLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (profilesAsync.hasError ||
|
||||
officesAsync.hasError ||
|
||||
assignmentsAsync.hasError ||
|
||||
messagesAsync.hasError) {
|
||||
final error =
|
||||
profilesAsync.error ??
|
||||
officesAsync.error ??
|
||||
assignmentsAsync.error ??
|
||||
messagesAsync.error ??
|
||||
'Unknown error';
|
||||
return Center(child: Text('Failed to load data: $error'));
|
||||
}
|
||||
|
||||
final profiles = profilesAsync.valueOrNull ?? [];
|
||||
final offices = officesAsync.valueOrNull ?? [];
|
||||
final assignments = assignmentsAsync.valueOrNull ?? [];
|
||||
final messages = messagesAsync.valueOrNull ?? [];
|
||||
|
||||
_prefetchStatuses(profiles);
|
||||
|
||||
final lastActiveByUser = <String, DateTime>{};
|
||||
for (final message in messages) {
|
||||
final senderId = message.senderId;
|
||||
if (senderId == null) continue;
|
||||
final current = lastActiveByUser[senderId];
|
||||
if (current == null || message.createdAt.isAfter(current)) {
|
||||
lastActiveByUser[senderId] = message.createdAt;
|
||||
}
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'User Management',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w700),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Expanded(
|
||||
child: _buildUserTable(
|
||||
context,
|
||||
profiles,
|
||||
offices,
|
||||
assignments,
|
||||
lastActiveByUser,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildUserTable(
|
||||
BuildContext context,
|
||||
List<Profile> profiles,
|
||||
List<Office> offices,
|
||||
List<UserOffice> assignments,
|
||||
Map<String, DateTime> lastActiveByUser,
|
||||
) {
|
||||
if (profiles.isEmpty) {
|
||||
return const Center(child: Text('No users found.'));
|
||||
}
|
||||
final officeNameById = {
|
||||
for (final office in offices) office.id: office.name,
|
||||
};
|
||||
|
||||
final officeCountByUser = <String, int>{};
|
||||
for (final assignment in assignments) {
|
||||
officeCountByUser.update(
|
||||
assignment.userId,
|
||||
(value) => value + 1,
|
||||
ifAbsent: () => 1,
|
||||
);
|
||||
}
|
||||
|
||||
return Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(minWidth: 720),
|
||||
child: SingleChildScrollView(
|
||||
child: DataTable(
|
||||
headingRowHeight: 46,
|
||||
dataRowMinHeight: 48,
|
||||
dataRowMaxHeight: 64,
|
||||
columnSpacing: 24,
|
||||
horizontalMargin: 16,
|
||||
dividerThickness: 1,
|
||||
headingRowColor: MaterialStateProperty.resolveWith(
|
||||
(states) => Theme.of(context).colorScheme.surfaceVariant,
|
||||
),
|
||||
columns: const [
|
||||
DataColumn(label: Text('User')),
|
||||
DataColumn(label: Text('Email')),
|
||||
DataColumn(label: Text('Role')),
|
||||
DataColumn(label: Text('Offices')),
|
||||
DataColumn(label: Text('Status')),
|
||||
DataColumn(label: Text('Last active')),
|
||||
],
|
||||
rows: profiles.asMap().entries.map((entry) {
|
||||
final index = entry.key;
|
||||
final profile = entry.value;
|
||||
final label = profile.fullName.isEmpty
|
||||
? profile.id
|
||||
: profile.fullName;
|
||||
final status = _statusCache[profile.id];
|
||||
final hasError = _statusErrors.contains(profile.id);
|
||||
final isLoading = _statusLoading.contains(profile.id);
|
||||
final email = hasError
|
||||
? 'Unavailable'
|
||||
: (status?.email ?? (isLoading ? 'Loading...' : 'N/A'));
|
||||
final statusLabel = hasError
|
||||
? 'Unavailable'
|
||||
: (status == null
|
||||
? (isLoading ? 'Loading...' : 'Unknown')
|
||||
: (status.isLocked ? 'Locked' : 'Active'));
|
||||
final officeCount = officeCountByUser[profile.id] ?? 0;
|
||||
final officeLabel = officeCount == 0 ? 'None' : '$officeCount';
|
||||
final officeNames = assignments
|
||||
.where((assignment) => assignment.userId == profile.id)
|
||||
.map(
|
||||
(assignment) =>
|
||||
officeNameById[assignment.officeId] ??
|
||||
assignment.officeId,
|
||||
)
|
||||
.toList();
|
||||
final officesText = officeNames.isEmpty
|
||||
? 'No offices'
|
||||
: officeNames.join(', ');
|
||||
final lastActive = _formatLastActive(
|
||||
lastActiveByUser[profile.id]?.toLocal(),
|
||||
);
|
||||
|
||||
return DataRow.byIndex(
|
||||
index: index,
|
||||
onSelectChanged: (selected) {
|
||||
if (selected != true) return;
|
||||
_showUserDialog(context, profile, offices, assignments);
|
||||
},
|
||||
color: MaterialStateProperty.resolveWith((states) {
|
||||
if (states.contains(MaterialState.selected)) {
|
||||
return Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceTint.withOpacity(0.12);
|
||||
}
|
||||
if (index.isEven) {
|
||||
return Theme.of(
|
||||
context,
|
||||
).colorScheme.surface.withOpacity(0.6);
|
||||
}
|
||||
return Theme.of(context).colorScheme.surface;
|
||||
}),
|
||||
cells: [
|
||||
DataCell(Text(label)),
|
||||
DataCell(Text(email)),
|
||||
DataCell(Text(profile.role)),
|
||||
DataCell(
|
||||
Tooltip(message: officesText, child: Text(officeLabel)),
|
||||
),
|
||||
DataCell(Text(statusLabel)),
|
||||
DataCell(Text(lastActive)),
|
||||
],
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _ensureStatusLoaded(String userId) {
|
||||
if (_statusCache.containsKey(userId) || _statusLoading.contains(userId)) {
|
||||
return;
|
||||
}
|
||||
_statusLoading.add(userId);
|
||||
_statusErrors.remove(userId);
|
||||
ref
|
||||
.read(adminUserControllerProvider)
|
||||
.fetchStatus(userId)
|
||||
.then((status) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_statusCache[userId] = status;
|
||||
_statusLoading.remove(userId);
|
||||
});
|
||||
})
|
||||
.catchError((_) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_statusLoading.remove(userId);
|
||||
_statusErrors.add(userId);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
void _prefetchStatuses(List<Profile> profiles) {
|
||||
final ids = profiles.map((profile) => profile.id).toSet();
|
||||
final missing = ids.difference(_prefetchedUserIds);
|
||||
if (missing.isEmpty) return;
|
||||
_prefetchedUserIds = ids;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
for (final userId in missing) {
|
||||
_ensureStatusLoaded(userId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _showUserDialog(
|
||||
BuildContext context,
|
||||
Profile profile,
|
||||
List<Office> offices,
|
||||
List<UserOffice> assignments,
|
||||
) async {
|
||||
await _selectUser(profile);
|
||||
final currentOfficeIds = assignments
|
||||
.where((assignment) => assignment.userId == profile.id)
|
||||
.map((assignment) => assignment.officeId)
|
||||
.toSet();
|
||||
|
||||
if (!context.mounted) return;
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
return StatefulBuilder(
|
||||
builder: (context, setDialogState) {
|
||||
return AlertDialog(
|
||||
title: const Text('Update user'),
|
||||
content: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 520),
|
||||
child: SingleChildScrollView(
|
||||
child: _buildUserForm(
|
||||
context,
|
||||
profile,
|
||||
offices,
|
||||
currentOfficeIds,
|
||||
setDialogState,
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
child: const Text('Close'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildUserForm(
|
||||
BuildContext context,
|
||||
Profile profile,
|
||||
List<Office> offices,
|
||||
Set<String> currentOfficeIds,
|
||||
StateSetter setDialogState,
|
||||
) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _fullNameController,
|
||||
decoration: const InputDecoration(labelText: 'Full name'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
DropdownButtonFormField<String>(
|
||||
key: ValueKey('role_${_selectedUserId ?? 'none'}'),
|
||||
initialValue: _selectedRole,
|
||||
items: _roles
|
||||
.map((role) => DropdownMenuItem(value: role, child: Text(role)))
|
||||
.toList(),
|
||||
onChanged: (value) => setDialogState(() => _selectedRole = value),
|
||||
decoration: const InputDecoration(labelText: 'Role'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildStatusRow(profile),
|
||||
const SizedBox(height: 16),
|
||||
Text('Offices', style: Theme.of(context).textTheme.titleSmall),
|
||||
const SizedBox(height: 8),
|
||||
if (offices.isEmpty) const Text('No offices available.'),
|
||||
if (offices.isNotEmpty)
|
||||
Column(
|
||||
children: offices
|
||||
.map(
|
||||
(office) => CheckboxListTile(
|
||||
value: _selectedOfficeIds.contains(office.id),
|
||||
onChanged: _isSaving
|
||||
? null
|
||||
: (selected) {
|
||||
setDialogState(() {
|
||||
if (selected == true) {
|
||||
_selectedOfficeIds.add(office.id);
|
||||
} else {
|
||||
_selectedOfficeIds.remove(office.id);
|
||||
}
|
||||
});
|
||||
},
|
||||
title: Text(office.name),
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: FilledButton(
|
||||
onPressed: _isSaving
|
||||
? null
|
||||
: () async {
|
||||
final saved = await _saveChanges(
|
||||
context,
|
||||
profile,
|
||||
currentOfficeIds,
|
||||
setDialogState,
|
||||
);
|
||||
if (saved && context.mounted) {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
},
|
||||
child: _isSaving
|
||||
? const SizedBox(
|
||||
height: 18,
|
||||
width: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Save changes'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatusRow(Profile profile) {
|
||||
final email = _selectedStatus?.email;
|
||||
final isLocked = _selectedStatus?.isLocked ?? false;
|
||||
final lockLabel = isLocked ? 'Unlock' : 'Lock';
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Email: ${email ?? 'Loading...'}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
OutlinedButton.icon(
|
||||
onPressed: _isStatusLoading
|
||||
? null
|
||||
: () => _showPasswordResetDialog(profile.id),
|
||||
icon: const Icon(Icons.password),
|
||||
label: const Text('Reset password'),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _isStatusLoading
|
||||
? null
|
||||
: () => _toggleLock(profile.id, !isLocked),
|
||||
icon: Icon(isLocked ? Icons.lock_open : Icons.lock),
|
||||
label: Text(lockLabel),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _selectUser(Profile profile) async {
|
||||
setState(() {
|
||||
_selectedUserId = profile.id;
|
||||
_selectedRole = profile.role;
|
||||
_fullNameController.text = profile.fullName;
|
||||
_selectedStatus = null;
|
||||
_isStatusLoading = true;
|
||||
});
|
||||
|
||||
final assignments = ref.read(userOfficesProvider).valueOrNull ?? [];
|
||||
final officeIds = assignments
|
||||
.where((assignment) => assignment.userId == profile.id)
|
||||
.map((assignment) => assignment.officeId)
|
||||
.toSet();
|
||||
setState(() => _selectedOfficeIds = officeIds);
|
||||
|
||||
try {
|
||||
final status = await ref
|
||||
.read(adminUserControllerProvider)
|
||||
.fetchStatus(profile.id);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_selectedStatus = status;
|
||||
_statusCache[profile.id] = status;
|
||||
});
|
||||
}
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
setState(
|
||||
() =>
|
||||
_selectedStatus = AdminUserStatus(email: null, bannedUntil: null),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isStatusLoading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _saveChanges(
|
||||
BuildContext context,
|
||||
Profile profile,
|
||||
Set<String> currentOfficeIds,
|
||||
StateSetter setDialogState,
|
||||
) async {
|
||||
final role = _selectedRole ?? profile.role;
|
||||
final fullName = _fullNameController.text.trim();
|
||||
if (fullName.isEmpty) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(const SnackBar(content: Text('Full name is required.')));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_selectedOfficeIds.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Select at least one office.')),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
setDialogState(() => _isSaving = true);
|
||||
try {
|
||||
await ref
|
||||
.read(adminUserControllerProvider)
|
||||
.updateProfile(userId: profile.id, fullName: fullName, role: role);
|
||||
|
||||
final toAdd = _selectedOfficeIds.difference(currentOfficeIds);
|
||||
final toRemove = currentOfficeIds.difference(_selectedOfficeIds);
|
||||
final controller = ref.read(userOfficesControllerProvider);
|
||||
|
||||
for (final officeId in toAdd) {
|
||||
await controller.assignUserOffice(
|
||||
userId: profile.id,
|
||||
officeId: officeId,
|
||||
);
|
||||
}
|
||||
|
||||
for (final officeId in toRemove) {
|
||||
await controller.removeUserOffice(
|
||||
userId: profile.id,
|
||||
officeId: officeId,
|
||||
);
|
||||
}
|
||||
|
||||
ref.invalidate(profilesProvider);
|
||||
ref.invalidate(userOfficesProvider);
|
||||
|
||||
if (!context.mounted) return true;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(const SnackBar(content: Text('User updated.')));
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!context.mounted) return false;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Update failed: $error')));
|
||||
return false;
|
||||
} finally {
|
||||
setDialogState(() => _isSaving = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showPasswordResetDialog(String userId) async {
|
||||
final controller = TextEditingController();
|
||||
final formKey = GlobalKey<FormState>();
|
||||
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
return AlertDialog(
|
||||
title: const Text('Set temporary password'),
|
||||
content: Form(
|
||||
key: formKey,
|
||||
child: TextFormField(
|
||||
controller: controller,
|
||||
decoration: const InputDecoration(labelText: 'New password'),
|
||||
obscureText: true,
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().length < 8) {
|
||||
return 'Use at least 8 characters.';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
if (!formKey.currentState!.validate()) return;
|
||||
try {
|
||||
await ref
|
||||
.read(adminUserControllerProvider)
|
||||
.setPassword(
|
||||
userId: userId,
|
||||
password: controller.text.trim(),
|
||||
);
|
||||
if (!dialogContext.mounted) return;
|
||||
Navigator.of(dialogContext).pop();
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Password updated.')),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Reset failed: $error')),
|
||||
);
|
||||
}
|
||||
},
|
||||
child: const Text('Update password'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _toggleLock(String userId, bool locked) async {
|
||||
setState(() => _isStatusLoading = true);
|
||||
try {
|
||||
await ref
|
||||
.read(adminUserControllerProvider)
|
||||
.setLock(userId: userId, locked: locked);
|
||||
final status = await ref
|
||||
.read(adminUserControllerProvider)
|
||||
.fetchStatus(userId);
|
||||
if (!mounted) return;
|
||||
setState(() => _selectedStatus = status);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(locked ? 'User locked.' : 'User unlocked.')),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Lock update failed: $error')));
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isStatusLoading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String _formatLastActive(DateTime? value) {
|
||||
if (value == null) return 'N/A';
|
||||
final now = DateTime.now();
|
||||
final diff = now.difference(value);
|
||||
if (diff.inMinutes < 1) return 'Just now';
|
||||
if (diff.inHours < 1) return '${diff.inMinutes}m ago';
|
||||
if (diff.inDays < 1) return '${diff.inHours}h ago';
|
||||
if (diff.inDays < 7) return '${diff.inDays}d ago';
|
||||
final month = value.month.toString().padLeft(2, '0');
|
||||
final day = value.day.toString().padLeft(2, '0');
|
||||
return '${value.year}-$month-$day';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../providers/auth_provider.dart';
|
||||
import '../../widgets/responsive_body.dart';
|
||||
|
||||
class LoginScreen extends ConsumerStatefulWidget {
|
||||
const LoginScreen({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<LoginScreen> createState() => _LoginScreenState();
|
||||
}
|
||||
|
||||
class _LoginScreenState extends ConsumerState<LoginScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
|
||||
bool _isLoading = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _handleEmailSignIn() async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
setState(() => _isLoading = true);
|
||||
|
||||
final auth = ref.read(authControllerProvider);
|
||||
try {
|
||||
final response = await auth.signInWithPassword(
|
||||
email: _emailController.text.trim(),
|
||||
password: _passwordController.text,
|
||||
);
|
||||
if (response.session != null && mounted) {
|
||||
context.go('/tickets');
|
||||
} else if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Check your email to confirm sign-in.')),
|
||||
);
|
||||
}
|
||||
} on Exception catch (error) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Sign in failed: $error')));
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isLoading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _handleOAuthSignIn({required bool google}) async {
|
||||
setState(() => _isLoading = true);
|
||||
final auth = ref.read(authControllerProvider);
|
||||
final redirectTo = kIsWeb ? Uri.base.origin : null;
|
||||
|
||||
try {
|
||||
if (google) {
|
||||
await auth.signInWithGoogle(redirectTo: redirectTo);
|
||||
} else {
|
||||
await auth.signInWithMeta(redirectTo: redirectTo);
|
||||
}
|
||||
} on Exception catch (error) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('OAuth failed: $error')));
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isLoading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Sign In')),
|
||||
body: ResponsiveBody(
|
||||
maxWidth: 480,
|
||||
padding: const EdgeInsets.symmetric(vertical: 24),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Center(
|
||||
child: Column(
|
||||
children: [
|
||||
Image.asset('assets/tasq_ico.png', height: 72, width: 72),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'TasQ',
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
decoration: const InputDecoration(labelText: 'Email'),
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
textInputAction: TextInputAction.next,
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Email is required.';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
decoration: const InputDecoration(labelText: 'Password'),
|
||||
obscureText: true,
|
||||
textInputAction: TextInputAction.done,
|
||||
onFieldSubmitted: (_) {
|
||||
if (!_isLoading) {
|
||||
_handleEmailSignIn();
|
||||
}
|
||||
},
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Password is required.';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
onPressed: _isLoading ? null : _handleEmailSignIn,
|
||||
child: _isLoading
|
||||
? const SizedBox(
|
||||
height: 18,
|
||||
width: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Sign In'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _isLoading
|
||||
? null
|
||||
: () => _handleOAuthSignIn(google: true),
|
||||
icon: const FaIcon(FontAwesomeIcons.google, size: 18),
|
||||
label: const Text('Continue with Google'),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _isLoading
|
||||
? null
|
||||
: () => _handleOAuthSignIn(google: false),
|
||||
icon: const FaIcon(FontAwesomeIcons.facebook, size: 18),
|
||||
label: const Text('Continue with Meta'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextButton(
|
||||
onPressed: _isLoading ? null : () => context.go('/signup'),
|
||||
child: const Text('Create account'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../providers/auth_provider.dart';
|
||||
import '../../providers/tickets_provider.dart';
|
||||
import '../../widgets/responsive_body.dart';
|
||||
|
||||
class SignUpScreen extends ConsumerStatefulWidget {
|
||||
const SignUpScreen({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<SignUpScreen> createState() => _SignUpScreenState();
|
||||
}
|
||||
|
||||
class _SignUpScreenState extends ConsumerState<SignUpScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _fullNameController = TextEditingController();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
final _confirmPasswordController = TextEditingController();
|
||||
|
||||
final Set<String> _selectedOfficeIds = {};
|
||||
double _passwordStrength = 0.0;
|
||||
String _passwordStrengthLabel = 'Very weak';
|
||||
Color _passwordStrengthColor = Colors.red;
|
||||
|
||||
bool _isLoading = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_passwordController.addListener(_updatePasswordStrength);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_passwordController.removeListener(_updatePasswordStrength);
|
||||
_fullNameController.dispose();
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
_confirmPasswordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _handleSignUp() async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
if (_selectedOfficeIds.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Select at least one office.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setState(() => _isLoading = true);
|
||||
|
||||
final auth = ref.read(authControllerProvider);
|
||||
try {
|
||||
await auth.signUp(
|
||||
email: _emailController.text.trim(),
|
||||
password: _passwordController.text,
|
||||
fullName: _fullNameController.text.trim(),
|
||||
officeIds: _selectedOfficeIds.toList(),
|
||||
);
|
||||
if (mounted) {
|
||||
context.go('/login');
|
||||
}
|
||||
} on Exception catch (error) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Sign up failed: $error')));
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isLoading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final officesAsync = ref.watch(officesOnceProvider);
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Create Account')),
|
||||
body: ResponsiveBody(
|
||||
maxWidth: 480,
|
||||
padding: const EdgeInsets.symmetric(vertical: 24),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Center(
|
||||
child: Column(
|
||||
children: [
|
||||
Image.asset('assets/tasq_ico.png', height: 72, width: 72),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'TasQ',
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
TextFormField(
|
||||
controller: _fullNameController,
|
||||
decoration: const InputDecoration(labelText: 'Full name'),
|
||||
textInputAction: TextInputAction.next,
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Full name is required.';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
decoration: const InputDecoration(labelText: 'Email'),
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
textInputAction: TextInputAction.next,
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Email is required.';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
decoration: const InputDecoration(labelText: 'Password'),
|
||||
obscureText: true,
|
||||
textInputAction: TextInputAction.next,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Password is required.';
|
||||
}
|
||||
if (value.length < 6) {
|
||||
return 'Use at least 6 characters.';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Password strength: $_passwordStrengthLabel',
|
||||
style: Theme.of(context).textTheme.labelMedium,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
LinearProgressIndicator(
|
||||
value: _passwordStrength,
|
||||
minHeight: 8,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
color: _passwordStrengthColor,
|
||||
backgroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextFormField(
|
||||
controller: _confirmPasswordController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Confirm password',
|
||||
),
|
||||
obscureText: true,
|
||||
textInputAction: TextInputAction.done,
|
||||
onFieldSubmitted: (_) {
|
||||
if (!_isLoading) {
|
||||
_handleSignUp();
|
||||
}
|
||||
},
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Confirm your password.';
|
||||
}
|
||||
if (value != _passwordController.text) {
|
||||
return 'Passwords do not match.';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text('Offices', style: Theme.of(context).textTheme.titleSmall),
|
||||
const SizedBox(height: 8),
|
||||
officesAsync.when(
|
||||
data: (offices) {
|
||||
if (offices.isEmpty) {
|
||||
return const Text('No offices available.');
|
||||
}
|
||||
return Column(
|
||||
children: offices
|
||||
.map(
|
||||
(office) => CheckboxListTile(
|
||||
value: _selectedOfficeIds.contains(office.id),
|
||||
onChanged: _isLoading
|
||||
? null
|
||||
: (selected) {
|
||||
setState(() {
|
||||
if (selected == true) {
|
||||
_selectedOfficeIds.add(office.id);
|
||||
} else {
|
||||
_selectedOfficeIds.remove(office.id);
|
||||
}
|
||||
});
|
||||
},
|
||||
title: Text(office.name),
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
},
|
||||
loading: () => const LinearProgressIndicator(),
|
||||
error: (error, _) => Text('Failed to load offices: $error'),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
onPressed: _isLoading ? null : _handleSignUp,
|
||||
child: _isLoading
|
||||
? const SizedBox(
|
||||
height: 18,
|
||||
width: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Create Account'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextButton(
|
||||
onPressed: _isLoading ? null : () => context.go('/login'),
|
||||
child: const Text('Back to sign in'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _updatePasswordStrength() {
|
||||
final text = _passwordController.text;
|
||||
var score = 0;
|
||||
if (text.length >= 8) score++;
|
||||
if (text.length >= 12) score++;
|
||||
if (RegExp(r'[A-Z]').hasMatch(text)) score++;
|
||||
if (RegExp(r'[a-z]').hasMatch(text)) score++;
|
||||
if (RegExp(r'\d').hasMatch(text)) score++;
|
||||
if (RegExp(r'[!@#$%^&*(),.?":{}|<>\[\]\\/+=;_-]').hasMatch(text)) {
|
||||
score++;
|
||||
}
|
||||
|
||||
final normalized = (score / 6).clamp(0.0, 1.0);
|
||||
final (label, color) = switch (normalized) {
|
||||
<= 0.2 => ('Very weak', Colors.red),
|
||||
<= 0.4 => ('Weak', Colors.deepOrange),
|
||||
<= 0.6 => ('Fair', Colors.orange),
|
||||
<= 0.8 => ('Strong', Colors.green),
|
||||
_ => ('Excellent', Colors.teal),
|
||||
};
|
||||
|
||||
setState(() {
|
||||
_passwordStrength = normalized;
|
||||
_passwordStrengthLabel = label;
|
||||
_passwordStrengthColor = color;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,637 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../models/profile.dart';
|
||||
import '../../models/task.dart';
|
||||
import '../../models/task_assignment.dart';
|
||||
import '../../models/ticket.dart';
|
||||
import '../../models/ticket_message.dart';
|
||||
import '../../providers/profile_provider.dart';
|
||||
import '../../providers/tasks_provider.dart';
|
||||
import '../../providers/tickets_provider.dart';
|
||||
import '../../widgets/responsive_body.dart';
|
||||
|
||||
class DashboardMetrics {
|
||||
DashboardMetrics({
|
||||
required this.newTicketsToday,
|
||||
required this.closedToday,
|
||||
required this.openTickets,
|
||||
required this.avgResponse,
|
||||
required this.avgTriage,
|
||||
required this.longestResponse,
|
||||
required this.tasksCreatedToday,
|
||||
required this.tasksCompletedToday,
|
||||
required this.openTasks,
|
||||
required this.staffRows,
|
||||
});
|
||||
|
||||
final int newTicketsToday;
|
||||
final int closedToday;
|
||||
final int openTickets;
|
||||
|
||||
final Duration? avgResponse;
|
||||
final Duration? avgTriage;
|
||||
final Duration? longestResponse;
|
||||
|
||||
final int tasksCreatedToday;
|
||||
final int tasksCompletedToday;
|
||||
final int openTasks;
|
||||
|
||||
final List<StaffRowMetrics> staffRows;
|
||||
}
|
||||
|
||||
class StaffRowMetrics {
|
||||
StaffRowMetrics({
|
||||
required this.userId,
|
||||
required this.name,
|
||||
required this.status,
|
||||
required this.ticketsRespondedToday,
|
||||
required this.tasksClosedToday,
|
||||
});
|
||||
|
||||
final String userId;
|
||||
final String name;
|
||||
final String status;
|
||||
final int ticketsRespondedToday;
|
||||
final int tasksClosedToday;
|
||||
}
|
||||
|
||||
final dashboardMetricsProvider = Provider<AsyncValue<DashboardMetrics>>((ref) {
|
||||
final ticketsAsync = ref.watch(ticketsProvider);
|
||||
final tasksAsync = ref.watch(tasksProvider);
|
||||
final profilesAsync = ref.watch(profilesProvider);
|
||||
final assignmentsAsync = ref.watch(taskAssignmentsProvider);
|
||||
final messagesAsync = ref.watch(ticketMessagesAllProvider);
|
||||
|
||||
final asyncValues = [
|
||||
ticketsAsync,
|
||||
tasksAsync,
|
||||
profilesAsync,
|
||||
assignmentsAsync,
|
||||
messagesAsync,
|
||||
];
|
||||
|
||||
if (asyncValues.any((value) => value.hasError)) {
|
||||
final errorValue = asyncValues.firstWhere((value) => value.hasError);
|
||||
final error = errorValue.error ?? 'Failed to load dashboard';
|
||||
final stack = errorValue.stackTrace ?? StackTrace.current;
|
||||
return AsyncError(error, stack);
|
||||
}
|
||||
|
||||
if (asyncValues.any((value) => value.isLoading)) {
|
||||
return const AsyncLoading();
|
||||
}
|
||||
|
||||
final tickets = ticketsAsync.valueOrNull ?? const <Ticket>[];
|
||||
final tasks = tasksAsync.valueOrNull ?? const <Task>[];
|
||||
final profiles = profilesAsync.valueOrNull ?? const <Profile>[];
|
||||
final assignments = assignmentsAsync.valueOrNull ?? const <TaskAssignment>[];
|
||||
final messages = messagesAsync.valueOrNull ?? const <TicketMessage>[];
|
||||
|
||||
final now = DateTime.now();
|
||||
final startOfDay = DateTime(now.year, now.month, now.day);
|
||||
|
||||
final staffProfiles = profiles
|
||||
.where((profile) => profile.role == 'it_staff')
|
||||
.toList();
|
||||
final staffIds = profiles
|
||||
.where(
|
||||
(profile) =>
|
||||
profile.role == 'admin' ||
|
||||
profile.role == 'dispatcher' ||
|
||||
profile.role == 'it_staff',
|
||||
)
|
||||
.map((profile) => profile.id)
|
||||
.toSet();
|
||||
|
||||
bool isToday(DateTime value) => !value.isBefore(startOfDay);
|
||||
|
||||
final firstStaffMessageByTicket = <String, DateTime>{};
|
||||
final lastStaffMessageByUser = <String, DateTime>{};
|
||||
final respondedTicketsByUser = <String, Set<String>>{};
|
||||
for (final message in messages) {
|
||||
final ticketId = message.ticketId;
|
||||
final senderId = message.senderId;
|
||||
if (ticketId != null && senderId != null && staffIds.contains(senderId)) {
|
||||
final current = firstStaffMessageByTicket[ticketId];
|
||||
if (current == null || message.createdAt.isBefore(current)) {
|
||||
firstStaffMessageByTicket[ticketId] = message.createdAt;
|
||||
}
|
||||
final last = lastStaffMessageByUser[senderId];
|
||||
if (last == null || message.createdAt.isAfter(last)) {
|
||||
lastStaffMessageByUser[senderId] = message.createdAt;
|
||||
}
|
||||
if (isToday(message.createdAt)) {
|
||||
respondedTicketsByUser
|
||||
.putIfAbsent(senderId, () => <String>{})
|
||||
.add(ticketId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DateTime? respondedAtForTicket(Ticket ticket) {
|
||||
final staffMessageAt = firstStaffMessageByTicket[ticket.id];
|
||||
if (staffMessageAt != null) {
|
||||
return staffMessageAt;
|
||||
}
|
||||
if (ticket.promotedAt != null) {
|
||||
return ticket.promotedAt;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Duration? responseDuration(Ticket ticket) {
|
||||
final respondedAt = respondedAtForTicket(ticket);
|
||||
if (respondedAt == null) {
|
||||
return null;
|
||||
}
|
||||
final duration = respondedAt.difference(ticket.createdAt);
|
||||
return duration.isNegative ? Duration.zero : duration;
|
||||
}
|
||||
|
||||
Duration? triageDuration(Ticket ticket) {
|
||||
final respondedAt = respondedAtForTicket(ticket);
|
||||
if (respondedAt == null) {
|
||||
return null;
|
||||
}
|
||||
final triageEnd = _earliestDate(ticket.promotedAt, ticket.closedAt);
|
||||
if (triageEnd == null) {
|
||||
return null;
|
||||
}
|
||||
final duration = triageEnd.difference(respondedAt);
|
||||
return duration.isNegative ? Duration.zero : duration;
|
||||
}
|
||||
|
||||
final ticketsToday = tickets.where((ticket) => isToday(ticket.createdAt));
|
||||
final closedToday = tickets.where(
|
||||
(ticket) => ticket.closedAt != null && isToday(ticket.closedAt!),
|
||||
);
|
||||
final openTickets = tickets.where((ticket) => ticket.status != 'closed');
|
||||
|
||||
final responseDurationsToday = ticketsToday
|
||||
.map(responseDuration)
|
||||
.whereType<Duration>()
|
||||
.toList();
|
||||
final triageDurationsToday = ticketsToday
|
||||
.map(triageDuration)
|
||||
.whereType<Duration>()
|
||||
.toList();
|
||||
|
||||
final avgResponse = _averageDuration(responseDurationsToday);
|
||||
final avgTriage = _averageDuration(triageDurationsToday);
|
||||
final longestResponse = responseDurationsToday.isEmpty
|
||||
? null
|
||||
: responseDurationsToday.reduce(
|
||||
(a, b) => a.inSeconds >= b.inSeconds ? a : b,
|
||||
);
|
||||
|
||||
final tasksCreatedToday = tasks.where((task) => isToday(task.createdAt));
|
||||
final tasksCompletedToday = tasks.where(
|
||||
(task) => task.completedAt != null && isToday(task.completedAt!),
|
||||
);
|
||||
final openTasks = tasks.where((task) => task.status != 'completed');
|
||||
|
||||
final taskById = {for (final task in tasks) task.id: task};
|
||||
final staffOnTask = <String>{};
|
||||
for (final assignment in assignments) {
|
||||
final task = taskById[assignment.taskId];
|
||||
if (task == null) {
|
||||
continue;
|
||||
}
|
||||
if (task.status == 'in_progress') {
|
||||
staffOnTask.add(assignment.userId);
|
||||
}
|
||||
}
|
||||
|
||||
final tasksClosedByUser = <String, Set<String>>{};
|
||||
for (final assignment in assignments) {
|
||||
final task = taskById[assignment.taskId];
|
||||
if (task == null || task.completedAt == null) {
|
||||
continue;
|
||||
}
|
||||
if (!isToday(task.completedAt!)) {
|
||||
continue;
|
||||
}
|
||||
tasksClosedByUser
|
||||
.putIfAbsent(assignment.userId, () => <String>{})
|
||||
.add(task.id);
|
||||
}
|
||||
|
||||
const triageWindow = Duration(minutes: 1);
|
||||
final triageCutoff = now.subtract(triageWindow);
|
||||
|
||||
final staffRows = staffProfiles.map((staff) {
|
||||
final lastMessage = lastStaffMessageByUser[staff.id];
|
||||
final ticketsResponded = respondedTicketsByUser[staff.id]?.length ?? 0;
|
||||
final tasksClosed = tasksClosedByUser[staff.id]?.length ?? 0;
|
||||
final onTask = staffOnTask.contains(staff.id);
|
||||
final inTriage = lastMessage != null && lastMessage.isAfter(triageCutoff);
|
||||
final status = onTask
|
||||
? 'On task'
|
||||
: inTriage
|
||||
? 'In triage'
|
||||
: 'Vacant';
|
||||
|
||||
return StaffRowMetrics(
|
||||
userId: staff.id,
|
||||
name: staff.fullName.isNotEmpty ? staff.fullName : staff.id,
|
||||
status: status,
|
||||
ticketsRespondedToday: ticketsResponded,
|
||||
tasksClosedToday: tasksClosed,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
return AsyncData(
|
||||
DashboardMetrics(
|
||||
newTicketsToday: ticketsToday.length,
|
||||
closedToday: closedToday.length,
|
||||
openTickets: openTickets.length,
|
||||
avgResponse: avgResponse,
|
||||
avgTriage: avgTriage,
|
||||
longestResponse: longestResponse,
|
||||
tasksCreatedToday: tasksCreatedToday.length,
|
||||
tasksCompletedToday: tasksCompletedToday.length,
|
||||
openTasks: openTasks.length,
|
||||
staffRows: staffRows,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
class DashboardScreen extends StatelessWidget {
|
||||
const DashboardScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ResponsiveBody(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final isWide = constraints.maxWidth >= 980;
|
||||
final metricsColumn = Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16, bottom: 8),
|
||||
child: Align(
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
'Dashboard',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const _DashboardStatusBanner(),
|
||||
_sectionTitle(context, 'Core Daily KPIs'),
|
||||
_cardGrid(context, [
|
||||
_MetricCard(
|
||||
title: 'New tickets today',
|
||||
valueBuilder: (metrics) => metrics.newTicketsToday.toString(),
|
||||
),
|
||||
_MetricCard(
|
||||
title: 'Closed today',
|
||||
valueBuilder: (metrics) => metrics.closedToday.toString(),
|
||||
),
|
||||
_MetricCard(
|
||||
title: 'Open tickets',
|
||||
valueBuilder: (metrics) => metrics.openTickets.toString(),
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 20),
|
||||
_sectionTitle(context, 'TAT / Response'),
|
||||
_cardGrid(context, [
|
||||
_MetricCard(
|
||||
title: 'Avg response',
|
||||
valueBuilder: (metrics) =>
|
||||
_formatDuration(metrics.avgResponse),
|
||||
),
|
||||
_MetricCard(
|
||||
title: 'Avg triage',
|
||||
valueBuilder: (metrics) => _formatDuration(metrics.avgTriage),
|
||||
),
|
||||
_MetricCard(
|
||||
title: 'Longest response',
|
||||
valueBuilder: (metrics) =>
|
||||
_formatDuration(metrics.longestResponse),
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 20),
|
||||
_sectionTitle(context, 'Task Flow'),
|
||||
_cardGrid(context, [
|
||||
_MetricCard(
|
||||
title: 'Tasks created',
|
||||
valueBuilder: (metrics) =>
|
||||
metrics.tasksCreatedToday.toString(),
|
||||
),
|
||||
_MetricCard(
|
||||
title: 'Tasks completed',
|
||||
valueBuilder: (metrics) =>
|
||||
metrics.tasksCompletedToday.toString(),
|
||||
),
|
||||
_MetricCard(
|
||||
title: 'Open tasks',
|
||||
valueBuilder: (metrics) => metrics.openTasks.toString(),
|
||||
),
|
||||
]),
|
||||
],
|
||||
);
|
||||
|
||||
final staffColumn = Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
_sectionTitle(context, 'IT Staff Pulse'),
|
||||
const _StaffTable(),
|
||||
],
|
||||
);
|
||||
|
||||
if (isWide) {
|
||||
return Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(minHeight: constraints.maxHeight),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: constraints.maxWidth * 0.6,
|
||||
),
|
||||
child: metricsColumn,
|
||||
),
|
||||
const SizedBox(width: 20),
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: constraints.maxWidth * 0.35,
|
||||
),
|
||||
child: staffColumn,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.only(bottom: 24),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(minHeight: constraints.maxHeight),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
metricsColumn,
|
||||
const SizedBox(height: 12),
|
||||
staffColumn,
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _sectionTitle(BuildContext context, String title) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Text(
|
||||
title,
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w700),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cardGrid(BuildContext context, List<Widget> cards) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final width = constraints.maxWidth;
|
||||
final columns = width >= 900
|
||||
? 3
|
||||
: width >= 620
|
||||
? 2
|
||||
: 1;
|
||||
final spacing = 12.0;
|
||||
final cardWidth = (width - (columns - 1) * spacing) / columns;
|
||||
return Wrap(
|
||||
alignment: WrapAlignment.center,
|
||||
runAlignment: WrapAlignment.center,
|
||||
spacing: spacing,
|
||||
runSpacing: spacing,
|
||||
children: cards
|
||||
.map((card) => SizedBox(width: cardWidth, child: card))
|
||||
.toList(),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DashboardStatusBanner extends ConsumerWidget {
|
||||
const _DashboardStatusBanner();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final metricsAsync = ref.watch(dashboardMetricsProvider);
|
||||
return metricsAsync.when(
|
||||
data: (_) => const SizedBox.shrink(),
|
||||
loading: () => const Padding(
|
||||
padding: EdgeInsets.only(bottom: 12),
|
||||
child: LinearProgressIndicator(minHeight: 2),
|
||||
),
|
||||
error: (error, _) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Text(
|
||||
'Dashboard data error: $error',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MetricCard extends ConsumerWidget {
|
||||
const _MetricCard({required this.title, required this.valueBuilder});
|
||||
|
||||
final String title;
|
||||
final String Function(DashboardMetrics metrics) valueBuilder;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final metricsAsync = ref.watch(dashboardMetricsProvider);
|
||||
final value = metricsAsync.when(
|
||||
data: (metrics) => valueBuilder(metrics),
|
||||
loading: () => '—',
|
||||
error: (error, _) => 'Error',
|
||||
);
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: Theme.of(context).colorScheme.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.labelLarge?.copyWith(fontWeight: FontWeight.w600),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
value,
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.w700),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StaffTable extends StatelessWidget {
|
||||
const _StaffTable();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: Theme.of(context).colorScheme.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: const [
|
||||
_StaffTableHeader(),
|
||||
SizedBox(height: 8),
|
||||
_StaffTableBody(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StaffTableHeader extends StatelessWidget {
|
||||
const _StaffTableHeader();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final style = Theme.of(
|
||||
context,
|
||||
).textTheme.labelMedium?.copyWith(fontWeight: FontWeight.w700);
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(flex: 3, child: Text('IT Staff', style: style)),
|
||||
Expanded(flex: 2, child: Text('Status', style: style)),
|
||||
Expanded(flex: 2, child: Text('Tickets', style: style)),
|
||||
Expanded(flex: 2, child: Text('Tasks', style: style)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StaffTableBody extends ConsumerWidget {
|
||||
const _StaffTableBody();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final metricsAsync = ref.watch(dashboardMetricsProvider);
|
||||
return metricsAsync.when(
|
||||
data: (metrics) {
|
||||
if (metrics.staffRows.isEmpty) {
|
||||
return Text(
|
||||
'No IT staff available.',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
children: metrics.staffRows
|
||||
.map((row) => _StaffRow(row: row))
|
||||
.toList(),
|
||||
);
|
||||
},
|
||||
loading: () => const Text('Loading staff...'),
|
||||
error: (error, _) => Text('Failed to load staff: $error'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StaffRow extends StatelessWidget {
|
||||
const _StaffRow({required this.row});
|
||||
|
||||
final StaffRowMetrics row;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final valueStyle = Theme.of(context).textTheme.bodySmall;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(flex: 3, child: Text(row.name, style: valueStyle)),
|
||||
Expanded(flex: 2, child: Text(row.status, style: valueStyle)),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Text(
|
||||
row.ticketsRespondedToday.toString(),
|
||||
style: valueStyle,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Text(row.tasksClosedToday.toString(), style: valueStyle),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Duration? _averageDuration(List<Duration> durations) {
|
||||
if (durations.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
final totalSeconds = durations
|
||||
.map((duration) => duration.inSeconds)
|
||||
.reduce((a, b) => a + b);
|
||||
return Duration(seconds: (totalSeconds / durations.length).round());
|
||||
}
|
||||
|
||||
DateTime? _earliestDate(DateTime? first, DateTime? second) {
|
||||
if (first == null) return second;
|
||||
if (second == null) return first;
|
||||
return first.isBefore(second) ? first : second;
|
||||
}
|
||||
|
||||
String _formatDuration(Duration? duration) {
|
||||
if (duration == null) {
|
||||
return 'Pending';
|
||||
}
|
||||
if (duration.inSeconds < 60) {
|
||||
return 'Less than a minute';
|
||||
}
|
||||
final hours = duration.inHours;
|
||||
final minutes = duration.inMinutes.remainder(60);
|
||||
if (hours > 0) {
|
||||
return '${hours}h ${minutes}m';
|
||||
}
|
||||
return '${minutes}m';
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../providers/notifications_provider.dart';
|
||||
import '../../providers/profile_provider.dart';
|
||||
import '../../providers/tasks_provider.dart';
|
||||
import '../../providers/tickets_provider.dart';
|
||||
import '../../widgets/responsive_body.dart';
|
||||
|
||||
class NotificationsScreen extends ConsumerWidget {
|
||||
const NotificationsScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final notificationsAsync = ref.watch(notificationsProvider);
|
||||
final profilesAsync = ref.watch(profilesProvider);
|
||||
final ticketsAsync = ref.watch(ticketsProvider);
|
||||
final tasksAsync = ref.watch(tasksProvider);
|
||||
|
||||
final profileById = {
|
||||
for (final profile in profilesAsync.valueOrNull ?? [])
|
||||
profile.id: profile,
|
||||
};
|
||||
final ticketById = {
|
||||
for (final ticket in ticketsAsync.valueOrNull ?? []) ticket.id: ticket,
|
||||
};
|
||||
final taskById = {
|
||||
for (final task in tasksAsync.valueOrNull ?? []) task.id: task,
|
||||
};
|
||||
|
||||
return ResponsiveBody(
|
||||
child: notificationsAsync.when(
|
||||
data: (items) {
|
||||
if (items.isEmpty) {
|
||||
return const Center(child: Text('No notifications yet.'));
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16, bottom: 8),
|
||||
child: Text(
|
||||
'Notifications',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w700),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView.separated(
|
||||
padding: const EdgeInsets.only(bottom: 24),
|
||||
itemCount: items.length,
|
||||
separatorBuilder: (context, index) =>
|
||||
const SizedBox(height: 12),
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
final actorName = item.actorId == null
|
||||
? 'System'
|
||||
: (profileById[item.actorId]?.fullName ??
|
||||
item.actorId!);
|
||||
final ticketSubject = item.ticketId == null
|
||||
? 'Ticket'
|
||||
: (ticketById[item.ticketId]?.subject ??
|
||||
item.ticketId!);
|
||||
final taskTitle = item.taskId == null
|
||||
? 'Task'
|
||||
: (taskById[item.taskId]?.title ?? item.taskId!);
|
||||
final subtitle = item.taskId != null
|
||||
? taskTitle
|
||||
: ticketSubject;
|
||||
|
||||
final title = _notificationTitle(item.type, actorName);
|
||||
final icon = _notificationIcon(item.type);
|
||||
|
||||
return ListTile(
|
||||
leading: Icon(icon),
|
||||
title: Text(title),
|
||||
subtitle: Text(subtitle),
|
||||
trailing: item.isUnread
|
||||
? const Icon(
|
||||
Icons.circle,
|
||||
size: 10,
|
||||
color: Colors.red,
|
||||
)
|
||||
: null,
|
||||
onTap: () async {
|
||||
final ticketId = item.ticketId;
|
||||
final taskId = item.taskId;
|
||||
if (ticketId != null) {
|
||||
await ref
|
||||
.read(notificationsControllerProvider)
|
||||
.markReadForTicket(ticketId);
|
||||
} else if (taskId != null) {
|
||||
await ref
|
||||
.read(notificationsControllerProvider)
|
||||
.markReadForTask(taskId);
|
||||
} else if (item.isUnread) {
|
||||
await ref
|
||||
.read(notificationsControllerProvider)
|
||||
.markRead(item.id);
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
if (taskId != null) {
|
||||
context.go('/tasks/$taskId');
|
||||
} else if (ticketId != null) {
|
||||
context.go('/tickets/$ticketId');
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, _) =>
|
||||
Center(child: Text('Failed to load notifications: $error')),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _notificationTitle(String type, String actorName) {
|
||||
switch (type) {
|
||||
case 'assignment':
|
||||
return '$actorName assigned you';
|
||||
case 'created':
|
||||
return '$actorName created a new item';
|
||||
case 'mention':
|
||||
default:
|
||||
return '$actorName mentioned you';
|
||||
}
|
||||
}
|
||||
|
||||
IconData _notificationIcon(String type) {
|
||||
switch (type) {
|
||||
case 'assignment':
|
||||
return Icons.assignment_ind_outlined;
|
||||
case 'created':
|
||||
return Icons.campaign_outlined;
|
||||
case 'mention':
|
||||
default:
|
||||
return Icons.alternate_email;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../widgets/responsive_body.dart';
|
||||
|
||||
class UnderDevelopmentScreen extends StatelessWidget {
|
||||
const UnderDevelopmentScreen({
|
||||
super.key,
|
||||
required this.title,
|
||||
required this.subtitle,
|
||||
required this.icon,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final IconData icon;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ResponsiveBody(
|
||||
maxWidth: 720,
|
||||
padding: const EdgeInsets.symmetric(vertical: 32),
|
||||
child: Center(
|
||||
child: Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 72,
|
||||
height: 72,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.primaryContainer.withValues(alpha: 0.7),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
size: 36,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
subtitle,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 8,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
child: Text(
|
||||
'Under development',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,822 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../models/profile.dart';
|
||||
import '../../models/task.dart';
|
||||
import '../../models/task_assignment.dart';
|
||||
import '../../models/ticket.dart';
|
||||
import '../../models/ticket_message.dart';
|
||||
import '../../providers/notifications_provider.dart';
|
||||
import '../../providers/profile_provider.dart';
|
||||
import '../../providers/tasks_provider.dart';
|
||||
import '../../providers/tickets_provider.dart';
|
||||
import '../../providers/typing_provider.dart';
|
||||
import '../../widgets/responsive_body.dart';
|
||||
import '../../widgets/task_assignment_section.dart';
|
||||
import '../../widgets/typing_dots.dart';
|
||||
|
||||
class TaskDetailScreen extends ConsumerStatefulWidget {
|
||||
const TaskDetailScreen({super.key, required this.taskId});
|
||||
|
||||
final String taskId;
|
||||
|
||||
@override
|
||||
ConsumerState<TaskDetailScreen> createState() => _TaskDetailScreenState();
|
||||
}
|
||||
|
||||
class _TaskDetailScreenState extends ConsumerState<TaskDetailScreen> {
|
||||
final _messageController = TextEditingController();
|
||||
static const List<String> _statusOptions = [
|
||||
'queued',
|
||||
'in_progress',
|
||||
'completed',
|
||||
];
|
||||
String? _mentionQuery;
|
||||
int? _mentionStart;
|
||||
List<Profile> _mentionResults = [];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
Future.microtask(
|
||||
() => ref
|
||||
.read(notificationsControllerProvider)
|
||||
.markReadForTask(widget.taskId),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_messageController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final tasksAsync = ref.watch(tasksProvider);
|
||||
final ticketsAsync = ref.watch(ticketsProvider);
|
||||
final officesAsync = ref.watch(officesProvider);
|
||||
final profileAsync = ref.watch(currentProfileProvider);
|
||||
final assignmentsAsync = ref.watch(taskAssignmentsProvider);
|
||||
final taskMessagesAsync = ref.watch(taskMessagesProvider(widget.taskId));
|
||||
final profilesAsync = ref.watch(profilesProvider);
|
||||
|
||||
final task = _findTask(tasksAsync, widget.taskId);
|
||||
if (task == null) {
|
||||
return const ResponsiveBody(
|
||||
child: Center(child: Text('Task not found.')),
|
||||
);
|
||||
}
|
||||
|
||||
final ticketId = task.ticketId;
|
||||
final typingChannelId = task.id;
|
||||
final ticket = ticketId == null
|
||||
? null
|
||||
: _findTicket(ticketsAsync, ticketId);
|
||||
final officeById = {
|
||||
for (final office in officesAsync.valueOrNull ?? []) office.id: office,
|
||||
};
|
||||
final officeId = ticket?.officeId ?? task.officeId;
|
||||
final officeName = officeId == null
|
||||
? 'Unassigned office'
|
||||
: (officeById[officeId]?.name ?? officeId);
|
||||
final description = ticket?.description ?? task.description;
|
||||
|
||||
final canAssign = profileAsync.maybeWhen(
|
||||
data: (profile) => profile != null && _canAssignStaff(profile.role),
|
||||
orElse: () => false,
|
||||
);
|
||||
final showAssign = canAssign && task.status != 'completed';
|
||||
final assignments = assignmentsAsync.valueOrNull ?? <TaskAssignment>[];
|
||||
final canUpdateStatus = _canUpdateStatus(
|
||||
profileAsync.valueOrNull,
|
||||
assignments,
|
||||
task.id,
|
||||
);
|
||||
final typingState = ref.watch(typingIndicatorProvider(typingChannelId));
|
||||
final canSendMessages = task.status != 'completed';
|
||||
|
||||
final messagesAsync = _mergeMessages(
|
||||
taskMessagesAsync,
|
||||
ticketId == null ? null : ref.watch(ticketMessagesProvider(ticketId)),
|
||||
);
|
||||
|
||||
return ResponsiveBody(
|
||||
child: Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16, bottom: 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
task.title.isNotEmpty ? task.title : 'Task ${task.id}',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Align(
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
_createdByLabel(profilesAsync, task, ticket),
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 8,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
_buildStatusChip(context, task, canUpdateStatus),
|
||||
Text('Office: $officeName'),
|
||||
],
|
||||
),
|
||||
if (description.isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(description),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
_buildTatSection(task),
|
||||
const SizedBox(height: 16),
|
||||
TaskAssignmentSection(taskId: task.id, canAssign: showAssign),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
Expanded(
|
||||
child: messagesAsync.when(
|
||||
data: (messages) => _buildMessages(
|
||||
context,
|
||||
messages,
|
||||
profilesAsync.valueOrNull ?? [],
|
||||
),
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, _) =>
|
||||
Center(child: Text('Failed to load messages: $error')),
|
||||
),
|
||||
),
|
||||
SafeArea(
|
||||
top: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(0, 8, 0, 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (typingState.userIds.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 6),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 10,
|
||||
vertical: 6,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_typingLabel(typingState.userIds, profilesAsync),
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
TypingDots(
|
||||
size: 8,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_mentionQuery != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: _buildMentionList(profilesAsync),
|
||||
),
|
||||
if (!canSendMessages)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text(
|
||||
'Messaging is disabled for completed tasks.',
|
||||
style: Theme.of(context).textTheme.labelMedium,
|
||||
),
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _messageController,
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'Message...',
|
||||
),
|
||||
textInputAction: TextInputAction.send,
|
||||
enabled: canSendMessages,
|
||||
onChanged: (_) => _handleComposerChanged(
|
||||
profilesAsync.valueOrNull ?? [],
|
||||
ref.read(currentUserIdProvider),
|
||||
canSendMessages,
|
||||
typingChannelId,
|
||||
),
|
||||
onSubmitted: (_) => _handleSendMessage(
|
||||
task,
|
||||
profilesAsync.valueOrNull ?? [],
|
||||
ref.read(currentUserIdProvider),
|
||||
canSendMessages,
|
||||
typingChannelId,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
IconButton(
|
||||
tooltip: 'Send',
|
||||
onPressed: canSendMessages
|
||||
? () => _handleSendMessage(
|
||||
task,
|
||||
profilesAsync.valueOrNull ?? [],
|
||||
ref.read(currentUserIdProvider),
|
||||
canSendMessages,
|
||||
typingChannelId,
|
||||
)
|
||||
: null,
|
||||
icon: const Icon(Icons.send),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _createdByLabel(
|
||||
AsyncValue<List<Profile>> profilesAsync,
|
||||
Task task,
|
||||
Ticket? ticket,
|
||||
) {
|
||||
final creatorId = task.creatorId ?? ticket?.creatorId;
|
||||
if (creatorId == null || creatorId.isEmpty) {
|
||||
return 'Created by: Unknown';
|
||||
}
|
||||
final profile = profilesAsync.valueOrNull
|
||||
?.where((item) => item.id == creatorId)
|
||||
.firstOrNull;
|
||||
final name = profile?.fullName.isNotEmpty == true
|
||||
? profile!.fullName
|
||||
: creatorId;
|
||||
return 'Created by: $name';
|
||||
}
|
||||
|
||||
Widget _buildMessages(
|
||||
BuildContext context,
|
||||
List<TicketMessage> messages,
|
||||
List<Profile> profiles,
|
||||
) {
|
||||
if (messages.isEmpty) {
|
||||
return const Center(child: Text('No messages yet.'));
|
||||
}
|
||||
final profileById = {for (final profile in profiles) profile.id: profile};
|
||||
final currentUserId = ref.read(currentUserIdProvider);
|
||||
|
||||
return ListView.builder(
|
||||
reverse: true,
|
||||
padding: const EdgeInsets.fromLTRB(0, 16, 0, 72),
|
||||
itemCount: messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
final message = messages[index];
|
||||
final isMe = currentUserId != null && message.senderId == currentUserId;
|
||||
final senderName = message.senderId == null
|
||||
? 'System'
|
||||
: profileById[message.senderId]?.fullName ?? message.senderId!;
|
||||
final bubbleColor = isMe
|
||||
? Theme.of(context).colorScheme.primaryContainer
|
||||
: Theme.of(context).colorScheme.surfaceContainerHighest;
|
||||
final textColor = isMe
|
||||
? Theme.of(context).colorScheme.onPrimaryContainer
|
||||
: Theme.of(context).colorScheme.onSurface;
|
||||
|
||||
return Align(
|
||||
alignment: isMe ? Alignment.centerRight : Alignment.centerLeft,
|
||||
child: Column(
|
||||
crossAxisAlignment: isMe
|
||||
? CrossAxisAlignment.end
|
||||
: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (!isMe)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Text(
|
||||
senderName,
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
),
|
||||
Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(12),
|
||||
constraints: const BoxConstraints(maxWidth: 520),
|
||||
decoration: BoxDecoration(
|
||||
color: bubbleColor,
|
||||
borderRadius: BorderRadius.only(
|
||||
topLeft: const Radius.circular(16),
|
||||
topRight: const Radius.circular(16),
|
||||
bottomLeft: Radius.circular(isMe ? 16 : 4),
|
||||
bottomRight: Radius.circular(isMe ? 4 : 16),
|
||||
),
|
||||
),
|
||||
child: _buildMentionText(message.content, textColor, profiles),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTatSection(Task task) {
|
||||
final animateQueue = task.status == 'queued';
|
||||
final animateExecution = task.startedAt != null && task.completedAt == null;
|
||||
|
||||
if (!animateQueue && !animateExecution) {
|
||||
return _buildTatContent(task, DateTime.now());
|
||||
}
|
||||
|
||||
return StreamBuilder<int>(
|
||||
stream: Stream.periodic(const Duration(seconds: 1), (tick) => tick),
|
||||
builder: (context, snapshot) {
|
||||
return _buildTatContent(task, DateTime.now());
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTatContent(Task task, DateTime now) {
|
||||
final queueDuration = task.status == 'queued'
|
||||
? now.difference(task.createdAt)
|
||||
: _safeDuration(task.startedAt?.difference(task.createdAt));
|
||||
final executionDuration = task.status == 'queued'
|
||||
? null
|
||||
: task.startedAt == null
|
||||
? null
|
||||
: task.completedAt == null
|
||||
? now.difference(task.startedAt!)
|
||||
: task.completedAt!.difference(task.startedAt!);
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Queue duration: ${_formatDuration(queueDuration)}'),
|
||||
const SizedBox(height: 8),
|
||||
Text('Task execution time: ${_formatDuration(executionDuration)}'),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Duration? _safeDuration(Duration? duration) {
|
||||
if (duration == null) {
|
||||
return null;
|
||||
}
|
||||
return duration.isNegative ? Duration.zero : duration;
|
||||
}
|
||||
|
||||
String _formatDuration(Duration? duration) {
|
||||
if (duration == null) {
|
||||
return 'Pending';
|
||||
}
|
||||
if (duration.inSeconds < 60) {
|
||||
return 'Less than a minute';
|
||||
}
|
||||
final hours = duration.inHours;
|
||||
final minutes = duration.inMinutes.remainder(60);
|
||||
if (hours > 0) {
|
||||
return '${hours}h ${minutes}m';
|
||||
}
|
||||
return '${minutes}m';
|
||||
}
|
||||
|
||||
Widget _buildMentionText(
|
||||
String text,
|
||||
Color baseColor,
|
||||
List<Profile> profiles,
|
||||
) {
|
||||
final mentionColor = Theme.of(context).colorScheme.primary;
|
||||
final spans = _mentionSpans(text, baseColor, mentionColor, profiles);
|
||||
return RichText(
|
||||
text: TextSpan(
|
||||
children: spans,
|
||||
style: TextStyle(color: baseColor),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<TextSpan> _mentionSpans(
|
||||
String text,
|
||||
Color baseColor,
|
||||
Color mentionColor,
|
||||
List<Profile> profiles,
|
||||
) {
|
||||
final mentionLabels = profiles
|
||||
.map(
|
||||
(profile) => profile.fullName.isEmpty ? profile.id : profile.fullName,
|
||||
)
|
||||
.where((label) => label.isNotEmpty)
|
||||
.map(_escapeRegExp)
|
||||
.toList();
|
||||
final pattern = mentionLabels.isEmpty
|
||||
? r'@\S+'
|
||||
: '@(?:${mentionLabels.join('|')})';
|
||||
final matches = RegExp(pattern, caseSensitive: false).allMatches(text);
|
||||
if (matches.isEmpty) {
|
||||
return [
|
||||
TextSpan(
|
||||
text: text,
|
||||
style: TextStyle(color: baseColor),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
final spans = <TextSpan>[];
|
||||
var lastIndex = 0;
|
||||
for (final match in matches) {
|
||||
if (match.start > lastIndex) {
|
||||
spans.add(
|
||||
TextSpan(
|
||||
text: text.substring(lastIndex, match.start),
|
||||
style: TextStyle(color: baseColor),
|
||||
),
|
||||
);
|
||||
}
|
||||
spans.add(
|
||||
TextSpan(
|
||||
text: text.substring(match.start, match.end),
|
||||
style: TextStyle(color: mentionColor, fontWeight: FontWeight.w700),
|
||||
),
|
||||
);
|
||||
lastIndex = match.end;
|
||||
}
|
||||
if (lastIndex < text.length) {
|
||||
spans.add(
|
||||
TextSpan(
|
||||
text: text.substring(lastIndex),
|
||||
style: TextStyle(color: baseColor),
|
||||
),
|
||||
);
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
String _escapeRegExp(String value) {
|
||||
return value.replaceAllMapped(
|
||||
RegExp(r'[\\^$.*+?()[\]{}|]'),
|
||||
(match) => '\\${match[0]}',
|
||||
);
|
||||
}
|
||||
|
||||
AsyncValue<List<TicketMessage>> _mergeMessages(
|
||||
AsyncValue<List<TicketMessage>> taskMessages,
|
||||
AsyncValue<List<TicketMessage>>? ticketMessages,
|
||||
) {
|
||||
if (ticketMessages == null) {
|
||||
return taskMessages;
|
||||
}
|
||||
return taskMessages.when(
|
||||
data: (taskData) => ticketMessages.when(
|
||||
data: (ticketData) {
|
||||
final byId = <int, TicketMessage>{
|
||||
for (final message in taskData) message.id: message,
|
||||
for (final message in ticketData) message.id: message,
|
||||
};
|
||||
final merged = byId.values.toList()
|
||||
..sort((a, b) => b.createdAt.compareTo(a.createdAt));
|
||||
return AsyncValue.data(merged);
|
||||
},
|
||||
loading: () => const AsyncLoading<List<TicketMessage>>(),
|
||||
error: (error, stackTrace) =>
|
||||
AsyncError<List<TicketMessage>>(error, stackTrace),
|
||||
),
|
||||
loading: () => const AsyncLoading<List<TicketMessage>>(),
|
||||
error: (error, stackTrace) =>
|
||||
AsyncError<List<TicketMessage>>(error, stackTrace),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _handleSendMessage(
|
||||
Task task,
|
||||
List<Profile> profiles,
|
||||
String? currentUserId,
|
||||
bool canSendMessages,
|
||||
String typingChannelId,
|
||||
) async {
|
||||
if (!canSendMessages) return;
|
||||
final content = _messageController.text.trim();
|
||||
if (content.isEmpty) {
|
||||
return;
|
||||
}
|
||||
ref.read(typingIndicatorProvider(typingChannelId).notifier).stopTyping();
|
||||
final message = await ref
|
||||
.read(ticketsControllerProvider)
|
||||
.sendTaskMessage(
|
||||
taskId: task.id,
|
||||
ticketId: task.ticketId,
|
||||
content: content,
|
||||
);
|
||||
final mentionUserIds = _extractMentionedUserIds(
|
||||
content,
|
||||
profiles,
|
||||
currentUserId,
|
||||
);
|
||||
if (mentionUserIds.isNotEmpty && currentUserId != null) {
|
||||
await ref
|
||||
.read(notificationsControllerProvider)
|
||||
.createMentionNotifications(
|
||||
userIds: mentionUserIds,
|
||||
actorId: currentUserId,
|
||||
ticketId: task.ticketId,
|
||||
taskId: task.id,
|
||||
messageId: message.id,
|
||||
);
|
||||
}
|
||||
ref.invalidate(taskMessagesProvider(task.id));
|
||||
if (task.ticketId != null) {
|
||||
ref.invalidate(ticketMessagesProvider(task.ticketId!));
|
||||
}
|
||||
if (mounted) {
|
||||
_messageController.clear();
|
||||
_clearMentions();
|
||||
}
|
||||
}
|
||||
|
||||
void _handleComposerChanged(
|
||||
List<Profile> profiles,
|
||||
String? currentUserId,
|
||||
bool canSendMessages,
|
||||
String typingChannelId,
|
||||
) {
|
||||
if (!canSendMessages) {
|
||||
ref.read(typingIndicatorProvider(typingChannelId).notifier).stopTyping();
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
ref.read(typingIndicatorProvider(typingChannelId).notifier).userTyping();
|
||||
final text = _messageController.text;
|
||||
final cursor = _messageController.selection.baseOffset;
|
||||
if (cursor < 0) {
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
final textBeforeCursor = text.substring(0, cursor);
|
||||
final atIndex = textBeforeCursor.lastIndexOf('@');
|
||||
if (atIndex == -1) {
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
if (atIndex > 0 && !_isWhitespace(textBeforeCursor[atIndex - 1])) {
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
final query = textBeforeCursor.substring(atIndex + 1);
|
||||
if (query.contains(RegExp(r'\s'))) {
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
final normalizedQuery = query.toLowerCase();
|
||||
final candidates = profiles.where((profile) {
|
||||
if (profile.id == currentUserId) {
|
||||
return false;
|
||||
}
|
||||
final label = profile.fullName.isEmpty ? profile.id : profile.fullName;
|
||||
return label.toLowerCase().contains(normalizedQuery);
|
||||
}).toList();
|
||||
setState(() {
|
||||
_mentionQuery = query;
|
||||
_mentionStart = atIndex;
|
||||
_mentionResults = candidates.take(6).toList();
|
||||
});
|
||||
}
|
||||
|
||||
void _clearMentions() {
|
||||
if (_mentionQuery == null && _mentionResults.isEmpty) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_mentionQuery = null;
|
||||
_mentionStart = null;
|
||||
_mentionResults = [];
|
||||
});
|
||||
}
|
||||
|
||||
bool _isWhitespace(String char) {
|
||||
return char.trim().isEmpty;
|
||||
}
|
||||
|
||||
List<String> _extractMentionedUserIds(
|
||||
String content,
|
||||
List<Profile> profiles,
|
||||
String? currentUserId,
|
||||
) {
|
||||
final lower = content.toLowerCase();
|
||||
final mentioned = <String>{};
|
||||
for (final profile in profiles) {
|
||||
if (profile.id == currentUserId) continue;
|
||||
final label = profile.fullName.isEmpty ? profile.id : profile.fullName;
|
||||
if (label.isEmpty) continue;
|
||||
final token = '@${label.toLowerCase()}';
|
||||
if (lower.contains(token)) {
|
||||
mentioned.add(profile.id);
|
||||
}
|
||||
}
|
||||
return mentioned.toList();
|
||||
}
|
||||
|
||||
Widget _buildMentionList(AsyncValue<List<Profile>> profilesAsync) {
|
||||
if (_mentionResults.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return Container(
|
||||
constraints: const BoxConstraints(maxHeight: 200),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: ListView.separated(
|
||||
shrinkWrap: true,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: _mentionResults.length,
|
||||
separatorBuilder: (context, index) => const SizedBox(height: 4),
|
||||
itemBuilder: (context, index) {
|
||||
final profile = _mentionResults[index];
|
||||
final label = profile.fullName.isEmpty
|
||||
? profile.id
|
||||
: profile.fullName;
|
||||
return ListTile(
|
||||
dense: true,
|
||||
title: Text(label),
|
||||
onTap: () => _insertMention(profile),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _insertMention(Profile profile) {
|
||||
final start = _mentionStart;
|
||||
if (start == null) {
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
final text = _messageController.text;
|
||||
final cursor = _messageController.selection.baseOffset;
|
||||
final end = cursor < 0 ? text.length : cursor;
|
||||
final label = profile.fullName.isEmpty ? profile.id : profile.fullName;
|
||||
final mentionText = '@$label ';
|
||||
final updated = text.replaceRange(start, end, mentionText);
|
||||
final newCursor = start + mentionText.length;
|
||||
_messageController.text = updated;
|
||||
_messageController.selection = TextSelection.collapsed(offset: newCursor);
|
||||
_clearMentions();
|
||||
}
|
||||
|
||||
String _typingLabel(
|
||||
Set<String> userIds,
|
||||
AsyncValue<List<Profile>> profilesAsync,
|
||||
) {
|
||||
final profileById = {
|
||||
for (final profile in profilesAsync.valueOrNull ?? [])
|
||||
profile.id: profile,
|
||||
};
|
||||
final names = userIds
|
||||
.map((id) => profileById[id]?.fullName ?? id)
|
||||
.where((name) => name.isNotEmpty)
|
||||
.toList();
|
||||
if (names.isEmpty) {
|
||||
return 'Someone is typing...';
|
||||
}
|
||||
if (names.length == 1) {
|
||||
return '${names.first} is typing...';
|
||||
}
|
||||
if (names.length == 2) {
|
||||
return '${names[0]} and ${names[1]} are typing...';
|
||||
}
|
||||
return '${names[0]}, ${names[1]} and others are typing...';
|
||||
}
|
||||
|
||||
Task? _findTask(AsyncValue<List<Task>> tasksAsync, String taskId) {
|
||||
return tasksAsync.maybeWhen(
|
||||
data: (tasks) => tasks.where((task) => task.id == taskId).firstOrNull,
|
||||
orElse: () => null,
|
||||
);
|
||||
}
|
||||
|
||||
Ticket? _findTicket(AsyncValue<List<Ticket>> ticketsAsync, String ticketId) {
|
||||
return ticketsAsync.maybeWhen(
|
||||
data: (tickets) =>
|
||||
tickets.where((ticket) => ticket.id == ticketId).firstOrNull,
|
||||
orElse: () => null,
|
||||
);
|
||||
}
|
||||
|
||||
bool _canAssignStaff(String role) {
|
||||
return role == 'admin' || role == 'dispatcher' || role == 'it_staff';
|
||||
}
|
||||
|
||||
Widget _buildStatusChip(
|
||||
BuildContext context,
|
||||
Task task,
|
||||
bool canUpdateStatus,
|
||||
) {
|
||||
final chip = Chip(
|
||||
label: Text(task.status.toUpperCase()),
|
||||
backgroundColor: _statusColor(context, task.status),
|
||||
labelStyle: TextStyle(
|
||||
color: _statusTextColor(context, task.status),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
);
|
||||
|
||||
if (!canUpdateStatus) {
|
||||
return chip;
|
||||
}
|
||||
|
||||
return PopupMenuButton<String>(
|
||||
onSelected: (value) async {
|
||||
await ref
|
||||
.read(tasksControllerProvider)
|
||||
.updateTaskStatus(taskId: task.id, status: value);
|
||||
ref.invalidate(tasksProvider);
|
||||
},
|
||||
itemBuilder: (context) => _statusOptions
|
||||
.map(
|
||||
(status) => PopupMenuItem(
|
||||
value: status,
|
||||
child: Text(_statusMenuLabel(status)),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
child: chip,
|
||||
);
|
||||
}
|
||||
|
||||
String _statusMenuLabel(String status) {
|
||||
return switch (status) {
|
||||
'queued' => 'Queued',
|
||||
'in_progress' => 'In progress',
|
||||
'completed' => 'Completed',
|
||||
_ => status,
|
||||
};
|
||||
}
|
||||
|
||||
Color _statusColor(BuildContext context, String status) {
|
||||
return switch (status) {
|
||||
'queued' => Colors.blueGrey.shade200,
|
||||
'in_progress' => Colors.blue.shade300,
|
||||
'completed' => Colors.green.shade300,
|
||||
_ => Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
};
|
||||
}
|
||||
|
||||
Color _statusTextColor(BuildContext context, String status) {
|
||||
return switch (status) {
|
||||
'queued' => Colors.blueGrey.shade900,
|
||||
'in_progress' => Colors.blue.shade900,
|
||||
'completed' => Colors.green.shade900,
|
||||
_ => Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
};
|
||||
}
|
||||
|
||||
bool _canUpdateStatus(
|
||||
Profile? profile,
|
||||
List<TaskAssignment> assignments,
|
||||
String taskId,
|
||||
) {
|
||||
if (profile == null) {
|
||||
return false;
|
||||
}
|
||||
final isGlobal =
|
||||
profile.role == 'admin' ||
|
||||
profile.role == 'dispatcher' ||
|
||||
profile.role == 'it_staff';
|
||||
if (isGlobal) {
|
||||
return true;
|
||||
}
|
||||
return assignments.any(
|
||||
(assignment) =>
|
||||
assignment.taskId == taskId && assignment.userId == profile.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension _FirstOrNull<T> on Iterable<T> {
|
||||
T? get firstOrNull => isEmpty ? null : first;
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../models/notification_item.dart';
|
||||
import '../../models/task.dart';
|
||||
import '../../providers/notifications_provider.dart';
|
||||
import '../../providers/profile_provider.dart';
|
||||
import '../../providers/tasks_provider.dart';
|
||||
import '../../providers/tickets_provider.dart';
|
||||
import '../../providers/typing_provider.dart';
|
||||
import '../../widgets/responsive_body.dart';
|
||||
import '../../widgets/typing_dots.dart';
|
||||
|
||||
class TasksListScreen extends ConsumerWidget {
|
||||
const TasksListScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tasksAsync = ref.watch(tasksProvider);
|
||||
final ticketsAsync = ref.watch(ticketsProvider);
|
||||
final officesAsync = ref.watch(officesProvider);
|
||||
final profileAsync = ref.watch(currentProfileProvider);
|
||||
final notificationsAsync = ref.watch(notificationsProvider);
|
||||
|
||||
final canCreate = profileAsync.maybeWhen(
|
||||
data: (profile) =>
|
||||
profile != null &&
|
||||
(profile.role == 'admin' ||
|
||||
profile.role == 'dispatcher' ||
|
||||
profile.role == 'it_staff'),
|
||||
orElse: () => false,
|
||||
);
|
||||
|
||||
final ticketById = {
|
||||
for (final ticket in ticketsAsync.valueOrNull ?? []) ticket.id: ticket,
|
||||
};
|
||||
final officeById = {
|
||||
for (final office in officesAsync.valueOrNull ?? []) office.id: office,
|
||||
};
|
||||
|
||||
return Scaffold(
|
||||
body: ResponsiveBody(
|
||||
child: tasksAsync.when(
|
||||
data: (tasks) {
|
||||
if (tasks.isEmpty) {
|
||||
return const Center(child: Text('No tasks yet.'));
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16, bottom: 8),
|
||||
child: Align(
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
'Tasks',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView.separated(
|
||||
padding: const EdgeInsets.only(bottom: 24),
|
||||
itemCount: tasks.length,
|
||||
separatorBuilder: (context, index) =>
|
||||
const SizedBox(height: 12),
|
||||
itemBuilder: (context, index) {
|
||||
final task = tasks[index];
|
||||
final ticketId = task.ticketId;
|
||||
final ticket = ticketId == null
|
||||
? null
|
||||
: ticketById[ticketId];
|
||||
final officeId = ticket?.officeId ?? task.officeId;
|
||||
final officeName = officeId == null
|
||||
? 'Unassigned office'
|
||||
: (officeById[officeId]?.name ?? officeId);
|
||||
final subtitle = _buildSubtitle(officeName, task.status);
|
||||
final hasMention = _hasTaskMention(
|
||||
notificationsAsync,
|
||||
task,
|
||||
);
|
||||
final typingChannelId = task.id;
|
||||
final typingState = ref.watch(
|
||||
typingIndicatorProvider(typingChannelId),
|
||||
);
|
||||
final showTyping = typingState.userIds.isNotEmpty;
|
||||
|
||||
return ListTile(
|
||||
leading: _buildQueueBadge(context, task),
|
||||
title: Text(
|
||||
task.title.isNotEmpty
|
||||
? task.title
|
||||
: (ticket?.subject ?? 'Task ${task.id}'),
|
||||
),
|
||||
subtitle: Text(subtitle),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_buildStatusChip(context, task.status),
|
||||
if (showTyping) ...[
|
||||
const SizedBox(width: 6),
|
||||
TypingDots(
|
||||
size: 6,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
],
|
||||
if (hasMention)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(left: 8),
|
||||
child: Icon(
|
||||
Icons.circle,
|
||||
size: 10,
|
||||
color: Colors.red,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
onTap: () => context.go('/tasks/${task.id}'),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, _) =>
|
||||
Center(child: Text('Failed to load tasks: $error')),
|
||||
),
|
||||
),
|
||||
floatingActionButton: canCreate
|
||||
? FloatingActionButton.extended(
|
||||
onPressed: () => _showCreateTaskDialog(context, ref),
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('New Task'),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showCreateTaskDialog(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
) async {
|
||||
final titleController = TextEditingController();
|
||||
final descriptionController = TextEditingController();
|
||||
String? selectedOfficeId;
|
||||
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
return StatefulBuilder(
|
||||
builder: (context, setState) {
|
||||
final officesAsync = ref.watch(officesProvider);
|
||||
return AlertDialog(
|
||||
title: const Text('Create Task'),
|
||||
content: SizedBox(
|
||||
width: 360,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextField(
|
||||
controller: titleController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Task title',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: descriptionController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Description',
|
||||
),
|
||||
maxLines: 3,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
officesAsync.when(
|
||||
data: (offices) {
|
||||
if (offices.isEmpty) {
|
||||
return const Text('No offices available.');
|
||||
}
|
||||
selectedOfficeId ??= offices.first.id;
|
||||
return DropdownButtonFormField<String>(
|
||||
initialValue: selectedOfficeId,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Office',
|
||||
),
|
||||
items: offices
|
||||
.map(
|
||||
(office) => DropdownMenuItem(
|
||||
value: office.id,
|
||||
child: Text(office.name),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
onChanged: (value) =>
|
||||
setState(() => selectedOfficeId = value),
|
||||
);
|
||||
},
|
||||
loading: () => const Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
error: (error, _) =>
|
||||
Text('Failed to load offices: $error'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final title = titleController.text.trim();
|
||||
final description = descriptionController.text.trim();
|
||||
final officeId = selectedOfficeId;
|
||||
if (title.isEmpty || officeId == null) {
|
||||
return;
|
||||
}
|
||||
await ref
|
||||
.read(tasksControllerProvider)
|
||||
.createTask(
|
||||
title: title,
|
||||
description: description,
|
||||
officeId: officeId,
|
||||
);
|
||||
if (context.mounted) {
|
||||
Navigator.of(dialogContext).pop();
|
||||
}
|
||||
},
|
||||
child: const Text('Create'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
bool _hasTaskMention(
|
||||
AsyncValue<List<NotificationItem>> notificationsAsync,
|
||||
Task task,
|
||||
) {
|
||||
return notificationsAsync.maybeWhen(
|
||||
data: (items) => items.any(
|
||||
(item) =>
|
||||
item.isUnread &&
|
||||
(item.taskId == task.id || item.ticketId == task.ticketId),
|
||||
),
|
||||
orElse: () => false,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildQueueBadge(BuildContext context, Task task) {
|
||||
final queueOrder = task.queueOrder;
|
||||
final isQueued = task.status == 'queued';
|
||||
if (!isQueued || queueOrder == null) {
|
||||
return const Icon(Icons.fact_check_outlined);
|
||||
}
|
||||
return Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
'#$queueOrder',
|
||||
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
color: Theme.of(context).colorScheme.onPrimaryContainer,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _buildSubtitle(String officeName, String status) {
|
||||
final statusLabel = status.toUpperCase();
|
||||
return '$officeName · $statusLabel';
|
||||
}
|
||||
|
||||
Widget _buildStatusChip(BuildContext context, String status) {
|
||||
return Chip(
|
||||
label: Text(status.toUpperCase()),
|
||||
backgroundColor: _statusColor(context, status),
|
||||
labelStyle: TextStyle(
|
||||
color: _statusTextColor(context, status),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Color _statusColor(BuildContext context, String status) {
|
||||
return switch (status) {
|
||||
'queued' => Colors.blueGrey.shade200,
|
||||
'in_progress' => Colors.blue.shade300,
|
||||
'completed' => Colors.green.shade300,
|
||||
_ => Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
};
|
||||
}
|
||||
|
||||
Color _statusTextColor(BuildContext context, String status) {
|
||||
return switch (status) {
|
||||
'queued' => Colors.blueGrey.shade900,
|
||||
'in_progress' => Colors.blue.shade900,
|
||||
'completed' => Colors.green.shade900,
|
||||
_ => Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,859 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
import '../../models/office.dart';
|
||||
import '../../models/profile.dart';
|
||||
import '../../models/task.dart';
|
||||
import '../../models/ticket.dart';
|
||||
import '../../models/ticket_message.dart';
|
||||
import '../../providers/notifications_provider.dart';
|
||||
import '../../providers/profile_provider.dart';
|
||||
import '../../providers/tasks_provider.dart';
|
||||
import '../../providers/tickets_provider.dart';
|
||||
import '../../providers/typing_provider.dart';
|
||||
import '../../widgets/responsive_body.dart';
|
||||
import '../../widgets/task_assignment_section.dart';
|
||||
import '../../widgets/typing_dots.dart';
|
||||
|
||||
class TicketDetailScreen extends ConsumerStatefulWidget {
|
||||
const TicketDetailScreen({super.key, required this.ticketId});
|
||||
|
||||
final String ticketId;
|
||||
|
||||
@override
|
||||
ConsumerState<TicketDetailScreen> createState() => _TicketDetailScreenState();
|
||||
}
|
||||
|
||||
class _TicketDetailScreenState extends ConsumerState<TicketDetailScreen> {
|
||||
final _messageController = TextEditingController();
|
||||
static const List<String> _statusOptions = ['pending', 'promoted', 'closed'];
|
||||
String? _mentionQuery;
|
||||
int? _mentionStart;
|
||||
List<Profile> _mentionResults = [];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
Future.microtask(
|
||||
() => ref
|
||||
.read(notificationsControllerProvider)
|
||||
.markReadForTicket(widget.ticketId),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_messageController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final ticket = _findTicket(ref, widget.ticketId);
|
||||
final messagesAsync = ref.watch(ticketMessagesProvider(widget.ticketId));
|
||||
final profilesAsync = ref.watch(profilesProvider);
|
||||
final officesAsync = ref.watch(officesProvider);
|
||||
final currentProfileAsync = ref.watch(currentProfileProvider);
|
||||
final tasksAsync = ref.watch(tasksProvider);
|
||||
final typingState = ref.watch(typingIndicatorProvider(widget.ticketId));
|
||||
final canPromote = currentProfileAsync.maybeWhen(
|
||||
data: (profile) => profile != null && _canPromote(profile.role),
|
||||
orElse: () => false,
|
||||
);
|
||||
final canSendMessages = ticket != null && ticket.status != 'closed';
|
||||
final canAssign = currentProfileAsync.maybeWhen(
|
||||
data: (profile) => profile != null && _canAssignStaff(profile.role),
|
||||
orElse: () => false,
|
||||
);
|
||||
final showAssign = canAssign && ticket?.status != 'closed';
|
||||
final taskForTicket = ticket == null
|
||||
? null
|
||||
: _findTaskForTicket(tasksAsync, ticket.id);
|
||||
final hasStaffMessage = _hasStaffMessage(
|
||||
messagesAsync.valueOrNull ?? const [],
|
||||
profilesAsync.valueOrNull ?? const [],
|
||||
);
|
||||
final effectiveRespondedAt = ticket?.promotedAt != null && !hasStaffMessage
|
||||
? ticket!.promotedAt
|
||||
: ticket?.respondedAt;
|
||||
|
||||
return ResponsiveBody(
|
||||
child: Column(
|
||||
children: [
|
||||
if (ticket != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
ticket.subject,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Align(
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
_filedByLabel(profilesAsync, ticket),
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 8,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
_buildStatusChip(context, ref, ticket, canPromote),
|
||||
Text('Office: ${_officeLabel(officesAsync, ticket)}'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(ticket.description),
|
||||
const SizedBox(height: 12),
|
||||
_buildTatRow(context, ticket, effectiveRespondedAt),
|
||||
if (taskForTicket != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: TaskAssignmentSection(
|
||||
taskId: taskForTicket.id,
|
||||
canAssign: showAssign,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
tooltip: 'Open task',
|
||||
onPressed: () =>
|
||||
context.go('/tasks/${taskForTicket.id}'),
|
||||
icon: const Icon(Icons.open_in_new),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
Expanded(
|
||||
child: messagesAsync.when(
|
||||
data: (messages) {
|
||||
if (messages.isEmpty) {
|
||||
return const Center(child: Text('No messages yet.'));
|
||||
}
|
||||
final profileById = {
|
||||
for (final profile in profilesAsync.valueOrNull ?? [])
|
||||
profile.id: profile,
|
||||
};
|
||||
return ListView.builder(
|
||||
reverse: true,
|
||||
padding: const EdgeInsets.fromLTRB(0, 16, 0, 72),
|
||||
itemCount: messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
final message = messages[index];
|
||||
final currentUserId =
|
||||
Supabase.instance.client.auth.currentUser?.id;
|
||||
final isMe =
|
||||
currentUserId != null &&
|
||||
message.senderId == currentUserId;
|
||||
final senderName = message.senderId == null
|
||||
? 'System'
|
||||
: profileById[message.senderId]?.fullName ??
|
||||
message.senderId!;
|
||||
final bubbleColor = isMe
|
||||
? Theme.of(context).colorScheme.primaryContainer
|
||||
: Theme.of(context).colorScheme.surfaceContainerHighest;
|
||||
final textColor = isMe
|
||||
? Theme.of(context).colorScheme.onPrimaryContainer
|
||||
: Theme.of(context).colorScheme.onSurface;
|
||||
|
||||
return Align(
|
||||
alignment: isMe
|
||||
? Alignment.centerRight
|
||||
: Alignment.centerLeft,
|
||||
child: Column(
|
||||
crossAxisAlignment: isMe
|
||||
? CrossAxisAlignment.end
|
||||
: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (!isMe)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Text(
|
||||
senderName,
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
),
|
||||
Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(12),
|
||||
constraints: const BoxConstraints(maxWidth: 520),
|
||||
decoration: BoxDecoration(
|
||||
color: bubbleColor,
|
||||
borderRadius: BorderRadius.only(
|
||||
topLeft: const Radius.circular(16),
|
||||
topRight: const Radius.circular(16),
|
||||
bottomLeft: Radius.circular(isMe ? 16 : 4),
|
||||
bottomRight: Radius.circular(isMe ? 4 : 16),
|
||||
),
|
||||
),
|
||||
child: _buildMentionText(
|
||||
message.content,
|
||||
textColor,
|
||||
profilesAsync.valueOrNull ?? [],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, _) =>
|
||||
Center(child: Text('Failed to load messages: $error')),
|
||||
),
|
||||
),
|
||||
SafeArea(
|
||||
top: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(0, 8, 0, 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (typingState.userIds.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 6),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 10,
|
||||
vertical: 6,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_typingLabel(typingState.userIds, profilesAsync),
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
TypingDots(
|
||||
size: 8,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_mentionQuery != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: _buildMentionList(profilesAsync),
|
||||
),
|
||||
if (!canSendMessages)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text(
|
||||
'Messaging is disabled for closed tickets.',
|
||||
style: Theme.of(context).textTheme.labelMedium,
|
||||
),
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _messageController,
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'Message...',
|
||||
),
|
||||
enabled: canSendMessages,
|
||||
textInputAction: TextInputAction.send,
|
||||
onChanged: canSendMessages
|
||||
? (_) => _handleComposerChanged(
|
||||
profilesAsync.valueOrNull ?? [],
|
||||
Supabase.instance.client.auth.currentUser?.id,
|
||||
canSendMessages,
|
||||
)
|
||||
: null,
|
||||
onSubmitted: canSendMessages
|
||||
? (_) => _handleSendMessage(
|
||||
ref,
|
||||
profilesAsync.valueOrNull ?? [],
|
||||
Supabase.instance.client.auth.currentUser?.id,
|
||||
canSendMessages,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
IconButton(
|
||||
tooltip: 'Send',
|
||||
onPressed: canSendMessages
|
||||
? () => _handleSendMessage(
|
||||
ref,
|
||||
profilesAsync.valueOrNull ?? [],
|
||||
Supabase.instance.client.auth.currentUser?.id,
|
||||
canSendMessages,
|
||||
)
|
||||
: null,
|
||||
icon: const Icon(Icons.send),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _filedByLabel(AsyncValue<List<Profile>> profilesAsync, Ticket ticket) {
|
||||
final creatorId = ticket.creatorId;
|
||||
if (creatorId == null || creatorId.isEmpty) {
|
||||
return 'Filed by: Unknown';
|
||||
}
|
||||
final profile = profilesAsync.valueOrNull
|
||||
?.where((item) => item.id == creatorId)
|
||||
.firstOrNull;
|
||||
final name = profile?.fullName.isNotEmpty == true
|
||||
? profile!.fullName
|
||||
: creatorId;
|
||||
return 'Filed by: $name';
|
||||
}
|
||||
|
||||
Ticket? _findTicket(WidgetRef ref, String ticketId) {
|
||||
final ticketsAsync = ref.watch(ticketsProvider);
|
||||
return ticketsAsync.maybeWhen(
|
||||
data: (tickets) =>
|
||||
tickets.where((ticket) => ticket.id == ticketId).firstOrNull,
|
||||
orElse: () => null,
|
||||
);
|
||||
}
|
||||
|
||||
bool _hasStaffMessage(List<TicketMessage> messages, List<Profile> profiles) {
|
||||
if (messages.isEmpty || profiles.isEmpty) {
|
||||
return false;
|
||||
}
|
||||
final staffIds = profiles
|
||||
.where(
|
||||
(profile) =>
|
||||
profile.role == 'admin' ||
|
||||
profile.role == 'dispatcher' ||
|
||||
profile.role == 'it_staff',
|
||||
)
|
||||
.map((profile) => profile.id)
|
||||
.toSet();
|
||||
if (staffIds.isEmpty) {
|
||||
return false;
|
||||
}
|
||||
return messages.any(
|
||||
(message) =>
|
||||
message.senderId != null && staffIds.contains(message.senderId!),
|
||||
);
|
||||
}
|
||||
|
||||
Task? _findTaskForTicket(AsyncValue<List<Task>> tasksAsync, String ticketId) {
|
||||
return tasksAsync.maybeWhen(
|
||||
data: (tasks) =>
|
||||
tasks.where((task) => task.ticketId == ticketId).firstOrNull,
|
||||
orElse: () => null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _handleSendMessage(
|
||||
WidgetRef ref,
|
||||
List<Profile> profiles,
|
||||
String? currentUserId,
|
||||
bool canSendMessages,
|
||||
) async {
|
||||
if (!canSendMessages) return;
|
||||
final content = _messageController.text.trim();
|
||||
if (content.isEmpty) return;
|
||||
ref.read(typingIndicatorProvider(widget.ticketId).notifier).stopTyping();
|
||||
final message = await ref
|
||||
.read(ticketsControllerProvider)
|
||||
.sendTicketMessage(ticketId: widget.ticketId, content: content);
|
||||
final mentionUserIds = _extractMentionedUserIds(
|
||||
content,
|
||||
profiles,
|
||||
currentUserId,
|
||||
);
|
||||
if (mentionUserIds.isNotEmpty && currentUserId != null) {
|
||||
await ref
|
||||
.read(notificationsControllerProvider)
|
||||
.createMentionNotifications(
|
||||
userIds: mentionUserIds,
|
||||
actorId: currentUserId,
|
||||
ticketId: widget.ticketId,
|
||||
messageId: message.id,
|
||||
);
|
||||
}
|
||||
ref.invalidate(ticketMessagesProvider(widget.ticketId));
|
||||
if (mounted) {
|
||||
_messageController.clear();
|
||||
_clearMentions();
|
||||
}
|
||||
}
|
||||
|
||||
List<String> _extractMentionedUserIds(
|
||||
String content,
|
||||
List<Profile> profiles,
|
||||
String? currentUserId,
|
||||
) {
|
||||
final lower = content.toLowerCase();
|
||||
final mentioned = <String>{};
|
||||
for (final profile in profiles) {
|
||||
if (profile.id == currentUserId) continue;
|
||||
final label = profile.fullName.isEmpty ? profile.id : profile.fullName;
|
||||
if (label.isEmpty) continue;
|
||||
final token = '@${label.toLowerCase()}';
|
||||
if (lower.contains(token)) {
|
||||
mentioned.add(profile.id);
|
||||
}
|
||||
}
|
||||
return mentioned.toList();
|
||||
}
|
||||
|
||||
void _handleComposerChanged(
|
||||
List<Profile> profiles,
|
||||
String? currentUserId,
|
||||
bool canSendMessages,
|
||||
) {
|
||||
if (!canSendMessages) {
|
||||
ref.read(typingIndicatorProvider(widget.ticketId).notifier).stopTyping();
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
ref.read(typingIndicatorProvider(widget.ticketId).notifier).userTyping();
|
||||
final text = _messageController.text;
|
||||
final cursor = _messageController.selection.baseOffset;
|
||||
if (cursor < 0) {
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
final textBeforeCursor = text.substring(0, cursor);
|
||||
final atIndex = textBeforeCursor.lastIndexOf('@');
|
||||
if (atIndex == -1) {
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
if (atIndex > 0 && !_isWhitespace(textBeforeCursor[atIndex - 1])) {
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
final query = textBeforeCursor.substring(atIndex + 1);
|
||||
if (query.contains(RegExp(r'\s'))) {
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
final normalizedQuery = query.toLowerCase();
|
||||
final candidates = profiles.where((profile) {
|
||||
if (profile.id == currentUserId) {
|
||||
return false;
|
||||
}
|
||||
final label = profile.fullName.isEmpty ? profile.id : profile.fullName;
|
||||
return label.toLowerCase().contains(normalizedQuery);
|
||||
}).toList();
|
||||
setState(() {
|
||||
_mentionQuery = query;
|
||||
_mentionStart = atIndex;
|
||||
_mentionResults = candidates.take(6).toList();
|
||||
});
|
||||
}
|
||||
|
||||
void _clearMentions() {
|
||||
if (_mentionQuery == null && _mentionResults.isEmpty) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_mentionQuery = null;
|
||||
_mentionStart = null;
|
||||
_mentionResults = [];
|
||||
});
|
||||
}
|
||||
|
||||
bool _isWhitespace(String char) {
|
||||
return char.trim().isEmpty;
|
||||
}
|
||||
|
||||
String _typingLabel(
|
||||
Set<String> userIds,
|
||||
AsyncValue<List<Profile>> profilesAsync,
|
||||
) {
|
||||
final profileById = {
|
||||
for (final profile in profilesAsync.valueOrNull ?? [])
|
||||
profile.id: profile,
|
||||
};
|
||||
final names = userIds
|
||||
.map((id) => profileById[id]?.fullName ?? id)
|
||||
.where((name) => name.isNotEmpty)
|
||||
.toList();
|
||||
if (names.isEmpty) {
|
||||
return 'Someone is typing...';
|
||||
}
|
||||
if (names.length == 1) {
|
||||
return '${names.first} is typing...';
|
||||
}
|
||||
if (names.length == 2) {
|
||||
return '${names[0]} and ${names[1]} are typing...';
|
||||
}
|
||||
return '${names[0]}, ${names[1]} and others are typing...';
|
||||
}
|
||||
|
||||
Widget _buildMentionList(AsyncValue<List<Profile>> profilesAsync) {
|
||||
if (_mentionResults.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return Container(
|
||||
constraints: const BoxConstraints(maxHeight: 200),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: ListView.separated(
|
||||
shrinkWrap: true,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: _mentionResults.length,
|
||||
separatorBuilder: (context, index) => const SizedBox(height: 4),
|
||||
itemBuilder: (context, index) {
|
||||
final profile = _mentionResults[index];
|
||||
final label = profile.fullName.isEmpty
|
||||
? profile.id
|
||||
: profile.fullName;
|
||||
return ListTile(
|
||||
dense: true,
|
||||
title: Text(label),
|
||||
onTap: () => _insertMention(profile),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _insertMention(Profile profile) {
|
||||
final start = _mentionStart;
|
||||
if (start == null) {
|
||||
_clearMentions();
|
||||
return;
|
||||
}
|
||||
final text = _messageController.text;
|
||||
final cursor = _messageController.selection.baseOffset;
|
||||
final end = cursor < 0 ? text.length : cursor;
|
||||
final label = profile.fullName.isEmpty ? profile.id : profile.fullName;
|
||||
final mentionText = '@$label ';
|
||||
final updated = text.replaceRange(start, end, mentionText);
|
||||
final newCursor = start + mentionText.length;
|
||||
_messageController.text = updated;
|
||||
_messageController.selection = TextSelection.collapsed(offset: newCursor);
|
||||
_clearMentions();
|
||||
}
|
||||
|
||||
Widget _buildTatRow(
|
||||
BuildContext context,
|
||||
Ticket ticket,
|
||||
DateTime? respondedAtOverride,
|
||||
) {
|
||||
final respondedAt = respondedAtOverride ?? ticket.respondedAt;
|
||||
final responseDuration = respondedAt?.difference(ticket.createdAt);
|
||||
final triageEnd = _earliestDate(ticket.promotedAt, ticket.closedAt);
|
||||
final triageStart = respondedAt;
|
||||
final triageDuration = triageStart == null || triageEnd == null
|
||||
? null
|
||||
: triageEnd.difference(triageStart);
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Response time: ${responseDuration == null ? 'Pending' : _formatDuration(responseDuration)}',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Triage duration: ${triageDuration == null ? 'Pending' : _formatDuration(triageDuration)}',
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'View timeline',
|
||||
onPressed: () => _showTimelineDialog(context, ticket),
|
||||
icon: const Icon(Icons.access_time),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMentionText(
|
||||
String text,
|
||||
Color baseColor,
|
||||
List<Profile> profiles,
|
||||
) {
|
||||
final mentionColor = Theme.of(context).colorScheme.primary;
|
||||
final spans = _mentionSpans(text, baseColor, mentionColor, profiles);
|
||||
return RichText(
|
||||
text: TextSpan(
|
||||
children: spans,
|
||||
style: TextStyle(color: baseColor),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<TextSpan> _mentionSpans(
|
||||
String text,
|
||||
Color baseColor,
|
||||
Color mentionColor,
|
||||
List<Profile> profiles,
|
||||
) {
|
||||
final mentionLabels = profiles
|
||||
.map(
|
||||
(profile) => profile.fullName.isEmpty ? profile.id : profile.fullName,
|
||||
)
|
||||
.where((label) => label.isNotEmpty)
|
||||
.map(_escapeRegExp)
|
||||
.toList();
|
||||
final pattern = mentionLabels.isEmpty
|
||||
? r'@\S+'
|
||||
: '@(?:${mentionLabels.join('|')})';
|
||||
final matches = RegExp(pattern, caseSensitive: false).allMatches(text);
|
||||
if (matches.isEmpty) {
|
||||
return [
|
||||
TextSpan(
|
||||
text: text,
|
||||
style: TextStyle(color: baseColor),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
final spans = <TextSpan>[];
|
||||
var lastIndex = 0;
|
||||
for (final match in matches) {
|
||||
if (match.start > lastIndex) {
|
||||
spans.add(
|
||||
TextSpan(
|
||||
text: text.substring(lastIndex, match.start),
|
||||
style: TextStyle(color: baseColor),
|
||||
),
|
||||
);
|
||||
}
|
||||
spans.add(
|
||||
TextSpan(
|
||||
text: text.substring(match.start, match.end),
|
||||
style: TextStyle(color: mentionColor, fontWeight: FontWeight.w700),
|
||||
),
|
||||
);
|
||||
lastIndex = match.end;
|
||||
}
|
||||
if (lastIndex < text.length) {
|
||||
spans.add(
|
||||
TextSpan(
|
||||
text: text.substring(lastIndex),
|
||||
style: TextStyle(color: baseColor),
|
||||
),
|
||||
);
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
String _escapeRegExp(String value) {
|
||||
return value.replaceAllMapped(
|
||||
RegExp(r'[\\^$.*+?()[\]{}|]'),
|
||||
(match) => '\\${match[0]}',
|
||||
);
|
||||
}
|
||||
|
||||
DateTime? _earliestDate(DateTime? first, DateTime? second) {
|
||||
if (first == null) return second;
|
||||
if (second == null) return first;
|
||||
return first.isBefore(second) ? first : second;
|
||||
}
|
||||
|
||||
String _officeLabel(AsyncValue<List<Office>> officesAsync, Ticket ticket) {
|
||||
final offices = officesAsync.valueOrNull ?? [];
|
||||
final office = offices
|
||||
.where((item) => item.id == ticket.officeId)
|
||||
.firstOrNull;
|
||||
return office?.name ?? ticket.officeId;
|
||||
}
|
||||
|
||||
String _formatDate(DateTime value) {
|
||||
final local = value.toLocal();
|
||||
final monthNames = [
|
||||
'Jan',
|
||||
'Feb',
|
||||
'Mar',
|
||||
'Apr',
|
||||
'May',
|
||||
'Jun',
|
||||
'Jul',
|
||||
'Aug',
|
||||
'Sep',
|
||||
'Oct',
|
||||
'Nov',
|
||||
'Dec',
|
||||
];
|
||||
final month = monthNames[local.month - 1];
|
||||
final day = local.day.toString().padLeft(2, '0');
|
||||
final year = local.year.toString();
|
||||
final hour24 = local.hour;
|
||||
final hour12 = hour24 % 12 == 0 ? 12 : hour24 % 12;
|
||||
final minute = local.minute.toString().padLeft(2, '0');
|
||||
final ampm = hour24 >= 12 ? 'PM' : 'AM';
|
||||
return '$month $day, $year $hour12:$minute $ampm';
|
||||
}
|
||||
|
||||
Future<void> _showTimelineDialog(BuildContext context, Ticket ticket) async {
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
return AlertDialog(
|
||||
title: const Text('Ticket Timeline'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_timelineRow('Created', ticket.createdAt),
|
||||
_timelineRow('Responded', ticket.respondedAt),
|
||||
_timelineRow('Promoted', ticket.promotedAt),
|
||||
_timelineRow('Closed', ticket.closedAt),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
child: const Text('Close'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _timelineRow(String label, DateTime? value) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text('$label: ${value == null ? '—' : _formatDate(value)}'),
|
||||
);
|
||||
}
|
||||
|
||||
String _formatDuration(Duration duration) {
|
||||
if (duration.inSeconds < 60) {
|
||||
return 'Less than a minute';
|
||||
}
|
||||
final hours = duration.inHours;
|
||||
final minutes = duration.inMinutes.remainder(60);
|
||||
if (hours > 0) {
|
||||
return '${hours}h ${minutes}m';
|
||||
}
|
||||
return '${minutes}m';
|
||||
}
|
||||
|
||||
Widget _buildStatusChip(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
Ticket ticket,
|
||||
bool canPromote,
|
||||
) {
|
||||
final isLocked = ticket.status == 'promoted' || ticket.status == 'closed';
|
||||
final chip = Chip(
|
||||
label: Text(_statusLabel(ticket.status)),
|
||||
backgroundColor: _statusColor(context, ticket.status),
|
||||
labelStyle: TextStyle(
|
||||
color: _statusTextColor(context, ticket.status),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
);
|
||||
|
||||
if (isLocked) {
|
||||
return chip;
|
||||
}
|
||||
|
||||
final availableStatuses = canPromote
|
||||
? _statusOptions
|
||||
: _statusOptions.where((status) => status != 'promoted').toList();
|
||||
|
||||
return PopupMenuButton<String>(
|
||||
onSelected: (value) async {
|
||||
await ref
|
||||
.read(ticketsControllerProvider)
|
||||
.updateTicketStatus(ticketId: ticket.id, status: value);
|
||||
ref.invalidate(ticketsProvider);
|
||||
},
|
||||
itemBuilder: (context) => availableStatuses
|
||||
.map(
|
||||
(status) => PopupMenuItem(
|
||||
value: status,
|
||||
child: Text(_statusMenuLabel(status)),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
child: chip,
|
||||
);
|
||||
}
|
||||
|
||||
String _statusLabel(String status) {
|
||||
return status.toUpperCase();
|
||||
}
|
||||
|
||||
String _statusMenuLabel(String status) {
|
||||
return switch (status) {
|
||||
'pending' => 'Pending',
|
||||
'promoted' => 'Promote to Task',
|
||||
'closed' => 'Close',
|
||||
_ => status,
|
||||
};
|
||||
}
|
||||
|
||||
bool _canPromote(String role) {
|
||||
return role == 'admin' || role == 'dispatcher' || role == 'it_staff';
|
||||
}
|
||||
|
||||
bool _canAssignStaff(String role) {
|
||||
return role == 'admin' || role == 'dispatcher' || role == 'it_staff';
|
||||
}
|
||||
|
||||
Color _statusColor(BuildContext context, String status) {
|
||||
return switch (status) {
|
||||
'pending' => Colors.amber.shade300,
|
||||
'promoted' => Colors.blue.shade300,
|
||||
'closed' => Colors.green.shade300,
|
||||
_ => Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
};
|
||||
}
|
||||
|
||||
Color _statusTextColor(BuildContext context, String status) {
|
||||
return switch (status) {
|
||||
'pending' => Colors.brown.shade900,
|
||||
'promoted' => Colors.blue.shade900,
|
||||
'closed' => Colors.green.shade900,
|
||||
_ => Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
extension _FirstOrNull<T> on Iterable<T> {
|
||||
T? get firstOrNull => isEmpty ? null : first;
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../models/office.dart';
|
||||
import '../../models/notification_item.dart';
|
||||
import '../../providers/notifications_provider.dart';
|
||||
import '../../providers/tickets_provider.dart';
|
||||
import '../../providers/typing_provider.dart';
|
||||
import '../../widgets/responsive_body.dart';
|
||||
import '../../widgets/typing_dots.dart';
|
||||
|
||||
class TicketsListScreen extends ConsumerWidget {
|
||||
const TicketsListScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final ticketsAsync = ref.watch(ticketsProvider);
|
||||
final officesAsync = ref.watch(officesProvider);
|
||||
final notificationsAsync = ref.watch(notificationsProvider);
|
||||
|
||||
return Scaffold(
|
||||
body: ResponsiveBody(
|
||||
child: ticketsAsync.when(
|
||||
data: (tickets) {
|
||||
if (tickets.isEmpty) {
|
||||
return const Center(child: Text('No tickets yet.'));
|
||||
}
|
||||
final officeById = {
|
||||
for (final office in officesAsync.valueOrNull ?? [])
|
||||
office.id: office,
|
||||
};
|
||||
final unreadByTicketId = _unreadByTicketId(notificationsAsync);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16, bottom: 8),
|
||||
child: Align(
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
'Tickets',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView.separated(
|
||||
padding: const EdgeInsets.only(bottom: 24),
|
||||
itemCount: tickets.length,
|
||||
separatorBuilder: (context, index) =>
|
||||
const SizedBox(height: 12),
|
||||
itemBuilder: (context, index) {
|
||||
final ticket = tickets[index];
|
||||
final officeName =
|
||||
officeById[ticket.officeId]?.name ?? ticket.officeId;
|
||||
final hasMention = unreadByTicketId[ticket.id] == true;
|
||||
final typingState = ref.watch(
|
||||
typingIndicatorProvider(ticket.id),
|
||||
);
|
||||
final showTyping = typingState.userIds.isNotEmpty;
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.confirmation_number_outlined),
|
||||
title: Text(ticket.subject),
|
||||
subtitle: Text(officeName),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_buildStatusChip(context, ticket.status),
|
||||
if (showTyping) ...[
|
||||
const SizedBox(width: 6),
|
||||
TypingDots(
|
||||
size: 6,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
],
|
||||
if (hasMention)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(left: 8),
|
||||
child: Icon(
|
||||
Icons.circle,
|
||||
size: 10,
|
||||
color: Colors.red,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
onTap: () => context.go('/tickets/${ticket.id}'),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, _) =>
|
||||
Center(child: Text('Failed to load tickets: $error')),
|
||||
),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton.extended(
|
||||
onPressed: () => _showCreateTicketDialog(context, ref),
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('New Ticket'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showCreateTicketDialog(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
) async {
|
||||
final subjectController = TextEditingController();
|
||||
final descriptionController = TextEditingController();
|
||||
Office? selectedOffice;
|
||||
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
return StatefulBuilder(
|
||||
builder: (context, setState) {
|
||||
return AlertDialog(
|
||||
title: const Text('Create Ticket'),
|
||||
content: Consumer(
|
||||
builder: (context, ref, child) {
|
||||
final officesAsync = ref.watch(officesProvider);
|
||||
return SizedBox(
|
||||
width: 360,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextField(
|
||||
controller: subjectController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Subject',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: descriptionController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Description',
|
||||
),
|
||||
maxLines: 3,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
officesAsync.when(
|
||||
data: (offices) {
|
||||
if (offices.isEmpty) {
|
||||
return const Text('No offices assigned.');
|
||||
}
|
||||
selectedOffice ??= offices.first;
|
||||
return DropdownButtonFormField<Office>(
|
||||
key: ValueKey(selectedOffice?.id),
|
||||
initialValue: selectedOffice,
|
||||
items: offices
|
||||
.map(
|
||||
(office) => DropdownMenuItem(
|
||||
value: office,
|
||||
child: Text(office.name),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
onChanged: (value) =>
|
||||
setState(() => selectedOffice = value),
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Office',
|
||||
),
|
||||
);
|
||||
},
|
||||
loading: () => const LinearProgressIndicator(),
|
||||
error: (error, _) =>
|
||||
Text('Failed to load offices: $error'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final subject = subjectController.text.trim();
|
||||
final description = descriptionController.text.trim();
|
||||
if (subject.isEmpty ||
|
||||
description.isEmpty ||
|
||||
selectedOffice == null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Fill out all fields.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
await ref
|
||||
.read(ticketsControllerProvider)
|
||||
.createTicket(
|
||||
subject: subject,
|
||||
description: description,
|
||||
officeId: selectedOffice!.id,
|
||||
);
|
||||
ref.invalidate(ticketsProvider);
|
||||
if (context.mounted) {
|
||||
Navigator.of(dialogContext).pop();
|
||||
}
|
||||
},
|
||||
child: const Text('Create'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, bool> _unreadByTicketId(
|
||||
AsyncValue<List<NotificationItem>> notificationsAsync,
|
||||
) {
|
||||
return notificationsAsync.maybeWhen(
|
||||
data: (items) {
|
||||
final map = <String, bool>{};
|
||||
for (final item in items) {
|
||||
if (item.ticketId == null) continue;
|
||||
if (item.isUnread) {
|
||||
map[item.ticketId!] = true;
|
||||
}
|
||||
}
|
||||
return map;
|
||||
},
|
||||
orElse: () => <String, bool>{},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatusChip(BuildContext context, String status) {
|
||||
return Chip(
|
||||
label: Text(status.toUpperCase()),
|
||||
backgroundColor: _statusColor(context, status),
|
||||
labelStyle: TextStyle(
|
||||
color: _statusTextColor(context, status),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Color _statusColor(BuildContext context, String status) {
|
||||
return switch (status) {
|
||||
'pending' => Colors.amber.shade300,
|
||||
'promoted' => Colors.blue.shade300,
|
||||
'closed' => Colors.green.shade300,
|
||||
_ => Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
};
|
||||
}
|
||||
|
||||
Color _statusTextColor(BuildContext context, String status) {
|
||||
return switch (status) {
|
||||
'pending' => Colors.brown.shade900,
|
||||
'promoted' => Colors.blue.shade900,
|
||||
'closed' => Colors.green.shade900,
|
||||
_ => Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user