From 524da71a45e53dd20c18d36d0674c0bae80dba8d Mon Sep 17 00:00:00 2001 From: Mark M2 Macbook Date: Fri, 18 Sep 2026 11:41:26 +0200 Subject: [PATCH] gestione obiettivi --- .gitea/workflows/release.yaml | 44 +- lib/core/routes/app_router.dart | 8 + .../dashboard_target_progress_cubit.dart | 155 +++++ .../dashboard_target_progress_state.dart | 81 +++ .../ui/dashboard_target_hero_card.dart | 656 ++++++++++++++++++ lib/features/home/ui/home_screen.dart | 99 ++- .../operations/ui/operation_form_screen.dart | 40 +- .../tickets/ui/ticket_form_screen.dart | 22 +- pubspec.yaml | 2 +- 9 files changed, 1058 insertions(+), 49 deletions(-) create mode 100644 lib/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart create mode 100644 lib/features/home/dashboard_target_progress/blocs/dashboard_target_progress_state.dart create mode 100644 lib/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart diff --git a/.gitea/workflows/release.yaml b/.gitea/workflows/release.yaml index e5eb31c..185e1d3 100644 --- a/.gitea/workflows/release.yaml +++ b/.gitea/workflows/release.yaml @@ -118,7 +118,7 @@ jobs: # JOB 4: LINUX APPIMAGE (Gira sul tuo PC Fedora / Linux Runner) # ----------------------------------------------------------------- build-linux: - runs-on: cross-runner # <--- Etichetta del tuo runner Linux / Fedora + runs-on: linux-runner # <--- Etichetta del tuo runner Linux / Fedora in ufficio steps: - name: Checkout del codice uses: actions/checkout@v3 @@ -175,4 +175,44 @@ jobs: - name: Aggiorna Link Linux su Supabase run: | - curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.linux" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-x86_64.AppImage\"}" \ No newline at end of file + curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.linux" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-x86_64.AppImage\"}" + + # ----------------------------------------------------------------- + # JOB 5: MACOS (Gira sul tuo Mac / macos-runner) + # ----------------------------------------------------------------- + build-macos: + runs-on: macos-runner + steps: + - name: Checkout del codice + uses: actions/checkout@v3 + + - name: Crea file .env + run: | + cat << 'EOF' > .env + ${{ secrets.ENV_FILE_CONTENT }} + EOF + + - name: Build Flutter macOS + run: flutter build macos --release + + - name: Genera DMG e ZIP macOS + run: | + # Crea DMG dell'applicazione + hdiutil create -volname "Flux" -srcfolder "build/macos/Build/Products/Release/flux.app" -ov -format UDZO "Flux-macOS.dmg" + + # Crea anche archivio ZIP di backup + cd build/macos/Build/Products/Release + zip -r -y ../../../../Flux-macOS.zip "flux.app" + cd - + + - name: Upload macOS Assets + uses: https://gitea.com/actions/release-action@main + with: + files: | + Flux-macOS.dmg + Flux-macOS.zip + api_key: ${{ secrets.MYRELEASE_TOKEN }} + + - name: Aggiorna Link macOS su Supabase + run: | + curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.macos" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-macOS.dmg\"}" \ No newline at end of file diff --git a/lib/core/routes/app_router.dart b/lib/core/routes/app_router.dart index 8868f6f..877caa0 100644 --- a/lib/core/routes/app_router.dart +++ b/lib/core/routes/app_router.dart @@ -21,6 +21,7 @@ import 'package:flux/features/customers/ui/customers_list_screen.dart'; import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart'; import 'package:flux/features/home/dashboard_store_operation_list/bloc/dashboard_store_operation_list_cubit.dart'; import 'package:flux/features/home/dashboard_store_ticket_list/blocs/dashboard_store_ticket_list_cubit.dart'; +import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart'; import 'package:flux/features/home/dashboard_task_list/blocs/dashboard_task_list_cubit.dart'; import 'package:flux/features/home/ui/home_screen.dart'; import 'package:flux/features/master_data/master_data_hub_content.dart'; @@ -189,6 +190,13 @@ class AppRouter { staffId: sessionCubit.state.currentStaffMember?.id, ), ), + BlocProvider( + create: (context) => DashboardTargetProgressCubit( + companyId: sessionCubit.state.company?.id, + storeId: sessionCubit.state.currentStore?.id, + staffId: sessionCubit.state.currentStaffMember?.id, + ), + ), ], child: const HomeScreen(), ); diff --git a/lib/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart b/lib/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart new file mode 100644 index 0000000..aa154f3 --- /dev/null +++ b/lib/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart @@ -0,0 +1,155 @@ +import 'dart:async'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/features/operations/data/operations_repository.dart'; +import 'package:flux/features/targets/data/target_progress_service.dart'; +import 'package:flux/features/targets/data/targets_repository.dart'; +import 'package:flux/service_locator.dart'; +import 'dashboard_target_progress_state.dart'; + +class DashboardTargetProgressCubit extends Cubit { + final TargetsRepository _targetsRepository = sl(); + final OperationsRepository _operationsRepository = sl(); + final TargetProgressService _progressService = sl(); + + String? companyId; + String? storeId; + String? staffId; + + StreamSubscription? _operationsSubscription; + StreamSubscription? _targetsSubscription; + Timer? _pollingTimer; + + DashboardTargetProgressCubit({ + this.companyId, + this.storeId, + this.staffId, + }) : super( + DashboardTargetProgressState( + currentStaffId: staffId, + ), + ); + + void updateContext({ + String? newCompanyId, + String? newStoreId, + String? newStaffId, + }) { + bool changed = false; + if (newCompanyId != null && newCompanyId != companyId) { + companyId = newCompanyId; + changed = true; + } + if (newStoreId != null && newStoreId != storeId) { + storeId = newStoreId; + changed = true; + } + if (newStaffId != null && newStaffId != staffId) { + staffId = newStaffId; + changed = true; + } + + if (changed) { + emit(state.copyWith(currentStaffId: staffId)); + refresh(); + } + } + + void startListening() { + emit(state.copyWith(status: DashboardTargetProgressStatus.loading)); + stopListening(); + + _loadProgressSilently(); + + // 1. Ascolto modifiche delle operazioni in real-time + _operationsSubscription = + _operationsRepository.onOperationsChanged.listen((_) { + _loadProgressSilently(); + }); + + // 2. Ascolto modifiche ai target + _targetsSubscription = _targetsRepository.onTargetsChanged.listen((_) { + _loadProgressSilently(); + }); + + // 3. Polling leggero ogni 45 secondi + _pollingTimer = Timer.periodic(const Duration(seconds: 45), (_) { + _loadProgressSilently(); + }); + } + + void stopListening() { + _operationsSubscription?.cancel(); + _operationsSubscription = null; + _targetsSubscription?.cancel(); + _targetsSubscription = null; + _pollingTimer?.cancel(); + _pollingTimer = null; + } + + void refresh() { + _loadProgressSilently(); + } + + Future _loadProgressSilently() async { + if (companyId == null || storeId == null) { + if (!isClosed) { + emit(state.copyWith(status: DashboardTargetProgressStatus.noTarget)); + } + return; + } + + try { + final now = DateTime.now(); + final target = await _targetsRepository.getStoreTargetForMonth( + companyId: companyId!, + storeId: storeId!, + month: now, + ); + + if (isClosed) return; + + if (target == null) { + emit( + state.copyWith( + status: DashboardTargetProgressStatus.noTarget, + target: null, + progress: null, + currentStaffId: staffId, + ), + ); + return; + } + + final progress = await _progressService.calculateTargetProgress( + target: target, + now: now, + ); + + if (isClosed) return; + + emit( + state.copyWith( + status: DashboardTargetProgressStatus.success, + target: target, + progress: progress, + currentStaffId: staffId, + errorMessage: null, + ), + ); + } catch (e) { + if (isClosed) return; + emit( + state.copyWith( + status: DashboardTargetProgressStatus.failure, + errorMessage: e.toString(), + ), + ); + } + } + + @override + Future close() { + stopListening(); + return super.close(); + } +} diff --git a/lib/features/home/dashboard_target_progress/blocs/dashboard_target_progress_state.dart b/lib/features/home/dashboard_target_progress/blocs/dashboard_target_progress_state.dart new file mode 100644 index 0000000..0781542 --- /dev/null +++ b/lib/features/home/dashboard_target_progress/blocs/dashboard_target_progress_state.dart @@ -0,0 +1,81 @@ +import 'package:equatable/equatable.dart'; +import 'package:flux/features/targets/models/target_model.dart'; +import 'package:flux/features/targets/models/target_progress_model.dart'; + +enum DashboardTargetProgressStatus { + initial, + loading, + success, + noTarget, + failure, +} + +class DashboardTargetProgressState extends Equatable { + final DashboardTargetProgressStatus status; + final TargetModel? target; + final TargetProgressModel? progress; + final String? currentStaffId; + final String? errorMessage; + + const DashboardTargetProgressState({ + this.status = DashboardTargetProgressStatus.initial, + this.target, + this.progress, + this.currentStaffId, + this.errorMessage, + }); + + DashboardTargetProgressState copyWith({ + DashboardTargetProgressStatus? status, + TargetModel? target, + TargetProgressModel? progress, + String? currentStaffId, + String? errorMessage, + }) { + return DashboardTargetProgressState( + status: status ?? this.status, + target: target ?? this.target, + progress: progress ?? this.progress, + currentStaffId: currentStaffId ?? this.currentStaffId, + errorMessage: errorMessage, + ); + } + + /// Avanzamento specifico del membro dello staff correntemente connesso + TargetProgressModel? get currentStaffProgress { + final curProgress = progress; + final staffId = currentStaffId; + if (curProgress == null || staffId == null) return null; + return curProgress.staffProgress[staffId]; + } + + /// True se lo staff connesso ha almeno un target individuale attivo impostato + bool get hasStaffTargets { + final sp = currentStaffProgress; + if (sp == null) return false; + return sp.categories.values.any((c) => c.hasTarget); + } + + /// Lista delle categorie con target attivo per l'addetto connesso + List get activeStaffCategories { + final sp = currentStaffProgress; + if (sp == null) return const []; + return sp.categories.values.where((c) => c.hasTarget).toList(); + } + + /// Lista delle categorie con target attivo per il negozio + List get activeStoreCategories { + final curProgress = progress; + if (curProgress == null) return const []; + return curProgress.categories.values.where((c) => c.hasTarget).toList(); + } + + @override + List get props => [ + status, + target, + progress, + currentStaffId, + errorMessage, + ]; +} 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 new file mode 100644 index 0000000..18b97b5 --- /dev/null +++ b/lib/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart @@ -0,0 +1,656 @@ +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/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart'; +import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_state.dart'; +import 'package:flux/features/targets/models/target_progress_model.dart'; +import 'package:go_router/go_router.dart'; + +class DashboardTargetHeroCard extends StatelessWidget { + const DashboardTargetHeroCard({super.key}); + + @override + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, state) { + final theme = Theme.of(context); + + if (state.status == DashboardTargetProgressStatus.loading || + state.status == DashboardTargetProgressStatus.initial) { + return _buildLoadingCard(theme); + } + + if (state.status == DashboardTargetProgressStatus.noTarget || + state.target == null || + state.progress == null) { + return _buildNoTargetCard(context, theme); + } + + return _buildHeroContent(context, theme, state); + }, + ); + } + + Widget _buildLoadingCard(ThemeData theme) { + return Container( + height: 160, + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(20), + border: Border.all(color: theme.dividerColor.withValues(alpha: 0.2)), + ), + child: const Center( + child: SizedBox( + width: 28, + height: 28, + child: CircularProgressIndicator(strokeWidth: 2.5), + ), + ), + ); + } + + Widget _buildNoTargetCard(BuildContext context, ThemeData theme) { + final currentStore = context.watch().state.currentStore; + final now = DateTime.now(); + final months = [ + 'Gennaio', + 'Febbraio', + 'Marzo', + 'Aprile', + 'Maggio', + 'Giugno', + 'Luglio', + 'Agosto', + 'Settembre', + 'Ottobre', + 'Novembre', + 'Dicembre' + ]; + 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), + ), + 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), + ), + ), + ), + ], + ), + ); + } + + Widget _buildHeroContent( + BuildContext context, + ThemeData theme, + DashboardTargetProgressState state, + ) { + final progress = state.progress!; + final target = state.target!; + final staffMember = + context.watch().state.currentStaffMember; + final staffName = staffMember?.name ?? 'Ospite'; + + final hasStaffTargets = state.hasStaffTargets; + final displayCategories = hasStaffTargets + ? state.activeStaffCategories + : state.activeStoreCategories; + + final remainingDays = progress.remainingWorkingDays; + + return Container( + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: theme.colorScheme.primary.withValues(alpha: 0.25), + width: 1.5, + ), + boxShadow: [ + BoxShadow( + color: theme.colorScheme.primary.withValues(alpha: 0.06), + blurRadius: 20, + offset: const Offset(0, 6), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // ========================================== + // 1. HEADER DELLA CARD (TITOLO & GIORNI) + // ========================================== + Padding( + padding: const EdgeInsets.fromLTRB(20, 18, 20, 14), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [ + theme.colorScheme.primary, + theme.colorScheme.primary.withValues(alpha: 0.8), + ], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: theme.colorScheme.primary.withValues(alpha: 0.25), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.trending_up_rounded, + color: Colors.white, + size: 22, + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Flexible( + child: Text( + hasStaffTargets + ? 'IL TUO RITMO PER OGGI' + : 'RITMO GIORNALIERO NEGOZIO', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w800, + letterSpacing: 0.8, + color: theme.colorScheme.primary, + ), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 2, + ), + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer + .withValues(alpha: 0.35), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + remainingDays > 1 + ? 'Mancano $remainingDays gg' + : (remainingDays == 1 + ? 'Ultimo giorno!' + : 'Mese concluso'), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: theme.colorScheme.primary, + ), + ), + ), + ], + ), + const SizedBox(height: 3), + Text( + hasStaffTargets + ? 'Cosa portare a casa oggi, $staffName' + : 'Obiettivi di ${target.store?.name ?? "Negozio"} per oggi', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w900, + fontSize: 17, + ), + ), + ], + ), + ), + // Tasto rapido dettaglio + TextButton.icon( + onPressed: () => context.pushNamed( + Routes.targetDetail, + extra: target, + ), + icon: const Icon(Icons.analytics_outlined, size: 18), + label: const Text('Dettagli'), + style: TextButton.styleFrom( + visualDensity: VisualDensity.compact, + foregroundColor: theme.colorScheme.primary, + textStyle: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + ], + ), + ), + + // ========================================== + // 2. FOCUS METRICHE: MEDIE RICHIESTE PER OGGI + // ========================================== + if (displayCategories.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), + child: Text( + 'Nessun obiettivo attivo configurato per questo mese.', + style: TextStyle( + color: theme.colorScheme.onSurfaceVariant, + fontSize: 13, + ), + ), + ) + else + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: LayoutBuilder( + builder: (context, constraints) { + final isWide = constraints.maxWidth > 700; + + return GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: displayCategories.length, + gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: isWide ? 260 : 200, + mainAxisExtent: 154, + crossAxisSpacing: 10, + mainAxisSpacing: 10, + ), + itemBuilder: (context, index) { + final category = displayCategories[index]; + return _buildCategoryDailyPacingCard(theme, category); + }, + ); + }, + ), + ), + + const SizedBox(height: 14), + + // ========================================== + // 3. SEZIONE INFERIORE: RIEPILOGO NEGOZIO + // ========================================== + Container( + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest + .withValues(alpha: 0.35), + borderRadius: const BorderRadius.vertical( + bottom: Radius.circular(19), + ), + border: Border( + top: BorderSide( + color: theme.dividerColor.withValues(alpha: 0.2), + ), + ), + ), + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), + child: Row( + children: [ + Icon( + Icons.storefront_outlined, + size: 18, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 8), + Text( + 'Negozio:', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w800, + color: theme.colorScheme.primary, + letterSpacing: 0.5, + ), + ), + const SizedBox(width: 10), + // Badge sintetici del negozio + _buildMiniBadge( + label: '${progress.countAchieved}/${progress.countTotalActive} Presi', + color: const Color(0xFF15803D), + bgColor: const Color(0xFFDCFCE7), + ), + const SizedBox(width: 6), + _buildMiniBadge( + label: '${progress.countInLineOnly} In linea', + color: const Color(0xFF0D9488), + bgColor: const Color(0xFFCCFBF1), + ), + if (progress.countBehind > 0) ...[ + const SizedBox(width: 6), + _buildMiniBadge( + label: '${progress.countBehind} Sotto ritmo', + color: const Color(0xFFDC2626), + bgColor: const Color(0xFFFEE2E2), + ), + ], + const Spacer(), + InkWell( + onTap: () => context.pushNamed( + Routes.targetDetail, + extra: target, + ), + borderRadius: BorderRadius.circular(6), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Apri analisi completa', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: theme.colorScheme.primary, + ), + ), + const SizedBox(width: 4), + Icon( + Icons.arrow_forward_rounded, + size: 14, + color: theme.colorScheme.primary, + ), + ], + ), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildCategoryDailyPacingCard( + ThemeData theme, + CategoryProgress category, + ) { + final pacingTheme = PacingTheme.of(category.status); + final isAchieved = category.isAchieved; + final hasS2 = category.targetS2 > 0; + + return Container( + padding: const EdgeInsets.all(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: 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: 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 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, + ), + ), + 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( + 'Soglia minima centrata!', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ) + 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 (hasS2) + Text( + 'Sfida S2: ${category.requiredDailyRateS2.toStringAsFixed(1)} / gg', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: theme.colorScheme.onSurfaceVariant, + ), + ) + else + Text( + 'per Minimo (${category.targetS1})', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + + const Spacer(), + + // Footer: Avanzamento e ritmo attuale + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Fatti: ${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, + ), + ), + ], + ), + ); + } + + Widget _buildMiniBadge({ + required String label, + required Color color, + required Color bgColor, + }) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3), + decoration: BoxDecoration( + color: bgColor, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + label, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: color, + ), + ), + ); + } +} diff --git a/lib/features/home/ui/home_screen.dart b/lib/features/home/ui/home_screen.dart index dfddd2d..a58ffb3 100644 --- a/lib/features/home/ui/home_screen.dart +++ b/lib/features/home/ui/home_screen.dart @@ -19,6 +19,8 @@ import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; import 'package:flux/features/notes/data/notes_repository.dart'; import 'package:flux/features/notes/models/note_model.dart'; import 'package:flux/features/home/dashboard_note_list/ui/dashboard_note_list_card.dart'; +import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart'; +import 'package:flux/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart'; import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; @@ -73,6 +75,7 @@ class _HomeScreenState extends State { context.read().stopListening(); context.read().stopListening(); context.read().stopListening(); + context.read().stopListening(); } void _startListeners() { @@ -80,6 +83,7 @@ class _HomeScreenState extends State { context.read().startListening(); context.read().startListening(); context.read().startListening(); + context.read().startListening(); } @override @@ -112,47 +116,68 @@ class _HomeScreenState extends State { // 2. CORPO DELLA DASHBOARD (Scrollabile) // ========================================== Expanded( - child: CustomScrollView( - slivers: [ - // --- QUICK ACTIONS: AZIONI RAPIDE --- - SliverToBoxAdapter( - child: Padding( + 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, + ); + }, + child: CustomScrollView( + slivers: [ + // --- HERO TARGET DEL GIORNO (TUTTA LARGHEZZA IN CIMA) --- + const SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0), + child: DashboardTargetHeroCard(), + ), + ), + + // --- QUICK ACTIONS: AZIONI RAPIDE --- + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0), + child: _buildQuickActions(context), + ), + ), + + const SliverToBoxAdapter(child: SizedBox(height: 32)), + + // --- I WIDGET DELLA DASHBOARD (Responsive Grid) --- + SliverPadding( padding: const EdgeInsets.symmetric(horizontal: 24.0), - child: _buildQuickActions(context), - ), - ), - - const SliverToBoxAdapter(child: SizedBox(height: 32)), - - // --- 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, + sliver: SliverGrid( + gridDelegate: + const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 500, + mainAxisSpacing: 16, + crossAxisSpacing: 16, + childAspectRatio: 1.3, + ), + delegate: SliverChildListDelegate([ + DashboardStoreOperationListCard(), + DashboardStoreTicketListCard(), + _buildDashboardWidget( + title: context.l10n.homeExpiringContracts, + icon: Icons.assignment_late_outlined, + color: Colors.orange, + context: context, ), - delegate: SliverChildListDelegate([ - DashboardStoreOperationListCard(), - DashboardStoreTicketListCard(), - _buildDashboardWidget( - title: context.l10n.homeExpiringContracts, - icon: Icons.assignment_late_outlined, - color: Colors.orange, - context: context, - ), - DashboardNoteListCard(), - DashboardTaskListCard(), - ]), + DashboardNoteListCard(), + DashboardTaskListCard(), + ]), + ), ), - ), - // Spazio finale per non far attaccare l'ultima card al fondo - const SliverToBoxAdapter(child: SizedBox(height: 40)), - ], + // Spazio finale per non far attaccare l'ultima card al fondo + const SliverToBoxAdapter(child: SizedBox(height: 40)), + ], + ), ), ), ], diff --git a/lib/features/operations/ui/operation_form_screen.dart b/lib/features/operations/ui/operation_form_screen.dart index 9cbecc5..38a9008 100644 --- a/lib/features/operations/ui/operation_form_screen.dart +++ b/lib/features/operations/ui/operation_form_screen.dart @@ -83,9 +83,17 @@ class _OperationFormScreenState extends State { void _saveOperation({ required OperationStatus targetStatus, required bool isClosingIntent, - }) { + }) async { if (!_formKey.currentState!.validate()) return; + if (isClosingIntent) { + final details = context.read().state.operation.details; + if (details.isEmpty) { + final shouldProceed = await _showEmptyDetailsWarningDialog(context); + if (shouldProceed != true || !mounted) return; + } + } + _isClosingIntent = isClosingIntent; _flushControllersToCubit(); @@ -95,6 +103,36 @@ class _OperationFormScreenState extends State { ); } + Future _showEmptyDetailsWarningDialog(BuildContext context) { + return showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + title: const Row( + children: [ + Icon(Icons.warning_amber_rounded, color: Colors.orange), + SizedBox(width: 8), + Text('Dettagli operazione vuoti'), + ], + ), + content: const Text( + 'Non hai inserito alcun dettaglio per questa operazione.\n\nVuoi procedere comunque a salvare e uscire, oppure annullare per aggiungerli?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: const Text('Annulla'), + ), + ElevatedButton( + onPressed: () => Navigator.of(dialogContext).pop(true), + child: const Text('Salva e chiudi comunque'), + ), + ], + ); + }, + ); + } + Future<_UnsavedChangesAction?> _showUnsavedChangesDialog( BuildContext context, ) { diff --git a/lib/features/tickets/ui/ticket_form_screen.dart b/lib/features/tickets/ui/ticket_form_screen.dart index a8ec338..657dd60 100644 --- a/lib/features/tickets/ui/ticket_form_screen.dart +++ b/lib/features/tickets/ui/ticket_form_screen.dart @@ -4,9 +4,9 @@ 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/widgets/shared_forms/attachments_section.dart'; import 'package:flux/core/widgets/shared_forms/customer_section.dart'; import 'package:flux/core/widgets/shared_forms/model_section.dart'; -import 'package:flux/core/widgets/shared_forms/shared_files_section.dart'; import 'package:flux/core/widgets/staff_selector_modal.dart'; import 'package:flux/features/attachments/blocs/attachments_bloc.dart'; import 'package:flux/features/company/models/company_model.dart'; @@ -385,6 +385,15 @@ class _TicketFormScreenState extends State { _syncTextControllers(state.ticket); } + if (state.ticket.id != null && state.ticket.id!.isNotEmpty) { + final attachmentsBloc = context.read(); + if (attachmentsBloc.state.parentId != state.ticket.id) { + attachmentsBloc.add( + ParentEntitySavedEvent(state.ticket.id!), + ); + } + } + if (state.status == TicketFormStatus.deleted) { Navigator.of(context).pop(); } @@ -1047,15 +1056,12 @@ class _TicketFormScreenState extends State { .updateFields(assignedToId: staff.id, assignedToName: staff.name), ), const Divider(height: 32), - // ECCO LA MAGIA: - SharedFilesSection( - titleNameForUpload: ticket.customer?.name ?? 'Nuovo Ticket', - onGenerateIdForQr: _generateIdForQr, - ), - /* SharedAttachmentsSection( + SharedAttachmentsSection( parentType: AttachmentParentType.ticket, parentId: ticket.id, - ), */ + titleForUpload: ticket.customer?.name ?? 'Nuovo Ticket', + onEnsureEntitySaved: _generateIdForQr, + ), ], ); } diff --git a/pubspec.yaml b/pubspec.yaml index 6a5b848..ed7e633 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: flux description: "Gestione attività negozio di telefonia" publish_to: 'none' -version: 1.3.8+54 +version: 2.0.0+56 environment: sdk: ^3.11.3