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,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,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user