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,56 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flux/core/blocs/session/session_bloc.dart';
import 'package:flux/features/master_data/store/data/store_repository.dart';
import 'package:flux/features/master_data/store/models/store_model.dart';
import 'package:get_it/get_it.dart';
part 'store_events.dart';
part 'store_state.dart';
class StoreBloc extends Bloc<StoreEvent, StoreState> {
final StoreRepository _repository = GetIt.I<StoreRepository>();
final SessionBloc _sessionBloc;
StoreBloc(this._sessionBloc) : super(const StoreState(stores: [])) {
on<CreateStoreRequested>(_onCreateStore);
on<LoadStoresRequested>(_onLoadStores);
}
Future<void> _onCreateStore(
CreateStoreRequested event,
Emitter<StoreState> emit,
) async {
emit(state.copyWith(status: StoreStatus.loading));
try {
await _repository.createStore(event.store);
emit(state.copyWith(status: StoreStatus.success));
} catch (e) {
emit(
state.copyWith(status: StoreStatus.failure, errorMessage: e.toString()),
);
}
}
Future<void> _onLoadStores(
LoadStoresRequested event,
Emitter<StoreState> emit,
) async {
emit(state.copyWith(status: StoreStatus.loading));
try {
final stores = await _repository.getStoresByCompany(
_sessionBloc.state.company!.id,
);
emit(
state.copyWith(
status: StoreStatus.success,
stores: stores, // Assicurati di avere 'stores' nello StoreState
),
);
} catch (e) {
emit(
state.copyWith(status: StoreStatus.failure, errorMessage: e.toString()),
);
}
}
}

View File

@@ -0,0 +1,18 @@
part of 'store_bloc.dart';
abstract class StoreEvent extends Equatable {
const StoreEvent();
@override
List<Object?> get props => [];
}
class CreateStoreRequested extends StoreEvent {
final StoreModel store;
const CreateStoreRequested({required this.store});
@override
List<Object?> get props => [store];
}
class LoadStoresRequested extends StoreEvent {}

View File

@@ -0,0 +1,34 @@
part of 'store_bloc.dart';
enum StoreStatus { initial, loading, success, failure }
class StoreState extends Equatable {
final StoreStatus status;
final StoreModel? store;
final String? errorMessage;
final List<StoreModel> stores;
const StoreState({
this.status = StoreStatus.initial,
this.store,
this.errorMessage,
required this.stores,
});
StoreState copyWith({
StoreStatus? status,
StoreModel? store,
String? errorMessage,
List<StoreModel>? stores,
}) {
return StoreState(
status: status ?? this.status,
store: store ?? this.store,
errorMessage: errorMessage ?? this.errorMessage,
stores: stores ?? this.stores,
);
}
@override
List<Object?> get props => [status, store, errorMessage, stores];
}

View File

@@ -0,0 +1,36 @@
import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/store_model.dart';
class StoreRepository {
final SupabaseClient _client = GetIt.I.get<SupabaseClient>();
/// Crea un nuovo negozio associato alla compagnia dell'utente
Future<void> createStore(StoreModel store) async {
try {
await _client.from('store').insert(store.toJson());
} on PostgrestException catch (e) {
// Intercettiamo errori specifici del database
throw e.message;
} catch (e) {
throw 'Errore imprevisto durante la creazione del negozio: $e';
}
}
/// Recupera tutti i negozi di una determinata compagnia
Future<List<StoreModel>> getStoresByCompany(String companyId) async {
try {
final response = await _client
.from('store')
.select()
.eq('company_id', companyId)
.order('created_at');
return (response as List)
.map((json) => StoreModel.fromJson(json))
.toList();
} catch (e) {
throw 'Errore nel recupero dei negozi';
}
}
}

View File

@@ -0,0 +1,102 @@
import 'package:equatable/equatable.dart';
class StoreModel extends Equatable {
final String? id;
final String nome;
final String companyId;
final bool isActive;
final bool isPaid;
final DateTime? paymentExpiration;
final String indirizzo;
final String cap;
final String comune;
final String provincia;
const StoreModel({
this.id,
required this.nome,
required this.companyId,
this.isActive = true,
this.isPaid = false,
this.paymentExpiration,
required this.indirizzo,
required this.cap,
required this.comune,
required this.provincia,
});
// Fondamentale per Equatable: definisce quali proprietà determinano l'uguaglianza
@override
List<Object?> get props => [
id,
nome,
companyId,
isActive,
isPaid,
paymentExpiration,
indirizzo,
cap,
comune,
provincia,
];
// Il mitico copyWith per creare nuove istanze modificando solo ciò che serve
StoreModel copyWith({
String? id,
String? nome,
String? companyId,
bool? isActive,
bool? isPaid,
DateTime? paymentExpiration,
String? indirizzo,
String? cap,
String? comune,
String? provincia,
}) {
return StoreModel(
id: id ?? this.id,
nome: nome ?? this.nome,
companyId: companyId ?? this.companyId,
isActive: isActive ?? this.isActive,
isPaid: isPaid ?? this.isPaid,
paymentExpiration: paymentExpiration ?? this.paymentExpiration,
indirizzo: indirizzo ?? this.indirizzo,
cap: cap ?? this.cap,
comune: comune ?? this.comune,
provincia: provincia ?? this.provincia,
);
}
factory StoreModel.fromJson(Map<String, dynamic> json) {
return StoreModel(
id: json['id'] as String,
nome: json['nome'],
companyId: json['company_id'] as String,
isActive: json['is_active'] ?? true,
isPaid: json['is_paid'] ?? false,
paymentExpiration: json['payment_expiration'] != null
? DateTime.parse(json['payment_expiration'])
: null,
indirizzo: json['indirizzo'],
cap: json['cap'],
comune: json['comune'],
provincia: json['provincia'],
);
}
Map<String, dynamic> toJson() {
return {
if (id != null) 'id': id,
'nome': nome,
'company_id': companyId,
'is_active': isActive,
'is_paid': isPaid,
if (paymentExpiration != null)
'payment_expiration': paymentExpiration!.toIso8601String(),
'indirizzo': indirizzo,
'cap': cap,
'comune': comune,
'provincia': provincia,
};
}
}

View File

@@ -0,0 +1,253 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/master_data/store/bloc/store_bloc.dart';
import 'package:flux/features/master_data/store/models/store_model.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';
class CreateStoreScreen extends StatefulWidget {
const CreateStoreScreen({super.key});
@override
State<CreateStoreScreen> createState() => _CreateStoreScreenState();
}
class _CreateStoreScreenState extends State<CreateStoreScreen> {
final _formKey = GlobalKey<FormState>();
final _nomeController = TextEditingController();
final _indirizzoController = TextEditingController();
final _capController = TextEditingController();
final _comuneController = TextEditingController();
final _provinciaController = TextEditingController();
@override
void dispose() {
_nomeController.dispose();
_indirizzoController.dispose();
_capController.dispose();
_comuneController.dispose();
_provinciaController.dispose();
super.dispose();
}
/// Funzione magica per copiare i dati dall'azienda salvata in GetIt
void _useCompanyAddress() {
final company = context.read<SessionBloc>().state.company;
if (company != null) {
setState(() {
_indirizzoController.text = company.indirizzo;
_capController.text = company.cap;
_comuneController.text =
company.citta; // Nel DB company è 'citta', store è 'comune'
_provinciaController.text = company.provincia;
// Suggeriamo anche un nome se vuoto
if (_nomeController.text.isEmpty) {
_nomeController.text = '${company.ragioneSociale} - Sede';
}
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Dati indirizzo copiati dalla sede legale'),
),
);
}
}
void _onSave() {
if (_formKey.currentState!.validate()) {
final company = context.read<SessionBloc>().state.company;
if (company == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Errore: Azienda non trovata')),
);
return;
}
final store = StoreModel(
nome: _nomeController.text.trim(),
companyId: company.id,
indirizzo: _indirizzoController.text.trim(),
cap: _capController.text.trim(),
comune: _comuneController.text.trim(),
provincia: _provinciaController.text.trim().toUpperCase(),
);
context.read<StoreBloc>().add(CreateStoreRequested(store: store));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Il tuo primo Negozio')),
body: BlocConsumer<StoreBloc, StoreState>(
listener: (context, state) {
if (state.status == StoreStatus.success) {
context.read<SessionBloc>().add(AppStarted());
}
if (state.status == StoreStatus.failure) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.errorMessage ?? 'Errore salvataggio'),
),
);
}
},
builder: (context, state) {
return SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildHeader(context),
const SizedBox(height: 32),
// Nome del Negozio (Icona obbligatoria)
FluxTextField(
label: 'Nome del Negozio',
icon: Icons.storefront_rounded,
controller: _nomeController,
keyboardType: TextInputType.name,
),
const SizedBox(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_SectionTitle(title: 'LOCALIZZAZIONE'),
TextButton.icon(
onPressed: _useCompanyAddress,
icon: const Icon(Icons.copy_rounded, size: 16),
label: const Text(
'Copia da Azienda',
style: TextStyle(fontSize: 12),
),
),
],
),
const SizedBox(height: 12),
// Indirizzo (Icona obbligatoria)
FluxTextField(
label: 'Indirizzo e n. civico',
icon: Icons.map_outlined,
controller: _indirizzoController,
keyboardType: TextInputType.streetAddress,
),
const SizedBox(height: 16),
// RIGA TRIPLA: Comune, CAP, PR
Row(
crossAxisAlignment: CrossAxisAlignment
.start, // Allinea in alto in caso di errori
children: [
Expanded(
flex: 2,
child: FluxTextField(
label: 'CAP',
icon: Icons.post_add_rounded, // Icona aggiunta
controller: _capController,
keyboardType: TextInputType.number,
maxLength: 5,
),
),
const SizedBox(width: 12),
Expanded(
flex: 3,
child: FluxTextField(
label: 'Comune',
icon: Icons.location_city_rounded, // Icona aggiunta
controller: _comuneController,
keyboardType: TextInputType.name,
),
),
const SizedBox(width: 12),
Expanded(
flex: 2, // Aumentato leggermente per ospitare l'icona
child: FluxTextField(
label: 'PR',
icon: Icons.explore_outlined, // Icona aggiunta
controller: _provinciaController,
keyboardType: TextInputType.name,
onChanged: (value) => value.toUpperCase(),
maxLength: 2,
),
),
],
),
const SizedBox(height: 48),
_buildSubmitButton(context, state),
],
),
),
),
);
},
),
);
}
Widget _buildSubmitButton(BuildContext context, StoreState state) {
return SizedBox(
width: double.infinity,
height: 56,
child: ElevatedButton(
onPressed: state.status == StoreStatus.loading ? null : _onSave,
child: state.status == StoreStatus.loading
? const CircularProgressIndicator(color: Colors.white)
: const Text('ATTIVA NEGOZIO'),
),
);
}
Widget _buildHeader(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.add_location_alt_rounded, color: context.accent, size: 48),
const SizedBox(height: 16),
Text(
'Dove si trova il tuo store?',
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
color: context.primaryText,
),
),
const SizedBox(height: 8),
Text(
'Configura il primo punto vendita per iniziare a gestire i tuoi clienti e le operazioni.',
style: TextStyle(color: context.secondaryText, fontSize: 15),
),
],
);
}
}
class _SectionTitle extends StatelessWidget {
final String title;
const _SectionTitle({required this.title});
@override
Widget build(BuildContext context) {
return Text(
title,
style: TextStyle(
color: context.accent,
fontWeight: FontWeight.w800,
letterSpacing: 1.2,
fontSize: 12,
),
);
}
}

View File

@@ -0,0 +1,296 @@
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';
import 'package:flux/features/master_data/store/bloc/store_bloc.dart';
import 'package:flux/features/master_data/store/models/store_model.dart';
class StoresScreen extends StatefulWidget {
const StoresScreen({super.key});
@override
State<StoresScreen> createState() => _StoresScreenState();
}
class _StoresScreenState extends State<StoresScreen> {
@override
void initState() {
super.initState();
// Carichiamo i negozi e anche lo staff (per poterlo assegnare)
context.read<StoreBloc>().add(LoadStoresRequested());
context.read<StaffCubit>().loadAllStaff();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("I Tuoi Negozi")),
body: BlocBuilder<StoreBloc, StoreState>(
builder: (context, state) {
if (state.status == StoreStatus.loading)
return const Center(child: CircularProgressIndicator());
return ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: state.stores.length,
itemBuilder: (context, index) {
final store = state.stores[index];
return _buildStoreCard(store);
},
);
},
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => _openStoreForm(context),
label: const Text("Nuovo Negozio"),
icon: const Icon(Icons.store),
),
);
}
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<StaffCubit, StaffState>(
builder: (context, staffState) {
final staffCount =
staffState.storesByStaff[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>(
builder: (context, state) {
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),
// Lista di TUTTO lo staff dell'azienda con checkbox
...state.allStaff.map((person) {
final bool isAssigned =
state.storesByStaff[store.id!]?.any(
(s) => s.id == person.id,
) ??
false;
return CheckboxListTile(
title: Text(person.name),
value: isAssigned,
onChanged: (selected) {
if (selected == true) {
context.read<StaffCubit>().assignMemberToStore(
person.id!,
store.id!,
);
} else {
context.read<StaffCubit>().removeMemberFromStore(
person.id!,
store.id!,
);
}
},
);
}),
],
),
);
},
),
);
}
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(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => 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(
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<StoreBloc>().add(
CreateStoreRequested(store: storeData),
);
Navigator.pop(context);
},
child: Text(store == null ? "CREA NEGOZIO" : "AGGIORNA DATI"),
),
),
],
),
),
),
);
}
}