refactor nomi tabelle

This commit is contained in:
2026-05-20 11:03:33 +02:00
parent f190ad9353
commit c85f4b086e
24 changed files with 217 additions and 159 deletions

View File

@@ -1,2 +0,0 @@
const String resetPasswordUrl =
'https://flux-web-invite.marco-6ba.workers.dev/';

View File

@@ -1,5 +1,6 @@
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/company/models/company_model.dart'; import 'package:flux/features/company/models/company_model.dart';
import 'package:flux/features/master_data/store/models/store_model.dart'; import 'package:flux/features/master_data/store/models/store_model.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
@@ -15,7 +16,7 @@ class CoreRepository {
Future<CompanyModel?> getCompanyByOwnerId(String userId) async { Future<CompanyModel?> getCompanyByOwnerId(String userId) async {
try { try {
final response = await _supabase final response = await _supabase
.from('company') .from(Tables.companies)
.select() .select()
.eq('user_id', userId) // <-- Assicurati di avere questo campo nel DB! .eq('user_id', userId) // <-- Assicurati di avere questo campo nel DB!
.maybeSingle(); .maybeSingle();
@@ -31,7 +32,7 @@ class CoreRepository {
Future<CompanyModel?> getCompanyById(String companyId) async { Future<CompanyModel?> getCompanyById(String companyId) async {
try { try {
final response = await _supabase final response = await _supabase
.from('company') .from(Tables.companies)
.select() .select()
.eq('id', companyId) .eq('id', companyId)
.maybeSingle(); .maybeSingle();
@@ -46,7 +47,7 @@ class CoreRepository {
Future<List<StoreModel>> getStoresByCompanyId(String companyId) async { Future<List<StoreModel>> getStoresByCompanyId(String companyId) async {
try { try {
final response = await _supabase final response = await _supabase
.from('store') .from(Tables.stores)
.select() .select()
.eq('company_id', companyId) .eq('company_id', companyId)
.eq('is_active', true) // Buona pratica .eq('is_active', true) // Buona pratica
@@ -62,7 +63,7 @@ class CoreRepository {
Future<StaffMemberModel?> getStaffMemberByUserId(String userId) async { Future<StaffMemberModel?> getStaffMemberByUserId(String userId) async {
try { try {
final response = await _supabase final response = await _supabase
.from('staff_member') .from(Tables.staffMembers)
.select() .select()
.eq('user_id', userId) .eq('user_id', userId)
.maybeSingle(); .maybeSingle();
@@ -80,7 +81,7 @@ class CoreRepository {
Future<CompanyModel> createCompany(CompanyModel company) async { Future<CompanyModel> createCompany(CompanyModel company) async {
try { try {
final response = await _supabase final response = await _supabase
.from('company') .from(Tables.companies)
.insert(company.toMap()) .insert(company.toMap())
.select() .select()
.single(); .single();
@@ -94,7 +95,7 @@ class CoreRepository {
Future<StoreModel> createStore(StoreModel store) async { Future<StoreModel> createStore(StoreModel store) async {
try { try {
final response = await _supabase final response = await _supabase
.from('store') .from(Tables.stores)
.insert(store.toMap()) .insert(store.toMap())
.select() .select()
.single(); .single();
@@ -108,12 +109,12 @@ class CoreRepository {
Future<StaffMemberModel> createStaffMember(StaffMemberModel staff) async { Future<StaffMemberModel> createStaffMember(StaffMemberModel staff) async {
try { try {
final response = await _supabase final response = await _supabase
.from('staff_member') .from(Tables.staffMembers)
.insert(staff.toMap()) .insert(staff.toMap())
.select() .select()
.single(); .single();
final StaffMemberModel staffMember = StaffMemberModel.fromMap(response); final StaffMemberModel staffMember = StaffMemberModel.fromMap(response);
await _supabase.from('staff_in_stores').insert({ await _supabase.from(Tables.staffInStores).insert({
'staff_member_id': staffMember.id, 'staff_member_id': staffMember.id,
'store_id': GetIt.I.get<SessionCubit>().state.currentStore!.id, 'store_id': GetIt.I.get<SessionCubit>().state.currentStore!.id,
}); });
@@ -126,7 +127,7 @@ class CoreRepository {
// Assegna un membro a un negozio // Assegna un membro a un negozio
Future<void> assignStaffToStore(String staffId, String storeId) async { Future<void> assignStaffToStore(String staffId, String storeId) async {
await _supabase.from('staff_in_stores').insert({ await _supabase.from(Tables.staffInStores).insert({
'staff_member_id': staffId, 'staff_member_id': staffId,
'store_id': storeId, 'store_id': storeId,
}); });
@@ -136,6 +137,6 @@ class CoreRepository {
String staffId, String staffId,
Map<String, dynamic> data, Map<String, dynamic> data,
) async { ) async {
await _supabase.from('staff_member').update(data).eq('id', staffId); await _supabase.from(Tables.staffMembers).update(data).eq('id', staffId);
} }
} }

View File

@@ -0,0 +1,24 @@
class Tables {
static const String attachments = 'attachments';
static const String brands = 'brands';
static const String campaigns = 'campaigns';
static const String companies = 'companies';
static const String customers = 'customers';
static const String documentSequences = 'document_sequences';
static const String models = 'models';
static const String notes = 'notes';
static const String noteCollaborators = 'note_collaborators';
static const String operations = 'operations';
static const String providerLocations = 'provider_locations';
static const String providers = 'providers';
static const String providersInStores = 'providers_in_stores';
static const String shippingDocuments = 'shipping_documents';
static const String staffInStores = 'staff_in_stores';
static const String staffMembers = 'staff_members';
static const String stores = 'stores';
static const String tickets = 'tickets';
static const String trackings = 'trackings';
}
const String resetPasswordUrl =
'https://flux-web-invite.marco-6ba.workers.dev/';

View File

@@ -1,6 +1,6 @@
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:flux/core/enums/enums.dart'; import 'package:flux/core/enums_and_consts/enums.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';

View File

@@ -306,6 +306,8 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
return file.copyWith(operationId: event.targetId); return file.copyWith(operationId: event.targetId);
case AttachmentParentType.shippingDocument: case AttachmentParentType.shippingDocument:
return file.copyWith(shippingDocumentId: event.targetId); return file.copyWith(shippingDocumentId: event.targetId);
case AttachmentParentType.note:
return file.copyWith(noteId: event.targetId);
} }
} }
return file; return file;
@@ -405,6 +407,8 @@ class AttachmentsBloc extends Bloc<AttachmentsEvent, AttachmentsState> {
return Bucket.documents; return Bucket.documents;
case AttachmentParentType.shippingDocument: case AttachmentParentType.shippingDocument:
return Bucket.companyDocuments; return Bucket.companyDocuments;
case AttachmentParentType.note:
return Bucket.documents;
} }
} }
} }

View File

@@ -6,7 +6,8 @@ enum AttachmentParentType {
operation('operation_id'), operation('operation_id'),
ticket('ticket_id'), ticket('ticket_id'),
customer('customer_id'), customer('customer_id'),
shippingDocument('shipping_document_id'); shippingDocument('shipping_document_id'),
note('note_id');
final String dbColumn; final String dbColumn;
const AttachmentParentType(this.dbColumn); const AttachmentParentType(this.dbColumn);

View File

@@ -1,5 +1,6 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:file_picker/file_picker.dart'; import 'package:file_picker/file_picker.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/attachments/models/attachment_model.dart'; import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:flux/features/attachments/blocs/attachments_bloc.dart'; import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
@@ -14,8 +15,7 @@ enum Bucket {
class AttachmentsRepository { class AttachmentsRepository {
final _supabase = Supabase.instance.client; final _supabase = Supabase.instance.client;
static const String _tableName = static const String _tableName = Tables.attachments;
'attachment'; // Cambia col vero nome della tua tabella se diverso!
/// Scarica i byte di un file direttamente da Supabase Storage /// Scarica i byte di un file direttamente da Supabase Storage
Future<Uint8List> downloadAttachmentBytes({ Future<Uint8List> downloadAttachmentBytes({
@@ -43,6 +43,8 @@ class AttachmentsRepository {
return 'customer_id'; return 'customer_id';
case AttachmentParentType.shippingDocument: case AttachmentParentType.shippingDocument:
return 'shipping_document_id'; return 'shipping_document_id';
case AttachmentParentType.note:
return 'note_id';
} }
} }

View File

@@ -9,6 +9,7 @@ class AttachmentModel extends Equatable {
final String? operationId; final String? operationId;
final String? ticketId; final String? ticketId;
final String? shippingDocumentId; final String? shippingDocumentId;
final String? noteId;
final String name; final String name;
final String extension; final String extension;
final String? storagePath; final String? storagePath;
@@ -23,6 +24,7 @@ class AttachmentModel extends Equatable {
this.operationId, this.operationId,
this.ticketId, this.ticketId,
this.shippingDocumentId, this.shippingDocumentId,
this.noteId,
required this.name, required this.name,
required this.extension, required this.extension,
this.storagePath, this.storagePath,
@@ -39,6 +41,7 @@ class AttachmentModel extends Equatable {
operationId, operationId,
ticketId, ticketId,
shippingDocumentId, shippingDocumentId,
noteId,
name, name,
extension, extension,
storagePath, storagePath,
@@ -67,6 +70,7 @@ class AttachmentModel extends Equatable {
String? operationId, String? operationId,
String? ticketId, String? ticketId,
String? shippingDocumentId, String? shippingDocumentId,
String? noteId,
String? name, String? name,
String? extension, String? extension,
String? storagePath, String? storagePath,
@@ -80,6 +84,7 @@ class AttachmentModel extends Equatable {
operationId: operationId ?? this.operationId, operationId: operationId ?? this.operationId,
ticketId: ticketId ?? this.ticketId, ticketId: ticketId ?? this.ticketId,
shippingDocumentId: shippingDocumentId ?? this.shippingDocumentId, shippingDocumentId: shippingDocumentId ?? this.shippingDocumentId,
noteId: noteId ?? this.noteId,
name: name ?? this.name, name: name ?? this.name,
extension: extension ?? this.extension, extension: extension ?? this.extension,
storagePath: storagePath ?? this.storagePath, storagePath: storagePath ?? this.storagePath,
@@ -98,6 +103,7 @@ class AttachmentModel extends Equatable {
operationId: map['operation_id'] as String?, operationId: map['operation_id'] as String?,
ticketId: map['ticket_id'] as String?, ticketId: map['ticket_id'] as String?,
shippingDocumentId: map['shipping_document_id'] as String?, shippingDocumentId: map['shipping_document_id'] as String?,
noteId: map['note_id'] as String?,
name: map['name'] as String, name: map['name'] as String,
extension: map['extension'] as String, extension: map['extension'] as String,
storagePath: map['storage_path'] as String?, storagePath: map['storage_path'] as String?,
@@ -118,6 +124,7 @@ class AttachmentModel extends Equatable {
'operation_id': operationId, 'operation_id': operationId,
'ticket_id': ticketId, 'ticket_id': ticketId,
'shipping_document_id': shippingDocumentId, 'shipping_document_id': shippingDocumentId,
'note_id': noteId,
'file_size': fileSize, 'file_size': fileSize,
'company_id': companyId, 'company_id': companyId,
}; };

View File

@@ -1,7 +1,7 @@
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/data/constants.dart'; import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/core/utils/app_message.dart'; import 'package:flux/core/utils/app_message.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/supabase_flutter.dart';

View File

@@ -1,5 +1,6 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/company_model.dart'; import '../models/company_model.dart';
@@ -10,7 +11,7 @@ class CompanyRepository {
try { try {
// .select().single() trasforma la risposta nell'oggetto appena inserito // .select().single() trasforma la risposta nell'oggetto appena inserito
final response = await _supabase final response = await _supabase
.from('company') .from(Tables.companies)
.insert(company.toMap()) .insert(company.toMap())
.select() .select()
.single(); .single();
@@ -26,7 +27,7 @@ class CompanyRepository {
Future<CompanyModel> updateCompany(CompanyModel company) async { Future<CompanyModel> updateCompany(CompanyModel company) async {
try { try {
final response = await _supabase final response = await _supabase
.from('company') .from(Tables.companies)
.update(company.toMap()) .update(company.toMap())
.eq('id', company.id!) .eq('id', company.id!)
.select() .select()
@@ -83,7 +84,7 @@ class CompanyRepository {
try { try {
final userId = _supabase.auth.currentUser?.id; final userId = _supabase.auth.currentUser?.id;
final response = await _supabase final response = await _supabase
.from('company') .from(Tables.companies)
.select() .select()
.eq('user_id', userId as Object) .eq('user_id', userId as Object)
.maybeSingle(); .maybeSingle();

View File

@@ -1,5 +1,6 @@
import 'package:file_picker/file_picker.dart'; import 'package:file_picker/file_picker.dart';
import 'package:flux/core/blocs/session/session_cubit.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/core/utils/extensions.dart';
import 'package:flux/features/attachments/models/attachment_model.dart'; import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
@@ -14,7 +15,7 @@ class CustomerRepository {
Future<CustomerModel> insertCustomer(CustomerModel customer) async { Future<CustomerModel> insertCustomer(CustomerModel customer) async {
try { try {
final response = await _supabase final response = await _supabase
.from('customer') .from(Tables.customers)
.upsert(customer.toJson()) .upsert(customer.toJson())
.select() .select()
.single(); .single();
@@ -27,7 +28,7 @@ class CustomerRepository {
Future<CustomerModel> updateCustomer(CustomerModel customer) async { Future<CustomerModel> updateCustomer(CustomerModel customer) async {
try { try {
final response = await _supabase final response = await _supabase
.from('customer') .from(Tables.customers)
.update(customer.toJson()) .update(customer.toJson())
.eq('id', customer.id!) .eq('id', customer.id!)
.select() .select()
@@ -42,10 +43,10 @@ class CustomerRepository {
Future<List<CustomerModel>> getCustomers(String companyId) async { Future<List<CustomerModel>> getCustomers(String companyId) async {
try { try {
final response = await _supabase final response = await _supabase
.from('customer') .from(Tables.customers)
.select(''' .select('''
*, *,
attachment(*) ${Tables.attachments}(*)
''') ''')
.eq('company_id', companyId) .eq('company_id', companyId)
.eq('is_active', true) .eq('is_active', true)
@@ -60,10 +61,10 @@ class CustomerRepository {
Future<CustomerModel> getCustomerById(String customerId) async { Future<CustomerModel> getCustomerById(String customerId) async {
try { try {
final response = await _supabase final response = await _supabase
.from('customer') .from(Tables.customers)
.select(''' .select('''
*, *,
attachment(*) ${Tables.attachments}(*)
''') ''')
.eq('id', customerId) .eq('id', customerId)
.single(); .single();
@@ -81,7 +82,7 @@ class CustomerRepository {
) async { ) async {
try { try {
final response = await _supabase final response = await _supabase
.from('customer') .from(Tables.customers)
.select() .select()
.eq('company_id', companyId) .eq('company_id', companyId)
.or('name.ilike.%$query%,phone_number.ilike.%$query%') .or('name.ilike.%$query%,phone_number.ilike.%$query%')
@@ -96,7 +97,7 @@ class CustomerRepository {
/// Ascolta in tempo reale i file caricati per un cliente /// Ascolta in tempo reale i file caricati per un cliente
Stream<List<AttachmentModel>> getCustomerFilesStream(String customerId) { Stream<List<AttachmentModel>> getCustomerFilesStream(String customerId) {
return _supabase return _supabase
.from('attachment') .from(Tables.attachments)
.stream(primaryKey: ['id']) .stream(primaryKey: ['id'])
.eq('customer_id', customerId) .eq('customer_id', customerId)
.order('created_at', ascending: false) .order('created_at', ascending: false)
@@ -110,7 +111,7 @@ class CustomerRepository {
Future<List<AttachmentModel>> getCustomerFiles(String customerId) async { Future<List<AttachmentModel>> getCustomerFiles(String customerId) async {
try { try {
final response = await _supabase final response = await _supabase
.from('attachment') .from(Tables.attachments)
.select() .select()
.eq('customer_id', customerId); .eq('customer_id', customerId);
@@ -161,7 +162,7 @@ class CustomerRepository {
} }
final response = await _supabase final response = await _supabase
.from('attachment') .from(Tables.attachments)
.insert(fileToSave.toMap()) .insert(fileToSave.toMap())
.select() .select()
.single(); .single();
@@ -173,7 +174,7 @@ class CustomerRepository {
} }
Future<void> saveFileReference(AttachmentModel file) async { Future<void> saveFileReference(AttachmentModel file) async {
await _supabase.from('attachment').upsert(file.toMap()); await _supabase.from(Tables.attachments).upsert(file.toMap());
} }
Future<void> deleteDocuments(List<AttachmentModel> files) async { Future<void> deleteDocuments(List<AttachmentModel> files) async {
@@ -192,13 +193,16 @@ class CustomerRepository {
} }
try { try {
if (idsToDelete.isNotEmpty) { if (idsToDelete.isNotEmpty) {
await _supabase.from('attachment').delete().inFilter('id', idsToDelete); await _supabase
.from(Tables.attachments)
.delete()
.inFilter('id', idsToDelete);
// 3. Cancellazione MASSIVA dallo Storage // 3. Cancellazione MASSIVA dallo Storage
await _supabase.storage.from('documents').remove(storagePathsToDelete); await _supabase.storage.from('documents').remove(storagePathsToDelete);
} }
if (idsToEdit.isNotEmpty) { if (idsToEdit.isNotEmpty) {
await _supabase await _supabase
.from('attachment') .from(Tables.attachments)
.update({'customer_id': null}) .update({'customer_id': null})
.inFilter('id', idsToEdit); .inFilter('id', idsToEdit);
} }

View File

@@ -1,4 +1,5 @@
import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/brand_model.dart'; import '../models/brand_model.dart';
@@ -14,7 +15,7 @@ class ProductRepository {
Future<List<BrandModel>> getBrands() async { Future<List<BrandModel>> getBrands() async {
try { try {
final response = await _supabase final response = await _supabase
.from('brand') .from(Tables.brands)
.select() .select()
.eq('company_id', _companyId) .eq('company_id', _companyId)
.eq('is_active', true) .eq('is_active', true)
@@ -30,7 +31,7 @@ class ProductRepository {
Future<BrandModel> upsertBrand(BrandModel brand) async { Future<BrandModel> upsertBrand(BrandModel brand) async {
try { try {
final response = await _supabase final response = await _supabase
.from('brand') .from(Tables.brands)
.upsert(brand.toJson()) .upsert(brand.toJson())
.select() .select()
.single(); .single();
@@ -47,7 +48,7 @@ class ProductRepository {
Future<List<ModelModel>> getModelsByBrand(String brandId) async { Future<List<ModelModel>> getModelsByBrand(String brandId) async {
try { try {
final response = await _supabase final response = await _supabase
.from('model') .from(Tables.models)
.select() .select()
.eq('brand_id', brandId) .eq('brand_id', brandId)
.eq('is_active', true) .eq('is_active', true)
@@ -62,7 +63,7 @@ class ProductRepository {
Future<List<ModelModel>> getModels() async { Future<List<ModelModel>> getModels() async {
try { try {
final response = await _supabase final response = await _supabase
.from('model') .from(Tables.models)
.select() .select()
.eq('is_active', true) .eq('is_active', true)
.order('name'); .order('name');
@@ -77,7 +78,7 @@ class ProductRepository {
Future<ModelModel> upsertModel(ModelModel model) async { Future<ModelModel> upsertModel(ModelModel model) async {
try { try {
final response = await _supabase final response = await _supabase
.from('model') .from(Tables.models)
.upsert(model.toJson()) .upsert(model.toJson())
.select() .select()
.single(); .single();
@@ -102,7 +103,7 @@ class ProductRepository {
Future<List<ModelModel>> searchModels(String query) async { Future<List<ModelModel>> searchModels(String query) async {
try { try {
final response = await _supabase final response = await _supabase
.from('model') .from(Tables.models)
.select() .select()
.ilike('name_with_brand', '%$query%') // Cerca ovunque nel nome .ilike('name_with_brand', '%$query%') // Cerca ovunque nel nome
.eq('is_active', true) .eq('is_active', true)

View File

@@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/core/theme/theme.dart'; import 'package:flux/core/theme/theme.dart';
import 'package:flux/features/master_data/products/blocs/product_cubit.dart'; import 'package:flux/features/master_data/products/blocs/product_cubit.dart';
import 'package:flux/features/master_data/products/ui/product_dialogs.dart'; import 'package:flux/features/master_data/products/ui/product_dialogs.dart';
@@ -63,9 +64,12 @@ class ModelsList extends StatelessWidget {
: Icons.visibility_off_outlined, : Icons.visibility_off_outlined,
color: model.isActive ? context.accent : Colors.grey, color: model.isActive ? context.accent : Colors.grey,
), ),
onPressed: () => context onPressed: () =>
.read<ProductsCubit>() context.read<ProductsCubit>().toggleStatus(
.toggleStatus('model', model.id!, model.isActive), Tables.models,
model.id!,
model.isActive,
),
), ),
], ],
), ),

View File

@@ -1,4 +1,5 @@
import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/provider_model.dart'; import '../models/provider_model.dart';
@@ -11,12 +12,12 @@ class ProviderRepository {
// 1. Carica i provider abilitati per uno specifico Store // 1. Carica i provider abilitati per uno specifico Store
Future<List<ProviderModel>> getProvidersByStore(String storeId) async { Future<List<ProviderModel>> getProvidersByStore(String storeId) async {
final response = await _supabase final response = await _supabase
.from('providers_in_stores') .from(Tables.providersInStores)
.select(''' .select('''
provider_id, provider_id,
provider:provider ( provider:${Tables.providers} (
*, *,
provider_locations (*) ${Tables.providerLocations} (*)
) )
''') ''')
.eq('store_id', storeId) .eq('store_id', storeId)
@@ -31,8 +32,8 @@ class ProviderRepository {
// 2. Carica TUTTI i provider della Company (per la gestione anagrafica) // 2. Carica TUTTI i provider della Company (per la gestione anagrafica)
Future<List<ProviderModel>> getAllCompanyProviders() async { Future<List<ProviderModel>> getAllCompanyProviders() async {
final response = await _supabase final response = await _supabase
.from('provider') .from(Tables.providers)
.select('*, provider_locations (*)') .select('*, ${Tables.providerLocations} (*)')
.order('name'); .order('name');
return (response as List) return (response as List)
@@ -48,7 +49,7 @@ class ProviderRepository {
// A. Salva/Aggiorna il Provider principale // A. Salva/Aggiorna il Provider principale
final providerWithCompany = provider.copyWith(companyId: _companyId); final providerWithCompany = provider.copyWith(companyId: _companyId);
final savedRow = await _supabase final savedRow = await _supabase
.from('provider') .from(Tables.providers)
.upsert(providerWithCompany.toMap()) .upsert(providerWithCompany.toMap())
.select() .select()
.single(); .single();
@@ -58,7 +59,7 @@ class ProviderRepository {
// B. Sincronizza gli Store (Cancelliamo i vecchi e mettiamo i nuovi per semplicità) // B. Sincronizza gli Store (Cancelliamo i vecchi e mettiamo i nuovi per semplicità)
// In un'app ad alto traffico faremmo un confronto, qui l'upsert totale è più veloce da scrivere. // In un'app ad alto traffico faremmo un confronto, qui l'upsert totale è più veloce da scrivere.
await _supabase await _supabase
.from('providers_in_stores') .from(Tables.providersInStores)
.delete() .delete()
.eq('provider_id', savedProvider.id!); .eq('provider_id', savedProvider.id!);
@@ -67,7 +68,7 @@ class ProviderRepository {
.map((sId) => {'provider_id': savedProvider.id, 'store_id': sId}) .map((sId) => {'provider_id': savedProvider.id, 'store_id': sId})
.toList(); .toList();
await _supabase.from('providers_in_stores').insert(storeLinks); await _supabase.from(Tables.providersInStores).insert(storeLinks);
} }
return savedProvider; return savedProvider;
@@ -75,10 +76,13 @@ class ProviderRepository {
// 4. Gestione Sedi (Locations) // 4. Gestione Sedi (Locations)
Future<void> saveLocation(ProviderLocationModel location) async { Future<void> saveLocation(ProviderLocationModel location) async {
await _supabase.from('provider_locations').upsert(location.toMap()); await _supabase.from(Tables.providerLocations).upsert(location.toMap());
} }
Future<void> deleteLocation(String locationId) async { Future<void> deleteLocation(String locationId) async {
await _supabase.from('provider_locations').delete().eq('id', locationId); await _supabase
.from(Tables.providerLocations)
.delete()
.eq('id', locationId);
} }
} }

View File

@@ -1,3 +1,4 @@
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/master_data/store/models/store_model.dart'; import 'package:flux/features/master_data/store/models/store_model.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
@@ -11,7 +12,7 @@ class StaffRepository {
// Prende tutto lo staff della Company (per l'Hub Anagrafiche) // Prende tutto lo staff della Company (per l'Hub Anagrafiche)
Future<List<StaffMemberModel>> getStaffMembers(String companyId) async { Future<List<StaffMemberModel>> getStaffMembers(String companyId) async {
final response = await _supabase final response = await _supabase
.from('staff_member') .from(Tables.staffMembers)
.select() .select()
.eq('company_id', companyId) .eq('company_id', companyId)
.order('name', ascending: true); .order('name', ascending: true);
@@ -21,7 +22,7 @@ class StaffRepository {
Future<StaffMemberModel> saveStaffMember(StaffMemberModel member) async { Future<StaffMemberModel> saveStaffMember(StaffMemberModel member) async {
final response = await _supabase final response = await _supabase
.from('staff_member') .from(Tables.staffMembers)
.upsert(member.toMap()) .upsert(member.toMap())
.select() .select()
.single(); .single();
@@ -64,7 +65,7 @@ class StaffRepository {
try { try {
await _supabase.auth.resetPasswordForEmail( await _supabase.auth.resetPasswordForEmail(
email, email,
redirectTo: 'https://flux-web-invite.marco-6ba.workers.dev/', redirectTo: resetPasswordUrl,
); );
} catch (e) { } catch (e) {
throw Exception("Errore nell'invio del link: $e"); throw Exception("Errore nell'invio del link: $e");
@@ -77,14 +78,14 @@ class StaffRepository {
// Qui facciamo una JOIN per avere i dati del membro partendo dalla tabella di giunzione // Qui facciamo una JOIN per avere i dati del membro partendo dalla tabella di giunzione
Future<List<StaffMemberModel>> getStaffMembersInStore(String storeId) async { Future<List<StaffMemberModel>> getStaffMembersInStore(String storeId) async {
final response = await _supabase final response = await _supabase
.from('staff_in_stores') .from(Tables.staffInStores)
.select( .select(
'staff_member (*)', '${Tables.staffMembers} (*)',
) // Prende tutti i campi della tabella staff_member collegata ) // Prende tutti i campi della tabella staff_member collegata
.eq('store_id', storeId); .eq('store_id', storeId);
return (response as List) return (response as List)
.map((item) => StaffMemberModel.fromMap(item['staff_member'])) .map((item) => StaffMemberModel.fromMap(item[Tables.staffMembers]))
.toList(); .toList();
} }
@@ -92,20 +93,20 @@ class StaffRepository {
// Qui facciamo una JOIN per avere i dati del membro partendo dalla tabella di giunzione // Qui facciamo una JOIN per avere i dati del membro partendo dalla tabella di giunzione
Future<List<StoreModel>> getStaffMemberStore(String staffId) async { Future<List<StoreModel>> getStaffMemberStore(String staffId) async {
final response = await _supabase final response = await _supabase
.from('staff_in_stores') .from(Tables.staffInStores)
.select( .select(
'store (*)', '${Tables.stores} (*)',
) // Prende tutti i campi della tabella store collegata ) // Prende tutti i campi della tabella store collegata
.eq('staff_member_id', staffId); .eq('staff_member_id', staffId);
return (response as List) return (response as List)
.map((item) => StoreModel.fromMap(item['store'])) .map((item) => StoreModel.fromMap(item[Tables.stores]))
.toList(); .toList();
} }
// Assegna un membro a un negozio // Assegna un membro a un negozio
Future<void> assignStaffToStore(String staffId, String storeId) async { Future<void> assignStaffToStore(String staffId, String storeId) async {
await _supabase.from('staff_in_stores').insert({ await _supabase.from(Tables.staffInStores).insert({
'staff_member_id': staffId, 'staff_member_id': staffId,
'store_id': storeId, 'store_id': storeId,
}); });
@@ -114,7 +115,7 @@ class StaffRepository {
// Rimuove l'assegnazione // Rimuove l'assegnazione
Future<void> removeStaffFromStore(String staffId, String storeId) async { Future<void> removeStaffFromStore(String staffId, String storeId) async {
await _supabase await _supabase
.from('staff_in_stores') .from(Tables.staffInStores)
.delete() .delete()
.eq('staff_member_id', staffId) .eq('staff_member_id', staffId)
.eq('store_id', storeId); .eq('store_id', storeId);
@@ -125,7 +126,7 @@ class StaffRepository {
// Utility per pulire le assegnazioni esistenti prima di riscriverle // Utility per pulire le assegnazioni esistenti prima di riscriverle
Future<void> clearStoreAssignments(String staffId) async { Future<void> clearStoreAssignments(String staffId) async {
await _supabase await _supabase
.from('staff_in_stores') .from(Tables.staffInStores)
.delete() .delete()
.eq('staff_member_id', staffId); .eq('staff_member_id', staffId);
} }

View File

@@ -1,3 +1,5 @@
import 'package:flutter/widgets.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/master_data/providers/models/provider_model.dart'; import 'package:flux/features/master_data/providers/models/provider_model.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
@@ -10,7 +12,7 @@ class StoreRepository {
/// Crea un nuovo negozio associato alla compagnia dell'utente /// Crea un nuovo negozio associato alla compagnia dell'utente
Future<void> createStore(StoreModel store) async { Future<void> createStore(StoreModel store) async {
try { try {
await _supabase.from('store').insert(store.toMap()); await _supabase.from(Tables.stores).insert(store.toMap());
} on PostgrestException catch (e) { } on PostgrestException catch (e) {
// Intercettiamo errori specifici del database // Intercettiamo errori specifici del database
throw e.message; throw e.message;
@@ -22,7 +24,7 @@ class StoreRepository {
Future<StoreModel> saveStore(StoreModel store) async { Future<StoreModel> saveStore(StoreModel store) async {
try { try {
final response = await _supabase final response = await _supabase
.from('store') .from(Tables.stores)
.upsert(store.toMap()) .upsert(store.toMap())
.select() .select()
.single(); .single();
@@ -41,7 +43,7 @@ class StoreRepository {
try { try {
// 1. Eliminiamo tutte le associazioni correnti per questo negozio // 1. Eliminiamo tutte le associazioni correnti per questo negozio
await _supabase await _supabase
.from('providers_in_stores') .from(Tables.providersInStores)
.delete() .delete()
.eq('store_id', storeId); .eq('store_id', storeId);
@@ -51,7 +53,7 @@ class StoreRepository {
.map((p) => {'store_id': storeId, 'provider_id': p.id}) .map((p) => {'store_id': storeId, 'provider_id': p.id})
.toList(); .toList();
await _supabase.from('providers_in_stores').insert(inserts); await _supabase.from(Tables.providersInStores).insert(inserts);
} }
} catch (e) { } catch (e) {
throw 'Errore durante la sincronizzazione provider: $e'; throw 'Errore durante la sincronizzazione provider: $e';
@@ -64,7 +66,10 @@ class StoreRepository {
) async { ) async {
try { try {
// 1. Eliminiamo tutte le associazioni correnti per questo negozio // 1. Eliminiamo tutte le associazioni correnti per questo negozio
await _supabase.from('staff_in_stores').delete().eq('store_id', storeId); await _supabase
.from(Tables.staffInStores)
.delete()
.eq('store_id', storeId);
// 2. Se ci sono nuovi dipendenti da associare, li inseriamo // 2. Se ci sono nuovi dipendenti da associare, li inseriamo
if (staffMembers.isNotEmpty) { if (staffMembers.isNotEmpty) {
@@ -72,7 +77,7 @@ class StoreRepository {
.map((s) => {'store_id': storeId, 'staff_id': s.id}) .map((s) => {'store_id': storeId, 'staff_id': s.id})
.toList(); .toList();
await _supabase.from('staff_in_stores').insert(inserts); await _supabase.from(Tables.staffInStores).insert(inserts);
} }
} catch (e) { } catch (e) {
throw 'Errore durante la sincronizzazione staff: $e'; throw 'Errore durante la sincronizzazione staff: $e';
@@ -83,16 +88,16 @@ class StoreRepository {
Future<List<StoreModel>> fetchAllCompanyStores(String companyId) async { Future<List<StoreModel>> fetchAllCompanyStores(String companyId) async {
try { try {
final response = await _supabase final response = await _supabase
.from('store') .from(Tables.stores)
.select(''' .select('''
*, *,
associated_providers:providers_in_stores ( associated_providers:${Tables.providersInStores} (
provider ( ${Tables.providers} (
* *
) )
) )
associated_staff:staff_in_stores ( associated_staff:${Tables.staffInStores} (
staff_member ( ${Tables.staffMembers} (
* *
) )
) )
@@ -111,7 +116,7 @@ class StoreRepository {
required String providerId, required String providerId,
}) async { }) async {
try { try {
await _supabase.from('providers_in_stores').insert({ await _supabase.from(Tables.providersInStores).insert({
'store_id': storeId, 'store_id': storeId,
'provider_id': providerId, 'provider_id': providerId,
}); });
@@ -126,7 +131,7 @@ class StoreRepository {
}) async { }) async {
try { try {
await _supabase await _supabase
.from('providers_in_stores') .from(Tables.providersInStores)
.delete() .delete()
.eq('store_id', storeId) .eq('store_id', storeId)
.eq('provider_id', providerId); .eq('provider_id', providerId);

View File

@@ -104,6 +104,7 @@ class OperationFormCubit extends Cubit<OperationFormState> {
batchUuid: current.batchUuid, // MANTIENE IL COLLEGAMENTO batchUuid: current.batchUuid, // MANTIENE IL COLLEGAMENTO
customerId: current.customerId, // MANTIENE IL CLIENTE customerId: current.customerId, // MANTIENE IL CLIENTE
customer: current.customer, customer: current.customer,
reference: current.reference,
status: OperationStatus.draft, status: OperationStatus.draft,
createdAt: DateTime.now(), createdAt: DateTime.now(),
), ),
@@ -122,7 +123,21 @@ class OperationFormCubit extends Cubit<OperationFormState> {
); );
try { try {
final operationToSave = state.operation.copyWith(status: targetStatus); OperationModel operationToSave = state.operation.copyWith(
status: targetStatus,
);
if (operationToSave.reference.isEmpty) {
if (operationToSave.customer != null &&
operationToSave.customer!.phoneNumber.isNotEmpty) {
operationToSave = operationToSave.copyWith(
reference: '${operationToSave.customer?.phoneNumber} - auto',
);
} else {
operationToSave = operationToSave.copyWith(
reference: 'Nessun riferimento',
);
}
}
final savedOperation = await _repository.saveFullOperation( final savedOperation = await _repository.saveFullOperation(
operation: operationToSave, operation: operationToSave,
); );

View File

@@ -1,6 +1,7 @@
import 'package:file_picker/file_picker.dart'; import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flux/core/blocs/session/session_cubit.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/core/utils/extensions.dart';
import 'package:flux/features/attachments/models/attachment_model.dart'; import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
@@ -15,15 +16,15 @@ class OperationsRepository {
Future<OperationModel> fetchOperationById(String id) async { Future<OperationModel> fetchOperationById(String id) async {
try { try {
final response = await _supabase final response = await _supabase
.from('operation') .from(Tables.operations)
.select(''' .select('''
*, *,
customer(*), ${Tables.customers}(*),
store(name), ${Tables.stores}(name),
staff_member(name), ${Tables.staffMembers}(name),
provider(name), ${Tables.providers}(name),
model(name_with_brand), ${Tables.models}(name_with_brand),
attachment(*) ${Tables.attachments}(*)
''') ''')
.eq('id', id) .eq('id', id)
.single(); .single();
@@ -44,15 +45,15 @@ class OperationsRepository {
}) async { }) async {
try { try {
var query = _supabase var query = _supabase
.from('operation') .from(Tables.operations)
.select(''' .select('''
*, *,
customer(*), ${Tables.customers}(*),
store(name), ${Tables.stores}(name),
provider(name), ${Tables.providers}(name),
model(name_with_brand), ${Tables.models}(name_with_brand),
staff_member(name), ${Tables.staffMembers}(name),
attachment(*) ${Tables.attachments}(*)
''') ''')
.eq('company_id', companyId); .eq('company_id', companyId);
@@ -87,7 +88,7 @@ class OperationsRepository {
required int limit, required int limit,
}) { }) {
return _supabase return _supabase
.from('operation') .from(Tables.operations)
.stream(primaryKey: ['id']) .stream(primaryKey: ['id'])
.eq('store_id', storeId) .eq('store_id', storeId)
.order('created_at', ascending: false) .order('created_at', ascending: false)
@@ -105,10 +106,10 @@ class OperationsRepository {
try { try {
// 1. Salvataggio classico dell'operazione corrente // 1. Salvataggio classico dell'operazione corrente
final response = await _supabase final response = await _supabase
.from('operation') .from(Tables.operations)
.upsert(operation.toMap()) .upsert(operation.toMap())
.select( .select(
'*, provider(*), model(*), store(*), staff_member(*), customer(*), attachment(*)', '*, ${Tables.providers}(*), ${Tables.models}(*), ${Tables.stores}(*), ${Tables.staffMembers}(*), ${Tables.customers}(*), ${Tables.attachments}(*)',
) )
.single(); .single();
@@ -117,7 +118,7 @@ class OperationsRepository {
// 2. ALLINEAMENTO BATCH SEMPRE ATTIVO! // 2. ALLINEAMENTO BATCH SEMPRE ATTIVO!
if (operation.batchUuid.isNotEmpty) { if (operation.batchUuid.isNotEmpty) {
await _supabase await _supabase
.from('operation') .from(Tables.operations)
.update({'note': operation.note}) // Spalmiamo la nota attuale .update({'note': operation.note}) // Spalmiamo la nota attuale
.eq( .eq(
'batch_uuid', 'batch_uuid',
@@ -134,7 +135,7 @@ class OperationsRepository {
// --- ELIMINAZIONE --- // --- ELIMINAZIONE ---
Future<void> deleteOperation(String id) async { Future<void> deleteOperation(String id) async {
try { try {
await _supabase.from('operation').delete().eq('id', id); await _supabase.from(Tables.operations).delete().eq('id', id);
} catch (e) { } catch (e) {
throw Exception('$e'); throw Exception('$e');
} }
@@ -146,7 +147,7 @@ class OperationsRepository {
// Cerchiamo i tipi più frequenti associati ai servizi di questa company // Cerchiamo i tipi più frequenti associati ai servizi di questa company
// Nota: dobbiamo passare attraverso la tabella 'operation' per filtrare per company_id // Nota: dobbiamo passare attraverso la tabella 'operation' per filtrare per company_id
final response = await _supabase final response = await _supabase
.from('operation') .from(Tables.operations)
.select('description') .select('description')
.eq('company_id', companyId) .eq('company_id', companyId)
.eq('type', 'Entertainment') .eq('type', 'Entertainment')
@@ -176,7 +177,7 @@ class OperationsRepository {
/// Ascolta in tempo reale i file caricati per una pratica /// Ascolta in tempo reale i file caricati per una pratica
Stream<List<AttachmentModel>> getOperationFilesStream(String operationId) { Stream<List<AttachmentModel>> getOperationFilesStream(String operationId) {
return _supabase return _supabase
.from('attachment') .from(Tables.attachments)
.stream(primaryKey: ['id']) .stream(primaryKey: ['id'])
.eq('operation_id', operationId) .eq('operation_id', operationId)
.order('created_at', ascending: false) .order('created_at', ascending: false)
@@ -226,7 +227,7 @@ class OperationsRepository {
} }
final response = await _supabase final response = await _supabase
.from('attachment') .from(Tables.attachments)
.insert(fileToSave.toMap()) .insert(fileToSave.toMap())
.select() .select()
.single(); .single();
@@ -242,14 +243,17 @@ class OperationsRepository {
required String customerId, required String customerId,
}) async { }) async {
await _supabase await _supabase
.from('attachment') .from(Tables.attachments)
.update({'customer_id': customerId}) .update({'customer_id': customerId})
.eq('id', file.id!); .eq('id', file.id!);
} }
Future<void> renameAttachment(String id, String newName) async { Future<void> renameAttachment(String id, String newName) async {
try { try {
await _supabase.from('attachment').update({'name': newName}).eq('id', id); await _supabase
.from(Tables.attachments)
.update({'name': newName})
.eq('id', id);
} catch (e) { } catch (e) {
throw '$e'; throw '$e';
} }
@@ -258,11 +262,11 @@ class OperationsRepository {
Future<void> deleteSpecificOperationFile(AttachmentModel file) async { Future<void> deleteSpecificOperationFile(AttachmentModel file) async {
try { try {
if (file.customerId == null) { if (file.customerId == null) {
await _supabase.from('attachment').delete().eq('id', file.id!); await _supabase.from(Tables.attachments).delete().eq('id', file.id!);
await _supabase.storage.from('documents').remove([file.storagePath!]); await _supabase.storage.from('documents').remove([file.storagePath!]);
} else { } else {
await _supabase await _supabase
.from('attachment') .from(Tables.attachments)
.update({'operation_id': null}) .update({'operation_id': null})
.eq('id', file.id!); .eq('id', file.id!);
} }
@@ -287,12 +291,15 @@ class OperationsRepository {
} }
try { try {
if (idsToDelete.isNotEmpty) { if (idsToDelete.isNotEmpty) {
await _supabase.from('attachment').delete().inFilter('id', idsToDelete); await _supabase
.from(Tables.attachments)
.delete()
.inFilter('id', idsToDelete);
await _supabase.storage.from('documents').remove(storagePathsToDelete); await _supabase.storage.from('documents').remove(storagePathsToDelete);
} }
if (idsToEdit.isNotEmpty) { if (idsToEdit.isNotEmpty) {
await _supabase await _supabase
.from('attachment') .from(Tables.attachments)
.update({'operation_id': null}) .update({'operation_id': null})
.inFilter('id', idsToEdit); .inFilter('id', idsToEdit);
} }

View File

@@ -1,4 +1,5 @@
import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/settings/document_sequence/models/document_sequence_model.dart'; import 'package:flux/features/settings/document_sequence/models/document_sequence_model.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/supabase_flutter.dart';
@@ -10,7 +11,7 @@ class DocumentSequenceRepository {
Future<List<DocumentSequence>> getDocumentSequences() async { Future<List<DocumentSequence>> getDocumentSequences() async {
try { try {
final response = await _supabase final response = await _supabase
.from('document_sequences') .from(Tables.documentSequences)
.select() .select()
.eq('company_id', _companyId); .eq('company_id', _companyId);
@@ -39,7 +40,7 @@ class DocumentSequenceRepository {
required DocumentSequence sequence, required DocumentSequence sequence,
}) async { }) async {
try { try {
await _supabase.from('document_sequences').upsert({ await _supabase.from(Tables.documentSequences).upsert({
'company_id': _companyId, 'company_id': _companyId,
'doc_type': sequence.docType, 'doc_type': sequence.docType,
'next_value': sequence.nextValue, 'next_value': sequence.nextValue,
@@ -51,7 +52,7 @@ class DocumentSequenceRepository {
} }
Future<void> updateSequence({required DocumentSequence sequence}) async { Future<void> updateSequence({required DocumentSequence sequence}) async {
await _supabase.from('document_sequences').upsert({ await _supabase.from(Tables.documentSequences).upsert({
'company_id': _companyId, 'company_id': _companyId,
'doc_type': sequence.docType, 'doc_type': sequence.docType,
'next_value': sequence.nextValue, 'next_value': sequence.nextValue,

View File

@@ -1,4 +1,4 @@
import 'package:flux/core/enums/enums.dart'; import 'package:flux/core/enums_and_consts/enums.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';

View File

@@ -1,6 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/enums/enums.dart'; import 'package:flux/core/enums_and_consts/enums.dart';
import 'package:flux/core/theme/theme.dart'; import 'package:flux/core/theme/theme.dart';
import 'package:flux/core/theme/bloc/theme_bloc.dart'; import 'package:flux/core/theme/bloc/theme_bloc.dart';

View File

@@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/settings/document_sequence/data/document_sequence_repository.dart'; import 'package:flux/features/settings/document_sequence/data/document_sequence_repository.dart';
import 'package:flux/features/settings/document_sequence/models/document_sequence_model.dart'; import 'package:flux/features/settings/document_sequence/models/document_sequence_model.dart';
import 'package:flux/features/tickets/models/ticket_model.dart'; import 'package:flux/features/tickets/models/ticket_model.dart';
@@ -13,7 +14,7 @@ class TicketRepository {
TicketRepository(); TicketRepository();
static const String _tableName = 'ticket'; static const String _tableName = Tables.tickets;
// --- RECUPERO PAGINATO CON FILTRI E JOIN DEI TICKET DI UNO STORE --- // --- RECUPERO PAGINATO CON FILTRI E JOIN DEI TICKET DI UNO STORE ---
Future<List<TicketModel>> fetchStoreTickets({ Future<List<TicketModel>> fetchStoreTickets({
@@ -30,12 +31,12 @@ class TicketRepository {
.from(_tableName) .from(_tableName)
.select(''' .select('''
*, *,
customer (*), ${Tables.customers} (*),
shipping_documents (*, attachment (*)), ${Tables.shippingDocuments} (*, ${Tables.attachments} (*)),
created_by:staff_member!ticket_staff_id_fkey (*), created_by:${Tables.staffMembers}!ticket_staff_id_fkey (*),
assigned_to:staff_member!ticket_assigned_to_id_fkey (*), assigned_to:${Tables.staffMembers}!ticket_assigned_to_id_fkey (*),
target_model:model!ticket_model_id_1_fkey (*), target_model:${Tables.models}!ticket_model_id_1_fkey (*),
source_model:model!ticket_model_id_2_fkey (*) source_model:${Tables.models}!ticket_model_id_2_fkey (*)
''') ''')
.eq('store_id', GetIt.I.get<SessionCubit>().state.currentStore!.id!); .eq('store_id', GetIt.I.get<SessionCubit>().state.currentStore!.id!);
@@ -88,12 +89,12 @@ class TicketRepository {
.from(_tableName) .from(_tableName)
.select(''' .select('''
*, *,
customer (*), ${Tables.customers} (*),
shipping_documents (*, attachment (*)), ${Tables.shippingDocuments} (*, ${Tables.attachments} (*)),
created_by:staff_member!ticket_staff_id_fkey (*), created_by:${Tables.staffMembers}!ticket_staff_id_fkey (*),
assigned_to:staff_member!ticket_assigned_to_id_fkey (*), assigned_to:${Tables.staffMembers}!ticket_assigned_to_id_fkey (*),
target_model:model!ticket_model_id_1_fkey (*), target_model:${Tables.models}!ticket_model_id_1_fkey (*),
source_model:model!ticket_model_id_2_fkey (*) source_model:${Tables.models}!ticket_model_id_2_fkey (*)
''') ''')
.eq('company_id', GetIt.I.get<SessionCubit>().state.company!.id!); .eq('company_id', GetIt.I.get<SessionCubit>().state.company!.id!);
@@ -199,12 +200,12 @@ class TicketRepository {
.from(_tableName) .from(_tableName)
.select(''' .select('''
*, *,
customer (*), ${Tables.customers} (*),
target_model:model!ticket_model_id_1_fkey (*), target_model:${Tables.models}!ticket_model_id_1_fkey (*),
source_model:model!ticket_model_id_2_fkey (*), source_model:${Tables.models}!ticket_model_id_2_fkey (*),
created_by:staff_member!ticket_staff_id_fkey (*), created_by:${Tables.staffMembers}!ticket_staff_id_fkey (*),
assigned_to:staff_member!ticket_assigned_to_id_fkey (*), assigned_to:${Tables.staffMembers}!ticket_assigned_to_id_fkey (*),
shipping_documents (*, attachment (*)) ${Tables.shippingDocuments} (*, ${Tables.attachments} (*))
''') ''')
.eq('id', ticketId) .eq('id', ticketId)
.single(); .single();
@@ -215,30 +216,6 @@ class TicketRepository {
} }
} }
// Future<String> generateTicketReference(String companyId) async {
// final response = await Supabase.instance.client.rpc(
// 'get_next_document_number',
// params: {'p_company_id': companyId, 'p_doc_type': 'ticket'},
// );
// // Estraiamo i dati dal JSON
// final int nextValue = response['next_value'];
// final String prefix = response['prefix'] ?? '';
// final year = DateTime.now().year; // 2026
// // Formattazione con zeri iniziali (es. 000125)
// final paddedNumber = nextValue.toString().padLeft(6, '0');
// // Costruiamo la stringa. Se c'è un prefisso mette "TCK-2026-000125",
// // altrimenti solo "2026-000125"
// if (prefix.isNotEmpty) {
// return '$prefix-$year-$paddedNumber';
// } else {
// return '$year-$paddedNumber';
// }
// }
/// Salva il ticket /// Salva il ticket
Future<TicketModel> insertTicket(TicketModel ticket) async { Future<TicketModel> insertTicket(TicketModel ticket) async {
if (ticket.id != null) { if (ticket.id != null) {

View File

@@ -1,3 +1,4 @@
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/tracking/models/tracking_model.dart'; import 'package:flux/features/tracking/models/tracking_model.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/supabase_flutter.dart';
@@ -14,8 +15,8 @@ class TrackingRepository {
}) async { }) async {
// Facciamo la query con la JOIN per recuperare il nome dello staff al volo // Facciamo la query con la JOIN per recuperare il nome dello staff al volo
final response = await _supabase final response = await _supabase
.from('tracking') .from(Tables.trackings)
.select('*, staff_member(name)') .select('*, ${Tables.staffMembers}(name)')
.eq('parent_id', parentId) .eq('parent_id', parentId)
.eq('parent_type', parentType.name) .eq('parent_type', parentType.name)
.order('created_at', ascending: false); .order('created_at', ascending: false);
@@ -25,7 +26,7 @@ class TrackingRepository {
/// Inserisce un nuovo evento di tracking /// Inserisce un nuovo evento di tracking
Future<void> logEvent(TrackingModel tracking) async { Future<void> logEvent(TrackingModel tracking) async {
await _supabase.from('tracking').insert(tracking.toMap()); await _supabase.from(Tables.trackings).insert(tracking.toMap());
} }
/// Metodo helper rapido per loggare un cambio di stato o una nota /// Metodo helper rapido per loggare un cambio di stato o una nota