From 0cc7c76df9414a9230013628394f59e209a25016 Mon Sep 17 00:00:00 2001 From: Mark M2 Macbook Date: Thu, 15 Oct 2026 11:45:08 +0200 Subject: [PATCH] wow, cropped images e thumbnails --- .../shared_forms/attachments_section.dart | 65 +++- .../attachments/blocs/attachments_bloc.dart | 340 +++++++++++++----- .../attachments/blocs/attachments_events.dart | 17 + .../data/attachments_repository.dart | 108 +++++- .../attachments/models/attachment_model.dart | 63 ++++ .../ui/attachment_viewer_screen.dart | 187 +++++++++- .../customers/ui/customer_detail_screen.dart | 4 +- .../tickets/ui/widgets/ticket_list_card.dart | 5 + lib/service_locator.dart | 12 +- pubspec.yaml | 2 +- .../models/attachment_model_test.dart | 134 +++++++ 11 files changed, 807 insertions(+), 130 deletions(-) create mode 100644 test/features/attachments/models/attachment_model_test.dart diff --git a/lib/core/widgets/shared_forms/attachments_section.dart b/lib/core/widgets/shared_forms/attachments_section.dart index afdc8e5..3743297 100644 --- a/lib/core/widgets/shared_forms/attachments_section.dart +++ b/lib/core/widgets/shared_forms/attachments_section.dart @@ -360,6 +360,11 @@ class _SharedAttachmentsSectionState extends State { DeleteSpecificAttachmentEvent(targetFile), ); }, + onViewModeChanged: (targetFile, newMode) { + operationFilesBloc.add( + UpdateAttachmentViewModeEvent(targetFile, newMode), + ); + }, ), ), ), @@ -406,11 +411,12 @@ class _SharedAttachmentsSectionState extends State { for (final file in selectedFiles) { Uint8List? fileBytes; + final targetPath = file.effectiveStoragePath; if (file.localBytes != null) { fileBytes = file.localBytes; - } else if (file.storagePath != null && file.storagePath!.isNotEmpty) { + } else if (targetPath != null && targetPath.isNotEmpty) { fileBytes = await repository.downloadAttachmentBytes( - storagePath: file.storagePath!, + storagePath: targetPath, bucket: Bucket.documents, ); } @@ -533,11 +539,13 @@ class _SharedAttachmentsSectionState extends State { for (var file in selectedFiles) { Uint8List? fileBytes; + final targetPath = file.effectiveStoragePath; + if (file.localBytes != null) { fileBytes = file.localBytes; - } else if (file.storagePath != null && file.storagePath!.isNotEmpty) { + } else if (targetPath != null && targetPath.isNotEmpty) { fileBytes = await repository.downloadAttachmentBytes( - storagePath: file.storagePath!, + storagePath: targetPath, bucket: Bucket.documents, ); } @@ -676,11 +684,13 @@ class _SharedAttachmentsSectionState extends State { for (var file in selectedFiles) { Uint8List? fileBytes; + final targetPath = file.effectiveStoragePath; + if (file.localBytes != null) { fileBytes = file.localBytes; - } else if (file.storagePath != null && file.storagePath!.isNotEmpty) { + } else if (targetPath != null && targetPath.isNotEmpty) { fileBytes = await repository.downloadAttachmentBytes( - storagePath: file.storagePath!, + storagePath: targetPath, bucket: Bucket.documents, ); } @@ -810,7 +820,17 @@ class _SharedAttachmentsSectionState extends State { Widget build(BuildContext context) { final theme = Theme.of(context); - return BlocBuilder( + return BlocConsumer( + listener: (context, state) { + if (state.status == AttachmentsStatus.failure && state.error != null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(state.error!), + backgroundColor: theme.colorScheme.error, + ), + ); + } + }, builder: (context, state) { final allFiles = state.allFiles; final selectedFiles = state.selectedFiles; @@ -1422,6 +1442,10 @@ class _AttachmentThumbnailState extends State<_AttachmentThumbnail> { bool _isLoading = true; String get _cacheKey { + if (widget.file.thumbnailPath != null && + widget.file.thumbnailPath!.isNotEmpty) { + return 'thumb_${widget.file.thumbnailPath}'; + } return widget.file.id ?? widget.file.storagePath ?? '${widget.file.name}_${widget.file.fileSize}'; @@ -1437,6 +1461,7 @@ class _AttachmentThumbnailState extends State<_AttachmentThumbnail> { void didUpdateWidget(covariant _AttachmentThumbnail oldWidget) { super.didUpdateWidget(oldWidget); if (widget.file.id != oldWidget.file.id || + widget.file.thumbnailPath != oldWidget.file.thumbnailPath || widget.file.storagePath != oldWidget.file.storagePath || widget.file.localBytes != oldWidget.file.localBytes) { _loadThumbnail(); @@ -1457,6 +1482,32 @@ class _AttachmentThumbnailState extends State<_AttachmentThumbnail> { try { final file = widget.file; + + // ⚡ Se il worker sul server ha generato il thumbnail (WebP), lo scarichiamo direttamente! + if (file.thumbnailPath != null && file.thumbnailPath!.isNotEmpty) { + try { + final repository = GetIt.I.get(); + final thumbBytes = await repository.downloadAttachmentBytes( + storagePath: file.thumbnailPath!, + bucket: Bucket.documents, + ); + if (thumbBytes.isNotEmpty) { + _thumbnailCache[key] = thumbBytes; + if (mounted) { + setState(() { + _bytes = thumbBytes; + _isLoading = false; + }); + } + return; + } + } catch (e) { + debugPrint( + 'Impossibile scaricare thumbnail da ${file.thumbnailPath}, procedo con fallback: $e', + ); + } + } + Uint8List? sourceBytes; if (file.localBytes != null) { diff --git a/lib/features/attachments/blocs/attachments_bloc.dart b/lib/features/attachments/blocs/attachments_bloc.dart index fa3ea88..e32a0f3 100644 --- a/lib/features/attachments/blocs/attachments_bloc.dart +++ b/lib/features/attachments/blocs/attachments_bloc.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'dart:io'; -import 'dart:typed_data'; import 'package:file_picker/file_picker.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flux/core/blocs/session/session_cubit.dart'; @@ -16,6 +16,7 @@ part 'attachments_state.dart'; class AttachmentsBloc extends Bloc { final _repository = GetIt.I.get(); + StreamSubscription>? _realtimeSubscription; AttachmentsBloc({String? parentId, required AttachmentParentType parentType}) : super( @@ -36,6 +37,8 @@ class AttachmentsBloc extends Bloc { on(_onDeleteSpecificAttachment); on(_onSelectAllAttachments); on(_onClearAttachmentSelection); + on(_onRemoteAttachmentsUpdated); + on(_onUpdateAttachmentViewMode); final currentCompanyId = GetIt.I.get().state.company?.id; if (parentId != null && currentCompanyId != null) { @@ -43,6 +46,12 @@ class AttachmentsBloc extends Bloc { } } + @override + Future close() { + _realtimeSubscription?.cancel(); + return super.close(); + } + FutureOr _onParentEntitySaved( ParentEntitySavedEvent event, Emitter emit, @@ -65,7 +74,6 @@ class AttachmentsBloc extends Bloc { bytes: file.localBytes, ); - // Chiamiamo il metodo generico passando il parentId e il TYPE return _repository.uploadAndRegisterFile( parentId: event.newParentId, parentType: state.parentType, @@ -96,26 +104,75 @@ class AttachmentsBloc extends Bloc { Emitter emit, ) async { final currentId = event.parentId ?? state.parentId; + if (currentId == null || currentId.isEmpty) return; - if (currentId != null) { - emit(state.copyWith(status: AttachmentsStatus.loading)); + emit( + state.copyWith( + parentId: currentId, + status: + state.remoteFiles.isEmpty + ? AttachmentsStatus.loading + : state.status, + ), + ); - await emit.forEach( - _repository.getFilesStream( - currentId, - state.parentType, - ), // Passiamo il tipo! - onData: (List data) => - state.copyWith(status: AttachmentsStatus.ready, remoteFiles: data), - onError: (error, stackTrace) => state.copyWith( - status: AttachmentsStatus.failure, - error: error.toString(), + // 1. Caricamento immediato via REST (Robusto e istantaneo) + try { + final remoteList = await _repository.getFiles( + currentId, + state.parentType, + ); + emit( + state.copyWith( + status: AttachmentsStatus.ready, + remoteFiles: remoteList, + error: null, ), ); + } catch (e) { + debugPrint("Avviso REST getFiles: $e"); + if (state.remoteFiles.isEmpty) { + emit( + state.copyWith( + status: AttachmentsStatus.failure, + error: "Impossibile recuperare gli allegati: $e", + ), + ); + } + } + + // 2. Iscrizione Realtime in background (senza bloccare la coda eventi) + await _realtimeSubscription?.cancel(); + try { + _realtimeSubscription = _repository + .getFilesStream(currentId, state.parentType) + .listen( + (data) { + add(RemoteAttachmentsUpdatedEvent(data)); + }, + onError: (error) { + debugPrint("Avviso stream Realtime AttachmentsBloc: $error"); + }, + ); + } catch (e) { + debugPrint("Avviso inizializzazione Realtime: $e"); } } - void _onAddAttachments( + void _onRemoteAttachmentsUpdated( + RemoteAttachmentsUpdatedEvent event, + Emitter emit, + ) { + emit( + state.copyWith( + status: AttachmentsStatus.ready, + remoteFiles: event.files, + error: null, + ), + ); + } + + FutureOr _onAddAttachments( AddAttachmentsEvent event, Emitter emit, ) async { @@ -132,32 +189,48 @@ class AttachmentsBloc extends Bloc { return; } - // BIVIO 1: PRATICA NUOVA (Salvataggio locale in memoria) - if (currentId == null) { - final newLocalFiles = event.files.map((file) { - // FISCHIO SALVAVITA PER DESKTOP: se i bytes sono nulli, li leggiamo dal path fisico! - Uint8List? rawBytes = file.bytes; - if (rawBytes == null && file.path != null) { - rawBytes = File(file.path!).readAsBytesSync(); - } + // Normalizziamo i file garantendo la presenza dei byte (fondamentale su desktop) + final processedFiles = + event.files.map((file) { + Uint8List? rawBytes = file.bytes; + if (rawBytes == null && file.path != null && !kIsWeb) { + try { + final f = File(file.path!); + if (f.existsSync()) { + rawBytes = f.readAsBytesSync(); + } + } catch (_) {} + } - return AttachmentModel( - id: null, - companyId: currentCompanyId, - operationId: state.parentType == AttachmentParentType.operation - ? '' - : null, - ticketId: state.parentType == AttachmentParentType.ticket ? '' : null, - customerId: state.parentType == AttachmentParentType.customer - ? '' - : null, - name: file.name.fileNameWithoutExtension(), - extension: file.name.fileExtension(), - storagePath: '', - fileSize: file.size, - localBytes: rawBytes, // Ora i byte ci sono al 100% anche su Mac! - ); - }).toList(); + return PlatformFile( + name: file.name, + size: file.size > 0 ? file.size : (rawBytes?.length ?? 0), + bytes: rawBytes, + path: file.path, + readStream: file.readStream, + ); + }).toList(); + + // BIVIO 1: PRATICA NUOVA (Salvataggio locale in memoria) + if (currentId == null || currentId.isEmpty) { + final newLocalFiles = + processedFiles.map((file) { + return AttachmentModel( + id: null, + companyId: currentCompanyId, + operationId: + state.parentType == AttachmentParentType.operation ? '' : null, + ticketId: + state.parentType == AttachmentParentType.ticket ? '' : null, + customerId: + state.parentType == AttachmentParentType.customer ? '' : null, + name: file.name.fileNameWithoutExtension(), + extension: file.name.fileExtension(), + storagePath: '', + fileSize: file.size, + localBytes: file.bytes, + ); + }).toList(); emit( state.copyWith( @@ -171,18 +244,31 @@ class AttachmentsBloc extends Bloc { // BIVIO 2: PRATICA ESISTENTE (Upload immediato) emit(state.copyWith(status: AttachmentsStatus.uploading)); try { - final List> uploadTasks = event.files.map((file) { - return _repository.uploadAndRegisterFile( - parentId: currentId, - parentType: state.parentType, - pickedFile: file, - companyId: currentCompanyId, - bucket: _getBucketForParentType, - ); - }).toList(); + final List> uploadTasks = + processedFiles.map((file) { + return _repository.uploadAndRegisterFile( + parentId: currentId, + parentType: state.parentType, + pickedFile: file, + companyId: currentCompanyId, + bucket: _getBucketForParentType, + ); + }).toList(); await Future.wait(uploadTasks); - emit(state.copyWith(status: AttachmentsStatus.ready)); + + // Aggiornamento immediato via REST (garantisce visualizzazione immediata anche senza WebSocket) + final updatedFiles = await _repository.getFiles( + currentId, + state.parentType, + ); + emit( + state.copyWith( + status: AttachmentsStatus.ready, + remoteFiles: updatedFiles, + error: null, + ), + ); } catch (e) { emit( state.copyWith(status: AttachmentsStatus.failure, error: e.toString()), @@ -223,11 +309,9 @@ class AttachmentsBloc extends Bloc { // 2. Gestione Foto Fotocamera (XFile) if (event.photos != null) { for (var photo in event.photos!) { - // Leggiamo i byte asincronamente final bytes = await photo.readAsBytes(); final fileSize = await photo.length(); - // Lo travestiamo da PlatformFile per passarlo al Repository! final fakePlatformFile = PlatformFile( name: photo.name, size: fileSize, @@ -247,9 +331,18 @@ class AttachmentsBloc extends Bloc { } } - // Esecuzione parallela di tutti i documenti e foto await Future.wait(uploadTasks); - emit(state.copyWith(status: AttachmentsStatus.success)); + + final updatedFiles = await _repository.getFiles( + state.parentId!, + state.parentType, + ); + emit( + state.copyWith( + status: AttachmentsStatus.success, + remoteFiles: updatedFiles, + ), + ); } catch (e) { emit( state.copyWith(status: AttachmentsStatus.failure, error: e.toString()), @@ -268,7 +361,22 @@ class AttachmentsBloc extends Bloc { currentContextType: state.parentType, bucket: _getBucketForParentType, ); - emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: [])); + + if (state.parentId != null) { + final updatedFiles = await _repository.getFiles( + state.parentId!, + state.parentType, + ); + emit( + state.copyWith( + status: AttachmentsStatus.ready, + remoteFiles: updatedFiles, + selectedFiles: [], + ), + ); + } else { + emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: [])); + } } catch (e) { emit( state.copyWith(status: AttachmentsStatus.failure, error: e.toString()), @@ -293,7 +401,6 @@ class AttachmentsBloc extends Bloc { SelectAllAttachmentsEvent event, Emitter emit, ) { - // Prendiamo TUTTI i file (locali e remoti) e li buttiamo nei selezionati emit(state.copyWith(selectedFiles: state.allFiles)); } @@ -301,7 +408,6 @@ class AttachmentsBloc extends Bloc { ClearAttachmentSelectionEvent event, Emitter emit, ) { - // Svuotiamo brutalmente la lista emit(state.copyWith(selectedFiles: [])); } @@ -311,38 +417,36 @@ class AttachmentsBloc extends Bloc { ) async { if (state.selectedFiles.isEmpty) return; - // BIVIO 1: PRATICA/TICKET NON ANCORA SALVATA (Modalità Locale) if (state.parentId == null) { - final updatedLocalFiles = state.localFiles.map((file) { - if (state.selectedFiles.contains(file)) { - // Assegniamo dinamicamente l'ID in base all'entità scelta - switch (event.targetType) { - case AttachmentParentType.customer: - return file.copyWith(customerId: event.targetId); - case AttachmentParentType.ticket: - return file.copyWith(ticketId: event.targetId); - case AttachmentParentType.operation: - return file.copyWith(operationId: event.targetId); - case AttachmentParentType.shippingDocument: - return file.copyWith(shippingDocumentId: event.targetId); - case AttachmentParentType.note: - return file.copyWith(noteId: event.targetId); - } - } - return file; - }).toList(); + final updatedLocalFiles = + state.localFiles.map((file) { + if (state.selectedFiles.contains(file)) { + switch (event.targetType) { + case AttachmentParentType.customer: + return file.copyWith(customerId: event.targetId); + case AttachmentParentType.ticket: + return file.copyWith(ticketId: event.targetId); + case AttachmentParentType.operation: + return file.copyWith(operationId: event.targetId); + case AttachmentParentType.shippingDocument: + return file.copyWith(shippingDocumentId: event.targetId); + case AttachmentParentType.note: + return file.copyWith(noteId: event.targetId); + } + } + return file; + }).toList(); emit( state.copyWith( localFiles: updatedLocalFiles, - selectedFiles: [], // Svuotiamo la selezione + selectedFiles: [], status: AttachmentsStatus.ready, ), ); return; } - // BIVIO 2: PRATICA/TICKET ESISTENTE (Modalità Remota su DB) emit(state.copyWith(status: AttachmentsStatus.loading)); try { final List> linkTasks = []; @@ -361,8 +465,17 @@ class AttachmentsBloc extends Bloc { await Future.wait(linkTasks); - // Lo stream aggiornerà automaticamente la UI - emit(state.copyWith(status: AttachmentsStatus.ready, selectedFiles: [])); + final updatedFiles = await _repository.getFiles( + state.parentId!, + state.parentType, + ); + emit( + state.copyWith( + status: AttachmentsStatus.ready, + remoteFiles: updatedFiles, + selectedFiles: [], + ), + ); } catch (e) { emit( state.copyWith( @@ -377,23 +490,35 @@ class AttachmentsBloc extends Bloc { RenameAttachmentEvent event, Emitter emit, ) async { - // BIVIO 1: File Locale (Bozza) if (event.file.localBytes != null) { - final updatedLocalFiles = state.localFiles.map((f) { - if (f == event.file) { - return f.copyWith(name: event.newName); - } - return f; - }).toList(); + final updatedLocalFiles = + state.localFiles.map((f) { + if (f == event.file) { + return f.copyWith(name: event.newName); + } + return f; + }).toList(); emit(state.copyWith(localFiles: updatedLocalFiles)); return; } - // BIVIO 2: File Remoto (Salvato su DB) emit(state.copyWith(status: AttachmentsStatus.loading)); try { await _repository.renameAttachment(event.file.id!, event.newName); - emit(state.copyWith(status: AttachmentsStatus.ready)); + if (state.parentId != null) { + final updatedFiles = await _repository.getFiles( + state.parentId!, + state.parentType, + ); + emit( + state.copyWith( + status: AttachmentsStatus.ready, + remoteFiles: updatedFiles, + ), + ); + } else { + emit(state.copyWith(status: AttachmentsStatus.ready)); + } } catch (e) { emit( state.copyWith( @@ -409,13 +534,44 @@ class AttachmentsBloc extends Bloc { Emitter emit, ) { if (event.file.localBytes != null) { - final updatedLocalFiles = state.localFiles - .where((f) => f != event.file) - .toList(); + final updatedLocalFiles = + state.localFiles.where((f) => f != event.file).toList(); emit(state.copyWith(localFiles: updatedLocalFiles)); } } + FutureOr _onUpdateAttachmentViewMode( + UpdateAttachmentViewModeEvent event, + Emitter emit, + ) async { + if (event.file.localBytes != null) { + final updatedLocalFiles = state.localFiles.map((f) { + if (f == event.file) { + return f.copyWith(viewMode: event.viewMode); + } + return f; + }).toList(); + emit(state.copyWith(localFiles: updatedLocalFiles)); + return; + } + + if (event.file.id == null) return; + + try { + final updatedRemoteFiles = state.remoteFiles.map((f) { + if (f.id == event.file.id) { + return f.copyWith(viewMode: event.viewMode); + } + return f; + }).toList(); + emit(state.copyWith(remoteFiles: updatedRemoteFiles)); + + await _repository.updateAttachmentViewMode(event.file.id!, event.viewMode); + } catch (e) { + debugPrint("Errore aggiornamento viewMode in DB: $e"); + } + } + Bucket get _getBucketForParentType { switch (state.parentType) { case AttachmentParentType.customer: diff --git a/lib/features/attachments/blocs/attachments_events.dart b/lib/features/attachments/blocs/attachments_events.dart index 6fe6826..e00ffbd 100644 --- a/lib/features/attachments/blocs/attachments_events.dart +++ b/lib/features/attachments/blocs/attachments_events.dart @@ -71,3 +71,20 @@ class DeleteSpecificAttachmentEvent extends AttachmentsEvent { final AttachmentModel file; const DeleteSpecificAttachmentEvent(this.file); } + +class RemoteAttachmentsUpdatedEvent extends AttachmentsEvent { + final List files; + const RemoteAttachmentsUpdatedEvent(this.files); + + @override + List get props => [files]; +} + +class UpdateAttachmentViewModeEvent extends AttachmentsEvent { + final AttachmentModel file; + final AttachmentViewMode viewMode; + const UpdateAttachmentViewModeEvent(this.file, this.viewMode); + + @override + List get props => [file, viewMode]; +} diff --git a/lib/features/attachments/data/attachments_repository.dart b/lib/features/attachments/data/attachments_repository.dart index 3b99f05..4b53555 100644 --- a/lib/features/attachments/data/attachments_repository.dart +++ b/lib/features/attachments/data/attachments_repository.dart @@ -1,5 +1,6 @@ -import 'dart:typed_data'; +import 'dart:io'; import 'package:file_picker/file_picker.dart'; +import 'package:flutter/foundation.dart'; import 'package:flux/core/enums_and_consts/consts.dart'; import 'package:flux/features/attachments/models/attachment_model.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; @@ -47,6 +48,28 @@ class AttachmentsRepository { } } + /// RECUPERA I FILE IN MODALITÀ REST (Immediato e affidabile) + Future> getFiles( + String parentId, + AttachmentParentType parentType, + ) async { + try { + final columnName = _getColumnNameForParent(parentType); + + final response = await _supabase + .from(Tables.attachments) + .select() + .eq(columnName, parentId) + .order('created_at', ascending: true); + + return (response as List) + .map((map) => AttachmentModel.fromMap(map as Map)) + .toList(); + } catch (e) { + throw Exception("Impossibile recuperare gli allegati dal DB: $e"); + } + } + /// RECUPERA I FILE IN TEMPO REALE Stream> getFilesStream( String parentId, @@ -75,7 +98,6 @@ class AttachmentsRepository { String? rawFileName, // Alternativa: nome del file }) async { // 🛡️ L'ASSERT NINJA: O c'è il pickedFile, o ci sono i byte e il nome. - // L'assert funziona solo in debug, ma è perfetto per beccare subito errori di chiamata! assert( pickedFile != null || (rawBytes != null && rawFileName != null), 'Devi passare o un PlatformFile, oppure rawBytes e rawFileName!', @@ -88,25 +110,35 @@ class AttachmentsRepository { final int finalFileSize; if (pickedFile != null) { - if (pickedFile.bytes == null) { + Uint8List? fileBytes = pickedFile.bytes; + // Se su Desktop i bytes sono nulli ma abbiamo il path, leggiamo direttamente da disco + if (fileBytes == null && pickedFile.path != null && !kIsWeb) { + try { + final f = File(pickedFile.path!); + if (f.existsSync()) { + fileBytes = f.readAsBytesSync(); + } + } catch (_) {} + } + + if (fileBytes == null) { throw Exception( "I bytes del file sono vuoti! Ricarica la pagina senza cache.", ); } - finalBytes = pickedFile.bytes!; + finalBytes = fileBytes; finalFileName = pickedFile.name; - finalFileSize = pickedFile.size; + finalFileSize = pickedFile.size > 0 ? pickedFile.size : finalBytes.length; } else { - // Se pickedFile è null, grazie all'assert sappiamo che questi non lo sono finalBytes = rawBytes!; finalFileName = rawFileName!; - finalFileSize = finalBytes.length; // Calcoliamo la size dai byte reali + finalFileSize = finalBytes.length; } // 2. Estraiamo l'estensione e puliamo il nome final extension = finalFileName.contains('.') ? finalFileName.split('.').last - : ''; // Fallback se il file non ha estensione + : ''; final cleanName = finalFileName .replaceAll(RegExp(r'[^\w\s\.-]'), '') @@ -123,7 +155,10 @@ class AttachmentsRepository { .uploadBinary( storagePath, finalBytes, - fileOptions: FileOptions(contentType: _guessContentType(extension)), + fileOptions: FileOptions( + contentType: _guessContentType(extension), + upsert: true, + ), ); // 5. Creiamo la mappa per il DB dinamicamente @@ -185,10 +220,17 @@ class AttachmentsRepository { // B. Nessuno usa più questo file! ELIMINAZIONE FISICA TOTALE. await _supabase.from(Tables.attachments).delete().eq('id', file.id!); - if (file.storagePath != null) { - await _supabase.storage.from(bucket.value).remove([ + final pathsToRemove = [ + if (file.storagePath != null && file.storagePath!.isNotEmpty) file.storagePath!, - ]); + if (file.thumbnailPath != null && file.thumbnailPath!.isNotEmpty) + file.thumbnailPath!, + if (file.croppedStoragePath != null && + file.croppedStoragePath!.isNotEmpty) + file.croppedStoragePath!, + ]; + if (pathsToRemove.isNotEmpty) { + await _supabase.storage.from(bucket.value).remove(pathsToRemove); } } } @@ -216,7 +258,6 @@ class AttachmentsRepository { required String targetId, }) async { try { - // Facciamo un semplice UPDATE aggiungendo l'ID nella colonna giusta await _supabase .from(Tables.attachments) .update({targetType.dbColumn: targetId}) @@ -226,9 +267,26 @@ class AttachmentsRepository { } } + /// AGGIORNA LA MODALITÀ DI VISUALIZZAZIONE PREFERITA (cropped / original) + Future updateAttachmentViewMode( + String fileId, + AttachmentViewMode viewMode, + ) async { + try { + await _supabase + .from(Tables.attachments) + .update({'view_mode': viewMode.value}) + .eq('id', fileId); + } catch (e) { + throw Exception( + "Errore nell'aggiornamento della modalità di visualizzazione: $e", + ); + } + } + // Helper per indovinare il content-type base String _guessContentType(String extension) { - switch (extension.toLowerCase()) { + switch (extension.toLowerCase().replaceAll('.', '')) { case 'pdf': return 'application/pdf'; case 'png': @@ -236,6 +294,28 @@ class AttachmentsRepository { case 'jpg': case 'jpeg': return 'image/jpeg'; + case 'webp': + return 'image/webp'; + case 'heic': + return 'image/heic'; + case 'heif': + return 'image/heif'; + case 'gif': + return 'image/gif'; + case 'svg': + return 'image/svg+xml'; + case 'txt': + return 'text/plain'; + case 'csv': + return 'text/csv'; + case 'doc': + return 'application/msword'; + case 'docx': + return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; + case 'xls': + return 'application/vnd.ms-excel'; + case 'xlsx': + return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; default: return 'application/octet-stream'; } diff --git a/lib/features/attachments/models/attachment_model.dart b/lib/features/attachments/models/attachment_model.dart index b46f3c7..3bfcb3c 100644 --- a/lib/features/attachments/models/attachment_model.dart +++ b/lib/features/attachments/models/attachment_model.dart @@ -2,6 +2,22 @@ import 'dart:typed_data'; import 'package:equatable/equatable.dart'; +enum AttachmentViewMode { + cropped('cropped'), + original('original'); + + final String value; + const AttachmentViewMode(this.value); + + static AttachmentViewMode? fromString(String? val) { + if (val == null) return null; + final clean = val.trim().toLowerCase(); + if (clean == 'cropped') return AttachmentViewMode.cropped; + if (clean == 'original') return AttachmentViewMode.original; + return null; + } +} + class AttachmentModel extends Equatable { final String? id; final DateTime? createdAt; @@ -13,6 +29,9 @@ class AttachmentModel extends Equatable { final String name; final String extension; final String? storagePath; + final String? thumbnailPath; + final String? croppedStoragePath; + final AttachmentViewMode? viewMode; final int fileSize; final Uint8List? localBytes; final String companyId; @@ -28,11 +47,21 @@ class AttachmentModel extends Equatable { required this.name, required this.extension, this.storagePath, + this.thumbnailPath, + this.croppedStoragePath, + this.viewMode, required this.fileSize, this.localBytes, required this.companyId, }); + factory AttachmentModel.empty() => const AttachmentModel( + name: '', + extension: '', + fileSize: 0, + companyId: '', + ); + @override List get props => [ id, @@ -45,6 +74,9 @@ class AttachmentModel extends Equatable { name, extension, storagePath, + thumbnailPath, + croppedStoragePath, + viewMode, fileSize, localBytes, companyId, @@ -54,6 +86,25 @@ class AttachmentModel extends Equatable { bool get isPdf => extension.toLowerCase().replaceAll('.', '') == 'pdf'; + String? get effectiveStoragePath { + if (viewMode == AttachmentViewMode.cropped) { + if (croppedStoragePath != null && croppedStoragePath!.isNotEmpty) { + return croppedStoragePath; + } + return storagePath; + } else if (viewMode == AttachmentViewMode.original) { + if (storagePath != null && storagePath!.isNotEmpty) { + return storagePath; + } + return croppedStoragePath; + } + // Default fallback quando viewMode non è specificato + if (croppedStoragePath != null && croppedStoragePath!.isNotEmpty) { + return croppedStoragePath; + } + return storagePath; + } + String get sizeFormatted { if (fileSize <= 0) return "0 B"; const suffixes = ["B", "KB", "MB", "GB", "TB"]; @@ -74,6 +125,9 @@ class AttachmentModel extends Equatable { String? name, String? extension, String? storagePath, + String? thumbnailPath, + String? croppedStoragePath, + AttachmentViewMode? viewMode, int? fileSize, Uint8List? localBytes, String? companyId, @@ -88,6 +142,9 @@ class AttachmentModel extends Equatable { name: name ?? this.name, extension: extension ?? this.extension, storagePath: storagePath ?? this.storagePath, + thumbnailPath: thumbnailPath ?? this.thumbnailPath, + croppedStoragePath: croppedStoragePath ?? this.croppedStoragePath, + viewMode: viewMode ?? this.viewMode, fileSize: fileSize ?? this.fileSize, localBytes: localBytes ?? this.localBytes, companyId: companyId ?? this.companyId, @@ -107,6 +164,9 @@ class AttachmentModel extends Equatable { name: map['name'] as String, extension: map['extension'] as String, storagePath: map['storage_path'] as String?, + thumbnailPath: map['thumbnail_path'] as String?, + croppedStoragePath: map['cropped_storage_path'] as String?, + viewMode: AttachmentViewMode.fromString(map['view_mode'] as String?), fileSize: map['file_size'] is int ? map['file_size'] : int.tryParse(map['file_size']?.toString() ?? '0') ?? 0, @@ -127,6 +187,9 @@ class AttachmentModel extends Equatable { 'note_id': noteId, 'file_size': fileSize, 'company_id': companyId, + 'thumbnail_path': thumbnailPath, + 'cropped_storage_path': croppedStoragePath, + 'view_mode': viewMode?.value, }; } } diff --git a/lib/features/attachments/ui/attachment_viewer_screen.dart b/lib/features/attachments/ui/attachment_viewer_screen.dart index b55eb80..d3b11f2 100644 --- a/lib/features/attachments/ui/attachment_viewer_screen.dart +++ b/lib/features/attachments/ui/attachment_viewer_screen.dart @@ -4,9 +4,11 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:file_picker/file_picker.dart'; +import 'package:get_it/get_it.dart'; import 'package:universal_html/html.dart' as html; import 'package:flux/core/utils/functions.dart'; import 'package:flux/features/attachments/models/attachment_model.dart'; +import 'package:flux/features/attachments/data/attachments_repository.dart'; import 'package:flux/core/utils/image_utils.dart'; import 'package:pdfrx/pdfrx.dart'; import 'package:internet_file/internet_file.dart'; @@ -19,6 +21,7 @@ class AttachmentViewerScreen extends StatefulWidget { final Function(AttachmentModel attachment, String newName)? onRenameAttachment; final VoidCallback? onDelete; final Function(AttachmentModel attachment)? onDeleteAttachment; + final Function(AttachmentModel attachment, AttachmentViewMode viewMode)? onViewModeChanged; const AttachmentViewerScreen({ super.key, @@ -29,6 +32,7 @@ class AttachmentViewerScreen extends StatefulWidget { this.onRenameAttachment, this.onDelete, this.onDeleteAttachment, + this.onViewModeChanged, }) : assert( attachment != null || (attachments != null && attachments.length > 0), 'Devi fornire un allegato o una lista di allegati non vuota.', @@ -48,6 +52,8 @@ class _AttachmentViewerScreenState extends State { Uint8List? _fileBytes; int _loadToken = 0; int _rotationTurns = 0; + bool _showCropped = true; + final Map _bytesCache = {}; AttachmentModel get _currentAttachment => _items[_currentIndex]; bool get isPdf => @@ -56,6 +62,33 @@ class _AttachmentViewerScreenState extends State { bool get canGoPrevious => _currentIndex > 0; bool get canGoNext => _currentIndex < _items.length - 1; + bool get _hasCropped => + _currentAttachment.croppedStoragePath != null && + _currentAttachment.croppedStoragePath!.isNotEmpty; + bool get _hasOriginal => + _currentAttachment.storagePath != null && + _currentAttachment.storagePath!.isNotEmpty; + bool get canToggleCrop => !isPdf && _hasCropped && _hasOriginal; + + String? get _activeStoragePath { + final item = _currentAttachment; + if (_showCropped && _hasCropped) { + return item.croppedStoragePath; + } + return item.storagePath; + } + + bool _computeInitialShowCropped(AttachmentModel attachment) { + if (attachment.viewMode == AttachmentViewMode.original) { + return false; + } + if (attachment.viewMode == AttachmentViewMode.cropped) { + return true; + } + return attachment.croppedStoragePath != null && + attachment.croppedStoragePath!.isNotEmpty; + } + @override void initState() { super.initState(); @@ -70,6 +103,10 @@ class _AttachmentViewerScreenState extends State { _currentIndex = 0; } + if (_items.isNotEmpty) { + _showCropped = _computeInitialShowCropped(_currentAttachment); + } + _loadFile(); WidgetsBinding.instance.addPostFrameCallback((_) { @@ -97,8 +134,10 @@ class _AttachmentViewerScreenState extends State { void _changeFile(int newIndex) { if (newIndex < 0 || newIndex >= _items.length) return; + final newAttachment = _items[newIndex]; setState(() { _currentIndex = newIndex; + _showCropped = _computeInitialShowCropped(newAttachment); _isLoading = true; _errorMessage = null; _fileBytes = null; @@ -107,6 +146,48 @@ class _AttachmentViewerScreenState extends State { _loadFile(); } + void _toggleCropView() { + if (!canToggleCrop) return; + final nextShowCropped = !_showCropped; + final nextMode = nextShowCropped + ? AttachmentViewMode.cropped + : AttachmentViewMode.original; + final nextPath = nextShowCropped + ? _currentAttachment.croppedStoragePath + : _currentAttachment.storagePath; + + final updatedAttachment = _currentAttachment.copyWith(viewMode: nextMode); + + setState(() { + _showCropped = nextShowCropped; + _items[_currentIndex] = updatedAttachment; + _rotationTurns = 0; + }); + + if (widget.onViewModeChanged != null) { + widget.onViewModeChanged!(updatedAttachment, nextMode); + } else if (updatedAttachment.id != null) { + try { + final repository = GetIt.I.get(); + repository.updateAttachmentViewMode(updatedAttachment.id!, nextMode); + } catch (_) {} + } + + if (nextPath != null && _bytesCache.containsKey(nextPath)) { + setState(() { + _fileBytes = _bytesCache[nextPath]; + _isLoading = false; + _errorMessage = null; + }); + } else { + setState(() { + _isLoading = true; + _errorMessage = null; + }); + _loadFile(); + } + } + KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) { if (event is KeyDownEvent) { if (event.logicalKey == LogicalKeyboardKey.arrowLeft) { @@ -132,18 +213,47 @@ class _AttachmentViewerScreenState extends State { Uint8List? bytes; if (item.localBytes != null) { bytes = item.localBytes; - } else if (item.storagePath != null && - item.storagePath!.isNotEmpty) { - final signedUrl = await getSignedUrl(item.storagePath!); - bytes = await InternetFile.get(signedUrl); } else { - throw Exception("Nessun documento trovato o byte mancanti."); + final path = _activeStoragePath; + if (path != null && path.isNotEmpty) { + if (_bytesCache.containsKey(path)) { + bytes = _bytesCache[path]; + } else { + try { + final signedUrl = await getSignedUrl(path); + bytes = await InternetFile.get(signedUrl); + } catch (e) { + // Se fallisce il ritaglio e abbiamo l'originale, proviamo l'originale come fallback + if (_showCropped && _hasOriginal && item.storagePath != path) { + final signedUrl = await getSignedUrl(item.storagePath!); + bytes = await InternetFile.get(signedUrl); + _showCropped = false; + } else { + rethrow; + } + } + + if (!isPdf) { + bytes = ImageUtils.normalizeOrientation( + bytes, + extension: item.extension, + ); + } + + _bytesCache[path] = bytes; + } + } else { + throw Exception("Nessun documento trovato o byte mancanti."); + } } if (token != _loadToken || !mounted) return; - if (bytes != null && !isPdf) { - bytes = ImageUtils.normalizeOrientation(bytes, extension: item.extension); + if (bytes != null && !isPdf && item.localBytes != null) { + bytes = ImageUtils.normalizeOrientation( + bytes, + extension: item.extension, + ); } setState(() { @@ -266,6 +376,9 @@ class _AttachmentViewerScreenState extends State { String fullName = _currentAttachment.name; final ext = _currentAttachment.extension.toLowerCase().replaceAll('.', ''); + if (_showCropped && canToggleCrop) { + fullName = '${fullName}_cropped'; + } if (ext.isNotEmpty && !fullName.toLowerCase().endsWith('.$ext')) { fullName = '$fullName.$ext'; } @@ -320,14 +433,64 @@ class _AttachmentViewerScreenState extends State { style: const TextStyle(fontSize: 16), overflow: TextOverflow.ellipsis, ), - if (hasMultipleFiles) - Text( - '${_currentIndex + 1} di ${_items.length}', - style: const TextStyle(fontSize: 12, color: Colors.white70), - ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (hasMultipleFiles) ...[ + Text( + '${_currentIndex + 1} di ${_items.length}', + style: const TextStyle(fontSize: 12, color: Colors.white70), + ), + if (canToggleCrop) + const Text( + ' • ', + style: TextStyle(fontSize: 12, color: Colors.white70), + ), + ], + if (canToggleCrop) + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), + decoration: BoxDecoration( + color: _showCropped + ? Colors.amber.withValues(alpha: 0.2) + : Colors.white10, + borderRadius: BorderRadius.circular(4), + border: Border.all( + color: _showCropped + ? Colors.amberAccent + : Colors.white30, + width: 0.8, + ), + ), + child: Text( + _showCropped ? 'Ritaglio automatico' : 'Originale', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: _showCropped + ? Colors.amberAccent + : Colors.white70, + ), + ), + ), + ], + ), ], ), actions: [ + if (canToggleCrop) + IconButton( + icon: Icon( + _showCropped + ? Icons.photo_size_select_actual_outlined + : Icons.crop, + color: _showCropped ? Colors.amberAccent : Colors.white, + ), + tooltip: _showCropped + ? 'Passa alla foto originale' + : 'Passa al ritaglio automatico', + onPressed: _toggleCropView, + ), if (!isPdf) IconButton( icon: const Icon(Icons.rotate_right), diff --git a/lib/features/customers/ui/customer_detail_screen.dart b/lib/features/customers/ui/customer_detail_screen.dart index 0e2e949..4192b14 100644 --- a/lib/features/customers/ui/customer_detail_screen.dart +++ b/lib/features/customers/ui/customer_detail_screen.dart @@ -352,7 +352,9 @@ class _FileCard extends StatelessWidget { height: MediaQuery.of(context).size.height * 0.8, child: file.isPdf ? PdfViewerWidget(storagePath: file.storagePath) - : ImageViewerWidget(storagePath: file.storagePath), + : ImageViewerWidget( + storagePath: file.effectiveStoragePath, + ), ), ), ), diff --git a/lib/features/tickets/ui/widgets/ticket_list_card.dart b/lib/features/tickets/ui/widgets/ticket_list_card.dart index 085e2ab..5eaa4d1 100644 --- a/lib/features/tickets/ui/widgets/ticket_list_card.dart +++ b/lib/features/tickets/ui/widgets/ticket_list_card.dart @@ -53,6 +53,11 @@ class TicketListCard extends StatelessWidget { DeleteSpecificAttachmentEvent(targetFile), ); }, + onViewModeChanged: (targetFile, newMode) { + operationFilesBloc.add( + UpdateAttachmentViewModeEvent(targetFile, newMode), + ); + }, ), ), ), diff --git a/lib/service_locator.dart b/lib/service_locator.dart index c0ae46e..08bec77 100644 --- a/lib/service_locator.dart +++ b/lib/service_locator.dart @@ -39,10 +39,16 @@ import 'package:supabase_flutter/supabase_flutter.dart'; final sl = GetIt.instance; Future init() async { + final envUrl = dotenv.env['SUPABASE_URL']?.trim(); + final envKey = dotenv.env['SUPABASE_PUBLISHABLE_KEY']?.trim(); + await Supabase.initialize( - url: dotenv.env['SUPABASE_URL'] ?? 'https://supabaseapi.catelli.it', - publishableKey: dotenv.env['SUPABASE_PUBLISHABLE_KEY'] ?? - 'sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo', + url: (envUrl != null && envUrl.isNotEmpty) + ? envUrl + : 'https://supabaseapi.catelli.it', + publishableKey: (envKey != null && envKey.isNotEmpty) + ? envKey + : 'sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo', ); sl.registerSingleton(Supabase.instance.client); sl.registerSingleton( diff --git a/pubspec.yaml b/pubspec.yaml index 4f82953..e5f6c74 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: flux description: "Gestione attività negozio di telefonia" publish_to: 'none' -version: 2.4.2+83 +version: 2.5.0+84 environment: sdk: ^3.11.3 diff --git a/test/features/attachments/models/attachment_model_test.dart b/test/features/attachments/models/attachment_model_test.dart new file mode 100644 index 0000000..df04ba1 --- /dev/null +++ b/test/features/attachments/models/attachment_model_test.dart @@ -0,0 +1,134 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:flux/features/attachments/models/attachment_model.dart'; + +void main() { + group('AttachmentModel Tests', () { + test('empty() creates a valid default empty instance', () { + final empty = AttachmentModel.empty(); + expect(empty.name, ''); + expect(empty.extension, ''); + expect(empty.fileSize, 0); + expect(empty.companyId, ''); + expect(empty.thumbnailPath, isNull); + expect(empty.croppedStoragePath, isNull); + expect(empty.storagePath, isNull); + expect(empty.viewMode, isNull); + }); + + test('fromMap and toMap handle thumbnailPath, croppedStoragePath, and viewMode correctly', () { + final map = { + 'id': 'att-123', + 'created_at': '2026-10-15T10:00:00.000Z', + 'customer_id': 'cust-1', + 'operation_id': 'op-1', + 'ticket_id': 'tick-1', + 'shipping_document_id': 'ship-1', + 'note_id': 'note-1', + 'name': 'documento_test', + 'extension': 'jpg', + 'storage_path': 'company/operation/op-1/orig.jpg', + 'thumbnail_path': 'company/operation/op-1/thumb.webp', + 'cropped_storage_path': 'company/operation/op-1/crop.jpg', + 'view_mode': 'cropped', + 'file_size': 204800, + 'company_id': 'comp-99', + }; + + final model = AttachmentModel.fromMap(map); + + expect(model.id, 'att-123'); + expect(model.name, 'documento_test'); + expect(model.extension, 'jpg'); + expect(model.storagePath, 'company/operation/op-1/orig.jpg'); + expect(model.thumbnailPath, 'company/operation/op-1/thumb.webp'); + expect(model.croppedStoragePath, 'company/operation/op-1/crop.jpg'); + expect(model.viewMode, AttachmentViewMode.cropped); + expect(model.fileSize, 204800); + expect(model.companyId, 'comp-99'); + + final serialized = model.toMap(); + expect(serialized['thumbnail_path'], 'company/operation/op-1/thumb.webp'); + expect(serialized['cropped_storage_path'], 'company/operation/op-1/crop.jpg'); + expect(serialized['storage_path'], 'company/operation/op-1/orig.jpg'); + expect(serialized['view_mode'], 'cropped'); + }); + + test('effectiveStoragePath resolves properly according to viewMode', () { + const orig = 'company/orig.jpg'; + const crop = 'company/crop.jpg'; + + // 1. viewMode = cropped -> crop + final croppedModel = AttachmentModel.empty().copyWith( + storagePath: orig, + croppedStoragePath: crop, + viewMode: AttachmentViewMode.cropped, + ); + expect(croppedModel.effectiveStoragePath, crop); + + // 2. viewMode = original -> orig + final originalModel = AttachmentModel.empty().copyWith( + storagePath: orig, + croppedStoragePath: crop, + viewMode: AttachmentViewMode.original, + ); + expect(originalModel.effectiveStoragePath, orig); + + // 3. viewMode = null -> defaults to crop if available + final defaultWithCrop = AttachmentModel.empty().copyWith( + storagePath: orig, + croppedStoragePath: crop, + ); + expect(defaultWithCrop.effectiveStoragePath, crop); + + // 4. viewMode = cropped but croppedStoragePath is null -> fallback to orig + final fallbackToOrig = AttachmentModel.empty().copyWith( + storagePath: orig, + viewMode: AttachmentViewMode.cropped, + ); + expect(fallbackToOrig.effectiveStoragePath, orig); + }); + + test('copyWith properly updates thumbnailPath, croppedStoragePath, and viewMode', () { + final initial = AttachmentModel.empty().copyWith( + name: 'test', + extension: 'png', + companyId: 'comp-1', + ); + + final updated = initial.copyWith( + thumbnailPath: 'thumbs/1.webp', + croppedStoragePath: 'crops/1.png', + viewMode: AttachmentViewMode.original, + ); + + expect(updated.thumbnailPath, 'thumbs/1.webp'); + expect(updated.croppedStoragePath, 'crops/1.png'); + expect(updated.viewMode, AttachmentViewMode.original); + expect(updated.name, 'test'); + }); + + test('Equatable props comparison works as expected', () { + final a = AttachmentModel.empty().copyWith( + id: '1', + thumbnailPath: 'thumb.webp', + croppedStoragePath: 'crop.jpg', + viewMode: AttachmentViewMode.cropped, + ); + final b = AttachmentModel.empty().copyWith( + id: '1', + thumbnailPath: 'thumb.webp', + croppedStoragePath: 'crop.jpg', + viewMode: AttachmentViewMode.cropped, + ); + final c = AttachmentModel.empty().copyWith( + id: '1', + thumbnailPath: 'thumb.webp', + croppedStoragePath: 'crop.jpg', + viewMode: AttachmentViewMode.original, + ); + + expect(a, equals(b)); + expect(a, isNot(equals(c))); + }); + }); +}