181186 - Criar PDV Android para rodar em maquinas P.O.S.
This commit is contained in:
commit
c9983cbad5
204 files changed
+11453
No files matched your search
@@ -0,0 +1,27 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'app_services.dart';
|
||||
import 'router/app_router.dart';
|
||||
import 'theme/app_theme.dart';
|
||||
|
||||
class PdvApp extends StatelessWidget {
|
||||
const PdvApp({this.services, super.key});
|
||||
|
||||
static final GlobalKey<NavigatorState> navigatorKey =
|
||||
GlobalKey<NavigatorState>();
|
||||
|
||||
final AppServices? services;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final appServices = services ?? AppServices.defaults;
|
||||
return MaterialApp(
|
||||
title: 'PDV',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: AppTheme.light,
|
||||
navigatorKey: navigatorKey,
|
||||
initialRoute: AppRoutes.login,
|
||||
onGenerateRoute: AppRouter(services: appServices).onGenerateRoute,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import '../core/config/app_version_provider.dart';
|
||||
import '../core/config/pos_device_provider.dart';
|
||||
import '../core/storage/session_storage_factory.dart';
|
||||
import '../data/datasources/remote/odoo_connection_tester.dart';
|
||||
import '../data/datasources/remote/odoo_session_api_client.dart';
|
||||
import '../data/repositories/odoo_customer_repository.dart';
|
||||
import '../data/repositories/odoo_payment_methods_repository.dart';
|
||||
import '../data/repositories/odoo_sale_checkout_repository.dart';
|
||||
import '../data/repositories/odoo_sales_history_repository.dart';
|
||||
import '../data/repositories/odoo_catalog_repository.dart';
|
||||
import '../data/repositories/odoo_auth_repository.dart';
|
||||
import '../data/repositories/shared_preferences_sale_view_preference_repository.dart';
|
||||
import '../data/repositories/shared_preferences_settings_repository.dart';
|
||||
import '../domain/repositories/auth_repository.dart';
|
||||
import '../domain/repositories/cart_repository.dart';
|
||||
import '../domain/repositories/catalog_repository.dart';
|
||||
import '../domain/repositories/customer_repository.dart';
|
||||
import '../domain/repositories/connection_tester.dart';
|
||||
import '../domain/repositories/payment_methods_repository.dart';
|
||||
import '../domain/repositories/sale_checkout_repository.dart';
|
||||
import '../domain/repositories/sales_history_repository.dart';
|
||||
import '../domain/repositories/settings_repository.dart';
|
||||
import '../domain/repositories/sale_view_preference_repository.dart';
|
||||
|
||||
class AppServices {
|
||||
const AppServices({
|
||||
required this.settingsRepository,
|
||||
required this.connectionTester,
|
||||
required this.authRepository,
|
||||
required this.appVersionProvider,
|
||||
required this.posDeviceProvider,
|
||||
required this.catalogRepository,
|
||||
required this.cartRepository,
|
||||
required this.saleViewPreferenceRepository,
|
||||
required this.customerRepository,
|
||||
required this.paymentMethodsRepository,
|
||||
required this.saleCheckoutRepository,
|
||||
required this.salesHistoryRepository,
|
||||
});
|
||||
|
||||
static final defaults = _createDefaults();
|
||||
|
||||
static AppServices _createDefaults() {
|
||||
const settingsRepository = SharedPreferencesSettingsRepository();
|
||||
final sessionStorage = createSessionStorage();
|
||||
final authRepository = OdooAuthRepository(sessionStorage: sessionStorage);
|
||||
final apiClient = OdooSessionApiClient(
|
||||
authRepository: authRepository,
|
||||
settingsRepository: settingsRepository,
|
||||
sessionStorage: sessionStorage,
|
||||
);
|
||||
return AppServices(
|
||||
settingsRepository: settingsRepository,
|
||||
connectionTester: OdooConnectionTester(),
|
||||
authRepository: authRepository,
|
||||
appVersionProvider: const PackageInfoAppVersionProvider(),
|
||||
posDeviceProvider: PlatformPosDeviceProvider(),
|
||||
catalogRepository: OdooCatalogRepository(apiClient: apiClient),
|
||||
customerRepository: OdooCustomerRepository(apiClient: apiClient),
|
||||
paymentMethodsRepository:
|
||||
OdooPaymentMethodsRepository(apiClient: apiClient),
|
||||
saleCheckoutRepository: OdooSaleCheckoutRepository(apiClient: apiClient),
|
||||
salesHistoryRepository: OdooSalesHistoryRepository(apiClient: apiClient),
|
||||
cartRepository: InMemoryCartRepository(),
|
||||
saleViewPreferenceRepository:
|
||||
const SharedPreferencesSaleViewPreferenceRepository(),
|
||||
);
|
||||
}
|
||||
|
||||
final SettingsRepository settingsRepository;
|
||||
final ConnectionTester connectionTester;
|
||||
final AuthRepository authRepository;
|
||||
final AppVersionProvider appVersionProvider;
|
||||
final PosDeviceProvider posDeviceProvider;
|
||||
final CatalogRepository catalogRepository;
|
||||
final CartRepository cartRepository;
|
||||
final SaleViewPreferenceRepository saleViewPreferenceRepository;
|
||||
final CustomerRepository customerRepository;
|
||||
final PaymentMethodsRepository paymentMethodsRepository;
|
||||
final SaleCheckoutRepository saleCheckoutRepository;
|
||||
final SalesHistoryRepository salesHistoryRepository;
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app_services.dart';
|
||||
import '../../domain/entities/customer.dart';
|
||||
import '../../domain/entities/sale_completion.dart';
|
||||
import '../../features/cart/presentation/cart_screen.dart';
|
||||
import '../../features/customer_search/presentation/customer_search_screen.dart';
|
||||
import '../../features/login/presentation/login_screen.dart';
|
||||
import '../../features/menu/presentation/menu_screen.dart';
|
||||
import '../../features/payment/presentation/payment_screen.dart';
|
||||
import '../../features/payment/presentation/sale_complete_screen.dart';
|
||||
import '../../features/sale/presentation/sale_screen.dart';
|
||||
import '../../features/sales_history/presentation/sales_history_screen.dart';
|
||||
import '../../features/settings/presentation/settings_screen.dart';
|
||||
import '../../features/shared/presentation/placeholder_screen.dart';
|
||||
|
||||
class AppRoutes {
|
||||
AppRoutes._();
|
||||
|
||||
static const login = '/login';
|
||||
static const menu = '/menu';
|
||||
static const settings = '/settings';
|
||||
static const sale = '/sale';
|
||||
static const cart = '/cart';
|
||||
static const payment = '/payment';
|
||||
static const customerSearch = '/customer-search';
|
||||
static const saleComplete = '/sale-complete';
|
||||
static const salesHistory = '/sales-history';
|
||||
static const saleDetail = '/sale-detail';
|
||||
}
|
||||
|
||||
class AppRouter {
|
||||
AppRouter({required this.services});
|
||||
|
||||
final AppServices services;
|
||||
|
||||
static const _protectedRoutes = <String>{
|
||||
AppRoutes.sale,
|
||||
AppRoutes.menu,
|
||||
AppRoutes.cart,
|
||||
AppRoutes.payment,
|
||||
AppRoutes.customerSearch,
|
||||
AppRoutes.saleComplete,
|
||||
AppRoutes.salesHistory,
|
||||
AppRoutes.saleDetail,
|
||||
};
|
||||
|
||||
Route<dynamic> onGenerateRoute(RouteSettings settings) {
|
||||
final routeName = settings.name ?? AppRoutes.login;
|
||||
if (_protectedRoutes.contains(routeName) &&
|
||||
!services.authRepository.isAuthenticated) {
|
||||
if (routeName == AppRoutes.customerSearch) {
|
||||
return MaterialPageRoute<Customer?>(
|
||||
settings: const RouteSettings(name: AppRoutes.login),
|
||||
builder: (_) => LoginScreen(services: services),
|
||||
);
|
||||
}
|
||||
return MaterialPageRoute<void>(
|
||||
settings: const RouteSettings(name: AppRoutes.login),
|
||||
builder: (_) => LoginScreen(services: services),
|
||||
);
|
||||
}
|
||||
|
||||
if (routeName == AppRoutes.customerSearch) {
|
||||
return MaterialPageRoute<Customer?>(
|
||||
settings: settings,
|
||||
builder: (_) => CustomerSearchScreen(services: services),
|
||||
);
|
||||
}
|
||||
|
||||
if (routeName == AppRoutes.saleComplete) {
|
||||
final completion = settings.arguments;
|
||||
if (completion is SaleCompletion) {
|
||||
return MaterialPageRoute<void>(
|
||||
settings: settings,
|
||||
builder: (_) => SaleCompleteScreen(
|
||||
services: services,
|
||||
completion: completion,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final page = switch (routeName) {
|
||||
AppRoutes.login => LoginScreen(services: services),
|
||||
AppRoutes.menu => MenuScreen(services: services),
|
||||
AppRoutes.settings => SettingsScreen(services: services),
|
||||
AppRoutes.sale => SaleScreen(services: services),
|
||||
AppRoutes.cart => CartScreen(services: services),
|
||||
AppRoutes.payment => PaymentScreen(services: services),
|
||||
AppRoutes.saleComplete => const PlaceholderScreen(
|
||||
title: 'Encerramento da venda',
|
||||
message: 'Dados da NFC-e não recebidos.',
|
||||
),
|
||||
AppRoutes.salesHistory => SalesHistoryScreen(services: services),
|
||||
AppRoutes.saleDetail => const PlaceholderScreen(
|
||||
title: 'Detalhes da venda',
|
||||
message: 'Os detalhes serão carregados do servidor.',
|
||||
),
|
||||
_ => const PlaceholderScreen(
|
||||
title: 'Página não encontrada',
|
||||
message: 'O endereço solicitado não existe.',
|
||||
),
|
||||
};
|
||||
|
||||
return MaterialPageRoute<void>(
|
||||
settings: settings,
|
||||
builder: (_) => page,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AppTheme {
|
||||
AppTheme._();
|
||||
|
||||
static const _brandColor = Color(0xFF087F76);
|
||||
|
||||
static ThemeData get light {
|
||||
final colorScheme = ColorScheme.fromSeed(
|
||||
seedColor: _brandColor,
|
||||
brightness: Brightness.light,
|
||||
);
|
||||
|
||||
return ThemeData(
|
||||
useMaterial3: true,
|
||||
colorScheme: colorScheme,
|
||||
scaffoldBackgroundColor: const Color(0xFFF6F8F9),
|
||||
appBarTheme: const AppBarTheme(
|
||||
centerTitle: false,
|
||||
backgroundColor: Color(0xFFF6F8F9),
|
||||
surfaceTintColor: Colors.transparent,
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
filled: true,
|
||||
fillColor: Colors.white,
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: Color(0xFFD7DEDF)),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: Color(0xFFD7DEDF)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: _brandColor, width: 2),
|
||||
),
|
||||
),
|
||||
filledButtonTheme: FilledButtonThemeData(
|
||||
style: FilledButton.styleFrom(
|
||||
minimumSize: const Size.fromHeight(52),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
textStyle: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
|
||||
abstract interface class AppVersionProvider {
|
||||
Future<String> getVersion();
|
||||
}
|
||||
|
||||
class PackageInfoAppVersionProvider implements AppVersionProvider {
|
||||
const PackageInfoAppVersionProvider();
|
||||
|
||||
@override
|
||||
Future<String> getVersion() async {
|
||||
final packageInfo = await PackageInfo.fromPlatform();
|
||||
return packageInfo.version;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
|
||||
import '../../domain/entities/pos_device.dart';
|
||||
|
||||
abstract interface class PosDeviceProvider {
|
||||
Future<PosDevice> getDevice();
|
||||
}
|
||||
|
||||
class PlatformPosDeviceProvider implements PosDeviceProvider {
|
||||
PlatformPosDeviceProvider({DeviceInfoPlugin? plugin})
|
||||
: _plugin = plugin ?? DeviceInfoPlugin();
|
||||
|
||||
final DeviceInfoPlugin _plugin;
|
||||
|
||||
@override
|
||||
Future<PosDevice> getDevice() async {
|
||||
if (!Platform.isAndroid) {
|
||||
return PosDevice(platform: Platform.operatingSystem);
|
||||
}
|
||||
final info = await _plugin.androidInfo;
|
||||
return PosDevice(
|
||||
platform: 'android',
|
||||
serial: info.id,
|
||||
model: info.model,
|
||||
brand: info.brand,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
class ServerUrlValidator {
|
||||
ServerUrlValidator._();
|
||||
|
||||
static String? validate(String value, {bool requireHttps = false}) {
|
||||
final trimmed = value.trim();
|
||||
if (trimmed.isEmpty) {
|
||||
return 'Informe a URL do servidor.';
|
||||
}
|
||||
|
||||
final uri = Uri.tryParse(trimmed);
|
||||
if (uri == null || !uri.hasAuthority || uri.host.isEmpty) {
|
||||
return 'Informe uma URL válida, incluindo o host.';
|
||||
}
|
||||
if (uri.scheme != 'https' && uri.scheme != 'http') {
|
||||
return 'A URL deve usar HTTP ou HTTPS.';
|
||||
}
|
||||
if (requireHttps && uri.scheme != 'https') {
|
||||
return 'Use uma URL HTTPS para proteger a conexão.';
|
||||
}
|
||||
if (uri.userInfo.isNotEmpty || uri.hasFragment) {
|
||||
return 'A URL não pode conter credenciais ou fragmentos.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
|
||||
abstract interface class SecureSessionStorage {
|
||||
Future<String?> readCookie();
|
||||
|
||||
Future<String?> readServerUrl();
|
||||
|
||||
Future<String?> readSessionId();
|
||||
|
||||
Future<void> writeSession(
|
||||
{required String cookie,
|
||||
required String serverUrl,
|
||||
required String sessionId});
|
||||
|
||||
Future<void> clearCookie();
|
||||
}
|
||||
|
||||
class FlutterSecureSessionStorage implements SecureSessionStorage {
|
||||
FlutterSecureSessionStorage({FlutterSecureStorage? storage})
|
||||
: _storage = storage ?? const FlutterSecureStorage();
|
||||
|
||||
static const _cookieKey = 'pdv.odoo_session_cookie';
|
||||
static const _serverUrlKey = 'pdv.odoo_session_server_url';
|
||||
static const _sessionIdKey = 'pdv.odoo_session_id';
|
||||
final FlutterSecureStorage _storage;
|
||||
|
||||
@override
|
||||
Future<String?> readCookie() => _storage.read(key: _cookieKey);
|
||||
|
||||
@override
|
||||
Future<String?> readServerUrl() => _storage.read(key: _serverUrlKey);
|
||||
|
||||
@override
|
||||
Future<String?> readSessionId() => _storage.read(key: _sessionIdKey);
|
||||
|
||||
@override
|
||||
Future<void> writeSession(
|
||||
{required String cookie,
|
||||
required String serverUrl,
|
||||
required String sessionId}) async {
|
||||
await _storage.write(key: _cookieKey, value: cookie);
|
||||
await _storage.write(key: _serverUrlKey, value: serverUrl);
|
||||
await _storage.write(key: _sessionIdKey, value: sessionId);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearCookie() async {
|
||||
await _storage.delete(key: _cookieKey);
|
||||
await _storage.delete(key: _serverUrlKey);
|
||||
await _storage.delete(key: _sessionIdKey);
|
||||
}
|
||||
}
|
||||
|
||||
class InMemorySessionStorage implements SecureSessionStorage {
|
||||
String? _cookie;
|
||||
String? _serverUrl;
|
||||
String? _sessionId;
|
||||
|
||||
@override
|
||||
Future<String?> readCookie() async => _cookie;
|
||||
|
||||
@override
|
||||
Future<String?> readServerUrl() async => _serverUrl;
|
||||
|
||||
@override
|
||||
Future<String?> readSessionId() async => _sessionId;
|
||||
|
||||
@override
|
||||
Future<void> writeSession({
|
||||
required String cookie,
|
||||
required String serverUrl,
|
||||
required String sessionId,
|
||||
}) async {
|
||||
_cookie = cookie;
|
||||
_serverUrl = serverUrl;
|
||||
_sessionId = sessionId;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearCookie() async {
|
||||
_cookie = null;
|
||||
_serverUrl = null;
|
||||
_sessionId = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'secure_session_storage.dart';
|
||||
|
||||
SecureSessionStorage createSessionStorage() {
|
||||
if (Platform.isAndroid || Platform.isIOS) {
|
||||
return FlutterSecureSessionStorage();
|
||||
}
|
||||
if (kDebugMode) {
|
||||
return InMemorySessionStorage();
|
||||
}
|
||||
throw UnsupportedError(
|
||||
'O armazenamento seguro de sessão só está disponível em Android/iOS.',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
class CurrencyFormatter {
|
||||
CurrencyFormatter._();
|
||||
|
||||
static String formatBrl(int? minorUnits) {
|
||||
if (minorUnits == null) return 'Preço indisponível';
|
||||
|
||||
final negative = minorUnits < 0;
|
||||
final value = minorUnits.abs();
|
||||
final whole = value ~/ 100;
|
||||
final cents = (value % 100).toString().padLeft(2, '0');
|
||||
final groupedWhole = _groupThousands(whole.toString());
|
||||
final sign = negative ? '-' : '';
|
||||
return '${sign}R\$ $groupedWhole,$cents';
|
||||
}
|
||||
|
||||
static String _groupThousands(String digits) {
|
||||
final groups = <String>[];
|
||||
for (var end = digits.length; end > 0; end -= 3) {
|
||||
final start = end - 3 < 0 ? 0 : end - 3;
|
||||
groups.insert(0, digits.substring(start, end));
|
||||
}
|
||||
return groups.join('.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AppButton extends StatelessWidget {
|
||||
const AppButton({
|
||||
required this.label,
|
||||
required this.onPressed,
|
||||
this.icon,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final VoidCallback? onPressed;
|
||||
final IconData? icon;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FilledButton.icon(
|
||||
onPressed: onPressed,
|
||||
icon: Icon(icon ?? Icons.arrow_forward),
|
||||
label: Text(label),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AppTextField extends StatelessWidget {
|
||||
const AppTextField({
|
||||
required this.label,
|
||||
this.controller,
|
||||
this.obscureText = false,
|
||||
this.keyboardType,
|
||||
this.textInputAction,
|
||||
this.prefixIcon,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final TextEditingController? controller;
|
||||
final bool obscureText;
|
||||
final TextInputType? keyboardType;
|
||||
final TextInputAction? textInputAction;
|
||||
final IconData? prefixIcon;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TextField(
|
||||
controller: controller,
|
||||
obscureText: obscureText,
|
||||
keyboardType: keyboardType,
|
||||
textInputAction: textInputAction,
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
prefixIcon: prefixIcon == null ? null : Icon(prefixIcon),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class EmptyView extends StatelessWidget {
|
||||
const EmptyView({
|
||||
required this.title,
|
||||
required this.message,
|
||||
this.icon = Icons.inbox_outlined,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String message;
|
||||
final IconData icon;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 48, color: Theme.of(context).colorScheme.outline),
|
||||
const SizedBox(height: 12),
|
||||
Text(title, style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 4),
|
||||
Text(message, textAlign: TextAlign.center),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ErrorView extends StatelessWidget {
|
||||
const ErrorView({
|
||||
required this.message,
|
||||
this.onRetry,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final String message;
|
||||
final VoidCallback? onRetry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.cloud_off_outlined,
|
||||
size: 40,
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(message, textAlign: TextAlign.center),
|
||||
if (onRetry != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
TextButton.icon(
|
||||
onPressed: onRetry,
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('Tentar novamente'),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class LoadingView extends StatelessWidget {
|
||||
const LoadingView({this.message = 'Carregando...', super.key});
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const CircularProgressIndicator(),
|
||||
const SizedBox(height: 16),
|
||||
Text(message),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
class OdooApiUriBuilder {
|
||||
OdooApiUriBuilder._();
|
||||
|
||||
static Uri endpoint(Uri serverUri, String endpointPath) {
|
||||
final basePath = serverUri.path.replaceFirst(RegExp(r'/+$'), '');
|
||||
final normalizedEndpoint =
|
||||
endpointPath.startsWith('/') ? endpointPath : '/$endpointPath';
|
||||
return Uri(
|
||||
scheme: serverUri.scheme,
|
||||
host: serverUri.host,
|
||||
port: serverUri.hasPort ? serverUri.port : null,
|
||||
path: '$basePath$normalizedEndpoint',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../../domain/repositories/connection_tester.dart';
|
||||
import 'odoo_api_uri_builder.dart';
|
||||
|
||||
class OdooConnectionTester implements ConnectionTester {
|
||||
OdooConnectionTester({http.Client? client})
|
||||
: _client = client ?? http.Client();
|
||||
|
||||
static const _timeout = Duration(seconds: 10);
|
||||
final http.Client _client;
|
||||
|
||||
@override
|
||||
Future<ConnectionTestResult> test(Uri serverUri) async {
|
||||
final healthUri = OdooApiUriBuilder.endpoint(serverUri, '/pdv_pos/health');
|
||||
try {
|
||||
final request = http.Request('GET', healthUri)
|
||||
..followRedirects = false
|
||||
..headers['Accept'] = 'application/json';
|
||||
final response = await _client
|
||||
.send(request)
|
||||
.then(http.Response.fromStream)
|
||||
.timeout(_timeout);
|
||||
if (response.statusCode != HttpStatus.ok) {
|
||||
return ConnectionTestResult(
|
||||
isAvailable: false,
|
||||
message: 'O servidor respondeu com erro HTTP ${response.statusCode}.',
|
||||
);
|
||||
}
|
||||
|
||||
final body = jsonDecode(response.body);
|
||||
if (body is Map<String, dynamic> &&
|
||||
body['status'] == 'ok' &&
|
||||
body['api_version'] == 1) {
|
||||
return const ConnectionTestResult(
|
||||
isAvailable: true,
|
||||
message: 'Conexão com o servidor estabelecida.',
|
||||
);
|
||||
}
|
||||
|
||||
return const ConnectionTestResult(
|
||||
isAvailable: false,
|
||||
message: 'O servidor não confirmou a disponibilidade da API PDV.',
|
||||
);
|
||||
} on TimeoutException {
|
||||
return const ConnectionTestResult(
|
||||
isAvailable: false,
|
||||
message: 'Tempo esgotado ao conectar ao servidor.',
|
||||
);
|
||||
} on SocketException {
|
||||
return const ConnectionTestResult(
|
||||
isAvailable: false,
|
||||
message: 'Não foi possível alcançar o servidor.',
|
||||
);
|
||||
} on FormatException {
|
||||
return const ConnectionTestResult(
|
||||
isAvailable: false,
|
||||
message: 'O servidor retornou uma resposta inválida.',
|
||||
);
|
||||
} catch (_) {
|
||||
return const ConnectionTestResult(
|
||||
isAvailable: false,
|
||||
message: 'Não foi possível testar a conexão com o servidor.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../../core/storage/secure_session_storage.dart';
|
||||
import '../../../domain/repositories/auth_repository.dart';
|
||||
import '../../../domain/repositories/settings_repository.dart';
|
||||
import 'odoo_api_uri_builder.dart';
|
||||
|
||||
class OdooSessionApiClient {
|
||||
OdooSessionApiClient({
|
||||
required AuthRepository authRepository,
|
||||
required SettingsRepository settingsRepository,
|
||||
required SecureSessionStorage sessionStorage,
|
||||
http.Client? client,
|
||||
}) : _authRepository = authRepository,
|
||||
_settingsRepository = settingsRepository,
|
||||
_sessionStorage = sessionStorage,
|
||||
_client = client ?? http.Client();
|
||||
|
||||
static const _timeout = Duration(seconds: 60);
|
||||
final AuthRepository _authRepository;
|
||||
final SettingsRepository _settingsRepository;
|
||||
final SecureSessionStorage _sessionStorage;
|
||||
final http.Client _client;
|
||||
|
||||
Future<Map<String, dynamic>> getJson(
|
||||
String endpoint, {
|
||||
Map<String, String> query = const {},
|
||||
}) =>
|
||||
_request('GET', endpoint, query: query);
|
||||
|
||||
Future<Map<String, dynamic>> postForm(
|
||||
String endpoint, {
|
||||
required Map<String, String> body,
|
||||
Duration? timeout,
|
||||
}) =>
|
||||
_request('POST', endpoint, body: body, requestTimeout: timeout);
|
||||
|
||||
Future<Map<String, dynamic>> _request(
|
||||
String method,
|
||||
String endpoint, {
|
||||
Map<String, String> query = const {},
|
||||
Map<String, String> body = const {},
|
||||
Duration? requestTimeout,
|
||||
}) async {
|
||||
if (!_authRepository.isAuthenticated ||
|
||||
_authRepository.currentSession == null) {
|
||||
throw const OdooApiException(
|
||||
'session_required',
|
||||
'A sessão expirou. Entre novamente.',
|
||||
);
|
||||
}
|
||||
|
||||
final settings = await _settingsRepository.load();
|
||||
if (settings?.isConfigured != true) {
|
||||
throw const OdooApiException(
|
||||
'configuration_required',
|
||||
'Configure o servidor antes de continuar.',
|
||||
);
|
||||
}
|
||||
|
||||
final cookie = await _sessionStorage.readCookie();
|
||||
final sessionId = await _sessionStorage.readSessionId();
|
||||
if (cookie == null || sessionId == null) {
|
||||
throw const OdooApiException(
|
||||
'session_required',
|
||||
'A sessão do servidor não está disponível. Entre novamente.',
|
||||
);
|
||||
}
|
||||
|
||||
final endpointUri = OdooApiUriBuilder.endpoint(
|
||||
Uri.parse(settings!.serverUrl),
|
||||
endpoint,
|
||||
);
|
||||
final uri = method == 'GET'
|
||||
? endpointUri.replace(
|
||||
queryParameters: {'session_id': sessionId, ...query},
|
||||
)
|
||||
: endpointUri;
|
||||
final request = http.Request(method, uri)
|
||||
..followRedirects = false
|
||||
..headers['Accept'] = 'application/json'
|
||||
..headers['Cookie'] = cookie;
|
||||
if (method == 'POST') {
|
||||
request
|
||||
..headers['Content-Type'] =
|
||||
'application/x-www-form-urlencoded; charset=utf-8'
|
||||
..body = Uri(queryParameters: {'session_id': sessionId, ...body}).query;
|
||||
}
|
||||
|
||||
try {
|
||||
final response = await _client
|
||||
.send(request)
|
||||
.then(http.Response.fromStream)
|
||||
.timeout(requestTimeout ?? _timeout);
|
||||
if (response.statusCode != HttpStatus.ok) {
|
||||
throw OdooApiException(
|
||||
'http_error',
|
||||
'O servidor respondeu com erro HTTP ${response.statusCode}.',
|
||||
);
|
||||
}
|
||||
|
||||
final decoded = jsonDecode(response.body);
|
||||
if (decoded is! Map<String, dynamic>) {
|
||||
throw const OdooApiException(
|
||||
'invalid_response',
|
||||
'O servidor retornou uma resposta inválida.',
|
||||
);
|
||||
}
|
||||
if (decoded['status'] != 'ok') {
|
||||
final code = decoded['code'];
|
||||
final message = decoded['message'];
|
||||
throw OdooApiException(
|
||||
code is String ? code : 'api_error',
|
||||
message is String ? message : 'O servidor não concluiu a operação.',
|
||||
);
|
||||
}
|
||||
return decoded;
|
||||
} on TimeoutException {
|
||||
throw const OdooApiException(
|
||||
'timeout',
|
||||
'Tempo esgotado ao consultar o servidor.',
|
||||
);
|
||||
} on SocketException {
|
||||
throw const OdooApiException(
|
||||
'network_error',
|
||||
'Não foi possível alcançar o servidor.',
|
||||
);
|
||||
} on OdooApiException {
|
||||
rethrow;
|
||||
} on FormatException {
|
||||
throw const OdooApiException(
|
||||
'invalid_response',
|
||||
'O servidor retornou dados inválidos.',
|
||||
);
|
||||
} catch (_) {
|
||||
throw const OdooApiException(
|
||||
'network_error',
|
||||
'Falha de comunicação com o servidor.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class OdooApiException implements Exception {
|
||||
const OdooApiException(this.code, this.message);
|
||||
|
||||
final String code;
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:developer' as developer;
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../core/storage/secure_session_storage.dart';
|
||||
import '../../domain/entities/app_settings.dart';
|
||||
import '../../domain/entities/app_session.dart';
|
||||
import '../../domain/entities/pos_device.dart';
|
||||
import '../../domain/repositories/auth_repository.dart';
|
||||
import '../datasources/remote/odoo_api_uri_builder.dart';
|
||||
|
||||
class OdooAuthRepository implements AuthRepository {
|
||||
OdooAuthRepository({
|
||||
required SecureSessionStorage sessionStorage,
|
||||
http.Client? client,
|
||||
}) : _sessionStorage = sessionStorage,
|
||||
_client = client ?? http.Client();
|
||||
|
||||
static const _requestTimeout = Duration(seconds: 60);
|
||||
final SecureSessionStorage _sessionStorage;
|
||||
final http.Client _client;
|
||||
Uri? _activeServerUri;
|
||||
bool _isAuthenticated = false;
|
||||
AppSession? _currentSession;
|
||||
|
||||
@override
|
||||
bool get isAuthenticated => _isAuthenticated;
|
||||
|
||||
@override
|
||||
AppSession? get currentSession => _currentSession;
|
||||
|
||||
@override
|
||||
Future<AppSession> authenticate({
|
||||
required String username,
|
||||
required String password,
|
||||
required AppSettings settings,
|
||||
required PosDevice device,
|
||||
required String appVersion,
|
||||
}) async {
|
||||
if (await _sessionStorage.readCookie() != null) {
|
||||
await logout();
|
||||
}
|
||||
_isAuthenticated = false;
|
||||
_currentSession = null;
|
||||
final serverUri = Uri.parse(settings.serverUrl);
|
||||
final endpoint = OdooApiUriBuilder.endpoint(serverUri, '/pdv_pos/logar');
|
||||
final response = await _sendPost(
|
||||
endpoint,
|
||||
body: {
|
||||
'cnpj': settings.companyIdentifier,
|
||||
'username': username,
|
||||
'password': password,
|
||||
'platform': device.platform,
|
||||
if (device.serial != null) 'serial': device.serial!,
|
||||
if (device.model != null) 'model': device.model!,
|
||||
if (device.brand != null) 'brand': device.brand!,
|
||||
'version': appVersion,
|
||||
},
|
||||
);
|
||||
|
||||
final payload = _decodeResponse(response);
|
||||
if (payload['status'] != 'ok') {
|
||||
final message = payload['message'];
|
||||
throw AuthUnavailableException(
|
||||
message is String
|
||||
? message
|
||||
: 'Não foi possível autenticar no servidor.',
|
||||
);
|
||||
}
|
||||
|
||||
final cookie = _sessionCookie(response.headers['set-cookie']);
|
||||
final sessionId = payload['session_id'];
|
||||
if (cookie == null || sessionId is! String || sessionId.isEmpty) {
|
||||
throw const AuthUnavailableException(
|
||||
'O servidor não iniciou uma sessão segura para o PDV.',
|
||||
);
|
||||
}
|
||||
|
||||
await _sessionStorage.writeSession(
|
||||
cookie: cookie,
|
||||
serverUrl: settings.serverUrl,
|
||||
sessionId: sessionId,
|
||||
);
|
||||
final user = payload['user'];
|
||||
final userId = user is Map ? user['id'] : null;
|
||||
if (userId is! num) {
|
||||
await _sessionStorage.clearCookie();
|
||||
throw const AuthUnavailableException(
|
||||
'O servidor não retornou os dados do operador.',
|
||||
);
|
||||
}
|
||||
final companyIdValue = payload['company_id'];
|
||||
final companyNameValue = payload['company_name'];
|
||||
_currentSession = AppSession(
|
||||
userId: userId.toInt(),
|
||||
userName: user['name'] is String ? user['name'] as String : username,
|
||||
companyId: companyIdValue is num ? companyIdValue.toInt() : null,
|
||||
companyName: companyNameValue is String ? companyNameValue : null,
|
||||
);
|
||||
_activeServerUri = serverUri;
|
||||
_isAuthenticated = true;
|
||||
return _currentSession!;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> logout() async {
|
||||
var serverUri = _activeServerUri;
|
||||
final cookie = await _sessionStorage.readCookie();
|
||||
final sessionId = await _sessionStorage.readSessionId();
|
||||
if (serverUri == null) {
|
||||
final storedServerUrl = await _sessionStorage.readServerUrl();
|
||||
if (storedServerUrl != null) serverUri = Uri.tryParse(storedServerUrl);
|
||||
}
|
||||
try {
|
||||
if (serverUri != null && cookie != null && sessionId != null) {
|
||||
await _sendPost(
|
||||
OdooApiUriBuilder.endpoint(serverUri, '/pdv_pos/logout'),
|
||||
body: {'session_id': sessionId},
|
||||
cookie: cookie,
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
// Local credentials are cleared even if the server cannot be reached.
|
||||
} finally {
|
||||
await _sessionStorage.clearCookie();
|
||||
_activeServerUri = null;
|
||||
_isAuthenticated = false;
|
||||
_currentSession = null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<http.Response> _sendPost(
|
||||
Uri uri, {
|
||||
required Map<String, String> body,
|
||||
String? cookie,
|
||||
}) async {
|
||||
final request = http.Request('POST', uri)
|
||||
..followRedirects = false
|
||||
..headers['Accept'] = 'application/json'
|
||||
..headers['Content-Type'] =
|
||||
'application/x-www-form-urlencoded; charset=utf-8'
|
||||
..body = Uri(queryParameters: body).query;
|
||||
if (cookie != null) request.headers['Cookie'] = cookie;
|
||||
developer.log('Enviando chamada HTTP ${request.method} ${uri.path}.',
|
||||
name: 'pdv.auth');
|
||||
|
||||
try {
|
||||
final response = await _client
|
||||
.send(request)
|
||||
.then(http.Response.fromStream)
|
||||
.timeout(_requestTimeout);
|
||||
if (response.statusCode != HttpStatus.ok) {
|
||||
developer.log(
|
||||
'Resposta HTTP ${response.statusCode} em ${uri.path}.',
|
||||
name: 'pdv.auth',
|
||||
);
|
||||
throw const AuthUnavailableException(
|
||||
'O servidor não conseguiu processar a solicitação do PDV.',
|
||||
);
|
||||
}
|
||||
return response;
|
||||
} on TimeoutException {
|
||||
developer.log('Timeout na chamada HTTP ${uri.path}.', name: 'pdv.auth');
|
||||
throw const AuthUnavailableException(
|
||||
'Tempo esgotado ao comunicar com o servidor.',
|
||||
);
|
||||
} on SocketException {
|
||||
developer.log('Falha de socket na chamada HTTP ${uri.path}.',
|
||||
name: 'pdv.auth');
|
||||
throw const AuthUnavailableException(
|
||||
'Não foi possível alcançar o servidor.',
|
||||
);
|
||||
} on AuthUnavailableException {
|
||||
rethrow;
|
||||
} catch (error, stackTrace) {
|
||||
developer.log(
|
||||
'Falha HTTP ${uri.path}: ${error.runtimeType}.',
|
||||
name: 'pdv.auth',
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
throw const AuthUnavailableException(
|
||||
'Falha de comunicação com o servidor.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _decodeResponse(http.Response response) {
|
||||
try {
|
||||
final decoded = jsonDecode(response.body);
|
||||
if (decoded is Map<String, dynamic>) return decoded;
|
||||
} on FormatException {
|
||||
// Mapped below to a safe protocol error.
|
||||
}
|
||||
throw const AuthUnavailableException(
|
||||
'O servidor retornou uma resposta inválida.',
|
||||
);
|
||||
}
|
||||
|
||||
String? _sessionCookie(String? setCookieHeader) {
|
||||
if (setCookieHeader == null) return null;
|
||||
final cookie = setCookieHeader.split(';').first.trim();
|
||||
return cookie.startsWith('sid=') && cookie.length > 4 ? cookie : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import '../../domain/entities/department.dart';
|
||||
import '../../domain/entities/product.dart';
|
||||
import '../../domain/repositories/catalog_repository.dart';
|
||||
import '../datasources/remote/odoo_session_api_client.dart';
|
||||
|
||||
class OdooCatalogRepository implements CatalogRepository {
|
||||
const OdooCatalogRepository({required this.apiClient});
|
||||
|
||||
final OdooSessionApiClient apiClient;
|
||||
|
||||
@override
|
||||
Future<List<Department>> fetchDepartments() async {
|
||||
try {
|
||||
final payload = await apiClient.getJson('/pdv_pos/departamentos');
|
||||
final records = payload['departments'];
|
||||
if (records is! List) {
|
||||
throw const CatalogException('Resposta de departamentos inválida.');
|
||||
}
|
||||
return records
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(Department.fromJson)
|
||||
.toList(growable: false);
|
||||
} on OdooApiException catch (error) {
|
||||
throw CatalogException(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<Product>> fetchProductsByDepartment(int departmentId) async {
|
||||
try {
|
||||
final payload = await apiClient.getJson(
|
||||
'/pdv_pos/produtos_por_departamento',
|
||||
query: {'department_id': departmentId.toString()},
|
||||
);
|
||||
final records = payload['products'];
|
||||
if (records is! List) {
|
||||
throw const CatalogException('Resposta de produtos inválida.');
|
||||
}
|
||||
return records
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(Product.fromJson)
|
||||
.toList(growable: false);
|
||||
} on OdooApiException catch (error) {
|
||||
throw CatalogException(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Product?> fetchProductByBarcode(String barcode) async {
|
||||
try {
|
||||
final payload = await apiClient.getJson(
|
||||
'/pdv_pos/produto_por_codigo_barra',
|
||||
query: {'barcode': barcode},
|
||||
);
|
||||
final record = payload['product'];
|
||||
if (record == null) return null;
|
||||
if (record is! Map<String, dynamic>) {
|
||||
throw const CatalogException('Resposta de produto inválida.');
|
||||
}
|
||||
return Product.fromJson(record);
|
||||
} on OdooApiException catch (error) {
|
||||
throw CatalogException(error.message);
|
||||
} on FormatException {
|
||||
throw const CatalogException('O servidor retornou um produto inválido.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import '../../domain/entities/customer.dart';
|
||||
import '../../domain/repositories/customer_repository.dart';
|
||||
import '../datasources/remote/odoo_session_api_client.dart';
|
||||
|
||||
class OdooCustomerRepository implements CustomerRepository {
|
||||
const OdooCustomerRepository({required this.apiClient});
|
||||
|
||||
final OdooSessionApiClient apiClient;
|
||||
|
||||
@override
|
||||
Future<List<Customer>> search(String query) async {
|
||||
try {
|
||||
final payload = await apiClient.postForm(
|
||||
'/pdv_pos/clientes',
|
||||
body: {'query': query.trim()},
|
||||
);
|
||||
final records = payload['customers'];
|
||||
if (records is! List) {
|
||||
throw const CustomerSearchException('Resposta de clientes inválida.');
|
||||
}
|
||||
return records
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(Customer.fromJson)
|
||||
.toList(growable: false);
|
||||
} on OdooApiException catch (error) {
|
||||
throw CustomerSearchException(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import '../../domain/entities/payment_method.dart';
|
||||
import '../../domain/repositories/payment_methods_repository.dart';
|
||||
import '../datasources/remote/odoo_session_api_client.dart';
|
||||
|
||||
class OdooPaymentMethodsRepository implements PaymentMethodsRepository {
|
||||
const OdooPaymentMethodsRepository({required this.apiClient});
|
||||
|
||||
final OdooSessionApiClient apiClient;
|
||||
|
||||
@override
|
||||
Future<List<PaymentMethod>> loadAvailable() async {
|
||||
try {
|
||||
final payload = await apiClient.getJson('/pdv_pos/formas_pagamento');
|
||||
final records = payload['payment_methods'];
|
||||
if (records is! List) {
|
||||
throw const PaymentMethodsException(
|
||||
'Resposta de formas de pagamento inválida.',
|
||||
);
|
||||
}
|
||||
return records
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(PaymentMethod.fromJson)
|
||||
.toList(growable: false);
|
||||
} on OdooApiException catch (error) {
|
||||
throw PaymentMethodsException(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import '../../domain/entities/cart_item.dart';
|
||||
import '../../domain/entities/customer.dart';
|
||||
import '../../domain/entities/sale_completion.dart';
|
||||
import '../../domain/entities/sale_payment.dart';
|
||||
import '../../domain/repositories/sale_checkout_repository.dart';
|
||||
import '../datasources/remote/odoo_session_api_client.dart';
|
||||
|
||||
class OdooSaleCheckoutRepository implements SaleCheckoutRepository {
|
||||
const OdooSaleCheckoutRepository({required this.apiClient});
|
||||
|
||||
final OdooSessionApiClient apiClient;
|
||||
|
||||
@override
|
||||
Future<SaleCompletion> finalizeCashSale({
|
||||
required List<CartItem> items,
|
||||
required List<SalePayment> payments,
|
||||
Customer? customer,
|
||||
String? customerCpf,
|
||||
required String checkoutKey,
|
||||
}) async {
|
||||
try {
|
||||
final itemPayload = items.map((item) {
|
||||
final price = item.product.priceMinorUnits;
|
||||
if (price == null || item.product.gradeId <= 0) {
|
||||
throw const SaleCheckoutException(
|
||||
'invalid_item',
|
||||
'Um produto não possui preço ou grade válida.',
|
||||
);
|
||||
}
|
||||
return {
|
||||
'product_id': item.product.id,
|
||||
'grade_id': item.product.gradeId,
|
||||
'quantity': item.quantity,
|
||||
'unit_price_minor_units': price,
|
||||
};
|
||||
}).toList(growable: false);
|
||||
|
||||
final payload = await apiClient.postForm(
|
||||
'/pdv_pos/finalizar_venda',
|
||||
body: {
|
||||
'checkout_key': checkoutKey,
|
||||
'customer_id': customer?.id.toString() ?? '',
|
||||
'customer_cpf': customerCpf ?? '',
|
||||
'amount_minor_units': payments
|
||||
.fold<int>(0, (sum, payment) => sum + payment.amountMinorUnits)
|
||||
.toString(),
|
||||
'items': jsonEncode(itemPayload),
|
||||
'payments': jsonEncode(payments
|
||||
.map((payment) => {
|
||||
'condition_form_id': payment.conditionFormId,
|
||||
'amount_minor_units': payment.amountMinorUnits,
|
||||
'payment_type': payment.paymentType,
|
||||
})
|
||||
.toList(growable: false)),
|
||||
},
|
||||
timeout: const Duration(minutes: 3),
|
||||
);
|
||||
final sale = payload['sale'];
|
||||
if (sale is! Map<String, dynamic>) {
|
||||
throw const SaleCheckoutException(
|
||||
'invalid_response',
|
||||
'O servidor não retornou os dados da NFC-e.',
|
||||
);
|
||||
}
|
||||
return SaleCompletion.fromJson(sale);
|
||||
} on SaleCheckoutException {
|
||||
rethrow;
|
||||
} on OdooApiException catch (error) {
|
||||
throw SaleCheckoutException(error.code, error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import '../../domain/entities/historical_sale.dart';
|
||||
import '../../domain/repositories/sales_history_repository.dart';
|
||||
import '../datasources/remote/odoo_session_api_client.dart';
|
||||
|
||||
class OdooSalesHistoryRepository implements SalesHistoryRepository {
|
||||
const OdooSalesHistoryRepository({required this.apiClient});
|
||||
|
||||
final OdooSessionApiClient apiClient;
|
||||
|
||||
@override
|
||||
Future<List<HistoricalSale>> fetchSales() async {
|
||||
try {
|
||||
final payload = await apiClient.getJson('/pdv_pos/historico_vendas');
|
||||
final records = payload['sales'];
|
||||
if (records is! List) {
|
||||
throw const SalesHistoryException(
|
||||
'O servidor retornou um histórico inválido.',
|
||||
);
|
||||
}
|
||||
return records
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(HistoricalSale.fromJson)
|
||||
.toList(growable: false);
|
||||
} on OdooApiException catch (error) {
|
||||
throw SalesHistoryException(error.message);
|
||||
} on FormatException {
|
||||
throw const SalesHistoryException(
|
||||
'O servidor retornou dados inválidos no histórico.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../domain/entities/sale_view_mode.dart';
|
||||
import '../../domain/repositories/sale_view_preference_repository.dart';
|
||||
|
||||
class SharedPreferencesSaleViewPreferenceRepository
|
||||
implements SaleViewPreferenceRepository {
|
||||
const SharedPreferencesSaleViewPreferenceRepository();
|
||||
|
||||
static const _keyPrefix = 'pdv.sale_view.user.';
|
||||
|
||||
@override
|
||||
Future<SaleViewMode> loadForUser(int userId) async {
|
||||
final preferences = await SharedPreferences.getInstance();
|
||||
final value = preferences.getString('$_keyPrefix$userId');
|
||||
return value == SaleViewMode.list.name
|
||||
? SaleViewMode.list
|
||||
: SaleViewMode.kanban;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> saveForUser(int userId, SaleViewMode mode) async {
|
||||
final preferences = await SharedPreferences.getInstance();
|
||||
await preferences.setString('$_keyPrefix$userId', mode.name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../domain/entities/app_settings.dart';
|
||||
import '../../domain/repositories/settings_repository.dart';
|
||||
|
||||
class SharedPreferencesSettingsRepository implements SettingsRepository {
|
||||
const SharedPreferencesSettingsRepository();
|
||||
|
||||
static const _serverUrlKey = 'pdv.server_url';
|
||||
static const _companyIdentifierKey = 'pdv.company_identifier';
|
||||
|
||||
@override
|
||||
Future<AppSettings?> load() async {
|
||||
final preferences = await SharedPreferences.getInstance();
|
||||
final serverUrl = preferences.getString(_serverUrlKey);
|
||||
final companyIdentifier = preferences.getString(_companyIdentifierKey);
|
||||
if (serverUrl == null || companyIdentifier == null) return null;
|
||||
|
||||
return AppSettings(
|
||||
serverUrl: serverUrl,
|
||||
companyIdentifier: companyIdentifier,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save(AppSettings settings) async {
|
||||
final preferences = await SharedPreferences.getInstance();
|
||||
await preferences.setString(_serverUrlKey, settings.serverUrl);
|
||||
await preferences.setString(
|
||||
_companyIdentifierKey,
|
||||
settings.companyIdentifier,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
class AppSession {
|
||||
const AppSession({
|
||||
required this.userId,
|
||||
required this.userName,
|
||||
this.companyId,
|
||||
this.companyName,
|
||||
});
|
||||
|
||||
final int userId;
|
||||
final String userName;
|
||||
final int? companyId;
|
||||
final String? companyName;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
class AppSettings {
|
||||
const AppSettings({
|
||||
required this.serverUrl,
|
||||
required this.companyIdentifier,
|
||||
});
|
||||
|
||||
final String serverUrl;
|
||||
final String companyIdentifier;
|
||||
|
||||
bool get isConfigured => serverUrl.isNotEmpty && companyIdentifier.isNotEmpty;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is AppSettings &&
|
||||
other.serverUrl == serverUrl &&
|
||||
other.companyIdentifier == companyIdentifier;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(serverUrl, companyIdentifier);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'product.dart';
|
||||
|
||||
class CartItem {
|
||||
const CartItem({required this.product, required this.quantity});
|
||||
|
||||
final Product product;
|
||||
final int quantity;
|
||||
|
||||
int? get subtotalMinorUnits {
|
||||
final unitPrice = product.priceMinorUnits;
|
||||
return unitPrice == null ? null : unitPrice * quantity;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
class Customer {
|
||||
const Customer({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.documentMasked,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final String name;
|
||||
final String documentMasked;
|
||||
|
||||
factory Customer.fromJson(Map<String, dynamic> json) {
|
||||
final id = json['id'];
|
||||
final name = json['name'];
|
||||
if (id is! num || name is! String) {
|
||||
throw const FormatException('Resposta de cliente inválida.');
|
||||
}
|
||||
return Customer(
|
||||
id: id.toInt(),
|
||||
name: name,
|
||||
documentMasked: json['document_masked']?.toString() ?? '',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
class Department {
|
||||
const Department({required this.id, required this.name});
|
||||
|
||||
final int id;
|
||||
final String name;
|
||||
|
||||
factory Department.fromJson(Map<String, dynamic> json) {
|
||||
final id = json['id'];
|
||||
final name = json['name'];
|
||||
if (id is! num || name is! String) {
|
||||
throw const FormatException('Resposta de departamento inválida.');
|
||||
}
|
||||
return Department(id: id.toInt(), name: name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
class HistoricalSale {
|
||||
const HistoricalSale({
|
||||
required this.orderNumber,
|
||||
required this.issueDate,
|
||||
required this.customerName,
|
||||
required this.totalMinorUnits,
|
||||
required this.state,
|
||||
});
|
||||
|
||||
final String orderNumber;
|
||||
final String issueDate;
|
||||
final String customerName;
|
||||
final int totalMinorUnits;
|
||||
final String state;
|
||||
|
||||
factory HistoricalSale.fromJson(Map<String, dynamic> json) {
|
||||
final orderNumber = json['order_number'];
|
||||
final issueDate = json['issue_date'];
|
||||
final customerName = json['customer_name'];
|
||||
final total = json['total'];
|
||||
final state = json['state'];
|
||||
if (orderNumber is! String ||
|
||||
issueDate is! String ||
|
||||
customerName is! String ||
|
||||
total is! num ||
|
||||
state is! String) {
|
||||
throw const FormatException('Pedido inválido no histórico de vendas.');
|
||||
}
|
||||
return HistoricalSale(
|
||||
orderNumber: orderNumber,
|
||||
issueDate: issueDate,
|
||||
customerName: customerName,
|
||||
totalMinorUnits: (total * 100).round(),
|
||||
state: state,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
class PaymentMethod {
|
||||
const PaymentMethod({
|
||||
required this.id,
|
||||
required this.name,
|
||||
this.paymentType,
|
||||
this.conditionId,
|
||||
this.conditionType,
|
||||
this.installments,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final String name;
|
||||
final String? paymentType;
|
||||
final int? conditionId;
|
||||
final String? conditionType;
|
||||
final int? installments;
|
||||
|
||||
factory PaymentMethod.fromJson(Map<String, dynamic> json) {
|
||||
final id = json['id'];
|
||||
final name = json['name'];
|
||||
if (id is! num || name is! String) {
|
||||
throw const FormatException('Resposta de forma de pagamento inválida.');
|
||||
}
|
||||
return PaymentMethod(
|
||||
id: id.toInt(),
|
||||
name: name,
|
||||
paymentType: json['payment_type']?.toString(),
|
||||
conditionId: _asInt(json['condition_id']),
|
||||
conditionType: json['condition_type']?.toString(),
|
||||
installments: _asInt(json['installments']),
|
||||
);
|
||||
}
|
||||
|
||||
static int? _asInt(dynamic value) => value is num ? value.toInt() : null;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
class PosDevice {
|
||||
const PosDevice({
|
||||
required this.platform,
|
||||
this.serial,
|
||||
this.model,
|
||||
this.brand,
|
||||
});
|
||||
|
||||
final String platform;
|
||||
final String? serial;
|
||||
final String? model;
|
||||
final String? brand;
|
||||
|
||||
bool get requiresLicense => platform.toLowerCase() == 'android';
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
class Product {
|
||||
const Product({
|
||||
required this.id,
|
||||
this.gradeId = 0,
|
||||
required this.code,
|
||||
required this.grade,
|
||||
required this.name,
|
||||
required this.departmentCode,
|
||||
required this.writeDate,
|
||||
this.priceMinorUnits,
|
||||
this.stock,
|
||||
this.imageBase64,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final int gradeId;
|
||||
final String code;
|
||||
final String grade;
|
||||
final String name;
|
||||
final int departmentCode;
|
||||
final String writeDate;
|
||||
final int? priceMinorUnits;
|
||||
final num? stock;
|
||||
final String? imageBase64;
|
||||
|
||||
String get cartKey => '$id:$grade';
|
||||
|
||||
factory Product.fromJson(Map<String, dynamic> json) {
|
||||
final id = json['id'];
|
||||
final departmentCode = json['departamento_id'];
|
||||
if (id is! num || departmentCode is! num) {
|
||||
throw const FormatException('Resposta de produto inválida.');
|
||||
}
|
||||
|
||||
return Product(
|
||||
id: id.toInt(),
|
||||
gradeId: json['grade_id'] is num ? (json['grade_id'] as num).toInt() : 0,
|
||||
code: json['codigo']?.toString() ?? '',
|
||||
grade: json['grade']?.toString() ?? '',
|
||||
name: json['descricao']?.toString() ?? '',
|
||||
departmentCode: departmentCode.toInt(),
|
||||
writeDate: json['write_date']?.toString() ?? '',
|
||||
priceMinorUnits: _toMinorUnits(json['preco']),
|
||||
stock: _number(json['qtdEmEstoque']),
|
||||
imageBase64: json['foto'] is String && (json['foto'] as String).isNotEmpty
|
||||
? json['foto'] as String
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
static int? _toMinorUnits(dynamic value) {
|
||||
if (value == null || value is bool) return null;
|
||||
final normalized = value.toString().replaceAll(',', '.');
|
||||
final match = RegExp(r'^(-?)(\d+)(?:\.(\d+))?$').firstMatch(normalized);
|
||||
if (match == null) return null;
|
||||
|
||||
final isNegative = match.group(1) == '-';
|
||||
final whole = int.tryParse(match.group(2)!);
|
||||
if (whole == null) return null;
|
||||
|
||||
final fraction = match.group(3) ?? '';
|
||||
final centsText = fraction.padRight(2, '0');
|
||||
var minorUnits = whole * 100 + int.parse(centsText.substring(0, 2));
|
||||
if (fraction.length > 2 && int.parse(fraction[2]) >= 5) minorUnits++;
|
||||
return isNegative ? -minorUnits : minorUnits;
|
||||
}
|
||||
|
||||
static num? _number(dynamic value) {
|
||||
if (value is num) return value;
|
||||
if (value is String) return num.tryParse(value.replaceAll(',', '.'));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
class SaleCompletion {
|
||||
const SaleCompletion({
|
||||
required this.orderNumber,
|
||||
required this.invoiceId,
|
||||
required this.invoiceNumber,
|
||||
required this.invoiceSeries,
|
||||
this.invoiceState = '',
|
||||
this.invoiceContingency = false,
|
||||
this.invoiceMessage = '',
|
||||
});
|
||||
|
||||
final String orderNumber;
|
||||
final int invoiceId;
|
||||
final String invoiceNumber;
|
||||
final String invoiceSeries;
|
||||
final String invoiceState;
|
||||
final bool invoiceContingency;
|
||||
final String invoiceMessage;
|
||||
|
||||
factory SaleCompletion.fromJson(Map<String, dynamic> json) {
|
||||
final orderNumber = json['order_number'];
|
||||
final invoiceId = json['invoice_id'];
|
||||
final invoiceNumber = json['invoice_number'];
|
||||
final invoiceSeries = json['invoice_series'];
|
||||
final invoiceState = json['invoice_state'];
|
||||
final invoiceContingency = json['invoice_contingency'];
|
||||
final invoiceMessage = json['invoice_message'];
|
||||
if (orderNumber is! String ||
|
||||
invoiceId is! num ||
|
||||
invoiceNumber == null ||
|
||||
invoiceSeries == null) {
|
||||
throw const FormatException('Resposta de finalização inválida.');
|
||||
}
|
||||
return SaleCompletion(
|
||||
orderNumber: orderNumber,
|
||||
invoiceId: invoiceId.toInt(),
|
||||
invoiceNumber: invoiceNumber.toString(),
|
||||
invoiceSeries: invoiceSeries.toString(),
|
||||
invoiceState: invoiceState?.toString() ?? '',
|
||||
invoiceContingency: invoiceContingency == true,
|
||||
invoiceMessage: invoiceMessage?.toString() ?? '',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
class SalePayment {
|
||||
const SalePayment({
|
||||
required this.conditionFormId,
|
||||
required this.amountMinorUnits,
|
||||
required this.paymentType,
|
||||
});
|
||||
|
||||
final int conditionFormId;
|
||||
final int amountMinorUnits;
|
||||
final String paymentType;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
enum SaleViewMode { list, kanban }
|
||||
@@ -0,0 +1,28 @@
|
||||
import '../entities/app_settings.dart';
|
||||
import '../entities/app_session.dart';
|
||||
import '../entities/pos_device.dart';
|
||||
|
||||
abstract interface class AuthRepository {
|
||||
bool get isAuthenticated;
|
||||
|
||||
AppSession? get currentSession;
|
||||
|
||||
Future<AppSession> authenticate({
|
||||
required String username,
|
||||
required String password,
|
||||
required AppSettings settings,
|
||||
required PosDevice device,
|
||||
required String appVersion,
|
||||
});
|
||||
|
||||
Future<void> logout();
|
||||
}
|
||||
|
||||
class AuthUnavailableException implements Exception {
|
||||
const AuthUnavailableException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../entities/cart_item.dart';
|
||||
import '../entities/product.dart';
|
||||
|
||||
abstract interface class CartRepository implements Listenable {
|
||||
List<CartItem> get items;
|
||||
|
||||
int get itemCount;
|
||||
|
||||
int? get totalMinorUnits;
|
||||
|
||||
void addProduct(Product product);
|
||||
|
||||
void increaseQuantity(Product product);
|
||||
|
||||
void decreaseQuantity(Product product);
|
||||
|
||||
void removeProduct(Product product);
|
||||
|
||||
void clear();
|
||||
}
|
||||
|
||||
class InMemoryCartRepository extends ChangeNotifier implements CartRepository {
|
||||
final Map<String, CartItem> _items = {};
|
||||
|
||||
@override
|
||||
List<CartItem> get items => List.unmodifiable(_items.values);
|
||||
|
||||
@override
|
||||
int get itemCount =>
|
||||
_items.values.fold(0, (count, item) => count + item.quantity);
|
||||
|
||||
@override
|
||||
int? get totalMinorUnits {
|
||||
if (_items.values.any((item) => item.product.priceMinorUnits == null)) {
|
||||
return null;
|
||||
}
|
||||
return _items.values.fold<int>(
|
||||
0,
|
||||
(total, item) => total + item.product.priceMinorUnits! * item.quantity,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void addProduct(Product product) {
|
||||
increaseQuantity(product);
|
||||
}
|
||||
|
||||
@override
|
||||
void increaseQuantity(Product product) {
|
||||
final key = product.cartKey;
|
||||
final existing = _items[key];
|
||||
_items[key] = CartItem(
|
||||
product: product,
|
||||
quantity: (existing?.quantity ?? 0) + 1,
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void decreaseQuantity(Product product) {
|
||||
final key = product.cartKey;
|
||||
final existing = _items[key];
|
||||
if (existing == null || existing.quantity <= 1) return;
|
||||
_items[key] = CartItem(
|
||||
product: existing.product,
|
||||
quantity: existing.quantity - 1,
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void removeProduct(Product product) {
|
||||
if (_items.remove(product.cartKey) != null) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void clear() {
|
||||
if (_items.isEmpty) return;
|
||||
_items.clear();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import '../entities/department.dart';
|
||||
import '../entities/product.dart';
|
||||
|
||||
abstract interface class CatalogRepository {
|
||||
Future<List<Department>> fetchDepartments();
|
||||
|
||||
Future<List<Product>> fetchProductsByDepartment(int departmentId);
|
||||
|
||||
Future<Product?> fetchProductByBarcode(String barcode);
|
||||
}
|
||||
|
||||
class CatalogException implements Exception {
|
||||
const CatalogException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
class ConnectionTestResult {
|
||||
const ConnectionTestResult({
|
||||
required this.isAvailable,
|
||||
required this.message,
|
||||
});
|
||||
|
||||
final bool isAvailable;
|
||||
final String message;
|
||||
}
|
||||
|
||||
abstract interface class ConnectionTester {
|
||||
Future<ConnectionTestResult> test(Uri serverUri);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import '../entities/customer.dart';
|
||||
|
||||
abstract interface class CustomerRepository {
|
||||
Future<List<Customer>> search(String query);
|
||||
}
|
||||
|
||||
class CustomerSearchException implements Exception {
|
||||
const CustomerSearchException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import '../entities/payment_method.dart';
|
||||
|
||||
abstract interface class PaymentMethodsRepository {
|
||||
Future<List<PaymentMethod>> loadAvailable();
|
||||
}
|
||||
|
||||
class PaymentMethodsException implements Exception {
|
||||
const PaymentMethodsException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import '../entities/cart_item.dart';
|
||||
import '../entities/customer.dart';
|
||||
import '../entities/sale_completion.dart';
|
||||
import '../entities/sale_payment.dart';
|
||||
|
||||
abstract interface class SaleCheckoutRepository {
|
||||
Future<SaleCompletion> finalizeCashSale({
|
||||
required List<CartItem> items,
|
||||
required List<SalePayment> payments,
|
||||
Customer? customer,
|
||||
String? customerCpf,
|
||||
required String checkoutKey,
|
||||
});
|
||||
}
|
||||
|
||||
class SaleCheckoutException implements Exception {
|
||||
const SaleCheckoutException(this.code, this.message);
|
||||
|
||||
final String code;
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import '../entities/sale_view_mode.dart';
|
||||
|
||||
abstract interface class SaleViewPreferenceRepository {
|
||||
Future<SaleViewMode> loadForUser(int userId);
|
||||
|
||||
Future<void> saveForUser(int userId, SaleViewMode mode);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import '../entities/historical_sale.dart';
|
||||
|
||||
abstract interface class SalesHistoryRepository {
|
||||
Future<List<HistoricalSale>> fetchSales();
|
||||
}
|
||||
|
||||
class SalesHistoryException implements Exception {
|
||||
const SalesHistoryException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import '../entities/app_settings.dart';
|
||||
|
||||
abstract interface class SettingsRepository {
|
||||
Future<AppSettings?> load();
|
||||
|
||||
Future<void> save(AppSettings settings);
|
||||
}
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'app/app.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const PdvApp());
|
||||
}
|
||||
Reference in new issue
Block a user