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