181186 - Criar PDV Android para rodar em maquinas P.O.S.

This commit is contained in:
felipe.franca committed 2026-11-17 17:43:00 -03:00
commit c9983cbad5
204 files changed
+11453

No files matched your search

@@ -0,0 +1,210 @@
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 '../../../domain/entities/cart_item.dart';
class CartScreen extends StatelessWidget {
const CartScreen({required this.services, super.key});
final AppServices services;
Future<void> _confirmClear(BuildContext context) async {
final shouldClear = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Limpar carrinho?'),
content: const Text('Todos os produtos serão removidos do carrinho.'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancelar'),
),
FilledButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Limpar'),
),
],
),
);
if (shouldClear == true) services.cartRepository.clear();
}
Widget _buildCartItem(BuildContext context, CartItem item) {
final repository = services.cartRepository;
return Card(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
item.product.name,
style: Theme.of(context).textTheme.titleMedium,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Text(
'Código ${item.product.code} · Grade ${item.product.grade}',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Unitário: ${CurrencyFormatter.formatBrl(item.product.priceMinorUnits)}',
),
Text(
'Subtotal: ${CurrencyFormatter.formatBrl(item.subtotalMinorUnits)}',
style: const TextStyle(fontWeight: FontWeight.w600),
),
],
),
),
IconButton(
key: Key('decrease-${item.product.cartKey}'),
tooltip: 'Diminuir quantidade',
onPressed: item.quantity <= 1
? null
: () => repository.decreaseQuantity(item.product),
icon: const Icon(Icons.remove_circle_outline),
),
Text(
'${item.quantity}',
key: Key('quantity-${item.product.cartKey}'),
style: Theme.of(context).textTheme.titleMedium,
),
IconButton(
key: Key('increase-${item.product.cartKey}'),
tooltip: 'Aumentar quantidade',
onPressed: () => repository.increaseQuantity(item.product),
icon: const Icon(Icons.add_circle_outline),
),
IconButton(
key: Key('remove-${item.product.cartKey}'),
tooltip: 'Remover produto',
onPressed: () => repository.removeProduct(item.product),
icon: Icon(
Icons.delete_outline,
color: Theme.of(context).colorScheme.error,
),
),
],
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Carrinho'),
actions: [
AnimatedBuilder(
animation: services.cartRepository,
builder: (context, _) => IconButton(
key: const Key('clear-cart-button'),
tooltip: 'Limpar carrinho',
onPressed: services.cartRepository.itemCount == 0
? null
: () => _confirmClear(context),
icon: const Icon(Icons.delete_sweep_outlined),
),
),
],
),
body: AnimatedBuilder(
animation: services.cartRepository,
builder: (context, _) {
final items = services.cartRepository.items;
if (items.isEmpty) {
return Column(
children: [
const Expanded(
child: EmptyView(
title: 'Carrinho vazio',
message: 'Adicione produtos na tela de venda.',
icon: Icons.shopping_cart_outlined,
),
),
Padding(
padding: const EdgeInsets.all(16),
child: AppButton(
label: 'Voltar para venda',
icon: Icons.storefront_outlined,
onPressed: () => Navigator.of(context).pop(),
),
),
],
);
}
final total = services.cartRepository.totalMinorUnits;
return Column(
children: [
Expanded(
child: ListView.builder(
padding: const EdgeInsets.only(top: 8, bottom: 8),
itemCount: items.length,
itemBuilder: (context, index) =>
_buildCartItem(context, items[index]),
),
),
Material(
elevation: 4,
color: Theme.of(context).colorScheme.surface,
child: SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
const Expanded(
child: Text(
'Total (prévia)',
style: TextStyle(fontWeight: FontWeight.w600),
),
),
Text(
total == null
? 'Total indisponível'
: CurrencyFormatter.formatBrl(total),
key: const Key('cart-total'),
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const SizedBox(height: 10),
AppButton(
label: 'Pagamento',
icon: Icons.payments_outlined,
onPressed: () => Navigator.of(context)
.pushNamed(AppRoutes.payment),
),
],
),
),
),
),
],
);
},
),
);
}
}
@@ -0,0 +1,146 @@
import 'package:flutter/material.dart';
import '../../../app/app_services.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/repositories/customer_repository.dart';
class CustomerSearchScreen extends StatefulWidget {
const CustomerSearchScreen({required this.services, super.key});
final AppServices services;
@override
State<CustomerSearchScreen> createState() => _CustomerSearchScreenState();
}
class _CustomerSearchScreenState extends State<CustomerSearchScreen> {
final _queryController = TextEditingController();
List<Customer> _customers = [];
bool _loading = false;
bool _hasSearched = false;
String? _errorMessage;
@override
void dispose() {
_queryController.dispose();
super.dispose();
}
Future<void> _search() async {
final query = _queryController.text.trim();
if (query.isEmpty || _loading) return;
setState(() {
_loading = true;
_hasSearched = true;
_errorMessage = null;
_customers = [];
});
try {
final customers = await widget.services.customerRepository.search(query);
if (mounted) setState(() => _customers = customers);
} on CustomerSearchException catch (error) {
if (mounted) setState(() => _errorMessage = error.message);
} catch (_) {
if (mounted) {
setState(() => _errorMessage = 'Não foi possível pesquisar clientes.');
}
} finally {
if (mounted) setState(() => _loading = false);
}
}
void _select(Customer customer) {
Navigator.of(context).pop(customer);
}
Widget _buildResults() {
if (_loading) return const LoadingView(message: 'Pesquisando clientes...');
if (_errorMessage != null) {
return ErrorView(message: _errorMessage!, onRetry: _search);
}
if (!_hasSearched) {
return const EmptyView(
title: 'Pesquisar cliente',
message: 'Informe o nome ou CPF do cliente.',
icon: Icons.person_search_outlined,
);
}
if (_customers.isEmpty) {
return const EmptyView(
title: 'Nenhum cliente encontrado',
message: 'Tente outro nome ou CPF.',
icon: Icons.person_off_outlined,
);
}
return ListView.separated(
padding: const EdgeInsets.all(12),
itemCount: _customers.length,
separatorBuilder: (_, __) => const SizedBox(height: 6),
itemBuilder: (context, index) {
final customer = _customers[index];
return Card(
child: ListTile(
key: Key('customer-${customer.id}'),
title: Text(customer.name),
subtitle: customer.documentMasked.isEmpty
? null
: Text(customer.documentMasked),
trailing: const Icon(Icons.chevron_right),
onTap: () => _select(customer),
),
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Consulta de cliente')),
body: SafeArea(
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Row(
children: [
Expanded(
child: TextField(
key: const Key('customer-search-query'),
controller: _queryController,
enabled: !_loading,
textInputAction: TextInputAction.search,
onSubmitted: (_) => _search(),
decoration: const InputDecoration(
labelText: 'Nome ou CPF',
prefixIcon: Icon(Icons.search),
),
),
),
const SizedBox(width: 10),
IconButton.filledTonal(
key: const Key('customer-search-button'),
tooltip: 'Pesquisar cliente',
constraints:
const BoxConstraints.tightFor(width: 52, height: 52),
onPressed: _loading ? null : _search,
icon: _loading
? const SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.search),
),
],
),
),
Expanded(child: _buildResults()),
],
),
),
);
}
}
@@ -0,0 +1,244 @@
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../app/app_services.dart';
import '../../../app/router/app_router.dart';
import '../../../core/widgets/app_button.dart';
import '../../../domain/repositories/auth_repository.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({required this.services, super.key});
final AppServices services;
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _formKey = GlobalKey<FormState>();
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
bool _obscurePassword = true;
bool _submitting = false;
late final Future<String> _appVersion;
@override
void initState() {
super.initState();
_appVersion = widget.services.appVersionProvider.getVersion();
}
@override
void dispose() {
_usernameController.dispose();
_passwordController.dispose();
super.dispose();
}
Future<void> _submit() async {
if (_submitting || !_formKey.currentState!.validate()) return;
setState(() => _submitting = true);
try {
final settings = await widget.services.settingsRepository.load();
if (settings?.isConfigured != true) {
_showMessage('Configure o servidor pela engrenagem antes de entrar.');
return;
}
final device = await widget.services.posDeviceProvider.getDevice();
final appVersion = await widget.services.appVersionProvider.getVersion();
await widget.services.authRepository.authenticate(
username: _usernameController.text.trim(),
password: _passwordController.text,
settings: settings!,
device: device,
appVersion: appVersion,
);
if (mounted) {
Navigator.of(context).pushNamedAndRemoveUntil(
AppRoutes.menu,
(route) => false,
);
}
} on UnsupportedError catch (error) {
developer.log(
'Login bloqueado pela plataforma do dispositivo.',
name: 'pdv.auth',
);
_showMessage(error.message.toString());
} on AuthUnavailableException catch (error) {
_showMessage(error.message);
} catch (error, stackTrace) {
developer.log(
'Falha ao preparar login do PDV: ${error.runtimeType}.',
name: 'pdv.auth',
stackTrace: stackTrace,
);
_showMessage(
'Não foi possível autenticar. Verifique os dados e tente novamente.');
} finally {
if (mounted) setState(() => _submitting = false);
}
}
Future<void> _exit() async {
await widget.services.authRepository.logout();
await SystemNavigator.pop();
}
void _openSettings() {
Navigator.of(context).pushNamed(AppRoutes.settings);
}
void _showMessage(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text(message)));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('PDV'),
),
body: SafeArea(
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(left: 16, right: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
FutureBuilder<String>(
future: _appVersion,
builder: (context, snapshot) {
if (!snapshot.hasData || snapshot.hasError) {
return const SizedBox.shrink();
}
return Text(
'Versão: ${snapshot.data}',
key: const Key('app-version'),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 11,
),
);
},
),
IconButton(
key: const Key('settings-button'),
tooltip: 'Configuração',
onPressed: _submitting ? null : _openSettings,
icon: const Icon(Icons.settings_outlined),
),
],
),
),
Expanded(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 440),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Icon(
Icons.point_of_sale_rounded,
size: 64,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(height: 20),
Text(
'Acesso ao PDV',
textAlign: TextAlign.center,
style: Theme.of(context)
.textTheme
.headlineSmall
?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 28),
TextFormField(
key: const Key('login-username'),
controller: _usernameController,
enabled: !_submitting,
textInputAction: TextInputAction.next,
autocorrect: false,
decoration: const InputDecoration(
labelText: 'Usuário',
prefixIcon: Icon(Icons.person_outline),
),
validator: (value) =>
value == null || value.trim().isEmpty
? 'Informe o usuário.'
: null,
),
const SizedBox(height: 16),
TextFormField(
key: const Key('login-password'),
controller: _passwordController,
enabled: !_submitting,
obscureText: _obscurePassword,
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => _submit(),
decoration: InputDecoration(
labelText: 'Senha',
prefixIcon: const Icon(Icons.lock_outline),
suffixIcon: IconButton(
tooltip: _obscurePassword
? 'Mostrar senha'
: 'Ocultar senha',
onPressed: () => setState(
() => _obscurePassword = !_obscurePassword,
),
icon: Icon(
_obscurePassword
? Icons.visibility_outlined
: Icons.visibility_off_outlined,
),
),
),
validator: (value) => value == null || value.isEmpty
? 'Informe a senha.'
: null,
),
const SizedBox(height: 24),
AppButton(
label: 'Entrar',
icon: Icons.login,
onPressed: _submitting ? null : _submit,
),
if (_submitting) ...[
const SizedBox(height: 16),
const Center(child: CircularProgressIndicator()),
],
const SizedBox(height: 12),
TextButton.icon(
onPressed: _submitting ? null : _exit,
icon: const Icon(Icons.exit_to_app),
label: const Text('Sair'),
),
],
),
),
),
),
),
),
],
),
),
);
}
}
@@ -0,0 +1,164 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../app/app_services.dart';
import '../../../app/router/app_router.dart';
class MenuScreen extends StatefulWidget {
const MenuScreen({required this.services, super.key});
final AppServices services;
@override
State<MenuScreen> createState() => _MenuScreenState();
}
class _MenuScreenState extends State<MenuScreen> {
bool _loggingOut = false;
Future<void> _logout() async {
if (_loggingOut) return;
setState(() => _loggingOut = true);
await widget.services.authRepository.logout();
if (!mounted) return;
Navigator.of(context).pushNamedAndRemoveUntil(
AppRoutes.login,
(_) => false,
);
}
Future<void> _exit() => SystemNavigator.pop();
@override
Widget build(BuildContext context) {
final session = widget.services.authRepository.currentSession;
final companyId = session?.companyId;
final companyName = session?.companyName;
final companyDescription = [
if (companyId != null) companyId.toString(),
if (companyName != null && companyName.trim().isNotEmpty)
companyName.trim(),
].join(' - ');
final actions = [
_MenuAction(
label: 'Venda',
icon: Icons.point_of_sale_outlined,
onPressed: () => Navigator.of(context).pushNamed(AppRoutes.sale),
),
_MenuAction(
label: 'Histórico de vendas',
icon: Icons.receipt_long_outlined,
onPressed: () =>
Navigator.of(context).pushNamed(AppRoutes.salesHistory),
),
_MenuAction(
label: _loggingOut ? 'Saindo...' : 'Log out',
icon: Icons.logout,
onPressed: _loggingOut ? null : _logout,
),
_MenuAction(
label: 'Sair',
icon: Icons.power_settings_new,
onPressed: _exit,
),
];
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Menu do PDV'),
),
body: SafeArea(
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 760),
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Card(
child: ListTile(
leading: const CircleAvatar(
child: Icon(Icons.person_outline),
),
title: Text(
session?.userName ?? 'Usuário',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
subtitle: Text(
companyDescription.isEmpty
? 'Empresa não informada'
: 'Empresa: $companyDescription',
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
),
),
Expanded(
child: GridView.builder(
padding: const EdgeInsets.all(16),
itemCount: actions.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
childAspectRatio: 1,
),
itemBuilder: (context, index) {
final action = actions[index];
return Card(
clipBehavior: Clip.antiAlias,
child: InkWell(
key: Key('menu-${index + 1}'),
onTap: action.onPressed,
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(action.icon, size: 48),
const SizedBox(height: 12),
Text(
action.label,
textAlign: TextAlign.center,
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(fontWeight: FontWeight.w600),
),
],
),
),
),
);
},
),
),
],
),
),
),
),
);
}
}
class _MenuAction {
const _MenuAction({
required this.label,
required this.icon,
required this.onPressed,
});
final String label;
final IconData icon;
final VoidCallback? onPressed;
}
@@ -0,0 +1,679 @@
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<PaymentScreen> createState() => _PaymentScreenState();
}
class _PaymentScreenState extends State<PaymentScreen> {
List<PaymentMethod> _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<void> _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<void> _includeCustomer() async {
final customer = await Navigator.of(context)
.pushNamed<Customer>(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<String?> _requestCustomerCpf() async {
final controller = TextEditingController();
String? errorMessage;
final cpf = await showDialog<String>(
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<void> _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<void, void>(
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<PaymentMethod> _methodsFor(_PaymentCategory category) => _methods
.where((method) => _categoryFor(method) == category)
.toList(growable: false);
int get _allocatedMinorUnits => _allocations.fold<int>(
0,
(total, allocation) => total + allocation.amountMinor,
);
Future<void> _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<PaymentMethod>(
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<int>(0, (sum, allocation) => sum + allocation.amountMinor);
final awaitingTerminal = _allocations
.where((allocation) => !allocation.isCash)
.fold<int>(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,
),
],
),
),
),
),
],
],
),
);
}
}
@@ -0,0 +1,189 @@
import 'package:flutter/material.dart';
import '../../../app/app_services.dart';
import '../../../app/router/app_router.dart';
import '../../../domain/entities/sale_completion.dart';
import '../../../core/widgets/app_button.dart';
class SaleCompleteScreen extends StatelessWidget {
const SaleCompleteScreen({
required this.services,
required this.completion,
super.key,
});
final AppServices services;
final SaleCompletion completion;
void _startNextSale(BuildContext context) {
services.cartRepository.clear();
Navigator.of(context).popUntil(
(route) => route.settings.name == AppRoutes.sale,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Venda finalizada'),
automaticallyImplyLeading: false,
),
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 520),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Icon(
Icons.check_circle,
size: 88,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(height: 16),
Text(
'NFC-e gerada',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 20),
Card(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
children: [
_DocumentRow(
label: 'Pedido',
value: completion.orderNumber,
),
const Divider(height: 24),
_DocumentRow(
label: 'Número NFC-e',
value: completion.invoiceNumber,
),
const Divider(height: 24),
_DocumentRow(
label: 'Série',
value: completion.invoiceSeries,
),
const Divider(height: 24),
_DocumentRow(
label: 'Estado da NFC-e',
value: _invoiceStateLabel(
completion.invoiceState,
completion.invoiceContingency,
),
),
],
),
),
),
if (completion.invoiceMessage.isNotEmpty) ...[
const SizedBox(height: 12),
Card(
color: Theme.of(context).colorScheme.surface,
child: Padding(
padding: const EdgeInsets.all(16),
child: Text(
completion.invoiceMessage,
),
),
),
],
const SizedBox(height: 20),
AppButton(
label: 'Imprimir NFC-e',
icon: Icons.print_outlined,
onPressed: () => _showPrintNotConfigured(context),
),
const SizedBox(height: 10),
AppButton(
label: 'Nova venda',
icon: Icons.storefront_outlined,
onPressed: () => _startNextSale(context),
),
],
),
),
),
),
),
);
}
void _showPrintNotConfigured(BuildContext context) {
showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Impressão indisponível'),
content: const Text(
'A API/SDK da impressora do POS ainda não foi configurada.',
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Fechar'),
),
],
),
);
}
String _invoiceStateLabel(String state, bool contingency) {
if (contingency) return 'Emitida em Contingência';
switch (state) {
case '1':
return 'Rascunho';
case '2':
return 'Validada';
case '2E':
return 'Validada com erro';
case '3':
return 'Faturada/autorizada';
case 'C':
return 'Cancelada';
case 'D':
return 'Denegada';
case 'EP':
return 'Em processamento';
case 'I':
return 'Inutilizada';
case 'P':
return 'Pendente';
default:
return state.isEmpty ? 'Não informado' : state;
}
}
}
class _DocumentRow extends StatelessWidget {
const _DocumentRow({required this.label, required this.value});
final String label;
final String value;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label),
const SizedBox(width: 16),
Flexible(
child: Text(
value,
textAlign: TextAlign.end,
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
),
],
);
}
}
@@ -0,0 +1,597 @@
import 'dart:convert';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
import '../../../app/app_services.dart';
import '../../../app/router/app_router.dart';
import '../../../core/utils/currency_formatter.dart';
import '../../../core/widgets/empty_view.dart';
import '../../../core/widgets/error_view.dart';
import '../../../core/widgets/loading_view.dart';
import '../../../domain/entities/department.dart';
import '../../../domain/entities/product.dart';
import '../../../domain/entities/sale_view_mode.dart';
import '../../../domain/repositories/catalog_repository.dart';
class SaleScreen extends StatefulWidget {
const SaleScreen({required this.services, super.key});
final AppServices services;
@override
State<SaleScreen> createState() => _SaleScreenState();
}
class _SaleScreenState extends State<SaleScreen> {
final Map<int, List<Product>> _productsByDepartment = {};
List<Department> _departments = [];
int? _selectedDepartmentId;
bool _loadingDepartments = true;
bool _loadingProducts = false;
bool _showKanban = true;
bool _scanningBarcode = false;
String? _departmentError;
String? _productError;
int _productRequest = 0;
@override
void initState() {
super.initState();
_initialize();
}
Future<void> _initialize() async {
final userId = widget.services.authRepository.currentSession?.userId;
if (userId != null) {
try {
final viewMode = await widget.services.saleViewPreferenceRepository
.loadForUser(userId);
if (mounted) {
setState(() => _showKanban = viewMode == SaleViewMode.kanban);
}
} catch (_) {
// Use Kanban as the default if preference storage is unavailable.
}
}
if (mounted) await _loadDepartments();
}
Future<void> _setViewMode(bool showKanban) async {
setState(() => _showKanban = showKanban);
final userId = widget.services.authRepository.currentSession?.userId;
if (userId == null) return;
try {
await widget.services.saleViewPreferenceRepository.saveForUser(
userId,
showKanban ? SaleViewMode.kanban : SaleViewMode.list,
);
} catch (_) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Não foi possível salvar a visualização.')),
);
}
}
}
Future<void> _loadDepartments() async {
setState(() {
_loadingDepartments = true;
_departmentError = null;
});
try {
final departments =
await widget.services.catalogRepository.fetchDepartments();
if (!mounted) return;
setState(() {
_departments = departments;
_selectedDepartmentId =
departments.isEmpty ? null : departments.first.id;
_loadingDepartments = false;
});
if (departments.isNotEmpty) {
await _selectDepartment(departments.first);
}
} on CatalogException catch (error) {
if (mounted) {
setState(() {
_departmentError = error.message;
_loadingDepartments = false;
});
}
} catch (_) {
if (mounted) {
setState(() {
_departmentError = 'Não foi possível carregar os departamentos.';
_loadingDepartments = false;
});
}
}
}
Future<void> _selectDepartment(Department department) async {
setState(() {
_selectedDepartmentId = department.id;
_productError = null;
_loadingProducts = !_productsByDepartment.containsKey(department.id);
});
if (_productsByDepartment.containsKey(department.id)) return;
final requestId = ++_productRequest;
try {
final products = await widget.services.catalogRepository
.fetchProductsByDepartment(department.id);
if (!mounted || requestId != _productRequest) return;
setState(() {
_productsByDepartment[department.id] = products;
_loadingProducts = false;
});
} on CatalogException catch (error) {
if (mounted && requestId == _productRequest) {
setState(() {
_productError = error.message;
_loadingProducts = false;
});
}
} catch (_) {
if (mounted && requestId == _productRequest) {
setState(() {
_productError = 'Não foi possível carregar os produtos.';
_loadingProducts = false;
});
}
}
}
Future<void> _retryProducts() async {
final selectedId = _selectedDepartmentId;
if (selectedId == null) return;
_productsByDepartment.remove(selectedId);
final department = _departments.firstWhere((item) => item.id == selectedId);
await _selectDepartment(department);
}
void _addProduct(Product product) {
widget.services.cartRepository.addProduct(product);
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text('${product.name} adicionado.')));
}
Future<void> _scanProductBarcode() async {
if (_scanningBarcode) return;
setState(() => _scanningBarcode = true);
try {
final barcode = await FlutterBarcodeScanner.scanBarcode(
'#ff6666',
'Cancelar',
true,
ScanMode.BARCODE,
);
if (!mounted || barcode == '-1' || barcode.trim().isEmpty) return;
final product = await widget.services.catalogRepository
.fetchProductByBarcode(barcode.trim());
if (!mounted) return;
if (product == null) {
await showDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Produto não encontrado'),
content: Text('O código "$barcode" não foi encontrado.'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('Ok'),
),
],
),
);
return;
}
_addProduct(product);
} on PlatformException {
if (mounted) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
const SnackBar(content: Text('Não foi possível abrir a câmera.')),
);
}
} on CatalogException catch (error) {
if (mounted) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text(error.message)));
}
} catch (_) {
if (mounted) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
const SnackBar(
content: Text('Não foi possível consultar o código lido.'),
),
);
}
} finally {
if (mounted) setState(() => _scanningBarcode = false);
}
}
String get _selectedDepartmentName {
for (final department in _departments) {
if (department.id == _selectedDepartmentId) return department.name;
}
return '';
}
Widget _productImage(
Product product, {
double? width,
double? height,
BoxFit fit = BoxFit.cover,
}) {
final encodedImage = product.imageBase64;
if (encodedImage == null) return _imagePlaceholder(width, height);
try {
return Image.memory(
base64Decode(encodedImage),
width: width,
height: height,
fit: fit,
errorBuilder: (_, __, ___) => _imagePlaceholder(width, height),
);
} on FormatException {
return _imagePlaceholder(width, height);
}
}
Widget _imagePlaceholder(double? width, double? height) {
return Container(
width: width,
height: height,
color: Theme.of(context).colorScheme.surfaceVariant,
alignment: Alignment.center,
child: const Icon(Icons.image_outlined, size: 36),
);
}
Widget _buildProductCard(Product product, {required bool grid}) {
if (grid) {
return Card(
clipBehavior: Clip.antiAlias,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: ColoredBox(
color: Theme.of(context).colorScheme.surfaceVariant,
child: _productImage(product, fit: BoxFit.contain),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(6, 6, 6, 2),
child: Text(
product.name,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6),
child: Text(
product.code,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
Padding(
padding: const EdgeInsets.fromLTRB(4, 2, 4, 0),
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
CurrencyFormatter.formatBrl(product.priceMinorUnits),
style: Theme.of(context)
.textTheme
.labelLarge
?.copyWith(fontWeight: FontWeight.bold),
),
),
),
Align(
alignment: Alignment.center,
child: IconButton.filledTonal(
constraints:
const BoxConstraints.tightFor(width: 38, height: 38),
padding: EdgeInsets.zero,
tooltip: 'Adicionar ${product.name}',
onPressed: () => _addProduct(product),
icon: const Icon(Icons.add_shopping_cart, size: 18),
),
),
],
),
);
}
return Card(
clipBehavior: Clip.antiAlias,
child: ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
leading: SizedBox.square(
dimension: 64,
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: _productImage(product),
),
),
title: Text(
product.name,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
subtitle: Text(
'Código ${product.code} · '
'${CurrencyFormatter.formatBrl(product.priceMinorUnits)}',
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(fontWeight: FontWeight.bold),
),
trailing: IconButton.filledTonal(
tooltip: 'Adicionar ${product.name}',
onPressed: () => _addProduct(product),
icon: const Icon(Icons.add_shopping_cart),
),
),
);
}
Widget _buildProducts() {
if (_loadingProducts) {
return const LoadingView(message: 'Carregando produtos...');
}
if (_productError != null) {
return ErrorView(message: _productError!, onRetry: _retryProducts);
}
final products = _productsByDepartment[_selectedDepartmentId] ?? [];
if (products.isEmpty) {
return const EmptyView(
title: 'Nenhum produto',
message: 'Não há produtos neste departamento.',
icon: Icons.inventory_2_outlined,
);
}
if (!_showKanban) {
return ListView.builder(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
itemCount: products.length,
itemBuilder: (_, index) =>
_buildProductCard(products[index], grid: false),
);
}
return LayoutBuilder(
builder: (context, constraints) {
final tileWidth = (constraints.maxWidth - 44) / 3;
// Reserve at least 64 px for the image, matching the list thumbnail.
final tileHeight = math.max(196.0, tileWidth / 0.9);
return GridView.builder(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
childAspectRatio: tileWidth / tileHeight,
),
itemCount: products.length,
itemBuilder: (_, index) =>
_buildProductCard(products[index], grid: true),
);
},
);
}
Widget _buildCartBar() {
return AnimatedBuilder(
animation: widget.services.cartRepository,
builder: (context, _) {
final itemCount = widget.services.cartRepository.itemCount;
final totalMinorUnits = widget.services.cartRepository.totalMinorUnits;
return Material(
elevation: 4,
color: Theme.of(context).colorScheme.surface,
child: SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Total do carrinho',
style: Theme.of(context).textTheme.bodySmall,
),
Text(
totalMinorUnits == null
? 'Total indisponível'
: CurrencyFormatter.formatBrl(totalMinorUnits),
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
],
),
),
SizedBox.square(
dimension: 56,
child: Stack(
clipBehavior: Clip.none,
children: [
Positioned.fill(
child: IconButton.filledTonal(
tooltip: 'Carrinho',
onPressed: itemCount == 0
? null
: () => Navigator.of(context)
.pushNamed(AppRoutes.cart),
icon: const Icon(Icons.shopping_cart_outlined),
),
),
if (itemCount > 0)
Positioned(
top: -2,
right: -2,
child: Container(
constraints: const BoxConstraints(
minWidth: 20,
minHeight: 20,
),
padding:
const EdgeInsets.symmetric(horizontal: 5),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.error,
borderRadius: BorderRadius.circular(10),
),
alignment: Alignment.center,
child: Text(
itemCount > 99 ? '99+' : '$itemCount',
style: TextStyle(
color: Theme.of(context).colorScheme.onError,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
),
),
],
),
),
],
),
),
),
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Venda'),
actions: [
IconButton(
key: const Key('refresh-products-button'),
tooltip: 'Atualizar produtos',
onPressed: _loadingProducts || _selectedDepartmentId == null
? null
: _retryProducts,
icon: const Icon(Icons.refresh),
),
],
),
body: SafeArea(
child: Column(
children: [
if (_loadingDepartments)
const Expanded(
child: LoadingView(message: 'Carregando departamentos...'),
)
else if (_departmentError != null)
Expanded(
child: ErrorView(
message: _departmentError!,
onRetry: _loadDepartments,
),
)
else if (_departments.isEmpty)
const Expanded(
child: EmptyView(
title: 'Nenhum departamento',
message: 'O servidor não retornou departamentos para venda.',
icon: Icons.category_outlined,
),
)
else ...[
SizedBox(
height: 58,
child: ListView.separated(
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
scrollDirection: Axis.horizontal,
itemCount: _departments.length,
separatorBuilder: (_, __) => const SizedBox(width: 8),
itemBuilder: (context, index) {
final department = _departments[index];
return ChoiceChip(
label: Text(department.name),
selected: department.id == _selectedDepartmentId,
onSelected: (_) => _selectDepartment(department),
);
},
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 8, 8),
child: Row(
children: [
Expanded(
child: Text(
_selectedDepartmentName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleMedium,
),
),
IconButton.filledTonal(
tooltip: 'Ler código de barras',
onPressed: _scanningBarcode ? null : _scanProductBarcode,
icon: _scanningBarcode
? SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Theme.of(context)
.colorScheme
.onSecondaryContainer,
),
)
: const Icon(Icons.camera_alt_outlined),
),
const SizedBox(width: 20),
IconButton(
tooltip: _showKanban
? 'Visualizar em lista'
: 'Visualizar em Kanban',
onPressed: () => _setViewMode(!_showKanban),
icon: Icon(
_showKanban ? Icons.view_list : Icons.grid_view,
),
),
],
),
),
Expanded(child: _buildProducts()),
],
],
),
),
bottomNavigationBar: _buildCartBar(),
);
}
}
@@ -0,0 +1,255 @@
import 'package:flutter/material.dart';
import '../../../app/app_services.dart';
import '../../../core/utils/currency_formatter.dart';
import '../../../domain/entities/historical_sale.dart';
import '../../../domain/repositories/sales_history_repository.dart';
class SalesHistoryScreen extends StatefulWidget {
const SalesHistoryScreen({required this.services, super.key});
final AppServices services;
@override
State<SalesHistoryScreen> createState() => _SalesHistoryScreenState();
}
class _SalesHistoryScreenState extends State<SalesHistoryScreen> {
late Future<List<HistoricalSale>> _salesFuture;
@override
void initState() {
super.initState();
_salesFuture = widget.services.salesHistoryRepository.fetchSales();
}
Future<void> _reload() async {
final future = widget.services.salesHistoryRepository.fetchSales();
setState(() => _salesFuture = future);
try {
await future;
} catch (_) {
// FutureBuilder displays the error while RefreshIndicator is dismissed.
}
}
String _formatDate(String value) {
final parts = value.split('-');
if (parts.length != 3) return value;
return '${parts[2]}/${parts[1]}/${parts[0]}';
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Histórico de vendas')),
body: SafeArea(
child: FutureBuilder<List<HistoricalSale>>(
future: _salesFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
final error = snapshot.error;
final message = error is SalesHistoryException
? error.message
: 'Não foi possível carregar o histórico de vendas.';
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.error_outline, size: 48),
const SizedBox(height: 12),
Text(message, textAlign: TextAlign.center),
const SizedBox(height: 16),
FilledButton.icon(
onPressed: _reload,
icon: const Icon(Icons.refresh),
label: const Text('Tentar novamente'),
),
],
),
),
);
}
final sales = snapshot.data ?? const <HistoricalSale>[];
if (sales.isEmpty) {
return RefreshIndicator(
onRefresh: _reload,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const [
SizedBox(height: 120),
Icon(Icons.receipt_long_outlined, size: 56),
SizedBox(height: 16),
Center(child: Text('Nenhuma venda encontrada.')),
SizedBox(height: 24),
],
),
);
}
return RefreshIndicator(
onRefresh: _reload,
child: ListView.separated(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(16),
itemCount: sales.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
itemBuilder: (context, index) => _SaleCard(
sale: sales[index],
formatDate: _formatDate,
onReprint: _confirmReprint,
),
),
);
},
),
),
);
}
Future<void> _confirmReprint(HistoricalSale sale) async {
final shouldReprint = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Reimprimir NFC-e?'),
content: Text(
'Deseja reimprimir a nota do pedido ${sale.orderNumber}?',
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('Cancelar'),
),
FilledButton.icon(
onPressed: () => Navigator.of(dialogContext).pop(true),
icon: const Icon(Icons.print_outlined),
label: const Text('Reimprimir'),
),
],
),
);
if (shouldReprint != true || !mounted) return;
await showDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Impressão indisponível'),
content: const Text(
'A impressão da NFC-e ainda depende da integração com a API/SDK '
'da impressora do POS.',
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('Fechar'),
),
],
),
);
}
}
class _SaleCard extends StatelessWidget {
const _SaleCard({
required this.sale,
required this.formatDate,
required this.onReprint,
});
final HistoricalSale sale;
final String Function(String) formatDate;
final ValueChanged<HistoricalSale> onReprint;
Color _backgroundColor() => switch (sale.state) {
'V' => const Color(0xFFE8F5E9),
'F' => const Color(0xFFFFEBEE),
_ => Colors.white,
};
Color _stateColor() => switch (sale.state) {
'V' => const Color(0xFF2E7D32),
'F' => const Color(0xFFC62828),
_ => Colors.black87,
};
String _stateLabel() => switch (sale.state) {
'V' => 'Validado',
'F' => 'Faturado',
_ => sale.state,
};
@override
Widget build(BuildContext context) {
return Card(
color: _backgroundColor(),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: sale.state == 'F' ? () => onReprint(sale) : null,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.receipt_long_outlined),
const SizedBox(width: 10),
Expanded(
child: Text(
'Pedido ${sale.orderNumber}',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
Text(
CurrencyFormatter.formatBrl(sale.totalMinorUnits),
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerRight,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_stateLabel(),
style: TextStyle(
color: _stateColor(),
fontWeight: FontWeight.w700,
),
),
if (sale.state == 'F') ...[
const SizedBox(width: 6),
Icon(Icons.print_outlined,
size: 18, color: _stateColor()),
],
],
),
),
const SizedBox(height: 10),
Text('Emissão: ${formatDate(sale.issueDate)}'),
if (sale.customerName.trim().isNotEmpty) ...[
const SizedBox(height: 4),
Text(
'Cliente: ${sale.customerName}',
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
],
),
),
),
);
}
}
@@ -0,0 +1,236 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../app/app_services.dart';
import '../../../core/config/server_url_validator.dart';
import '../../../core/widgets/app_button.dart';
import '../../../core/widgets/error_view.dart';
import '../../../core/widgets/loading_view.dart';
import '../../../domain/entities/app_settings.dart';
class SettingsScreen extends StatefulWidget {
const SettingsScreen({required this.services, super.key});
final AppServices services;
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen> {
final _formKey = GlobalKey<FormState>();
final _serverUrlController = TextEditingController();
final _identifierController = TextEditingController();
bool _loading = true;
bool _saving = false;
bool _testing = false;
Object? _loadError;
@override
void initState() {
super.initState();
_loadSettings();
}
@override
void dispose() {
_serverUrlController.dispose();
_identifierController.dispose();
super.dispose();
}
Future<void> _loadSettings() async {
setState(() {
_loading = true;
_loadError = null;
});
try {
final settings = await widget.services.settingsRepository.load();
if (!mounted) return;
_serverUrlController.text = settings?.serverUrl ?? '';
_identifierController.text = settings?.companyIdentifier ?? '';
setState(() => _loading = false);
} catch (error) {
if (mounted) {
setState(() {
_loadError = error;
_loading = false;
});
}
}
}
String? _validateServerUrl(String? value) =>
ServerUrlValidator.validate(value ?? '');
String? _validateIdentifier(String? value) {
final identifier = value?.trim() ?? '';
if (identifier.isEmpty) return 'Informe o identificador da empresa.';
if (identifier.length > 14 ||
!RegExp(r'^[a-zA-Z0-9]+$').hasMatch(identifier)) {
return 'Use até 14 letras ou números.';
}
return null;
}
AppSettings _formSettings() => AppSettings(
serverUrl: _serverUrlController.text.trim(),
companyIdentifier: _identifierController.text.trim(),
);
Future<void> _testConnection() async {
if (_testing || !_formKey.currentState!.validate()) return;
setState(() => _testing = true);
try {
final result = await widget.services.connectionTester.test(
Uri.parse(_serverUrlController.text.trim()),
);
if (mounted) _showMessage(result.message);
} catch (_) {
if (mounted) {
_showMessage('Não foi possível testar a conexão. Tente novamente.');
}
} finally {
if (mounted) setState(() => _testing = false);
}
}
Future<void> _save() async {
if (_saving || !_formKey.currentState!.validate()) return;
setState(() => _saving = true);
try {
final settings = _formSettings();
final previous = await widget.services.settingsRepository.load();
if (previous != settings) {
await widget.services.authRepository.logout();
}
await widget.services.settingsRepository.save(settings);
if (mounted) {
_showMessage('Configuração salva.');
Navigator.of(context).pop();
}
} catch (_) {
if (mounted) _showMessage('Não foi possível salvar a configuração.');
} finally {
if (mounted) setState(() => _saving = false);
}
}
void _showMessage(String message) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text(message)));
}
@override
Widget build(BuildContext context) {
if (_loading) {
return const Scaffold(
body: LoadingView(message: 'Carregando configuração...'));
}
if (_loadError != null) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Configuração'),
),
body: ErrorView(
message: 'Não foi possível carregar a configuração.',
onRetry: _loadSettings,
),
);
}
final busy = _saving || _testing;
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Configuração'),
),
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 520),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 24),
TextFormField(
key: const Key('settings-server-url'),
controller: _serverUrlController,
enabled: !busy,
keyboardType: TextInputType.url,
textInputAction: TextInputAction.next,
autocorrect: false,
decoration: const InputDecoration(
labelText: 'Servidor (URL)',
hintText: 'https://odoo.exemplo.com',
helperText:
'Aceita HTTP e HTTPS. HTTP não criptografa os dados.',
prefixIcon: Icon(Icons.language),
),
validator: _validateServerUrl,
),
const SizedBox(height: 16),
TextFormField(
key: const Key('settings-company-identifier'),
controller: _identifierController,
enabled: !busy,
maxLength: 14,
textCapitalization: TextCapitalization.characters,
textInputAction: TextInputAction.done,
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp('[a-zA-Z0-9]')),
LengthLimitingTextInputFormatter(14),
],
decoration: const InputDecoration(
labelText: 'CNPJ',
prefixIcon: Icon(Icons.business_outlined),
),
validator: _validateIdentifier,
),
const SizedBox(height: 8),
OutlinedButton.icon(
key: const Key('test-connection-button'),
onPressed: busy ? null : _testConnection,
icon: _testing
? const SizedBox.square(
dimension: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.wifi_tethering),
label: const Text('Testar conexão'),
style: OutlinedButton.styleFrom(
minimumSize: const Size.fromHeight(52),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
const SizedBox(height: 12),
AppButton(
label: _saving ? 'Salvando...' : 'Salvar',
icon: Icons.save_outlined,
onPressed: busy ? null : _save,
),
const SizedBox(height: 8),
TextButton(
onPressed:
busy ? null : () => Navigator.of(context).pop(),
child: const Text('Cancelar'),
),
],
),
),
),
),
),
),
);
}
}
@@ -0,0 +1,22 @@
import 'package:flutter/material.dart';
import '../../../core/widgets/empty_view.dart';
class PlaceholderScreen extends StatelessWidget {
const PlaceholderScreen({
required this.title,
required this.message,
super.key,
});
final String title;
final String message;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: EmptyView(title: title, message: message),
);
}
}