b
This commit is contained in:
1 parent
66667fb440
commit
409c064902
10 files changed
+346
-449
No files matched your search
+82
-7
@@ -140,14 +140,19 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
),
|
||||
Expanded(
|
||||
flex: 5,
|
||||
child: Text(
|
||||
operation.type,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: context.primaryText,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8.0,
|
||||
),
|
||||
child: _buildBadgeList(
|
||||
operation.details
|
||||
.map((d) => d.type)
|
||||
.whereType<String>()
|
||||
.where(
|
||||
(t) => t.trim().isNotEmpty,
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
@@ -172,4 +177,74 @@ class _LatestOperationsCardContent extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBadgeList(List<String> types) {
|
||||
if (types.isEmpty) {
|
||||
return const Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: _OperationTypeBadge(label: 'N/A'),
|
||||
);
|
||||
}
|
||||
|
||||
return Wrap(
|
||||
spacing: 4,
|
||||
runSpacing: 4,
|
||||
children: types.map((t) => _OperationTypeBadge(label: t)).toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _OperationTypeBadge extends StatelessWidget {
|
||||
final String label;
|
||||
|
||||
const _OperationTypeBadge({required this.label});
|
||||
|
||||
Color _getBadgeColor(String type) {
|
||||
switch (type.toUpperCase()) {
|
||||
case 'FIN':
|
||||
case 'FINANZIAMENTO':
|
||||
return Colors.deepPurple;
|
||||
case 'TELEPASS':
|
||||
return Colors.amber.shade800;
|
||||
case 'ENERGY':
|
||||
case 'ENERGIA':
|
||||
return Colors.orange.shade800;
|
||||
case 'ENTERTAINMENT':
|
||||
return Colors.pinkAccent.shade700;
|
||||
case 'AL':
|
||||
case 'MNP':
|
||||
return Colors.indigo;
|
||||
case 'NIP':
|
||||
case 'FWA':
|
||||
return Colors.cyan.shade800;
|
||||
case 'FIBRA':
|
||||
case 'MOBILE':
|
||||
return Colors.blue.shade700;
|
||||
default:
|
||||
return Colors.blueGrey;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = _getBadgeColor(label);
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: color.withValues(alpha: 0.3), width: 1),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
letterSpacing: 0.2,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
|
||||
import 'package:flux/features/operations/models/operation_detail_model.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
|
||||
part 'operation_details_list_state.dart';
|
||||
|
||||
class OperationDetailsListCubit extends Cubit<OperationDetailsListState> {
|
||||
final OperationFormCubit _operationFormCubit = sl<OperationFormCubit>();
|
||||
|
||||
OperationDetailsListCubit(List<OperationDetailModel> details)
|
||||
: super(OperationDetailsListState(details: details));
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
part of 'operation_details_list_cubit.dart';
|
||||
|
||||
enum OperationDetailsListStatus {
|
||||
initial,
|
||||
loading,
|
||||
ready,
|
||||
saving,
|
||||
success,
|
||||
failure,
|
||||
}
|
||||
|
||||
class OperationDetailsListState extends Equatable {
|
||||
final OperationDetailsListStatus status;
|
||||
final List<OperationDetailModel> details;
|
||||
final String? errorMessage;
|
||||
|
||||
const OperationDetailsListState({
|
||||
this.status = OperationDetailsListStatus.initial,
|
||||
this.details = const [],
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
OperationDetailsListState copyWith({
|
||||
OperationDetailsListStatus? status,
|
||||
List<OperationDetailModel>? details,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return OperationDetailsListState(
|
||||
status: status ?? this.status,
|
||||
details: details ?? this.details,
|
||||
errorMessage: errorMessage,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, details, errorMessage];
|
||||
}
|
||||
@@ -7,15 +7,13 @@ import 'package:flux/features/master_data/providers/models/provider_model_extens
|
||||
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
|
||||
part 'operation_form_state.dart';
|
||||
|
||||
class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
final OperationsRepository _repository = GetIt.I<OperationsRepository>();
|
||||
final SessionCubit _sessionCubit = GetIt.I<SessionCubit>();
|
||||
final Uuid _uuid = const Uuid();
|
||||
final OperationsRepository _repository = sl<OperationsRepository>();
|
||||
final SessionCubit _sessionCubit = sl<SessionCubit>();
|
||||
|
||||
OperationFormCubit({
|
||||
StaffMemberModel? createdBy,
|
||||
@@ -48,7 +46,7 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
} else if (operationId != null) {
|
||||
emit(state.copyWith(status: OperationFormStatus.loading));
|
||||
try {
|
||||
final operation = await _repository.fetchOperationById(operationId);
|
||||
final operation = await _repository.getOperationById(operationId);
|
||||
emit(
|
||||
state.copyWith(
|
||||
operation: operation,
|
||||
@@ -66,13 +64,9 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
} else {
|
||||
// NUOVA PRATICA: Creiamo un nuovo Batch UUID
|
||||
final currentStore = _sessionCubit.state.currentStore;
|
||||
final companyId = _sessionCubit.state.company?.id ?? '';
|
||||
final newOperation = state.operation.copyWith(
|
||||
companyId: companyId,
|
||||
storeId: currentStore?.id,
|
||||
status: OperationStatus.success,
|
||||
reference: '',
|
||||
batchUuid: _uuid.v4(),
|
||||
final newOperation = await _repository.createNewOperation(
|
||||
currentStore: currentStore!,
|
||||
createdById: state.operation.staffId!,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -91,41 +85,9 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
}
|
||||
}
|
||||
|
||||
// --- LOGICA BATCH ---
|
||||
|
||||
void _prepareNextOperationInBatch() {
|
||||
final current = state.operation;
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.ready,
|
||||
operation: OperationModel(
|
||||
companyId: current.companyId,
|
||||
storeId: current.storeId,
|
||||
storeDisplayName: current.storeDisplayName,
|
||||
// 🥷 REINSERIAMO LO STAFF (Il "colpevole" era qui)
|
||||
staffId: current.staffId,
|
||||
staffDisplayName: current.staffDisplayName,
|
||||
|
||||
batchUuid: current.batchUuid,
|
||||
customerId: current.customerId,
|
||||
customer: current.customer,
|
||||
reference: current.reference,
|
||||
status: OperationStatus.draft,
|
||||
createdAt: DateTime.now(),
|
||||
// Mantieni isBusiness se vuoi che rimanga coerente col cliente
|
||||
isBusiness: current.isBusiness,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// --- SALVATAGGIO ---
|
||||
|
||||
Future<void> saveOperation({
|
||||
required OperationStatus targetStatus,
|
||||
required bool keepAdding,
|
||||
}) async {
|
||||
Future<void> saveOperation({required OperationStatus targetStatus}) async {
|
||||
emit(
|
||||
state.copyWith(status: OperationFormStatus.saving, errorMessage: null),
|
||||
);
|
||||
@@ -146,33 +108,13 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
);
|
||||
}
|
||||
}
|
||||
final savedOperation = await _repository.saveFullOperation(
|
||||
operation: operationToSave,
|
||||
await _repository.updateOperation(operationToSave);
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.success,
|
||||
operation: operationToSave, // Aggiorniamo con l'ID restituito dal DB
|
||||
),
|
||||
);
|
||||
|
||||
if (keepAdding) {
|
||||
// Salviamo nella "memoria" del batch le pratiche create finora
|
||||
final updatedBatchList = List<OperationModel>.from(
|
||||
state.savedBatchOperations,
|
||||
)..add(savedOperation);
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.successAndAddAnother,
|
||||
savedBatchOperations: updatedBatchList,
|
||||
),
|
||||
);
|
||||
|
||||
// Pulisce i campi per la prossima operazione
|
||||
_prepareNextOperationInBatch();
|
||||
} else {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.success,
|
||||
operation: savedOperation, // Aggiorniamo con l'ID restituito dal DB
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
@@ -183,36 +125,10 @@ class OperationFormCubit extends Cubit<OperationFormState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> saveOperationDraft() async {
|
||||
try {
|
||||
final operationToSave = state.operation;
|
||||
if (operationToSave.customerId == null ||
|
||||
operationToSave.customerId!.isEmpty) {
|
||||
throw Exception('Seleziona un cliente prima di poter usare il QR');
|
||||
}
|
||||
final savedOperation = await _repository.saveFullOperation(
|
||||
operation: operationToSave,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
operation: savedOperation,
|
||||
status: OperationFormStatus.ready,
|
||||
),
|
||||
);
|
||||
return savedOperation.id;
|
||||
} catch (e) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
status: OperationFormStatus.failure,
|
||||
errorMessage: e.toString(),
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// --- GESTIONE DEI CAMPI IN TEMPO REALE ---
|
||||
|
||||
void updateDetails
|
||||
|
||||
void updateFields({
|
||||
String? reference,
|
||||
String? note,
|
||||
|
||||
@@ -1,27 +1,16 @@
|
||||
part of 'operation_form_cubit.dart';
|
||||
|
||||
enum OperationFormStatus {
|
||||
initial,
|
||||
loading,
|
||||
ready,
|
||||
saving,
|
||||
success,
|
||||
successAndAddAnother, // Nuovo stato in stile Ticket!
|
||||
failure,
|
||||
}
|
||||
enum OperationFormStatus { initial, loading, ready, saving, success, failure }
|
||||
|
||||
class OperationFormState extends Equatable {
|
||||
final OperationFormStatus status;
|
||||
final OperationModel operation;
|
||||
final String? errorMessage;
|
||||
// Teniamo traccia delle operazioni salvate in questa sessione (per UI riepilogo)
|
||||
final List<OperationModel> savedBatchOperations;
|
||||
|
||||
const OperationFormState({
|
||||
this.status = OperationFormStatus.initial,
|
||||
required this.operation,
|
||||
this.errorMessage,
|
||||
this.savedBatchOperations = const [],
|
||||
});
|
||||
|
||||
OperationFormState copyWith({
|
||||
@@ -34,15 +23,9 @@ class OperationFormState extends Equatable {
|
||||
status: status ?? this.status,
|
||||
operation: operation ?? this.operation,
|
||||
errorMessage: errorMessage,
|
||||
savedBatchOperations: savedBatchOperations ?? this.savedBatchOperations,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
status,
|
||||
operation,
|
||||
errorMessage,
|
||||
savedBatchOperations,
|
||||
];
|
||||
List<Object?> get props => [status, operation, errorMessage];
|
||||
}
|
||||
@@ -1,48 +1,48 @@
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/enums_and_consts/consts.dart';
|
||||
import 'package:flux/core/utils/extensions.dart';
|
||||
import 'package:flux/features/attachments/models/attachment_model.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:flux/features/master_data/store/models/store_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_detail_model.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
import 'package:flux/features/operations/models/paginated_operations.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import '../models/operation_model.dart';
|
||||
|
||||
class OperationsRepositoryOld {
|
||||
final _supabase = Supabase.instance.client;
|
||||
final companyId = GetIt.I.get<SessionCubit>().state.company!.id;
|
||||
class OperationsRepository {
|
||||
final SupabaseClient _supabase = sl<SupabaseClient>();
|
||||
|
||||
// --- RECUPERO SINGOLO SERVIZIO CON JOIN COMPLETO ---
|
||||
Future<OperationModel> fetchOperationById(String id) async {
|
||||
Future<OperationModel?> getOperationById(String id) async {
|
||||
try {
|
||||
final response = await _supabase
|
||||
.from(Tables.operations)
|
||||
.select('''
|
||||
*,
|
||||
${Tables.customers}(*),
|
||||
${Tables.stores}(name),
|
||||
${Tables.staffMembers}(name),
|
||||
${Tables.providers}(name),
|
||||
${Tables.models}(name_with_brand),
|
||||
${Tables.attachments}(*)
|
||||
''')
|
||||
*,
|
||||
${Tables.customers}(*),
|
||||
${Tables.stores}(*),
|
||||
${Tables.staffMembers}(*),
|
||||
${Tables.attachments}(*),
|
||||
${Tables.operationDetails}(
|
||||
*,
|
||||
${Tables.providers}(*),
|
||||
${Tables.models}(*)
|
||||
)
|
||||
''')
|
||||
.eq('id', id)
|
||||
.single();
|
||||
|
||||
debugPrint('response: $response');
|
||||
return OperationModel.fromMap(response);
|
||||
} catch (e) {
|
||||
throw Exception('Errore nel caricamento del servizio: $e');
|
||||
} on Exception catch (e) {
|
||||
debugPrint('response error: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 🥷 2. RECUPERO PAGINATO ASSOLUTO CON CONTEGGIO TOTALI
|
||||
Future<PaginatedOperations> fetchPaginatedOperations({
|
||||
required String companyId,
|
||||
String? storeId,
|
||||
String? staffId,
|
||||
String? providerId,
|
||||
required int page, // Usiamo 'page' (1, 2, 3...) invece di 'offset'
|
||||
int itemsPerPage = 25, // Default a 25 elementi per pagina
|
||||
required int page,
|
||||
int itemsPerPage = 20,
|
||||
String? searchTerm,
|
||||
DateTimeRange? dateRange,
|
||||
}) async {
|
||||
@@ -56,14 +56,17 @@ class OperationsRepositoryOld {
|
||||
var query = _supabase
|
||||
.from(Tables.operations)
|
||||
.select('''
|
||||
*,
|
||||
${Tables.customers}(*),
|
||||
${Tables.stores}(name),
|
||||
${Tables.providers}(*),
|
||||
${Tables.models}(name_with_brand),
|
||||
${Tables.staffMembers}(name),
|
||||
${Tables.attachments}(*)
|
||||
''')
|
||||
*,
|
||||
${Tables.customers}(*),
|
||||
${Tables.stores}(*),
|
||||
${Tables.staffMembers}(*),
|
||||
${Tables.attachments}(*),
|
||||
${Tables.operationDetails}(
|
||||
*,
|
||||
${Tables.providers}(*),
|
||||
${Tables.models}(*)
|
||||
)
|
||||
''')
|
||||
.eq('company_id', companyId);
|
||||
|
||||
// Filtro Range Date
|
||||
@@ -127,6 +130,7 @@ class OperationsRepositoryOld {
|
||||
totalCount: totalCount,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('Errore nel recupero della pagina $page: $e');
|
||||
throw Exception('Errore nel recupero della pagina $page: $e');
|
||||
}
|
||||
}
|
||||
@@ -143,221 +147,54 @@ class OperationsRepositoryOld {
|
||||
.limit(limit);
|
||||
}
|
||||
|
||||
// --- SALVATAGGIO COMPLETO (PRIMA PADRE, POI FIGLI) ---
|
||||
Future<OperationModel> saveFullOperation({
|
||||
required OperationModel operation,
|
||||
Future<OperationModel> createNewOperation({
|
||||
required StoreModel currentStore,
|
||||
required String createdById,
|
||||
}) async {
|
||||
try {
|
||||
// 1. Salvataggio classico dell'operazione corrente
|
||||
final response = await _supabase
|
||||
final res = await _supabase
|
||||
.from(Tables.operations)
|
||||
.upsert(operation.toMap())
|
||||
.select(
|
||||
'*, ${Tables.providers}(*), ${Tables.models}(*), ${Tables.stores}(*), ${Tables.staffMembers}(*), ${Tables.customers}(*), ${Tables.attachments}(*)',
|
||||
.insert(
|
||||
OperationModel.empty()
|
||||
.copyWith(
|
||||
storeId: currentStore.id,
|
||||
staffId: createdById,
|
||||
companyId: currentStore.companyId,
|
||||
)
|
||||
.toMap(),
|
||||
)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
final savedOperation = OperationModel.fromMap(response);
|
||||
|
||||
// 2. ALLINEAMENTO BATCH SEMPRE ATTIVO!
|
||||
if (operation.batchUuid.isNotEmpty) {
|
||||
await _supabase
|
||||
.from(Tables.operations)
|
||||
.update({'note': operation.note}) // Spalmiamo la nota attuale
|
||||
.eq(
|
||||
'batch_uuid',
|
||||
operation.batchUuid,
|
||||
); // Su tutte le pratiche di questo scontrino
|
||||
}
|
||||
|
||||
return savedOperation;
|
||||
} catch (e) {
|
||||
throw Exception("Errore nel salvataggio dell'operazione: $e");
|
||||
return OperationModel.fromMap(res);
|
||||
} on Exception catch (e) {
|
||||
debugPrint('ERRORE CREAZIONE OPERAZIONE: $e');
|
||||
throw Exception('Errore nella creazione dell\'operazione: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// --- ELIMINAZIONE ---
|
||||
Future<void> deleteOperation(String id) async {
|
||||
try {
|
||||
await _supabase.from(Tables.operations).delete().eq('id', id);
|
||||
} catch (e) {
|
||||
throw Exception('$e');
|
||||
debugPrint('ERRORE CANCELLAZIONE OPERAZIONE: $e');
|
||||
throw Exception('Errore nella cancellazione dell\'operazione: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// --- RECUPERO TIPI CONTENUTI PIÙ FREQUENTI PER AUTOCOMPLETE ---
|
||||
Future<List<String>> fetchTopEntertainmentTypes(String companyId) async {
|
||||
try {
|
||||
// Cerchiamo i tipi più frequenti associati ai servizi di questa company
|
||||
// Nota: dobbiamo passare attraverso la tabella 'operation' per filtrare per company_id
|
||||
final response = await _supabase
|
||||
.from(Tables.operations)
|
||||
.select('description')
|
||||
.eq('company_id', companyId)
|
||||
.eq('type', 'Entertainment')
|
||||
.limit(50); // Prendiamo un campione
|
||||
|
||||
// Logica rapida per contare le occorrenze e prendere i primi 5
|
||||
final Map<String, int> counts = {};
|
||||
for (var item in (response as List)) {
|
||||
final description = item['description'] as String;
|
||||
counts[description] = (counts[description] ?? 0) + 1;
|
||||
}
|
||||
|
||||
var sortedKeys = counts.keys.toList()
|
||||
..sort((a, b) => counts[b]!.compareTo(counts[a]!));
|
||||
|
||||
return sortedKeys.take(5).toList();
|
||||
} catch (e) {
|
||||
return [
|
||||
"Netflix",
|
||||
"DAZN",
|
||||
"Disney+",
|
||||
"Sky",
|
||||
]; // Fallback se non c'è ancora storia
|
||||
}
|
||||
}
|
||||
|
||||
/// Ascolta in tempo reale i file caricati per una pratica
|
||||
Stream<List<AttachmentModel>> getOperationFilesStream(String operationId) {
|
||||
return _supabase
|
||||
.from(Tables.attachments)
|
||||
.stream(primaryKey: ['id'])
|
||||
.eq('operation_id', operationId)
|
||||
.order('created_at', ascending: false)
|
||||
.map(
|
||||
(listOfMaps) =>
|
||||
listOfMaps.map((map) => AttachmentModel.fromMap(map)).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<AttachmentModel> uploadAndRegisterOperationFile({
|
||||
required String operationId,
|
||||
required PlatformFile pickedFile,
|
||||
}) async {
|
||||
final cleanFileName = pickedFile.name.replaceAll(
|
||||
RegExp(r'[^a-zA-Z0-9\.\-]'),
|
||||
'_',
|
||||
);
|
||||
final storagePath =
|
||||
'$companyId/operations/$operationId/${DateTime.now().millisecondsSinceEpoch}_$cleanFileName';
|
||||
final int fileSize = pickedFile.size;
|
||||
final fileToSave = AttachmentModel(
|
||||
companyId: GetIt.I.get<SessionCubit>().state.company!.id!,
|
||||
operationId: operationId,
|
||||
name: cleanFileName.fileNameWithoutExtension(),
|
||||
extension: cleanFileName.fileExtension(),
|
||||
storagePath: storagePath,
|
||||
fileSize: fileSize,
|
||||
);
|
||||
final String mimeType = fileToSave.extension.toLowerCase() == 'pdf'
|
||||
? 'application/pdf'
|
||||
: 'image/${fileToSave.extension}';
|
||||
try {
|
||||
// Usiamo bytes invece del path per massima compatibilità
|
||||
if (pickedFile.bytes == null && pickedFile.path == null) {
|
||||
throw 'Impossibile leggere il contenuto del file';
|
||||
}
|
||||
|
||||
// Se siamo su desktop/mobile abbiamo il path, su web abbiamo i bytes
|
||||
if (pickedFile.bytes != null) {
|
||||
await _supabase.storage
|
||||
.from('documents')
|
||||
.uploadBinary(
|
||||
storagePath,
|
||||
pickedFile.bytes!,
|
||||
fileOptions: FileOptions(contentType: mimeType, upsert: true),
|
||||
);
|
||||
}
|
||||
|
||||
final response = await _supabase
|
||||
.from(Tables.attachments)
|
||||
.insert(fileToSave.toMap())
|
||||
.select()
|
||||
.single();
|
||||
|
||||
return AttachmentModel.fromMap(response);
|
||||
} catch (e) {
|
||||
throw 'Errore durante l\'upload: $e';
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> copyFileToCustomer({
|
||||
required AttachmentModel file,
|
||||
required String customerId,
|
||||
}) async {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({'customer_id': customerId})
|
||||
.eq('id', file.id!);
|
||||
}
|
||||
|
||||
Future<void> renameAttachment(String id, String newName) async {
|
||||
Future<void> updateOperation(OperationModel operation) async {
|
||||
try {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({'name': newName})
|
||||
.eq('id', id);
|
||||
} catch (e) {
|
||||
throw '$e';
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteSpecificOperationFile(AttachmentModel file) async {
|
||||
try {
|
||||
if (file.customerId == null) {
|
||||
await _supabase.from(Tables.attachments).delete().eq('id', file.id!);
|
||||
await _supabase.storage.from('documents').remove([file.storagePath!]);
|
||||
} else {
|
||||
.from(Tables.operations)
|
||||
.update(operation.toMap())
|
||||
.eq('id', operation.id!);
|
||||
for (OperationDetailModel operationDetail in operation.details) {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({'operation_id': null})
|
||||
.eq('id', file.id!);
|
||||
.from(Tables.operationDetails)
|
||||
.upsert(operationDetail.toMap());
|
||||
}
|
||||
} catch (e) {
|
||||
throw '$e';
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteOperationFiles(List<AttachmentModel> files) async {
|
||||
if (files.isEmpty) return;
|
||||
// 1. Prepariamo le liste di ID e di Percorsi
|
||||
final List<String> idsToDelete = [];
|
||||
final List<String> idsToEdit = [];
|
||||
final List<String> storagePathsToDelete = [];
|
||||
for (var file in files) {
|
||||
if (file.customerId == null) {
|
||||
idsToDelete.add(file.id!);
|
||||
storagePathsToDelete.add(file.storagePath!);
|
||||
} else {
|
||||
idsToEdit.add(file.id!);
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (idsToDelete.isNotEmpty) {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.delete()
|
||||
.inFilter('id', idsToDelete);
|
||||
await _supabase.storage.from('documents').remove(storagePathsToDelete);
|
||||
}
|
||||
if (idsToEdit.isNotEmpty) {
|
||||
await _supabase
|
||||
.from(Tables.attachments)
|
||||
.update({'operation_id': null})
|
||||
.inFilter('id', idsToEdit);
|
||||
}
|
||||
} on PostgrestException catch (e) {
|
||||
throw 'Errore database: ${e.message}';
|
||||
} catch (e) {
|
||||
throw 'Errore durante l\'eliminazione dei file: $e';
|
||||
debugPrint('ERRORE SALVATAGGIO OPERAZIONE: $e');
|
||||
throw Exception('Errore nel salvataggio dell\'operazione: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class PaginatedOperations {
|
||||
final List<OperationModel> operations;
|
||||
final int totalCount;
|
||||
|
||||
PaginatedOperations({required this.operations, required this.totalCount});
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
class OperationsRepository {}
|
||||
@@ -0,0 +1,25 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flux/features/operations/models/operation_model.dart';
|
||||
|
||||
class PaginatedOperations extends Equatable {
|
||||
final List<OperationModel> operations;
|
||||
final int totalCount;
|
||||
|
||||
const PaginatedOperations({
|
||||
required this.operations,
|
||||
required this.totalCount,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [operations, totalCount];
|
||||
|
||||
PaginatedOperations copyWith({
|
||||
List<OperationModel>? operations,
|
||||
int? totalCount,
|
||||
}) {
|
||||
return PaginatedOperations(
|
||||
operations: operations ?? this.operations,
|
||||
totalCount: totalCount ?? this.totalCount,
|
||||
);
|
||||
}
|
||||
}
|
||||
+21
-93
@@ -8,61 +8,40 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:flux/core/services/notification_service.dart';
|
||||
import 'package:flux/core/utils/version_check_service.dart';
|
||||
import 'package:flux/features/attachments/data/attachments_repository.dart';
|
||||
import 'package:flux/features/auth/bloc/auth_cubit.dart';
|
||||
import 'package:flux/features/company/data/company_repository.dart';
|
||||
import 'package:flux/features/notes/blocs/notes_cubit.dart';
|
||||
import 'package:flux/features/notes/data/notes_repository.dart';
|
||||
import 'package:flux/features/settings/data/settings_repository.dart';
|
||||
import 'package:flux/features/tasks/data/task_repository.dart';
|
||||
import 'package:flux/features/tickets/data/tickets_shipping_repository.dart';
|
||||
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
|
||||
import 'package:flux/features/notes/blocs/notes_cubit.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_list_cubit.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:flux/features/settings/blocs/settings_cubit.dart';
|
||||
import 'package:flux/features/settings/document_sequence/data/document_sequence_repository.dart';
|
||||
import 'package:flux/features/tickets/blocs/ticket_list_cubit.dart';
|
||||
import 'package:flux/features/tickets/data/ticket_repository.dart';
|
||||
import 'package:flux/features/tracking/blocs/tracking_cubit.dart';
|
||||
import 'package:flux/features/tracking/data/tracking_repository.dart';
|
||||
import 'package:flux/firebase_options.dart';
|
||||
import 'package:flux/l10n/app_localizations.dart';
|
||||
import 'package:flux/service_locator.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/data/core_repository.dart';
|
||||
import 'package:flux/core/routes/app_router.dart';
|
||||
import 'package:flux/core/theme/theme.dart';
|
||||
import 'package:flux/core/theme/bloc/theme_bloc.dart';
|
||||
import 'package:flux/features/customers/blocs/customers_list_cubit.dart';
|
||||
import 'package:flux/features/customers/data/customer_repository.dart';
|
||||
import 'package:flux/features/master_data/products/blocs/product_cubit.dart';
|
||||
import 'package:flux/features/master_data/products/data/product_repository.dart';
|
||||
import 'package:flux/features/master_data/providers/data/provider_repository.dart';
|
||||
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
|
||||
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
|
||||
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
|
||||
import 'package:flux/features/master_data/store/data/store_repository.dart';
|
||||
import 'package:flux/features/settings/ui/settings.dart';
|
||||
import 'package:flutter_web_plugins/url_strategy.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
String? initialRecoveryFragment;
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await sl.init();
|
||||
await init();
|
||||
final initialUri = Uri.base;
|
||||
if (initialUri.fragment.contains('access_token=')) {
|
||||
initialRecoveryFragment = initialUri.fragment;
|
||||
}
|
||||
await dotenv.load(fileName: ".env");
|
||||
|
||||
// Inizializza le dipendenze PRIMA di lanciare l'app
|
||||
await setupLocator();
|
||||
// RIMUOVE IL CARATTERE # DAGLI URL WEB!
|
||||
usePathUrlStrategy();
|
||||
// Lo Scudo Ninja: Inizializziamo Firebase SOLO sulle piattaforme supportate
|
||||
@@ -79,90 +58,39 @@ void main() async {
|
||||
runApp(
|
||||
MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider<AuthCubit>(create: (context) => AuthCubit()),
|
||||
BlocProvider<AuthCubit>(create: (_) => sl<AuthCubit>()),
|
||||
BlocProvider<ThemeBloc>(
|
||||
create: (context) => ThemeBloc()..add(LoadThemeEvent()),
|
||||
create: (_) => sl<ThemeBloc>()..add(LoadThemeEvent()),
|
||||
),
|
||||
// Il Vigile Urbano viene inizializzato!
|
||||
BlocProvider<SessionCubit>(create: (_) => GetIt.I<SessionCubit>()),
|
||||
BlocProvider<SessionCubit>(create: (_) => sl<SessionCubit>()),
|
||||
|
||||
// Cubit delle feature
|
||||
BlocProvider<StoreCubit>(create: (_) => StoreCubit()),
|
||||
BlocProvider<CustomersListCubit>(create: (_) => CustomersListCubit()),
|
||||
BlocProvider<ProductsCubit>(create: (_) => ProductsCubit()),
|
||||
BlocProvider<StoreCubit>(create: (_) => sl<StoreCubit>()),
|
||||
BlocProvider<CustomersListCubit>(
|
||||
create: (_) => sl<CustomersListCubit>(),
|
||||
),
|
||||
BlocProvider<ProductsCubit>(create: (_) => sl<ProductsCubit>()),
|
||||
BlocProvider<StaffCubit>(
|
||||
create: (_) => StaffCubit()
|
||||
create: (_) => sl<StaffCubit>()
|
||||
..loadStaffForStore(
|
||||
GetIt.I.get<SessionCubit>().state.currentStore!.id!,
|
||||
),
|
||||
),
|
||||
BlocProvider<OperationListCubit>(create: (_) => OperationListCubit()),
|
||||
BlocProvider<ProviderListCubit>(create: (_) => ProviderListCubit()),
|
||||
BlocProvider<SettingsCubit>(create: (_) => SettingsCubit()),
|
||||
BlocProvider<TicketListCubit>(create: (_) => TicketListCubit()),
|
||||
BlocProvider<OperationListCubit>(create: (_) => OperationListCubit()),
|
||||
BlocProvider<TrackingCubit>(create: (_) => TrackingCubit()),
|
||||
BlocProvider<NotesCubit>(create: (_) => NotesCubit()),
|
||||
BlocProvider<OperationListCubit>(
|
||||
create: (_) => sl<OperationListCubit>(),
|
||||
),
|
||||
BlocProvider<ProviderListCubit>(create: (_) => sl<ProviderListCubit>()),
|
||||
BlocProvider<SettingsCubit>(create: (_) => sl<SettingsCubit>()),
|
||||
BlocProvider<TicketListCubit>(create: (_) => sl<TicketListCubit>()),
|
||||
BlocProvider<TrackingCubit>(create: (_) => sl<TrackingCubit>()),
|
||||
BlocProvider<NotesCubit>(create: (_) => sl<NotesCubit>()),
|
||||
],
|
||||
child: const FluxApp(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> setupLocator() async {
|
||||
final GetIt getIt = GetIt.instance;
|
||||
|
||||
getIt.registerSingleton<SharedPreferences>(
|
||||
await SharedPreferences.getInstance(),
|
||||
);
|
||||
|
||||
await Supabase.initialize(
|
||||
url: dotenv.env['SUPABASE_URL'] ?? '',
|
||||
publishableKey: dotenv.env['SUPABASE_PUBLISHABLE_KEY'] ?? '',
|
||||
);
|
||||
|
||||
// Settings
|
||||
getIt.registerLazySingleton<AppSettings>(() => AppSettings());
|
||||
|
||||
// Repositories
|
||||
getIt.registerLazySingleton<CoreRepository>(
|
||||
() => CoreRepository(),
|
||||
); // <-- NUOVO
|
||||
getIt.registerLazySingleton<StoreRepository>(() => StoreRepository());
|
||||
getIt.registerLazySingleton<CustomerRepository>(() => CustomerRepository());
|
||||
getIt.registerLazySingleton<ProductRepository>(() => ProductRepository());
|
||||
getIt.registerLazySingleton<StaffRepository>(() => StaffRepository());
|
||||
getIt.registerLazySingleton<OperationsRepository>(
|
||||
() => OperationsRepository(),
|
||||
);
|
||||
getIt.registerLazySingleton<ProviderRepository>(() => ProviderRepository());
|
||||
getIt.registerLazySingleton<AttachmentsRepository>(
|
||||
() => AttachmentsRepository(),
|
||||
);
|
||||
getIt.registerLazySingleton<TicketRepository>(() => TicketRepository());
|
||||
getIt.registerLazySingleton<DocumentSequenceRepository>(
|
||||
() => DocumentSequenceRepository(),
|
||||
);
|
||||
|
||||
// NOTA: CompanyRepository l'ho tolto perché la logica della Company
|
||||
// ora è gestita dal CoreRepository durante l'Onboarding.
|
||||
// Se ti serve per altro, rimettilo pure!
|
||||
|
||||
// Inizializziamo il SessionCubit (che prende CoreRepository e SharedPreferences)
|
||||
// Usiamo registerSingleton così viene creato subito e inizia ad ascoltare Supabase Auth.
|
||||
getIt.registerSingleton<SessionCubit>(
|
||||
SessionCubit(getIt<CoreRepository>(), getIt<SharedPreferences>()),
|
||||
);
|
||||
getIt.registerLazySingleton<CompanyRepository>(() => CompanyRepository());
|
||||
getIt.registerLazySingleton<TrackingRepository>(() => TrackingRepository());
|
||||
getIt.registerLazySingleton<TicketsShippingRepository>(
|
||||
() => TicketsShippingRepository(),
|
||||
);
|
||||
getIt.registerLazySingleton<NotesRepository>(() => NotesRepository());
|
||||
getIt.registerLazySingleton<TasksRepository>(() => TasksRepository());
|
||||
getIt.registerLazySingleton<SettingsRepository>(() => SettingsRepository());
|
||||
}
|
||||
|
||||
class FluxApp extends StatefulWidget {
|
||||
const FluxApp({super.key});
|
||||
|
||||
@@ -178,7 +106,7 @@ class _FluxAppState extends State<FluxApp> {
|
||||
super.initState();
|
||||
// Creiamo il router passandogli il Cubit per i redirect
|
||||
_router = AppRouter.createRouter(context.read<SessionCubit>());
|
||||
GetIt.I.get<SessionCubit>().setIsMobileDevice(isMobileDevice(context));
|
||||
sl<SessionCubit>().setIsMobileDevice(isMobileDevice(context));
|
||||
}
|
||||
|
||||
bool isMobileDevice(BuildContext context) {
|
||||
|
||||
@@ -1,8 +1,91 @@
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:flux/core/blocs/session/session_cubit.dart';
|
||||
import 'package:flux/core/data/core_repository.dart';
|
||||
import 'package:flux/core/theme/bloc/theme_bloc.dart';
|
||||
import 'package:flux/features/attachments/data/attachments_repository.dart';
|
||||
import 'package:flux/features/auth/bloc/auth_cubit.dart';
|
||||
import 'package:flux/features/company/data/company_repository.dart';
|
||||
import 'package:flux/features/customers/blocs/customers_list_cubit.dart';
|
||||
import 'package:flux/features/customers/data/customer_repository.dart';
|
||||
import 'package:flux/features/master_data/products/blocs/product_cubit.dart';
|
||||
import 'package:flux/features/master_data/products/data/product_repository.dart';
|
||||
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
|
||||
import 'package:flux/features/master_data/providers/data/provider_repository.dart';
|
||||
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
|
||||
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
|
||||
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
|
||||
import 'package:flux/features/master_data/store/data/store_repository.dart';
|
||||
import 'package:flux/features/notes/blocs/notes_cubit.dart';
|
||||
import 'package:flux/features/notes/data/notes_repository.dart';
|
||||
import 'package:flux/features/operations/blocs/operation_list_cubit.dart';
|
||||
import 'package:flux/features/operations/data/operations_repository.dart';
|
||||
import 'package:flux/features/settings/blocs/settings_cubit.dart';
|
||||
import 'package:flux/features/settings/data/settings_repository.dart';
|
||||
import 'package:flux/features/settings/document_sequence/data/document_sequence_repository.dart';
|
||||
import 'package:flux/features/settings/ui/settings.dart';
|
||||
import 'package:flux/features/tasks/data/task_repository.dart';
|
||||
import 'package:flux/features/tickets/blocs/ticket_list_cubit.dart';
|
||||
import 'package:flux/features/tickets/data/ticket_repository.dart';
|
||||
import 'package:flux/features/tickets/data/tickets_shipping_repository.dart';
|
||||
import 'package:flux/features/tracking/blocs/tracking_cubit.dart';
|
||||
import 'package:flux/features/tracking/data/tracking_repository.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
final sl = GetIt.instance;
|
||||
|
||||
void init() async {
|
||||
Future<void> init() async {
|
||||
await Supabase.initialize(
|
||||
url: dotenv.env['SUPABASE_URL'] ?? '',
|
||||
publishableKey: dotenv.env['SUPABASE_PUBLISHABLE_KEY'] ?? '',
|
||||
);
|
||||
sl.registerSingleton<SupabaseClient>(Supabase.instance.client);
|
||||
sl.registerSingleton<SharedPreferences>(
|
||||
await SharedPreferences.getInstance(),
|
||||
);
|
||||
sl.registerLazySingleton<AppSettings>(() => AppSettings());
|
||||
|
||||
// Repositories
|
||||
sl.registerLazySingleton<CoreRepository>(() => CoreRepository());
|
||||
sl.registerLazySingleton<StoreRepository>(() => StoreRepository());
|
||||
sl.registerLazySingleton<CustomerRepository>(() => CustomerRepository());
|
||||
sl.registerLazySingleton<ProductRepository>(() => ProductRepository());
|
||||
sl.registerLazySingleton<StaffRepository>(() => StaffRepository());
|
||||
sl.registerLazySingleton<OperationsRepository>(() => OperationsRepository());
|
||||
sl.registerLazySingleton<ProviderRepository>(() => ProviderRepository());
|
||||
sl.registerLazySingleton<AttachmentsRepository>(
|
||||
() => AttachmentsRepository(),
|
||||
);
|
||||
sl.registerLazySingleton<CompanyRepository>(() => CompanyRepository());
|
||||
sl.registerLazySingleton<SettingsRepository>(() => SettingsRepository());
|
||||
sl.registerLazySingleton<TicketRepository>(() => TicketRepository());
|
||||
sl.registerLazySingleton<TicketsShippingRepository>(
|
||||
() => TicketsShippingRepository(),
|
||||
);
|
||||
sl.registerLazySingleton<TasksRepository>(() => TasksRepository());
|
||||
sl.registerLazySingleton<TrackingRepository>(() => TrackingRepository());
|
||||
sl.registerLazySingleton<NotesRepository>(() => NotesRepository());
|
||||
sl.registerLazySingleton<DocumentSequenceRepository>(
|
||||
() => DocumentSequenceRepository(),
|
||||
);
|
||||
|
||||
//Cubit globali
|
||||
sl.registerLazySingleton<SessionCubit>(
|
||||
() => SessionCubit(sl<CoreRepository>(), sl<SharedPreferences>()),
|
||||
);
|
||||
sl.registerLazySingleton<ThemeBloc>(() => ThemeBloc());
|
||||
sl.registerLazySingleton<StaffCubit>(() => StaffCubit());
|
||||
sl.registerLazySingleton<StoreCubit>(() => StoreCubit());
|
||||
sl.registerLazySingleton<ProviderListCubit>(() => ProviderListCubit());
|
||||
sl.registerLazySingleton<SettingsCubit>(() => SettingsCubit());
|
||||
sl.registerLazySingleton<AuthCubit>(() => AuthCubit());
|
||||
|
||||
//Cubit specifici
|
||||
sl.registerFactory<CustomersListCubit>(() => CustomersListCubit());
|
||||
sl.registerFactory<ProductsCubit>(() => ProductsCubit());
|
||||
sl.registerFactory<OperationListCubit>(() => OperationListCubit());
|
||||
sl.registerFactory<TicketListCubit>(() => TicketListCubit());
|
||||
sl.registerFactory<TrackingCubit>(() => TrackingCubit());
|
||||
sl.registerFactory<NotesCubit>(() => NotesCubit());
|
||||
}
|
||||
Reference in new issue
Block a user