From 53496a2a9dd57aafe4fc474749ce0b2d8567fce5 Mon Sep 17 00:00:00 2001 From: Mark M2 Macbook Date: Thu, 15 Oct 2026 13:11:51 +0200 Subject: [PATCH] aggiunto supporto al salvataggio rotazione immagini --- lib/core/utils/image_utils.dart | 29 ++++++ .../shared_forms/attachments_section.dart | 5 + .../attachments/blocs/attachments_bloc.dart | 25 +++++ .../attachments/blocs/attachments_events.dart | 8 ++ .../data/attachments_repository.dart | 82 +++++++++++++++++ .../ui/attachment_viewer_screen.dart | 91 +++++++++++++++++++ .../tickets/ui/widgets/ticket_list_card.dart | 5 + pubspec.yaml | 2 +- test/core/utils/image_utils_test.dart | 49 ++++++++++ 9 files changed, 295 insertions(+), 1 deletion(-) create mode 100644 test/core/utils/image_utils_test.dart diff --git a/lib/core/utils/image_utils.dart b/lib/core/utils/image_utils.dart index 22a02b0..445d065 100644 --- a/lib/core/utils/image_utils.dart +++ b/lib/core/utils/image_utils.dart @@ -46,4 +46,33 @@ class ImageUtils { return bytes; } } + + /// Ruota fisicamente i byte di un'immagine di un numero di quarti di giro (90° * quarterTurns). + static Uint8List rotateBytes( + Uint8List bytes, { + required int quarterTurns, + String? extension, + }) { + final turns = quarterTurns % 4; + if (turns == 0) return bytes; + + try { + final image = img.decodeImage(bytes); + if (image == null) return bytes; + + final angle = turns * 90; + final rotated = img.copyRotate(image, angle: angle); + + final ext = extension?.toLowerCase().replaceAll('.', ''); + final isPng = ext == 'png' || (ext == null && image.hasAlpha); + + if (isPng) { + return Uint8List.fromList(img.encodePng(rotated)); + } else { + return Uint8List.fromList(img.encodeJpg(rotated, quality: 92)); + } + } catch (_) { + return bytes; + } + } } diff --git a/lib/core/widgets/shared_forms/attachments_section.dart b/lib/core/widgets/shared_forms/attachments_section.dart index 3743297..e9ef0fe 100644 --- a/lib/core/widgets/shared_forms/attachments_section.dart +++ b/lib/core/widgets/shared_forms/attachments_section.dart @@ -365,6 +365,11 @@ class _SharedAttachmentsSectionState extends State { UpdateAttachmentViewModeEvent(targetFile, newMode), ); }, + onAttachmentUpdated: (updatedFile) { + operationFilesBloc.add( + AttachmentUpdatedEvent(updatedFile), + ); + }, ), ), ), diff --git a/lib/features/attachments/blocs/attachments_bloc.dart b/lib/features/attachments/blocs/attachments_bloc.dart index e32a0f3..d1abe38 100644 --- a/lib/features/attachments/blocs/attachments_bloc.dart +++ b/lib/features/attachments/blocs/attachments_bloc.dart @@ -39,6 +39,7 @@ class AttachmentsBloc extends Bloc { on(_onClearAttachmentSelection); on(_onRemoteAttachmentsUpdated); on(_onUpdateAttachmentViewMode); + on(_onAttachmentUpdated); final currentCompanyId = GetIt.I.get().state.company?.id; if (parentId != null && currentCompanyId != null) { @@ -572,6 +573,30 @@ class AttachmentsBloc extends Bloc { } } + FutureOr _onAttachmentUpdated( + AttachmentUpdatedEvent event, + Emitter emit, + ) { + final updatedRemote = state.remoteFiles.map((f) { + if (f.id == event.file.id) { + return event.file; + } + return f; + }).toList(); + + final updatedLocal = state.localFiles.map((f) { + if (f.id == event.file.id || (f.id == null && f.name == event.file.name)) { + return event.file; + } + return f; + }).toList(); + + emit(state.copyWith( + remoteFiles: updatedRemote, + localFiles: updatedLocal, + )); + } + 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 e00ffbd..5b24b14 100644 --- a/lib/features/attachments/blocs/attachments_events.dart +++ b/lib/features/attachments/blocs/attachments_events.dart @@ -88,3 +88,11 @@ class UpdateAttachmentViewModeEvent extends AttachmentsEvent { @override List get props => [file, viewMode]; } + +class AttachmentUpdatedEvent extends AttachmentsEvent { + final AttachmentModel file; + const AttachmentUpdatedEvent(this.file); + + @override + List get props => [file]; +} diff --git a/lib/features/attachments/data/attachments_repository.dart b/lib/features/attachments/data/attachments_repository.dart index 4b53555..751b7d0 100644 --- a/lib/features/attachments/data/attachments_repository.dart +++ b/lib/features/attachments/data/attachments_repository.dart @@ -3,6 +3,7 @@ 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:flux/core/utils/image_utils.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:flux/features/attachments/blocs/attachments_bloc.dart'; @@ -284,6 +285,87 @@ class AttachmentsRepository { } } + /// Salva la rotazione permanente del file originale aggiornando storage_path con un nuovo timestamp. + /// Questo farà scattare il trigger Postgres per il worker Python (autocrop e thumbnail). + Future rotateAttachment({ + required AttachmentModel attachment, + required int quarterTurns, + required Bucket bucket, + }) async { + final turns = quarterTurns % 4; + if (turns == 0) return attachment; + if (attachment.storagePath == null || attachment.storagePath!.isEmpty) { + throw Exception("Impossibile ruotare: storagePath mancante."); + } + + try { + // 1. Recuperiamo i byte originali + Uint8List originalBytes; + if (attachment.localBytes != null) { + originalBytes = attachment.localBytes!; + } else { + originalBytes = await downloadAttachmentBytes( + storagePath: attachment.storagePath!, + bucket: bucket, + ); + } + + // 2. Ruotiamo fisicamente i pixel + final rotatedBytes = ImageUtils.rotateBytes( + originalBytes, + quarterTurns: turns, + extension: attachment.extension, + ); + + // 3. Generiamo il nuovo storagePath con un nuovo timestamp per evitare cache e triggerare l'update + final oldPath = attachment.storagePath!; + final lastSlash = oldPath.lastIndexOf('/'); + final dir = lastSlash != -1 ? oldPath.substring(0, lastSlash) : ''; + final filename = + lastSlash != -1 ? oldPath.substring(lastSlash + 1) : oldPath; + final nameWithoutTimestamp = + filename.replaceFirst(RegExp(r'^\d+_'), ''); + final newTimestamp = DateTime.now().millisecondsSinceEpoch; + final newStoragePath = dir.isNotEmpty + ? '$dir/${newTimestamp}_$nameWithoutTimestamp' + : '${newTimestamp}_$nameWithoutTimestamp'; + + // 4. Carichiamo il nuovo file ruotato nello storage + await _supabase.storage + .from(bucket.value) + .uploadBinary( + newStoragePath, + rotatedBytes, + fileOptions: FileOptions( + contentType: _guessContentType(attachment.extension), + upsert: true, + ), + ); + + // 5. Aggiorniamo il record su Postgres (triggera il worker Python) + final updateData = { + 'storage_path': newStoragePath, + 'file_size': rotatedBytes.length, + }; + + if (attachment.id != null) { + await _supabase + .from(Tables.attachments) + .update(updateData) + .eq('id', attachment.id!); + } + + // 6. Restituiamo il modello aggiornato + return attachment.copyWith( + storagePath: newStoragePath, + fileSize: rotatedBytes.length, + localBytes: rotatedBytes, + ); + } catch (e) { + throw Exception("Errore durante il salvataggio della rotazione: $e"); + } + } + // Helper per indovinare il content-type base String _guessContentType(String extension) { switch (extension.toLowerCase().replaceAll('.', '')) { diff --git a/lib/features/attachments/ui/attachment_viewer_screen.dart b/lib/features/attachments/ui/attachment_viewer_screen.dart index d3b11f2..dc18aca 100644 --- a/lib/features/attachments/ui/attachment_viewer_screen.dart +++ b/lib/features/attachments/ui/attachment_viewer_screen.dart @@ -22,6 +22,7 @@ class AttachmentViewerScreen extends StatefulWidget { final VoidCallback? onDelete; final Function(AttachmentModel attachment)? onDeleteAttachment; final Function(AttachmentModel attachment, AttachmentViewMode viewMode)? onViewModeChanged; + final Function(AttachmentModel attachment)? onAttachmentUpdated; const AttachmentViewerScreen({ super.key, @@ -33,6 +34,7 @@ class AttachmentViewerScreen extends StatefulWidget { this.onDelete, this.onDeleteAttachment, this.onViewModeChanged, + this.onAttachmentUpdated, }) : assert( attachment != null || (attachments != null && attachments.length > 0), 'Devi fornire un allegato o una lista di allegati non vuota.', @@ -48,6 +50,7 @@ class _AttachmentViewerScreenState extends State { final FocusNode _focusNode = FocusNode(); bool _isLoading = true; + bool _isSavingRotation = false; String? _errorMessage; Uint8List? _fileBytes; int _loadToken = 0; @@ -188,6 +191,62 @@ class _AttachmentViewerScreenState extends State { } } + Future _saveRotation() async { + final turns = _rotationTurns % 4; + if (turns == 0 || _isSavingRotation) return; + + setState(() { + _isSavingRotation = true; + }); + + try { + final repository = GetIt.I.get(); + final updated = await repository.rotateAttachment( + attachment: _currentAttachment, + quarterTurns: turns, + bucket: Bucket.documents, + ); + + if (!mounted) return; + + setState(() { + _items[_currentIndex] = updated; + _rotationTurns = 0; + _showCropped = false; // Mostra l'originale ruotato appena salvato + _isSavingRotation = false; + if (updated.storagePath != null && updated.localBytes != null) { + _bytesCache[updated.storagePath!] = updated.localBytes!; + } + if (updated.localBytes != null) { + _fileBytes = updated.localBytes; + } + }); + + widget.onAttachmentUpdated?.call(updated); + + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text( + 'Rotazione salvata! Il server aggiornerà ritaglio e anteprima.', + ), + backgroundColor: Colors.green, + duration: Duration(seconds: 4), + ), + ); + } catch (e) { + if (!mounted) return; + setState(() { + _isSavingRotation = false; + }); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Errore durante il salvataggio della rotazione: $e'), + backgroundColor: Colors.red, + ), + ); + } + } + KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) { if (event is KeyDownEvent) { if (event.logicalKey == LogicalKeyboardKey.arrowLeft) { @@ -501,6 +560,38 @@ class _AttachmentViewerScreenState extends State { }); }, ), + if (!isPdf && _rotationTurns % 4 != 0) + _isSavingRotation + ? const Padding( + padding: EdgeInsets.symmetric(horizontal: 10), + child: Center( + child: SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ), + ), + ) + : Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4), + child: FilledButton.icon( + style: FilledButton.styleFrom( + backgroundColor: Colors.green.shade700, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(horizontal: 10), + visualDensity: VisualDensity.compact, + ), + icon: const Icon(Icons.check, size: 16), + label: const Text( + 'Salva', + style: TextStyle(fontWeight: FontWeight.bold), + ), + onPressed: _saveRotation, + ), + ), IconButton( icon: const Icon(Icons.download), tooltip: 'Scarica', diff --git a/lib/features/tickets/ui/widgets/ticket_list_card.dart b/lib/features/tickets/ui/widgets/ticket_list_card.dart index 5eaa4d1..e5501a9 100644 --- a/lib/features/tickets/ui/widgets/ticket_list_card.dart +++ b/lib/features/tickets/ui/widgets/ticket_list_card.dart @@ -58,6 +58,11 @@ class TicketListCard extends StatelessWidget { UpdateAttachmentViewModeEvent(targetFile, newMode), ); }, + onAttachmentUpdated: (updatedFile) { + operationFilesBloc.add( + AttachmentUpdatedEvent(updatedFile), + ); + }, ), ), ), diff --git a/pubspec.yaml b/pubspec.yaml index e5f6c74..66546f1 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.0+84 +version: 2.5.1+85 environment: sdk: ^3.11.3 diff --git a/test/core/utils/image_utils_test.dart b/test/core/utils/image_utils_test.dart new file mode 100644 index 0000000..e89e902 --- /dev/null +++ b/test/core/utils/image_utils_test.dart @@ -0,0 +1,49 @@ +import 'dart:typed_data'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flux/core/utils/image_utils.dart'; +import 'package:image/image.dart' as img; + +void main() { + group('ImageUtils Tests', () { + test('rotateBytes with quarterTurns 0 or 4 returns original bytes', () { + final dummy = Uint8List.fromList([1, 2, 3, 4]); + expect(ImageUtils.rotateBytes(dummy, quarterTurns: 0), equals(dummy)); + expect(ImageUtils.rotateBytes(dummy, quarterTurns: 4), equals(dummy)); + }); + + test('rotateBytes correctly rotates an image by 90 degrees', () { + // Creiamo un'immagine 10x20 (larghezza 10, altezza 20) + final testImg = img.Image(width: 10, height: 20); + final encodedPng = Uint8List.fromList(img.encodePng(testImg)); + + // Ruotiamo di 1 quarto (90°) + final rotatedBytes = ImageUtils.rotateBytes( + encodedPng, + quarterTurns: 1, + extension: 'png', + ); + + final decoded = img.decodeImage(rotatedBytes); + expect(decoded, isNotNull); + // Dopo 90 gradi di rotazione, larghezza e altezza devono invertirsi (20x10) + expect(decoded!.width, 20); + expect(decoded.height, 10); + }); + + test('rotateBytes correctly rotates an image by 180 degrees', () { + final testImg = img.Image(width: 15, height: 30); + final encodedPng = Uint8List.fromList(img.encodePng(testImg)); + + final rotatedBytes = ImageUtils.rotateBytes( + encodedPng, + quarterTurns: 2, + extension: 'png', + ); + + final decoded = img.decodeImage(rotatedBytes); + expect(decoded, isNotNull); + expect(decoded!.width, 15); + expect(decoded.height, 30); + }); + }); +}