Add Providers Management to Master Data Hub and Enhance Provider Model

This commit is contained in:
2026-04-16 19:25:42 +02:00
parent c7eedba5ac
commit aa18b7dd1f
5 changed files with 188 additions and 46 deletions

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flux/core/theme/theme.dart'; import 'package:flux/core/theme/theme.dart';
import 'package:flux/features/customers/ui/customers_content.dart'; import 'package:flux/features/customers/ui/customers_content.dart';
import 'package:flux/features/master_data/products/ui/products_screen.dart'; import 'package:flux/features/master_data/products/ui/products_screen.dart';
import 'package:flux/features/master_data/providers/ui/providers_master_data_screen.dart';
import 'package:flux/features/master_data/staff/ui/staff_screen.dart'; import 'package:flux/features/master_data/staff/ui/staff_screen.dart';
import 'package:flux/features/master_data/store/ui/stores_screen.dart'; import 'package:flux/features/master_data/store/ui/stores_screen.dart';
@@ -38,34 +39,57 @@ class MasterDataHubContent extends StatelessWidget {
mainAxisSpacing: 16, mainAxisSpacing: 16,
crossAxisSpacing: 16, crossAxisSpacing: 16,
children: [ children: [
_HubCard( _buildHubCard(
label: 'Prodotti', context,
title: 'Prodotti',
subtitle: 'Anagrafica di Marche e Modelli',
icon: Icons.inventory_2_outlined, icon: Icons.inventory_2_outlined,
color: Colors.blue, color: Colors.blue,
onTap: () => onOpenPage( onTap: () => onOpenPage(
const ProductsScreen(), const ProductsScreen(),
), // Apre ProductsScreen, // Indice per ProductsScreen ), // Apre ProductsScreen, // Indice per ProductsScreen
), ),
_HubCard( _buildHubCard(
label: 'Clienti', context,
title: 'Clienti',
subtitle: 'Anagrafica dei clienti del tuo business',
icon: Icons.people_outlined, icon: Icons.people_outlined,
color: Colors.orange, color: Colors.orange,
onTap: () => onOpenPage( onTap: () => onOpenPage(
const CustomersContent(), const CustomersContent(),
), // Indice per CustomersContent ), // Indice per CustomersContent
), ),
_HubCard( _buildHubCard(
label: 'Commessi', context,
title: 'Addetti',
subtitle: 'Anagrafica del personale e dei collaboratori',
icon: Icons.badge_outlined, icon: Icons.badge_outlined,
color: Colors.teal, color: Colors.teal,
onTap: () => onOpenPage(const StaffScreen()), onTap: () => onOpenPage(const StaffScreen()),
), ),
_HubCard( _buildHubCard(
label: 'Negozi', context,
title: 'Negozi',
subtitle: 'Anagrafica punti vendita della tua azienda',
icon: Icons.storefront_outlined, icon: Icons.storefront_outlined,
color: Colors.purple, color: Colors.purple,
onTap: () => onOpenPage(const StoresScreen()), onTap: () => onOpenPage(const StoresScreen()),
), ),
_buildHubCard(
context,
title: 'Gestione Provider',
subtitle: 'Anagrafica mandati e servizi abilitati',
icon: Icons.handshake_rounded,
color: Colors.indigo,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ProvidersMasterDataScreen(),
),
);
},
),
], ],
), ),
), ),
@@ -75,41 +99,57 @@ class MasterDataHubContent extends StatelessWidget {
} }
} }
// Widget semplice per le card dell'hub Widget _buildHubCard(
class _HubCard extends StatelessWidget { BuildContext context, {
final String label; required String title,
final IconData icon; required String subtitle,
final Color color; required IconData icon,
final VoidCallback onTap; required Color color,
required VoidCallback onTap,
const _HubCard({ }) {
required this.label,
required this.icon,
required this.color,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return Card( return Card(
elevation: 0, clipBehavior: Clip.antiAlias,
color: context.background, elevation: 2,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
side: BorderSide(color: context.accent.withValues(alpha: 0.1)), ), // Un pelo più arrotondato
),
child: InkWell( child: InkWell(
onTap: onTap, onTap: onTap,
borderRadius: BorderRadius.circular(16), child: Padding(
padding: const EdgeInsets.all(
24.0,
), // Aumentiamo il padding per dare respiro
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, // CENTRA VERTICALMENTE
crossAxisAlignment:
CrossAxisAlignment.center, // CENTRA ORIZZONTALMENTE
children: [ children: [
Icon(icon, color: color, size: 40), // Icona con un leggero sfondo circolare opaco per farla risaltare
const SizedBox(height: 12), Container(
Text(label, style: const TextStyle(fontWeight: FontWeight.bold)), padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.1), // <--- API moderna
shape: BoxShape.circle,
),
child: Icon(icon, size: 48, color: color),
),
const SizedBox(height: 16),
Text(
title,
textAlign: TextAlign.center, // Centra il testo
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
subtitle,
textAlign: TextAlign.center, // Centra il sottotitolo
style: TextStyle(fontSize: 13, color: Colors.grey.shade500),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
], ],
), ),
), ),
),
); );
} }
}

View File

@@ -108,7 +108,10 @@ class ProvidersCubit extends Cubit<ProvidersState> {
Future<void> saveProvider(ProviderModel provider) async { Future<void> saveProvider(ProviderModel provider) async {
emit(state.copyWith(isLoading: true)); emit(state.copyWith(isLoading: true));
try { try {
await _repository.saveProvider(provider); final providerWithCompanyId = provider.copyWith(
companyId: _sessionBloc.state.company!.id,
);
await _repository.saveProvider(providerWithCompanyId);
// Ricarichiamo la lista per vedere le modifiche // Ricarichiamo la lista per vedere le modifiche
await loadProviders(null); await loadProviders(null);
} catch (e) { } catch (e) {

View File

@@ -40,14 +40,29 @@ 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('''
.eq('company_id', companyId); *,
providers_in_stores(count)
''')
.eq('company_id', companyId)
.order('nome');
return (response as List).map((m) => ProviderModel.fromMap(m)).toList(); return (response as List).map((m) {
// 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 provider: $e'); throw Exception('Errore fetch all providers: $e');
} }
} }

View File

@@ -11,6 +11,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;
const ProviderModel({ const ProviderModel({
this.id, this.id,
@@ -23,6 +24,7 @@ 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
}); });
factory ProviderModel.fromMap(Map<String, dynamic> map) { factory ProviderModel.fromMap(Map<String, dynamic> map) {
@@ -37,6 +39,11 @@ 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:
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
); );
} }
@@ -72,6 +79,7 @@ class ProviderModel extends Equatable {
altro, altro,
isActive, isActive,
companyId, companyId,
storesCount,
]; ];
ProviderModel copyWith({ ProviderModel copyWith({
@@ -85,6 +93,7 @@ class ProviderModel extends Equatable {
bool? altro, bool? altro,
bool? isActive, bool? isActive,
String? companyId, String? companyId,
int? storesCount,
}) { }) {
return ProviderModel( return ProviderModel(
id: id ?? this.id, id: id ?? this.id,
@@ -97,6 +106,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,
); );
} }
} }

View File

@@ -30,6 +30,54 @@ class _ProvidersMasterDataScreenState extends State<ProvidersMasterDataScreen> {
return const Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
} }
if (state.allProviders.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(32.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Un'icona grande e stilizzata
Icon(
Icons.handshake_outlined,
size: 80,
color: Colors.indigo.withValues(alpha: 0.3),
),
const SizedBox(height: 24),
const Text(
"Nessun Provider configurato",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 12),
const Text(
"Aggiungi i partner con cui collabori (es. Enel, WindTre, ecc.) per poter gestire i servizi e i mandati nei tuoi negozi.",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey),
),
const SizedBox(height: 32),
// Un bel bottone centrato per chi non vuole usare il FAB in basso
ElevatedButton.icon(
onPressed: () => _showProviderForm(context, null),
icon: const Icon(Icons.add),
label: const Text("AGGIUNGI IL PRIMO PROVIDER"),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.indigo,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
),
),
],
),
),
);
}
return ListView.separated( return ListView.separated(
itemCount: state.allProviders.length, itemCount: state.allProviders.length,
separatorBuilder: (context, index) => const Divider(height: 1), separatorBuilder: (context, index) => const Divider(height: 1),
@@ -49,7 +97,9 @@ class _ProvidersMasterDataScreenState extends State<ProvidersMasterDataScreen> {
provider.nome, provider.nome,
style: const TextStyle(fontWeight: FontWeight.bold), style: const TextStyle(fontWeight: FontWeight.bold),
), ),
subtitle: _buildProviderBadges(provider), subtitle: _buildCardSubtitle(
provider,
), // Una funzione che costruisce il sottotitolo con i badge
trailing: const Icon(Icons.edit_outlined), trailing: const Icon(Icons.edit_outlined),
onTap: () => _showProviderForm(context, provider), onTap: () => _showProviderForm(context, provider),
); );
@@ -64,6 +114,30 @@ class _ProvidersMasterDataScreenState extends State<ProvidersMasterDataScreen> {
); );
} }
Widget _buildCardSubtitle(ProviderModel provider) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildProviderBadges(provider), // I badge che abbiamo fatto prima
const SizedBox(height: 4),
BlocBuilder<ProvidersCubit, ProvidersState>(
builder: (context, state) {
// Un piccolo testo che indica il numero di store associati
// Nota: Dovrai assicurarti che il Cubit carichi queste info
return Text(
"Disponibile in ${provider.storesCount} negozi",
style: TextStyle(
fontSize: 11,
color: Colors.indigo.withValues(alpha: 0.7),
),
);
},
),
_buildProviderBadges(provider),
],
);
}
// Visualizza i servizi abilitati per quel provider nella lista // Visualizza i servizi abilitati per quel provider nella lista
Widget _buildProviderBadges(ProviderModel p) { Widget _buildProviderBadges(ProviderModel p) {
return Wrap( return Wrap(