This commit is contained in:
J. A. Messias 2024-11-13 13:37:34 -03:00
parent 5a0e9dc129
commit 32c0b96074
4 changed files with 247 additions and 85 deletions

View File

@ -141,3 +141,54 @@ extension SQLIteStorageKeyExtension on SQLiteStorageKey {
}
}
}
enum LicenseStorageKey {
messages,
liberations,
reservations,
access,
openedVisits,
vehicles,
residents,
pets,
orders,
completeSchedule,
providerSchedule,
deliverySchedule,
fastPass,
}
extension LicenseKeyExtension on LicenseStorageKey {
String get value {
switch (this) {
case LicenseStorageKey.messages:
return 'FRE-HUB-MESSAGES';
case LicenseStorageKey.liberations:
return 'FRE-HUB-LIBERATIONS';
case LicenseStorageKey.reservations:
return 'FRE-HUB-RESERVATIONS';
case LicenseStorageKey.access:
return 'FRE-HUB-ACCESS';
case LicenseStorageKey.openedVisits:
return 'FRE-HUB-OPENED-VISITS';
case LicenseStorageKey.vehicles:
return 'FRE-HUB-VEHICLES';
case LicenseStorageKey.residents:
return 'FRE-HUB-RESIDENTS';
case LicenseStorageKey.pets:
return 'FRE-HUB-PETS';
case LicenseStorageKey.orders:
return 'FRE-HUB-ORDERS';
case LicenseStorageKey.completeSchedule:
return 'FRE-HUB-COMPLETE-SCHEDULE';
case LicenseStorageKey.providerSchedule:
return 'FRE-HUB-AGE-PROV-PRESTADOR';
case LicenseStorageKey.deliverySchedule:
return 'FRE-HUB-AGE-PROV-DELIVERY';
case LicenseStorageKey.fastPass:
return 'FRE-HUB-FASTPASS';
default:
return '';
}
}
}

View File

@ -1,3 +1,6 @@
import 'dart:convert';
import 'dart:developer';
import 'package:hub/shared/helpers/base_storage.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.dart';
@ -7,13 +10,15 @@ class SQLiteStorage implements BaseStorage {
SQLiteStorage._();
static final String _dbName = 'database.db';
static final int _dbVersion = 1;
static final int _dbVersion = 2;
static const String tableKeychain = 'keychain';
static const String tableLicense = 'license';
static final SQLiteStorage instance = SQLiteStorage._();
late final _database;
static late final Database _database;
static Database get database => _database;
@override
Future<void> init() async {
@ -21,20 +26,29 @@ class SQLiteStorage implements BaseStorage {
join(await getDatabasesPath(), _dbName),
version: _dbVersion,
onCreate: _onCreate,
onUpgrade: _onUpdate,
onUpgrade: _onUpgrade,
onDowngrade: _onDowngrade,
);
// await _onInitLocalVariables(_database);
}
_onCreate(Database database, int version) async {
await database.execute(_tableKeychain);
log('Creating database...');
await database.execute(_keychain);
await database.execute(_license);
await initLicense(database);
}
_onUpgrade(Database database, int oldVersion, int newVersion) async {
log('Upgrading database from version $oldVersion to $newVersion...');
if (oldVersion < 2) {
await database.execute(_license);
await initLicense(database);
}
}
_onUpdate(Database database, int oldVersion, int newVersion) async {}
_onDowngrade(Database database, int oldVersion, int newVersion) async {}
String get _tableKeychain => '''
String get _keychain => '''
CREATE TABLE keychain (
key TEXT UNIQUE,
value TEXT,
@ -45,39 +59,76 @@ class SQLiteStorage implements BaseStorage {
);
''';
List<Map<String, dynamic>> get _localVariables => [
{'key': SQLiteStorageKey.devUUID.value, 'value': '', 'type': 'user'},
{'key': SQLiteStorageKey.userUUID.value, 'value': '', 'type': 'user'},
{'key': SQLiteStorageKey.userDevUUID.value, 'value': '', 'type': 'user'},
{'key': SQLiteStorageKey.status.value, 'value': '', 'type': 'user'},
{'key': SQLiteStorageKey.userName.value, 'value': '', 'type': 'user'},
{'key': SQLiteStorageKey.clientUUID.value, 'value': '', 'type': 'local'},
{'key': SQLiteStorageKey.ownerUUID.value, 'value': '', 'type': 'local'},
{'key': SQLiteStorageKey.clientName.value, 'value': '', 'type': 'local'},
{'key': SQLiteStorageKey.whatsapp.value, 'value': 'false', 'type': 'util'},
{'key': SQLiteStorageKey.provisional.value, 'value': 'false', 'type': 'util'},
{'key': SQLiteStorageKey.pets.value, 'value': 'false', 'type': 'util'},
{'key': SQLiteStorageKey.local.value, 'value': 'false', 'type': 'util'},
{'key': SQLiteStorageKey.notify.value, 'value': 'false', 'type': 'util'},
{'key': SQLiteStorageKey.fingerprint.value, 'value': 'false', 'type': 'util'},
{'key': SQLiteStorageKey.access.value, 'value': 'false', 'type': 'util'},
{'key': SQLiteStorageKey.panic.value, 'value': 'false', 'type': 'util'},
{'key': SQLiteStorageKey.person.value, 'value': 'false', 'type': 'util'},
{'key': SQLiteStorageKey.requestOSNotification.value, 'value': 'false', 'type': 'util'},
{'key': SQLiteStorageKey.petAmount.value, 'value': '', 'type': 'local'},
];
String get _license => '''
CREATE TABLE license (
key TEXT UNIQUE,
display TEXT,
expirationDate TEXT,
startDate TEXT,
quantity TEXT
);
''';
static Future<void> initLicense(Database database) async {
log('initLicense()');
for (var element in LicenseStorageKey.values.map((e) => e.value)) {
await database.insert(
tableLicense,
{
'key': element,
'display': 'VISIVEL',
'expirationDate': '',
'startDate': '',
'quantity': '',
},
conflictAlgorithm: ConflictAlgorithm.ignore,
);
}
}
@override
Future<String?> get(String key) async {
var response = await _database.query('keychain', where: 'key = ?', whereArgs: [key]);
if (LicenseStorageKey.values.map((e) => e.value).toList().contains(key)) {
return await _getLicense(key);
} else {
return await _getKeychain(key);
}
}
Future<String?> _getKeychain(String key) async {
var response = await _database.query(tableKeychain, where: 'key = ?', whereArgs: [key]);
if (response.isEmpty) {
return null;
}
return response.first['value'];
return response.first['value'].toString();
}
Future<String?> _getLicense(String key) async {
var response = await _database.query(tableLicense, where: 'key = ?', whereArgs: [key]);
if (response.isEmpty) {
return null;
}
return response.first['value'].toString();
}
Future<String?> getAll(String table) async {
var response = await _database.query(table);
if (response.isEmpty) {
return null;
}
return jsonEncode(response);
}
@override
Future<void> set(String key, String value) async {
if (LicenseStorageKey.values.map((e) => e.value).toList().contains(key)) {
return await _setLicense(key, value);
} else {
return await _setKeychain(key, value);
}
}
Future<void> _setKeychain(String key, String value) async {
var date = DateTime.now().toIso8601String();
await _database.insert(
tableKeychain,
@ -92,6 +143,23 @@ class SQLiteStorage implements BaseStorage {
conflictAlgorithm: ConflictAlgorithm.replace);
}
Future<void> _setLicense(String key, String value) async {
log('setLicense($key, $value)');
Map<String, dynamic> valueMap = jsonDecode(value);
log('String to Map<String, dynamic>: $value to $valueMap');
await _database.insert(
tableLicense,
{
'key': key,
'display': valueMap['display'],
'expirationDate': valueMap['expirationDate'],
'startDate': valueMap['startDate'],
'quantity': valueMap['quantity'],
},
conflictAlgorithm: ConflictAlgorithm.replace);
}
@override
Future<void> delete(String key) async {
await _database.delete('keychain', where: 'key = ?', whereArgs: [key]);

View File

@ -3,72 +3,112 @@
import 'dart:developer';
import 'package:hub/backend/api_requests/api_calls.dart';
import 'package:hub/shared/helpers/base_storage.dart';
import 'package:hub/shared/helpers/sqlite_storage.dart';
import 'dart:convert';
import 'package:hub/shared/helpers/storage_helper.dart';
import 'package:sqflite/sqflite.dart';
class LicenseService {
static final LicenseService _instance = LicenseService._internal();
factory LicenseService() => _instance;
LicenseService._internal();
List<Module> _modules = [];
List<Module> get modules => List.unmodifiable(_modules);
Future<void> initLicenseService() async {
await _fetchLicenses();
static Future<void> initLicenseService() async {
// for (var element in LicenseStorageKey.values.map((e) => e.value)) {
// await SQLiteStorage.database.insert(
// SQLiteStorage.tableLicense,
// {
// 'key': element,
// 'display': 'VISIVEL',
// 'expirationDate': '',
// 'startDate': '',
// 'quantity': '',
// },
// conflictAlgorithm: ConflictAlgorithm.ignore,
// );
// }
}
Future<void> _fetchLicenses() async {
static Future<void> processLicense() async {}
static Future<void> fetchLicenses() async {
try {
log('Obtendo licenças...');
final ApiCallResponse response = await PhpGroup.testCall();
final String responseBody = response.jsonBody.toString();
final List<dynamic> responseBody = response.jsonBody;
if (responseBody.isEmpty) {
throw Exception('Licensa ausente ou vazia.');
if (responseBody == []) {
// throw Exception('Licensa ausente ou vazia.');
}
// if (responseBody == "[]") {
// log('Nenhuma licença encontrada.');
// _modules = [];
// log('() MOD => $_modules');
// return;
// }
final dynamic jsonBody = jsonDecode(responseBody);
if (jsonBody is Map && jsonBody['error'] == true) {
final String error = jsonBody['error_msg'] ?? 'Erro desconhecido';
if (response.jsonBody is! List<dynamic> && response.jsonBody['error'] != null) {
final String error = response.jsonBody['error_msg'] ?? 'Erro desconhecido';
throw Exception('Erro ao consultar licenças: $error');
}
final bool isList = jsonBody is List;
final bool isMap = jsonBody is Map<String, dynamic>;
final dynamic license = isList
? (jsonBody).map<Module>((data) => Module.fromJson(data as Map<String, dynamic>)).toList()
: isMap
? [Module.fromJson(jsonBody)]
: [];
log('Modulos obtidos: $license');
if (license is List<Module> && license.isNotEmpty && license != _modules) {
_modules = license;
log('Licença obtida com sucesso');
log('$_modules');
} else if (license is List<Module> && license.isEmpty) {
throw Exception('Nenhum módulo encontrado.');
for (var element in responseBody) {
switch (element['key']) {
case 'FRE-HUB-MESSAGES':
_saveModule(element);
break;
case 'FRE-HUB-LIBERATIONS':
_saveModule(element);
break;
case 'FRE-HUB-RESERVATIONS':
_saveModule(element);
break;
case 'FRE-HUB-ACCESS':
_saveModule(element);
break;
case 'FRE-HUB-OPENED-VISITS':
_saveModule(element);
break;
case 'FRE-HUB-VEHICLES':
_saveModule(element);
break;
case 'FRE-HUB-RESIDENTS':
_saveModule(element);
break;
case 'FRE-HUB-PETS':
_saveModule(element);
break;
case 'FRE-HUB-FASTPASS':
_saveModule(element);
break;
case 'FRE-HUB-ORDERS':
_saveModule(element);
break;
case 'FRE-HUB-COMPLETE-SCHEDULE':
_saveModule(element);
break;
case 'FRE-HUB-AGE-PROV-DELIVERY':
_saveModule(element);
break;
case 'FRE-HUB-AGE-PROV-PRESTADOR':
_saveModule(element);
break;
case 'FRE-WHATSAPP':
_saveModule(element);
break;
}
}
} catch (e, s) {
log('Erro ao obter licença', error: e, stackTrace: s);
}
}
Future<void> checkLicense() async {
log('Verificando licença...');
await _fetchLicenses();
static Future<void> _saveModule(final dynamic body) async {
if (body is Map<String, dynamic>) log('Salvando módulo: ${body.toString()}');
// if (body is Map<String, dynamic>) await StorageHelper().set(body['key'], '', Storage.SQLiteStorage);
if (body is Map<String, dynamic>) await StorageHelper().set(body['key'], jsonEncode(body), Storage.SQLiteStorage);
}
Future<void> catchLicense() async {
static Future<void> updateLicense(final dynamic body) async {}
static Future<void> catchLicense() async {
await PhpGroup.getLicense();
}
}

View File

@ -8,6 +8,7 @@ import 'package:hub/backend/api_requests/api_manager.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/helpers/base_storage.dart';
import 'package:hub/shared/helpers/storage_helper.dart';
import 'package:hub/shared/services/license/license_service.dart';
import 'package:hub/shared/utils/device_util.dart';
import 'package:hub/shared/utils/dialog_util.dart';
@ -162,6 +163,8 @@ class LocalizationService {
);
await DialogUtil.error(context, errorMsg).whenComplete(() => selectLocal(context, null));
return false;
} finally {
await LicenseService.fetchLicenses();
}
}
@ -293,6 +296,22 @@ class LocalizationService {
}
}
static Future<void> _updateStorageUtil(Map<String, dynamic> jsonBody) async {
await StorageHelper().set(SQLiteStorageKey.whatsapp.value,
jsonBody['whatsapp'] != null && jsonBody['whatsapp'] ? 'true' : 'false', Storage.SQLiteStorage);
await StorageHelper().set(SQLiteStorageKey.provisional.value,
jsonBody['provisional'] != null && jsonBody['provisional'] ? 'true' : 'false', Storage.SQLiteStorage);
await StorageHelper().set(SQLiteStorageKey.pets.value,
jsonBody['pet'] != null && jsonBody['pet'] ? 'true' : 'false', Storage.SQLiteStorage);
await StorageHelper().set(
SQLiteStorageKey.petAmount.value,
jsonBody['petAmountRegister'] != null && jsonBody['petAmountRegister'].toString().isEmpty
? '0'
: jsonBody['petAmountRegister'].toString(),
Storage.SQLiteStorage);
await StorageHelper().set(SQLiteStorageKey.userName.value, jsonBody['visitado']['VDO_NOME'], Storage.SQLiteStorage);
}
static bool _isActive(List<dynamic> locals) {
return locals.where((local) => local['CLU_STATUS'] == 'A').isNotEmpty;
}
@ -324,20 +343,4 @@ class LocalizationService {
String cliName = (await StorageHelper().get(SQLiteStorageKey.clientName.value, Storage.SQLiteStorage)) ?? '';
return cliUUID.isNotEmpty && cliName.isNotEmpty;
}
static Future<void> _updateStorageUtil(Map<String, dynamic> jsonBody) async {
await StorageHelper().set(SQLiteStorageKey.whatsapp.value,
jsonBody['whatsapp'] != null && jsonBody['whatsapp'] ? 'true' : 'false', Storage.SQLiteStorage);
await StorageHelper().set(SQLiteStorageKey.provisional.value,
jsonBody['provisional'] != null && jsonBody['provisional'] ? 'true' : 'false', Storage.SQLiteStorage);
await StorageHelper().set(SQLiteStorageKey.pets.value,
jsonBody['pet'] != null && jsonBody['pet'] ? 'true' : 'false', Storage.SQLiteStorage);
await StorageHelper().set(
SQLiteStorageKey.petAmount.value,
jsonBody['petAmountRegister'] != null && jsonBody['petAmountRegister'].toString().isEmpty
? '0'
: jsonBody['petAmountRegister'].toString(),
Storage.SQLiteStorage);
await StorageHelper().set(SQLiteStorageKey.userName.value, jsonBody['visitado']['VDO_NOME'], Storage.SQLiteStorage);
}
}