6 Commits

Author SHA1 Message Date
d2ff2de673 Merge pull request 'feat-invite_staff' (#9) from feat-invite_staff into main
Reviewed-on: #9
2026-04-28 15:34:33 +02:00
32c97accd7 ottimo
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 15:33:38 +02:00
f86b52e236 fix 2026-04-28 11:05:03 +02:00
c49964e5c5 fixes
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 10:12:15 +02:00
77987258aa import inutile 2026-04-26 16:30:18 +02:00
6cbf0479a1 urca non ci credo, potrebbe già funzionare
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 16:29:31 +02:00
20 changed files with 542 additions and 119 deletions

View File

@@ -39,8 +39,35 @@ class SessionCubit extends Cubit<SessionState> {
} }
try { try {
// 1. CHI È QUESTO UTENTE? (Vediamo se ha un profilo staff, che sia Invitato o Admin)
StaffMemberModel? staff = await _repository.getStaffMemberByUserId(
user.id,
);
CompanyModel? company;
if (staff != null) {
// --- LA MAGIA DEL SENSORE ---
if (staff.hasJoined == false) {
// È la primissima volta che entra! Aggiorniamo il DB.
await _repository.updateStaffMember(staff.id!, {'has_joined': true});
// Aggiorniamo anche il nostro modello in memoria per questa sessione
staff = staff.copyWith(hasJoined: true);
}
company = await _repository.getCompanyById(staff.companyId);
} else {
// È l'Admin in onboarding
company = await _repository.getCompanyByOwnerId(user.id);
}
// 1. Controllo Azienda // 1. Controllo Azienda
final company = await _repository.getCompanyByOwnerId(user.id);
if (staff != null) {
// L'utente esiste già nel sistema! Carichiamo l'azienda per cui lavora
company = await _repository.getCompanyById(staff.companyId);
} else {
// L'utente non ha profilo. Probabilmente è l'Admin che ha appena
// fatto Sign Up e sta iniziando l'Onboarding
company = await _repository.getCompanyByOwnerId(user.id);
}
if (company == null) { if (company == null) {
return emit( return emit(
state.copyWith( state.copyWith(
@@ -69,7 +96,6 @@ class SessionCubit extends Cubit<SessionState> {
} }
// 3. Controllo Staff (Paziente Zero) // 3. Controllo Staff (Paziente Zero)
final staff = await _repository.getStaffMemberByUserId(user.id);
if (staff == null) { if (staff == null) {
return emit( return emit(
state.copyWith( state.copyWith(
@@ -102,7 +128,7 @@ class SessionCubit extends Cubit<SessionState> {
user: user, user: user,
company: company, company: company,
currentStore: activeStore, currentStore: activeStore,
currentStaff: staff, currentStaffMember: staff,
onboardingStep: OnboardingStep.none, // Svuotiamo l'onboarding onboardingStep: OnboardingStep.none, // Svuotiamo l'onboarding
), ),
); );

View File

@@ -22,7 +22,7 @@ class SessionState extends Equatable {
final User? user; // Utente di Supabase Auth final User? user; // Utente di Supabase Auth
final CompanyModel? company; final CompanyModel? company;
final StoreModel? currentStore; final StoreModel? currentStore;
final StaffMemberModel? currentStaff; final StaffMemberModel? currentStaffMember;
final OnboardingStep onboardingStep; final OnboardingStep onboardingStep;
final bool isMobileDevice; final bool isMobileDevice;
@@ -31,7 +31,7 @@ class SessionState extends Equatable {
this.user, this.user,
this.company, this.company,
this.currentStore, this.currentStore,
this.currentStaff, this.currentStaffMember,
this.onboardingStep = OnboardingStep.none, this.onboardingStep = OnboardingStep.none,
this.isMobileDevice = false, this.isMobileDevice = false,
}); });
@@ -42,7 +42,7 @@ class SessionState extends Equatable {
User? user, User? user,
CompanyModel? company, CompanyModel? company,
StoreModel? currentStore, StoreModel? currentStore,
StaffMemberModel? currentStaff, StaffMemberModel? currentStaffMember,
OnboardingStep? onboardingStep, OnboardingStep? onboardingStep,
bool? isMobileDevice, bool? isMobileDevice,
}) { }) {
@@ -51,7 +51,7 @@ class SessionState extends Equatable {
user: user ?? this.user, user: user ?? this.user,
company: company ?? this.company, company: company ?? this.company,
currentStore: currentStore ?? this.currentStore, currentStore: currentStore ?? this.currentStore,
currentStaff: currentStaff ?? this.currentStaff, currentStaffMember: currentStaffMember ?? this.currentStaffMember,
onboardingStep: onboardingStep ?? this.onboardingStep, onboardingStep: onboardingStep ?? this.onboardingStep,
isMobileDevice: isMobileDevice ?? this.isMobileDevice, isMobileDevice: isMobileDevice ?? this.isMobileDevice,
); );
@@ -63,7 +63,7 @@ class SessionState extends Equatable {
user, user,
company, company,
currentStore, currentStore,
currentStaff, currentStaffMember,
onboardingStep, onboardingStep,
isMobileDevice, isMobileDevice,
]; ];

View File

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

View File

@@ -28,6 +28,21 @@ class CoreRepository {
} }
} }
Future<CompanyModel?> getCompanyById(String companyId) async {
try {
final response = await _supabase
.from('company')
.select()
.eq('id', companyId)
.maybeSingle();
if (response == null) return null;
return CompanyModel.fromMap(response);
} catch (e) {
debugPrint('Errore recupero azienda per ID: $e');
return null;
}
}
Future<List<StoreModel>> getStoresByCompanyId(String companyId) async { Future<List<StoreModel>> getStoresByCompanyId(String companyId) async {
try { try {
final response = await _supabase final response = await _supabase
@@ -108,4 +123,19 @@ class CoreRepository {
throw Exception('Creazione profilo staff fallita: $e'); throw Exception('Creazione profilo staff fallita: $e');
} }
} }
// Assegna un membro a un negozio
Future<void> assignStaffToStore(String staffId, String storeId) async {
await _supabase.from('staff_in_stores').insert({
'staff_member_id': staffId,
'store_id': storeId,
});
}
Future<void> updateStaffMember(
String staffId,
Map<String, dynamic> data,
) async {
await _supabase.from('staff_member').update(data).eq('id', staffId);
}
} }

View File

@@ -5,6 +5,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
// Importa il tuo SessionCubit e lo State // Importa il tuo SessionCubit e lo State
import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/data/core_repository.dart'; import 'package:flux/core/data/core_repository.dart';
import 'package:flux/core/widgets/set_password_screen.dart';
import 'package:flux/features/customers/ui/customer_mobile_upload_screen.dart'; import 'package:flux/features/customers/ui/customer_mobile_upload_screen.dart';
import 'package:flux/features/auth/ui/auth_screen.dart'; import 'package:flux/features/auth/ui/auth_screen.dart';
import 'package:flux/features/customers/blocs/customer_files_bloc.dart'; import 'package:flux/features/customers/blocs/customer_files_bloc.dart';
@@ -33,6 +34,7 @@ class AppRouter {
final sessionState = sessionCubit.state; final sessionState = sessionCubit.state;
final isGoingToLogin = state.matchedLocation == '/login'; final isGoingToLogin = state.matchedLocation == '/login';
final isGoingToOnboarding = state.matchedLocation == '/onboarding'; final isGoingToOnboarding = state.matchedLocation == '/onboarding';
final isGoingToSetPassword = state.matchedLocation == '/set-password';
// Caso 1: L'app si sta ancora avviando. // Caso 1: L'app si sta ancora avviando.
// Restituiamo null per farlo rimanere sulla SplashScreen del main.dart // Restituiamo null per farlo rimanere sulla SplashScreen del main.dart
@@ -43,7 +45,8 @@ class AppRouter {
// Caso 2: Utente NON loggato. // Caso 2: Utente NON loggato.
if (sessionState.status == SessionStatus.unauthenticated) { if (sessionState.status == SessionStatus.unauthenticated) {
// Se sta già andando al login, lascialo andare. Altrimenti, forzalo al login. // Se sta già andando al login, lascialo andare. Altrimenti, forzalo al login.
return isGoingToLogin ? null : '/login'; if (isGoingToLogin || isGoingToSetPassword) return null;
return '/login';
} }
// Caso 3: Utente loggato MA manca un pezzo dell'azienda (Flusso Canalizzatore) // Caso 3: Utente loggato MA manca un pezzo dell'azienda (Flusso Canalizzatore)
@@ -55,13 +58,13 @@ class AppRouter {
// Caso 4: Utente loggato e configurato (Tutto OK!) // Caso 4: Utente loggato e configurato (Tutto OK!)
if (sessionState.status == SessionStatus.authenticated) { if (sessionState.status == SessionStatus.authenticated) {
// Se per sbaglio cerca di tornare al login o all'onboarding, // Attenzione: un utente appena invitato viene considerato "loggato"
// lo rimbalziamo alla home. // da Supabase appena clicca il link. Quindi se sta andando su /set-password,
// dobbiamo permetterglielo e non rimbalzarlo!
if (isGoingToLogin || isGoingToOnboarding) { if (isGoingToLogin || isGoingToOnboarding) {
return '/'; return '/';
} }
// Per tutte le altre rotte (dashboard, clienti, anagrafiche), lascialo passare. return null; // Lascia passare per /, /customer, e anche /set-password
return null;
} }
return null; return null;
@@ -72,6 +75,10 @@ class AppRouter {
//builder: (context, state) => const LoginScreen(), //builder: (context, state) => const LoginScreen(),
builder: (context, state) => const AuthScreen(), builder: (context, state) => const AuthScreen(),
), ),
GoRoute(
path: '/set-password',
builder: (context, state) => const SetPasswordScreen(),
),
GoRoute( GoRoute(
path: '/onboarding', path: '/onboarding',
builder: (context, state) => BlocProvider( builder: (context, state) => BlocProvider(

View File

@@ -20,6 +20,7 @@ class FluxTextField extends StatefulWidget {
final List<TextInputFormatter>? inputFormatters; final List<TextInputFormatter>? inputFormatters;
final TextCapitalization? textCapitalization; final TextCapitalization? textCapitalization;
final bool? autocorrect; final bool? autocorrect;
final bool? enabled;
const FluxTextField({ const FluxTextField({
super.key, // Usiamo super.key per Flutter moderno super.key, // Usiamo super.key per Flutter moderno
@@ -39,6 +40,7 @@ class FluxTextField extends StatefulWidget {
this.inputFormatters, this.inputFormatters,
this.textCapitalization, this.textCapitalization,
this.autocorrect, this.autocorrect,
this.enabled = true,
}); });
@override @override
@@ -115,6 +117,7 @@ class _FluxTextFieldState extends State<FluxTextField> {
inputFormatters: widget.inputFormatters, inputFormatters: widget.inputFormatters,
textCapitalization: widget.textCapitalization ?? TextCapitalization.none, textCapitalization: widget.textCapitalization ?? TextCapitalization.none,
enabled: widget.enabled,
); );
} }
} }

View File

@@ -0,0 +1,121 @@
import 'package:flutter/material.dart';
import 'package:flux/core/widgets/flux_text_field.dart';
import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:go_router/go_router.dart';
class SetPasswordScreen extends StatefulWidget {
const SetPasswordScreen({super.key});
@override
State<SetPasswordScreen> createState() => _SetPasswordScreenState();
}
class _SetPasswordScreenState extends State<SetPasswordScreen> {
final _passwordCtrl = TextEditingController();
bool _isLoading = false;
@override
void dispose() {
_passwordCtrl.dispose();
super.dispose();
}
Future<void> _savePassword() async {
final newPassword = _passwordCtrl.text.trim();
if (newPassword.length < 6) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("La password deve avere almeno 6 caratteri"),
),
);
return;
}
setState(() => _isLoading = true);
try {
// 1. Aggiorniamo la password dell'utente (che Supabase ha già loggato grazie al link della mail)
await GetIt.I.get<SupabaseClient>().auth.updateUser(
UserAttributes(password: newPassword),
);
// 2. Finito! Lo mandiamo alla home o facciamo ricaricare la sessione al SessionCubit
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Password impostata! Benvenuto a bordo 🚀"),
),
);
context.go('/'); // Rimandiamo al router principale
}
} on AuthException catch (e) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text("Errore Auth: ${e.message}")));
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text("Errore: $e")));
}
} finally {
if (mounted) setState(() => _isLoading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Benvenuto in FLUX!"),
automaticallyImplyLeading:
false, // Non può tornare indietro, deve mettere la password!
),
body: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Icon(Icons.lock_reset, size: 80, color: Colors.blueAccent),
const SizedBox(height: 24),
const Text(
"Imposta la tua Password",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
const Text(
"Hai accettato l'invito. Scegli una password sicura per accedere in futuro.",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey),
),
const SizedBox(height: 32),
FluxTextField(
controller: _passwordCtrl,
label: "Nuova Password",
icon: Icons.lock,
isPassword: true,
),
const SizedBox(height: 32),
ElevatedButton(
onPressed: _isLoading ? null : _savePassword,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
child: _isLoading
? const CircularProgressIndicator(color: Colors.white)
: const Text(
"SALVA E INIZIA",
style: TextStyle(fontSize: 16),
),
),
],
),
),
);
}
}

View File

@@ -1,6 +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: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';
part 'auth_state.dart'; part 'auth_state.dart';
@@ -64,6 +65,28 @@ class AuthCubit extends Cubit<AuthState> {
} }
} }
Future<void> requestPasswordReset(String email) async {
if (email.isEmpty) {
emit(
state.copyWith(
status: AuthStatus.failure,
errorMessage: 'Devi inserire l\'indirizzo email',
),
);
return;
}
await _supabase.auth.resetPasswordForEmail(
email,
redirectTo: resetPasswordUrl,
);
emit(
state.copyWith(
status: AuthStatus.pwResetSent,
infoMessage: "Email per reset password inviata a $email!",
),
);
}
Future<void> requestLogout() async { Future<void> requestLogout() async {
await _supabase.auth.signOut(); await _supabase.auth.signOut();
emit(state.copyWith(status: AuthStatus.initial)); emit(state.copyWith(status: AuthStatus.initial));

View File

@@ -1,6 +1,6 @@
part of 'auth_cubit.dart'; part of 'auth_cubit.dart';
enum AuthStatus { initial, loading, failure } enum AuthStatus { initial, pwResetSent, loading, failure }
class AuthState extends Equatable { class AuthState extends Equatable {
final AuthStatus status; final AuthStatus status;

View File

@@ -162,6 +162,21 @@ class _AuthScreenState extends State<AuthScreen> {
), ),
), ),
), ),
if (state.isLoginMode) ...[
const SizedBox(height: 24),
TextButton(
onPressed: () => context
.read<AuthCubit>()
.requestPasswordReset(_emailController.text.trim()),
child: Text(
'Pw dimenticata/Invito scaduto?',
style: TextStyle(
color: context.accent,
fontWeight: FontWeight.bold,
),
),
),
],
], ],
), ),
), ),

View File

@@ -16,7 +16,7 @@ class StaffCubit extends Cubit<StaffState> {
// Carica tutto lo staff della compagnia // Carica tutto lo staff della compagnia
Future<void> loadAllStaff() async { Future<void> loadAllStaff() async {
emit(state.copyWith(isLoading: true, error: null)); emit(state.copyWith(status: StaffStatus.loading, error: null));
try { try {
final staff = await _repository.getStaffMembers( final staff = await _repository.getStaffMembers(
_sessionCubit.state.company!.id!, _sessionCubit.state.company!.id!,
@@ -27,18 +27,19 @@ class StaffCubit extends Cubit<StaffState> {
} }
emit( emit(
state.copyWith( state.copyWith(
status: StaffStatus.success,
allStaff: staff, allStaff: staff,
isLoading: false,
storesByStaff: storesByStaff, storesByStaff: storesByStaff,
), ),
); );
} catch (e) { } catch (e) {
emit(state.copyWith(isLoading: false, error: e.toString())); emit(state.copyWith(status: StaffStatus.error, error: e.toString()));
} }
} }
Future<List<StoreModel>> loadStoresByStaff(String staffId) async { Future<List<StoreModel>> loadStoresByStaff(String staffId) async {
try { try {
emit(state.copyWith(error: null));
return await _repository.getStaffMemberStore(staffId); return await _repository.getStaffMemberStore(staffId);
} catch (e) { } catch (e) {
emit(state.copyWith(error: e.toString())); emit(state.copyWith(error: e.toString()));
@@ -48,6 +49,7 @@ class StaffCubit extends Cubit<StaffState> {
// Carica lo staff di uno specifico negozio e aggiorna la mappa // Carica lo staff di uno specifico negozio e aggiorna la mappa
Future<void> loadStaffForStore(String storeId) async { Future<void> loadStaffForStore(String storeId) async {
emit(state.copyWith(error: null));
try { try {
final staffInStore = await _repository.getStaffMembersInStore(storeId); final staffInStore = await _repository.getStaffMembersInStore(storeId);
final newMap = Map<String, List<StaffMemberModel>>.from( final newMap = Map<String, List<StaffMemberModel>>.from(
@@ -56,48 +58,87 @@ class StaffCubit extends Cubit<StaffState> {
newMap[storeId] = staffInStore; newMap[storeId] = staffInStore;
emit(state.copyWith(staffByStore: newMap)); emit(state.copyWith(staffByStore: newMap));
} catch (e) { } catch (e) {
// Qui potresti gestire l'errore silenziosamente per non bloccare tutta l'UI emit(state.copyWith(status: StaffStatus.error, error: e.toString()));
} }
} }
// Salva o aggiorna un membro // Salva o aggiorna un membro
Future<void> saveStaffMember(StaffMemberModel member) async { Future<void> saveStaffMember(StaffMemberModel member) async {
emit(state.copyWith(isLoading: true)); emit(state.copyWith(status: StaffStatus.loading, error: null));
try { try {
await _repository.saveStaffMember(member); await _repository.saveStaffMember(member);
await loadAllStaff(); // Ricarichiamo la lista aggiornata await loadAllStaff(); // Ricarichiamo la lista aggiornata
} catch (e) { } catch (e) {
emit(state.copyWith(isLoading: false, error: e.toString())); emit(state.copyWith(status: StaffStatus.error, error: e.toString()));
}
}
Future<void> inviteStaffMember({
required StaffMemberModel member,
required List<String> selectedStoreIds,
}) async {
emit(state.copyWith(status: StaffStatus.loading, error: null));
try {
// 1. Invitiamo il membro e ci facciamo dare l'ID
final newStaffId = await _repository.inviteStaffMember(member);
// 2. Assegniamo i negozi uno ad uno (usando il metodo che avevi già nel repo!)
if (selectedStoreIds.isNotEmpty) {
final List<Future> assignTasks = [];
for (var storeId in selectedStoreIds) {
assignTasks.add(_repository.assignStaffToStore(newStaffId, storeId));
}
await Future.wait(assignTasks); // In parallelo per la massima velocità
}
// 3. Ricarichiamo la lista globale così la UI si aggiorna
await loadAllStaff();
// (Nota: se hai un loadStaffForStore o loadAllStaff, chiamalo qui per rinfrescare lo stato)
emit(state.copyWith(status: StaffStatus.success));
} catch (e) {
emit(state.copyWith(status: StaffStatus.error, error: e.toString()));
} }
} }
// Associa un dipendente a un negozio // Associa un dipendente a un negozio
Future<void> assignMemberToStore(String staffId, String storeId) async { Future<void> assignMemberToStore(String staffId, String storeId) async {
try { try {
await _repository.assignToStore(staffId, storeId); await _repository.assignStaffToStore(staffId, storeId);
final stuffStores = await loadStoresByStaff(staffId); final stuffStores = await loadStoresByStaff(staffId);
final Map<String, List<StoreModel>> storesByStaff = Map.from( final Map<String, List<StoreModel>> storesByStaff = Map.from(
state.storesByStaff, state.storesByStaff,
); );
storesByStaff[staffId] = stuffStores; storesByStaff[staffId] = stuffStores;
emit(state.copyWith(storesByStaff: storesByStaff)); emit(state.copyWith(storesByStaff: storesByStaff, error: null));
} catch (e) { } catch (e) {
emit(state.copyWith(error: "Errore nell'assegnazione: $e")); emit(
state.copyWith(
status: StaffStatus.error,
error: "Errore nell'assegnazione: $e",
),
);
} }
} }
// Rimuove un dipendente da un negozio // Rimuove un dipendente da un negozio
Future<void> removeMemberFromStore(String staffId, String storeId) async { Future<void> removeMemberFromStore(String staffId, String storeId) async {
try { try {
await _repository.removeFromStore(staffId, storeId); await _repository.removeStaffFromStore(staffId, storeId);
final stuffStores = await loadStoresByStaff(staffId); final stuffStores = await loadStoresByStaff(staffId);
final Map<String, List<StoreModel>> storesByStaff = Map.from( final Map<String, List<StoreModel>> storesByStaff = Map.from(
state.storesByStaff, state.storesByStaff,
); );
storesByStaff[staffId] = stuffStores; storesByStaff[staffId] = stuffStores;
emit(state.copyWith(storesByStaff: storesByStaff)); emit(state.copyWith(storesByStaff: storesByStaff, error: null));
} catch (e) { } catch (e) {
emit(state.copyWith(error: "Errore nella rimozione: $e")); emit(
state.copyWith(
status: StaffStatus.error,
error: "Errore nella rimozione: $e",
),
);
} }
} }
@@ -105,7 +146,7 @@ class StaffCubit extends Cubit<StaffState> {
required StaffMemberModel member, required StaffMemberModel member,
required List<String> selectedStoreIds, required List<String> selectedStoreIds,
}) async { }) async {
emit(state.copyWith(isLoading: true)); emit(state.copyWith(status: StaffStatus.loading, error: null));
try { try {
// 1. Salva o aggiorna l'anagrafica (ci serve l'ID) // 1. Salva o aggiorna l'anagrafica (ci serve l'ID)
// Se è un nuovo membro, Supabase ci restituirà l'ID generato // Se è un nuovo membro, Supabase ci restituirà l'ID generato
@@ -120,7 +161,7 @@ class StaffCubit extends Cubit<StaffState> {
if (selectedStoreIds.isNotEmpty) { if (selectedStoreIds.isNotEmpty) {
await Future.wait( await Future.wait(
selectedStoreIds.map( selectedStoreIds.map(
(storeId) => _repository.assignToStore(staffId, storeId), (storeId) => _repository.assignStaffToStore(staffId, storeId),
), ),
); );
} }
@@ -128,9 +169,9 @@ class StaffCubit extends Cubit<StaffState> {
// 3. Rinfresca i dati // 3. Rinfresca i dati
await loadAllStaff(); await loadAllStaff();
emit(state.copyWith(isLoading: false)); emit(state.copyWith(status: StaffStatus.success));
} catch (e) { } catch (e) {
emit(state.copyWith(isLoading: false, error: e.toString())); emit(state.copyWith(status: StaffStatus.error, error: e.toString()));
} }
} }
} }

View File

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

View File

@@ -29,6 +29,37 @@ class StaffRepository {
return StaffMemberModel.fromMap(response); return StaffMemberModel.fromMap(response);
} }
// --- LOGICA DI INVITO (Tramite Edge Function) ---
Future<String> inviteStaffMember(StaffMemberModel newMember) async {
if (newMember.email == null || newMember.email!.isEmpty) {
throw Exception(
"L'indirizzo email è obbligatorio per invitare un collega.",
);
}
try {
final response = await _supabase.functions.invoke(
'invite_staff',
body: newMember.toMap(),
);
if (response.status != 200) {
throw Exception("Errore dal server: ${response.data}");
}
// La funzione ci restituisce l'ID fresco di database!
final responseData = response.data as Map<String, dynamic>;
return responseData['user_id'] as String;
} on FunctionException catch (e) {
throw Exception(
"Errore di comunicazione con il server: ${e.reasonPhrase}",
);
} catch (e) {
throw Exception("Impossibile invitare il collega: $e");
}
}
// --- LOGICA DI GIUNZIONE (Staff <-> Store) --- // --- LOGICA DI GIUNZIONE (Staff <-> Store) ---
// Recupera i membri assegnati a uno specifico negozio // Recupera i membri assegnati a uno specifico negozio
@@ -62,7 +93,7 @@ class StaffRepository {
} }
// Assegna un membro a un negozio // Assegna un membro a un negozio
Future<void> assignToStore(String staffId, String storeId) async { Future<void> assignStaffToStore(String staffId, String storeId) async {
await _supabase.from('staff_in_stores').insert({ await _supabase.from('staff_in_stores').insert({
'staff_member_id': staffId, 'staff_member_id': staffId,
'store_id': storeId, 'store_id': storeId,
@@ -70,7 +101,7 @@ class StaffRepository {
} }
// Rimuove l'assegnazione // Rimuove l'assegnazione
Future<void> removeFromStore(String staffId, String storeId) async { Future<void> removeStaffFromStore(String staffId, String storeId) async {
await _supabase await _supabase
.from('staff_in_stores') .from('staff_in_stores')
.delete() .delete()

View File

@@ -25,6 +25,7 @@ class StaffMemberModel extends Equatable {
final String? jobTitle; final String? jobTitle;
final SystemRole systemRole; final SystemRole systemRole;
final bool isActive; final bool isActive;
final bool hasJoined;
const StaffMemberModel({ const StaffMemberModel({
this.id, this.id,
@@ -36,6 +37,7 @@ class StaffMemberModel extends Equatable {
this.jobTitle, this.jobTitle,
this.systemRole = SystemRole.user, this.systemRole = SystemRole.user,
this.isActive = true, this.isActive = true,
this.hasJoined = false,
}); });
StaffMemberModel copyWith({ StaffMemberModel copyWith({
@@ -49,6 +51,7 @@ class StaffMemberModel extends Equatable {
String? jobTitle, String? jobTitle,
SystemRole? systemRole, SystemRole? systemRole,
bool? isActive, bool? isActive,
bool? hasJoined,
}) { }) {
return StaffMemberModel( return StaffMemberModel(
id: id ?? this.id, id: id ?? this.id,
@@ -60,6 +63,7 @@ class StaffMemberModel extends Equatable {
jobTitle: jobTitle ?? this.jobTitle, jobTitle: jobTitle ?? this.jobTitle,
systemRole: systemRole ?? this.systemRole, systemRole: systemRole ?? this.systemRole,
isActive: isActive ?? this.isActive, isActive: isActive ?? this.isActive,
hasJoined: hasJoined ?? this.hasJoined,
); );
} }
@@ -71,8 +75,6 @@ class StaffMemberModel extends Equatable {
email: '', email: '',
phoneNumber: '', phoneNumber: '',
jobTitle: '', jobTitle: '',
systemRole: SystemRole.user,
isActive: true,
); );
} }
@@ -87,6 +89,7 @@ class StaffMemberModel extends Equatable {
jobTitle: map['job_title'] as String?, jobTitle: map['job_title'] as String?,
systemRole: SystemRole.fromString(map['system_role']), systemRole: SystemRole.fromString(map['system_role']),
isActive: map['is_active'] ?? true, isActive: map['is_active'] ?? true,
hasJoined: map['has_joined'] ?? false,
); );
} }
@@ -101,6 +104,7 @@ class StaffMemberModel extends Equatable {
if (jobTitle != null) 'job_title': jobTitle, if (jobTitle != null) 'job_title': jobTitle,
'system_role': systemRole.name, // Trasforma SystemRole.admin in 'admin' 'system_role': systemRole.name, // Trasforma SystemRole.admin in 'admin'
'is_active': isActive, 'is_active': isActive,
'has_joined': hasJoined,
}; };
} }
@@ -115,5 +119,6 @@ class StaffMemberModel extends Equatable {
jobTitle, jobTitle,
systemRole, systemRole,
isActive, isActive,
hasJoined,
]; ];
} }

View File

@@ -28,6 +28,14 @@ class _StaffScreenState extends State<StaffScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// 1. Peschiamo chi siamo noi e che poteri abbiamo
final myRole = context
.read<SessionCubit>()
.state
.currentStaffMember
?.systemRole;
final canManageStaff =
myRole == SystemRole.admin || myRole == SystemRole.manager;
return Scaffold( return Scaffold(
backgroundColor: context.background, backgroundColor: context.background,
appBar: AppBar( appBar: AppBar(
@@ -45,7 +53,18 @@ class _StaffScreenState extends State<StaffScreen> {
), ),
], ],
), ),
body: Column( body: BlocListener<StaffCubit, StaffState>(
listener: (context, state) {
if (state.status == StaffStatus.error) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.error ?? 'Errore sconosciuto'),
backgroundColor: Colors.red,
),
);
}
},
child: Column(
children: [ children: [
// --- BARRA FILTRO NEGOZIO (Visibile solo se non 'Tutta l'Azienda') --- // --- BARRA FILTRO NEGOZIO (Visibile solo se non 'Tutta l'Azienda') ---
AnimatedContainer( AnimatedContainer(
@@ -64,7 +83,7 @@ class _StaffScreenState extends State<StaffScreen> {
? state.allStaff ? state.allStaff
: (state.staffByStore[_selectedStoreId] ?? []); : (state.staffByStore[_selectedStoreId] ?? []);
if (state.isLoading && list.isEmpty) { if (state.status == StaffStatus.loading && list.isEmpty) {
return const Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
} }
@@ -86,11 +105,14 @@ class _StaffScreenState extends State<StaffScreen> {
), ),
], ],
), ),
floatingActionButton: FloatingActionButton.extended( ),
floatingActionButton: canManageStaff
? FloatingActionButton.extended(
onPressed: () => _openStaffForm(context), onPressed: () => _openStaffForm(context),
label: const Text("Aggiungi"), label: const Text("Aggiungi"),
icon: const Icon(Icons.person_add_alt_1), icon: const Icon(Icons.person_add_alt_1),
), )
: null,
); );
} }
@@ -117,6 +139,13 @@ class _StaffScreenState extends State<StaffScreen> {
} }
Widget _buildStaffCard(StaffMemberModel member) { Widget _buildStaffCard(StaffMemberModel member) {
final myRole = context
.read<SessionCubit>()
.state
.currentStaffMember
?.systemRole;
final canManageStaff =
myRole == SystemRole.admin || myRole == SystemRole.manager;
return Card( return Card(
elevation: 0, elevation: 0,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
@@ -145,8 +174,9 @@ class _StaffScreenState extends State<StaffScreen> {
), ),
], ],
), ),
trailing: const Icon(Icons.edit_note), trailing: canManageStaff ? const Icon(Icons.edit_note) : null,
onTap: () => _openStaffForm(context, member: member), onTap: () =>
canManageStaff ? _openStaffForm(context, member: member) : null,
), ),
); );
} }
@@ -155,9 +185,10 @@ class _StaffScreenState extends State<StaffScreen> {
final nameController = TextEditingController(text: member?.name); final nameController = TextEditingController(text: member?.name);
final emailController = TextEditingController(text: member?.email); final emailController = TextEditingController(text: member?.email);
final phoneController = TextEditingController(text: member?.phoneNumber); final phoneController = TextEditingController(text: member?.phoneNumber);
final jobTitleController = TextEditingController(text: member?.jobTitle);
// 1. Inizializziamo la lista temporanea attingendo dallo stato del Cubit // Variabili di stato per il BottomSheet
// Usiamo storesByStaff (la mappa che indicizza i negozi per ogni ID dipendente) SystemRole selectedRole = member?.systemRole ?? SystemRole.user;
List<String> tempSelectedStores = List<String> tempSelectedStores =
context context
.read<StaffCubit>() .read<StaffCubit>()
@@ -172,7 +203,6 @@ class _StaffScreenState extends State<StaffScreen> {
isScrollControlled: true, isScrollControlled: true,
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
builder: (context) => StatefulBuilder( builder: (context) => StatefulBuilder(
// <--- QUESTO è il segreto per le Chip
builder: (context, setModalState) { builder: (context, setModalState) {
return Container( return Container(
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -194,7 +224,7 @@ class _StaffScreenState extends State<StaffScreen> {
children: [ children: [
Text( Text(
member == null member == null
? "Nuovo Collaboratore" ? "Invita Collaboratore" // Cambiato il titolo per chiarezza!
: "Modifica Collaboratore", : "Modifica Collaboratore",
style: const TextStyle( style: const TextStyle(
fontSize: 20, fontSize: 20,
@@ -202,32 +232,77 @@ class _StaffScreenState extends State<StaffScreen> {
), ),
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
FluxTextField( FluxTextField(
controller: nameController, controller: nameController,
label: "Nome e Cognome", label: "Nome e Cognome",
icon: Icons.person, icon: Icons.person,
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
// Reso visivamente obbligatorio se è un nuovo utente
FluxTextField( FluxTextField(
controller: emailController, controller: emailController,
label: "Email", label: member == null
? "Email (Obbligatoria per invito)*"
: "Email",
icon: Icons.email, icon: Icons.email,
enabled:
member ==
null, // UX: Di solito l'email non si cambia dopo l'invito
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
FluxTextField( FluxTextField(
controller: phoneController, controller: phoneController,
label: "Telefono", label: "Telefono",
icon: Icons.phone, icon: Icons.phone,
), ),
const SizedBox(height: 16),
// --- NOVITÀ: SCELTA DEL RUOLO E MANSIONE ---
Row(
children: [
Expanded(
flex: 2,
child: DropdownButtonFormField<SystemRole>(
initialValue: selectedRole,
decoration: const InputDecoration(
labelText: "Ruolo di Sistema",
prefixIcon: Icon(Icons.admin_panel_settings),
),
items: SystemRole.values.map((role) {
return DropdownMenuItem(
value: role,
child: Text(role.name.toUpperCase()),
);
}).toList(),
onChanged: (val) {
if (val != null) {
setModalState(() => selectedRole = val);
}
},
),
),
const SizedBox(width: 16),
Expanded(
flex: 3,
child: FluxTextField(
controller: jobTitleController,
label: "Qualifica (Es. Addetto)",
icon: Icons.badge,
),
),
],
),
const SizedBox(height: 24), const SizedBox(height: 24),
const Text( const Text(
"Assegna ai Negozi", "Assegna ai Negozi",
style: TextStyle(fontWeight: FontWeight.bold), style: TextStyle(fontWeight: FontWeight.bold),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
// --- SELETTORE NEGOZI (CHIPS) ---
// Qui usiamo il BlocBuilder per i negozi, ma il setModalState per il refresh
BlocBuilder<StoreCubit, StoreState>( BlocBuilder<StoreCubit, StoreState>(
builder: (context, storeState) { builder: (context, storeState) {
if (storeState.status == StoreStatus.loading) { if (storeState.status == StoreStatus.loading) {
@@ -244,7 +319,6 @@ class _StaffScreenState extends State<StaffScreen> {
label: Text(store.nome), label: Text(store.nome),
selected: isSelected, selected: isSelected,
onSelected: (selected) { onSelected: (selected) {
// IMPORTANTE: setModalState aggiorna l'UI del BottomSheet
setModalState(() { setModalState(() {
if (selected) { if (selected) {
tempSelectedStores.add(store.id!); tempSelectedStores.add(store.id!);
@@ -269,11 +343,26 @@ class _StaffScreenState extends State<StaffScreen> {
height: 50, height: 50,
child: ElevatedButton( child: ElevatedButton(
onPressed: () { onPressed: () {
// Validazione di base per i nuovi inviti
if (member == null &&
emailController.text.trim().isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
"L'email è obbligatoria per invitare!",
),
),
);
return;
}
final updatedMember = StaffMemberModel( final updatedMember = StaffMemberModel(
id: member?.id, id: member?.id, // Sarà null se è nuovo
name: nameController.text, name: nameController.text.trim(),
email: emailController.text, email: emailController.text.trim(),
phoneNumber: phoneController.text, phoneNumber: phoneController.text.trim(),
jobTitle: jobTitleController.text.trim(),
systemRole: selectedRole,
companyId: GetIt.I companyId: GetIt.I
.get<SessionCubit>() .get<SessionCubit>()
.state .state
@@ -282,15 +371,28 @@ class _StaffScreenState extends State<StaffScreen> {
userId: GetIt.I.get<SessionCubit>().state.user!.id, userId: GetIt.I.get<SessionCubit>().state.user!.id,
); );
// Chiamiamo il metodo atomico nel Cubit // --- IL BIVIO LOGICO MAGICO ---
if (member == null) {
// 1. UTENTE NUOVO -> Chiamiamo la Edge Function
// (Nota: Per i negozi, potresti dover fare una logica a parte nel Cubit
// perché l'ID del database viene generato DOPO che l'Edge Function ha finito)
context.read<StaffCubit>().inviteStaffMember(
member: updatedMember,
selectedStoreIds: tempSelectedStores,
);
} else {
// 2. UTENTE ESISTENTE -> Modifica classica
context.read<StaffCubit>().saveStaffWithStores( context.read<StaffCubit>().saveStaffWithStores(
member: updatedMember, member: updatedMember,
selectedStoreIds: tempSelectedStores, selectedStoreIds: tempSelectedStores,
); );
}
Navigator.pop(context); Navigator.pop(context);
}, },
child: const Text("SALVA COLLABORATORE"), child: Text(
member == null ? "INVIA INVITO" : "SALVA MODIFICHE",
),
), ),
), ),
], ],

View File

@@ -137,7 +137,7 @@ class StoreCubit extends Cubit<StoreState> {
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.assignStaffToStore(staffId, storeId);
// Dopo l'assegnazione, potresti voler ricaricare lo staff per quel negozio // Dopo l'assegnazione, potresti voler ricaricare lo staff per quel negozio
loadStores(); loadStores();
} catch (e) { } catch (e) {
@@ -150,7 +150,7 @@ class StoreCubit extends Cubit<StoreState> {
// Rimuove un dipendente da un negozio // Rimuove un dipendente da un negozio
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.removeStaffFromStore(staffId, storeId);
loadStores(); loadStores();
} catch (e) { } catch (e) {
emit( emit(

View File

@@ -13,11 +13,13 @@ class OnboardingCubit extends Cubit<OnboardingState> {
final SessionCubit _sessionCubit; final SessionCubit _sessionCubit;
OnboardingCubit(this._sessionCubit, this._repository) OnboardingCubit(this._sessionCubit, this._repository)
: super(OnboardingState( : super(
OnboardingState(
step: _sessionCubit.state.onboardingStep, step: _sessionCubit.state.onboardingStep,
companyId: _sessionCubit.state.company?.id, companyId: _sessionCubit.state.company?.id,
storeId: _sessionCubit.state.currentStore?.id, storeId: _sessionCubit.state.currentStore?.id,
)); ),
);
// --- STEP 1: REGISTRAZIONE AZIENDA --- // --- STEP 1: REGISTRAZIONE AZIENDA ---
Future<void> saveCompany(String companyName) async { Future<void> saveCompany(String companyName) async {
@@ -86,11 +88,17 @@ class OnboardingCubit extends Cubit<OnboardingState> {
// PARANOIA MODE: Forziamo i legami e il ruolo di sistema 'admin' // PARANOIA MODE: Forziamo i legami e il ruolo di sistema 'admin'
final staffToSave = staff.copyWith( final staffToSave = staff.copyWith(
companyId: state.companyId!, companyId: state.companyId!,
userId: _sessionCubit.state.user!.id, // Dall'utente loggato in Supabase userId: _sessionCubit.state.user!.id,
systemRole: SystemRole.admin, // Blindato! systemRole: SystemRole.admin,
); );
await _repository.createStaffMember(staffToSave); // 1. Salviamo lo staff e CI FACCIAMO RESTITUIRE IL MODELLO (con l'id generato!)
final savedStaff = await _repository.createStaffMember(staffToSave);
// 2. LA MAGIA: Colleghiamo il Paziente Zero al Negozio appena creato!
if (state.storeId != null && savedStaff.id != null) {
await _repository.assignStaffToStore(savedStaff.id!, state.storeId!);
}
emit(state.copyWith(isLoading: false, step: OnboardingStep.completed)); emit(state.copyWith(isLoading: false, step: OnboardingStep.completed));

View File

@@ -1,9 +1,11 @@
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_cubit.dart';
import 'package:flux/core/utils/validators.dart'; import 'package:flux/core/utils/validators.dart';
import 'package:flux/core/widgets/flux_text_field.dart'; import 'package:flux/core/widgets/flux_text_field.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/onboarding/blocs/onboarding_cubit.dart'; import 'package:flux/features/onboarding/blocs/onboarding_cubit.dart';
import 'package:get_it/get_it.dart';
class StaffOnboardingForm extends StatefulWidget { class StaffOnboardingForm extends StatefulWidget {
const StaffOnboardingForm({super.key}); const StaffOnboardingForm({super.key});
@@ -26,6 +28,12 @@ class _StaffOnboardingFormState extends State<StaffOnboardingForm> {
super.dispose(); super.dispose();
} }
@override
void initState() {
_emailCtrl.text = GetIt.I.get<SessionCubit>().state.user?.email ?? '';
super.initState();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Padding( return Padding(

View File

@@ -174,7 +174,6 @@ class AttachmentsSection extends StatelessWidget {
); );
}, },
), ),
// --- PANNELLO AZIONI CONTESTUALI (LA MAGIA) --- // --- PANNELLO AZIONI CONTESTUALI (LA MAGIA) ---
// Appare SOLO se c'è almeno un file selezionato // Appare SOLO se c'è almeno un file selezionato
if (state.selectedFiles.isNotEmpty) if (state.selectedFiles.isNotEmpty)