Compare commits

...
4 Commits
Author SHA1 Message Date
brontomark 53496a2a9d aggiunto supporto al salvataggio rotazione immagini
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m55s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m29s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m43s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m15s
2026-10-15 13:11:51 +02:00
brontomark 0cc7c76df9 wow, cropped images e thumbnails
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m35s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m13s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 3m13s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m18s
2026-10-15 11:45:08 +02:00
brontomark ca67d86a71 sdf 2026-10-14 17:34:54 +02:00
brontomark 33e309909e fix CI
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m21s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m45s
Build and Release FLUX (Multi-Platform) / build-windows (push) Failing after 8m9s
Build and Release FLUX (Multi-Platform) / build-macos (push) Failing after 12m42s
2026-10-14 16:24:18 +02:00
14 changed files with 1132 additions and 143 deletions

No files matched your search

+31 -13
View File
@@ -57,16 +57,22 @@ jobs:
- name: Aggiorna Link Windows su Supabase
run: |
$TagVersion = "${{ github.ref_name }}".TrimStart('v')
$headers = @{
"apikey" = "${{ secrets.SUPABASE_SERVICE_KEY }}"
"Authorization" = "Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}"
"Content-Type" = "application/json"
$apiKey = "${{ secrets.SUPABASE_SERVICE_KEY }}"
if ([string]::IsNullOrWhiteSpace($apiKey)) {
$apiKey = "sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
}
$body = (@{
$body = @{
download_url = "https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/FluxInstaller.exe"
latest_version = $TagVersion
} | ConvertTo-Json)
Invoke-RestMethod -Uri "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.windows" -Method Patch -Headers $headers -Body $body -UserAgent "flux-runner"
} | ConvertTo-Json -Compress
[System.IO.File]::WriteAllText("$PWD\payload.json", $body, (New-Object System.Text.UTF8Encoding($false)))
curl.exe -i -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.windows" `
-H "apikey: $apiKey" `
-H "Authorization: Bearer $apiKey" `
-H "Content-Type: application/json" `
--data-binary "@payload.json"
Remove-Item -Force "$PWD\payload.json"
- name: Pulisci Workspace Windows
if: always()
@@ -107,9 +113,13 @@ jobs:
- name: Aggiorna Versione Web su Supabase
run: |
TagVersion="${GITHUB_REF_NAME#v}"
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
if [ -z "$API_KEY" ]; then
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
fi
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.web" \
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
-H "apikey: $API_KEY" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d "{\"latest_version\": \"$TagVersion\"}"
@@ -180,9 +190,13 @@ jobs:
- name: Aggiorna Link Linux su Supabase
run: |
TagVersion="${GITHUB_REF_NAME#v}"
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
if [ -z "$API_KEY" ]; then
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
fi
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.AppImage" \
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
-H "apikey: $API_KEY" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-x86_64.AppImage\", \"latest_version\": \"$TagVersion\"}"
@@ -230,8 +244,12 @@ jobs:
- name: Aggiorna Link macOS su Supabase
run: |
TagVersion="${GITHUB_REF_NAME#v}"
API_KEY="${{ secrets.SUPABASE_SERVICE_KEY }}"
if [ -z "$API_KEY" ]; then
API_KEY="sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo"
fi
curl -X PATCH "https://supabaseapi.catelli.it/rest/v1/app_config?platform=eq.macos" \
-H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \
-H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \
-H "apikey: $API_KEY" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-macOS.dmg\", \"latest_version\": \"$TagVersion\"}"
+29
View File
@@ -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;
}
}
}
@@ -360,6 +360,16 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
DeleteSpecificAttachmentEvent(targetFile),
);
},
onViewModeChanged: (targetFile, newMode) {
operationFilesBloc.add(
UpdateAttachmentViewModeEvent(targetFile, newMode),
);
},
onAttachmentUpdated: (updatedFile) {
operationFilesBloc.add(
AttachmentUpdatedEvent(updatedFile),
);
},
),
),
),
@@ -406,11 +416,12 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
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 +544,13 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
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 +689,13 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
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 +825,17 @@ class _SharedAttachmentsSectionState extends State<SharedAttachmentsSection> {
Widget build(BuildContext context) {
final theme = Theme.of(context);
return BlocBuilder<AttachmentsBloc, AttachmentsState>(
return BlocConsumer<AttachmentsBloc, AttachmentsState>(
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 +1447,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 +1466,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 +1487,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<AttachmentsRepository>();
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) {
@@ -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<AttachmentsEvent, AttachmentsState> {
final _repository = GetIt.I.get<AttachmentsRepository>();
StreamSubscription<List<AttachmentModel>>? _realtimeSubscription;
AttachmentsBloc({String? parentId, required AttachmentParentType parentType})
: super(
@@ -36,6 +37,9 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
on<DeleteSpecificAttachmentEvent>(_onDeleteSpecificAttachment);
on<SelectAllAttachmentsEvent>(_onSelectAllAttachments);
on<ClearAttachmentSelectionEvent>(_onClearAttachmentSelection);
on<RemoteAttachmentsUpdatedEvent>(_onRemoteAttachmentsUpdated);
on<UpdateAttachmentViewModeEvent>(_onUpdateAttachmentViewMode);
on<AttachmentUpdatedEvent>(_onAttachmentUpdated);
final currentCompanyId = GetIt.I.get<SessionCubit>().state.company?.id;
if (parentId != null && currentCompanyId != null) {
@@ -43,6 +47,12 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
}
}
@override
Future<void> close() {
_realtimeSubscription?.cancel();
return super.close();
}
FutureOr<void> _onParentEntitySaved(
ParentEntitySavedEvent event,
Emitter<AttachmentsState> emit,
@@ -65,7 +75,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
bytes: file.localBytes,
);
// Chiamiamo il metodo generico passando il parentId e il TYPE
return _repository.uploadAndRegisterFile(
parentId: event.newParentId,
parentType: state.parentType,
@@ -96,26 +105,75 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
Emitter<AttachmentsState> 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<AttachmentModel> 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<AttachmentsState> emit,
) {
emit(
state.copyWith(
status: AttachmentsStatus.ready,
remoteFiles: event.files,
error: null,
),
);
}
FutureOr<void> _onAddAttachments(
AddAttachmentsEvent event,
Emitter<AttachmentsState> emit,
) async {
@@ -132,32 +190,48 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
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 +245,31 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
// BIVIO 2: PRATICA ESISTENTE (Upload immediato)
emit(state.copyWith(status: AttachmentsStatus.uploading));
try {
final List<Future<void>> uploadTasks = event.files.map((file) {
return _repository.uploadAndRegisterFile(
parentId: currentId,
parentType: state.parentType,
pickedFile: file,
companyId: currentCompanyId,
bucket: _getBucketForParentType,
);
}).toList();
final List<Future<void>> 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 +310,9 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
// 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 +332,18 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
}
}
// 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 +362,22 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
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 +402,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
SelectAllAttachmentsEvent event,
Emitter<AttachmentsState> emit,
) {
// Prendiamo TUTTI i file (locali e remoti) e li buttiamo nei selezionati
emit(state.copyWith(selectedFiles: state.allFiles));
}
@@ -301,7 +409,6 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
ClearAttachmentSelectionEvent event,
Emitter<AttachmentsState> emit,
) {
// Svuotiamo brutalmente la lista
emit(state.copyWith(selectedFiles: []));
}
@@ -311,38 +418,36 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
) 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<Future<void>> linkTasks = [];
@@ -361,8 +466,17 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
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 +491,35 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
RenameAttachmentEvent event,
Emitter<AttachmentsState> 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 +535,68 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
Emitter<AttachmentsState> 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<void> _onUpdateAttachmentViewMode(
UpdateAttachmentViewModeEvent event,
Emitter<AttachmentsState> 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");
}
}
FutureOr<void> _onAttachmentUpdated(
AttachmentUpdatedEvent event,
Emitter<AttachmentsState> 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:
@@ -71,3 +71,28 @@ class DeleteSpecificAttachmentEvent extends AttachmentsEvent {
final AttachmentModel file;
const DeleteSpecificAttachmentEvent(this.file);
}
class RemoteAttachmentsUpdatedEvent extends AttachmentsEvent {
final List<AttachmentModel> files;
const RemoteAttachmentsUpdatedEvent(this.files);
@override
List<Object?> get props => [files];
}
class UpdateAttachmentViewModeEvent extends AttachmentsEvent {
final AttachmentModel file;
final AttachmentViewMode viewMode;
const UpdateAttachmentViewModeEvent(this.file, this.viewMode);
@override
List<Object?> get props => [file, viewMode];
}
class AttachmentUpdatedEvent extends AttachmentsEvent {
final AttachmentModel file;
const AttachmentUpdatedEvent(this.file);
@override
List<Object?> get props => [file];
}
@@ -1,7 +1,9 @@
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:flux/core/utils/image_utils.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
@@ -47,6 +49,28 @@ class AttachmentsRepository {
}
}
/// RECUPERA I FILE IN MODALITÀ REST (Immediato e affidabile)
Future<List<AttachmentModel>> 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<String, dynamic>))
.toList();
} catch (e) {
throw Exception("Impossibile recuperare gli allegati dal DB: $e");
}
}
/// RECUPERA I FILE IN TEMPO REALE
Stream<List<AttachmentModel>> getFilesStream(
String parentId,
@@ -75,7 +99,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 +111,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 +156,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 +221,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 = <String>[
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 +259,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 +268,107 @@ class AttachmentsRepository {
}
}
/// AGGIORNA LA MODALITÀ DI VISUALIZZAZIONE PREFERITA (cropped / original)
Future<void> 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",
);
}
}
/// 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<AttachmentModel> 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()) {
switch (extension.toLowerCase().replaceAll('.', '')) {
case 'pdf':
return 'application/pdf';
case 'png':
@@ -236,6 +376,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';
}
@@ -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<Object?> 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,
};
}
}
@@ -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,8 @@ 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;
final Function(AttachmentModel attachment)? onAttachmentUpdated;
const AttachmentViewerScreen({
super.key,
@@ -29,6 +33,8 @@ class AttachmentViewerScreen extends StatefulWidget {
this.onRenameAttachment,
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.',
@@ -44,10 +50,13 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
final FocusNode _focusNode = FocusNode();
bool _isLoading = true;
bool _isSavingRotation = false;
String? _errorMessage;
Uint8List? _fileBytes;
int _loadToken = 0;
int _rotationTurns = 0;
bool _showCropped = true;
final Map<String, Uint8List> _bytesCache = {};
AttachmentModel get _currentAttachment => _items[_currentIndex];
bool get isPdf =>
@@ -56,6 +65,33 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
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 +106,10 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
_currentIndex = 0;
}
if (_items.isNotEmpty) {
_showCropped = _computeInitialShowCropped(_currentAttachment);
}
_loadFile();
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -97,8 +137,10 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
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 +149,104 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
_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<AttachmentsRepository>();
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();
}
}
Future<void> _saveRotation() async {
final turns = _rotationTurns % 4;
if (turns == 0 || _isSavingRotation) return;
setState(() {
_isSavingRotation = true;
});
try {
final repository = GetIt.I.get<AttachmentsRepository>();
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) {
@@ -132,18 +272,47 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
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 +435,9 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
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 +492,64 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
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),
@@ -338,6 +560,38 @@ class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
});
},
),
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',
@@ -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,
),
),
),
),
@@ -53,6 +53,16 @@ class TicketListCard extends StatelessWidget {
DeleteSpecificAttachmentEvent(targetFile),
);
},
onViewModeChanged: (targetFile, newMode) {
operationFilesBloc.add(
UpdateAttachmentViewModeEvent(targetFile, newMode),
);
},
onAttachmentUpdated: (updatedFile) {
operationFilesBloc.add(
AttachmentUpdatedEvent(updatedFile),
);
},
),
),
),
+9 -3
View File
@@ -39,10 +39,16 @@ import 'package:supabase_flutter/supabase_flutter.dart';
final sl = GetIt.instance;
Future<void> 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<SupabaseClient>(Supabase.instance.client);
sl.registerSingleton<SharedPreferences>(
+1 -1
View File
@@ -1,7 +1,7 @@
name: flux
description: "Gestione attività negozio di telefonia"
publish_to: 'none'
version: 2.4.1+82
version: 2.5.1+85
environment:
sdk: ^3.11.3
+49
View File
@@ -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);
});
});
}
@@ -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)));
});
});
}