From 3080eac50bff0c675ca7854d415bad1afe1a6ddf Mon Sep 17 00:00:00 2001 From: "J. A. Messias" Date: Fri, 6 Dec 2024 10:00:41 -0300 Subject: [PATCH] WIP --- .../order_filter_modal_model.dart | 2 +- .../order_filter_modal_widget.dart | 11 ++- .../home/presentation/pages/home_page.dart | 5 +- lib/flutter_flow/nav/nav.dart | 3 - lib/main.dart | 4 ++ .../package_order_page.dart | 11 ++- .../repositories/locals_repository_impl.dart | 31 +++++++-- .../blocs/local_profile_bloc.dart | 1 - .../repositories/menu_repository_impl.dart | 22 +++--- .../menu/presentation/blocs/menu_bloc.dart | 17 ++--- .../modules/constants/license_constants.dart | 61 +++++++++++----- .../license_local_data_source.dart | 20 ++---- .../license_remote_data_source.dart | 13 +--- .../modules/domain/entities/license.dart | 2 +- lib/shared/constants/keychain_constants.dart | 2 +- .../helpers/database/database_helper.dart | 69 +++++++++++++------ .../helpers/storage/keychain_storage.dart | 3 + .../helpers/storage/storage_helper.dart | 3 + .../authentication_service.dart | 6 +- 19 files changed, 175 insertions(+), 111 deletions(-) diff --git a/lib/components/molecular_components/order_filter_modal/order_filter_modal_model.dart b/lib/components/molecular_components/order_filter_modal/order_filter_modal_model.dart index 79eefd3c..ec888c47 100644 --- a/lib/components/molecular_components/order_filter_modal/order_filter_modal_model.dart +++ b/lib/components/molecular_components/order_filter_modal/order_filter_modal_model.dart @@ -25,4 +25,4 @@ class OrderFilterModalModel extends FlutterFlowModel { textFieldFocusNode?.dispose(); textController?.dispose(); } -} +} \ No newline at end of file diff --git a/lib/components/molecular_components/order_filter_modal/order_filter_modal_widget.dart b/lib/components/molecular_components/order_filter_modal/order_filter_modal_widget.dart index 4c74c366..1835eb3c 100644 --- a/lib/components/molecular_components/order_filter_modal/order_filter_modal_widget.dart +++ b/lib/components/molecular_components/order_filter_modal/order_filter_modal_widget.dart @@ -4,7 +4,6 @@ import 'package:hub/components/molecular_components/order_filter_modal/order_fil import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; -import 'package:hub/shared/helpers/storage/storage_helper.dart'; // ignore: unused_import import 'package:hub/shared/utils/limited_text_size.dart'; @@ -29,22 +28,22 @@ class _OrderFilterModalWidgetState extends State { late Map selected; final List> adresseeTypeOptions = [ { - 'title': FFLocalizations.of(StorageHelper().context!).getVariableText(enText: 'Resident', ptText: 'Morador'), + 'title': FFLocalizations.of(navigatorKey.currentContext!).getVariableText(enText: 'Resident', ptText: 'Morador'), 'value': 'MOR' }, { - 'title': FFLocalizations.of(StorageHelper().context!).getVariableText(enText: 'Property', ptText: 'Propriedade'), + 'title': FFLocalizations.of(navigatorKey.currentContext!).getVariableText(enText: 'Property', ptText: 'Propriedade'), 'value': 'PRO' }, ]; final List> statusOptions = [ { - 'title': FFLocalizations.of(StorageHelper().context!) + 'title': FFLocalizations.of(navigatorKey.currentContext!) .getVariableText(ptText: 'Aguardando Retirada', enText: 'Waiting for Pickup'), 'value': 'notPickedUp' }, { - 'title': FFLocalizations.of(StorageHelper().context!).getVariableText(ptText: 'Retirado', enText: 'Picked Up'), + 'title': FFLocalizations.of(navigatorKey.currentContext!).getVariableText(ptText: 'Retirado', enText: 'Picked Up'), 'value': 'pickedUp' }, ]; @@ -232,4 +231,4 @@ class _OrderFilterModalWidgetState extends State { ), ); } -} +} \ No newline at end of file diff --git a/lib/features/home/presentation/pages/home_page.dart b/lib/features/home/presentation/pages/home_page.dart index 2d64565d..dd567508 100644 --- a/lib/features/home/presentation/pages/home_page.dart +++ b/lib/features/home/presentation/pages/home_page.dart @@ -42,8 +42,11 @@ class _HomePageWidgetState extends State { Widget build(BuildContext context) { return Builder( builder: (context) { + // LocalsRepositoryImpl.license.add(false); + // context.read().add(LocalProfileEvent()); + // context.read().add(MenuEvent()); LocalsRepositoryImpl.license.add(true); - // context.read().updateProfile(context); + return Scaffold( key: scaffoldKey, backgroundColor: FlutterFlowTheme.of(context).primaryBackground, diff --git a/lib/flutter_flow/nav/nav.dart b/lib/flutter_flow/nav/nav.dart index 30aacafd..a62e5d2a 100644 --- a/lib/flutter_flow/nav/nav.dart +++ b/lib/flutter_flow/nav/nav.dart @@ -123,10 +123,7 @@ GoRouter createRouter(AppStateNotifier appStateNotifier) { ); }), FFRoute(name: 'homePage', path: '/homePage', builder: (context, params) { - log('params: $params'); final Future Function(BuildContext context)? update = params.getParam('update', ParamType.Function); - log('update: $update'); - return HomePageWidget(key: UniqueKey(), update: update); }), diff --git a/lib/main.dart b/lib/main.dart index f100c8c7..220796a2 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -192,11 +192,15 @@ class _AppState extends State with WidgetsBindingObserver { @override void didChangeAppLifecycleState(AppLifecycleState state) async { if (state == AppLifecycleState.detached) { + final isLogged = await StorageHelper().get(SecureStorageKey.isLogged.value); + log('isLogged: $isLogged'); + if (isLogged.toBoolean()) { LocalsRepositoryImpl.license.add(false); final response = await LocalsRepositoryImpl().update(context); LocalsRepositoryImpl.license.add(response); await FirebaseMessagingService().updateDeviceToken(); } + } } @override diff --git a/lib/pages/package_order_page/package_order_page.dart b/lib/pages/package_order_page/package_order_page.dart index 0df4e591..b63c5186 100644 --- a/lib/pages/package_order_page/package_order_page.dart +++ b/lib/pages/package_order_page/package_order_page.dart @@ -36,11 +36,11 @@ class _PackageOrderPage extends State { List _orderList = []; final Map filter = { - 'adresseeType': 'PRO', + 'adresseeType': '.*', 'status': 'notPickedUp', }; - String _adresseeType = 'PRO'; + String _adresseeType = '.*'; String _status = 'notPickedUp'; late BehaviorSubject> _selectedTypeSubject; @@ -64,7 +64,7 @@ class _PackageOrderPage extends State { } Future initDatabase() async { - cliUUID = (await StorageHelper().get(KeychainStorageKey.clientUUID.value)) ?? ''; + cliUUID = (await StorageHelper().get(KeychainStorageKey.clientUUID.value) ?? ''); } @override @@ -224,7 +224,7 @@ class _PackageOrderPage extends State { return AppBar( backgroundColor: FlutterFlowTheme.of(context).primaryBackground, automaticallyImplyLeading: false, - title: Text(FFLocalizations.of(context).getVariableText(enText: 'Orders', ptText: 'Encomendas'), + title: Text(FFLocalizations.of(context).getVariableText(enText: 'My Orders', ptText: 'Minhas Encomendas'), style: FlutterFlowTheme.of(context).headlineMedium.override( fontFamily: 'Nunito', color: FlutterFlowTheme.of(context).primaryText, @@ -412,9 +412,8 @@ class _PackageOrderPage extends State { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: FlutterFlowTheme.of(context).primaryBackground, appBar: _appBar(context), body: _appBody(context), ); } -} +} \ No newline at end of file diff --git a/lib/shared/components/molecules/locals/data/repositories/locals_repository_impl.dart b/lib/shared/components/molecules/locals/data/repositories/locals_repository_impl.dart index 1c8580ad..dd426587 100644 --- a/lib/shared/components/molecules/locals/data/repositories/locals_repository_impl.dart +++ b/lib/shared/components/molecules/locals/data/repositories/locals_repository_impl.dart @@ -3,6 +3,7 @@ import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hub/shared/components/molecules/locals/index.dart'; +import 'package:hub/shared/components/molecules/menu/presentation/blocs/menu_bloc.dart'; import 'package:hub/shared/components/molecules/modules/index.dart'; import 'package:hub/shared/helpers/storage/base_storage.dart'; import 'package:hub/shared/helpers/storage/storage_helper.dart'; @@ -23,18 +24,34 @@ class LocalsRepositoryImpl implements LocalsRepository { @override Future update(BuildContext context) async { bool response = false; - while (!response) { - response = await remoteDataSource.processLocals(context); - if (!response) { - await StorageHelper().set(KeychainStorageKey.clientUUID.value, ''); - const String errorMsg = 'Erro ao atualizar locais'; - await DialogUtil.error(context, errorMsg); + try { + while (!response) { + response = await remoteDataSource.processLocals(context); + if (!response) { + await _handleUpdateError(context); + } } + await _notifyBlocs(context); + } catch (e) { + log('Error updating locals: $e'); + await _handleUpdateError(context); } - context.read().add(LocalProfileEvent()); return response; } + Future _handleUpdateError(BuildContext context) async { + await StorageHelper().set(KeychainStorageKey.clientUUID.value, ''); + const String errorMsg = 'Erro ao atualizar locais'; + await DialogUtil.error(context, errorMsg); + } + + Future _notifyBlocs(BuildContext context) async { + LocalsRepositoryImpl.license.add(false); + context.read().add(LocalProfileEvent()); + context.read().add(MenuEvent()); + LocalsRepositoryImpl.license.add(true); + } + @override Future unlinkLocal(BuildContext context) { return remoteDataSource.detachLocal(context); diff --git a/lib/shared/components/molecules/locals/presentation/blocs/local_profile_bloc.dart b/lib/shared/components/molecules/locals/presentation/blocs/local_profile_bloc.dart index 95faea30..e05375c5 100644 --- a/lib/shared/components/molecules/locals/presentation/blocs/local_profile_bloc.dart +++ b/lib/shared/components/molecules/locals/presentation/blocs/local_profile_bloc.dart @@ -36,7 +36,6 @@ class LocalProfileBloc extends Bloc { } Future _onLocalProfileEvent(LocalProfileEvent event, Emitter emit) async { - log('LocalProfileBloc: _onLocalProfileEvent'); final cliName = (await StorageHelper().get(KeychainStorageKey.clientName.value)) ?? ''; final ownerName = (await StorageHelper().get(KeychainStorageKey.ownerName.value)) ?? ''; final cliUUID = (await StorageHelper().get(KeychainStorageKey.clientUUID.value)) ?? ''; diff --git a/lib/shared/components/molecules/menu/data/repositories/menu_repository_impl.dart b/lib/shared/components/molecules/menu/data/repositories/menu_repository_impl.dart index 3f2c2f6f..02cb24e5 100644 --- a/lib/shared/components/molecules/menu/data/repositories/menu_repository_impl.dart +++ b/lib/shared/components/molecules/menu/data/repositories/menu_repository_impl.dart @@ -22,17 +22,16 @@ class MenuRepositoryImpl implements MenuRepository { Future> generateMenuEntries(List menuEntries, EnumMenuItem item) async { log('Generating menu entries for $item'); List entries = []; - final bool isNewVersion = await StorageHelper().get(KeychainStorageKey.isNewVersion.value).then((v) => v.toBoolean()); + // final bool isNewVersion = await StorageHelper().get(KeychainStorageKey.isNewVersion.value).then((v) => v.toBoolean()); try { for (var entry in menuEntries) { - log('Processing entry: ${entry.key}'); final bool isDefault = await menuDataSource.processDisplayDefault(item, entry, entries); if (isDefault) continue; final licenseValue = await LicenseRepositoryImpl().getLicense(entry.key); if (licenseValue != null) { final licenseMap = await stringToMap(licenseValue); - final display = await processDisplay(licenseMap, isNewVersion); + final display = EnumDisplay.fromString(licenseMap['display']); final startDate = licenseMap['startDate'] ?? ''; final expirationDate = licenseMap['expirationDate'] ?? ''; final isStarted = await menuDataSource.processStartDate(startDate, entry); @@ -57,13 +56,9 @@ class MenuRepositoryImpl implements MenuRepository { } Future processDisplay(Map module, bool isNewVersion) async { - const keysToCheck = [ - LicenseKeys.residents, - LicenseKeys.vehicles, - LicenseKeys.openedVisits - ]; - if (isNewVersion && keysToCheck.any((key) => module['key'] == key.value)) { + + if (await _shouldUpdateDisplay(module, isNewVersion)) { final displayValue = module['display'] == EnumDisplay.active ? 'VISIVEL' : 'INVISIVEL'; await LicenseLocalDataSourceImpl().setDisplayByKey(['FRE-HUB-ABOUT-PROPERTY'], displayValue); return EnumDisplay.fromString(displayValue); @@ -72,5 +67,14 @@ class MenuRepositoryImpl implements MenuRepository { return EnumDisplay.fromString(module['display']); } + Future _shouldUpdateDisplay(Map module, bool isNewVersion) async { + const keysToCheck = [ + LicenseKeys.residents, + LicenseKeys.vehicles, + LicenseKeys.openedVisits + ]; + return isNewVersion && keysToCheck.any((key) => module['key'] == key.value); + } + } \ No newline at end of file diff --git a/lib/shared/components/molecules/menu/presentation/blocs/menu_bloc.dart b/lib/shared/components/molecules/menu/presentation/blocs/menu_bloc.dart index 8c249bf9..ed513784 100644 --- a/lib/shared/components/molecules/menu/presentation/blocs/menu_bloc.dart +++ b/lib/shared/components/molecules/menu/presentation/blocs/menu_bloc.dart @@ -33,24 +33,21 @@ class MenuBloc extends Bloc { final MenuView style; final EnumMenuItem item; final List entries; - late StreamSubscription _completer; - + late StreamSubscription _completer; MenuBloc({required this.style, required this.item, required this.entries}) : super(MenuState()) { on(_onMenuEvent); - - _completer = LicenseRemoteDataSourceImpl().streamCompleterController.listen((_) { + _completer = LocalsRepositoryImpl.license.stream.listen((v) { add(MenuEvent()); }); - } + } - Future _onMenuEvent(MenuEvent event, Emitter emit) async { - + Future _onMenuEvent(MenuEvent event, Emitter emit) async { await LicenseRemoteDataSourceImpl().waitForSaveCompletion(); - final List NewEntries = await MenuRepositoryImpl().generateMenuEntries(entries, item); - emit(state.copyWith(menuEntries: NewEntries)); - } + final List newEntries = await MenuRepositoryImpl().generateMenuEntries(entries, item); + emit(state.copyWith(menuEntries: newEntries)); + } @override Future close() { diff --git a/lib/shared/components/molecules/modules/constants/license_constants.dart b/lib/shared/components/molecules/modules/constants/license_constants.dart index 9f12dd9a..6a4a2fcc 100644 --- a/lib/shared/components/molecules/modules/constants/license_constants.dart +++ b/lib/shared/components/molecules/modules/constants/license_constants.dart @@ -1,7 +1,8 @@ const String tableLicense = 'license'; - String get createLicenseTable => ''' + class LicenseConstants { + static String get createLicenseTable => ''' CREATE TABLE IF NOT EXISTS $tableLicense ( key TEXT UNIQUE, display TEXT, @@ -11,9 +12,9 @@ ); '''; - String get deleteLicenseTable => 'DROP TABLE IF EXISTS $tableLicense;'; + static String get deleteLicenseTable => 'DROP TABLE IF EXISTS $tableLicense;'; - String get updatePetsHistoryTrigger => ''' + static String get updatePetsHistoryTrigger => ''' CREATE TRIGGER update_fre_hub_pets_history AFTER INSERT ON $tableLicense WHEN NEW.key = 'FRE-HUB-PETS' @@ -23,15 +24,35 @@ END; '''; - String get dropPetsHistoryTrigger => 'DROP TRIGGER IF EXISTS update_fre_hub_pets_history;'; + static String get dropPetsHistoryTrigger => 'DROP TRIGGER IF EXISTS update_fre_hub_pets_history;'; - String get updateDisplayTrigger => ''' + static String get updateDisplayTrigger => ''' CREATE TRIGGER update_display_trigger + AFTER UPDATE ON $tableLicense + WHEN NEW.key IN ('FRE-HUB-OPENED-VISITS', 'FRE-HUB-VEHICLES', 'FRE-HUB-RESIDENTS') + BEGIN + INSERT OR REPLACE INTO $tableLicense (key, display, expirationDate, startDate, quantity) + VALUES ( + 'FRE-HUB-ABOUT-PROPERTY', + CASE + WHEN (SELECT COUNT(*) FROM $tableLicense WHERE key IN ('FRE-HUB-OPENED-VISITS', 'FRE-HUB-VEHICLES', 'FRE-HUB-RESIDENTS') AND display = 'VISIVEL') > 0 + THEN 'VISIVEL' + ELSE 'INVISIVEL' + END, + NULL, NULL, NULL + ); + END; + '''; + + static String get dropUpdateDisplayTrigger => 'DROP TRIGGER IF EXISTS update_display_trigger;'; + + static String get insertDisplayTrigger => ''' + CREATE TRIGGER insert_display_trigger AFTER INSERT ON $tableLicense WHEN NEW.key IN ('FRE-HUB-OPENED-VISITS', 'FRE-HUB-VEHICLES', 'FRE-HUB-RESIDENTS') BEGIN UPDATE $tableLicense - SET display = + SET display = CASE WHEN (SELECT COUNT(*) FROM $tableLicense WHERE key IN ('FRE-HUB-OPENED-VISITS', 'FRE-HUB-VEHICLES', 'FRE-HUB-RESIDENTS') AND display = 'VISIVEL') > 0 THEN 'VISIVEL' @@ -41,17 +62,23 @@ END; '''; - String get dropDisplayTrigger => 'DROP TRIGGER IF EXISTS update_display_trigger;'; + static String get dropInsertDisplayTrigger => 'DROP TRIGGER IF EXISTS insert_display_trigger;'; - String get updatePeopleDisplayTrigger => ''' - CREATE TRIGGER update_people_display_trigger - AFTER UPDATE ON $tableLicense - WHEN NEW.key = 'FRE-HUB-ABOUT-PROPERTY' AND NEW.display = 'VISIVEL' - BEGIN - UPDATE $tableLicense - SET display = 'INVISIVEL' - WHERE key = 'FRE-HUB-PEOPLE'; - END; + static String get updatePeopleDisplayTrigger => ''' + CREATE TRIGGER update_people_display_trigger + AFTER UPDATE ON $tableLicense + WHEN NEW.key IN ('FRE-HUB-OPENED-VISITS', 'FRE-HUB-VEHICLES', 'FRE-HUB-RESIDENTS') + BEGIN + UPDATE $tableLicense + SET display = + CASE + WHEN (SELECT COUNT(*) FROM $tableLicense WHERE key IN ('FRE-HUB-OPENED-VISITS', 'FRE-HUB-VEHICLES', 'FRE-HUB-RESIDENTS') AND display = 'VISIVEL') > 0 + THEN 'VISIVEL' + ELSE 'INVISIVEL' + END + WHERE key = 'FRE-HUB-ABOUT-PROPERTY'; + END; '''; - String get dropPeopleDisplayTrigger => 'DROP TRIGGER IF EXISTS update_people_display_trigger;'; \ No newline at end of file + static String get dropPeopleDisplayTrigger => 'DROP TRIGGER IF EXISTS update_people_display_trigger;'; + } \ No newline at end of file diff --git a/lib/shared/components/molecules/modules/data/data_sources/license_local_data_source.dart b/lib/shared/components/molecules/modules/data/data_sources/license_local_data_source.dart index 65291d10..42e5bac7 100644 --- a/lib/shared/components/molecules/modules/data/data_sources/license_local_data_source.dart +++ b/lib/shared/components/molecules/modules/data/data_sources/license_local_data_source.dart @@ -34,7 +34,6 @@ class LicenseLocalDataSourceImpl implements LicenseLocalDataSource { if (keys.isEmpty) return; final validKeys = keys.where((key) => key.isNotEmpty).toList(); for (var key in validKeys) { - log('Setting display: $key : $display'); await set(key, { 'display': display, 'expirationDate': '', @@ -58,7 +57,6 @@ class LicenseLocalDataSourceImpl implements LicenseLocalDataSource { return null; } - log('Getting StartDate: ${response.toString()}'); return response.toString(); } @@ -68,19 +66,11 @@ class LicenseLocalDataSourceImpl implements LicenseLocalDataSource { value as Map; if (value.isEmpty) return; if (key == 'null') return; - - log('Setting: ${value['key']} : ${value['display']}'); - await DatabaseStorage.database.insert( - tableLicense, - { - 'key': key, - 'display': value['display'], - 'expirationDate': value['expirationDate'], - 'startDate': value['startDate'], - 'quantity': value['quantity'], - }, - conflictAlgorithm: ConflictAlgorithm.replace); + await DatabaseStorage.database.rawInsert( + 'INSERT OR REPLACE INTO $tableLicense (key, display, expirationDate, startDate, quantity) VALUES (?, ?, ?, ?, ?)', + [key, value['display'], value['expirationDate'], value['startDate'], value['quantity']], + ); return; } @@ -92,5 +82,7 @@ class LicenseLocalDataSourceImpl implements LicenseLocalDataSource { @override Future clear() async { await DatabaseStorage.database.delete(tableLicense); + await DatabaseStorage.database.rawDelete( + 'DELETE FROM sqlite_sequence WHERE name = "$tableLicense"'); } } diff --git a/lib/shared/components/molecules/modules/data/data_sources/license_remote_data_source.dart b/lib/shared/components/molecules/modules/data/data_sources/license_remote_data_source.dart index bd0cee47..5513c507 100644 --- a/lib/shared/components/molecules/modules/data/data_sources/license_remote_data_source.dart +++ b/lib/shared/components/molecules/modules/data/data_sources/license_remote_data_source.dart @@ -23,8 +23,7 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource { LicenseRemoteDataSourceImpl._internal(); - final StreamController completerController = StreamController.broadcast(); - Stream get streamCompleterController => completerController.stream; + @override @@ -46,19 +45,16 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource { .where((module) => module.display == ModuleStatus.inactive.key) .map((module) => module.key) .toList(); - log('Módulos inativos: $inactiveModuleKey'); final List activeModuleKey = license.modules .where((module) => module.display == ModuleStatus.active.key) .map((module) => module.key) .toList(); - log('Módulos ativos: $activeModuleKey'); final List disabledModuleKey = license.modules .where((module) => module.display == ModuleStatus.disabled.key) .map((module) => module.key) .toList(); - log('Módulos desabilitados: $disabledModuleKey'); await LicenseLocalDataSourceImpl().setDisplayByKey(inactiveModuleKey, 'INVISIVEL'); await LicenseLocalDataSourceImpl().setDisplayByKey(activeModuleKey, 'VISIVEL'); @@ -95,18 +91,13 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource { return true; } - log('Valores: ${LicenseKeys.values.map((e) => e.value).toList()}'); List> saveOperations = []; for (var element in responseBody) { - log('Elemento: ${element['key']}'); if (licenseContainsKey(element['key'])) { - log('Salvando licença: ${element['key']}'); saveOperations.add(_saveModule(element)); } } await Future.wait(saveOperations); - final String? v = await LicenseRepositoryImpl().getLicense(LicenseKeys.property.value); - log('Licenças obtidas: $v'); return true; } catch (e, s) { log('Erro ao obter licenças: $e', stackTrace: s); @@ -120,13 +111,11 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource { } static bool licenseContainsKey(final String key) { - log('licenseContainsKey: $key'); return LicenseKeys.values.map((e) => e.value).toList().contains(key); } static Future _saveModule(final dynamic body) async { - log('Salvando módulo: ${body['key']}'); if (body is! Map) return; await LicenseRepositoryImpl().setLicense(body['key'], body); } diff --git a/lib/shared/components/molecules/modules/domain/entities/license.dart b/lib/shared/components/molecules/modules/domain/entities/license.dart index 66ed8bd2..d643e322 100644 --- a/lib/shared/components/molecules/modules/domain/entities/license.dart +++ b/lib/shared/components/molecules/modules/domain/entities/license.dart @@ -198,7 +198,7 @@ class License { ), Module( key: LicenseKeys.property.value, - display: isNewVersionWithModule ? ModuleStatus.inactive.key : ModuleStatus.inactive.key, + display: isNewVersionWithModule ? ModuleStatus.active.key : ModuleStatus.inactive.key, expirationDate: '', startDate: '', quantity: 0, diff --git a/lib/shared/constants/keychain_constants.dart b/lib/shared/constants/keychain_constants.dart index 4a44fcfb..0aac6594 100644 --- a/lib/shared/constants/keychain_constants.dart +++ b/lib/shared/constants/keychain_constants.dart @@ -1,7 +1,7 @@ const String tableKeychain = 'keychain'; String get createKeychainTable => ''' - CREATE TABLE $tableKeychain ( + CREATE TABLE IF NOT EXISTS $tableKeychain ( key TEXT UNIQUE, value TEXT, type TEXT, diff --git a/lib/shared/helpers/database/database_helper.dart b/lib/shared/helpers/database/database_helper.dart index bd8f1e2d..dec8a983 100644 --- a/lib/shared/helpers/database/database_helper.dart +++ b/lib/shared/helpers/database/database_helper.dart @@ -6,8 +6,8 @@ import 'package:path/path.dart'; import 'dart:developer'; class DatabaseStorage { - static final String _dbName = 'database.db'; - static final int _dbVersion = 2; + static const String _dbName = 'database.db'; + static const int _dbVersion = 2; static final DatabaseStorage instance = DatabaseStorage._internal(); factory DatabaseStorage() => instance; @@ -21,49 +21,76 @@ class DatabaseStorage { return _database!; } - bool isInitialized = false; + static bool isInitialized = false; Future init() async { if (isInitialized) return; + _database = await openDatabase( join(await getDatabasesPath(), _dbName), version: _dbVersion, onCreate: _onCreate, onUpgrade: _onUpgrade, onDowngrade: _onDowngrade, + onOpen: _onOpen, + onConfigure: _onConfigure, + singleInstance: true, ); await LicenseRepositoryImpl().updateLicense(); isInitialized = true; } + Future _onConfigure(Database database) async { + print('Configuring database...'); + } + + Future _onOpen(Database database) async { + print('Opening database...'); + await _executePragmas(database); + } + Future _onCreate(Database database, int version) async { - log('Creating database...'); - await database.execute(createKeychainTable); - await database.execute(createLicenseTable); - if (version >= 2) { - await database.execute(updatePetsHistoryTrigger); - await database.execute(updatePeopleDisplayTrigger); - } + print('Creating database...'); + await _createTables(database, version); } Future _onUpgrade(Database database, int oldVersion, int newVersion) async { - log('Upgrading database from version $oldVersion to $newVersion...'); + print('Upgrading database from version $oldVersion to $newVersion...'); if (oldVersion < 2 && newVersion >= 2) { - await database.execute(createLicenseTable); - await database.execute(updatePetsHistoryTrigger); - await database.execute(updatePeopleDisplayTrigger); + await _createTables(database, newVersion); } - - - } Future _onDowngrade(Database database, int oldVersion, int newVersion) async { - log('Downgrading database from version $oldVersion to $newVersion...'); + print('Downgrading database from version $oldVersion to $newVersion...'); if (oldVersion >= 2 && newVersion < 2) { - await database.execute(deleteLicenseTable); - await database.execute(dropPeopleDisplayTrigger); - await database.execute(dropPetsHistoryTrigger); + await _dropTables(database); } } + + Future _executePragmas(Database database) async { + // await database.execute('PRAGMA journal_mode = WAL;'); + await database.execute('PRAGMA synchronous = NORMAL;'); + await database.execute('PRAGMA temp_store = MEMORY;'); + await database.execute('PRAGMA foreign_keys = ON;'); + } + + Future _createTables(Database database, int version) async { + await database.execute(createKeychainTable); + await database.execute(LicenseConstants.createLicenseTable); + if (version >= 2) { + await database.execute(LicenseConstants.updatePetsHistoryTrigger); + await database.execute(LicenseConstants.updateDisplayTrigger); + await database.execute(LicenseConstants.insertDisplayTrigger); + await database.execute(LicenseConstants.updatePeopleDisplayTrigger); + } + } + + Future _dropTables(Database database) async { + await database.execute(LicenseConstants.deleteLicenseTable); + await database.execute(LicenseConstants.dropPeopleDisplayTrigger); + await database.execute(LicenseConstants.dropInsertDisplayTrigger); + await database.execute(LicenseConstants.dropUpdateDisplayTrigger); + await database.execute(LicenseConstants.dropPetsHistoryTrigger); + } } diff --git a/lib/shared/helpers/storage/keychain_storage.dart b/lib/shared/helpers/storage/keychain_storage.dart index d662dc1a..4328c11f 100644 --- a/lib/shared/helpers/storage/keychain_storage.dart +++ b/lib/shared/helpers/storage/keychain_storage.dart @@ -59,6 +59,9 @@ class KeychainHelper implements BaseStorage { Future clearAll() async { try { await DatabaseStorage.database.delete(tableKeychain); + await DatabaseStorage.database.rawDelete( + 'DELETE FROM sqlite_sequence WHERE name = "$tableKeychain"'); + } catch (e, s) { log('() => clearAll keychain: $e', stackTrace: s); } diff --git a/lib/shared/helpers/storage/storage_helper.dart b/lib/shared/helpers/storage/storage_helper.dart index e59c39ea..c157698f 100644 --- a/lib/shared/helpers/storage/storage_helper.dart +++ b/lib/shared/helpers/storage/storage_helper.dart @@ -1,3 +1,5 @@ +import 'dart:developer'; + import 'package:flutter/cupertino.dart'; import 'package:hub/shared/helpers/storage/base_storage.dart'; import 'package:hub/shared/helpers/storage/keychain_storage.dart'; @@ -25,6 +27,7 @@ class StorageHelper { String? isFirstRun = await SharedPreferencesStorage.instance.get(SharedPreferencesKey.isFirstRun.value); if (isFirstRun != 'false') { + log('First run'); await SharedPreferencesStorage.instance.set(SharedPreferencesKey.isFirstRun.value, false); await SecureStorage.instance.set(SecureStorageKey.isLogged.value, false); } diff --git a/lib/shared/services/authentication/authentication_service.dart b/lib/shared/services/authentication/authentication_service.dart index ce753550..2977d9a8 100644 --- a/lib/shared/services/authentication/authentication_service.dart +++ b/lib/shared/services/authentication/authentication_service.dart @@ -3,6 +3,8 @@ import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:hub/features/home/presentation/pages/home_page.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; +import 'package:hub/shared/components/molecules/modules/data/repositories/license_repository_impl.dart'; +import 'package:hub/shared/helpers/database/database_helper.dart'; import 'package:hub/shared/helpers/storage/base_storage.dart'; import 'package:hub/shared/helpers/storage/storage_helper.dart'; @@ -147,7 +149,9 @@ class AuthenticationService { await StorageHelper().clean(Storage.databaseStorage); await StorageHelper().clean(Storage.secureStorage); - await StorageHelper().clean(Storage.databaseStorage); + await LicenseRepositoryImpl().cleanLicense(); + DatabaseStorage.isInitialized = false; + await StorageHelper().init(); context.go('/welcomePage', extra: extra); }