diff --git a/lib/shared/helpers/base_storage.dart b/lib/shared/helpers/base_storage.dart index 11bc2509..9cc96289 100644 --- a/lib/shared/helpers/base_storage.dart +++ b/lib/shared/helpers/base_storage.dart @@ -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 ''; + } + } +} diff --git a/lib/shared/helpers/sqlite_storage.dart b/lib/shared/helpers/sqlite_storage.dart index 774a9afe..9c4fd052 100644 --- a/lib/shared/helpers/sqlite_storage.dart +++ b/lib/shared/helpers/sqlite_storage.dart @@ -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 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> 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 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 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 _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 _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 getAll(String table) async { + var response = await _database.query(table); + if (response.isEmpty) { + return null; + } + return jsonEncode(response); } @override Future 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 _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 _setLicense(String key, String value) async { + log('setLicense($key, $value)'); + Map valueMap = jsonDecode(value); + log('String to Map: $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 delete(String key) async { await _database.delete('keychain', where: 'key = ?', whereArgs: [key]); diff --git a/lib/shared/services/license/license_service.dart b/lib/shared/services/license/license_service.dart index 51f234c4..4b562a09 100644 --- a/lib/shared/services/license/license_service.dart +++ b/lib/shared/services/license/license_service.dart @@ -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 _modules = []; - - List get modules => List.unmodifiable(_modules); - - Future initLicenseService() async { - await _fetchLicenses(); + static Future 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 _fetchLicenses() async { + static Future processLicense() async {} + + static Future fetchLicenses() async { try { log('Obtendo licenças...'); final ApiCallResponse response = await PhpGroup.testCall(); - final String responseBody = response.jsonBody.toString(); + final List 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 && 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; - final dynamic license = isList - ? (jsonBody).map((data) => Module.fromJson(data as Map)).toList() - : isMap - ? [Module.fromJson(jsonBody)] - : []; - log('Modulos obtidos: $license'); - if (license is List && license.isNotEmpty && license != _modules) { - _modules = license; - log('Licença obtida com sucesso'); - log('$_modules'); - } else if (license is List && 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 checkLicense() async { - log('Verificando licença...'); - await _fetchLicenses(); + static Future _saveModule(final dynamic body) async { + if (body is Map) log('Salvando módulo: ${body.toString()}'); + // if (body is Map) await StorageHelper().set(body['key'], '', Storage.SQLiteStorage); + if (body is Map) await StorageHelper().set(body['key'], jsonEncode(body), Storage.SQLiteStorage); } - Future catchLicense() async { + static Future updateLicense(final dynamic body) async {} + + static Future catchLicense() async { await PhpGroup.getLicense(); } } diff --git a/lib/shared/services/localization/localization_service.dart b/lib/shared/services/localization/localization_service.dart index e1319084..673c318f 100644 --- a/lib/shared/services/localization/localization_service.dart +++ b/lib/shared/services/localization/localization_service.dart @@ -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 _updateStorageUtil(Map 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 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 _updateStorageUtil(Map 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); - } }