Files
flux/lib/features/operations/ui/operation_form_screen.dart
T

767 lines
26 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/widgets/shared_forms/attachments_section.dart';
import 'package:flux/core/widgets/shared_forms/customer_section.dart';
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart';
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/ui/widgets/financing_qr_dialog.dart';
import 'package:flux/features/operations/ui/widgets/operation_details_section.dart';
class OperationFormScreen extends StatefulWidget {
final String? operationId;
final OperationModel? operation;
const OperationFormScreen({super.key, this.operationId, this.operation});
@override
State<OperationFormScreen> createState() => _OperationFormScreenState();
}
enum _UnsavedChangesAction { cancel, saveAndClose, discard }
class _OperationFormScreenState extends State<OperationFormScreen> {
final _formKey = GlobalKey<FormState>();
bool _isInitialized = false;
bool _isClosingIntent = false;
final _referenceController = TextEditingController();
final _notesController = TextEditingController();
@override
void initState() {
super.initState();
_referenceController.addListener(_onFieldChanged);
_notesController.addListener(_onFieldChanged);
// 1. Lanciamo l'inizializzazione sincrona/asincrona
context.read<OperationFormCubit>().initForm(
existingOperation: widget.operation,
operationId: widget.operationId,
);
// 2. Lettura immediata dello stato (come fatto per il customer!)
final currentState = context.read<OperationFormCubit>().state;
if (currentState.status == OperationFormStatus.ready && !_isInitialized) {
_syncTextControllers(currentState.operation);
}
}
@override
void dispose() {
_referenceController.removeListener(_onFieldChanged);
_notesController.removeListener(_onFieldChanged);
_referenceController.dispose();
_notesController.dispose();
super.dispose();
}
void _onFieldChanged() {
if (!_isInitialized) return;
_flushControllersToCubit();
}
void _syncTextControllers(OperationModel model) {
if (_referenceController.text.isEmpty) {
_referenceController.text = model.reference;
}
if (_notesController.text.isEmpty) {
_notesController.text = model.note;
}
_isInitialized = true;
}
void _flushControllersToCubit() {
context.read<OperationFormCubit>().updateFields(
reference: _referenceController.text,
note: _notesController.text,
);
}
void _saveOperation({
required OperationStatus targetStatus,
required bool isClosingIntent,
}) async {
if (!_formKey.currentState!.validate()) return;
if (isClosingIntent) {
final details = context.read<OperationFormCubit>().state.operation.details;
if (details.isEmpty) {
final shouldProceed = await _showEmptyDetailsWarningDialog(context);
if (shouldProceed != true || !mounted) return;
}
}
_isClosingIntent = isClosingIntent;
_flushControllersToCubit();
context.read<OperationFormCubit>().updateFields(status: targetStatus);
context.read<OperationFormCubit>().saveOperation(
targetStatus: targetStatus,
);
}
Future<bool?> _showEmptyDetailsWarningDialog(BuildContext context) {
return showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Row(
children: [
Icon(Icons.warning_amber_rounded, color: Colors.orange),
SizedBox(width: 8),
Text('Dettagli operazione vuoti'),
],
),
content: const Text(
'Non hai inserito alcun dettaglio per questa operazione.\n\nVuoi procedere comunque a salvare e uscire, oppure annullare per aggiungerli?',
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('Annulla'),
),
ElevatedButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('Salva e chiudi comunque'),
),
],
);
},
);
}
Future<_UnsavedChangesAction?> _showUnsavedChangesDialog(
BuildContext context,
) {
return showDialog<_UnsavedChangesAction>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Row(
children: [
Icon(Icons.warning_amber_rounded, color: Colors.orange),
SizedBox(width: 8),
Text('Modifiche non salvate'),
],
),
content: const Text(
'Ci sono modifiche non salvate. Cosa desideri fare?',
),
actions: [
TextButton(
onPressed: () =>
Navigator.of(dialogContext).pop(_UnsavedChangesAction.cancel),
child: const Text('Annulla'),
),
TextButton(
style: TextButton.styleFrom(foregroundColor: Colors.red),
onPressed: () => Navigator.of(
dialogContext,
).pop(_UnsavedChangesAction.discard),
child: const Text('Chiudi senza salvare'),
),
ElevatedButton(
onPressed: () => Navigator.of(
dialogContext,
).pop(_UnsavedChangesAction.saveAndClose),
child: const Text('Salva e chiudi'),
),
],
);
},
);
}
Color _getStatusColor(OperationStatus status) {
switch (status) {
case OperationStatus.success:
return Colors.green;
case OperationStatus.waitingForAction:
return Colors.orange;
case OperationStatus.waitingForSupport:
return Colors.blue;
case OperationStatus.failure:
return Colors.red;
case OperationStatus.draft:
return Colors.grey;
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return BlocListener<OperationDetailsListCubit, OperationDetailsListState>(
listener: (listContext, listState) {
if (listState.status == OperationDetailsListStatus.ready ||
listState.status == OperationDetailsListStatus.updated) {
context.read<OperationFormCubit>().updateOperationDetailsList(
listState.details,
);
}
},
child: BlocConsumer<OperationFormCubit, OperationFormState>(
listener: (formContext, formState) {
if (formState.status == OperationFormStatus.ready &&
!_isInitialized) {
_syncTextControllers(formState.operation);
}
if (formState.operation.id != null &&
formState.operation.id!.isNotEmpty) {
final attachmentsBloc = formContext.read<AttachmentsBloc>();
if (attachmentsBloc.state.parentId != formState.operation.id) {
attachmentsBloc.add(
ParentEntitySavedEvent(formState.operation.id!),
);
}
}
if ((formState.status == OperationFormStatus.success &&
_isClosingIntent) ||
formState.status == OperationFormStatus.discarded) {
Navigator.of(formContext).pop();
} else if (formState.status == OperationFormStatus.failure) {
ScaffoldMessenger.of(formContext).showSnackBar(
SnackBar(
content: Text(
'Si è verificato un errore. ${formState.errorMessage}',
),
backgroundColor: Colors.red,
),
);
}
},
builder: (formContext, formState) {
if (!_isInitialized &&
(widget.operationId != null || widget.operation != null) &&
formState.status == OperationFormStatus.loading) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
return PopScope(
canPop: !formState.hasUnsavedChanges,
onPopInvokedWithResult: (didPop, result) async {
if (didPop) return;
final action = await _showUnsavedChangesDialog(formContext);
if (!formContext.mounted ||
action == null ||
action == _UnsavedChangesAction.cancel) {
return;
}
if (action == _UnsavedChangesAction.saveAndClose) {
_saveOperation(
targetStatus: formState.operation.status,
isClosingIntent: true,
);
} else if (action == _UnsavedChangesAction.discard) {
formContext.read<OperationFormCubit>().discardAndExit();
}
},
child: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
Navigator.maybePop(formContext);
},
),
title: Text(
'Addetto selezionato: ${formState.operation.staffDisplayName}',
overflow: TextOverflow.ellipsis,
),
actions: [
if (formState.hasUnsavedChanges)
Padding(
padding: const EdgeInsets.only(right: 4.0),
child: Tooltip(
message: 'Modifiche non salvate',
child: Container(
width: 10,
height: 10,
decoration: const BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
),
),
),
IconButton(
icon: const Icon(Icons.save),
tooltip: formState.hasUnsavedChanges
? 'Salva modifiche'
: 'Nessuna modifica da salvare',
onPressed:
formState.hasUnsavedChanges &&
formState.status != OperationFormStatus.saving
? () => _saveOperation(
targetStatus: formState.operation.status,
isClosingIntent: false,
)
: null,
),
IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.red),
tooltip: 'Elimina pratica',
onPressed:
formState.status != OperationFormStatus.saving
? () => _showDeleteConfirmationDialog(formContext)
: null,
),
Padding(
padding: const EdgeInsets.only(right: 10),
child: ActionChip(
avatar: Icon(
formState.operation.status == OperationStatus.success
? Icons.check_circle
: Icons.error_outline,
color: Colors.white,
size: 14,
),
label: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
formState.operation.status.displayName,
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
const SizedBox(width: 2),
const Icon(
Icons.arrow_drop_down,
color: Colors.white,
size: 16,
),
],
),
backgroundColor: _getStatusColor(
formState.operation.status,
),
side: BorderSide.none,
onPressed: () => _showStatusBottomSheet(formContext),
),
),
],
),
body: Form(
key: _formKey,
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: LayoutBuilder(
builder: (context, constraints) {
final isUltraWide = constraints.maxWidth > 1400;
final isDesktop = constraints.maxWidth > 900;
return SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Center(
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: isUltraWide
? 1600
: isDesktop
? 1200
: 800,
),
child: _buildResponsiveLayout(
isUltraWide,
isDesktop,
formState,
),
),
),
);
},
),
),
),
bottomNavigationBar: SafeArea(
child: Container(
padding: const EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: theme.scaffoldBackgroundColor,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 10,
offset: const Offset(0, -3),
),
],
),
child: Row(
children: [
Expanded(
flex: 1,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: _getStatusColor(
formState.operation.status,
),
foregroundColor: Colors.white,
),
onPressed: () => _saveOperation(
targetStatus: formState.operation.status,
isClosingIntent: true,
),
child: formState.status == OperationFormStatus.saving
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2,
),
)
: const Text('Salva e chiudi'),
),
),
],
),
),
),
),
);
},
),
);
}
Future<void> _showDeleteConfirmationDialog(BuildContext context) async {
final cubit = context.read<OperationFormCubit>();
final confirm = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Row(
children: [
Icon(Icons.warning_amber_rounded, color: Colors.red),
SizedBox(width: 8),
Text('Conferma eliminazione'),
],
),
content: const Text(
'Sei sicuro di voler eliminare definitivamente questa pratica?\nL\'azione è irreversibile.',
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('Annulla'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('Elimina Pratica'),
),
],
);
},
);
if (confirm == true && context.mounted) {
cubit.deleteCurrentOperation();
}
}
void _showStatusBottomSheet(BuildContext context) {
final cubit = context.read<OperationFormCubit>();
final currentStatus = cubit.state.operation.status;
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (modalContext) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Seleziona Stato Pratica',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(modalContext),
),
],
),
const Divider(),
...OperationStatus.values.map((status) {
final isSelected = status == currentStatus;
final color = _getStatusColor(status);
return ListTile(
leading: Icon(
status == OperationStatus.success
? Icons.check_circle
: Icons.error_outline,
color: color,
),
title: Text(
status.displayName,
style: TextStyle(
fontWeight: isSelected
? FontWeight.bold
: FontWeight.normal,
color: isSelected ? color : null,
),
),
trailing: isSelected
? Icon(Icons.check_circle, color: color)
: null,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
tileColor: isSelected ? color.withValues(alpha: 0.1) : null,
onTap: () {
cubit.updateFields(status: status);
Navigator.pop(modalContext);
},
);
}),
],
),
);
},
);
}
Widget _buildResponsiveLayout(
bool isUltraWide,
bool isDesktop,
OperationFormState state,
) {
if (isUltraWide) {
return Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: _cardAnagrafica(state)),
const SizedBox(width: 18),
Expanded(child: _cardNote(state)),
const SizedBox(width: 18),
Expanded(child: _cardDettagli(state)),
],
),
_cardAllegati(state),
],
);
} else if (isDesktop) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
children: [_cardAnagrafica(state), _cardAllegati(state)],
),
),
const SizedBox(width: 18),
Expanded(
child: Column(children: [_cardNote(state), _cardDettagli(state)]),
),
],
);
} else {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_cardAnagrafica(state),
_cardDettagli(state),
_cardNote(state),
_cardAllegati(state),
],
);
}
}
// --- LE CARD MODULARIZZATE E COLORATE ---
Widget _cardDettagli(OperationFormState state) {
return _buildCard(
title: 'Dettagli Servizi',
icon: Icons.design_services,
themeColor: Colors.deepOrange,
children: [const OperationDetailsSection()],
);
}
Widget _cardAnagrafica(OperationFormState state) {
return _buildCard(
title: 'Cliente e Riferimento',
icon: Icons.person,
themeColor: Colors.indigo,
children: [
SharedCustomerSection(
customer: state.operation.customer,
onCustomerSelected: (customer) =>
context.read<OperationFormCubit>().updateCustomer(customer),
),
const SizedBox(height: 16),
TextFormField(
controller: _referenceController,
decoration: const InputDecoration(
labelText: 'Riferimenti',
prefixIcon: Icon(Icons.tag),
),
),
],
);
}
Widget _cardNote(OperationFormState state) {
return _buildCard(
title: 'Note Interne',
icon: Icons.notes,
themeColor: Colors.teal,
headerTrailing: OutlinedButton.icon(
icon: const Icon(Icons.qr_code_2, size: 18),
label: const Text('Dati Finanziamento'),
style: OutlinedButton.styleFrom(
foregroundColor: Colors.teal,
side: const BorderSide(color: Colors.teal),
visualDensity: VisualDensity.compact,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
onPressed: _showFinancingQrDialog,
),
children: [
TextFormField(
controller: _notesController,
minLines: 14,
maxLines: 500,
decoration: InputDecoration(
hintText: 'Incolla seriali, ICCID, IBAN...',
alignLabelWithHint: true,
fillColor: Colors.teal.withValues(alpha: 0.05),
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
),
),
],
);
}
void _showFinancingQrDialog() {
showDialog(
context: context,
builder: (dialogCtx) => FinancingQrDialog(
onDataReceived: (formattedData) {
setState(() {
final existing = _notesController.text.trim();
if (existing.isEmpty) {
_notesController.text = formattedData;
} else {
_notesController.text = '$existing\n\n$formattedData';
}
});
_flushControllersToCubit();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Dati finanziamento inseriti nelle note!'),
backgroundColor: Colors.teal,
duration: Duration(seconds: 3),
),
);
},
),
);
}
Widget _cardAllegati(OperationFormState state) {
return _buildCard(
title: 'Allegati e Documenti',
icon: Icons.attach_file,
themeColor: Colors.deepPurple,
children: [
SharedAttachmentsSection(
parentType: AttachmentParentType.operation,
parentId: state.operation.id,
titleForUpload: state.operation.customer?.name ?? 'Nuova Pratica',
onEnsureEntitySaved: () async {
if (!_formKey.currentState!.validate()) return null;
_flushControllersToCubit();
final cubit = context.read<OperationFormCubit>();
await cubit.saveOperation(
targetStatus: state.operation.status,
);
return cubit.state.operation.id;
},
),
],
);
}
// --- WIDGET BASE PER LA CARD ---
Widget _buildCard({
required String title,
required IconData icon,
required Color themeColor,
required List<Widget> children,
Widget? headerTrailing,
}) {
return Card(
margin: const EdgeInsets.only(bottom: 24),
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(color: themeColor.withValues(alpha: 0.3), width: 1),
),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: themeColor.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, color: themeColor),
),
const SizedBox(width: 12),
Expanded(
child: Text(
title,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
color: themeColor,
),
),
),
?headerTrailing,
],
),
const Divider(height: 32),
...children,
],
),
),
);
}
}