providers-in-store (#4)
Reviewed-on: http://catelliub.zapto.org:3000/brontomark/flux/pulls/4 Co-authored-by: mark-cachy <marco@catelli.it> Co-committed-by: mark-cachy <marco@catelli.it>
This commit is contained in:
@@ -71,9 +71,7 @@ class SessionBloc extends Bloc<SessionEvent, SessionState> {
|
|||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final availableStores = stores
|
final availableStores = stores.map((s) => StoreModel.fromMap(s)).toList();
|
||||||
.map((s) => StoreModel.fromJson(s))
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
// 3. Tutto ok, gestiamo le SharedPreferences per il negozio
|
// 3. Tutto ok, gestiamo le SharedPreferences per il negozio
|
||||||
final prefs = GetIt.I.get<SharedPreferences>();
|
final prefs = GetIt.I.get<SharedPreferences>();
|
||||||
@@ -84,7 +82,7 @@ class SessionBloc extends Bloc<SessionEvent, SessionState> {
|
|||||||
lastStoreId = stores.first['id'];
|
lastStoreId = stores.first['id'];
|
||||||
await prefs.setString('last_store_id', lastStoreId!);
|
await prefs.setString('last_store_id', lastStoreId!);
|
||||||
}
|
}
|
||||||
final selectedStore = StoreModel.fromJson(
|
final selectedStore = StoreModel.fromMap(
|
||||||
stores.firstWhere((s) => s['id'] == lastStoreId),
|
stores.firstWhere((s) => s['id'] == lastStoreId),
|
||||||
);
|
);
|
||||||
emit(
|
emit(
|
||||||
|
|||||||
@@ -40,29 +40,22 @@ class ProviderRepository {
|
|||||||
// Recupera tutti i provider di una company (per la lista generale)
|
// Recupera tutti i provider di una company (per la lista generale)
|
||||||
Future<List<ProviderModel>> fetchAllCompanyProviders(String companyId) async {
|
Future<List<ProviderModel>> fetchAllCompanyProviders(String companyId) async {
|
||||||
try {
|
try {
|
||||||
// La magia è qui: selezioniamo tutto e chiediamo il conteggio (count)
|
|
||||||
// della tabella pivot providers_in_stores
|
|
||||||
final response = await _supabase
|
final response = await _supabase
|
||||||
.from('provider')
|
.from('provider')
|
||||||
.select('''
|
.select('''
|
||||||
*,
|
*,
|
||||||
providers_in_stores(count)
|
associated_stores:providers_in_stores (
|
||||||
|
store (
|
||||||
|
*
|
||||||
|
)
|
||||||
|
)
|
||||||
''')
|
''')
|
||||||
.eq('company_id', companyId)
|
.eq('company_id', companyId)
|
||||||
.order('nome');
|
.order('nome');
|
||||||
|
|
||||||
return (response as List).map((m) {
|
return (response as List).map((m) => ProviderModel.fromMap(m)).toList();
|
||||||
// Estraiamo il conteggio dalla struttura restituita da Supabase
|
|
||||||
// La risposta per ogni riga sarà tipo: { "id": "...", "providers_in_stores": [{"count": 5}] }
|
|
||||||
final storesList = m['providers_in_stores'] as List?;
|
|
||||||
final count = (storesList != null && storesList.isNotEmpty)
|
|
||||||
? storesList[0]['count'] as int
|
|
||||||
: 0;
|
|
||||||
|
|
||||||
return ProviderModel.fromMap(m).copyWith(storesCount: count);
|
|
||||||
}).toList();
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw Exception('Errore fetch all providers: $e');
|
throw 'Errore fetch providers: $e';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import 'package:equatable/equatable.dart';
|
import 'package:equatable/equatable.dart';
|
||||||
|
import 'package:flux/features/master_data/store/models/store_model.dart';
|
||||||
|
|
||||||
class ProviderModel extends Equatable {
|
class ProviderModel extends Equatable {
|
||||||
final String? id;
|
final String? id;
|
||||||
@@ -11,7 +12,7 @@ class ProviderModel extends Equatable {
|
|||||||
final bool altro;
|
final bool altro;
|
||||||
final bool isActive;
|
final bool isActive;
|
||||||
final String companyId;
|
final String companyId;
|
||||||
final int storesCount;
|
final List<StoreModel> associatedStores;
|
||||||
|
|
||||||
const ProviderModel({
|
const ProviderModel({
|
||||||
this.id,
|
this.id,
|
||||||
@@ -24,10 +25,21 @@ class ProviderModel extends Equatable {
|
|||||||
required this.altro,
|
required this.altro,
|
||||||
required this.isActive,
|
required this.isActive,
|
||||||
required this.companyId,
|
required this.companyId,
|
||||||
this.storesCount = 0, // Numero di store associati, default a 0
|
this.associatedStores = const [],
|
||||||
});
|
});
|
||||||
|
|
||||||
factory ProviderModel.fromMap(Map<String, dynamic> map) {
|
factory ProviderModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
// Estraiamo la lista dalla pivot e poi prendiamo l'oggetto 'store' annidato
|
||||||
|
final pivotList = map['associated_stores'] as List?;
|
||||||
|
List<StoreModel> stores = [];
|
||||||
|
if (pivotList != null) {
|
||||||
|
stores = pivotList
|
||||||
|
.where((item) => item['store'] != null) // Sicurezza
|
||||||
|
.map(
|
||||||
|
(item) => StoreModel.fromMap(item['store'] as Map<String, dynamic>),
|
||||||
|
)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
return ProviderModel(
|
return ProviderModel(
|
||||||
id: map['id'],
|
id: map['id'],
|
||||||
nome: map['nome'],
|
nome: map['nome'],
|
||||||
@@ -39,11 +51,7 @@ class ProviderModel extends Equatable {
|
|||||||
altro: map['altro'] ?? false,
|
altro: map['altro'] ?? false,
|
||||||
isActive: map['is_active'] ?? true,
|
isActive: map['is_active'] ?? true,
|
||||||
companyId: map['company_id'],
|
companyId: map['company_id'],
|
||||||
storesCount:
|
associatedStores: stores,
|
||||||
map['providers_in_stores'] != null &&
|
|
||||||
map['providers_in_stores'].isNotEmpty
|
|
||||||
? map['providers_in_stores'][0]['count'] as int
|
|
||||||
: 0, // Assumiamo che l'API possa restituire questo campo
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,7 +87,7 @@ class ProviderModel extends Equatable {
|
|||||||
altro,
|
altro,
|
||||||
isActive,
|
isActive,
|
||||||
companyId,
|
companyId,
|
||||||
storesCount,
|
associatedStores,
|
||||||
];
|
];
|
||||||
|
|
||||||
ProviderModel copyWith({
|
ProviderModel copyWith({
|
||||||
@@ -93,7 +101,7 @@ class ProviderModel extends Equatable {
|
|||||||
bool? altro,
|
bool? altro,
|
||||||
bool? isActive,
|
bool? isActive,
|
||||||
String? companyId,
|
String? companyId,
|
||||||
int? storesCount,
|
List<StoreModel>? associatedStores,
|
||||||
}) {
|
}) {
|
||||||
return ProviderModel(
|
return ProviderModel(
|
||||||
id: id ?? this.id,
|
id: id ?? this.id,
|
||||||
@@ -106,7 +114,7 @@ class ProviderModel extends Equatable {
|
|||||||
altro: altro ?? this.altro,
|
altro: altro ?? this.altro,
|
||||||
isActive: isActive ?? this.isActive,
|
isActive: isActive ?? this.isActive,
|
||||||
companyId: companyId ?? this.companyId,
|
companyId: companyId ?? this.companyId,
|
||||||
storesCount: storesCount ?? this.storesCount,
|
associatedStores: associatedStores ?? this.associatedStores,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,9 @@ class _ProviderFormSheetState extends State<ProviderFormSheet> {
|
|||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
final p = widget.initialProvider;
|
final p = widget.initialProvider;
|
||||||
|
for (final store in p?.associatedStores ?? []) {
|
||||||
|
_tempSelectedStoreIds.add(store.id!);
|
||||||
|
}
|
||||||
_nameController = TextEditingController(text: p?.nome ?? '');
|
_nameController = TextEditingController(text: p?.nome ?? '');
|
||||||
_telefoniaFissa = p?.telefoniaFissa ?? false;
|
_telefoniaFissa = p?.telefoniaFissa ?? false;
|
||||||
_telefoniaMobile = p?.telefoniaMobile ?? false;
|
_telefoniaMobile = p?.telefoniaMobile ?? false;
|
||||||
|
|||||||
@@ -17,8 +17,6 @@ class _ProvidersMasterDataScreenState extends State<ProvidersMasterDataScreen> {
|
|||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
// Carichiamo i provider della company (senza store specifico per ora)
|
|
||||||
context.read<ProvidersCubit>().loadProviders(null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -126,7 +124,7 @@ class _ProvidersMasterDataScreenState extends State<ProvidersMasterDataScreen> {
|
|||||||
// Un piccolo testo che indica il numero di store associati
|
// Un piccolo testo che indica il numero di store associati
|
||||||
// Nota: Dovrai assicurarti che il Cubit carichi queste info
|
// Nota: Dovrai assicurarti che il Cubit carichi queste info
|
||||||
return Text(
|
return Text(
|
||||||
"Disponibile in ${provider.storesCount} negozi",
|
"Disponibile in ${provider.associatedStores.length} negozi",
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 11,
|
fontSize: 11,
|
||||||
color: Colors.indigo.withValues(alpha: 0.7),
|
color: Colors.indigo.withValues(alpha: 0.7),
|
||||||
|
|||||||
@@ -16,17 +16,17 @@ class StaffRepository {
|
|||||||
.eq('company_id', companyId)
|
.eq('company_id', companyId)
|
||||||
.order('name', ascending: true);
|
.order('name', ascending: true);
|
||||||
|
|
||||||
return (response as List).map((s) => StaffMemberModel.fromJson(s)).toList();
|
return (response as List).map((s) => StaffMemberModel.fromMap(s)).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<StaffMemberModel> saveStaffMember(StaffMemberModel member) async {
|
Future<StaffMemberModel> saveStaffMember(StaffMemberModel member) async {
|
||||||
final response = await _supabase
|
final response = await _supabase
|
||||||
.from('staff_member')
|
.from('staff_member')
|
||||||
.upsert(member.toJson())
|
.upsert(member.toMap())
|
||||||
.select()
|
.select()
|
||||||
.single();
|
.single();
|
||||||
|
|
||||||
return StaffMemberModel.fromJson(response);
|
return StaffMemberModel.fromMap(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- LOGICA DI GIUNZIONE (Staff <-> Store) ---
|
// --- LOGICA DI GIUNZIONE (Staff <-> Store) ---
|
||||||
@@ -42,7 +42,7 @@ class StaffRepository {
|
|||||||
.eq('store_id', storeId);
|
.eq('store_id', storeId);
|
||||||
|
|
||||||
return (response as List)
|
return (response as List)
|
||||||
.map((item) => StaffMemberModel.fromJson(item['staff_member']))
|
.map((item) => StaffMemberModel.fromMap(item['staff_member']))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +57,7 @@ class StaffRepository {
|
|||||||
.eq('staff_member_id', staffId);
|
.eq('staff_member_id', staffId);
|
||||||
|
|
||||||
return (response as List)
|
return (response as List)
|
||||||
.map((item) => StoreModel.fromJson(item['store']))
|
.map((item) => StoreModel.fromMap(item['store']))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,20 +18,20 @@ class StaffMemberModel extends Equatable {
|
|||||||
required this.companyId,
|
required this.companyId,
|
||||||
});
|
});
|
||||||
|
|
||||||
factory StaffMemberModel.fromJson(Map<String, dynamic> json) {
|
factory StaffMemberModel.fromMap(Map<String, dynamic> map) {
|
||||||
return StaffMemberModel(
|
return StaffMemberModel(
|
||||||
id: json['id'],
|
id: map['id'],
|
||||||
// Applichiamo il tuo myFormat per visualizzare i nomi correttamente
|
// Applichiamo il tuo myFormat per visualizzare i nomi correttamente
|
||||||
name: (json['name'] as String).myFormat(),
|
name: (map['name'] as String).myFormat(),
|
||||||
// L'email la teniamo lowercase per standard tecnico
|
// L'email la teniamo lowercase per standard tecnico
|
||||||
email: (json['email'] as String? ?? '').toLowerCase().trim(),
|
email: (map['email'] as String? ?? '').toLowerCase().trim(),
|
||||||
phone: (json['phone'] as String? ?? '').trim(),
|
phone: (map['phone'] as String? ?? '').trim(),
|
||||||
isActive: json['is_active'] ?? true,
|
isActive: map['is_active'] ?? true,
|
||||||
companyId: json['company_id'],
|
companyId: map['company_id'],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, dynamic> toJson() {
|
Map<String, dynamic> toMap() {
|
||||||
return {
|
return {
|
||||||
if (id != null) 'id': id,
|
if (id != null) 'id': id,
|
||||||
'name': name.toLowerCase().trim(), // Salviamo pulito per le query
|
'name': name.toLowerCase().trim(), // Salviamo pulito per le query
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
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/blocs/session/session_bloc.dart';
|
import 'package:flux/core/blocs/session/session_bloc.dart';
|
||||||
|
import 'package:flux/features/master_data/providers/models/provider_model.dart';
|
||||||
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
|
import 'package:flux/features/master_data/staff/data/staff_repository.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/data/store_repository.dart';
|
import 'package:flux/features/master_data/store/data/store_repository.dart';
|
||||||
@@ -31,7 +32,7 @@ class StoreCubit extends Cubit<StoreState> {
|
|||||||
Future<void> loadStores() async {
|
Future<void> loadStores() async {
|
||||||
emit(state.copyWith(status: StoreStatus.loading));
|
emit(state.copyWith(status: StoreStatus.loading));
|
||||||
try {
|
try {
|
||||||
final stores = await _repository.getStoresByCompany(
|
final stores = await _repository.fetchAllCompanyStores(
|
||||||
_sessionBloc.state.company!.id,
|
_sessionBloc.state.company!.id,
|
||||||
);
|
);
|
||||||
final Map<String, List<StaffMemberModel>> staffByStore = {};
|
final Map<String, List<StaffMemberModel>> staffByStore = {};
|
||||||
@@ -54,18 +55,91 @@ class StoreCubit extends Cubit<StoreState> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> saveProvidersForStore(
|
||||||
|
StoreModel store,
|
||||||
|
List<ProviderModel> providers,
|
||||||
|
) async {
|
||||||
|
emit(state.copyWith(status: StoreStatus.loading));
|
||||||
|
|
||||||
|
try {
|
||||||
|
final savedStore = await _repository.saveStore(store);
|
||||||
|
await _repository.syncStoreProviders(savedStore.id!, providers);
|
||||||
|
await loadStores();
|
||||||
|
} catch (e) {
|
||||||
|
emit(
|
||||||
|
state.copyWith(
|
||||||
|
status: StoreStatus.failure,
|
||||||
|
errorMessage: "Errore nel salvataggio dei provider: $e",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> saveStaffForStore(
|
||||||
|
StoreModel store,
|
||||||
|
List<StaffMemberModel> staffMembers,
|
||||||
|
) async {
|
||||||
|
emit(state.copyWith(status: StoreStatus.loading));
|
||||||
|
|
||||||
|
try {
|
||||||
|
final savedStore = await _repository.saveStore(store);
|
||||||
|
await _repository.syncStoreStaff(savedStore.id!, staffMembers);
|
||||||
|
await loadStores();
|
||||||
|
} catch (e) {
|
||||||
|
emit(
|
||||||
|
state.copyWith(
|
||||||
|
status: StoreStatus.failure,
|
||||||
|
errorMessage: "Errore nel salvataggio dello staff: $e",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> associateStoreToProvider(
|
||||||
|
String storeId,
|
||||||
|
String providerId,
|
||||||
|
) async {
|
||||||
|
try {
|
||||||
|
await _repository.associateStoreToProvider(
|
||||||
|
providerId: providerId,
|
||||||
|
storeId: storeId,
|
||||||
|
);
|
||||||
|
loadStores();
|
||||||
|
} catch (e) {
|
||||||
|
emit(
|
||||||
|
state.copyWith(
|
||||||
|
status: StoreStatus.failure,
|
||||||
|
errorMessage: "Errore nell'associazione: $e",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> removeProviderFromStore(
|
||||||
|
String storeId,
|
||||||
|
String providerId,
|
||||||
|
) async {
|
||||||
|
try {
|
||||||
|
await _repository.removeStoreFromProvider(
|
||||||
|
providerId: providerId,
|
||||||
|
storeId: storeId,
|
||||||
|
);
|
||||||
|
loadStores();
|
||||||
|
} catch (e) {
|
||||||
|
emit(
|
||||||
|
state.copyWith(
|
||||||
|
status: StoreStatus.failure,
|
||||||
|
errorMessage: "Errore nella rimozione: $e",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> assignStaffToStore(String storeId, String staffId) async {
|
Future<void> assignStaffToStore(String storeId, String staffId) async {
|
||||||
try {
|
try {
|
||||||
await _staffRepository.assignToStore(staffId, storeId);
|
await _staffRepository.assignToStore(staffId, storeId);
|
||||||
// Dopo l'assegnazione, potresti voler ricaricare lo staff per quel negozio
|
// Dopo l'assegnazione, potresti voler ricaricare lo staff per quel negozio
|
||||||
final updatedStaff = await _staffRepository.getStaffMembersInStore(
|
loadStores();
|
||||||
storeId,
|
|
||||||
);
|
|
||||||
final newMap = Map<String, List<StaffMemberModel>>.from(
|
|
||||||
state.staffByStore,
|
|
||||||
);
|
|
||||||
newMap[storeId] = updatedStaff;
|
|
||||||
emit(state.copyWith(status: StoreStatus.success, staffByStore: newMap));
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
emit(
|
emit(
|
||||||
state.copyWith(status: StoreStatus.failure, errorMessage: e.toString()),
|
state.copyWith(status: StoreStatus.failure, errorMessage: e.toString()),
|
||||||
@@ -77,14 +151,7 @@ class StoreCubit extends Cubit<StoreState> {
|
|||||||
Future<void> removeStaffFromStore(String staffId, String storeId) async {
|
Future<void> removeStaffFromStore(String staffId, String storeId) async {
|
||||||
try {
|
try {
|
||||||
await _staffRepository.removeFromStore(staffId, storeId);
|
await _staffRepository.removeFromStore(staffId, storeId);
|
||||||
final updatedStaff = await _staffRepository.getStaffMembersInStore(
|
loadStores();
|
||||||
storeId,
|
|
||||||
);
|
|
||||||
final newMap = Map<String, List<StaffMemberModel>>.from(
|
|
||||||
state.staffByStore,
|
|
||||||
);
|
|
||||||
newMap[storeId] = updatedStaff;
|
|
||||||
emit(state.copyWith(staffByStore: newMap));
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
emit(
|
emit(
|
||||||
state.copyWith(
|
state.copyWith(
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
|
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: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/store_model.dart';
|
import '../models/store_model.dart';
|
||||||
|
|
||||||
class StoreRepository {
|
class StoreRepository {
|
||||||
final SupabaseClient _client = GetIt.I.get<SupabaseClient>();
|
final SupabaseClient _supabase = GetIt.I.get<SupabaseClient>();
|
||||||
|
|
||||||
/// 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 _client.from('store').insert(store.toJson());
|
await _supabase.from('store').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;
|
||||||
@@ -17,20 +19,119 @@ class StoreRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Recupera tutti i negozi di una determinata compagnia
|
Future<StoreModel> saveStore(StoreModel store) async {
|
||||||
Future<List<StoreModel>> getStoresByCompany(String companyId) async {
|
|
||||||
try {
|
try {
|
||||||
final response = await _client
|
final response = await _supabase
|
||||||
.from('store')
|
.from('store')
|
||||||
|
.upsert(store.toMap())
|
||||||
.select()
|
.select()
|
||||||
.eq('company_id', companyId)
|
.single();
|
||||||
.order('created_at');
|
return StoreModel.fromMap(response);
|
||||||
|
} on PostgrestException catch (e) {
|
||||||
return (response as List)
|
throw e.message;
|
||||||
.map((json) => StoreModel.fromJson(json))
|
|
||||||
.toList();
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw 'Errore nel recupero dei negozi';
|
throw 'Errore imprevisto durante il salvataggio del negozio: $e';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> syncStoreProviders(
|
||||||
|
String storeId,
|
||||||
|
List<ProviderModel> providers,
|
||||||
|
) async {
|
||||||
|
try {
|
||||||
|
// 1. Eliminiamo tutte le associazioni correnti per questo negozio
|
||||||
|
await _supabase
|
||||||
|
.from('providers_in_stores')
|
||||||
|
.delete()
|
||||||
|
.eq('store_id', storeId);
|
||||||
|
|
||||||
|
// 2. Se ci sono nuovi provider da associare, li inseriamo
|
||||||
|
if (providers.isNotEmpty) {
|
||||||
|
final inserts = providers
|
||||||
|
.map((p) => {'store_id': storeId, 'provider_id': p.id})
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
await _supabase.from('providers_in_stores').insert(inserts);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
throw 'Errore durante la sincronizzazione provider: $e';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> syncStoreStaff(
|
||||||
|
String storeId,
|
||||||
|
List<StaffMemberModel> staffMembers,
|
||||||
|
) async {
|
||||||
|
try {
|
||||||
|
// 1. Eliminiamo tutte le associazioni correnti per questo negozio
|
||||||
|
await _supabase.from('staff_in_stores').delete().eq('store_id', storeId);
|
||||||
|
|
||||||
|
// 2. Se ci sono nuovi dipendenti da associare, li inseriamo
|
||||||
|
if (staffMembers.isNotEmpty) {
|
||||||
|
final inserts = staffMembers
|
||||||
|
.map((s) => {'store_id': storeId, 'staff_id': s.id})
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
await _supabase.from('staff_in_stores').insert(inserts);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
throw 'Errore durante la sincronizzazione staff: $e';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recupera tutti i negozi di una determinata compagnia
|
||||||
|
Future<List<StoreModel>> fetchAllCompanyStores(String companyId) async {
|
||||||
|
try {
|
||||||
|
final response = await _supabase
|
||||||
|
.from('store')
|
||||||
|
.select('''
|
||||||
|
*,
|
||||||
|
associated_providers:providers_in_stores (
|
||||||
|
provider (
|
||||||
|
*
|
||||||
|
)
|
||||||
|
)
|
||||||
|
associated_staff:staff_in_stores (
|
||||||
|
staff_member (
|
||||||
|
*
|
||||||
|
)
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
.eq('company_id', companyId)
|
||||||
|
.order('nome');
|
||||||
|
|
||||||
|
return (response as List).map((m) => StoreModel.fromMap(m)).toList();
|
||||||
|
} catch (e) {
|
||||||
|
throw 'Errore nel recupero dei negozi: $e';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> associateStoreToProvider({
|
||||||
|
required String storeId,
|
||||||
|
required String providerId,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
await _supabase.from('providers_in_stores').insert({
|
||||||
|
'store_id': storeId,
|
||||||
|
'provider_id': providerId,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
throw 'Errore durante l\'associazione del negozio al provider: $e';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> removeStoreFromProvider({
|
||||||
|
required String storeId,
|
||||||
|
required String providerId,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
await _supabase
|
||||||
|
.from('providers_in_stores')
|
||||||
|
.delete()
|
||||||
|
.eq('store_id', storeId)
|
||||||
|
.eq('provider_id', providerId);
|
||||||
|
} catch (e) {
|
||||||
|
throw 'Errore durante la rimozione del negozio dal provider: $e';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import 'package:equatable/equatable.dart';
|
import 'package:equatable/equatable.dart';
|
||||||
|
import 'package:flux/features/master_data/providers/models/provider_model.dart';
|
||||||
|
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||||
|
|
||||||
class StoreModel extends Equatable {
|
class StoreModel extends Equatable {
|
||||||
final String? id;
|
final String? id;
|
||||||
@@ -11,6 +13,9 @@ class StoreModel extends Equatable {
|
|||||||
final String cap;
|
final String cap;
|
||||||
final String comune;
|
final String comune;
|
||||||
final String provincia;
|
final String provincia;
|
||||||
|
final List<ProviderModel> associatedProviders; // Provider associati
|
||||||
|
final List<StaffMemberModel>
|
||||||
|
associatedStaffMembers; // Membri dello staff associati
|
||||||
|
|
||||||
const StoreModel({
|
const StoreModel({
|
||||||
this.id,
|
this.id,
|
||||||
@@ -23,6 +28,8 @@ class StoreModel extends Equatable {
|
|||||||
required this.cap,
|
required this.cap,
|
||||||
required this.comune,
|
required this.comune,
|
||||||
required this.provincia,
|
required this.provincia,
|
||||||
|
this.associatedProviders = const [],
|
||||||
|
this.associatedStaffMembers = const [],
|
||||||
});
|
});
|
||||||
|
|
||||||
// Fondamentale per Equatable: definisce quali proprietà determinano l'uguaglianza
|
// Fondamentale per Equatable: definisce quali proprietà determinano l'uguaglianza
|
||||||
@@ -38,6 +45,8 @@ class StoreModel extends Equatable {
|
|||||||
cap,
|
cap,
|
||||||
comune,
|
comune,
|
||||||
provincia,
|
provincia,
|
||||||
|
associatedProviders,
|
||||||
|
associatedStaffMembers,
|
||||||
];
|
];
|
||||||
|
|
||||||
// Il mitico copyWith per creare nuove istanze modificando solo ciò che serve
|
// Il mitico copyWith per creare nuove istanze modificando solo ciò che serve
|
||||||
@@ -52,6 +61,8 @@ class StoreModel extends Equatable {
|
|||||||
String? cap,
|
String? cap,
|
||||||
String? comune,
|
String? comune,
|
||||||
String? provincia,
|
String? provincia,
|
||||||
|
List<ProviderModel>? associatedProviders,
|
||||||
|
List<StaffMemberModel>? associatedStaffMembers,
|
||||||
}) {
|
}) {
|
||||||
return StoreModel(
|
return StoreModel(
|
||||||
id: id ?? this.id,
|
id: id ?? this.id,
|
||||||
@@ -64,27 +75,55 @@ class StoreModel extends Equatable {
|
|||||||
cap: cap ?? this.cap,
|
cap: cap ?? this.cap,
|
||||||
comune: comune ?? this.comune,
|
comune: comune ?? this.comune,
|
||||||
provincia: provincia ?? this.provincia,
|
provincia: provincia ?? this.provincia,
|
||||||
|
associatedProviders: associatedProviders ?? this.associatedProviders,
|
||||||
|
associatedStaffMembers:
|
||||||
|
associatedStaffMembers ?? this.associatedStaffMembers,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
factory StoreModel.fromJson(Map<String, dynamic> json) {
|
factory StoreModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
final providersPivotList = map['associated_providers'] as List?;
|
||||||
|
List<ProviderModel> providers = [];
|
||||||
|
if (providersPivotList != null) {
|
||||||
|
providers = providersPivotList
|
||||||
|
.where((item) => item['provider'] != null) // Sicurezza
|
||||||
|
.map(
|
||||||
|
(item) =>
|
||||||
|
ProviderModel.fromMap(item['provider'] as Map<String, dynamic>),
|
||||||
|
)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
final staffPivotList = map['associated_staff'] as List?;
|
||||||
|
List<StaffMemberModel> staffMembers = [];
|
||||||
|
if (staffPivotList != null) {
|
||||||
|
staffMembers = staffPivotList
|
||||||
|
.where((item) => item['staff_member'] != null) // Sicurezza
|
||||||
|
.map(
|
||||||
|
(item) => StaffMemberModel.fromMap(
|
||||||
|
item['staff_member'] as Map<String, dynamic>,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
return StoreModel(
|
return StoreModel(
|
||||||
id: json['id'] as String,
|
id: map['id'] as String,
|
||||||
nome: json['nome'],
|
nome: map['nome'],
|
||||||
companyId: json['company_id'] as String,
|
companyId: map['company_id'] as String,
|
||||||
isActive: json['is_active'] ?? true,
|
isActive: map['is_active'] ?? true,
|
||||||
isPaid: json['is_paid'] ?? false,
|
isPaid: map['is_paid'] ?? false,
|
||||||
paymentExpiration: json['payment_expiration'] != null
|
paymentExpiration: map['payment_expiration'] != null
|
||||||
? DateTime.parse(json['payment_expiration'])
|
? DateTime.parse(map['payment_expiration'])
|
||||||
: null,
|
: null,
|
||||||
indirizzo: json['indirizzo'],
|
indirizzo: map['indirizzo'],
|
||||||
cap: json['cap'],
|
cap: map['cap'],
|
||||||
comune: json['comune'],
|
comune: map['comune'],
|
||||||
provincia: json['provincia'],
|
provincia: map['provincia'],
|
||||||
|
associatedProviders: providers,
|
||||||
|
associatedStaffMembers: staffMembers,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, dynamic> toJson() {
|
Map<String, dynamic> toMap() {
|
||||||
return {
|
return {
|
||||||
if (id != null) 'id': id,
|
if (id != null) 'id': id,
|
||||||
'nome': nome,
|
'nome': nome,
|
||||||
|
|||||||
232
lib/features/master_data/store/ui/store_card.dart
Normal file
232
lib/features/master_data/store/ui/store_card.dart
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
|
import 'package:flux/core/theme/theme.dart';
|
||||||
|
import 'package:flux/features/master_data/providers/blocs/provider_cubit.dart';
|
||||||
|
import 'package:flux/features/master_data/providers/models/provider_model.dart';
|
||||||
|
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
|
||||||
|
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
|
||||||
|
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
|
||||||
|
import 'package:flux/features/master_data/store/models/store_model.dart';
|
||||||
|
import 'package:flux/features/master_data/store/ui/store_form.dart';
|
||||||
|
|
||||||
|
class StoreCard extends StatefulWidget {
|
||||||
|
final StoreModel store;
|
||||||
|
const StoreCard({super.key, required this.store});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<StoreCard> createState() => _StoreCardState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _StoreCardState extends State<StoreCard> {
|
||||||
|
late List<ProviderModel> _tempAssociatedProviders;
|
||||||
|
late List<StaffMemberModel> _tempAssociatedStaff;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
_tempAssociatedProviders = widget.store.associatedProviders;
|
||||||
|
_tempAssociatedStaff = widget.store.associatedStaffMembers;
|
||||||
|
super.initState();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _save() {
|
||||||
|
final storeCubit = context.read<StoreCubit>();
|
||||||
|
storeCubit.saveProvidersForStore(widget.store, _tempAssociatedProviders);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Card(
|
||||||
|
margin: const EdgeInsets.only(bottom: 16),
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(16),
|
||||||
|
side: BorderSide(
|
||||||
|
color: widget.store.isActive
|
||||||
|
? Colors.transparent
|
||||||
|
: Colors.red.withValues(alpha: 0.3),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
ListTile(
|
||||||
|
leading: Icon(
|
||||||
|
Icons.storefront,
|
||||||
|
color: widget.store.isActive ? context.accent : Colors.grey,
|
||||||
|
),
|
||||||
|
title: Text(
|
||||||
|
widget.store.nome,
|
||||||
|
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||||
|
),
|
||||||
|
subtitle: Text(
|
||||||
|
"${widget.store.comune} (${widget.store.provincia}) - ${widget.store.indirizzo}",
|
||||||
|
),
|
||||||
|
trailing: Switch(
|
||||||
|
value: widget.store.isActive,
|
||||||
|
onChanged: (val) {
|
||||||
|
// context.read<StoreBloc>().add(ToggleStoreStatus(store.id, val));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Divider(height: 1),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
child: Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
|
children: [
|
||||||
|
// Mostra quanti dipendenti ci sono (usando lo StaffCubit)
|
||||||
|
BlocBuilder<StoreCubit, StoreState>(
|
||||||
|
builder: (context, storeState) {
|
||||||
|
final staffCount =
|
||||||
|
storeState.staffByStore[widget.store.id]?.length ?? 0;
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
ActionChip(
|
||||||
|
avatar: const Icon(Icons.people, size: 16),
|
||||||
|
label: Text("$staffCount Dipendenti"),
|
||||||
|
onPressed: () => _manageStoreStaff(widget.store),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 16),
|
||||||
|
ActionChip(
|
||||||
|
avatar: const Icon(Icons.handshake, size: 16),
|
||||||
|
label: Text(
|
||||||
|
"${widget.store.associatedProviders.length} Providers",
|
||||||
|
),
|
||||||
|
onPressed: () => _manageStoreProviders(widget.store),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(width: 16),
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: () => _openStoreForm(context, store: widget.store),
|
||||||
|
icon: const Icon(Icons.edit, size: 18),
|
||||||
|
label: const Text("Modifica"),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _manageStoreStaff(StoreModel store) {
|
||||||
|
showModalBottomSheet(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
builder: (context) => BlocBuilder<StaffCubit, StaffState>(
|
||||||
|
// 1. Prendi TUTTI i dipendenti
|
||||||
|
builder: (context, staffState) {
|
||||||
|
return BlocBuilder<StoreCubit, StoreState>(
|
||||||
|
// 2. Prendi le ASSEGNAZIONI
|
||||||
|
builder: (context, storeState) {
|
||||||
|
final assignedToThisStore =
|
||||||
|
storeState.staffByStore[store.id!] ?? [];
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.all(24),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
"Personale di ${store.nome}",
|
||||||
|
style: context.titleLarge,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
...staffState.allStaff.map((person) {
|
||||||
|
// La spunta deve dipendere dallo StoreCubit!
|
||||||
|
final bool isAssigned = assignedToThisStore.any(
|
||||||
|
(s) => s.id == person.id,
|
||||||
|
);
|
||||||
|
|
||||||
|
return CheckboxListTile(
|
||||||
|
title: Text(person.name),
|
||||||
|
value: isAssigned,
|
||||||
|
onChanged: (selected) {
|
||||||
|
if (selected == true) {
|
||||||
|
_tempAssociatedStaff.add(person);
|
||||||
|
} else {
|
||||||
|
_tempAssociatedStaff.removeWhere(
|
||||||
|
(s) => s.id == person.id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
ElevatedButton(
|
||||||
|
style: ElevatedButton.styleFrom(
|
||||||
|
minimumSize: const Size.fromHeight(50),
|
||||||
|
),
|
||||||
|
onPressed: _save,
|
||||||
|
child: const Text('SALVA NEGOZIO'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _manageStoreProviders(StoreModel store) {
|
||||||
|
showModalBottomSheet(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
|
||||||
|
builder: (context) => BlocBuilder<ProvidersCubit, ProvidersState>(
|
||||||
|
builder: (context, state) {
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.all(24),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Text("Providers di ${store.nome}", style: context.titleLarge),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
...state.allProviders.map((provider) {
|
||||||
|
final isAssociated = _tempAssociatedProviders.any(
|
||||||
|
(p) => p.id == provider.id,
|
||||||
|
);
|
||||||
|
return CheckboxListTile(
|
||||||
|
title: Text(provider.nome),
|
||||||
|
value: isAssociated,
|
||||||
|
onChanged: (selected) {
|
||||||
|
if (selected == true) {
|
||||||
|
_tempAssociatedProviders.add(provider);
|
||||||
|
} else {
|
||||||
|
_tempAssociatedProviders.removeWhere(
|
||||||
|
(p) => p.id == provider.id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
ElevatedButton(
|
||||||
|
style: ElevatedButton.styleFrom(
|
||||||
|
minimumSize: const Size.fromHeight(50),
|
||||||
|
),
|
||||||
|
onPressed: _save,
|
||||||
|
child: const Text('SALVA NEGOZIO'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _openStoreForm(BuildContext context, {StoreModel? store}) {
|
||||||
|
showModalBottomSheet(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
backgroundColor: Colors.transparent,
|
||||||
|
builder: (context) => StoreForm(store: store),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
157
lib/features/master_data/store/ui/store_form.dart
Normal file
157
lib/features/master_data/store/ui/store_form.dart
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
|
import 'package:flux/core/blocs/session/session_bloc.dart';
|
||||||
|
import 'package:flux/core/widgets/flux_text_field.dart';
|
||||||
|
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
|
||||||
|
import 'package:flux/features/master_data/store/models/store_model.dart';
|
||||||
|
|
||||||
|
class StoreForm extends StatefulWidget {
|
||||||
|
final StoreModel? store; // Se è null, stiamo creando un nuovo negozio
|
||||||
|
const StoreForm({super.key, this.store});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<StoreForm> createState() => _StoreFormState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _StoreFormState extends State<StoreForm> {
|
||||||
|
final nomeController = TextEditingController();
|
||||||
|
final indirizzoController = TextEditingController();
|
||||||
|
final capController = TextEditingController();
|
||||||
|
final comuneController = TextEditingController();
|
||||||
|
final provinciaController = TextEditingController();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
if (widget.store != null) {
|
||||||
|
nomeController.text = widget.store!.nome;
|
||||||
|
indirizzoController.text = widget.store!.indirizzo;
|
||||||
|
capController.text = widget.store!.cap;
|
||||||
|
comuneController.text = widget.store!.comune;
|
||||||
|
provinciaController.text = widget.store!.provincia;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).scaffoldBackgroundColor,
|
||||||
|
borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
|
||||||
|
),
|
||||||
|
padding: EdgeInsets.only(
|
||||||
|
top: 24,
|
||||||
|
left: 24,
|
||||||
|
right: 24,
|
||||||
|
bottom: MediaQuery.of(context).viewInsets.bottom + 24,
|
||||||
|
),
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
widget.store == null ? "Nuovo Punto Vendita" : "Modifica Negozio",
|
||||||
|
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
|
||||||
|
// --- DATI PRINCIPALI ---
|
||||||
|
FluxTextField(
|
||||||
|
controller: nomeController,
|
||||||
|
label: "Nome Negozio (es. Flux Milano)",
|
||||||
|
icon: Icons.storefront_rounded,
|
||||||
|
keyboardType: TextInputType.name,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
FluxTextField(
|
||||||
|
controller: indirizzoController,
|
||||||
|
label: "Indirizzo",
|
||||||
|
icon: Icons.map_outlined,
|
||||||
|
keyboardType: TextInputType.streetAddress,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
|
||||||
|
// --- CAP, COMUNE, PROVINCIA (In riga) ---
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
flex: 2,
|
||||||
|
child: FluxTextField(
|
||||||
|
controller: capController,
|
||||||
|
label: "CAP",
|
||||||
|
icon: Icons.post_add_rounded,
|
||||||
|
keyboardType: TextInputType.number,
|
||||||
|
maxLength: 5,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
flex: 4,
|
||||||
|
child: FluxTextField(
|
||||||
|
controller: comuneController,
|
||||||
|
label: "Comune",
|
||||||
|
icon: Icons.location_city_rounded,
|
||||||
|
keyboardType: TextInputType.name,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
flex: 2,
|
||||||
|
child: FluxTextField(
|
||||||
|
controller: provinciaController,
|
||||||
|
label: "Prov",
|
||||||
|
icon: Icons.explore_outlined,
|
||||||
|
keyboardType: TextInputType.name,
|
||||||
|
onChanged: (value) => value.toUpperCase(),
|
||||||
|
maxLength: 2,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
|
||||||
|
const SizedBox(height: 32),
|
||||||
|
|
||||||
|
// --- TASTO SALVA ---
|
||||||
|
SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
height: 50,
|
||||||
|
child: ElevatedButton(
|
||||||
|
onPressed: () {
|
||||||
|
if (nomeController.text.isEmpty) return;
|
||||||
|
|
||||||
|
final storeData = StoreModel(
|
||||||
|
id: widget
|
||||||
|
.store
|
||||||
|
?.id, // Se nullo, Supabase ne crea uno nuovo
|
||||||
|
nome: nomeController.text,
|
||||||
|
indirizzo: indirizzoController.text,
|
||||||
|
cap: capController.text,
|
||||||
|
comune: comuneController.text,
|
||||||
|
provincia: provinciaController.text,
|
||||||
|
companyId: context
|
||||||
|
.read<SessionBloc>()
|
||||||
|
.state
|
||||||
|
.company!
|
||||||
|
.id, // Recuperiamo la companyId
|
||||||
|
isActive: widget.store?.isActive ?? true,
|
||||||
|
isPaid: widget.store?.isPaid ?? false,
|
||||||
|
paymentExpiration: widget.store?.paymentExpiration,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Chiamata al Bloc per il salvataggio
|
||||||
|
context.read<StoreCubit>().createStore(storeData);
|
||||||
|
|
||||||
|
Navigator.pop(context);
|
||||||
|
},
|
||||||
|
child: Text(
|
||||||
|
widget.store == null ? "CREA NEGOZIO" : "AGGIORNA DATI",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
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/blocs/session/session_bloc.dart';
|
|
||||||
import 'package:flux/core/theme/theme.dart';
|
|
||||||
import 'package:flux/core/widgets/flux_text_field.dart';
|
|
||||||
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
|
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
|
||||||
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
|
import 'package:flux/features/master_data/store/bloc/store_cubit.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/store/ui/store_card.dart';
|
||||||
|
import 'package:flux/features/master_data/store/ui/store_form.dart';
|
||||||
|
|
||||||
class StoresScreen extends StatefulWidget {
|
class StoresScreen extends StatefulWidget {
|
||||||
const StoresScreen({super.key});
|
const StoresScreen({super.key});
|
||||||
@@ -38,7 +37,7 @@ class _StoresScreenState extends State<StoresScreen> {
|
|||||||
itemCount: state.stores.length,
|
itemCount: state.stores.length,
|
||||||
itemBuilder: (context, index) {
|
itemBuilder: (context, index) {
|
||||||
final store = state.stores[index];
|
final store = state.stores[index];
|
||||||
return _buildStoreCard(store);
|
return StoreCard(store: store);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -51,255 +50,12 @@ class _StoresScreenState extends State<StoresScreen> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildStoreCard(StoreModel store) {
|
|
||||||
return Card(
|
|
||||||
margin: const EdgeInsets.only(bottom: 16),
|
|
||||||
shape: RoundedRectangleBorder(
|
|
||||||
borderRadius: BorderRadius.circular(16),
|
|
||||||
side: BorderSide(
|
|
||||||
color: store.isActive
|
|
||||||
? Colors.transparent
|
|
||||||
: Colors.red.withValues(alpha: 0.3),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Column(
|
|
||||||
children: [
|
|
||||||
ListTile(
|
|
||||||
leading: Icon(
|
|
||||||
Icons.storefront,
|
|
||||||
color: store.isActive ? context.accent : Colors.grey,
|
|
||||||
),
|
|
||||||
title: Text(
|
|
||||||
store.nome,
|
|
||||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
|
||||||
),
|
|
||||||
subtitle: Text(
|
|
||||||
"${store.comune} (${store.provincia}) - ${store.indirizzo}",
|
|
||||||
),
|
|
||||||
trailing: Switch(
|
|
||||||
value: store.isActive,
|
|
||||||
onChanged: (val) {
|
|
||||||
// context.read<StoreBloc>().add(ToggleStoreStatus(store.id, val));
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const Divider(height: 1),
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.all(12),
|
|
||||||
child: Row(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
|
||||||
children: [
|
|
||||||
// Mostra quanti dipendenti ci sono (usando lo StaffCubit)
|
|
||||||
BlocBuilder<StoreCubit, StoreState>(
|
|
||||||
builder: (context, storeState) {
|
|
||||||
final staffCount =
|
|
||||||
storeState.staffByStore[store.id]?.length ?? 0;
|
|
||||||
return ActionChip(
|
|
||||||
avatar: const Icon(Icons.people, size: 16),
|
|
||||||
label: Text("$staffCount Dipendenti"),
|
|
||||||
onPressed: () => _manageStoreStaff(store),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
TextButton.icon(
|
|
||||||
onPressed: () => _openStoreForm(context, store: store),
|
|
||||||
icon: const Icon(Icons.edit, size: 18),
|
|
||||||
label: const Text("Modifica"),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _manageStoreStaff(StoreModel store) {
|
|
||||||
showModalBottomSheet(
|
|
||||||
context: context,
|
|
||||||
isScrollControlled: true,
|
|
||||||
builder: (context) => BlocBuilder<StaffCubit, StaffState>(
|
|
||||||
// 1. Prendi TUTTI i dipendenti
|
|
||||||
builder: (context, staffState) {
|
|
||||||
return BlocBuilder<StoreCubit, StoreState>(
|
|
||||||
// 2. Prendi le ASSEGNAZIONI
|
|
||||||
builder: (context, storeState) {
|
|
||||||
final assignedToThisStore =
|
|
||||||
storeState.staffByStore[store.id!] ?? [];
|
|
||||||
|
|
||||||
return Container(
|
|
||||||
padding: const EdgeInsets.all(24),
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
"Personale di ${store.nome}",
|
|
||||||
style: context.titleLarge,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
...staffState.allStaff.map((person) {
|
|
||||||
// La spunta deve dipendere dallo StoreCubit!
|
|
||||||
final bool isAssigned = assignedToThisStore.any(
|
|
||||||
(s) => s.id == person.id,
|
|
||||||
);
|
|
||||||
|
|
||||||
return CheckboxListTile(
|
|
||||||
title: Text(person.name),
|
|
||||||
value: isAssigned,
|
|
||||||
onChanged: (selected) {
|
|
||||||
if (selected == true) {
|
|
||||||
context.read<StoreCubit>().assignStaffToStore(
|
|
||||||
store.id!,
|
|
||||||
person.id!,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
context.read<StoreCubit>().removeStaffFromStore(
|
|
||||||
person.id!,
|
|
||||||
store.id!,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _openStoreForm(BuildContext context, {StoreModel? store}) {
|
void _openStoreForm(BuildContext context, {StoreModel? store}) {
|
||||||
final nomeController = TextEditingController(text: store?.nome);
|
|
||||||
final indirizzoController = TextEditingController(text: store?.indirizzo);
|
|
||||||
final capController = TextEditingController(text: store?.cap);
|
|
||||||
final comuneController = TextEditingController(text: store?.comune);
|
|
||||||
final provinciaController = TextEditingController(text: store?.provincia);
|
|
||||||
|
|
||||||
showModalBottomSheet(
|
showModalBottomSheet(
|
||||||
context: context,
|
context: context,
|
||||||
isScrollControlled: true,
|
isScrollControlled: true,
|
||||||
backgroundColor: Colors.transparent,
|
backgroundColor: Colors.transparent,
|
||||||
builder: (context) => Container(
|
builder: (context) => StoreForm(store: store),
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).scaffoldBackgroundColor,
|
|
||||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
|
|
||||||
),
|
|
||||||
padding: EdgeInsets.only(
|
|
||||||
top: 24,
|
|
||||||
left: 24,
|
|
||||||
right: 24,
|
|
||||||
bottom: MediaQuery.of(context).viewInsets.bottom + 24,
|
|
||||||
),
|
|
||||||
child: SingleChildScrollView(
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
store == null ? "Nuovo Punto Vendita" : "Modifica Negozio",
|
|
||||||
style: const TextStyle(
|
|
||||||
fontSize: 20,
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
|
|
||||||
// --- DATI PRINCIPALI ---
|
|
||||||
FluxTextField(
|
|
||||||
controller: nomeController,
|
|
||||||
label: "Nome Negozio (es. Flux Milano)",
|
|
||||||
icon: Icons.storefront_rounded,
|
|
||||||
keyboardType: TextInputType.name,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
FluxTextField(
|
|
||||||
controller: indirizzoController,
|
|
||||||
label: "Indirizzo",
|
|
||||||
icon: Icons.map_outlined,
|
|
||||||
keyboardType: TextInputType.streetAddress,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
|
|
||||||
// --- CAP, COMUNE, PROVINCIA (In riga) ---
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
flex: 2,
|
|
||||||
child: FluxTextField(
|
|
||||||
controller: capController,
|
|
||||||
label: "CAP",
|
|
||||||
icon: Icons.post_add_rounded,
|
|
||||||
keyboardType: TextInputType.number,
|
|
||||||
maxLength: 5,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
flex: 4,
|
|
||||||
child: FluxTextField(
|
|
||||||
controller: comuneController,
|
|
||||||
label: "Comune",
|
|
||||||
icon: Icons.location_city_rounded,
|
|
||||||
keyboardType: TextInputType.name,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
flex: 2,
|
|
||||||
child: FluxTextField(
|
|
||||||
controller: provinciaController,
|
|
||||||
label: "Prov",
|
|
||||||
icon: Icons.explore_outlined,
|
|
||||||
keyboardType: TextInputType.name,
|
|
||||||
onChanged: (value) => value.toUpperCase(),
|
|
||||||
maxLength: 2,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
|
|
||||||
const SizedBox(height: 32),
|
|
||||||
|
|
||||||
// --- TASTO SALVA ---
|
|
||||||
SizedBox(
|
|
||||||
width: double.infinity,
|
|
||||||
height: 50,
|
|
||||||
child: ElevatedButton(
|
|
||||||
onPressed: () {
|
|
||||||
if (nomeController.text.isEmpty) return;
|
|
||||||
|
|
||||||
final storeData = StoreModel(
|
|
||||||
id: store?.id, // Se nullo, Supabase ne crea uno nuovo
|
|
||||||
nome: nomeController.text,
|
|
||||||
indirizzo: indirizzoController.text,
|
|
||||||
cap: capController.text,
|
|
||||||
comune: comuneController.text,
|
|
||||||
provincia: provinciaController.text,
|
|
||||||
companyId: context
|
|
||||||
.read<SessionBloc>()
|
|
||||||
.state
|
|
||||||
.company!
|
|
||||||
.id, // Recuperiamo la companyId
|
|
||||||
isActive: store?.isActive ?? true,
|
|
||||||
isPaid: store?.isPaid ?? false,
|
|
||||||
paymentExpiration: store?.paymentExpiration,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Chiamata al Bloc per il salvataggio
|
|
||||||
context.read<StoreCubit>().createStore(storeData);
|
|
||||||
|
|
||||||
Navigator.pop(context);
|
|
||||||
},
|
|
||||||
child: Text(store == null ? "CREA NEGOZIO" : "AGGIORNA DATI"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,7 +105,8 @@ class _FluxAppState extends State<FluxApp> {
|
|||||||
create: (_) => ServicesCubit(context.read<SessionBloc>()),
|
create: (_) => ServicesCubit(context.read<SessionBloc>()),
|
||||||
),
|
),
|
||||||
BlocProvider<ProvidersCubit>(
|
BlocProvider<ProvidersCubit>(
|
||||||
create: (_) => ProvidersCubit(context.read<SessionBloc>()),
|
create: (_) =>
|
||||||
|
ProvidersCubit(context.read<SessionBloc>())..loadProviders(null),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
child: BlocBuilder<ThemeBloc, ThemeState>(
|
child: BlocBuilder<ThemeBloc, ThemeState>(
|
||||||
|
|||||||
Reference in New Issue
Block a user