Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 1m37s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m38s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m24s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 10m50s
410 lines
13 KiB
Dart
410 lines
13 KiB
Dart
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';
|
|
|
|
enum Bucket {
|
|
documents('documents'),
|
|
companyDocuments('company_documents');
|
|
|
|
final String value;
|
|
const Bucket(this.value);
|
|
}
|
|
|
|
class AttachmentsRepository {
|
|
final _supabase = Supabase.instance.client;
|
|
|
|
/// Scarica i byte di un file direttamente da Supabase Storage
|
|
Future<Uint8List> downloadAttachmentBytes({
|
|
required String storagePath,
|
|
required Bucket bucket,
|
|
}) async {
|
|
try {
|
|
final Uint8List bytes = await _supabase.storage
|
|
.from(bucket.value)
|
|
.download(storagePath);
|
|
return bytes;
|
|
} catch (e) {
|
|
throw Exception("Impossibile scaricare il documento dal cloud: $e");
|
|
}
|
|
}
|
|
|
|
/// RESTITUISCE IL NOME DELLA COLONNA DB IN BASE AL TIPO
|
|
String _getColumnNameForParent(AttachmentParentType parentType) {
|
|
switch (parentType) {
|
|
case AttachmentParentType.operation:
|
|
return 'operation_id';
|
|
case AttachmentParentType.ticket:
|
|
return 'ticket_id';
|
|
case AttachmentParentType.customer:
|
|
return 'customer_id';
|
|
case AttachmentParentType.shippingDocument:
|
|
return 'shipping_document_id';
|
|
case AttachmentParentType.note:
|
|
return 'note_id';
|
|
case AttachmentParentType.customerOrder:
|
|
return 'customer_order_id';
|
|
}
|
|
}
|
|
|
|
/// 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,
|
|
AttachmentParentType parentType,
|
|
) {
|
|
final columnName = _getColumnNameForParent(parentType);
|
|
|
|
return _supabase
|
|
.from(Tables.attachments)
|
|
.stream(primaryKey: ['id'])
|
|
.eq(columnName, parentId)
|
|
.map(
|
|
(listOfMaps) =>
|
|
listOfMaps.map((map) => AttachmentModel.fromMap(map)).toList(),
|
|
);
|
|
}
|
|
|
|
/// CARICA IL FILE NELLO STORAGE E LO REGISTRA NEL DB
|
|
Future<void> uploadAndRegisterFile({
|
|
required String parentId,
|
|
required AttachmentParentType parentType,
|
|
required String companyId,
|
|
required Bucket bucket,
|
|
PlatformFile? pickedFile, // Ora è opzionale
|
|
Uint8List? rawBytes, // Alternativa: bytes grezzi
|
|
String? rawFileName, // Alternativa: nome del file
|
|
}) async {
|
|
// 🛡️ L'ASSERT NINJA: O c'è il pickedFile, o ci sono i byte e il nome.
|
|
assert(
|
|
pickedFile != null || (rawBytes != null && rawFileName != null),
|
|
'Devi passare o un PlatformFile, oppure rawBytes e rawFileName!',
|
|
);
|
|
|
|
try {
|
|
// 1. Normalizziamo i dati in base a cosa ci è stato passato
|
|
final Uint8List finalBytes;
|
|
final String finalFileName;
|
|
final int finalFileSize;
|
|
|
|
if (pickedFile != 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 = fileBytes;
|
|
finalFileName = pickedFile.name;
|
|
finalFileSize = pickedFile.size > 0 ? pickedFile.size : finalBytes.length;
|
|
} else {
|
|
finalBytes = rawBytes!;
|
|
finalFileName = rawFileName!;
|
|
finalFileSize = finalBytes.length;
|
|
}
|
|
|
|
// 2. Estraiamo l'estensione e puliamo il nome
|
|
final extension = finalFileName.contains('.')
|
|
? finalFileName.split('.').last
|
|
: '';
|
|
|
|
final cleanName = finalFileName
|
|
.replaceAll(RegExp(r'[^\w\s\.-]'), '')
|
|
.replaceAll(' ', '_');
|
|
|
|
// 3. Creiamo un path ordinato: idAzienda/tipoEntita/idEntita/timestamp_nomefile
|
|
final timestamp = DateTime.now().millisecondsSinceEpoch;
|
|
final storagePath =
|
|
'$companyId/${parentType.name}/$parentId/${timestamp}_$cleanName';
|
|
|
|
// 4. Upload su Supabase Storage
|
|
await _supabase.storage
|
|
.from(bucket.value)
|
|
.uploadBinary(
|
|
storagePath,
|
|
finalBytes,
|
|
fileOptions: FileOptions(
|
|
contentType: _guessContentType(extension),
|
|
upsert: true,
|
|
),
|
|
);
|
|
|
|
// 5. Creiamo la mappa per il DB dinamicamente
|
|
final Map<String, dynamic> insertData = {
|
|
'company_id': companyId,
|
|
'name': finalFileName.replaceAll('.$extension', ''),
|
|
'extension': extension,
|
|
'file_size': finalFileSize,
|
|
'storage_path': storagePath,
|
|
};
|
|
|
|
// Inseriamo l'ID nella colonna giusta!
|
|
final columnName = _getColumnNameForParent(parentType);
|
|
insertData[columnName] = parentId;
|
|
|
|
// 6. Salviamo su Postgres
|
|
await _supabase.from(Tables.attachments).insert(insertData);
|
|
} catch (e) {
|
|
throw Exception("Errore caricamento: $e");
|
|
}
|
|
}
|
|
|
|
/// ELIMINA IL FILE (Scollegamento intelligente)
|
|
Future<void> deleteFiles({
|
|
required List<AttachmentModel> files,
|
|
required AttachmentParentType currentContextType,
|
|
required Bucket bucket,
|
|
}) async {
|
|
if (files.isEmpty) return;
|
|
|
|
try {
|
|
for (var file in files) {
|
|
if (file.id == null) continue;
|
|
|
|
// 1. Capiamo quali collegamenti ha questo file attualmente
|
|
final currentLinks = {
|
|
AttachmentParentType.operation: file.operationId,
|
|
AttachmentParentType.ticket: file.ticketId,
|
|
AttachmentParentType.customer: file.customerId,
|
|
AttachmentParentType.shippingDocument: file.shippingDocumentId,
|
|
AttachmentParentType.note: file.noteId,
|
|
AttachmentParentType.customerOrder: file.customerOrderId,
|
|
};
|
|
|
|
// 2. Simuliamo la rimozione del collegamento per il contesto attuale
|
|
currentLinks[currentContextType] = null;
|
|
|
|
// 3. Controlliamo se rimangono altri ID valorizzati
|
|
final hasOtherActiveLinks = currentLinks.values.any(
|
|
(id) => id != null && id.isNotEmpty,
|
|
);
|
|
|
|
if (hasOtherActiveLinks) {
|
|
// A. Ci sono ancora altre entità che usano questo file!
|
|
// Scolleghiamolo SOLO dal contesto attuale mettendo a NULL la sua colonna
|
|
await _supabase
|
|
.from(Tables.attachments)
|
|
.update({currentContextType.dbColumn: null})
|
|
.eq('id', file.id!);
|
|
} else {
|
|
// B. Nessuno usa più questo file! ELIMINAZIONE FISICA TOTALE.
|
|
await _supabase.from(Tables.attachments).delete().eq('id', file.id!);
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
} catch (e) {
|
|
throw Exception("Errore nell'eliminazione dei file: $e");
|
|
}
|
|
}
|
|
|
|
/// RINOMINA UN FILE (Solo nel DB, non cambiamo il file fisico)
|
|
Future<void> renameAttachment(String fileId, String newName) async {
|
|
try {
|
|
await _supabase
|
|
.from(Tables.attachments)
|
|
.update({'name': newName})
|
|
.eq('id', fileId);
|
|
} catch (e) {
|
|
throw Exception("Errore nella rinomina del file: $e");
|
|
}
|
|
}
|
|
|
|
/// ASSOCIA UN FILE A UN'ALTRA ENTITÀ (Modifica il record esistente)
|
|
Future<void> linkFileToEntity({
|
|
required String fileId,
|
|
required AttachmentParentType targetType,
|
|
required String targetId,
|
|
}) async {
|
|
try {
|
|
await _supabase
|
|
.from(Tables.attachments)
|
|
.update({targetType.dbColumn: targetId})
|
|
.eq('id', fileId);
|
|
} catch (e) {
|
|
throw Exception("Errore nel collegamento del file: $e");
|
|
}
|
|
}
|
|
|
|
/// 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().replaceAll('.', '')) {
|
|
case 'pdf':
|
|
return 'application/pdf';
|
|
case 'png':
|
|
return 'image/png';
|
|
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';
|
|
}
|
|
}
|
|
}
|