diff --git a/.gitignore b/.gitignore index 4fb6c39..df3897e 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,4 @@ app.*.map.json appimagetool* *.AppDir +*.AppImage diff --git a/lib/features/tickets/blocs/ticket_shipping_cubit.dart b/lib/features/tickets/blocs/ticket_shipping_cubit.dart index 0a08183..bbd6b1a 100644 --- a/lib/features/tickets/blocs/ticket_shipping_cubit.dart +++ b/lib/features/tickets/blocs/ticket_shipping_cubit.dart @@ -55,6 +55,44 @@ class TicketShippingCubit extends Cubit { } } + Future createQuickProvider({ + required String name, + required String address, + String city = '', + String zipCode = '', + String province = '', + }) async { + emit(state.copyWith(status: TicketShippingStatus.loading)); + try { + final newProvider = await _repository.createQuickRepairCenter( + name: name, + address: address, + city: city, + zipCode: zipCode, + province: province, + ); + + final updatedProviders = List.from(state.availableProviders) + ..add(newProvider); + + emit( + state.copyWith( + status: TicketShippingStatus.initial, + availableProviders: updatedProviders, + ), + ); + + selectProvider(newProvider.id!); + } catch (e) { + emit( + state.copyWith( + status: TicketShippingStatus.failure, + errorMessage: e.toString(), + ), + ); + } + } + void selectProvider(String providerId) { final ProviderModel provider = state.availableProviders.firstWhere( (p) => p.id == providerId, diff --git a/lib/features/tickets/data/tickets_shipping_repository.dart b/lib/features/tickets/data/tickets_shipping_repository.dart index 02be140..44e7eb3 100644 --- a/lib/features/tickets/data/tickets_shipping_repository.dart +++ b/lib/features/tickets/data/tickets_shipping_repository.dart @@ -1,9 +1,11 @@ import 'dart:typed_data'; import 'package:flux/core/blocs/session/session_cubit.dart'; +import 'package:flux/core/enums_and_consts/consts.dart'; import 'package:flux/features/attachments/blocs/attachments_bloc.dart'; import 'package:flux/features/attachments/data/attachments_repository.dart'; import 'package:flux/features/tickets/models/shipping_document_model.dart'; +import 'package:flux/features/master_data/providers/models/provider_location_model.dart'; import 'package:flux/features/master_data/providers/models/provider_model.dart'; import 'package:flux/features/master_data/providers/models/provider_role.dart'; import 'package:flux/features/tickets/models/ticket_model.dart'; @@ -17,8 +19,8 @@ class TicketsShippingRepository { Future> fetchRepairCenters() async { try { final response = await _supabase - .from('provider') - .select('*, provider_locations (*)') + .from(Tables.providers) + .select('*, ${Tables.providerLocations} (*)') .eq('is_active', true) .order('name'); @@ -35,13 +37,63 @@ class TicketsShippingRepository { } } + Future createQuickRepairCenter({ + required String name, + required String address, + String city = '', + String zipCode = '', + String province = '', + }) async { + try { + final provider = ProviderModel( + companyId: _companyId, + name: name, + isActive: true, + roles: const [ProviderRole.repairCenter], + ); + + final savedRow = await _supabase + .from(Tables.providers) + .insert(provider.toMap()) + .select() + .single(); + + final savedProvider = ProviderModel.fromMap(savedRow); + + final location = ProviderLocationModel( + providerId: savedProvider.id!, + companyId: _companyId, + name: 'Sede Principale', + address: address, + city: city, + zipCode: zipCode, + province: province, + isMain: true, + ); + + final locationRow = await _supabase + .from(Tables.providerLocations) + .insert(location.toMap()) + .select() + .single(); + + final savedLocation = ProviderLocationModel.fromMap(locationRow); + + return savedProvider.copyWith( + locations: [savedLocation], + ); + } catch (e) { + throw ('Errore creazione centro di riparazione rapido: $e'); + } + } + Future> fetchShipmentDocumentsForTicket( String ticketId, ) async { try { final response = await _supabase - .from('shipping_documents') - .select('*, attachments (*)') + .from(Tables.shippingDocuments) + .select('*, ${Tables.attachments} (*)') .contains('ticket_ids', [ticketId]); return (response as List) @@ -57,8 +109,8 @@ class TicketsShippingRepository { Future> fetchCompanyShipmentDocuments() async { try { final response = await _supabase - .from('shipping_documents') - .select('*, attachments (*)') + .from(Tables.shippingDocuments) + .select('*, ${Tables.attachments} (*)') .eq('company_id', _companyId); return (response as List) @@ -76,8 +128,8 @@ class TicketsShippingRepository { ) async { try { final response = await _supabase - .from('shipping_documents') - .select('*, attachments (*)') + .from(Tables.shippingDocuments) + .select('*, ${Tables.attachments} (*)') .eq('id', documentId) .single(); @@ -99,7 +151,7 @@ class TicketsShippingRepository { // 1. Inseriamo prima il Documento di Trasporto (DDT) su Postgres // Il modello iniziale non ha ancora gli allegati popolati, quindi passiamo il toMap standard final savedDocument = await _supabase - .from('shipping_documents') + .from(Tables.shippingDocuments) .insert(document.toMap()) .select('id') .single(); @@ -123,7 +175,7 @@ class TicketsShippingRepository { // 4. Aggiorniamo lo stato di TUTTI i ticket inclusi nel DDT e li colleghiamo all'ID del DDT await _supabase - .from('ticket') + .from(Tables.tickets) .update({ 'ticket_status': newTicketStatus.value, 'shipping_document_id': documentId, diff --git a/lib/features/tickets/ui/widgets/quick_provider_dialog.dart b/lib/features/tickets/ui/widgets/quick_provider_dialog.dart new file mode 100644 index 0000000..3193ae9 --- /dev/null +++ b/lib/features/tickets/ui/widgets/quick_provider_dialog.dart @@ -0,0 +1,167 @@ +import 'package:flutter/material.dart'; + +typedef QuickProviderData = ({ + String name, + String address, + String city, + String zipCode, + String province, +}); + +class QuickProviderDialog extends StatefulWidget { + const QuickProviderDialog({super.key}); + + static Future show(BuildContext context) { + return showDialog( + context: context, + builder: (context) => const QuickProviderDialog(), + ); + } + + @override + State createState() => _QuickProviderDialogState(); +} + +class _QuickProviderDialogState extends State { + final _formKey = GlobalKey(); + final _nameController = TextEditingController(); + final _addressController = TextEditingController(); + final _cityController = TextEditingController(); + final _zipController = TextEditingController(); + final _provinceController = TextEditingController(); + + @override + void dispose() { + _nameController.dispose(); + _addressController.dispose(); + _cityController.dispose(); + _zipController.dispose(); + _provinceController.dispose(); + super.dispose(); + } + + void _submit() { + if (_formKey.currentState!.validate()) { + Navigator.of(context).pop(( + name: _nameController.text.trim(), + address: _addressController.text.trim(), + city: _cityController.text.trim(), + zipCode: _zipController.text.trim(), + province: _provinceController.text.trim().toUpperCase(), + )); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + title: Row( + children: [ + CircleAvatar( + backgroundColor: theme.colorScheme.primaryContainer, + child: Icon(Icons.domain_add, color: theme.colorScheme.primary), + ), + const SizedBox(width: 12), + const Expanded( + child: Text( + 'Nuovo Centro Riparazioni', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + ], + ), + content: SingleChildScrollView( + child: Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextFormField( + controller: _nameController, + autofocus: true, + decoration: const InputDecoration( + labelText: 'Nome Laboratorio *', + hintText: 'Es: riparazioni.it / Laboratorio Centrale', + prefixIcon: Icon(Icons.storefront), + ), + validator: (v) => v == null || v.trim().isEmpty + ? 'Campo obbligatorio' + : null, + ), + const SizedBox(height: 16), + TextFormField( + controller: _addressController, + decoration: const InputDecoration( + labelText: 'Indirizzo Spedizione *', + hintText: 'Es: Via Roma 15', + prefixIcon: Icon(Icons.location_on), + ), + validator: (v) => v == null || v.trim().isEmpty + ? 'Campo obbligatorio' + : null, + ), + const SizedBox(height: 16), + Row( + children: [ + Expanded( + flex: 2, + child: TextFormField( + controller: _cityController, + decoration: const InputDecoration( + labelText: 'Città', + hintText: 'Es: Milano', + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: TextFormField( + controller: _zipController, + decoration: const InputDecoration( + labelText: 'CAP', + hintText: '20100', + ), + keyboardType: TextInputType.number, + ), + ), + const SizedBox(width: 8), + Expanded( + child: TextFormField( + controller: _provinceController, + decoration: const InputDecoration( + labelText: 'Prov.', + hintText: 'MI', + ), + textCapitalization: TextCapitalization.characters, + maxLength: 2, + buildCounter: ( + _, { + required currentLength, + required isFocused, + maxLength, + }) => null, + ), + ), + ], + ), + ], + ), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Annulla'), + ), + FilledButton.icon( + onPressed: _submit, + icon: const Icon(Icons.check), + label: const Text('Salva e Seleziona'), + ), + ], + ); + } +} diff --git a/lib/features/tickets/ui/widgets/ticket_list_card.dart b/lib/features/tickets/ui/widgets/ticket_list_card.dart index 5baaac9..d2c4586 100644 --- a/lib/features/tickets/ui/widgets/ticket_list_card.dart +++ b/lib/features/tickets/ui/widgets/ticket_list_card.dart @@ -160,32 +160,39 @@ class TicketListCard extends StatelessWidget { // CASO 2: Più allegati. Mostriamo una BottomSheet fulminea per far scegliere all'utente. showModalBottomSheet( context: context, - builder: (context) => ListView.builder( - shrinkWrap: true, - itemCount: attachments.length, - itemBuilder: (context, index) { - final file = attachments[index]; - return ListTile( - leading: Icon( - file.extension == 'pdf' - ? Icons.picture_as_pdf - : Icons.image, - ), - title: Text(file.name), - subtitle: Text( - '${(file.fileSize / 1024).toStringAsFixed(1)} KB', - ), - onTap: () { - Navigator.pop( - context, - ); // Chiude la scelta - _openFile( - context: context, - file: file, - ); // Apre il viewer - }, - ); - }, + builder: (context) => Material( + color: Theme.of(context).colorScheme.surface, + borderRadius: const BorderRadius.vertical( + top: Radius.circular(28), + ), + clipBehavior: Clip.antiAlias, + child: ListView.builder( + shrinkWrap: true, + itemCount: attachments.length, + itemBuilder: (context, index) { + final file = attachments[index]; + return ListTile( + leading: Icon( + file.extension == 'pdf' + ? Icons.picture_as_pdf + : Icons.image, + ), + title: Text(file.name), + subtitle: Text( + '${(file.fileSize / 1024).toStringAsFixed(1)} KB', + ), + onTap: () { + Navigator.pop( + context, + ); // Chiude la scelta + _openFile( + context: context, + file: file, + ); // Apre il viewer + }, + ); + }, + ), ), ); } diff --git a/lib/features/tickets/ui/widgets/ticket_shipping_modal.dart b/lib/features/tickets/ui/widgets/ticket_shipping_modal.dart index 228f763..a2596bc 100644 --- a/lib/features/tickets/ui/widgets/ticket_shipping_modal.dart +++ b/lib/features/tickets/ui/widgets/ticket_shipping_modal.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flux/features/tickets/blocs/ticket_shipping_cubit.dart'; import 'package:flux/features/tickets/models/ticket_model.dart'; +import 'package:flux/features/tickets/ui/widgets/quick_provider_dialog.dart'; class TicketShippingModal extends StatefulWidget { final List ticketIds; @@ -24,18 +25,18 @@ class _TicketShippingModalState extends State { @override Widget build(BuildContext context) { - return Container( - padding: EdgeInsets.only( - bottom: MediaQuery.of(context).viewInsets.bottom + 24, - top: 24, - left: 24, - right: 24, - ), - decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surface, - borderRadius: const BorderRadius.vertical(top: Radius.circular(28)), - ), - child: BlocConsumer( + return Material( + color: Theme.of(context).colorScheme.surface, + borderRadius: const BorderRadius.vertical(top: Radius.circular(28)), + clipBehavior: Clip.antiAlias, + child: Padding( + padding: EdgeInsets.only( + bottom: MediaQuery.of(context).viewInsets.bottom + 24, + top: 24, + left: 24, + right: 24, + ), + child: BlocConsumer( listener: (context, state) { if (state.status == TicketShippingStatus.success) { Navigator.pop(context, true); @@ -129,11 +130,12 @@ class _TicketShippingModalState extends State { ), ), ), - ], + ], + ), ), - ), - ); - }, + ); + }, + ), ), ); } @@ -170,21 +172,49 @@ class _TicketShippingModalState extends State { BuildContext context, TicketShippingState state, ) { - return DropdownButtonFormField( - initialValue: state.document.providerId.isEmpty - ? null - : state.document.providerId, - decoration: const InputDecoration( - labelText: "Seleziona Centro Riparazioni", - prefixIcon: Icon(Icons.store), - ), - items: state.availableProviders - .map((p) => DropdownMenuItem(value: p.id, child: Text(p.name))) - .toList(), - onChanged: (val) => val != null - ? context.read().selectProvider(val) - : null, - validator: (v) => v == null || v.isEmpty ? 'Campo obbligatorio' : null, + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: DropdownButtonFormField( + key: ValueKey('provider_${state.document.providerId}'), + initialValue: state.document.providerId.isEmpty + ? null + : state.document.providerId, + decoration: const InputDecoration( + labelText: "Seleziona Centro Riparazioni", + prefixIcon: Icon(Icons.store), + ), + items: state.availableProviders + .map((p) => DropdownMenuItem(value: p.id, child: Text(p.name))) + .toList(), + onChanged: (val) => val != null + ? context.read().selectProvider(val) + : null, + validator: (v) => v == null || v.isEmpty ? 'Campo obbligatorio' : null, + ), + ), + const SizedBox(width: 8), + Padding( + padding: const EdgeInsets.only(top: 4.0), + child: IconButton.filledTonal( + icon: const Icon(Icons.add), + tooltip: "Aggiungi nuovo centro riparazioni", + onPressed: () async { + final data = await QuickProviderDialog.show(context); + if (data != null && context.mounted) { + context.read().createQuickProvider( + name: data.name, + address: data.address, + city: data.city, + zipCode: data.zipCode, + province: data.province, + ); + } + }, + ), + ), + ], ); } @@ -193,6 +223,7 @@ class _TicketShippingModalState extends State { TicketShippingState state, ) { return DropdownButtonFormField( + key: ValueKey('location_${state.document.destinationLocationId}'), initialValue: state.document.destinationLocationId.isEmpty ? null : state.document.destinationLocationId, diff --git a/lib/features/tickets/utils/ticket_shipping_pdf_service.dart b/lib/features/tickets/utils/ticket_shipping_pdf_service.dart index 893aa4c..10bea5e 100644 --- a/lib/features/tickets/utils/ticket_shipping_pdf_service.dart +++ b/lib/features/tickets/utils/ticket_shipping_pdf_service.dart @@ -126,7 +126,7 @@ class TicketShippingPdfService { build: (pw.Context context) { return [ pw.TableHelper.fromTextArray( - headers: ['Rif. Ticket', 'Modello', 'Difetto / Note', 'Q.tà'], + headers: ['Prodotto', 'Difetto', 'Q.tà'], headerStyle: pw.TextStyle( fontWeight: pw.FontWeight.bold, color: PdfColors.white, @@ -134,12 +134,24 @@ class TicketShippingPdfService { headerDecoration: const pw.BoxDecoration( color: PdfColors.blueGrey800, ), - cellAlignment: pw.Alignment.centerLeft, + columnWidths: { + 0: const pw.FlexColumnWidth(3), + 1: const pw.FlexColumnWidth(4), + 2: const pw.FixedColumnWidth(45), + }, + cellAlignments: { + 0: pw.Alignment.centerLeft, + 1: pw.Alignment.centerLeft, + 2: pw.Alignment.center, + }, + headerAlignments: { + 0: pw.Alignment.centerLeft, + 1: pw.Alignment.centerLeft, + 2: pw.Alignment.center, + }, data: tickets.map((t) { return [ - t.id?.substring(0, 8).toUpperCase() ?? - '-', // Magari hai un ID progressivo migliore - t.targetModelName ?? 'Sconosciuto', + '${t.targetModelName ?? 'Modello sconosciuto'} - Rif. Ticket ${t.referenceId ?? 'Sconosciuto'}', t.request, '1', // Tipicamente 1 per ogni ticket ];