import 'package:flutter/material.dart'; import '../../../app/app_services.dart'; import '../../../app/router/app_router.dart'; import '../../../core/utils/currency_formatter.dart'; import '../../../core/widgets/app_button.dart'; import '../../../core/widgets/empty_view.dart'; import '../../../core/widgets/error_view.dart'; import '../../../core/widgets/loading_view.dart'; import '../../../domain/entities/customer.dart'; import '../../../domain/entities/payment_method.dart'; import '../../../domain/entities/sale_payment.dart'; import '../../../domain/repositories/payment_methods_repository.dart'; import '../../../domain/repositories/sale_checkout_repository.dart'; enum _PaymentCategory { cash, pix, credit, debit } class _PaymentAllocation { const _PaymentAllocation({required this.method, required this.amountMinor}); final PaymentMethod method; final int amountMinor; bool get isCash => method.paymentType == '01'; } extension _PaymentCategoryPresentation on _PaymentCategory { String get label { switch (this) { case _PaymentCategory.cash: return 'Dinheiro'; case _PaymentCategory.pix: return 'PIX'; case _PaymentCategory.credit: return 'Cartão de Crédito'; case _PaymentCategory.debit: return 'Cartão de Débito'; } } IconData get icon { switch (this) { case _PaymentCategory.cash: return Icons.payments_outlined; case _PaymentCategory.pix: return Icons.qr_code_2_outlined; case _PaymentCategory.credit: return Icons.credit_card; case _PaymentCategory.debit: return Icons.credit_card_outlined; } } } class PaymentScreen extends StatefulWidget { const PaymentScreen({required this.services, super.key}); final AppServices services; @override State createState() => _PaymentScreenState(); } class _PaymentScreenState extends State { List _methods = []; bool _loading = true; String? _errorMessage; String? _checkoutError; String? _customerCpf; final List<_PaymentAllocation> _allocations = []; Customer? _customer; late final String _checkoutKey; bool _finalizing = false; @override void initState() { super.initState(); final userId = widget.services.authRepository.currentSession?.userId ?? 0; _checkoutKey = 'pdv-$userId-${DateTime.now().microsecondsSinceEpoch}'; _loadPaymentMethods(); } Future _loadPaymentMethods() async { setState(() { _loading = true; _errorMessage = null; }); try { final methods = await widget.services.paymentMethodsRepository.loadAvailable(); if (!mounted) return; setState(() { _methods = methods; _loading = false; }); } on PaymentMethodsException catch (error) { if (mounted) { setState(() { _errorMessage = error.message; _loading = false; }); } } catch (_) { if (mounted) { setState(() { _errorMessage = 'Não foi possível carregar formas de pagamento.'; _loading = false; }); } } } Future _includeCustomer() async { final customer = await Navigator.of(context) .pushNamed(AppRoutes.customerSearch); if (mounted && customer != null) setState(() => _customer = customer); } bool _canFinalize(int? total) => !_finalizing && total != null && _allocations.isNotEmpty && _allocatedMinorUnits == total && _allocations.every((allocation) => allocation.isCash); Future _requestCustomerCpf() async { final controller = TextEditingController(); String? errorMessage; final cpf = await showDialog( context: context, builder: (dialogContext) => StatefulBuilder( builder: (context, setDialogState) => AlertDialog( title: const Text('CPF/CNPJ para NFC-e'), content: TextField( controller: controller, autofocus: true, keyboardType: TextInputType.number, decoration: InputDecoration( labelText: 'CPF ou CNPJ', errorText: errorMessage, ), ), actions: [ TextButton( onPressed: () => Navigator.of(dialogContext).pop(), child: const Text('Cancelar'), ), FilledButton( onPressed: () { final digits = controller.text.replaceAll(RegExp(r'\D'), ''); if (digits.length != 11 && digits.length != 14) { setDialogState( () => errorMessage = 'Informe um CPF ou CNPJ válido.', ); return; } Navigator.of(dialogContext).pop(digits); }, child: const Text('Continuar'), ), ], ), ), ); controller.dispose(); return cpf; } Future _finalizeCashSale(int? total) async { if (!_canFinalize(total) || total == null) return; setState(() { _finalizing = true; _checkoutError = null; }); var cpf = _customerCpf; try { var completion = await widget.services.saleCheckoutRepository.finalizeCashSale( items: widget.services.cartRepository.items, payments: _allocations .map( (allocation) => SalePayment( conditionFormId: allocation.method.id, amountMinorUnits: allocation.amountMinor, paymentType: allocation.method.paymentType ?? '', ), ) .toList(growable: false), customer: _customer, customerCpf: cpf, checkoutKey: _checkoutKey, ); if (!mounted) return; await Navigator.of(context).pushReplacementNamed( AppRoutes.saleComplete, arguments: completion, ); } on SaleCheckoutException catch (error) { if (error.code == 'customer_cpf_required' && _customer == null) { cpf = await _requestCustomerCpf(); if (cpf != null && mounted) { setState(() => _customerCpf = cpf); setState(() => _finalizing = false); await _finalizeCashSale(total); return; } } if (mounted) setState(() => _checkoutError = error.message); } catch (_) { if (mounted) { setState(() { _checkoutError = 'Não foi possível concluir a venda no Odoo.'; }); } } finally { if (mounted && _finalizing) setState(() => _finalizing = false); } } _PaymentCategory? _categoryFor(PaymentMethod method) { switch (method.paymentType) { case '01': return _PaymentCategory.cash; case '17': case '20': case '23': return _PaymentCategory.pix; case '03': return _PaymentCategory.credit; case '04': return _PaymentCategory.debit; default: return null; } } List _methodsFor(_PaymentCategory category) => _methods .where((method) => _categoryFor(method) == category) .toList(growable: false); int get _allocatedMinorUnits => _allocations.fold( 0, (total, allocation) => total + allocation.amountMinor, ); Future _addPayment(_PaymentCategory category, int? total) async { if (total == null) return; final options = _methodsFor(category); if (options.isEmpty) return; final remaining = total - _allocatedMinorUnits; if (remaining <= 0) return; var selectedMethod = options.first; String? validationMessage; final amountController = TextEditingController( text: _formatAmountInput(remaining), ); final allocation = await showDialog<_PaymentAllocation>( context: context, builder: (dialogContext) => StatefulBuilder( builder: (context, setDialogState) => AlertDialog( title: Text('Adicionar ${category.label}'), content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (options.length > 1) DropdownButtonFormField( value: selectedMethod, decoration: const InputDecoration(labelText: 'Condição'), items: options .map( (method) => DropdownMenuItem( value: method, child: Text( method.name, overflow: TextOverflow.ellipsis, ), ), ) .toList(growable: false), onChanged: (method) { if (method != null) { setDialogState(() => selectedMethod = method); } }, ) else Text(selectedMethod.name), const SizedBox(height: 12), TextField( controller: amountController, autofocus: true, keyboardType: const TextInputType.numberWithOptions(decimal: true), decoration: InputDecoration( labelText: 'Valor desta parcela', prefixText: 'R\$ ', hintText: '0,00', errorText: validationMessage, ), ), const SizedBox(height: 8), Text( 'Saldo disponível: ${CurrencyFormatter.formatBrl(remaining)}'), ], ), actions: [ TextButton( onPressed: () => Navigator.of(dialogContext).pop(), child: const Text('Cancelar'), ), FilledButton( onPressed: () { final amount = _parseAmountMinorUnits(amountController.text); if (amount == null || amount <= 0) { setDialogState(() { validationMessage = 'Informe um valor válido.'; }); return; } if (amount > remaining) { setDialogState(() { validationMessage = 'O valor excede o saldo disponível.'; }); return; } Navigator.of(dialogContext).pop( _PaymentAllocation( method: selectedMethod, amountMinor: amount, ), ); }, child: const Text('Adicionar'), ), ], ), ), ); amountController.dispose(); if (mounted && allocation != null) { setState(() => _allocations.add(allocation)); } } static String _formatAmountInput(int amountMinor) { final whole = amountMinor ~/ 100; final cents = (amountMinor % 100).toString().padLeft(2, '0'); return '$whole,$cents'; } static int? _parseAmountMinorUnits(String input) { var value = input.trim().replaceAll('R\$', '').replaceAll(' ', ''); if (value.isEmpty) return null; final commaIndex = value.lastIndexOf(','); final dotIndex = value.lastIndexOf('.'); final decimalIndex = commaIndex > dotIndex ? commaIndex : dotIndex; String whole; String fraction; if (decimalIndex < 0) { whole = value; fraction = ''; } else { whole = value.substring(0, decimalIndex).replaceAll(RegExp(r'[.,]'), ''); fraction = value.substring(decimalIndex + 1); if (fraction.length > 2 || fraction.isEmpty) return null; } if (whole.isEmpty) whole = '0'; if (!RegExp(r'^\d+$').hasMatch(whole) || (fraction.isNotEmpty && !RegExp(r'^\d+$').hasMatch(fraction))) { return null; } final cents = fraction.isEmpty ? 0 : int.parse(fraction.padRight(2, '0')); return int.parse(whole) * 100 + cents; } Widget _buildPaymentCategories(int? total) { return GridView.count( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10, childAspectRatio: 1.55, children: _PaymentCategory.values.map((category) { final options = _methodsFor(category); final colorScheme = Theme.of(context).colorScheme; return FilledButton.tonal( key: Key('payment-category-${category.name}'), onPressed: options.isEmpty || total == null || _allocatedMinorUnits >= total ? null : () => _addPayment(category, total), style: FilledButton.styleFrom( minimumSize: const Size.fromHeight(92), padding: const EdgeInsets.all(8), backgroundColor: colorScheme.surfaceVariant, ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(category.icon, size: 30), const SizedBox(height: 6), Text(category.label, textAlign: TextAlign.center), ], ), ); }).toList(growable: false), ); } Widget _buildAllocations(int? total) { if (_allocations.isEmpty) return const SizedBox.shrink(); final cashReceived = _allocations .where((allocation) => allocation.isCash) .fold(0, (sum, allocation) => sum + allocation.amountMinor); final awaitingTerminal = _allocations .where((allocation) => !allocation.isCash) .fold(0, (sum, allocation) => sum + allocation.amountMinor); final remaining = total == null ? null : total - _allocatedMinorUnits; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const SizedBox(height: 16), Text('Pagamentos lançados', style: Theme.of(context).textTheme.titleMedium), if (cashReceived > 0) Padding( padding: const EdgeInsets.only(top: 8), child: Text( 'Dinheiro recebido: ${CurrencyFormatter.formatBrl(cashReceived)}', ), ), if (awaitingTerminal > 0) Padding( padding: const EdgeInsets.only(top: 4), child: Text( 'Aguardando API do POS: ' '${CurrencyFormatter.formatBrl(awaitingTerminal)}', ), ), if (remaining != null) Padding( padding: const EdgeInsets.only(top: 4, bottom: 4), child: Text( 'Saldo a distribuir: ${CurrencyFormatter.formatBrl(remaining)}', style: Theme.of(context).textTheme.titleSmall, ), ), ..._allocations.asMap().entries.map((entry) { final index = entry.key; final allocation = entry.value; return Card( child: ListTile( title: Text(allocation.method.name), subtitle: Text( allocation.isCash ? 'Recebido' : 'Pendente de confirmação POS', ), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ Text(CurrencyFormatter.formatBrl(allocation.amountMinor)), IconButton( tooltip: 'Remover pagamento', icon: const Icon(Icons.delete_outline), onPressed: () => setState(() => _allocations.removeAt(index)), ), ], ), ), ); }), ], ); } @override Widget build(BuildContext context) { final items = widget.services.cartRepository.items; final total = widget.services.cartRepository.totalMinorUnits; return PopScope( canPop: !_finalizing, child: Stack( fit: StackFit.expand, children: [ Scaffold( appBar: AppBar(title: const Text('Pagamento')), body: SafeArea( child: Column( children: [ Expanded( child: ListView( padding: const EdgeInsets.all(16), children: [ Card( child: Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( 'Total da venda (prévia)', style: Theme.of(context).textTheme.bodyMedium, ), const SizedBox(height: 4), Text( total == null ? 'Total indisponível' : CurrencyFormatter.formatBrl(total), style: Theme.of(context) .textTheme .headlineSmall ?.copyWith(fontWeight: FontWeight.bold), ), const SizedBox(height: 12), Row( children: [ Expanded( child: Text( _customer?.name ?? 'Consumidor não identificado', maxLines: 2, overflow: TextOverflow.ellipsis, style: Theme.of(context) .textTheme .titleSmall, ), ), TextButton.icon( onPressed: _includeCustomer, icon: const Icon(Icons.person_add_alt_1), label: Text( _customer == null ? 'Incluir cliente' : 'Alterar cliente', ), ), ], ), if (_customer?.documentMasked.isNotEmpty == true) Align( alignment: Alignment.centerLeft, child: Text( _customer!.documentMasked, style: Theme.of(context).textTheme.bodySmall, ), ), ], ), ), ), const SizedBox(height: 12), Text( 'Formas de pagamento disponíveis', style: Theme.of(context).textTheme.titleMedium, ), const SizedBox(height: 8), if (_loading) const LoadingView(message: 'Carregando pagamentos...') else if (_errorMessage != null) ErrorView( message: _errorMessage!, onRetry: _loadPaymentMethods, ) else if (_methods.isEmpty) const EmptyView( title: 'Nenhuma forma de pagamento', message: 'O servidor não retornou formas disponíveis.', icon: Icons.payments_outlined, ) else _buildPaymentCategories(total), _buildAllocations(total), if (_checkoutError != null) Padding( padding: const EdgeInsets.only(top: 12), child: Text( _checkoutError!, style: TextStyle( color: Theme.of(context).colorScheme.error, ), ), ), if (_methods.isNotEmpty && !_loading && _errorMessage == null) Padding( padding: const EdgeInsets.only(top: 8), child: Text( 'Por enquanto, a finalização aceita somente dinheiro. ' 'PIX e cartões aguardam confirmação da API do POS.', style: Theme.of(context).textTheme.bodySmall, textAlign: TextAlign.center, ), ), ], ), ), if (items.isEmpty) Padding( padding: const EdgeInsets.all(16), child: AppButton( label: 'Voltar para venda', icon: Icons.storefront_outlined, onPressed: () => Navigator.of(context).popUntil( (route) => route.settings.name == AppRoutes.sale, ), ), ) else Padding( padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), child: AppButton( label: _finalizing ? 'Finalizando...' : 'Finalizar venda', icon: Icons.check_circle_outline, onPressed: _canFinalize(total) ? () => _finalizeCashSale(total) : null, ), ), ], ), ), ), if (_finalizing) ...[ const ModalBarrier( dismissible: false, color: Color(0x99000000), ), Center( child: Card( margin: const EdgeInsets.all(28), child: Padding( padding: const EdgeInsets.symmetric( horizontal: 32, vertical: 28, ), child: Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox.square( dimension: 52, child: CircularProgressIndicator(strokeWidth: 5), ), const SizedBox(height: 20), Text( 'Finalizando a venda', textAlign: TextAlign.center, style: Theme.of(context).textTheme.titleLarge, ), const SizedBox(height: 8), Text( 'Aguardando o retorno do Odoo e da SEFAZ. ' 'Não feche o aplicativo.', textAlign: TextAlign.center, style: Theme.of(context).textTheme.bodyMedium, ), ], ), ), ), ), ], ], ), ); } }