ripristinato codice stabile da branch staff

This commit is contained in:
2026-04-14 11:29:49 +02:00
parent f33b63c0c6
commit 541000390e
28 changed files with 2260 additions and 13 deletions

View File

@@ -0,0 +1,136 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_bloc.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/store/models/store_model.dart';
import 'package:get_it/get_it.dart';
part 'staff_state.dart';
class StaffCubit extends Cubit<StaffState> {
final StaffRepository _repository = GetIt.I.get<StaffRepository>();
final SessionBloc _sessionBloc;
StaffCubit(this._sessionBloc) : super(const StaffState());
// Carica tutto lo staff della compagnia
Future<void> loadAllStaff() async {
emit(state.copyWith(isLoading: true, error: null));
try {
final staff = await _repository.getStaffMembers(
_sessionBloc.state.company!.id,
);
final Map<String, List<StoreModel>> storesByStaff = {};
for (StaffMemberModel member in staff) {
storesByStaff[member.id!] = await loadStoresByStaff(member.id!);
}
emit(
state.copyWith(
allStaff: staff,
isLoading: false,
storesByStaff: storesByStaff,
),
);
} catch (e) {
emit(state.copyWith(isLoading: false, error: e.toString()));
}
}
Future<List<StoreModel>> loadStoresByStaff(String staffId) async {
try {
return await _repository.getStaffMemberStore(staffId);
} catch (e) {
emit(state.copyWith(error: e.toString()));
return [];
}
}
// Carica lo staff di uno specifico negozio e aggiorna la mappa
Future<void> loadStaffForStore(String storeId) async {
try {
final staffInStore = await _repository.getStaffMembersInStore(storeId);
final newMap = Map<String, List<StaffMemberModel>>.from(
state.staffByStore,
);
newMap[storeId] = staffInStore;
emit(state.copyWith(staffByStore: newMap));
} catch (e) {
// Qui potresti gestire l'errore silenziosamente per non bloccare tutta l'UI
}
}
// Salva o aggiorna un membro
Future<void> saveStaffMember(StaffMemberModel member) async {
emit(state.copyWith(isLoading: true));
try {
await _repository.saveStaffMember(member);
await loadAllStaff(); // Ricarichiamo la lista aggiornata
} catch (e) {
emit(state.copyWith(isLoading: false, error: e.toString()));
}
}
// Associa un dipendente a un negozio
Future<void> assignMemberToStore(String staffId, String storeId) async {
try {
await _repository.assignToStore(staffId, storeId);
final stuffStores = await loadStoresByStaff(staffId);
final Map<String, List<StoreModel>> storesByStaff = Map.from(
state.storesByStaff,
);
storesByStaff[staffId] = stuffStores;
emit(state.copyWith(storesByStaff: storesByStaff));
} catch (e) {
emit(state.copyWith(error: "Errore nell'assegnazione: $e"));
}
}
// Rimuove un dipendente da un negozio
Future<void> removeMemberFromStore(String staffId, String storeId) async {
try {
await _repository.removeFromStore(staffId, storeId);
final stuffStores = await loadStoresByStaff(staffId);
final Map<String, List<StoreModel>> storesByStaff = Map.from(
state.storesByStaff,
);
storesByStaff[staffId] = stuffStores;
emit(state.copyWith(storesByStaff: storesByStaff));
} catch (e) {
emit(state.copyWith(error: "Errore nella rimozione: $e"));
}
}
Future<void> saveStaffWithStores({
required StaffMemberModel member,
required List<String> selectedStoreIds,
}) async {
emit(state.copyWith(isLoading: true));
try {
// 1. Salva o aggiorna l'anagrafica (ci serve l'ID)
// Se è un nuovo membro, Supabase ci restituirà l'ID generato
final savedMember = await _repository.saveStaffMember(member);
final String staffId = savedMember.id!;
// 2. Sincronizzazione Negozi
// Per semplicità e pulizia, rimuoviamo le vecchie assegnazioni e inseriamo le nuove
// (Oppure facciamo un confronto tra liste, ma il reset & rewrite è più sicuro qui)
await _repository.clearStoreAssignments(staffId);
if (selectedStoreIds.isNotEmpty) {
await Future.wait(
selectedStoreIds.map(
(storeId) => _repository.assignToStore(staffId, storeId),
),
);
}
// 3. Rinfresca i dati
await loadAllStaff();
emit(state.copyWith(isLoading: false));
} catch (e) {
emit(state.copyWith(isLoading: false, error: e.toString()));
}
}
}

View File

@@ -0,0 +1,42 @@
part of 'staff_cubit.dart';
class StaffState extends Equatable {
final List<StaffMemberModel> allStaff;
final Map<String, List<StoreModel>> storesByStaff;
final Map<String, List<StaffMemberModel>> staffByStore;
final bool isLoading;
final String? error;
const StaffState({
this.allStaff = const [],
this.storesByStaff = const {},
this.staffByStore = const {},
this.isLoading = false,
this.error,
});
StaffState copyWith({
List<StaffMemberModel>? allStaff,
Map<String, List<StoreModel>>? storesByStaff,
Map<String, List<StaffMemberModel>>? staffByStore,
bool? isLoading,
String? error,
}) {
return StaffState(
allStaff: allStaff ?? this.allStaff,
storesByStaff: storesByStaff ?? this.storesByStaff,
staffByStore: staffByStore ?? this.staffByStore,
isLoading: isLoading ?? this.isLoading,
error: error,
);
}
@override
List<Object?> get props => [
allStaff,
storesByStaff,
staffByStore,
isLoading,
error,
];
}

View File

@@ -0,0 +1,90 @@
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:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class StaffRepository {
final SupabaseClient _supabase = GetIt.I.get<SupabaseClient>();
// --- ANAGRAFICA PURA ---
// Prende tutto lo staff della Company (per l'Hub Anagrafiche)
Future<List<StaffMemberModel>> getStaffMembers(String companyId) async {
final response = await _supabase
.from('staff_member')
.select()
.eq('company_id', companyId)
.order('name', ascending: true);
return (response as List).map((s) => StaffMemberModel.fromJson(s)).toList();
}
Future<StaffMemberModel> saveStaffMember(StaffMemberModel member) async {
final response = await _supabase
.from('staff_member')
.upsert(member.toJson())
.select()
.single();
return StaffMemberModel.fromJson(response);
}
// --- LOGICA DI GIUNZIONE (Staff <-> Store) ---
// Recupera i membri assegnati a uno specifico negozio
// Qui facciamo una JOIN per avere i dati del membro partendo dalla tabella di giunzione
Future<List<StaffMemberModel>> getStaffMembersInStore(String storeId) async {
final response = await _supabase
.from('staff_in_stores')
.select(
'staff_member (*)',
) // Prende tutti i campi della tabella staff_member collegata
.eq('store_id', storeId);
return (response as List)
.map((item) => StaffMemberModel.fromJson(item['staff_member']))
.toList();
}
// Recupera i negozi assegnati a uno specifico membro
// Qui facciamo una JOIN per avere i dati del membro partendo dalla tabella di giunzione
Future<List<StoreModel>> getStaffMemberStore(String staffId) async {
final response = await _supabase
.from('staff_in_stores')
.select(
'store (*)',
) // Prende tutti i campi della tabella store collegata
.eq('staff_member_id', staffId);
return (response as List)
.map((item) => StoreModel.fromJson(item['store']))
.toList();
}
// Assegna un membro a un negozio
Future<void> assignToStore(String staffId, String storeId) async {
await _supabase.from('staff_in_stores').insert({
'staff_member_id': staffId,
'store_id': storeId,
});
}
// Rimuove l'assegnazione
Future<void> removeFromStore(String staffId, String storeId) async {
await _supabase
.from('staff_in_stores')
.delete()
.eq('staff_member_id', staffId)
.eq('store_id', storeId);
}
// Nel StaffRepository
// Utility per pulire le assegnazioni esistenti prima di riscriverle
Future<void> clearStoreAssignments(String staffId) async {
await _supabase
.from('staff_in_stores')
.delete()
.eq('staff_member_id', staffId);
}
}

View File

@@ -0,0 +1,47 @@
import 'package:equatable/equatable.dart';
import 'package:flux/core/utils/string_extensions.dart'; // Assicurati che il percorso sia corretto
class StaffMemberModel extends Equatable {
final String? id;
final String name;
final String email;
final String phone;
final bool isActive;
final String companyId;
const StaffMemberModel({
this.id,
required this.name,
this.email = '',
this.phone = '',
this.isActive = true,
required this.companyId,
});
factory StaffMemberModel.fromJson(Map<String, dynamic> json) {
return StaffMemberModel(
id: json['id'],
// Applichiamo il tuo myFormat per visualizzare i nomi correttamente
name: (json['name'] as String).myFormat(),
// L'email la teniamo lowercase per standard tecnico
email: (json['email'] as String? ?? '').toLowerCase().trim(),
phone: (json['phone'] as String? ?? '').trim(),
isActive: json['is_active'] ?? true,
companyId: json['company_id'],
);
}
Map<String, dynamic> toJson() {
return {
if (id != null) 'id': id,
'name': name.toLowerCase().trim(), // Salviamo pulito per le query
'email': email.toLowerCase().trim(),
'phone': phone.trim(),
'is_active': isActive,
'company_id': companyId,
};
}
@override
List<Object?> get props => [id, name, email, phone, isActive, companyId];
}

View File

@@ -0,0 +1,315 @@
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/theme/theme.dart';
import 'package:flux/core/widgets/flux_text_field.dart';
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart'; // Tuo percorso
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/master_data/store/bloc/store_bloc.dart';
class StaffScreen extends StatefulWidget {
const StaffScreen({super.key});
@override
State<StaffScreen> createState() => _StaffScreenState();
}
class _StaffScreenState extends State<StaffScreen> {
String? _selectedStoreId;
bool _showAllCompanyStaff = true; // Partiamo con la vista globale
@override
void initState() {
super.initState();
// Carichiamo subito tutto
context.read<StaffCubit>().loadAllStaff();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: context.background,
appBar: AppBar(
title: const Text("Anagrafica Personale"),
actions: [
// Toggle per vista Azienda / Negozio
Padding(
padding: const EdgeInsets.only(right: 16),
child: FilterChip(
label: const Text("Tutta l'Azienda"),
selected: _showAllCompanyStaff,
onSelected: (val) => setState(() => _showAllCompanyStaff = val),
selectedColor: context.accent.withValues(alpha: 0.2),
),
),
],
),
body: Column(
children: [
// --- BARRA FILTRO NEGOZIO (Visibile solo se non 'Tutta l'Azienda') ---
AnimatedContainer(
duration: const Duration(milliseconds: 300),
height: _showAllCompanyStaff ? 0 : 80,
child: _showAllCompanyStaff
? const SizedBox()
: _buildStoreSelector(),
),
// --- LISTA PERSONALE ---
Expanded(
child: BlocBuilder<StaffCubit, StaffState>(
builder: (context, state) {
final list = _showAllCompanyStaff
? state.allStaff
: (state.staffByStore[_selectedStoreId] ?? []);
if (state.isLoading && list.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (list.isEmpty) {
return _buildEmptyState();
}
return ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: list.length,
separatorBuilder: (_, _) => const SizedBox(height: 12),
itemBuilder: (context, index) {
final member = list[index];
return _buildStaffCard(member);
},
);
},
),
),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => _openStaffForm(context),
label: const Text("Aggiungi"),
icon: const Icon(Icons.person_add_alt_1),
),
);
}
Widget _buildStoreSelector() {
return BlocBuilder<StoreBloc, StoreState>(
// Assumendo tu abbia uno StoreCubit
builder: (context, state) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: DropdownButtonFormField<String>(
initialValue: _selectedStoreId,
decoration: const InputDecoration(labelText: "Filtra per Negozio"),
items: state.stores
.map((s) => DropdownMenuItem(value: s.id, child: Text(s.nome)))
.toList(),
onChanged: (id) {
setState(() => _selectedStoreId = id);
if (id != null) context.read<StaffCubit>().loadStaffForStore(id);
},
),
);
},
);
}
Widget _buildStaffCard(StaffMemberModel member) {
return Card(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(color: context.accent.withValues(alpha: 0.1)),
),
child: ListTile(
contentPadding: const EdgeInsets.all(12),
leading: CircleAvatar(
backgroundColor: context.accent.withValues(alpha: 0.1),
child: Text(member.name[0], style: TextStyle(color: context.accent)),
),
title: Text(
member.name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (member.email.isNotEmpty) Text(member.email),
Text(member.phone.isNotEmpty ? member.phone : "Nessun telefono"),
],
),
trailing: const Icon(Icons.edit_note),
onTap: () => _openStaffForm(context, member: member),
),
);
}
void _openStaffForm(BuildContext context, {StaffMemberModel? member}) {
final nameController = TextEditingController(text: member?.name);
final emailController = TextEditingController(text: member?.email);
final phoneController = TextEditingController(text: member?.phone);
// 1. Inizializziamo la lista temporanea attingendo dallo stato del Cubit
// Usiamo storesByStaff (la mappa che indicizza i negozi per ogni ID dipendente)
List<String> tempSelectedStores =
context
.read<StaffCubit>()
.state
.storesByStaff[member?.id]
?.map((s) => s.id!)
.toList() ??
[];
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => StatefulBuilder(
// <--- QUESTO è il segreto per le Chip
builder: (context, setModalState) {
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(
member == null
? "Nuovo Collaboratore"
: "Modifica Collaboratore",
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 24),
FluxTextField(
controller: nameController,
label: "Nome e Cognome",
icon: Icons.person,
),
const SizedBox(height: 16),
FluxTextField(
controller: emailController,
label: "Email",
icon: Icons.email,
),
const SizedBox(height: 16),
FluxTextField(
controller: phoneController,
label: "Telefono",
icon: Icons.phone,
),
const SizedBox(height: 24),
const Text(
"Assegna ai Negozi",
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 12),
// --- SELETTORE NEGOZI (CHIPS) ---
// Qui usiamo il BlocBuilder per i negozi, ma il setModalState per il refresh
BlocBuilder<StoreBloc, StoreState>(
builder: (context, storeState) {
if (storeState.status == StoreStatus.loading) {
return const CircularProgressIndicator();
}
return Wrap(
spacing: 8,
runSpacing: 8,
children: storeState.stores.map((store) {
final isSelected = tempSelectedStores.contains(
store.id,
);
return FilterChip(
label: Text(store.nome),
selected: isSelected,
onSelected: (selected) {
// IMPORTANTE: setModalState aggiorna l'UI del BottomSheet
setModalState(() {
if (selected) {
tempSelectedStores.add(store.id!);
} else {
tempSelectedStores.remove(store.id);
}
});
},
selectedColor: context.accent.withValues(
alpha: 0.2,
),
checkmarkColor: context.accent,
);
}).toList(),
);
},
),
const SizedBox(height: 32),
SizedBox(
width: double.infinity,
height: 50,
child: ElevatedButton(
onPressed: () {
final companyId = context
.read<SessionBloc>()
.state
.company!
.id;
final updatedMember = StaffMemberModel(
id: member?.id,
name: nameController.text,
email: emailController.text,
phone: phoneController.text,
companyId: companyId,
);
// Chiamiamo il metodo atomico nel Cubit
context.read<StaffCubit>().saveStaffWithStores(
member: updatedMember,
selectedStoreIds: tempSelectedStores,
);
Navigator.pop(context);
},
child: const Text("SALVA COLLABORATORE"),
),
),
],
),
),
);
},
),
);
}
Widget _buildEmptyState() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.people_outline, size: 64, color: context.secondaryText),
const SizedBox(height: 16),
Text(
"Nessun membro trovato",
style: TextStyle(color: context.secondaryText),
),
],
),
);
}
}