From 5fcc16fb9c44d22de096e56adc039de6687aadab Mon Sep 17 00:00:00 2001 From: Mark M2 Macbook Date: Sun, 29 Nov 2026 13:56:44 +0100 Subject: [PATCH] refactor: improve responsive layout across dashboard cards and add unit tests --- .../ui/dashboard_daily_ricontatti_card.dart | 298 ++++-- .../ui/dashboard_expiring_contracts_card.dart | 68 +- .../ui/dashboard_note_list_card.dart | 104 +- .../ui/latest_store_operations_card.dart | 76 +- .../ui/dashboard_store_ticket_list_card.dart | 69 +- .../ui/dashboard_target_hero_card.dart | 998 +++++++++++------- lib/features/home/ui/home_screen.dart | 270 +++-- .../home/ui/quick_actions_widget.dart | 17 +- lib/features/notes/ui/notes_form_screen.dart | 125 ++- .../blocs/operation_form_cubit.dart | 15 +- .../data/operations_repository.dart | 22 +- .../operations/models/operation_model.dart | 11 +- .../operations/ui/operation_form_screen.dart | 72 +- pubspec.yaml | 2 +- .../notes/ui/note_form_screen_test.dart | 110 ++ .../models/operation_model_test.dart | 61 ++ 16 files changed, 1542 insertions(+), 776 deletions(-) create mode 100644 test/features/notes/ui/note_form_screen_test.dart create mode 100644 test/features/operations/models/operation_model_test.dart diff --git a/lib/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart b/lib/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart index 1848928..1da0af6 100644 --- a/lib/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart +++ b/lib/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart @@ -28,59 +28,210 @@ class DashboardDailyRicontattiCard extends StatelessWidget { builder: (context, state) { final theme = Theme.of(context); - return Padding( - padding: const EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0), - child: Container( - decoration: BoxDecoration( - color: theme.colorScheme.surface, - borderRadius: BorderRadius.circular(20), - border: Border.all( - color: Colors.amber.shade600.withValues(alpha: 0.35), - width: 1.5, - ), - boxShadow: [ - BoxShadow( - color: Colors.amber.shade700.withValues(alpha: 0.06), - blurRadius: 18, - offset: const Offset(0, 6), - ), - ], - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _buildHeader(context, theme, state), - Divider( - height: 1, - color: theme.dividerColor.withValues(alpha: 0.15), - ), - if (state.status == DashboardDailyRicontattiStatus.loading && - state.summaries.isEmpty) - _buildLoading(theme) - else if (state.status == DashboardDailyRicontattiStatus.failure) - _buildError(context, theme, state) - else if (state.summaries.isEmpty) - _buildEmpty(theme) - else ...[ - _buildOverviewStats(context, theme, state), - Padding( - padding: const EdgeInsets.fromLTRB(18, 0, 18, 18), - child: _buildStaffGrid(context, theme, state.summaries), + return LayoutBuilder( + builder: (context, outerConstraints) { + final isMobile = outerConstraints.maxWidth < 600; + final hPad = isMobile ? 16.0 : 24.0; + final vGap = isMobile ? 16.0 : 24.0; + + return Padding( + padding: EdgeInsets.fromLTRB(hPad, 0, hPad, vGap), + child: Container( + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: Colors.amber.shade600.withValues(alpha: 0.35), + width: 1.5, + ), + boxShadow: [ + BoxShadow( + color: Colors.amber.shade700.withValues(alpha: 0.06), + blurRadius: 18, + offset: const Offset(0, 6), + ), + ], ), - ], - ], - ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildHeader(context, theme, state, isCompact: isMobile), + Divider( + height: 1, + color: theme.dividerColor.withValues(alpha: 0.15), + ), + if (state.status == DashboardDailyRicontattiStatus.loading && + state.summaries.isEmpty) + _buildLoading(theme) + else if (state.status == + DashboardDailyRicontattiStatus.failure) + _buildError(context, theme, state) + else if (state.summaries.isEmpty) + _buildEmpty(theme) + else ...[ + _buildOverviewStats( + context, + theme, + state, + isCompact: isMobile, + ), + Padding( + padding: EdgeInsets.fromLTRB( + isMobile ? 14 : 18, + 0, + isMobile ? 14 : 18, + isMobile ? 14 : 18, + ), + child: _buildStaffGrid(context, theme, state.summaries), + ), + ], + ], + ), + ), + ); + }, + ); + }, + ); + } + + Widget _buildTotalPillBadge(DashboardDailyRicontattiState state) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7), + decoration: BoxDecoration( + color: Colors.amber.shade500.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Colors.amber.shade600.withValues(alpha: 0.4), ), - ); - }, - ); + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${state.totalRicontattiToday}', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w900, + color: Colors.amber.shade900, + ), + ), + const SizedBox(width: 5), + Text( + 'oggi', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + color: Colors.amber.shade800, + ), + ), + const SizedBox(width: 6), + Text( + '(mese: ${state.totalRicontattiMonth})', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w800, + color: Colors.amber.shade900.withValues(alpha: 0.85), + ), + ), + ], + ), + ); } Widget _buildHeader( BuildContext context, ThemeData theme, - DashboardDailyRicontattiState state, - ) { + DashboardDailyRicontattiState state, { + bool isCompact = false, + }) { + if (isCompact) { + return Padding( + padding: const EdgeInsets.all(14.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + padding: const EdgeInsets.all(9), + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [ + Colors.amber.shade600, + Colors.orange.shade700, + ], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon( + Icons.event_repeat_rounded, + color: Colors.white, + size: 20, + ), + ), + const SizedBox(width: 10), + Expanded( + child: Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 6, + runSpacing: 4, + children: [ + Text( + 'FOCUS RICONTATTI DI OGGI', + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.w900, + letterSpacing: 0.3, + ), + ), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 2, + ), + decoration: BoxDecoration( + color: Colors.amber.shade100, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + 'MANAGER', + style: TextStyle( + fontSize: 9.5, + fontWeight: FontWeight.w800, + color: Colors.amber.shade900, + letterSpacing: 0.4, + ), + ), + ), + ], + ), + ), + IconButton( + tooltip: 'Aggiorna ora', + visualDensity: VisualDensity.compact, + icon: const Icon(Icons.refresh_rounded, size: 20), + onPressed: () => + context.read().refresh(), + ), + ], + ), + const SizedBox(height: 6), + Text( + 'Raccolta situazioni da ricontattare & bollette', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 10), + _buildTotalPillBadge(state), + ], + ), + ); + } + return Padding( padding: const EdgeInsets.all(18.0), child: Row( @@ -163,48 +314,7 @@ class DashboardDailyRicontattiCard extends StatelessWidget { ), ), const SizedBox(width: 12), - // Total today & month pill badge - Container( - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), - decoration: BoxDecoration( - color: Colors.amber.shade500.withValues(alpha: 0.15), - borderRadius: BorderRadius.circular(12), - border: Border.all( - color: Colors.amber.shade600.withValues(alpha: 0.4), - ), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - '${state.totalRicontattiToday}', - style: TextStyle( - fontSize: 20, - fontWeight: FontWeight.w900, - color: Colors.amber.shade900, - ), - ), - const SizedBox(width: 5), - Text( - 'oggi', - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w700, - color: Colors.amber.shade800, - ), - ), - const SizedBox(width: 6), - Text( - '(mese: ${state.totalRicontattiMonth})', - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w800, - color: Colors.amber.shade900.withValues(alpha: 0.85), - ), - ), - ], - ), - ), + _buildTotalPillBadge(state), const SizedBox(width: 6), IconButton( tooltip: 'Aggiorna ora', @@ -220,17 +330,19 @@ class DashboardDailyRicontattiCard extends StatelessWidget { Widget _buildOverviewStats( BuildContext context, ThemeData theme, - DashboardDailyRicontattiState state, - ) { + DashboardDailyRicontattiState state, { + bool isCompact = false, + }) { final hasZeros = state.staffAtZero > 0; + final pad = isCompact ? 14.0 : 18.0; return Padding( - padding: const EdgeInsets.fromLTRB(18, 14, 18, 14), + padding: EdgeInsets.fromLTRB(pad, 12, pad, 12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Wrap( - spacing: 12, + spacing: isCompact ? 8 : 12, runSpacing: 8, children: [ _buildStatChip( @@ -367,7 +479,7 @@ class DashboardDailyRicontattiCard extends StatelessWidget { crossAxisCount: crossAxisCount, mainAxisSpacing: 10, crossAxisSpacing: 10, - mainAxisExtent: 104, + mainAxisExtent: crossAxisCount == 1 ? 86 : 104, ), itemBuilder: (context, index) { final summary = summaries[index]; diff --git a/lib/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.dart b/lib/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.dart index 007cd2f..5d1b96a 100644 --- a/lib/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.dart +++ b/lib/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.dart @@ -126,17 +126,14 @@ class _ExpiringContractsCardContent extends StatelessWidget { ), child: Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, children: [ - // Nome Cliente & note - Expanded( - flex: 5, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Row( + Row( + children: [ + Expanded( + child: Row( children: [ Flexible( child: Text( @@ -150,7 +147,9 @@ class _ExpiringContractsCardContent extends StatelessWidget { overflow: TextOverflow.ellipsis, ), ), - if (operation.attachments.isNotEmpty) ...[ + if (operation + .attachments + .isNotEmpty) ...[ const SizedBox(width: 4), Icon( Icons.attach_file, @@ -160,32 +159,29 @@ class _ExpiringContractsCardContent extends StatelessWidget { ], ], ), - if (phone != null && phone.isNotEmpty) - Text( - phone, - style: TextStyle( - color: context.secondaryText, - fontSize: 11, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, + ), + const SizedBox(width: 8), + _buildExpiryBadge(context, earliestExp), + ], + ), + const SizedBox(height: 4), + Row( + children: [ + if (phone != null && phone.isNotEmpty) ...[ + Text( + phone, + style: TextStyle( + color: context.secondaryText, + fontSize: 11, ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(width: 8), ], - ), + Expanded(child: _buildBadges(operation)), + ], ), - - const SizedBox(width: 8), - - // Badge Tipo / Subtipo - Expanded( - flex: 4, - child: _buildBadges(operation), - ), - - const SizedBox(width: 8), - - // Data Scadenza Badge - _buildExpiryBadge(context, earliestExp), ], ), ), @@ -236,8 +232,8 @@ class _ExpiringContractsCardContent extends StatelessWidget { ), child: Text( label, - style: const TextStyle( - color: Colors.amber, + style: TextStyle( + color: Colors.amber.shade800, fontSize: 11, fontWeight: FontWeight.bold, ), diff --git a/lib/features/home/dashboard_note_list/ui/dashboard_note_list_card.dart b/lib/features/home/dashboard_note_list/ui/dashboard_note_list_card.dart index 8bdcc1b..e5a0970 100644 --- a/lib/features/home/dashboard_note_list/ui/dashboard_note_list_card.dart +++ b/lib/features/home/dashboard_note_list/ui/dashboard_note_list_card.dart @@ -1,14 +1,36 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/core/routes/routes.dart'; import 'package:flux/core/theme/theme.dart'; import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart'; +import 'package:flux/features/notes/data/notes_repository.dart'; import 'package:flux/features/notes/models/note_model.dart'; -import 'package:go_router/go_router.dart'; // Supponendo tu usi GoRouter per la navigazione +import 'package:get_it/get_it.dart'; +import 'package:go_router/go_router.dart'; class DashboardNoteListCard extends StatelessWidget { const DashboardNoteListCard({super.key}); + Future _createNewNote(BuildContext context) async { + final sessionState = context.read().state; + final companyId = sessionState.company?.id; + final currentStaffId = sessionState.currentStaffMember?.id; + if (companyId == null || currentStaffId == null) return; + + final emptyNote = NoteModel.empty( + createdBy: currentStaffId, + companyId: companyId, + ); + final noteId = await GetIt.I.get().saveNote(emptyNote); + if (!context.mounted) return; + context.pushNamed( + Routes.noteForm, + pathParameters: {'id': noteId}, + extra: emptyNote.copyWith(id: noteId), + ); + } + @override Widget build(BuildContext context) { return Card( @@ -44,55 +66,59 @@ class DashboardNoteListCard extends StatelessWidget { ), ), const SizedBox(width: 12), - Text( - 'Le mie Note', - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 16, - color: context.primaryText, + Expanded( + child: Text( + 'Le mie Note', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + color: context.primaryText, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, ), - maxLines: 1, - overflow: TextOverflow.ellipsis, ), ], ), const SizedBox(height: 12), // Il corpo del widget collegato al Bloc - BlocBuilder( - builder: (context, state) { - if (state.status == DashboardNoteListStatus.loading && - state.notes.isEmpty) { - return const Center(child: CircularProgressIndicator()); - } + Expanded( + child: BlocBuilder< + DashboardNoteListCubit, + DashboardNoteListState + >( + builder: (context, state) { + if (state.status == DashboardNoteListStatus.loading && + state.notes.isEmpty) { + return const Center(child: CircularProgressIndicator()); + } - if (state.status == DashboardNoteListStatus.failure) { - return const Center( - child: Text( - 'Errore nel caricamento delle note.', - style: TextStyle(color: Colors.red), - ), - ); - } + if (state.status == DashboardNoteListStatus.failure) { + return const Center( + child: Text( + 'Errore nel caricamento delle note.', + style: TextStyle(color: Colors.red), + ), + ); + } - if (state.notes.isEmpty) { - return _buildEmptyState(context); - } + if (state.notes.isEmpty) { + return _buildEmptyState(context); + } - // Prendiamo solo le prime 4 note per non intaccare troppo spazio in Dashboard - final displayNotes = state.notes.take(4).toList(); + // Prendiamo solo le prime 4 note per non intaccare troppo spazio in Dashboard + final displayNotes = state.notes.take(4).toList(); - return SizedBox( - height: 140, // Altezza fissa per lo scroll orizzontale - child: ListView.builder( + return ListView.builder( scrollDirection: Axis.horizontal, itemCount: displayNotes.length, itemBuilder: (context, index) { return _buildMiniPostIt(context, displayNotes[index]); }, - ), - ); - }, + ); + }, + ), ), ], ), @@ -168,7 +194,7 @@ class DashboardNoteListCard extends StatelessWidget { Widget _buildEmptyState(BuildContext context) { return Container( width: double.infinity, - padding: const EdgeInsets.all(24), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), decoration: BoxDecoration( color: Colors.grey.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(12), @@ -178,16 +204,18 @@ class DashboardNoteListCard extends StatelessWidget { ), ), child: Column( + mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon( Icons.sticky_note_2_outlined, - size: 32, + size: 28, color: Colors.grey, ), - const SizedBox(height: 8), + const SizedBox(height: 6), const Text('Nessuna nota presente.'), TextButton( - onPressed: () => context.push('/notes/create'), + style: TextButton.styleFrom(visualDensity: VisualDensity.compact), + onPressed: () => _createNewNote(context), child: const Text('Creane una ora'), ), ], diff --git a/lib/features/home/dashboard_store_operation_list/ui/latest_store_operations_card.dart b/lib/features/home/dashboard_store_operation_list/ui/latest_store_operations_card.dart index 87ea275..2566cd2 100644 --- a/lib/features/home/dashboard_store_operation_list/ui/latest_store_operations_card.dart +++ b/lib/features/home/dashboard_store_operation_list/ui/latest_store_operations_card.dart @@ -113,6 +113,17 @@ class _LatestOperationsCardContent extends StatelessWidget { ), itemBuilder: (context, index) { final operation = state.operations[index]; + final types = operation.details + .map( + (d) => + d.type?.shortLabel ?? d.type?.value ?? '', + ) + .where((t) => t.trim().isNotEmpty) + .toList(); + final dateStr = operation.createdAt != null + ? "${operation.createdAt!.day.toString().padLeft(2, '0')}/${operation.createdAt!.month.toString().padLeft(2, '0')}" + : ''; + return InkWell( onTap: () => context.pushNamed( Routes.operationForm, @@ -123,45 +134,40 @@ class _LatestOperationsCardContent extends StatelessWidget { padding: const EdgeInsets.symmetric( vertical: 8.0, ), - child: Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, children: [ - Expanded( - flex: 5, - child: Text( - operation.customer?.name ?? - 'Cliente sconosciuto', - style: TextStyle( - fontWeight: FontWeight.w700, - color: context.primaryText, + Row( + children: [ + Expanded( + child: Text( + operation.customer?.name ?? + (operation.reference + .trim() + .isNotEmpty + ? operation.reference + : 'Cliente sconosciuto'), + style: TextStyle( + fontWeight: FontWeight.w700, + color: context.primaryText, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ), - ), - ), - Expanded( - flex: 5, - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 8.0, + const SizedBox(width: 8), + Text( + dateStr, + style: TextStyle( + color: context.secondaryText, + fontSize: 12, + ), ), - child: _buildBadgeList( - operation.details - .map((d) => d.type) - .whereType() - .where( - (t) => t.trim().isNotEmpty, - ) - .toList(), - ), - ), - ), - Text( - "${operation.createdAt?.day}/${operation.createdAt?.month}", - style: TextStyle( - color: context.secondaryText, - fontSize: 12, - ), + ], ), + const SizedBox(height: 4), + _buildBadgeList(types), ], ), ), diff --git a/lib/features/home/dashboard_store_ticket_list/ui/dashboard_store_ticket_list_card.dart b/lib/features/home/dashboard_store_ticket_list/ui/dashboard_store_ticket_list_card.dart index 4712c9f..17d3840 100644 --- a/lib/features/home/dashboard_store_ticket_list/ui/dashboard_store_ticket_list_card.dart +++ b/lib/features/home/dashboard_store_ticket_list/ui/dashboard_store_ticket_list_card.dart @@ -114,6 +114,10 @@ class _DashboardStoreTicketListCardContent extends StatelessWidget { itemBuilder: (context, index) { final ticket = state.tickets[index]; final statusColor = ticket.ticketStatus.color; + final dateStr = ticket.createdAt != null + ? "${ticket.createdAt!.day.toString().padLeft(2, '0')}/${ticket.createdAt!.month.toString().padLeft(2, '0')}" + : ''; + return InkWell( onTap: () => context.pushNamed( Routes.ticketForm, @@ -125,47 +129,50 @@ class _DashboardStoreTicketListCardContent extends StatelessWidget { vertical: 8.0, ), child: Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, children: [ Container( - width: 8, - height: - 30, // Un'altezza fissa per farlo comparire! + width: 6, + height: 34, decoration: BoxDecoration( color: statusColor, - borderRadius: BorderRadius.circular( - 4, - ), // Angoli smussati per stile + borderRadius: BorderRadius.circular(4), ), ), - const SizedBox(width: 4), + const SizedBox(width: 10), Expanded( - flex: 5, - child: Text( - ticket.customer?.name ?? - 'Cliente sconosciuto', - style: TextStyle( - fontWeight: FontWeight.w700, - color: context.primaryText, - ), - ), - ), - Expanded( - flex: 5, - child: Text( - ticket.targetModelName ?? - 'Modello sconosciuto', - style: TextStyle( - fontWeight: FontWeight.w600, - color: context.primaryText, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + ticket.customer?.name ?? + 'Cliente sconosciuto', + style: TextStyle( + fontWeight: FontWeight.w700, + color: context.primaryText, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 2), + Text( + ticket.targetModelName ?? + 'Modello sconosciuto', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w500, + color: context.secondaryText, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], ), ), + const SizedBox(width: 8), Text( - "${ticket.createdAt?.day}/${ticket.createdAt?.month}", + dateStr, style: TextStyle( color: context.secondaryText, fontSize: 12, diff --git a/lib/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart b/lib/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart index dde705f..0c1f775 100644 --- a/lib/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart +++ b/lib/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart @@ -80,74 +80,148 @@ class _DashboardTargetHeroCardState extends State { ]; final monthLabel = '${months[now.month - 1]} ${now.year}'; - return Container( - padding: const EdgeInsets.all(20), - decoration: BoxDecoration( - color: theme.colorScheme.surface, - borderRadius: BorderRadius.circular(20), - border: Border.all( - color: theme.colorScheme.primary.withValues(alpha: 0.2), - width: 1.5, - ), - boxShadow: [ - BoxShadow( - color: theme.colorScheme.primary.withValues(alpha: 0.04), - blurRadius: 16, - offset: const Offset(0, 4), - ), - ], - ), - child: Row( - children: [ - Container( - padding: const EdgeInsets.all(14), - decoration: BoxDecoration( - color: theme.colorScheme.primary.withValues(alpha: 0.1), - borderRadius: BorderRadius.circular(14), + return LayoutBuilder( + builder: (context, constraints) { + final isCompact = constraints.maxWidth < 520; + + return Container( + padding: EdgeInsets.all(isCompact ? 16 : 20), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: theme.colorScheme.primary.withValues(alpha: 0.2), + width: 1.5, ), - child: Icon( - Icons.flag_outlined, - color: theme.colorScheme.primary, - size: 28, - ), - ), - const SizedBox(width: 16), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - 'Nessun obiettivo per $monthLabel', - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 4), - Text( - 'Imposta i target di ${currentStore?.name ?? "questo negozio"} per monitorare le medie giornaliere richieste e il ritmo di vendita.', - style: TextStyle( - fontSize: 13, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], - ), - ), - const SizedBox(width: 16), - FilledButton.icon( - onPressed: () => context.pushNamed(Routes.targets), - icon: const Icon(Icons.add, size: 18), - label: const Text('Imposta Target'), - style: FilledButton.styleFrom( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: theme.colorScheme.primary.withValues(alpha: 0.04), + blurRadius: 16, + offset: const Offset(0, 4), ), - ), + ], ), - ], - ), + child: isCompact + ? Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.all(11), + decoration: BoxDecoration( + color: theme.colorScheme.primary.withValues( + alpha: 0.1, + ), + borderRadius: BorderRadius.circular(12), + ), + child: Icon( + Icons.flag_outlined, + color: theme.colorScheme.primary, + size: 24, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Nessun obiettivo per $monthLabel', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + fontSize: 15, + ), + ), + const SizedBox(height: 4), + Text( + 'Imposta i target di ${currentStore?.name ?? "questo negozio"} per monitorare le medie giornaliere richieste e il ritmo di vendita.', + style: TextStyle( + fontSize: 12.5, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 14), + FilledButton.icon( + onPressed: () => context.pushNamed(Routes.targets), + icon: const Icon(Icons.add, size: 18), + label: const Text('Imposta Target'), + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + ), + ], + ) + : Row( + children: [ + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: theme.colorScheme.primary.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(14), + ), + child: Icon( + Icons.flag_outlined, + color: theme.colorScheme.primary, + size: 28, + ), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Nessun obiettivo per $monthLabel', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 4), + Text( + 'Imposta i target di ${currentStore?.name ?? "questo negozio"} per monitorare le medie giornaliere richieste e il ritmo di vendita.', + style: TextStyle( + fontSize: 13, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + const SizedBox(width: 16), + FilledButton.icon( + onPressed: () => context.pushNamed(Routes.targets), + icon: const Icon(Icons.add, size: 18), + label: const Text('Imposta Target'), + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + ), + ], + ), + ); + }, ); } @@ -370,22 +444,24 @@ class _DashboardTargetHeroCardState extends State { if (categoriesToDisplay.isNotEmpty) Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), + padding: EdgeInsets.symmetric( + horizontal: isCompact ? 12 : 16, + ), child: GridView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: categoriesToDisplay.length, gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( - maxCrossAxisExtent: - constraints.maxWidth > 700 ? 260 : 200, - mainAxisExtent: 168, - crossAxisSpacing: 10, - mainAxisSpacing: 10, + maxCrossAxisExtent: constraints.maxWidth > 700 + ? 260 + : (constraints.maxWidth < 310 ? 320 : 200), + mainAxisExtent: isCompact ? 176 : 168, + crossAxisSpacing: isCompact ? 8 : 10, + mainAxisSpacing: isCompact ? 8 : 10, ), itemBuilder: (context, index) { final category = categoriesToDisplay[index]; - final storeCategory = - progress.categories[category.key]; + final storeCategory = progress.categories[category.key]; return _buildCategoryDailyPacingCard( theme, category, @@ -558,254 +634,335 @@ class _DashboardTargetHeroCardState extends State { final isAchieved = category.isAchieved; final hasS2 = category.targetS2 > 0; - return Material( - color: Colors.transparent, - child: InkWell( - borderRadius: BorderRadius.circular(14), - onTap: () => _navigateToOperationsForCategory( - category, - isManager: isManager, - ), - child: Container( - padding: const EdgeInsets.all(12), + final statusLabel = isAchieved + ? 'Preso! 🎉' + : (category.status == TargetPacingStatus.inLineS1 || + category.status == TargetPacingStatus.inLineS2 + ? 'In linea ✅' + : (category.status == TargetPacingStatus.recoverable + ? 'Da spingere ⚡' + : 'In ritardo 🔴')); + + return LayoutBuilder( + builder: (context, cardConstraints) { + final isNarrowCard = cardConstraints.maxWidth < 185; + + final statusPill = Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( - color: theme.colorScheme.surface, - borderRadius: BorderRadius.circular(14), - border: Border.all( - color: pacingTheme.border.withValues(alpha: 0.7), - width: 1.2, - ), - boxShadow: [ - BoxShadow( - color: pacingTheme.primary.withValues(alpha: 0.04), - blurRadius: 8, - offset: const Offset(0, 2), + color: pacingTheme.background, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: pacingTheme.border, width: 0.8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + statusLabel, + style: TextStyle( + fontSize: 9, + fontWeight: FontWeight.w900, + color: pacingTheme.text, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ), + if (!isNarrowCard) ...[ + const SizedBox(width: 3), + Icon( + Icons.arrow_forward_ios, + size: 8, + color: pacingTheme.text, + ), + ], ], ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Header tessera: Nome metrica + Pillola di stato - Row( - children: [ - Expanded( - child: Text( - category.label.toUpperCase(), - style: const TextStyle( - fontSize: 11, - fontWeight: FontWeight.w800, - letterSpacing: 0.3, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - const SizedBox(width: 4), - Container( - padding: - const EdgeInsets.symmetric(horizontal: 6, vertical: 2), - decoration: BoxDecoration( - color: pacingTheme.background, - borderRadius: BorderRadius.circular(6), - border: Border.all(color: pacingTheme.border, width: 0.8), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - isAchieved - ? 'Preso! 🎉' - : (category.status == TargetPacingStatus.inLineS1 || - category.status == - TargetPacingStatus.inLineS2 - ? 'In linea ✅' - : (category.status == - TargetPacingStatus.recoverable - ? 'Da spingere ⚡' - : 'In ritardo 🔴')), - style: TextStyle( - fontSize: 9, - fontWeight: FontWeight.w900, - color: pacingTheme.text, - ), - ), - const SizedBox(width: 3), - Icon( - Icons.arrow_forward_ios, - size: 8, - color: pacingTheme.text, - ), - ], - ), + ); + + return Material( + color: Colors.transparent, + child: InkWell( + borderRadius: BorderRadius.circular(14), + onTap: () => _navigateToOperationsForCategory( + category, + isManager: isManager, + ), + child: Container( + padding: EdgeInsets.all(isNarrowCard ? 10 : 12), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: pacingTheme.border.withValues(alpha: 0.7), + width: 1.2, + ), + boxShadow: [ + BoxShadow( + color: pacingTheme.primary.withValues(alpha: 0.04), + blurRadius: 8, + offset: const Offset(0, 2), ), ], ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header tessera: su card strette impiliamo titolo e pillola così il nome si legge per intero + if (isNarrowCard) ...[ + Row( + children: [ + Expanded( + child: Text( + category.label.toUpperCase(), + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w800, + letterSpacing: 0.2, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 4), + Icon( + Icons.arrow_forward_ios, + size: 8.5, + color: theme.colorScheme.onSurfaceVariant, + ), + ], + ), + const SizedBox(height: 4), + statusPill, + ] else + Row( + children: [ + Expanded( + child: Text( + category.label.toUpperCase(), + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w800, + letterSpacing: 0.3, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 4), + statusPill, + ], + ), - const Spacer(), + const Spacer(), - // Centro: Numero gigante MEDIA GIORNALIERA RICHIESTA PER OGGI - if (isAchieved) - Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.baseline, - textBaseline: TextBaseline.alphabetic, - children: [ - Text( - 'RAGGIUNTO', - style: TextStyle( - fontSize: 18, - fontWeight: FontWeight.w900, - color: pacingTheme.primary, - letterSpacing: -0.5, + // Centro: Numero gigante MEDIA GIORNALIERA RICHIESTA PER OGGI + if (isAchieved) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Flexible( + child: Text( + 'RAGGIUNTO', + style: TextStyle( + fontSize: isNarrowCard ? 15.5 : 18, + fontWeight: FontWeight.w900, + color: pacingTheme.primary, + letterSpacing: -0.5, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 4), + Text( + '🏆', + style: TextStyle( + fontSize: isNarrowCard ? 14 : 16, + ), + ), + ], + ), + if (hasS2 && !category.isAchievedS2) + Text( + 'Sfida (S2): ${category.requiredDailyRateS2.toStringAsFixed(1)} / gg', + style: TextStyle( + fontSize: isNarrowCard ? 10 : 11, + fontWeight: FontWeight.bold, + color: Colors.purple.shade700, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ) + else + Text( + isManager + ? 'Obiettivo negozio centrato!' + : 'Obiettivo personale centrato!', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ) + else + Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Flexible( + child: Text( + category.requiredDailyRateS1.toStringAsFixed(1), + style: TextStyle( + fontSize: isNarrowCard ? 21 : 24, + fontWeight: FontWeight.w900, + color: pacingTheme.text, + letterSpacing: -0.5, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 4), + Text( + '/ giorno', + style: TextStyle( + fontSize: isNarrowCard ? 10.5 : 11, + fontWeight: FontWeight.w800, + color: pacingTheme.text.withValues(alpha: 0.8), + ), + ), + ], + ), + if (hasS2) + Text( + 'Sfida S2: ${category.requiredDailyRateS2.toStringAsFixed(1)} / gg', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: theme.colorScheme.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ) + else + Text( + 'Target: ${category.targetS1} pz', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ), + + const Spacer(), + + // Footer: Avanzamento e ritmo + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: Text( + isManager + ? 'Negozio: ${category.actualPieces}/${category.targetS1}' + : 'I tuoi: ${category.actualPieces}/${category.targetS1}', + style: TextStyle( + fontSize: isNarrowCard ? 9.5 : 10, + fontWeight: FontWeight.bold, + color: theme.colorScheme.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ), - ), - const SizedBox(width: 4), - const Text('🏆', style: TextStyle(fontSize: 16)), - ], - ), - if (hasS2 && !category.isAchievedS2) - Text( - 'Sfida (S2): ${category.requiredDailyRateS2.toStringAsFixed(1)} / gg', - style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.bold, - color: Colors.purple.shade700, - ), - ) - else - Text( - isManager - ? 'Obiettivo negozio centrato!' - : 'Obiettivo personale centrato!', - style: TextStyle( - fontSize: 10, - fontWeight: FontWeight.w600, - color: theme.colorScheme.onSurfaceVariant, + const SizedBox(width: 4), + Text( + isNarrowCard + ? '${category.actualDailyRate.toStringAsFixed(1)}/gg' + : 'ritmo: ${category.actualDailyRate.toStringAsFixed(1)}/gg', + style: TextStyle( + fontSize: isNarrowCard ? 9.5 : 10, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: 4), + ClipRRect( + borderRadius: BorderRadius.circular(2), + child: LinearProgressIndicator( + value: category.targetS1 > 0 + ? (category.actualPieces / category.targetS1).clamp( + 0.0, + 1.0, + ) + : 0.0, + minHeight: 4, + backgroundColor: pacingTheme.background, + color: pacingTheme.primary, ), ), - ], - ) - else - Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.baseline, - textBaseline: TextBaseline.alphabetic, - children: [ - Text( - category.requiredDailyRateS1.toStringAsFixed(1), - style: TextStyle( - fontSize: 24, - fontWeight: FontWeight.w900, - color: pacingTheme.text, - letterSpacing: -0.5, - ), - ), - const SizedBox(width: 4), - Text( - '/ giorno', - style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.w800, - color: pacingTheme.text.withValues(alpha: 0.8), - ), + if (!isManager && + storeCategory != null && + storeCategory.targetS1 > 0) ...[ + const SizedBox(height: 4), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: Text( + 'Negozio: ${storeCategory.actualPieces}/${storeCategory.targetS1}', + style: TextStyle( + fontSize: 9.5, + color: theme.colorScheme.onSurfaceVariant + .withValues(alpha: 0.75), + fontWeight: FontWeight.w600, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 4), + Text( + isNarrowCard + ? '${storeCategory.actualDailyRate.toStringAsFixed(1)}/gg' + : 'ritmo: ${storeCategory.actualDailyRate.toStringAsFixed(1)}/gg', + style: TextStyle( + fontSize: 9.5, + color: theme.colorScheme.onSurfaceVariant + .withValues(alpha: 0.75), + fontWeight: FontWeight.w600, + ), + ), + ], ), ], - ), - if (hasS2) - Text( - 'Sfida S2: ${category.requiredDailyRateS2.toStringAsFixed(1)} / gg', - style: TextStyle( - fontSize: 10, - fontWeight: FontWeight.bold, - color: theme.colorScheme.onSurfaceVariant, - ), - ) - else - Text( - 'Target: ${category.targetS1} pz', - style: TextStyle( - fontSize: 10, - fontWeight: FontWeight.w600, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], - ), - - const Spacer(), - - // Footer: Avanzamento e ritmo - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - isManager - ? 'Negozio: ${category.actualPieces} / ${category.targetS1}' - : 'I tuoi: ${category.actualPieces} / ${category.targetS1}', - style: TextStyle( - fontSize: 10, - fontWeight: FontWeight.bold, - color: theme.colorScheme.onSurfaceVariant, - ), + ], ), - Text( - 'ritmo: ${category.actualDailyRate.toStringAsFixed(1)}/gg', - style: TextStyle( - fontSize: 10, - fontWeight: FontWeight.w600, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], - ), - const SizedBox(height: 4), - ClipRRect( - borderRadius: BorderRadius.circular(2), - child: LinearProgressIndicator( - value: category.targetS1 > 0 - ? (category.actualPieces / category.targetS1).clamp(0.0, 1.0) - : 0.0, - minHeight: 4, - backgroundColor: pacingTheme.background, - color: pacingTheme.primary, ), ), - if (!isManager && storeCategory != null && storeCategory.targetS1 > 0) ...[ - const SizedBox(height: 4), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - 'Negozio: ${storeCategory.actualPieces}/${storeCategory.targetS1}', - style: TextStyle( - fontSize: 9.5, - color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.75), - fontWeight: FontWeight.w600, - ), - ), - Text( - 'ritmo: ${storeCategory.actualDailyRate.toStringAsFixed(1)}/gg', - style: TextStyle( - fontSize: 9.5, - color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.75), - fontWeight: FontWeight.w600, - ), - ), - ], - ), - ], - ], - ), - ), - ), -); + ); + }, + ); } Widget _buildInLineSummaryBanner( @@ -822,12 +979,15 @@ class _DashboardTargetHeroCardState extends State { final bannerBorder = isDark ? const Color(0xFF047857).withValues(alpha: 0.5) : const Color(0xFFBBF7D0); - final bannerIconColor = - isDark ? const Color(0xFF34D399) : const Color(0xFF16A34A); - final bannerTextColor = - isDark ? const Color(0xFF6EE7B7) : const Color(0xFF15803D); - final bannerSubtextColor = - isDark ? const Color(0xFFA7F3D0) : const Color(0xFF166534); + final bannerIconColor = isDark + ? const Color(0xFF34D399) + : const Color(0xFF16A34A); + final bannerTextColor = isDark + ? const Color(0xFF6EE7B7) + : const Color(0xFF15803D); + final bannerSubtextColor = isDark + ? const Color(0xFFA7F3D0) + : const Color(0xFF166534); final subjectText = isManager ? 'Il negozio è in linea' : 'Sei in linea'; @@ -837,86 +997,152 @@ class _DashboardTargetHeroCardState extends State { final categoryNames = inLineCategories.map((c) => c.label).join(' • '); - return Container( - margin: const EdgeInsets.fromLTRB(16, 0, 16, 12), - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), - decoration: BoxDecoration( - color: bannerBg, - borderRadius: BorderRadius.circular(12), - border: Border.all(color: bannerBorder, width: 1), - ), - child: Row( - children: [ - Icon( - Icons.check_circle_rounded, - color: bannerIconColor, - size: 20, - ), - const SizedBox(width: 10), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - titleText, - style: TextStyle( - fontSize: 12.5, - fontWeight: FontWeight.w800, - color: bannerTextColor, - ), - ), - const SizedBox(height: 2), - Text( - categoryNames, - style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.w500, - color: bannerSubtextColor, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ], - ), - ), - const SizedBox(width: 8), - InkWell( - onTap: () { - setState(() { - _showAllCategories = !_showAllCategories; - }); - }, - borderRadius: BorderRadius.circular(8), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - _showAllCategories - ? 'Nascondi' - : 'Mostra tutti (${inLineCategories.length})', - style: TextStyle( - fontSize: 11.5, - fontWeight: FontWeight.bold, - color: bannerTextColor, - ), - ), - Icon( - _showAllCategories - ? Icons.keyboard_arrow_up - : Icons.keyboard_arrow_down, - size: 16, - color: bannerTextColor, - ), - ], + final toggleButton = InkWell( + onTap: () { + setState(() { + _showAllCategories = !_showAllCategories; + }); + }, + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _showAllCategories + ? 'Nascondi' + : 'Mostra tutti (${inLineCategories.length})', + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.bold, + color: bannerTextColor, ), ), - ), - ], + Icon( + _showAllCategories + ? Icons.keyboard_arrow_up + : Icons.keyboard_arrow_down, + size: 16, + color: bannerTextColor, + ), + ], + ), ), ); + + return LayoutBuilder( + builder: (context, bannerConstraints) { + final isNarrowBanner = bannerConstraints.maxWidth < 460; + + return Container( + margin: EdgeInsets.fromLTRB( + isNarrowBanner ? 12 : 16, + 0, + isNarrowBanner ? 12 : 16, + 12, + ), + padding: EdgeInsets.symmetric( + horizontal: isNarrowBanner ? 12 : 14, + vertical: 10, + ), + decoration: BoxDecoration( + color: bannerBg, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: bannerBorder, width: 1), + ), + child: isNarrowBanner + ? Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + Icons.check_circle_rounded, + color: bannerIconColor, + size: 19, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + titleText, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w800, + color: bannerTextColor, + ), + ), + const SizedBox(height: 2), + Text( + categoryNames, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w500, + color: bannerSubtextColor, + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ], + ), + const SizedBox(height: 4), + Align( + alignment: Alignment.centerRight, + child: toggleButton, + ), + ], + ) + : Row( + children: [ + Icon( + Icons.check_circle_rounded, + color: bannerIconColor, + size: 20, + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + titleText, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w800, + color: bannerTextColor, + ), + ), + const SizedBox(height: 2), + Text( + categoryNames, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w500, + color: bannerSubtextColor, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + const SizedBox(width: 8), + toggleButton, + ], + ), + ); + }, + ); } Widget _buildMiniBadge({ diff --git a/lib/features/home/ui/home_screen.dart b/lib/features/home/ui/home_screen.dart index bd392c1..4148c71 100644 --- a/lib/features/home/ui/home_screen.dart +++ b/lib/features/home/ui/home_screen.dart @@ -118,103 +118,145 @@ class _HomeScreenState extends State { return Scaffold( backgroundColor: theme.colorScheme.surface, body: SafeArea( - child: Column( - children: [ - // ========================================== - // 1. HEADER FISSO (Non scrolla mai) - // ========================================== - Container( - padding: const EdgeInsets.all(24.0), - // Un leggero colore di sfondo aiuta a staccare l'header quando il contenuto ci passa sotto - color: theme.colorScheme.surface, - child: _buildHeader(context, theme), - ), + child: LayoutBuilder( + builder: (context, constraints) { + final isMobile = constraints.maxWidth < 600; + final isSingleColGrid = constraints.maxWidth < 650; + final hPad = isMobile ? 16.0 : 24.0; + final vGap = isMobile ? 16.0 : 24.0; - // ========================================== - // 2. CORPO DELLA DASHBOARD (Scrollabile) - // ========================================== - Expanded( - child: BlocListener( - listenWhen: (prev, curr) => - prev.currentStore?.id != curr.currentStore?.id || - prev.currentStaffMember?.id != curr.currentStaffMember?.id || - prev.company?.id != curr.company?.id, - listener: (context, sessionState) { - context.read().updateContext( + return Column( + children: [ + // ========================================== + // 1. HEADER FISSO SU DESKTOP / TABLET LARGO + // ========================================== + if (!isMobile) + Container( + padding: const EdgeInsets.all(24.0), + color: theme.colorScheme.surface, + child: _buildHeader(context, theme, isMobile: false), + ), + + // ========================================== + // 2. CORPO DELLA DASHBOARD (Scrollabile) + // ========================================== + Expanded( + child: BlocListener( + listenWhen: (prev, curr) => + prev.currentStore?.id != curr.currentStore?.id || + prev.currentStaffMember?.id != + curr.currentStaffMember?.id || + prev.company?.id != curr.company?.id, + listener: (context, sessionState) { + context.read().updateContext( newCompanyId: sessionState.company?.id, newStoreId: sessionState.currentStore?.id, newStaffId: sessionState.currentStaffMember?.id, ); - context.read().updateContext( + context.read().updateContext( newCompanyId: sessionState.company?.id, newStoreId: sessionState.currentStore?.id, ); - }, - child: CustomScrollView( - slivers: [ - // --- 1. QUICK ACTIONS: AZIONI RAPIDE (IN CIMA) --- - SliverToBoxAdapter( - child: Padding( - padding: const EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0), - child: _buildQuickActions(context), - ), - ), - - // --- 2. HERO FOCUS RICONTATTI DEL GIORNO (VISIBILE AI MANAGER) --- - const SliverToBoxAdapter( - child: DashboardDailyRicontattiCard(), - ), - - // --- 3. HERO TARGET DEL GIORNO --- - const SliverToBoxAdapter( - child: Padding( - padding: EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0), - child: DashboardTargetHeroCard(), - ), - ), - - const SliverToBoxAdapter(child: SizedBox(height: 8)), - - // --- 4. I WIDGET DELLA DASHBOARD (Responsive Grid) --- - SliverPadding( - padding: const EdgeInsets.symmetric(horizontal: 24.0), - sliver: SliverGrid( - gridDelegate: - const SliverGridDelegateWithMaxCrossAxisExtent( - maxCrossAxisExtent: 500, - mainAxisSpacing: 16, - crossAxisSpacing: 16, - childAspectRatio: 1.3, + }, + child: CustomScrollView( + slivers: [ + // Su mobile l'header scrolla col contenuto così non ruba mezzo schermo + if (isMobile) + SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.fromLTRB( + hPad, + 8.0, + hPad, + 14.0, + ), + child: _buildHeader( + context, + theme, + isMobile: true, + ), ), - delegate: SliverChildListDelegate([ - DashboardStoreOperationListCard(), - DashboardStoreTicketListCard(), - DashboardExpiringContractsCard(), - DashboardNoteListCard(), - DashboardTaskListCard(), - ]), - ), - ), + ), - // Spazio finale per non far attaccare l'ultima card al fondo - const SliverToBoxAdapter(child: SizedBox(height: 40)), - ], + // --- 1. QUICK ACTIONS: AZIONI RAPIDE (IN CIMA) --- + SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.fromLTRB(hPad, 0, hPad, vGap), + child: _buildQuickActions( + context, + isMobile: isMobile, + ), + ), + ), + + // --- 2. HERO FOCUS RICONTATTI DEL GIORNO (VISIBILE AI MANAGER) --- + const SliverToBoxAdapter( + child: DashboardDailyRicontattiCard(), + ), + + // --- 3. HERO TARGET DEL GIORNO --- + SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.fromLTRB(hPad, 0, hPad, vGap), + child: const DashboardTargetHeroCard(), + ), + ), + + SliverToBoxAdapter( + child: SizedBox(height: isMobile ? 4 : 8), + ), + + // --- 4. I WIDGET DELLA DASHBOARD (Responsive Grid) --- + SliverPadding( + padding: EdgeInsets.symmetric(horizontal: hPad), + sliver: SliverGrid( + gridDelegate: isSingleColGrid + ? const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 1, + mainAxisSpacing: 14, + mainAxisExtent: 268, + ) + : const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 500, + mainAxisSpacing: 16, + crossAxisSpacing: 16, + mainAxisExtent: 290, + ), + delegate: SliverChildListDelegate([ + const DashboardStoreOperationListCard(), + const DashboardStoreTicketListCard(), + const DashboardExpiringContractsCard(), + const DashboardNoteListCard(), + const DashboardTaskListCard(), + ]), + ), + ), + + // Spazio finale per non far attaccare l'ultima card al fondo + const SliverToBoxAdapter(child: SizedBox(height: 40)), + ], + ), + ), ), - ), - ), - ], + ], + ); + }, ), ), ); } // ========================================== - Widget _buildHeader(BuildContext context, ThemeData theme) { + Widget _buildHeader( + BuildContext context, + ThemeData theme, { + required bool isMobile, + }) { final user = context.watch().state.currentStaffMember; final currentStore = context.watch().state.currentStore; return Row( - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Column( @@ -222,31 +264,33 @@ class _HomeScreenState extends State { children: [ Text( context.l10n.homeWelcomeBack(user?.name ?? "Utente"), - style: theme.textTheme.headlineMedium?.copyWith( - fontWeight: FontWeight.bold, - letterSpacing: -0.5, - color: context.primaryText, // Uso dell'estensione! - ), + style: + (isMobile + ? theme.textTheme.titleLarge + : theme.textTheme.headlineMedium) + ?.copyWith( + fontWeight: FontWeight.bold, + letterSpacing: -0.5, + color: context.primaryText, + ), + maxLines: isMobile ? 1 : 2, + overflow: TextOverflow.ellipsis, ), - const SizedBox(height: 8), + SizedBox(height: isMobile ? 6 : 8), InkWell( onTap: () => _showStoreSelector(context, theme), borderRadius: BorderRadius.circular(8), child: Container( - padding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 6, + padding: EdgeInsets.symmetric( + horizontal: isMobile ? 10 : 12, + vertical: isMobile ? 5 : 6, ), decoration: BoxDecoration( - color: context.primary.withValues( - alpha: 0.08, - ), // Sfondo delicato + color: context.primary.withValues(alpha: 0.08), borderRadius: BorderRadius.circular(8), border: Border.all( - color: context.primary.withValues( - alpha: 0.2, - ), // Bordino netto + color: context.primary.withValues(alpha: 0.2), ), ), child: Row( @@ -254,15 +298,24 @@ class _HomeScreenState extends State { children: [ Icon(Icons.storefront, size: 16, color: context.primary), const SizedBox(width: 8), - Text( - currentStore?.name ?? context.l10n.homeNoStoreFound, - style: TextStyle( - fontWeight: FontWeight.w600, - color: context.primary, + Flexible( + child: Text( + currentStore?.name ?? context.l10n.homeNoStoreFound, + style: TextStyle( + fontSize: isMobile ? 13 : 14, + fontWeight: FontWeight.w600, + color: context.primary, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, ), ), const SizedBox(width: 4), - Icon(Icons.arrow_drop_down, color: context.primary), + Icon( + Icons.arrow_drop_down, + size: 20, + color: context.primary, + ), ], ), ), @@ -270,17 +323,22 @@ class _HomeScreenState extends State { ], ), ), + const SizedBox(width: 12), CircleAvatar( - radius: 24, - // Usiamo il Turchese (accent) in trasparenza per l'avatar + radius: isMobile ? 20 : 24, backgroundColor: context.accent.withValues(alpha: 0.15), - child: Icon(Icons.person, color: context.accent, size: 26), + child: Icon( + Icons.person, + color: context.accent, + size: isMobile ? 22 : 26, + ), ), ], ); } - Widget _buildQuickActions(BuildContext context) { + Widget _buildQuickActions(BuildContext context, {bool isMobile = false}) { + final gap = isMobile ? 8.0 : 12.0; return SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( @@ -289,6 +347,7 @@ class _HomeScreenState extends State { icon: Icons.add, label: context.l10n.commonOperation, color: Colors.blue, + compact: isMobile, onTap: () async { StaffMemberModel? createdBy = await getStaffMember(context); if (createdBy == null || !context.mounted) return; @@ -299,11 +358,12 @@ class _HomeScreenState extends State { ); }, ), - const SizedBox(width: 12), + SizedBox(width: gap), QuickActionButton( icon: Icons.handyman, label: context.l10n.homeNewOperationTicket, color: Colors.redAccent, + compact: isMobile, onTap: () async { StaffMemberModel? createdBy = await getStaffMember(context); if (createdBy == null || !context.mounted) return; @@ -314,11 +374,12 @@ class _HomeScreenState extends State { ); }, ), - const SizedBox(width: 12), + SizedBox(width: gap), QuickActionButton( icon: Icons.note_add, label: context.l10n.commonNote, color: Colors.amber, + compact: isMobile, onTap: () async { final companyId = context.read().state.company!.id!; final currentStaffId = context @@ -341,11 +402,12 @@ class _HomeScreenState extends State { ); }, ), - const SizedBox(width: 12), + SizedBox(width: gap), QuickActionButton( icon: Icons.task_alt, label: context.l10n.commonTask, color: Colors.orange, + compact: isMobile, onTap: () { context.pushNamed(Routes.taskForm, pathParameters: {'id': 'new'}); }, diff --git a/lib/features/home/ui/quick_actions_widget.dart b/lib/features/home/ui/quick_actions_widget.dart index e062fa0..5f09432 100644 --- a/lib/features/home/ui/quick_actions_widget.dart +++ b/lib/features/home/ui/quick_actions_widget.dart @@ -7,6 +7,7 @@ class QuickActionButton extends StatelessWidget { final String label; final Color color; final VoidCallback onTap; + final bool compact; const QuickActionButton({ super.key, @@ -14,6 +15,7 @@ class QuickActionButton extends StatelessWidget { required this.label, required this.color, required this.onTap, + this.compact = false, }); @override @@ -22,7 +24,10 @@ class QuickActionButton extends StatelessWidget { onTap: onTap, borderRadius: BorderRadius.circular(12), child: Container( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + padding: EdgeInsets.symmetric( + horizontal: compact ? 12 : 16, + vertical: compact ? 10 : 12, + ), decoration: BoxDecoration( border: Border.all(color: color.withValues(alpha: 0.3)), color: color.withValues(alpha: 0.05), @@ -31,11 +36,15 @@ class QuickActionButton extends StatelessWidget { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Icon(icon, color: color, size: 20), - const SizedBox(width: 8), + Icon(icon, color: color, size: compact ? 18 : 20), + SizedBox(width: compact ? 6 : 8), Text( label, - style: TextStyle(fontWeight: FontWeight.bold, color: color), + style: TextStyle( + fontSize: compact ? 13 : 14, + fontWeight: FontWeight.bold, + color: color, + ), ), ], ), diff --git a/lib/features/notes/ui/notes_form_screen.dart b/lib/features/notes/ui/notes_form_screen.dart index 0d5afd4..9f8f8cd 100644 --- a/lib/features/notes/ui/notes_form_screen.dart +++ b/lib/features/notes/ui/notes_form_screen.dart @@ -21,10 +21,13 @@ class _NoteFormScreenState extends State { late TextEditingController _titleController; late TextEditingController _contentController; late final NotesCubit _notesCubit; + late final String _companyId; late String _selectedColor; late bool _isPinned; late bool _isSharedAll; late List _selectedStaffIds; + bool _hasPendingChanges = false; + bool _isDeleted = false; // Inizializziamo il Debouncer a 500 millisecondi final _debouncer = Debouncer(milliseconds: 500); @@ -44,6 +47,9 @@ class _NoteFormScreenState extends State { _titleController = TextEditingController(text: widget.note.title ?? ''); _contentController = TextEditingController(text: widget.note.content ?? ''); _notesCubit = context.read(); + _companyId = widget.note.companyId.isNotEmpty + ? widget.note.companyId + : context.read().state.company!.id!; _selectedColor = widget.note.color; _isPinned = widget.note.isPinned; _isSharedAll = widget.note.isSharedAll; @@ -58,29 +64,49 @@ class _NoteFormScreenState extends State { void dispose() { _titleController.removeListener(_onFieldsChanged); _contentController.removeListener(_onFieldsChanged); - _titleController.dispose(); - _contentController.dispose(); _debouncer.dispose(); - // --- IL BOTTO FINALE: PULIZIA SILENZIOSA --- - _checkAndCleanupIfEmpty(_note.id!); + // Se ci sono modifiche pendenti non ancora salvate dal debouncer, salviamole subito + if (!_isDeleted) { + _flushIfPending(); + // --- IL BOTTO FINALE: PULIZIA SILENZIOSA --- + _checkAndCleanupIfEmpty(_note.id!); + } + _titleController.dispose(); + _contentController.dispose(); super.dispose(); } /// Chiamata ogni volta che l'utente digita una lettera void _onFieldsChanged() { + _hasPendingChanges = true; _debouncer.run(() => _triggerAutoSave()); } + void _flushIfPending() { + final isNoteEmpty = + _titleController.text.trim().isEmpty && + _contentController.text.trim().isEmpty; + if (_hasPendingChanges && !isNoteEmpty) { + _triggerAutoSave(); + } + } + + void _closeNote() { + FocusScope.of(context).unfocus(); + _flushIfPending(); + Navigator.of(context).maybePop(); + } + /// Salva in background notificando il BLoC (così la bacheca si aggiorna in tempo reale) void _triggerAutoSave() { - final companyId = context.read().state.company!.id!; + _hasPendingChanges = false; final updatedNote = NoteModel( id: widget.note.id, createdBy: widget.note.createdBy, - companyId: companyId, + companyId: _companyId, title: _titleController.text.trim(), content: _contentController.text.trim(), color: _selectedColor, @@ -98,9 +124,6 @@ class _NoteFormScreenState extends State { final titleEmpty = _titleController.text.trim().isEmpty; final contentEmpty = _contentController.text.trim().isEmpty; - //Se hai un modo per verificare se ci sono allegati associati (es. tramite una query locale o un contatore), - // assicurati che non ce ne siano prima di eliminare. - // Assumiamo che se non ha scritto testo ed è appena stata creata, sia vuota. if (titleEmpty && contentEmpty) { // Notifichiamo anche il Bloc dell'avvenuta cancellazione così pulisce lo stato locale _notesCubit.deleteNote(noteId); @@ -108,6 +131,9 @@ class _NoteFormScreenState extends State { } void _deleteNote() { + _isDeleted = true; + _hasPendingChanges = false; + _debouncer.dispose(); _notesCubit.deleteNote(widget.note.id!); Navigator.pop(context); } @@ -223,28 +249,60 @@ class _NoteFormScreenState extends State { appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back), + tooltip: 'Chiudi nota', + onPressed: _closeNote, + ), + flexibleSpace: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: _closeNote, + ), // Freccia indietro chiara per fare contrasto sullo sfondo grigio scuro iconTheme: const IconThemeData(color: Colors.white70), ), - body: Center( - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 680), - child: SingleChildScrollView( - padding: const EdgeInsets.only(bottom: 64, left: 16, right: 16), - child: Container( - // 2. IL NOSTRO POST-IT FISICO - decoration: BoxDecoration( - color: noteColor, - borderRadius: BorderRadius.circular(16), // Bordi arrotondati - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.4), // Ombra morbida - blurRadius: 24, - offset: const Offset(0, 12), - ), - ], - ), - padding: const EdgeInsets.all(24.0), + body: Stack( + children: [ + // Area esterna cliccabile: toccando fuori dal Post-it la nota si chiude + Positioned.fill( + child: GestureDetector( + key: const ValueKey('note_outside_backdrop'), + behavior: HitTestBehavior.opaque, + onTap: _closeNote, + ), + ), + Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 680), + child: SingleChildScrollView( + padding: const EdgeInsets.only( + top: 8, + bottom: 48, + left: 16, + right: 16, + ), + child: GestureDetector( + key: const ValueKey('note_postit_card'), + behavior: HitTestBehavior.opaque, + onTap: () {}, + child: Container( + // 2. IL NOSTRO POST-IT FISICO + decoration: BoxDecoration( + color: noteColor, + borderRadius: BorderRadius.circular( + 16, + ), // Bordi arrotondati + boxShadow: [ + BoxShadow( + color: Colors.black.withValues( + alpha: 0.4, + ), // Ombra morbida + blurRadius: 24, + offset: const Offset(0, 12), + ), + ], + ), + padding: const EdgeInsets.all(24.0), child: Column( // 3. MainAxisSize.min fa sì che il Post-it sia alto solo quanto serve! mainAxisSize: MainAxisSize.min, @@ -393,7 +451,7 @@ class _NoteFormScreenState extends State { height: 1.5, ), maxLines: null, - minLines: 12, + minLines: MediaQuery.sizeOf(context).height < 750 ? 6 : 10, decoration: const InputDecoration( hintText: 'Scrivi qui la tua nota...', hintStyle: TextStyle(color: Colors.black38), @@ -478,10 +536,6 @@ class _NoteFormScreenState extends State { ), ], - const SizedBox(height: 24), - const Divider(color: Colors.black12), - const SizedBox(height: 24), - // --- ALLEGATI --- // SharedAttachmentsSection( // parentType: AttachmentParentType.note, @@ -493,6 +547,9 @@ class _NoteFormScreenState extends State { ), ), ), - ); + ), + ], +), +); } } diff --git a/lib/features/operations/blocs/operation_form_cubit.dart b/lib/features/operations/blocs/operation_form_cubit.dart index 08ea504..5562c51 100644 --- a/lib/features/operations/blocs/operation_form_cubit.dart +++ b/lib/features/operations/blocs/operation_form_cubit.dart @@ -50,7 +50,6 @@ class OperationFormCubit extends Cubit { status: OperationFormStatus.ready, isNew: false, hasUnsavedChanges: false, - lastSavedAt: DateTime.now(), ), ); _startPeriodicTimer(); @@ -64,7 +63,6 @@ class OperationFormCubit extends Cubit { status: OperationFormStatus.ready, isNew: false, hasUnsavedChanges: false, - lastSavedAt: DateTime.now(), ), ); _startPeriodicTimer(); @@ -93,7 +91,6 @@ class OperationFormCubit extends Cubit { status: OperationFormStatus.ready, isNew: true, hasUnsavedChanges: false, - lastSavedAt: DateTime.now(), ), ); _startPeriodicTimer(); @@ -139,7 +136,8 @@ class OperationFormCubit extends Cubit { emit(state.copyWith(isAutoSaving: true, autoSaveError: null)); try { - OperationModel operationToSave = state.operation; + final snapshotBeforeSave = state.operation; + OperationModel operationToSave = snapshotBeforeSave; if (operationToSave.reference.isEmpty) { if (operationToSave.customer != null && operationToSave.customer!.phoneNumber.isNotEmpty) { @@ -150,16 +148,19 @@ class OperationFormCubit extends Cubit { } final savedOperation = await _repository.updateOperation(operationToSave); + final savedTimestamp = savedOperation.updatedAt ?? DateTime.now(); - final bool hasNewChanges = state.operation != operationToSave; + final bool hasNewChanges = state.operation != snapshotBeforeSave; emit( state.copyWith( isAutoSaving: false, hasUnsavedChanges: hasNewChanges, - lastSavedAt: DateTime.now(), + lastSavedAt: savedTimestamp, autoSaveError: null, operation: state.operation.copyWith( + createdAt: savedOperation.createdAt, + updatedAt: savedTimestamp, details: savedOperation.details, ), ), @@ -218,7 +219,7 @@ class OperationFormCubit extends Cubit { operation: savedOperation, isNew: false, hasUnsavedChanges: false, - lastSavedAt: DateTime.now(), + lastSavedAt: savedOperation.updatedAt ?? DateTime.now(), ), ); } catch (e) { diff --git a/lib/features/operations/data/operations_repository.dart b/lib/features/operations/data/operations_repository.dart index 23d2ce8..6184d41 100644 --- a/lib/features/operations/data/operations_repository.dart +++ b/lib/features/operations/data/operations_repository.dart @@ -257,10 +257,22 @@ class OperationsRepository { Future updateOperation(OperationModel operation) async { try { - await _supabase + final updatedRow = await _supabase .from(Tables.operations) .update(operation.toMap()) - .eq('id', operation.id!); + .eq('id', operation.id!) + .select() + .maybeSingle(); + + final DateTime resolvedUpdatedAt = updatedRow?['updated_at'] != null + ? DateTime.parse(updatedRow!['updated_at'] as String).toLocal() + : DateTime.now(); + + final DateTime? resolvedCreatedAt = + operation.createdAt ?? + (updatedRow?['created_at'] != null + ? DateTime.parse(updatedRow!['created_at'] as String).toLocal() + : null); final updatedDetails = []; for (OperationDetailModel detail in operation.details) { @@ -297,7 +309,11 @@ class OperationsRepository { } notifyOperationsChanged(); - return operation.copyWith(details: updatedDetails); + return operation.copyWith( + createdAt: resolvedCreatedAt, + updatedAt: resolvedUpdatedAt, + details: updatedDetails, + ); } catch (e) { debugPrint('ERRORE SALVATAGGIO OPERAZIONE: $e'); throw Exception('Errore nel salvataggio dell\'operazione: $e'); diff --git a/lib/features/operations/models/operation_model.dart b/lib/features/operations/models/operation_model.dart index 3301781..3ae5f24 100644 --- a/lib/features/operations/models/operation_model.dart +++ b/lib/features/operations/models/operation_model.dart @@ -28,6 +28,7 @@ enum OperationStatus { class OperationModel extends Equatable { final String? id; final DateTime? createdAt; + final DateTime? updatedAt; final String note; final bool showInDashboard; final String companyId; @@ -50,6 +51,7 @@ class OperationModel extends Equatable { const OperationModel({ this.id, this.createdAt, + this.updatedAt, this.note = '', this.showInDashboard = true, required this.companyId, @@ -69,6 +71,7 @@ class OperationModel extends Equatable { OperationModel copyWith({ String? id, DateTime? createdAt, + DateTime? updatedAt, String? note, bool? showInDashboard, String? companyId, @@ -86,6 +89,7 @@ class OperationModel extends Equatable { }) => OperationModel( id: id ?? this.id, createdAt: createdAt ?? this.createdAt, + updatedAt: updatedAt ?? this.updatedAt, note: note ?? this.note, showInDashboard: showInDashboard ?? this.showInDashboard, companyId: companyId ?? this.companyId, @@ -106,6 +110,7 @@ class OperationModel extends Equatable { List get props => [ id, createdAt, + updatedAt, note, showInDashboard, companyId, @@ -126,6 +131,7 @@ class OperationModel extends Equatable { return OperationModel( id: null, createdAt: null, + updatedAt: null, showInDashboard: false, companyId: '', details: const [], @@ -136,7 +142,10 @@ class OperationModel extends Equatable { return OperationModel( id: map['id'] as String?, createdAt: map['created_at'] != null - ? DateTime.parse(map['created_at']) + ? DateTime.parse(map['created_at'] as String).toLocal() + : null, + updatedAt: map['updated_at'] != null + ? DateTime.parse(map['updated_at'] as String).toLocal() : null, note: map['note'] as String? ?? '', showInDashboard: map['show_in_dashboard'] as bool? ?? true, diff --git a/lib/features/operations/ui/operation_form_screen.dart b/lib/features/operations/ui/operation_form_screen.dart index 81964f3..1e2aaf3 100644 --- a/lib/features/operations/ui/operation_form_screen.dart +++ b/lib/features/operations/ui/operation_form_screen.dart @@ -657,13 +657,71 @@ class _OperationFormScreenState extends State ); } + Widget _buildTimestampsBar(OperationFormState state) { + final createdAt = state.operation.createdAt; + final updatedAt = + state.lastSavedAt ?? state.operation.updatedAt ?? createdAt; + + if (createdAt == null && updatedAt == null) { + return const SizedBox.shrink(); + } + + final dateTimeFormat = DateFormat('dd/MM/yyyy HH:mm'); + final fullFormat = DateFormat('dd/MM/yyyy HH:mm:ss'); + final mutedColor = Theme.of( + context, + ).colorScheme.onSurfaceVariant.withValues(alpha: 0.8); + + return Padding( + padding: const EdgeInsets.only(left: 4, right: 4, bottom: 12), + child: Wrap( + spacing: 20, + runSpacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + if (createdAt != null) + Tooltip( + message: 'Creata il ${fullFormat.format(createdAt)}', + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.schedule_rounded, size: 14, color: mutedColor), + const SizedBox(width: 5), + Text( + 'Creata: ${dateTimeFormat.format(createdAt)}', + style: TextStyle(fontSize: 12, color: mutedColor), + ), + ], + ), + ), + if (updatedAt != null) + Tooltip( + message: 'Ultima modifica il ${fullFormat.format(updatedAt)}', + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.history_rounded, size: 15, color: mutedColor), + const SizedBox(width: 5), + Text( + 'Ultima modifica: ${dateTimeFormat.format(updatedAt)}', + style: TextStyle(fontSize: 12, color: mutedColor), + ), + ], + ), + ), + ], + ), + ); + } + Widget _buildResponsiveLayout( bool isUltraWide, bool isDesktop, OperationFormState state, ) { + final Widget cardsLayout; if (isUltraWide) { - return Column( + cardsLayout = Column( children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, @@ -679,7 +737,7 @@ class _OperationFormScreenState extends State ], ); } else if (isDesktop) { - return Row( + cardsLayout = Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( @@ -694,7 +752,7 @@ class _OperationFormScreenState extends State ], ); } else { - return Column( + cardsLayout = Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ _cardAnagrafica(state), @@ -704,6 +762,14 @@ class _OperationFormScreenState extends State ], ); } + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildTimestampsBar(state), + cardsLayout, + ], + ); } // --- LE CARD MODULARIZZATE E COLORATE --- diff --git a/pubspec.yaml b/pubspec.yaml index c86c20a..8d4ed5f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: flux description: "Gestione attività negozio di telefonia" publish_to: 'none' -version: 2.5.8+92 +version: 2.6.0+94 environment: sdk: ^3.11.3 diff --git a/test/features/notes/ui/note_form_screen_test.dart b/test/features/notes/ui/note_form_screen_test.dart new file mode 100644 index 0000000..bb5354c --- /dev/null +++ b/test/features/notes/ui/note_form_screen_test.dart @@ -0,0 +1,110 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flux/features/notes/blocs/notes_cubit.dart'; +import 'package:flux/features/notes/models/note_model.dart'; +import 'package:flux/features/notes/ui/notes_form_screen.dart'; + +class _FakeNotesCubit extends Cubit implements NotesCubit { + final List savedNotes = []; + final List deletedNoteIds = []; + + _FakeNotesCubit() : super(NotesState()); + + @override + String? get companyId => 'comp-1'; + + @override + String? get staffId => 'staff-1'; + + @override + void startListening() {} + + @override + void stopListening() {} + + @override + Future saveNote(NoteModel note) async { + savedNotes.add(note); + } + + @override + Future deleteNote(String noteId) async { + deletedNoteIds.add(noteId); + } +} + +void main() { + group('NoteFormScreen outside click behavior', () { + testWidgets( + 'clicking inside Post-it keeps note open, clicking outside saves and closes', + (tester) async { + tester.view.physicalSize = const Size(1200, 900); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + final fakeCubit = _FakeNotesCubit(); + final note = NoteModel( + id: 'note-1', + createdBy: 'staff-1', + companyId: 'comp-1', + title: 'Titolo iniziale', + content: 'Contenuto', + collaboratorIds: const [], + ); + + await tester.pumpWidget( + BlocProvider.value( + value: fakeCubit, + child: MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: Center( + child: ElevatedButton( + onPressed: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => NoteFormScreen(note: note), + ), + ); + }, + child: const Text('Apri Nota'), + ), + ), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Apri Nota')); + await tester.pumpAndSettle(); + + expect(find.byType(NoteFormScreen), findsOneWidget); + + // 1. Tap dentro il Post-it: la nota resta aperta + await tester.tap(find.text('Condividi con tutti')); + await tester.pumpAndSettle(); + expect(find.byType(NoteFormScreen), findsOneWidget); + + // 2. Digitiamo nel titolo e clicchiamo subito fuori (senza aspettare i 500ms del debouncer) + await tester.enterText( + find.widgetWithText(TextFormField, 'Titolo iniziale'), + 'Titolo aggiornato', + ); + + // Tap a sinistra fuori dal Post-it centrato (maxWidth 680 su schermo 1200 -> x=50 è fuori) + await tester.tapAt(const Offset(50, 450)); + await tester.pumpAndSettle(); + + // La nota si è chiusa e ha salvato immediatamente le modifiche pendenti + expect(find.byType(NoteFormScreen), findsNothing); + expect(fakeCubit.savedNotes.last.title, 'Titolo aggiornato'); + expect(fakeCubit.deletedNoteIds, isEmpty); + }, + ); + }); +} diff --git a/test/features/operations/models/operation_model_test.dart b/test/features/operations/models/operation_model_test.dart new file mode 100644 index 0000000..a126f13 --- /dev/null +++ b/test/features/operations/models/operation_model_test.dart @@ -0,0 +1,61 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:flux/features/operations/models/operation_model.dart'; + +void main() { + group('OperationModel timestamps', () { + test('empty() initializes createdAt and updatedAt to null', () { + final empty = OperationModel.empty(); + expect(empty.createdAt, isNull); + expect(empty.updatedAt, isNull); + }); + + test('fromMap parses created_at and updated_at into local DateTime', () { + final model = OperationModel.fromMap({ + 'id': 'op-1', + 'company_id': 'comp-1', + 'store_id': 'store-1', + 'status': 'success', + 'created_at': '2026-11-29T09:15:00.000Z', + 'updated_at': '2026-11-29T12:30:00.000Z', + }); + + expect(model.createdAt, isNotNull); + expect(model.updatedAt, isNotNull); + expect(model.createdAt!.isUtc, isFalse); + expect(model.updatedAt!.isUtc, isFalse); + expect(model.createdAt!.toUtc(), DateTime.utc(2026, 11, 29, 9, 15)); + expect(model.updatedAt!.toUtc(), DateTime.utc(2026, 11, 29, 12, 30)); + }); + + test('fromMap handles missing updated_at gracefully', () { + final model = OperationModel.fromMap({ + 'id': 'op-2', + 'company_id': 'comp-1', + 'store_id': 'store-1', + 'status': 'draft', + 'created_at': '2026-11-29T09:15:00.000Z', + }); + + expect(model.createdAt, isNotNull); + expect(model.updatedAt, isNull); + }); + + test('copyWith and Equatable include updatedAt', () { + final t1 = DateTime(2026, 11, 29, 10, 0); + final t2 = DateTime(2026, 11, 29, 13, 30); + + final a = OperationModel( + id: 'op-1', + companyId: 'comp-1', + createdAt: t1, + updatedAt: t1, + ); + final b = a.copyWith(updatedAt: t2); + + expect(b.createdAt, t1); + expect(b.updatedAt, t2); + expect(a == b, isFalse); + expect(b, a.copyWith(updatedAt: t2)); + }); + }); +}