Files
tasq/lib/screens/tickets/tickets_list_screen.dart
T
2026-04-30 06:45:51 +08:00

824 lines
30 KiB
Dart

import 'package:flutter/material.dart';
import '../../theme/m3_motion.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tasq/utils/app_time.dart';
import 'package:go_router/go_router.dart';
import '../../models/office.dart';
import '../../models/notification_item.dart';
import '../../models/profile.dart';
import '../../models/ticket.dart';
import '../../providers/notifications_provider.dart';
import '../../providers/profile_provider.dart';
import '../../providers/tickets_provider.dart';
import '../../providers/realtime_controller.dart';
import '../../providers/typing_provider.dart';
import '../../widgets/mono_text.dart';
import '../../widgets/reconnect_overlay.dart';
import 'package:skeletonizer/skeletonizer.dart';
import '../../widgets/responsive_body.dart';
import '../../widgets/tasq_adaptive_list.dart';
import '../../widgets/typing_dots.dart';
import '../../theme/app_surfaces.dart';
import '../../utils/snackbar.dart';
import '../../widgets/app_breakpoints.dart';
import '../../widgets/app_page_header.dart';
import '../../widgets/app_state_view.dart';
import '../../widgets/sync_pending_badge.dart';
class TicketsListScreen extends ConsumerStatefulWidget {
const TicketsListScreen({super.key});
@override
ConsumerState<TicketsListScreen> createState() => _TicketsListScreenState();
}
class _TicketsListScreenState extends ConsumerState<TicketsListScreen> {
final TextEditingController _subjectController = TextEditingController();
String? _selectedOfficeId;
String? _selectedStatus;
DateTimeRange? _selectedDateRange;
bool _isInitial = true;
// (previous deferred listen removed; providers are watched directly)
@override
void dispose() {
_subjectController.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
}
bool get _hasTicketFilters {
return _subjectController.text.trim().isNotEmpty ||
_selectedOfficeId != null ||
_selectedStatus != null ||
_selectedDateRange != null;
}
@override
Widget build(BuildContext context) {
final realtime = ref.watch(realtimeControllerProvider);
final ticketsAsync = ref.watch(ticketsProvider);
final offlinePending = ref.watch(offlinePendingTicketsProvider);
// When the live stream delivers a ticket whose UUID matches a pending offline
// ticket, remove it — sync completed successfully.
ref.listen<AsyncValue<List<Ticket>>>(ticketsProvider, (_, next) {
final live = next.valueOrNull;
if (live == null || live.isEmpty) return;
final pending = ref.read(offlinePendingTicketsProvider);
if (pending.isEmpty) return;
final liveIds = live.map((t) => t.id).toSet();
final stillPending = pending.where((t) => !liveIds.contains(t.id)).toList();
if (stillPending.length != pending.length) {
ref.read(offlinePendingTicketsProvider.notifier).state = stillPending;
}
});
final officesAsync = ref.watch(officesProvider);
final notificationsAsync = ref.watch(notificationsProvider);
final profilesAsync = ref.watch(profilesProvider);
final showSkeleton =
realtime.isChannelRecovering('tickets') ||
realtime.isChannelRecovering('offices') ||
(!ticketsAsync.hasValue && ticketsAsync.isLoading) ||
(!officesAsync.hasValue && officesAsync.isLoading) ||
(!profilesAsync.hasValue && profilesAsync.isLoading) ||
(!notificationsAsync.hasValue && notificationsAsync.isLoading);
if (_isInitial) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
setState(() => _isInitial = false);
});
}
final effectiveShowSkeleton = showSkeleton || _isInitial;
return Stack(
children: [
ResponsiveBody(
maxWidth: double.infinity,
child: Skeletonizer(
enabled: effectiveShowSkeleton,
child: Builder(
builder: (context) {
// Build the list UI immediately so `Skeletonizer` can
// render placeholders while providers are still loading.
if (ticketsAsync.hasError && !ticketsAsync.hasValue) {
return AppErrorView(
error: ticketsAsync.error!,
title: 'Could not load tickets',
onRetry: () => ref.invalidate(ticketsProvider),
);
}
final liveTickets = ticketsAsync.valueOrNull ?? <Ticket>[];
final liveIds = liveTickets.map((t) => t.id).toSet();
final pendingOnly =
offlinePending.where((t) => !liveIds.contains(t.id)).toList();
final tickets = [...pendingOnly, ...liveTickets];
final pendingTicketIds =
offlinePending.map((t) => t.id).toSet();
final officeById = <String, Office>{
for (final office in officesAsync.valueOrNull ?? <Office>[])
office.id: office,
};
final profileById = <String, Profile>{
for (final profile
in profilesAsync.valueOrNull ?? <Profile>[])
profile.id: profile,
};
final unreadByTicketId = _unreadByTicketId(notificationsAsync);
final offices = officesAsync.valueOrNull ?? <Office>[];
final officesSorted = List<Office>.from(offices)
..sort(
(a, b) =>
a.name.toLowerCase().compareTo(b.name.toLowerCase()),
);
final officeOptions = <DropdownMenuItem<String?>>[
const DropdownMenuItem<String?>(
value: null,
child: Text('All offices'),
),
...officesSorted.map(
(office) => DropdownMenuItem<String?>(
value: office.id,
child: Text(office.name),
),
),
];
final statusOptions = _ticketStatusOptions(tickets);
final filteredTickets = _applyTicketFilters(
tickets,
subjectQuery: _subjectController.text,
officeId: _selectedOfficeId,
status: _selectedStatus,
dateRange: _selectedDateRange,
);
final summaryDashboard = _StatusSummaryRow(
counts: _statusCounts(filteredTickets),
);
final filterHeader = Wrap(
spacing: 12,
runSpacing: 12,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
SizedBox(
width: 220,
child: TextField(
controller: _subjectController,
onChanged: (_) => setState(() {}),
decoration: const InputDecoration(
labelText: 'Subject',
prefixIcon: Icon(Icons.search),
),
),
),
SizedBox(
width: 200,
child: DropdownButtonFormField<String?>(
isExpanded: true,
key: ValueKey(_selectedOfficeId),
initialValue: _selectedOfficeId,
items: officeOptions,
onChanged: (value) =>
setState(() => _selectedOfficeId = value),
decoration: const InputDecoration(labelText: 'Office'),
),
),
SizedBox(
width: 180,
child: DropdownButtonFormField<String?>(
isExpanded: true,
key: ValueKey(_selectedStatus),
initialValue: _selectedStatus,
items: statusOptions,
onChanged: (value) =>
setState(() => _selectedStatus = value),
decoration: const InputDecoration(labelText: 'Status'),
),
),
OutlinedButton.icon(
onPressed: () async {
final next = await showDateRangePicker(
context: context,
firstDate: DateTime(2020),
lastDate: AppTime.now().add(
const Duration(days: 365),
),
currentDate: AppTime.now(),
initialDateRange: _selectedDateRange,
);
if (!mounted) return;
setState(() => _selectedDateRange = next);
},
icon: const Icon(Icons.date_range),
label: Text(
_selectedDateRange == null
? 'Date range'
: AppTime.formatDateRange(_selectedDateRange!),
),
),
if (_hasTicketFilters)
TextButton.icon(
onPressed: () => setState(() {
_subjectController.clear();
_selectedOfficeId = null;
_selectedStatus = null;
_selectedDateRange = null;
}),
icon: const Icon(Icons.close),
label: const Text('Clear'),
),
],
);
if (filteredTickets.isEmpty && !effectiveShowSkeleton) {
final hasFilters = _hasTicketFilters;
return Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const AppPageHeader(
title: 'Tickets',
subtitle: 'Support requests and service tickets',
),
Expanded(
child: AppEmptyView(
icon: Icons.confirmation_number_outlined,
title: hasFilters
? 'No matching tickets'
: 'No tickets yet',
subtitle: hasFilters
? 'Try adjusting your filters.'
: 'Tickets submitted by your team will appear here.',
),
),
],
);
}
final listBody = TasQAdaptiveList<Ticket>(
items: filteredTickets,
onRowTap: (ticket) => context.go('/tickets/${ticket.id}'),
summaryDashboard: summaryDashboard,
filterHeader: filterHeader,
skeletonMode: effectiveShowSkeleton,
onRequestRefresh: () {
ref.read(ticketsQueryProvider.notifier).state =
const TicketQuery(offset: 0, limit: 50);
},
onPageChanged: (firstRow) {
ref
.read(ticketsQueryProvider.notifier)
.update((q) => q.copyWith(offset: firstRow));
},
isLoading: ticketsAsync.maybeWhen(
loading: () => true,
orElse: () => false,
),
columns: [
TasQColumn<Ticket>(
header: 'Ticket ID',
technical: true,
cellBuilder: (context, ticket) => Text(ticket.id),
),
TasQColumn<Ticket>(
header: 'Subject',
cellBuilder: (context, ticket) {
final isPending =
pendingTicketIds.contains(ticket.id);
if (!isPending) return Text(ticket.subject);
return Row(
children: [
Flexible(child: Text(ticket.subject)),
const SizedBox(width: 6),
SyncPendingBadge(isPending: true, compact: true),
],
);
},
),
TasQColumn<Ticket>(
header: 'Office',
cellBuilder: (context, ticket) => Text(
officeById[ticket.officeId]?.name ?? ticket.officeId,
),
),
TasQColumn<Ticket>(
header: 'Filed by',
cellBuilder: (context, ticket) =>
Text(_assignedAgent(profileById, ticket.creatorId)),
),
TasQColumn<Ticket>(
header: 'Status',
cellBuilder: (context, ticket) =>
_StatusBadge(status: ticket.status),
),
TasQColumn<Ticket>(
header: 'Timestamp',
technical: true,
cellBuilder: (context, ticket) =>
Text(_formatTimestamp(ticket.createdAt)),
),
],
mobileTileBuilder: (context, ticket, actions) {
final officeName =
officeById[ticket.officeId]?.name ?? ticket.officeId;
final assigned = _assignedAgent(
profileById,
ticket.creatorId,
);
final hasMention = unreadByTicketId[ticket.id] == true;
final isTicketPending =
pendingTicketIds.contains(ticket.id);
final typingState = ref.watch(
typingIndicatorProvider(ticket.id),
);
final showTyping = typingState.userIds.isNotEmpty;
return M3PressScale(
onTap: () => context.go('/tickets/${ticket.id}'),
child: Card(
child: ListTile(
leading:
const Icon(Icons.confirmation_number_outlined),
dense: true,
visualDensity: VisualDensity.compact,
title: Text(
ticket.subject,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(officeName),
const SizedBox(height: 2),
Text('Filed by: $assigned'),
const SizedBox(height: 4),
MonoText('ID ${ticket.id}'),
const SizedBox(height: 2),
Text(_formatTimestamp(ticket.createdAt)),
],
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (isTicketPending) ...[
SyncPendingBadge(
isPending: true,
compact: true,
),
const SizedBox(width: 4),
],
_StatusBadge(status: ticket.status),
if (showTyping) ...[
const SizedBox(width: 6),
TypingDots(
size: 6,
color:
Theme.of(context).colorScheme.primary,
),
],
if (hasMention)
Padding(
padding: const EdgeInsets.only(left: 8),
child: Icon(
Icons.circle,
size: 10,
color:
Theme.of(context).colorScheme.error,
),
),
],
),
),
),
);
},
);
return Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const AppPageHeader(
title: 'Tickets',
subtitle: 'Support requests and service tickets',
),
Expanded(child: listBody),
],
);
},
),
),
),
Positioned(
right: 16,
bottom: 16,
child: SafeArea(
child: M3ExpandedFab(
onPressed: () => _showCreateTicketDialog(context, ref),
icon: const Icon(Icons.add),
label: const Text('New Ticket'),
),
),
),
const ReconnectIndicator(),
],
);
}
Future<void> _showCreateTicketDialog(
BuildContext context,
WidgetRef ref,
) async {
final subjectController = TextEditingController();
final descriptionController = TextEditingController();
Office? selectedOffice;
final isMobile = MediaQuery.sizeOf(context).width < AppBreakpoints.tablet;
var saving = false;
Widget buildFormContent(StateSetter setState) {
return Consumer(
builder: (context, ref, _) {
final officesAsync = ref.watch(officesProvider);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: subjectController,
decoration: const InputDecoration(labelText: 'Subject'),
enabled: !saving,
),
const SizedBox(height: 12),
TextField(
controller: descriptionController,
decoration: const InputDecoration(labelText: 'Description'),
maxLines: 3,
enabled: !saving,
),
const SizedBox(height: 12),
officesAsync.when(
data: (offices) {
if (offices.isEmpty) return const Text('No offices assigned.');
final officesSorted = List<Office>.from(offices)
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
selectedOffice ??= officesSorted.first;
return DropdownButtonFormField<Office>(
key: ValueKey(selectedOffice?.id),
initialValue: selectedOffice,
items: officesSorted
.map((o) => DropdownMenuItem(value: o, child: Text(o.name)))
.toList(),
onChanged: saving ? null : (v) => setState(() => selectedOffice = v),
decoration: const InputDecoration(labelText: 'Office'),
);
},
loading: () => const LinearProgressIndicator(),
error: (e, _) => Text('Failed to load offices: $e'),
),
],
);
},
);
}
List<Widget> buildActions(BuildContext closeCtx, StateSetter setState) {
return [
TextButton(
onPressed: saving ? null : () => Navigator.of(closeCtx).pop(),
child: const Text('Cancel'),
),
FilledButton(
onPressed: saving
? null
: () async {
final subject = subjectController.text.trim();
final description = descriptionController.text.trim();
if (subject.isEmpty || description.isEmpty || selectedOffice == null) {
showWarningSnackBar(closeCtx, 'Fill out all fields.');
return;
}
setState(() => saving = true);
try {
final pendingTicket = await ref
.read(ticketsControllerProvider)
.createTicket(
subject: subject,
description: description,
officeId: selectedOffice!.id,
);
if (pendingTicket != null) {
final current = ref.read(offlinePendingTicketsProvider);
ref.read(offlinePendingTicketsProvider.notifier).state = [
pendingTicket,
...current,
];
}
if (closeCtx.mounted) {
Navigator.of(closeCtx).pop();
showSuccessSnackBar(
closeCtx,
pendingTicket != null
? 'Ticket "$subject" saved offline — will sync when connected.'
: 'Ticket "$subject" has been created successfully.',
);
}
} catch (e) {
if (!closeCtx.mounted) return;
showErrorSnackBarGlobal('Failed to create ticket: $e');
} finally {
if (closeCtx.mounted) setState(() => saving = false);
}
},
child: saving
? const SizedBox(
height: 18,
width: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Create'),
),
];
}
if (isMobile) {
await m3ShowBottomSheet<void>(
context: context,
isScrollControlled: true,
useSafeArea: true,
builder: (ctx) => StatefulBuilder(
builder: (context, setState) => Padding(
padding: EdgeInsets.only(
left: 24,
right: 24,
top: 8,
bottom: MediaQuery.of(context).viewInsets.bottom + 24,
),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Create Ticket', style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 16),
buildFormContent(setState),
const SizedBox(height: 16),
OverflowBar(
alignment: MainAxisAlignment.end,
children: buildActions(ctx, setState),
),
const SizedBox(height: 8),
],
),
),
),
),
);
} else {
await m3ShowDialog<void>(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (context, setState) => AlertDialog(
shape: AppSurfaces.of(context).dialogShape,
title: const Text('Create Ticket'),
content: SizedBox(
width: 600,
child: buildFormContent(setState),
),
actions: buildActions(dialogContext, setState),
),
),
);
}
}
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>{},
);
}
}
List<DropdownMenuItem<String?>> _ticketStatusOptions(List<Ticket> tickets) {
final statuses = tickets.map((ticket) => ticket.status).toSet().toList()
..sort();
return [
const DropdownMenuItem<String?>(value: null, child: Text('All statuses')),
...statuses.map(
(status) => DropdownMenuItem<String?>(value: status, child: Text(status)),
),
];
}
List<Ticket> _applyTicketFilters(
List<Ticket> tickets, {
required String subjectQuery,
required String? officeId,
required String? status,
required DateTimeRange? dateRange,
}) {
final query = subjectQuery.trim().toLowerCase();
return tickets.where((ticket) {
if (query.isNotEmpty &&
!ticket.subject.toLowerCase().contains(query) &&
!ticket.id.toLowerCase().contains(query)) {
return false;
}
if (officeId != null && ticket.officeId != officeId) {
return false;
}
if (status != null && ticket.status != status) {
return false;
}
if (dateRange != null) {
final start = DateTime(
dateRange.start.year,
dateRange.start.month,
dateRange.start.day,
);
final end = DateTime(
dateRange.end.year,
dateRange.end.month,
dateRange.end.day,
23,
59,
59,
);
if (ticket.createdAt.isBefore(start) || ticket.createdAt.isAfter(end)) {
return false;
}
}
return true;
}).toList();
}
Map<String, int> _statusCounts(List<Ticket> tickets) {
final counts = <String, int>{};
for (final ticket in tickets) {
counts.update(ticket.status, (value) => value + 1, ifAbsent: () => 1);
}
return counts;
}
class _StatusSummaryRow extends StatelessWidget {
const _StatusSummaryRow({required this.counts});
final Map<String, int> counts;
@override
Widget build(BuildContext context) {
if (counts.isEmpty) return const SizedBox.shrink();
final entries = counts.entries.toList()
..sort((a, b) => a.key.compareTo(b.key));
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (int i = 0; i < entries.length; i++) ...[
if (i > 0) const SizedBox(width: 8),
_StatusSummaryCard(
status: entries[i].key,
count: entries[i].value,
),
],
],
),
);
}
}
class _StatusSummaryCard extends StatelessWidget {
const _StatusSummaryCard({required this.status, required this.count});
final String status;
final int count;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final background = switch (status) {
'critical' => scheme.errorContainer,
'pending' => scheme.tertiaryContainer,
'promoted' => scheme.secondaryContainer,
'closed' => scheme.primaryContainer,
_ => scheme.surfaceContainerHigh,
};
final foreground = switch (status) {
'critical' => scheme.onErrorContainer,
'pending' => scheme.onTertiaryContainer,
'promoted' => scheme.onSecondaryContainer,
'closed' => scheme.onPrimaryContainer,
_ => scheme.onSurfaceVariant,
};
final label = status.replaceAll('_', ' ').toUpperCase();
return Material(
color: background,
borderRadius: BorderRadius.circular(20),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
label,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: foreground,
fontWeight: FontWeight.w600,
letterSpacing: 0.4,
),
),
const SizedBox(width: 6),
Text(
count.toString(),
style: Theme.of(context).textTheme.labelLarge?.copyWith(
color: foreground,
fontWeight: FontWeight.w700,
),
),
],
),
),
);
}
}
String _assignedAgent(Map<String, Profile> profileById, String? userId) {
if (userId == null || userId.isEmpty) {
return 'Unassigned';
}
final profile = profileById[userId];
if (profile == null) {
return userId;
}
return profile.fullName.isNotEmpty ? profile.fullName : profile.id;
}
String _formatTimestamp(DateTime value) {
final year = value.year.toString().padLeft(4, '0');
final month = value.month.toString().padLeft(2, '0');
final day = value.day.toString().padLeft(2, '0');
final hour = value.hour.toString().padLeft(2, '0');
final minute = value.minute.toString().padLeft(2, '0');
return '$year-$month-$day $hour:$minute';
}
class _StatusBadge extends StatelessWidget {
const _StatusBadge({required this.status});
final String status;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final background = switch (status) {
'critical' => scheme.errorContainer,
'pending' => scheme.tertiaryContainer,
'promoted' => scheme.secondaryContainer,
'closed' => scheme.primaryContainer,
_ => scheme.surfaceContainerHighest,
};
final foreground = switch (status) {
'critical' => scheme.onErrorContainer,
'pending' => scheme.onTertiaryContainer,
'promoted' => scheme.onSecondaryContainer,
'closed' => scheme.onPrimaryContainer,
_ => scheme.onSurfaceVariant,
};
return Badge(
backgroundColor: background,
label: Text(
status.toUpperCase(),
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: foreground,
fontWeight: FontWeight.w600,
letterSpacing: 0.3,
),
),
);
}
}