diff --git a/lib/actions/actions.dart b/lib/actions/actions.dart index 34f2ffc1..d4953428 100644 --- a/lib/actions/actions.dart +++ b/lib/actions/actions.dart @@ -76,24 +76,7 @@ Future signInLoginAction( final ApiCallResponse? response; final DatabaseHelper db = DatabaseHelper(); final LoginCall callback = PhpGroup.loginCall; - - final String? devUUID; - final String userUUID; - final String status; - final String userDevUUID; - final String device; - final String email; - final String passwd; - final String description; - final bool haveLocal; - final bool isLogged; - - email = emailAdress!; - passwd = password!; - - devUUID = await getDevUUID(); - device = AppState().device; - description = randomString( + AppState().deviceDescription = randomString( 10, 10, true, @@ -101,45 +84,50 @@ Future signInLoginAction( false, ); + final String? devUUID; + final String userUUID; + final String status; + final String userDevUUID; + final String userName; + final String email; + final String passwd; + final bool isLogged; + + email = emailAdress!; + passwd = password!; + + devUUID = await getDevUUID(); + if ((email != '') && (passwd != '')) { - response = await callback.call( - email: email, - password: passwd, - uuid: devUUID, - type: device, - description: description, - ); + AppState().email = email; + AppState().passwd = passwd; + response = await callback.call(); - if (callback.error((response.jsonBody ?? '')) == false) { - userUUID = callback.userUUID( - (response.jsonBody ?? ''), - )!; - status = callback.userStatus((response.jsonBody ?? ''))!; - userDevUUID = callback.userDeviceId((response.jsonBody ?? ''))!; + if (response.jsonBody['error'] == false) { + userUUID = response.jsonBody['uid']; + + status = response.jsonBody['user']['status']; + userDevUUID = response.jsonBody['user']['dev_id']; + userName = response.jsonBody['user']['name']; - db.update('email', email, 'user'); - db.update('passwd', passwd, 'user'); db.update('devUUID', devUUID, 'user'); db.update('userUUID', userUUID, 'user'); db.update('userDevUUID', userDevUUID, 'user'); db.update('status', status, 'user'); + db.update('userName', userName, 'user'); - callback.userName((response.jsonBody ?? ''))!; isLogged = true; - haveLocal = await checkLocals(context: context, model: model); - - AppState().haveLocal = haveLocal; - AppState().isLogged = isLogged; - - AppState().update(() {}); - - toggleApp(context, haveLocal); + await checkLocals(context: context, model: model).then((value) { + AppState().haveLocal = value; + AppState().isLogged = isLogged; + AppState().update(() {}); + toggleApp(context); + }); } else { - if (callback.msg((response.jsonBody ?? '')) == null) { + if (response.jsonBody['error'] == null) { DialogUtil.errorDefault(context); } else { - DialogUtil.error( - context, callback.msg((response.jsonBody ?? '')).toString()); + DialogUtil.error(context, response.jsonBody['error_msg'].toString()); } } } @@ -160,11 +148,12 @@ Future signUpRegisterAction( String? device, }) async { try { - ApiCallResponse? registerCall; + ApiCallResponse? response; + if ((email != null && email != '') && (passwd != null && passwd != '' && passwd.length > 7) && (name != null && name != '')) { - registerCall = await PhpGroup.registerCall.call( + response = await PhpGroup.registerCall.call( name: name, password: passwd, email: email, @@ -192,14 +181,10 @@ Future signUpRegisterAction( ), ); - if (PhpGroup.registerCall.error( - (registerCall.jsonBody ?? ''), - ) == - false) { + if (response.jsonBody['error'] == false) { return true; } - final errorMessage = registerCall?.jsonBody['error_msg']; - DialogUtil.error(context, errorMessage); + DialogUtil.error(context, response.jsonBody['error_msg']); return false; } else { DialogUtil.errorDefault(context); @@ -224,10 +209,7 @@ Future forgotPasswdAction( email: email, ); - if (callback.error( - (response.jsonBody ?? ''), - ) != - false) { + if (response.jsonBody['error'] != false) { return; } } @@ -256,7 +238,8 @@ Future toggleSignUpPage(BuildContext context) async { ); } -Future toggleApp(BuildContext context, bool haveLocal) async { +Future toggleApp(BuildContext context) async { + final haveLocal = AppState().haveLocal; if (haveLocal == true) { context.go('/homePage'); } else if (haveLocal == false) { @@ -279,22 +262,8 @@ Future visitCancelAction(BuildContext context, required String? email}) async { final ApiCallResponse? response; final CancelaVisita callback = PhpGroup.cancelaVisita; - final DatabaseHelper db = DatabaseHelper(); - final userUUID = await db - .get(key: 'userUUID', field: 'value') - .then((value) => value.toString()); - final devUUID = await db - .get(key: 'devUUID', field: 'value') - .then((value) => value.toString()); - final cliUUID = await db - .get(key: 'cliUUID', field: 'value') - .then((value) => value.toString()); response = await callback.call( - userUUID: userUUID, - devUUID: devUUID, - cliID: cliUUID, - atividade: 'cancelaVisita', idDestino: idDestino, idVisita: idVisita, AccessKey: accessKey, @@ -342,16 +311,9 @@ Future checkLocals({ required FlutterFlowModel model, }) async { final GetLocalsCall callback = PhpGroup.getLocalsCall; - final DatabaseHelper db = DatabaseHelper(); - final userUUID = await db.get(key: 'userUUID', field: 'value'); - final devUUID = await db.get(key: 'devUUID', field: 'value'); - final response = await callback.call( - devUUID: devUUID.toString(), - userUUID: userUUID.toString(), - ); + final response = await callback.call(); - // Verificação rápida de erro para evitar processamento desnecessário. if (response.jsonBody['error']) { DialogUtil.errorDefault(context); return false; @@ -395,16 +357,8 @@ Future answersRequest( required String? id}) async { final ApiCallResponse? respondeSolicitacaoCall; final RespondeSolicitacaoCall callback = PhpGroup.respondeSolicitacaoCall; - final DatabaseHelper db = DatabaseHelper(); - final userUUID = await db.get(key: 'userUUID'); - final devUUID = await db.get(key: 'devUUID'); - final cliUUID = await db.get(key: 'cliUUID'); respondeSolicitacaoCall = await callback.call( - userUUID: userUUID, - devUUID: devUUID, - cliUUID: cliUUID, - atividade: 'respondeSolicitacao', referencia: ref, tarefa: task, resposta: response, diff --git a/lib/app_state.dart b/lib/app_state.dart index 49aef2fb..7052dc0e 100644 --- a/lib/app_state.dart +++ b/lib/app_state.dart @@ -71,19 +71,6 @@ class AppState extends ChangeNotifier { Future initializePersistedState() async { secureStorage = const FlutterSecureStorage(); - await _safeInitAsync(() async { - _cliUUID = await secureStorage.getString('ff_cliUUID') ?? _cliUUID; - }); - - await _safeInitAsync(() async { - _ownerUUID = await secureStorage.getString('ff_ownerUUID') ?? _ownerUUID; - }); - await _safeInitAsync(() async { - _userUUID = await secureStorage.getString('ff_userUUID') ?? _userUUID; - }); - await _safeInitAsync(() async { - _devUUID = await secureStorage.getString('ff_devUUID') ?? _devUUID; - }); await _safeInitAsync(() async { _email = await secureStorage.getString('ff_email') ?? _email; @@ -92,56 +79,17 @@ class AppState extends ChangeNotifier { _passwd = await secureStorage.getString('ff_passwd') ?? _passwd; }); await _safeInitAsync(() async { - _device = await secureStorage.getString('ff_device') ?? _device; + _deviceType = + await secureStorage.getString('ff_deviceType') ?? _deviceType; }); await _safeInitAsync(() async { _isLogged = await secureStorage.getBool('ff_isLogged') ?? _isLogged; }); - await _safeInitAsync(() async { - _local = await secureStorage.getString('ff_local') ?? _local; - }); - await _safeInitAsync(() async { - _token = await secureStorage.getString('ff_token') ?? _token; - }); - await _safeInitAsync(() async { - _createdAt = await secureStorage.getString('ff_createdAt') ?? _createdAt; - }); - await _safeInitAsync(() async { - _updatedAt = await secureStorage.getString('ff_updatedAt') ?? _updatedAt; - }); - await _safeInitAsync(() async { - _status = await secureStorage.getString('ff_status') ?? _status; - }); - await _safeInitAsync(() async { - _name = await secureStorage.getString('ff_name') ?? _name; - }); + await _safeInitAsync(() async { _tokenAPNS = await secureStorage.getString('ff_tokenAPNS') ?? _tokenAPNS; }); - await _safeInitAsync(() async { - _userDevUUID = - await secureStorage.getString('ff_user_dev_id') ?? _userDevUUID; - }); - await _safeInitAsync(() async { - _serialNumber = - await secureStorage.getString('ff_serialNumber') ?? _serialNumber; - }); - await _safeInitAsync(() async { - _fingerprintOPT = - await secureStorage.getBool('fingerprint') ?? _fingerprintOPT; - }); - await _safeInitAsync(() async { - _personOPT = await secureStorage.getBool('person') ?? _personOPT; - }); - await _safeInitAsync(() async { - _passOPT = await secureStorage.getBool('pass') ?? _passOPT; - }); - await _safeInitAsync(() async { - _panicOPT = await secureStorage.getBool('panic') ?? _panicOPT; - }); - await _safeInitAsync(() async { - _notifyOPT = await secureStorage.getBool('notify') ?? _notifyOPT; - }); + await _safeInitAsync(() async { _accessPass = await secureStorage.getString('accessPass') ?? _accessPass; }); @@ -155,27 +103,14 @@ class AppState extends ChangeNotifier { await _safeInitAsync(() async { _context = await secureStorage.getObject('ff_context') ?? _context; }); - await _safeInitAsync(() async { - _provisional = await secureStorage.getBool('provisional') ?? _provisional; - }); - await _safeInitAsync(() async { - _whatsapp = await secureStorage.getBool('whatsapp') ?? _whatsapp; - }); - await _safeInitAsync(() async { - _pets = await secureStorage.getBool('pets') ?? _pets; - }); + await _safeInitAsync(() async { _haveLocal = await secureStorage.getBool('ff_have_local') ?? _haveLocal; }); - await _safeInitAsync(() async { - _petAmountRegister = - await secureStorage.getInt('petAmountRegister') ?? _petAmountRegister; - }); await _safeInitAsync(() async { - _isRequestOSNotification = - await secureStorage.getBool('ff_request_os_notification') ?? - _isRequestOSNotification; + _deviceDescription = await secureStorage.getString('deviceDescription') ?? + _deviceDescription; }); } @@ -186,60 +121,15 @@ class AppState extends ChangeNotifier { late FlutterSecureStorage secureStorage; - int _petAmountRegister = 0; - int get petAmountRegister => _petAmountRegister; - set petAmountRegister(int value) { - _petAmountRegister = value; - secureStorage.setInt('petAmountRegister', value); + String _deviceDescription = ''; + String get deviceDescription => _deviceDescription; + set deviceDescription(String value) { + _deviceDescription = value; + secureStorage.setString('deviceDescription', value); } - void deletePetAmountRegister() { - secureStorage.delete(key: 'petAmountRegister'); - } - - bool _isRequestOSNotification = false; - bool get isRequestOSNotification => _isRequestOSNotification; - set isRequestOSNotification(bool value) { - _isRequestOSNotification = value; - secureStorage.setBool('ff_request_os_notification', value); - } - - void deleteIsRequestOSNotification() { - secureStorage.delete(key: 'ff_request_os_notification'); - } - - bool _pets = false; - bool get pets => _pets; - set pets(bool value) { - _pets = value; - secureStorage.setBool('pets', value); - } - - void deletePets() { - secureStorage.delete(key: 'pets'); - } - - bool _whatsapp = false; - bool get whatsapp => _whatsapp; - - set whatsapp(bool value) { - _whatsapp = value; - secureStorage.setBool('whatsapp', value); - } - - void deleteWhatsapp() { - secureStorage.delete(key: 'whatsapp'); - } - - bool _provisional = false; - bool get provisional => _provisional; - set provisional(bool value) { - _provisional = value; - secureStorage.setBool('provisional', value); - } - - void deleteProvisional() { - secureStorage.delete(key: 'provisional'); + void deleteDeviceDescription() { + secureStorage.delete(key: 'deviceDescription'); } BuildContext? _context; @@ -253,17 +143,6 @@ class AppState extends ChangeNotifier { secureStorage.delete(key: 'ff_context'); } - bool _panicOPT = false; - bool get panic => _panicOPT; - set panic(bool value) { - _panicOPT = value; - secureStorage.setBool('panic', value); - } - - void deletePanic() { - secureStorage.delete(key: 'panic'); - } - bool? _haveLocal = null; bool? get haveLocal => _haveLocal; set haveLocal(bool? value) { @@ -308,88 +187,11 @@ class AppState extends ChangeNotifier { secureStorage.delete(key: 'panicPass'); } - bool _notifyOPT = false; - bool get notify => _notifyOPT; - set notify(bool value) { - _notifyOPT = value; - secureStorage.setBool('notify', value); - } - - bool _passOPT = false; - bool get pass => _passOPT; - set pass(bool value) { - _passOPT = value; - secureStorage.setBool('pass', value); - } - - void deletePass() { - secureStorage.delete(key: 'pass'); - } - - bool _personOPT = false; - bool get person => _personOPT; - set person(bool value) { - _personOPT = value; - secureStorage.setBool('person', value); - } - - void deletePerson() { - secureStorage.delete(key: 'person'); - } - - bool _fingerprintOPT = false; - bool get fingerprint => _fingerprintOPT; - set fingerprint(bool value) { - _fingerprintOPT = value; - secureStorage.setBool('fingerprint', value); - } - - void deleteFingerprint() { - secureStorage.delete(key: 'fingerprint'); - } - - String _serialNumber = ''; - String get serialNumber => _serialNumber; - set serialNumber(String value) { - _serialNumber = value; - secureStorage.setString('ff_serialNumber', value); - } - - void deleteSerialNumber() { - secureStorage.delete(key: 'ff_serialNumber'); - AppState().serialNumber = ''; - } - - String _cliUUID = ''; - String get cliUUID => _cliUUID; - set cliUUID(String value) { - _cliUUID = value; - secureStorage.setString('ff_cliUUID', value); - } - - void deleteCliUUID() { - secureStorage.delete(key: 'ff_cliUUID'); - AppState().cliUUID = ''; - } - - String _userDevUUID = ''; - String get userDevUUID => _userDevUUID; - set userDevUUID(String value) { - _userDevUUID = value; - secureStorage.setString('ff_user_dev_id', value); - } - - void deleteRemoteId() { - secureStorage.delete(key: 'ff_user_dev_id'); - AppState().userDevUUID = ''; - } - String? _tokenAPNS = ''; String? get tokenAPNS => _tokenAPNS; set tokenAPNS(String? value) { _tokenAPNS = value; - // Verifica se o valor é nulo antes de tentar salvar no secureStorage if (value != null) { secureStorage.setString('ff_tokenAPNS', value); } else { @@ -402,42 +204,6 @@ class AppState extends ChangeNotifier { AppState().tokenAPNS = ''; } - String _ownerUUID = ''; - String get ownerUUID => _ownerUUID; - set ownerUUID(String value) { - _ownerUUID = value; - secureStorage.setString('ff_ownerUUID', value); - } - - void deleteOwnerUUID() { - secureStorage.delete(key: 'ff_ownerUUID'); - AppState().ownerUUID = ''; - } - - String _userUUID = ''; - String get userUUID => _userUUID; - set userUUID(String value) { - _userUUID = value; - secureStorage.setString('ff_userUUID', value); - } - - void deleteUserUUID() { - secureStorage.delete(key: 'ff_userUUID'); - AppState().userUUID = ''; - } - - String _devUUID = ''; - String get devUUID => _devUUID; - set devUUID(String value) { - _devUUID = value; - secureStorage.setString('ff_devUUID', value); - } - - void deleteDevUUID() { - secureStorage.delete(key: 'ff_devUUID'); - AppState().devUUID = ''; - } - String _email = ''; String get email => _email; set email(String value) { @@ -462,16 +228,16 @@ class AppState extends ChangeNotifier { AppState().passwd = ''; } - String _device = ''; - String get device => _device; - set device(String value) { - _device = value; - secureStorage.setString('ff_device', value); + String _deviceType = ''; + String get deviceType => _deviceType; + set deviceType(String value) { + _deviceType = value; + secureStorage.setString('ff_deviceType', value); } void deleteDevice() { - secureStorage.delete(key: 'ff_device'); - AppState().device = ''; + secureStorage.delete(key: 'ff_deviceType'); + AppState().deviceType = ''; } bool _isLogged = false; @@ -485,18 +251,6 @@ class AppState extends ChangeNotifier { secureStorage.delete(key: 'ff_isLogged'); } - String _local = ''; - String get local => _local; - set local(String value) { - _local = value; - secureStorage.setString('ff_local', value); - } - - void deleteLocal() { - secureStorage.delete(key: 'ff_local'); - AppState().local = ''; - } - String _token = ''; String get token => _token; set token(String value) { @@ -509,82 +263,17 @@ class AppState extends ChangeNotifier { AppState().token = ''; } - String _createdAt = ''; - String get createdAt => _createdAt; - set createdAt(String value) { - _createdAt = value; - secureStorage.setString('ff_createdAt', value); - } - - void deleteCreatedAt() { - secureStorage.delete(key: 'ff_createdAt'); - AppState().createdAt = ''; - } - - String _updatedAt = ''; - String get updatedAt => _updatedAt; - set updatedAt(String value) { - _updatedAt = value; - secureStorage.setString('ff_updatedAt', value); - } - - void deleteUpdatedAt() { - secureStorage.delete(key: 'ff_updatedAt'); - AppState().updatedAt = ''; - } - - String _status = ''; - String get status => _status; - set status(String value) { - _status = value; - secureStorage.setString('ff_status', value); - } - - void deleteStatus() { - secureStorage.delete(key: 'ff_status'); - AppState().status = ''; - } - - String _name = ''; - String get name => _name; - set name(String value) { - _name = value; - secureStorage.setString('ff_name', value); - } - - void deleteName() { - secureStorage.delete(key: 'ff_name'); - AppState().name = ''; - } - void deleteAll() { AppState().deleteAccessPass(); - AppState().deleteCliUUID(); - AppState().deleteCreatedAt(); - AppState().deleteDevUUID(); AppState().deleteDevice(); AppState().deleteEmail(); - AppState().deleteFingerprint(); AppState().deleteFingerprintPass(); AppState().deleteIsLogged(); - AppState().deleteLocal(); - AppState().deleteName(); - AppState().deleteOwnerUUID(); - AppState().deletePass(); AppState().deletePasswd(); - AppState().deletePerson(); - AppState().deletePanic(); AppState().deletePanicPass(); - AppState().deleteProvisional(); - AppState().deleteStatus(); AppState().deleteToken(); AppState().deleteTokenAPNS(); - AppState().deleteUpdatedAt(); - AppState().deleteUserUUID(); - AppState().deleteWhatsapp(); AppState().deleteContext(); - AppState().deleteRemoteId(); - AppState().deleteSerialNumber(); secureStorage.deleteAll(); AppState().isLogged = false; } diff --git a/lib/backend/api_requests/api_calls.dart b/lib/backend/api_requests/api_calls.dart index c3dcf8ed..dab1d43b 100644 --- a/lib/backend/api_requests/api_calls.dart +++ b/lib/backend/api_requests/api_calls.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'dart:developer'; import 'package:flutter/foundation.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/validator_util.dart'; import '/flutter_flow/flutter_flow_util.dart'; @@ -25,7 +26,6 @@ class PhpGroup { static PostScheduleVisitorCall postScheduleVisitorCall = PostScheduleVisitorCall(); static PostScheduleVisitCall postScheduleVisitCall = PostScheduleVisitCall(); - static DebugCallCall debugCallCall = DebugCallCall(); static GetScheduleVisitCall getScheduleVisitCall = GetScheduleVisitCall(); static GetDadosCall getDadosCall = GetDadosCall(); static GetVisitorByDocCall getVisitorByDocCall = GetVisitorByDocCall(); @@ -39,8 +39,6 @@ class PhpGroup { RespondeSolicitacaoCall(); static GetAccessCall getAccessCall = GetAccessCall(); static GetLiberationsCall getLiberationsCall = GetLiberationsCall(); - static GetLiberationsCopyCall getLiberationsCopyCall = - GetLiberationsCopyCall(); static GetMessagesCall getMessagesCall = GetMessagesCall(); static ChangeNotifica changeNotifica = ChangeNotifica(); static RespondeVinculo resopndeVinculo = RespondeVinculo(); @@ -58,11 +56,15 @@ class PhpGroup { } class UnregisterDevice { - Future call({ - String? devUUID = '', - String? userUUID = '', - }) async { + Future call() async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); return ApiManager.instance.makeApiCall( callName: 'unregisterDevice', @@ -88,13 +90,20 @@ class UnregisterDevice { class DeletePet { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = 'excluirPet', int? petID = 0, }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'excluirPet'; return ApiManager.instance.makeApiCall( callName: 'deletePet', @@ -123,10 +132,6 @@ class DeletePet { class UpdatePet { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = 'atualizarPet', int? petID = 0, String? image = '', String? name = '', @@ -139,6 +144,17 @@ class UpdatePet { String? notes = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'atualizarPet'; return ApiManager.instance.makeApiCall( callName: 'updatePet', @@ -176,14 +192,21 @@ class UpdatePet { class GetPets { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = 'consultaPets', int? page = 0, int? pageSize = 0, }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'consultaPets'; return ApiManager.instance.makeApiCall( callName: 'getPets', @@ -212,13 +235,20 @@ class GetPets { class GetPetPhoto { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = 'consultaFotoPet', int? petId = 0, }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'consultaFotoPet'; return ApiManager.instance.makeApiCall( callName: 'getPetPhoto', @@ -246,10 +276,6 @@ class GetPetPhoto { class RegisterPet { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = 'cadastrarPet', String? image = '', String? name = '', String? species = '', @@ -261,6 +287,17 @@ class RegisterPet { String? notes = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'cadastrarPet'; return ApiManager.instance.makeApiCall( callName: 'registerPet', @@ -299,15 +336,23 @@ class RegisterPet { class BuscaEnconcomendas { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? page = '', String? pageSize = '', String? adresseeType = '', String? status = '', }) async { + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'getEncomendas'; + final baseUrl = PhpGroup.getBaseUrl(); return ApiManager.instance.makeApiCall( @@ -335,19 +380,10 @@ class BuscaEnconcomendas { alwaysAllowBody: false, ); } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); } class CancelaVisita { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', int? idDestino, int? idVisita, String? AccessKey = '', @@ -355,6 +391,17 @@ class CancelaVisita { String? DevDesc = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + const atividade = 'cancelaVisita'; + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); return ApiManager.instance.makeApiCall( callName: 'cancelaVisita', @@ -381,18 +428,17 @@ class CancelaVisita { alwaysAllowBody: false, ); } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); } class DeleteAccount { - Future call({ - String? devUUID = '', - String? userUUID = '', - }) async { + Future call() async { + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); final baseUrl = PhpGroup.getBaseUrl(); return ApiManager.instance.makeApiCall( callName: 'deleteAccount', @@ -414,22 +460,25 @@ class DeleteAccount { alwaysAllowBody: false, ); } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); } class ChangePanic { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? newSenhaPanico = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'updVisitado'; return ApiManager.instance.makeApiCall( callName: 'changePass', @@ -454,22 +503,24 @@ class ChangePanic { alwaysAllowBody: false, ); } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); } class ChangePass { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? newSenha = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'updVisitado'; return ApiManager.instance.makeApiCall( callName: 'changePass', @@ -494,21 +545,21 @@ class ChangePass { alwaysAllowBody: false, ); } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); } class RespondeVinculo { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', String? tarefa = '', + String? cliID = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); return ApiManager.instance.makeApiCall( callName: 'respondeVinculo', @@ -536,13 +587,20 @@ class RespondeVinculo { class ChangeNotifica { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? notifica = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'updVisitado'; return ApiManager.instance.makeApiCall( callName: 'changeNotifica', @@ -567,20 +625,19 @@ class ChangeNotifica { alwaysAllowBody: false, ); } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); } class UpdToken { - Future call({ - String? token = '', - String? devid = '', - String? useruuid = '', - }) async { + Future call() async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final token = AppState().token; return ApiManager.instance.makeApiCall( callName: 'updToken', @@ -591,8 +648,8 @@ class UpdToken { }, params: { 'token': token, - 'devid': devid, - 'useruuid': useruuid, + 'devid': devUUID, + 'useruuid': userUUID, }, bodyType: BodyType.X_WWW_FORM_URL_ENCODED, returnBody: true, @@ -602,22 +659,19 @@ class UpdToken { alwaysAllowBody: false, ); } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); } class LoginCall { - Future call({ - String? email = '', - String? password = '', - String? uuid = '', - String? type = '', - String? description = '', - }) async { + Future call() async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final email = AppState().email; + final password = AppState().passwd; + final type = AppState().deviceType; + final description = AppState().deviceDescription; return ApiManager.instance.makeApiCall( callName: 'login', @@ -629,7 +683,7 @@ class LoginCall { params: { 'email': email, 'password': password, - 'uuid': uuid, + 'uuid': devUUID, 'tipo': type, 'descricao': description, }, @@ -642,52 +696,6 @@ class LoginCall { alwaysAllowBody: false, ); } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); - String? msg(dynamic response) => castToType(getJsonField( - response, - r'''$.error_msg''', - )); - List? info(dynamic response) => getJsonField( - response, - r'''$.error_info''', - true, - ) as List?; - String? userUUID(dynamic response) => castToType(getJsonField( - response, - r'''$.uid''', - )); - dynamic userObject(dynamic response) => getJsonField( - response, - r'''$.user''', - ); - String? userName(dynamic response) => castToType(getJsonField( - response, - r'''$.user.name''', - )); - String? userEmail(dynamic response) => castToType(getJsonField( - response, - r'''$.user.email''', - )); - String? userDeviceId(dynamic response) => castToType(getJsonField( - response, - r'''$.user.dev_id''', - )); - String? userCreatAt(dynamic response) => castToType(getJsonField( - response, - r'''$.user.created_at''', - )); - String? userUpdateAt(dynamic response) => castToType(getJsonField( - response, - r'''$.user.updated_at''', - )); - String? userStatus(dynamic response) => castToType(getJsonField( - response, - r'''$.user.status''', - )); } class RegisterCall { @@ -727,35 +735,6 @@ class RegisterCall { alwaysAllowBody: false, ); } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); - String? uid(dynamic response) => castToType(getJsonField( - response, - r'''$.uid''', - )); - dynamic user(dynamic response) => getJsonField( - response, - r'''$.user''', - ); - String? name(dynamic response) => castToType(getJsonField( - response, - r'''$.user.name''', - )); - String? email(dynamic response) => castToType(getJsonField( - response, - r'''$.user.email''', - )); - String? devId(dynamic response) => castToType(getJsonField( - response, - r'''$.user.dev_id''', - )); - String? createdAt(dynamic response) => castToType(getJsonField( - response, - r'''$.user.created_at''', - )); } class ForgotPasswordCall { @@ -783,23 +762,18 @@ class ForgotPasswordCall { alwaysAllowBody: false, ); } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); - String? msg(dynamic response) => castToType(getJsonField( - response, - r'''$.error_msg''', - )); } class GetLocalsCall { - Future call({ - String? devUUID = '', - String? userUUID = '', - }) async { + Future call() async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); return ApiManager.instance.makeApiCall( callName: 'getLocals', @@ -822,65 +796,32 @@ class GetLocalsCall { ); } - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); List? locais(dynamic response) => getJsonField( response, r'''$.locais''', true, ) as List?; - String? cluOwnerID(dynamic response) => castToType(getJsonField( - response, - r'''$.locais[:].CLU_OWNER_ID''', - )); - String? cluOwnerDSC(dynamic response) => castToType(getJsonField( - response, - r'''$.locais[:].CLU_OWNER_DSC''', - )); - String? cluStatus(dynamic response) => castToType(getJsonField( - response, - r'''$.locais[:].CLU_STATUS''', - )); - String? cluBlkMessage(dynamic response) => castToType(getJsonField( - response, - r'''$.locais[:].CLU_BLK_MESSAGE''', - )); - String? cliID(dynamic response) => castToType(getJsonField( - response, - r'''$.locais[:].CLI_ID''', - )); - String? cliPrefix(dynamic response) => castToType(getJsonField( - response, - r'''$.locais[:].CLI_PREFIXO''', - )); - String? cliName(dynamic response) => castToType(getJsonField( - response, - r'''$.locais[:].CLI_NOME''', - )); - String? userName(dynamic response) => castToType(getJsonField( - response, - r'''$.locais[:].USU_NOME''', - )); - String? cliSysId(dynamic response) => castToType(getJsonField( - response, - r'''$.locais[:].CLI_SIS_ID''', - )); } class PostScheduleVisitorCall { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = 'putVisitante', String? documento = '', String? nome = '', String? tipo = '', String? foto = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'putVisitante'; return ApiManager.instance.makeApiCall( callName: 'postScheduleVisitor', @@ -921,10 +862,6 @@ class PostScheduleVisitorCall { class PostScheduleVisitCall { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? devDesc = '', String? idVisitante = '', String? dtInicio = '', @@ -935,6 +872,17 @@ class PostScheduleVisitCall { String? obs = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'putVisita'; return ApiManager.instance.makeApiCall( callName: 'postScheduleVisit', @@ -977,75 +925,24 @@ class PostScheduleVisitCall { )); } -class DebugCallCall { - Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', - String? devDesc = '', - String? idVisitante = '', - String? dtInicio = '', - String? dtFim = '', - String? unica = '', - int? idMotivo, - int? idNAC, - String? obs = '', - }) async { - final baseUrl = PhpGroup.getBaseUrl(); - - return ApiManager.instance.makeApiCall( - callName: 'debugCall', - apiUrl: '$baseUrl/jonh.php', - callType: ApiCallType.POST, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - params: { - 'devUUID': devUUID, - 'userUUID': userUUID, - 'cliID': cliID, - 'atividade': atividade, - 'DevDesc': devDesc, - 'idVisitante': idVisitante, - 'dtInicio': dtInicio, - 'dtFim': dtFim, - 'unica': unica, - 'idMotivo': idMotivo, - 'idNAC': idNAC, - 'obs': obs, - }, - bodyType: BodyType.X_WWW_FORM_URL_ENCODED, - returnBody: true, - encodeBodyUtf8: false, - decodeUtf8: false, - cache: false, - isStreamingApi: false, - alwaysAllowBody: false, - ); - } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); - String? errorMsg(dynamic response) => castToType(getJsonField( - response, - r'''$.error_msg''', - )); -} - class GetScheduleVisitCall { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliUUID = '', - String? atividade = '', int? pageSize, int? pageNumber, String? chaveBusca = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'getVisitas'; return ApiManager.instance.makeApiCall( callName: 'getScheduleVisit', @@ -1313,13 +1210,19 @@ class GetScheduleVisitCall { } class GetDadosCall { - Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliUUID = '', - String? atividade = 'getDados', - }) async { + Future call() async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'getDados'; return ApiManager.instance.makeApiCall( callName: 'getDados', @@ -1555,13 +1458,20 @@ class GetDadosCall { class GetVisitorByDocCall { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? documento = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'getVisitante'; return ApiManager.instance.makeApiCall( callName: 'getVisitorByDoc', @@ -1603,35 +1513,25 @@ class GetVisitorByDocCall { response, r'''$.visitante.VTE_ID''', )); - String? visitanteNome(dynamic response) => castToType(getJsonField( - response, - r'''$.visitante.VTE_NOME''', - )); - String? visitanteRG(dynamic response) => castToType(getJsonField( - response, - r'''$.visitante.VTE_RG''', - )); - String? visitanteDocumento(dynamic response) => - castToType(getJsonField( - response, - r'''$.visitante.VTE_DOCUMENTO''', - )); - String? visitanteTipo(dynamic response) => castToType(getJsonField( - response, - r'''$.visitante.VTE_TIPO''', - )); } class GetFotoVisitanteCall { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? documento = '', String? tipo = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'getFotoVisitante'; return ApiManager.instance.makeApiCall( callName: 'getFotoVisitante', @@ -1660,16 +1560,23 @@ class GetFotoVisitanteCall { class PostProvVisitSchedulingCall { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? data = '', String? motivo = '', String? nome = '', String? proID = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'putAgendamentoProv'; return ApiManager.instance.makeApiCall( callName: 'postProvVisitScheduling', @@ -1710,14 +1617,21 @@ class PostProvVisitSchedulingCall { class GetVisitsCall { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', int? pageSize, int? pageNumber, }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'getVisitas'; return ApiManager.instance.makeApiCall( callName: 'getVisits', @@ -1973,13 +1887,20 @@ class GetVisitsCall { class DeleteVisitCall { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? idVisita = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'cancelaVisita'; return ApiManager.instance.makeApiCall( callName: 'deleteVisit', @@ -2016,13 +1937,21 @@ class DeleteVisitCall { } class GetPessoasLocalCall { - Future call({ - String? cliID = '', - String? ownID = '', - String? devUUID = '', - String? userUUID = '', - }) async { + Future call() async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final ownerUUID = await db + .get(key: 'ownerUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); return ApiManager.instance.makeApiCall( callName: 'getPessoasLocal', @@ -2032,8 +1961,8 @@ class GetPessoasLocalCall { 'Content-Type': 'application/x-www-form-urlencoded', }, params: { - 'cliID': cliID, - 'ownID': ownID, + 'cliID': cliUUID, + 'ownID': ownerUUID, 'devUUID': devUUID, 'userUUID': userUUID, }, @@ -2078,16 +2007,23 @@ class GetPessoasLocalCall { class RespondeSolicitacaoCall { Future call({ - String? userUUID = '', - String? devUUID = '', - String? atividade = '', String? referencia = '', String? tarefa = '', String? resposta = '', String? idVisitante = '', - String? cliUUID = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'respondeSolicitacao'; return ApiManager.instance.makeApiCall( callName: 'respondeSolicitacao', @@ -2128,15 +2064,22 @@ class RespondeSolicitacaoCall { class GetAccessCall { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? pageSize = '', String? pageNumber = '', String? pesTipo = '', - }) { + }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'getAcessos'; return ApiManager.instance.makeApiCall( callName: 'getAccess', @@ -2148,7 +2091,7 @@ class GetAccessCall { params: { 'devUUID': devUUID, 'userUUID': userUUID, - 'cliID': cliID, + 'cliID': cliUUID, 'atividade': atividade, 'pageSize': pageSize, 'pageNumber': pageNumber, @@ -2377,16 +2320,22 @@ class GetAccessCall { } class GetLiberationsCall { - Stream call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', - }) { + Stream call() { final baseUrl = PhpGroup.getBaseUrl(); final StreamController controller = StreamController(); + final DatabaseHelper db = DatabaseHelper(); Future.microtask(() async { + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'getSolicitacoes'; try { final response = await ApiManager.instance.makeApiCall( callName: 'getLiberations', @@ -2398,7 +2347,7 @@ class GetLiberationsCall { params: { 'devUUID': devUUID, 'userUUID': userUUID, - 'cliID': cliID, + 'cliID': cliUUID, 'atividade': atividade, }, bodyType: BodyType.X_WWW_FORM_URL_ENCODED, @@ -2568,15 +2517,22 @@ class GetLiberationsCall { class GetMessagesCall { Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', String? pageSize = '', String? pageNumber = '', String? tipoDestino = '', }) async { final baseUrl = PhpGroup.getBaseUrl(); + final DatabaseHelper db = DatabaseHelper(); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + const atividade = 'getMensagens'; return ApiManager.instance.makeApiCall( callName: 'getMessages', @@ -2588,7 +2544,7 @@ class GetMessagesCall { params: { 'devUUID': devUUID, 'userUUID': userUUID, - 'cliID': cliID, + 'cliID': cliUUID, 'atividade': atividade, 'pageSize': pageSize, 'pageNumber': pageNumber, @@ -2605,190 +2561,6 @@ class GetMessagesCall { } } -class GetLiberationsCopyCall { - Future call({ - String? devUUID = '', - String? userUUID = '', - String? cliID = '', - String? atividade = '', - String? page = '', - String? pageSize = '', - String? filter = '', - }) async { - final baseUrl = PhpGroup.getBaseUrl(); - - return ApiManager.instance.makeApiCall( - callName: 'getMessages', - apiUrl: '$baseUrl/processRequest.php', - callType: ApiCallType.POST, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - params: { - 'devUUID': devUUID, - 'userUUID': userUUID, - 'cliID': cliID, - 'atividade': atividade, - 'page': page, - 'pageSize': pageSize, - 'filter': filter, - }, - bodyType: BodyType.X_WWW_FORM_URL_ENCODED, - returnBody: true, - encodeBodyUtf8: false, - decodeUtf8: false, - cache: false, - isStreamingApi: false, - alwaysAllowBody: false, - ); - } - - bool? error(dynamic response) => castToType(getJsonField( - response, - r'''$.error''', - )); - List? rqList(dynamic response) => getJsonField( - response, - r'''$.solicitacoes''', - true, - ) as List?; - List? rqNotID(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_ID''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotDest(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_DESTINO''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotSendDate(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_DTENVIO''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotReceiveDate(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_DTRESPOSTA''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotEmailAnswer(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_EMAILRESPOSTA''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotReason(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_MOTIVO''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotSendMsg(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_MSGENVIO''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotReceiveMsg(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_MSGRESPOSTA''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotName(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_NOME''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotOperator(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_OPERADOR''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotStatus(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_STATUS''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqNotVTE(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].NOT_VISITANTE''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqVteID(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].VTE_ID''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqVteName(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].VTE_NOME''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); - List? rqVteRG(dynamic response) => (getJsonField( - response, - r'''$.solicitacoes[:].VTE_RG''', - true, - ) as List?) - ?.withoutNulls - .map((x) => castToType(x)) - .withoutNulls - .toList(); -} - /// End PHP Group Code class ApiPagingParams { diff --git a/lib/backend/notifications/firebase_messaging_service.dart b/lib/backend/notifications/firebase_messaging_service.dart index e6351ecf..36464962 100644 --- a/lib/backend/notifications/firebase_messaging_service.dart +++ b/lib/backend/notifications/firebase_messaging_service.dart @@ -63,17 +63,13 @@ class FirebaseMessagingService { if (deviceToken != null) { AppState().token = deviceToken; final ApiCallResponse? response; - final DatabaseHelper db = DatabaseHelper(); - final devUUID = await db.get(key: 'devUUID', field: 'value'); - final userUUID = await db.get(key: 'userUUID', field: 'value'); - response = await PhpGroup.updToken - .call(token: AppState().token, devid: devUUID, useruuid: userUUID); + response = await PhpGroup.updToken.call(); - if (PhpGroup.updToken.error((response?.jsonBody ?? '')) == false) { + if (response.jsonBody['error'] == false) { log('Token Atualizado com Sucesso!'); } else { - log('Falha ao Atualizar Token: ${response?.jsonBody}'); + log('Falha ao Atualizar Token: ${response.jsonBody}'); } } else { log('Falha ao Pegar Token do Firebase'); diff --git a/lib/backend/notifications/notification_service.dart b/lib/backend/notifications/notification_service.dart index 79b7cb7f..424cdb2a 100644 --- a/lib/backend/notifications/notification_service.dart +++ b/lib/backend/notifications/notification_service.dart @@ -267,9 +267,14 @@ class NotificationService { await AwesomeNotifications() .isNotificationAllowed() .then((isAllowed) async { - if (!AppState().isRequestOSNotification) { + final DatabaseHelper db = DatabaseHelper(); + final bool requestOSnotification = await db + .get(key: 'requestOSnotification', field: 'value') + .then((value) => value.toString() == 'true'); + + if (!requestOSnotification) { if (!isAllowed) { - AppState().isRequestOSNotification = true; + await db.update('requestOSnotification', 'true', 'util'); await AwesomeNotifications().requestPermissionToSendNotifications(); } } diff --git a/lib/components/organism_components/bottom_arrow_linked_locals_component/bottom_arrow_linked_locals_component_widget.dart b/lib/components/organism_components/bottom_arrow_linked_locals_component/bottom_arrow_linked_locals_component_widget.dart index 4ef1ba1c..06f4b4ee 100644 --- a/lib/components/organism_components/bottom_arrow_linked_locals_component/bottom_arrow_linked_locals_component_widget.dart +++ b/lib/components/organism_components/bottom_arrow_linked_locals_component/bottom_arrow_linked_locals_component_widget.dart @@ -70,10 +70,7 @@ class _BottomArrowLinkedLocalsComponentWidgetState final userUUID = await db.get(key: 'userUUID', field: 'value'); setState(() => _loading = true); - var response = await PhpGroup.getLocalsCall.call( - devUUID: devUUID, - userUUID: userUUID, - ); + var response = await PhpGroup.getLocalsCall.call(); final List locals = response.jsonBody['locais'] ?? []; @@ -115,12 +112,8 @@ class _BottomArrowLinkedLocalsComponentWidgetState Future _fetchResponseLink(String status, String cliID) async { try { - final DatabaseHelper db = DatabaseHelper(); - final devUUID = await db.get(key: 'devUUID', field: 'value'); - final userUUID = await db.get(key: 'userUUID', field: 'value'); - - var response = await PhpGroup.resopndeVinculo.call( - devUUID: devUUID, userUUID: userUUID, cliID: cliID, tarefa: status); + var response = + await PhpGroup.resopndeVinculo.call(tarefa: status, cliID: cliID); if (response.jsonBody['error'] == false) { return { diff --git a/lib/components/organism_components/local_profile_component/local_profile_component_model.dart b/lib/components/organism_components/local_profile_component/local_profile_component_model.dart index 1bab9c96..6b17df55 100644 --- a/lib/components/organism_components/local_profile_component/local_profile_component_model.dart +++ b/lib/components/organism_components/local_profile_component/local_profile_component_model.dart @@ -1,3 +1,6 @@ +import 'dart:ffi'; +import 'dart:math'; + import 'package:hub/shared/helpers/db_helper.dart'; import '/flutter_flow/flutter_flow_util.dart'; @@ -11,19 +14,21 @@ class LocalProfileComponentModel final DatabaseHelper db = DatabaseHelper(); String cliName = ''; String cliUUID = ''; + VoidCallback? setStateCallback; @override void initState(BuildContext context) { - init(); + getData(); } - Future init() async { + Future getData() async { cliName = await db .get(key: 'cliName', field: 'value') .then((value) => value.toString()); cliUUID = await db .get(key: 'cliUUID', field: 'value') .then((value) => value.toString()); + setStateCallback?.call(); } @override diff --git a/lib/components/organism_components/local_profile_component/local_profile_component_widget.dart b/lib/components/organism_components/local_profile_component/local_profile_component_widget.dart index d290feb8..e0dbbc42 100644 --- a/lib/components/organism_components/local_profile_component/local_profile_component_widget.dart +++ b/lib/components/organism_components/local_profile_component/local_profile_component_widget.dart @@ -1,6 +1,12 @@ +import 'dart:developer'; + import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; +import 'package:hub/backend/api_requests/api_calls.dart'; +import 'package:hub/components/organism_components/bottom_arrow_linked_locals_component/bottom_arrow_linked_locals_component_widget.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; +import 'package:hub/shared/utils/dialog_util.dart'; import 'package:provider/provider.dart'; import '/flutter_flow/custom_functions.dart' as functions; @@ -13,10 +19,7 @@ export 'local_profile_component_model.dart'; //// class LocalProfileComponentWidget extends StatefulWidget { - LocalProfileComponentWidget({Key? key, required this.showBottomSheet}) - : super(key: key); - - VoidCallback showBottomSheet; + LocalProfileComponentWidget({Key? key}) : super(key: key); @override State createState() => @@ -26,6 +29,7 @@ class LocalProfileComponentWidget extends StatefulWidget { class _LocalProfileComponentWidgetState extends State { late LocalProfileComponentModel _model; + final DatabaseHelper db = DatabaseHelper(); @override void setState(VoidCallback callback) { @@ -37,6 +41,18 @@ class _LocalProfileComponentWidgetState void initState() { super.initState(); _model = createModel(context, () => LocalProfileComponentModel()); + _model.setOnUpdate(onUpdate: () => setState(() {})); + _model.setStateCallback = () => safeSetState(() {}); + + () async { + _model.cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + + if (_model.cliUUID.isEmpty) { + await processLocals(); + } + }(); } @override @@ -46,6 +62,88 @@ class _LocalProfileComponentWidgetState super.dispose(); } + Future processData() async { + try { + final GetDadosCall callback = PhpGroup.getDadosCall; + + var response = await callback.call(); + + final error = response.jsonBody['error']; + // final errorMsg = response.jsonBody['error_msg']; + + if (error == false) { + final whatsapp = response.jsonBody['whatsapp'] ?? false; + final provisional = response.jsonBody['provisional'] ?? false; + final pets = response.jsonBody['pet'] ?? false; + final petAmountRegister = response.jsonBody['petAmountRegister'] ?? '0'; + final name = response.jsonBody['visitado']['VDO_NOME']; + + await db.update('whatsapp', whatsapp.toString(), 'local'); + await db.update('provisional', provisional.toString(), 'local'); + await db.update('pets', pets.toString(), 'local'); + await db.update('petAmountRegister', petAmountRegister, 'local'); + await db.update('name', name, 'local'); + + safeSetState(() {}); + return; + } + + DialogUtil.warningDefault(context).whenComplete(() => processLocals()); + safeSetState(() {}); + return; + } catch (e, s) { + DialogUtil.warningDefault(context).whenComplete(() => processLocals()); + } + } + + Future processLocals() async { + try { + final GetLocalsCall callback = PhpGroup.getLocalsCall; + + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + var response = await callback.call(); + + List locals = response.jsonBody['locais'] ?? []; + + final activeLocals = + locals.where((local) => local['CLU_STATUS'] == 'A').toList(); + + if (activeLocals.isEmpty || cliUUID.isEmpty) { + await showModalSelectLocal(); + } else { + await processData(); + } + } catch (e) { + await showModalSelectLocal(); + } + } + + Future showModalSelectLocal() async { + await showModalBottomSheet( + isScrollControlled: true, + backgroundColor: Colors.transparent, + enableDrag: false, + isDismissible: false, + context: context, + builder: (context) => Padding( + padding: MediaQuery.viewInsetsOf(context), + child: const BottomArrowLinkedLocalsComponentWidget(), + ), + ).then((_) async { + onUpdate(); + }); + + await processData(); + } + + void onUpdate() { + safeSetState(() { + _model.getData(); + }); + } + @override Widget build(BuildContext context) { context.watch(); @@ -79,7 +177,7 @@ class _LocalProfileComponentWidgetState hoverColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () async { - widget.showBottomSheet(); + showModalSelectLocal(); }, child: ClipRRect( borderRadius: BorderRadius.circular(200.0), diff --git a/lib/components/organism_components/menu_component/menu_component_model.dart b/lib/components/organism_components/menu_component/menu_component_model.dart index 4104a393..9a29635c 100644 --- a/lib/components/organism_components/menu_component/menu_component_model.dart +++ b/lib/components/organism_components/menu_component/menu_component_model.dart @@ -3,6 +3,8 @@ import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/organism_components/menu_staggered_view_component/menu_staggered_view_component_model.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/shared/extensions/dialog_extensions.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; +import 'package:sqflite/sqflite.dart'; import '/components/molecular_components/option_selection_modal/option_selection_modal_widget.dart'; import '/components/organism_components/menu_list_view_component/menu_list_view_component_widget.dart'; @@ -68,7 +70,12 @@ class MenuComponentModel extends FlutterFlowModel { } Future deliverySchedule(BuildContext context) async { - final isProvisional = AppState().provisional; + final DatabaseHelper db = DatabaseHelper(); + + final bool isProvisional = await db + .get(key: 'provisional', field: 'value') + .then((value) => value.toString() == 'true') as bool; + if (isProvisional == true) { context.push( '/deliverySchedule', @@ -86,7 +93,11 @@ class MenuComponentModel extends FlutterFlowModel { } Future provisionalSchedule(BuildContext context) async { - final isProvisional = AppState().provisional; + final DatabaseHelper db = DatabaseHelper(); + + final isProvisional = await db + .get(key: 'provisional', field: 'value') + .then((value) => value.toString() == 'true') as bool; if (isProvisional == true) { context.push( '/provisionalSchedule', @@ -104,7 +115,10 @@ class MenuComponentModel extends FlutterFlowModel { } Future fastPassAction(BuildContext context) async { - final isWpp = AppState().whatsapp; + final DatabaseHelper db = DatabaseHelper(); + final isWpp = await db.get(key: 'whatsapp', field: 'value').then((value) { + return value.toString() == 'true'; + }) as bool; if (isWpp) { context.push( '/fastPassPage', @@ -188,6 +202,15 @@ class MenuComponentModel extends FlutterFlowModel { } Future signOut(BuildContext context) async { + final DatabaseHelper db = DatabaseHelper(); + + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + showAlertDialog( context, 'Logout', @@ -195,11 +218,9 @@ class MenuComponentModel extends FlutterFlowModel { enText: 'Are you sure you want to logout?', ptText: 'Tem certeza', ), () async { - PhpGroup.unregisterDevice.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - ); + PhpGroup.unregisterDevice.call(); AppState().deleteAll(); + await db.purge(); context.go( '/welcomePage', @@ -228,7 +249,10 @@ class MenuComponentModel extends FlutterFlowModel { } Future packageOrder(BuildContext context) async { - final isWpp = AppState().whatsapp; + final DatabaseHelper db = DatabaseHelper(); + final isWpp = await db.get(key: 'whatsapp', field: 'value').then((value) { + return value.toString() == 'true'; + }) as bool; if (isWpp) { context.push( @@ -247,7 +271,10 @@ class MenuComponentModel extends FlutterFlowModel { } Future reservation(BuildContext context) async { - final isWpp = AppState().whatsapp; + final DatabaseHelper db = DatabaseHelper(); + final isWpp = await db.get(key: 'whatsapp', field: 'value').then((value) { + return value.toString() == 'true'; + }) as bool; if (isWpp) { context.push( '/reservation', @@ -363,7 +390,10 @@ class MenuComponentModel extends FlutterFlowModel { } Future petsAction(BuildContext context) async { - bool isPet = AppState().pets; + final DatabaseHelper db = DatabaseHelper(); + bool isPet = await db.get(key: 'pets', field: 'value').then((value) { + return value.toString() == 'true'; + }) as bool; if (isPet) { context.push( '/petsPage', diff --git a/lib/components/organism_components/menu_component/menu_component_widget.dart b/lib/components/organism_components/menu_component/menu_component_widget.dart index 60f0393d..26650732 100644 --- a/lib/components/organism_components/menu_component/menu_component_widget.dart +++ b/lib/components/organism_components/menu_component/menu_component_widget.dart @@ -53,21 +53,6 @@ class _MenuComponentWidgetState extends State { @override Widget build(BuildContext context) { - final DatabaseHelper db = DatabaseHelper(); - final cliUUID = db - .get(key: 'cliUUID', field: 'value') - .then((value) => value.toString()); - final userUUID = db - .get(key: 'userUUID', field: 'value') - .then((value) => value.toString()); - final devUUID = db - .get(key: 'devUUID', field: 'value') - .then((value) => value.toString()); - final provisional = - db.get(key: 'cliName', field: 'value').then((value) => value); - final whatsapp = - db.get(key: 'whatsapp', field: 'value').then((value) => value); - final options = () { if (widget.item == MenuItem.button) { if (_model.isGrid == true) diff --git a/lib/components/organism_components/message_well_component/message_well_component_widget.dart b/lib/components/organism_components/message_well_component/message_well_component_widget.dart index b6e77ccf..abe13043 100644 --- a/lib/components/organism_components/message_well_component/message_well_component_widget.dart +++ b/lib/components/organism_components/message_well_component/message_well_component_widget.dart @@ -8,6 +8,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:provider/provider.dart'; import 'package:rxdart/rxdart.dart'; @@ -338,6 +339,7 @@ class MessageWellState { class MessageWellNotifier extends StateNotifier { var _totalPageNumber = 1; int get totalPageNumber => _totalPageNumber; + final DatabaseHelper db = DatabaseHelper(); set totalPageNumber(int value) { _totalPageNumber = value; @@ -355,10 +357,6 @@ class MessageWellNotifier extends StateNotifier { if (state.pageNumber <= totalPageNumber) { var apiCall = GetMessagesCall(); var response = await apiCall.call( - devUUID: AppState().devUUID.toString(), - userUUID: AppState().userUUID.toString(), - cliID: AppState().cliUUID.toString(), - atividade: 'getMensagens', pageSize: '100', pageNumber: state.pageNumber.toString(), tipoDestino: dropdown.value.values.first, diff --git a/lib/components/organism_components/schedule_visit_detail/schedule_visit_detail_model.dart b/lib/components/organism_components/schedule_visit_detail/schedule_visit_detail_model.dart index 9abfbefe..c9950487 100644 --- a/lib/components/organism_components/schedule_visit_detail/schedule_visit_detail_model.dart +++ b/lib/components/organism_components/schedule_visit_detail/schedule_visit_detail_model.dart @@ -5,66 +5,65 @@ import 'package:hub/backend/api_requests/api_manager.dart'; import 'package:flutter/material.dart'; import 'package:hub/components/organism_components/schedule_visit_detail/schedule_visit_detail_widget.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:intl/intl.dart'; class ScheduleVisitDetailModel extends FlutterFlowModel { - /// State fields for stateful widgets in this component. + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode1; TextEditingController? textController1; String? Function(BuildContext, String?)? textController1Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode2; TextEditingController? textController2; String? Function(BuildContext, String?)? textController2Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode3; TextEditingController? textController3; String? Function(BuildContext, String?)? textController3Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode4; TextEditingController? textController4; String? Function(BuildContext, String?)? textController4Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode5; TextEditingController? textController5; String? Function(BuildContext, String?)? textController5Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode6; TextEditingController? textController6; String? Function(BuildContext, String?)? textController6Validator; - // Stores action output result for [Backend Call - API (postScheduleVisit)] action in Icon widget. ApiCallResponse? postScheduleVisit; String convertDateFormat(String dateStr) { try { - // Formato original DateFormat originalFormat = DateFormat('d/M/y H:mm:ss'); - // Novo formato DateFormat newFormat = DateFormat('y-M-d H:mm:ss'); - // Validate the input string format if (!RegExp(r'^\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2}:\d{2}$') .hasMatch(dateStr)) { return 'Invalid date format'; } - // Converte a string para DateTime DateTime dateTime = originalFormat.parse(dateStr); - // Converte DateTime para a nova string formatada String formattedDate = newFormat.format(dateTime); return formattedDate; } catch (e) { - // Handle the exception by returning an error message or a default value return 'Invalid date format'; } } @override - void initState(BuildContext context) {} + void initState(BuildContext context) { + initDB(); + } + + Future initDB() async { + devUUID = await db.get(key: 'devUUID', field: 'value'); + userUUID = await db.get(key: 'userUUID', field: 'value'); + cliUUID = await db.get(key: 'cliUUID', field: 'value'); + } @override void dispose() { diff --git a/lib/components/organism_components/schedule_visit_detail/schedule_visit_detail_widget.dart b/lib/components/organism_components/schedule_visit_detail/schedule_visit_detail_widget.dart index e8338984..b347c157 100644 --- a/lib/components/organism_components/schedule_visit_detail/schedule_visit_detail_widget.dart +++ b/lib/components/organism_components/schedule_visit_detail/schedule_visit_detail_widget.dart @@ -173,7 +173,7 @@ class _ScheduleVisitDetailWidgetState extends State { fadeInDuration: const Duration(milliseconds: 500), fadeOutDuration: const Duration(milliseconds: 500), imageUrl: valueOrDefault( - "https://freaccess.com.br/freaccess/getImage.php?devUUID=${AppState().devUUID}&userUUID=${AppState().userUUID}&cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${getJsonField( + "https://freaccess.com.br/freaccess/getImage.php?devUUID=${_model.devUUID}&userUUID=${_model.userUUID}&cliID=${_model.cliUUID}&atividade=getFoto&Documento=${getJsonField( visitorsDataItem, r'''$.VTE_DOCUMENTO''', ).toString()}&tipo=E", @@ -784,9 +784,6 @@ class _ScheduleVisitDetailWidgetState extends State { onPressed: () async { _model.postScheduleVisit = await PhpGroup.postScheduleVisitCall.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - atividade: 'putVisita', devDesc: widget.visitObsStr, idVisitante: widget.visitorStrList, dtInicio: @@ -796,7 +793,6 @@ class _ScheduleVisitDetailWidgetState extends State { idMotivo: extractIdToStr(widget.visitResonStr!), idNAC: extractIdToStr(widget.visitLevelStr!), obs: widget.visitObsStr, - cliID: AppState().cliUUID, ); if (PhpGroup.postScheduleVisitCall.error( diff --git a/lib/components/organism_components/up_arrow_linked_locals_component/up_arrow_linked_locals_component_model.dart b/lib/components/organism_components/up_arrow_linked_locals_component/up_arrow_linked_locals_component_model.dart index 54f840ca..5d2c488c 100644 --- a/lib/components/organism_components/up_arrow_linked_locals_component/up_arrow_linked_locals_component_model.dart +++ b/lib/components/organism_components/up_arrow_linked_locals_component/up_arrow_linked_locals_component_model.dart @@ -1,14 +1,37 @@ import 'package:hub/components/organism_components/up_arrow_linked_locals_component/up_arrow_linked_locals_component_widget.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; - import 'package:flutter/material.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; class UpArrowLinkedLocalsComponentModel extends FlutterFlowModel { + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; + late final String cliName; + @override - void initState(BuildContext context) {} + void initState(BuildContext context) { + initDB(); + } + + Future initDB() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + cliName = await db + .get(key: 'cliName', field: 'value') + .then((value) => value.toString()); + } @override void dispose() {} -} \ No newline at end of file +} diff --git a/lib/components/organism_components/up_arrow_linked_locals_component/up_arrow_linked_locals_component_widget.dart b/lib/components/organism_components/up_arrow_linked_locals_component/up_arrow_linked_locals_component_widget.dart index 65641bb8..85ca7b2c 100644 --- a/lib/components/organism_components/up_arrow_linked_locals_component/up_arrow_linked_locals_component_widget.dart +++ b/lib/components/organism_components/up_arrow_linked_locals_component/up_arrow_linked_locals_component_widget.dart @@ -78,10 +78,7 @@ class _UpArrowLinkedLocalsComponentWidgetState ), ), child: FutureBuilder( - future: PhpGroup.getLocalsCall.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - ), + future: PhpGroup.getLocalsCall.call(), builder: (context, snapshot) { // Customize what your widget looks like when it's loading. if (!snapshot.hasData) { @@ -131,12 +128,12 @@ class _UpArrowLinkedLocalsComponentWidgetState hoverColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () async { - AppState().cliUUID = getJsonField( + _model.cliUUID = getJsonField( eachLocalsItem, r'''$.CLI_ID''', ).toString(); setState(() {}); - AppState().local = getJsonField( + _model.cliName = getJsonField( eachLocalsItem, r'''$.CLI_NOME''', ).toString(); diff --git a/lib/components/templates_components/access_notification_modal_template_component/access_notification_modal_template_component_model.dart b/lib/components/templates_components/access_notification_modal_template_component/access_notification_modal_template_component_model.dart index f875a50b..0ef05d34 100644 --- a/lib/components/templates_components/access_notification_modal_template_component/access_notification_modal_template_component_model.dart +++ b/lib/components/templates_components/access_notification_modal_template_component/access_notification_modal_template_component_model.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import '/backend/api_requests/api_calls.dart'; import '/flutter_flow/flutter_flow_util.dart'; @@ -8,27 +9,40 @@ import 'access_notification_modal_template_component_widget.dart' class AccessNotificationModalTemplateComponentModel extends FlutterFlowModel { - /// State fields for stateful widgets in this component. + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode1; TextEditingController? textController1; String? Function(BuildContext, String?)? textController1Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode2; TextEditingController? textController2; String? Function(BuildContext, String?)? textController2Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode3; TextEditingController? textController3; String? Function(BuildContext, String?)? textController3Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode4; TextEditingController? textController4; String? Function(BuildContext, String?)? textController4Validator; @override - void initState(BuildContext context) {} + void initState(BuildContext context) { + initDB(); + } + + Future initDB() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + } @override void dispose() { @@ -45,7 +59,6 @@ class AccessNotificationModalTemplateComponentModel textController4?.dispose(); } - /// Action blocks. Future visitRequestComponentAction( BuildContext context, { required String? actionValue, @@ -56,10 +69,6 @@ class AccessNotificationModalTemplateComponentModel ApiCallResponse? visitRequest; visitRequest = await PhpGroup.respondeSolicitacaoCall.call( - userUUID: AppState().userUUID, - devUUID: AppState().devUUID, - cliUUID: AppState().cliUUID, - atividade: 'respondeSolicitacao', referencia: refUUID, tarefa: actionValue, resposta: responseValue, diff --git a/lib/components/templates_components/access_notification_modal_template_component/access_notification_modal_template_component_widget.dart b/lib/components/templates_components/access_notification_modal_template_component/access_notification_modal_template_component_widget.dart index f1861949..ffb2bd97 100644 --- a/lib/components/templates_components/access_notification_modal_template_component/access_notification_modal_template_component_widget.dart +++ b/lib/components/templates_components/access_notification_modal_template_component/access_notification_modal_template_component_widget.dart @@ -110,10 +110,7 @@ class _AccessNotificationModalTemplateComponentWidgetState fadeInDuration: const Duration(milliseconds: 100), fadeOutDuration: const Duration(milliseconds: 100), imageUrl: valueOrDefault( - // widget.type == 'O' - // ? 'https://freaccess.com.br/freaccess/getImage.php?cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${widget.id}&tipo=O' - // : 'https://freaccess.com.br/freaccess/getImage.php?cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${widget.id}&tipo=E', - 'https://freaccess.com.br/freaccess/getImage.php?cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${widget.id}&tipo=${widget.type}', + 'https://freaccess.com.br/freaccess/getImage.php?cliID=${_model.cliUUID}&atividade=getFoto&Documento=${widget.id}&tipo=${widget.type}', 'https://storage.googleapis.com/flutterflow-io-6f20.appspot.com/projects/flutter-freaccess-hub-0xgz9q/assets/7ftdetkzc3s0/360_F_64676383_LdbmhiNM6Ypzb3FM4PPuFP9rHe7ri8Ju.jpg', ), fit: BoxFit.cover, diff --git a/lib/components/templates_components/details_component/details_component_action.dart b/lib/components/templates_components/details_component/details_component_action.dart index fb4d4aed..6cf56968 100644 --- a/lib/components/templates_components/details_component/details_component_action.dart +++ b/lib/components/templates_components/details_component/details_component_action.dart @@ -1,21 +1,31 @@ +import 'dart:convert'; import 'dart:developer'; import 'package:flutter/material.dart'; +import 'package:http/http.dart'; import 'package:hub/actions/actions.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/templates_components/details_component/details_component_widget.dart'; +import 'package:hub/custom_code/actions/convert_to_upload_file.dart'; import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; +import 'package:hub/flutter_flow/form_field_controller.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; +import 'package:hub/pages/pets_page/pets_page_model.dart'; import 'package:hub/shared/utils/validator_util.dart'; import 'package:share_plus/share_plus.dart'; -Widget buildVisitDetails( - dynamic item, - BuildContext context, - Future Function(BuildContext, int, int, String, String)? - changeStatusAction) { +Widget buildVisitDetails({ + required dynamic item, + required BuildContext context, + required Future Function(BuildContext, int, int, String, String) + changeStatusAction, + required String devUUID, + required String userUUID, + required String cliUUID, + required String cliName, +}) { return DetailsComponentWidget( buttons: [ if (getStatus(item['VAW_STATUS']) == status.active) // REJECT ACTION @@ -137,13 +147,13 @@ Widget buildVisitDetails( icon: const Icon(Icons.share), onPressed: () async { Share.share(''' -Olá, \*${item['VTE_NOME']}\*! Você foi convidado para \*${AppState().local}\*. +Olá, \*${item['VTE_NOME']}\*! Você foi convidado para \*${cliName}\*. \*Validade do Convite\*: - Início: ${item['VAW_DTINICIO']} - Fim: ${item['VAW_DTFIM']} -URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/${AppState().cliUUID}/${item['VAW_CHAVE']} +URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/${cliUUID}/${item['VAW_CHAVE']} '''); }, options: FFButtonOptions( @@ -177,7 +187,7 @@ URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/${AppState().c : '', }), imagePath: - 'https://freaccess.com.br/freaccess/getImage.php?cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${item['VTE_DOCUMENTO'] ?? ''}&tipo=E', + 'https://freaccess.com.br/freaccess/getImage.php?cliID=${cliUUID}&atividade=getFoto&Documento=${item['VTE_DOCUMENTO'] ?? ''}&tipo=E', statusHashMap: [ if (getStatus(item['VAW_STATUS']) == status.active) Map.from({ @@ -225,11 +235,17 @@ URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/${AppState().c ); } -Widget buildPetDetails( - dynamic item, - BuildContext context, - Future Function(BuildContext, int, int, String, String)? - changeStatusAction) { +Widget buildPetDetails({ + required dynamic item, + required BuildContext context, + required Future Function(BuildContext, int, int, String, String) + changeStatusAction, + required String devUUID, + required String userUUID, + required String cliUUID, + required String cliName, + required PetsPageModel model, +}) { return DetailsComponentWidget( buttons: [ // EDIT ACTION @@ -241,11 +257,12 @@ Widget buildPetDetails( icon: const Icon(Icons.edit), onPressed: () async { context.pop(); - context.pop(); - context.pushNamed('petsPage', extra: { - 'pet': item, - }); + model.isEditing = true; + model.item = item; + model.switchTab(0); + model.setEditForm(); + // model.safeSetState!(); }, options: FFButtonOptions( width: 130, @@ -284,9 +301,6 @@ Widget buildPetDetails( int id = item['id']; await PhpGroup.deletePet .call( - userUUID: AppState().userUUID, - devUUID: AppState().devUUID, - cliID: AppState().cliUUID, petID: id, ) .then((value) { @@ -386,7 +400,7 @@ Widget buildPetDetails( item['notes'] ?? '', }), imagePath: - 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${AppState().devUUID}&userUUID=${AppState().userUUID}&cliID=${AppState().cliUUID}&atividade=consultaFotoPet&petId=${item['id'] ?? ''}', + 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${devUUID}&userUUID=${userUUID}&cliID=${cliUUID}&atividade=consultaFotoPet&petId=${item['id'] ?? ''}', statusHashMap: [ if (item['gender'] == "MAC") Map.from({ diff --git a/lib/components/templates_components/forgot_password_template_component/forgot_password_template_component_widget.dart b/lib/components/templates_components/forgot_password_template_component/forgot_password_template_component_widget.dart index 58a03d09..a5033296 100644 --- a/lib/components/templates_components/forgot_password_template_component/forgot_password_template_component_widget.dart +++ b/lib/components/templates_components/forgot_password_template_component/forgot_password_template_component_widget.dart @@ -265,9 +265,7 @@ class _ForgotPasswordTemplateComponentWidgetState email: _model.emailAddressTextController.text, ); - if (PhpGroup.forgotPasswordCall - .error((_model.req?.jsonBody ?? '')) == - false) { + if (_model.req?.jsonBody['error'] == false) { await DialogUtil.success( context, FFLocalizations.of(context).getVariableText( @@ -276,9 +274,7 @@ class _ForgotPasswordTemplateComponentWidgetState context.pop(); } else { await DialogUtil.error( - context, - PhpGroup.forgotPasswordCall - .msg((_model.req?.jsonBody ?? ''))!); + context, _model.req?.jsonBody['error_msg']); } setState(() {}); diff --git a/lib/components/templates_components/liberation_history_item_details_template_component/liberation_history_item_details_template_component_model.dart b/lib/components/templates_components/liberation_history_item_details_template_component/liberation_history_item_details_template_component_model.dart index 0678c1f5..a95c1eaa 100644 --- a/lib/components/templates_components/liberation_history_item_details_template_component/liberation_history_item_details_template_component_model.dart +++ b/lib/components/templates_components/liberation_history_item_details_template_component/liberation_history_item_details_template_component_model.dart @@ -4,25 +4,25 @@ import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/templates_components/liberation_history_item_details_template_component/liberation_history_item_details_template_component_widget.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; class LiberationHistoryItemDetailsTemplateComponentModel extends FlutterFlowModel< LiberationHistoryItemDetailsTemplateComponentWidget> { - /// State fields for stateful widgets in this component. + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode1; TextEditingController? textController1; String? Function(BuildContext, String?)? textController1Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode2; TextEditingController? textController2; String? Function(BuildContext, String?)? textController2Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode3; TextEditingController? textController3; String? Function(BuildContext, String?)? textController3Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode4; TextEditingController? textController4; String? Function(BuildContext, String?)? textController4Validator; @@ -30,6 +30,18 @@ class LiberationHistoryItemDetailsTemplateComponentModel @override void initState(BuildContext context) {} + Future initDatabase() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + } + @override void dispose() { textFieldFocusNode1?.dispose(); @@ -44,36 +56,4 @@ class LiberationHistoryItemDetailsTemplateComponentModel textFieldFocusNode4?.dispose(); textController4?.dispose(); } - - /// Action blocks. - Future visitRequestComponentAction( - BuildContext context, { - required String? actionValue, - required String? refUUID, - required String? responseValue, - required String? vteUUID, - }) async { - ApiCallResponse? visitRequest; - - visitRequest = await PhpGroup.respondeSolicitacaoCall.call( - userUUID: AppState().userUUID, - devUUID: AppState().devUUID, - cliUUID: AppState().cliUUID, - atividade: 'respondeSolicitacao', - referencia: refUUID, - tarefa: actionValue, - resposta: responseValue, - idVisitante: vteUUID, - ); - - if (PhpGroup.respondeSolicitacaoCall.error( - (visitRequest.jsonBody ?? ''), - ) == - false) { - context.pop(); - return true; - } else { - return false; - } - } } diff --git a/lib/components/templates_components/liberation_history_item_details_template_component/liberation_history_item_details_template_component_widget.dart b/lib/components/templates_components/liberation_history_item_details_template_component/liberation_history_item_details_template_component_widget.dart index 448d4a07..23c6a71e 100644 --- a/lib/components/templates_components/liberation_history_item_details_template_component/liberation_history_item_details_template_component_widget.dart +++ b/lib/components/templates_components/liberation_history_item_details_template_component/liberation_history_item_details_template_component_widget.dart @@ -105,7 +105,7 @@ class _LiberationHistoryItemDetailsTemplateComponentWidgetState fadeInDuration: const Duration(milliseconds: 100), fadeOutDuration: const Duration(milliseconds: 100), imageUrl: valueOrDefault( - 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${AppState().devUUID}&userUUID=${AppState().userUUID}&cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${widget.id}&tipo=E', + 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${_model.devUUID}&userUUID=${_model.userUUID}&cliID=${_model.cliUUID}&atividade=getFoto&Documento=${widget.id}&tipo=E', 'https://storage.googleapis.com/flutterflow-io-6f20.appspot.com/projects/flutter-freaccess-hub-0xgz9q/assets/7ftdetkzc3s0/360_F_64676383_LdbmhiNM6Ypzb3FM4PPuFP9rHe7ri8Ju.jpg', ), fit: BoxFit.cover, diff --git a/lib/components/templates_components/message_notificaion_modal_template_component/message_notification_model.dart b/lib/components/templates_components/message_notificaion_modal_template_component/message_notification_model.dart index 31b96ea8..f949913a 100644 --- a/lib/components/templates_components/message_notificaion_modal_template_component/message_notification_model.dart +++ b/lib/components/templates_components/message_notificaion_modal_template_component/message_notification_model.dart @@ -43,36 +43,4 @@ class MessageNotificationModalTemplateComponentModel textFieldFocusNode4?.dispose(); textController4?.dispose(); } - - /// Action blocks. - Future visitRequestComponentAction( - BuildContext context, { - required String? actionValue, - required String? refUUID, - required String? responseValue, - required String? vteUUID, - }) async { - ApiCallResponse? visitRequest; - - visitRequest = await PhpGroup.respondeSolicitacaoCall.call( - userUUID: AppState().userUUID, - devUUID: AppState().devUUID, - cliUUID: AppState().cliUUID, - atividade: 'respondeSolicitacao', - referencia: refUUID, - tarefa: actionValue, - resposta: responseValue, - idVisitante: vteUUID, - ); - - if (PhpGroup.respondeSolicitacaoCall.error( - (visitRequest.jsonBody ?? ''), - ) == - false) { - context.pop(); - return true; - } else { - return false; - } - } } diff --git a/lib/components/templates_components/provisional_schedule_template/provisional_schedule_template_model.dart b/lib/components/templates_components/provisional_schedule_template/provisional_schedule_template_model.dart index 86bbbb92..19311f40 100644 --- a/lib/components/templates_components/provisional_schedule_template/provisional_schedule_template_model.dart +++ b/lib/components/templates_components/provisional_schedule_template/provisional_schedule_template_model.dart @@ -13,6 +13,7 @@ class ScheduleProvisionalVisitPageModel String userUUID = ''; String cliName = ''; String ownerUUID = ''; + VoidCallback? setState; bool toggleIdx = false; @@ -33,10 +34,7 @@ class ScheduleProvisionalVisitPageModel void updateDocsAtIndex(int index, Function(String) updateFn) => docs[index] = updateFn(docs[index]); - /// State fields for stateful widgets in this page. - final formKey = GlobalKey(); - // State field(s) for personName widget. FocusNode? personNameFocusNode; TextEditingController? personNameTextController; String? Function(BuildContext, String?)? personNameTextControllerValidator; @@ -44,27 +42,26 @@ class ScheduleProvisionalVisitPageModel BuildContext context, String? val) { if (val == null || val.isEmpty) { return FFLocalizations.of(context).getText( - '3hqg8buh' /* Nome é Obrigatório */, + '3hqg8buh', ); } if (val.length > 80) { return FFLocalizations.of(context).getText( - 'l0b0zr50' /* Máximo 80 caracteres */, + 'l0b0zr50', ); } return null; } - // State field(s) for dateTime widget. FocusNode? dateTimeFocusNode; TextEditingController? dateTimeTextController; String? Function(BuildContext, String?)? dateTimeTextControllerValidator; String? _dateTimeTextControllerValidator(BuildContext context, String? val) { if (val == null || val.isEmpty) { return FFLocalizations.of(context).getText( - 'uzefkuf9' /* Data / Hora é Obrigatório */, + 'uzefkuf9', ); } @@ -92,26 +89,48 @@ class ScheduleProvisionalVisitPageModel } DateTime? datePicked; - // State field(s) for notes widget. FocusNode? notesFocusNode; TextEditingController? notesTextController; String? Function(BuildContext, String?)? notesTextControllerValidator; - // Stores action output result for [Backend Call - API (postProvVisitScheduling)] action in btnSend widget. ApiCallResponse? provVisitSchedule; @override void initState(BuildContext context) { personNameTextControllerValidator = _personNameTextControllerValidator; dateTimeTextControllerValidator = _dateTimeTextControllerValidator; + + personNameTextController ??= TextEditingController(); + personNameFocusNode ??= FocusNode(); + + dateTimeTextController ??= TextEditingController(); + dateTimeFocusNode ??= FocusNode(); + + notesTextController ??= TextEditingController(); + notesFocusNode ??= FocusNode(); + init(); } + bool isFormValid() { + if (personNameTextController.text == '' || + personNameTextController.text.length > 80) { + return false; + } + + if (dateTimeTextController.text == '') { + return false; + } + + return true; + } + Future init() async { cliUUID = await db.get(key: 'cliUUID', field: 'value'); devUUID = await db.get(key: 'devUUID', field: 'value'); userUUID = await db.get(key: 'userUUID', field: 'value'); cliName = await db.get(key: 'cliName', field: 'value'); ownerUUID = await db.get(key: 'ownerUUID', field: 'value'); + setState?.call(); } @override diff --git a/lib/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart b/lib/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart index 9c5dce23..f68c3264 100644 --- a/lib/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart +++ b/lib/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:hub/components/templates_components/provisional_schedule_template/provisional_schedule_template_model.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/log_util.dart'; import 'package:provider/provider.dart'; @@ -14,9 +15,7 @@ import '/flutter_flow/flutter_flow_util.dart'; import '/flutter_flow/flutter_flow_widgets.dart'; class ScheduleProvisionalVisitPageWidget extends StatefulWidget { - const ScheduleProvisionalVisitPageWidget({ - super.key, - }); + const ScheduleProvisionalVisitPageWidget({super.key}); @override State createState() => @@ -25,43 +24,22 @@ class ScheduleProvisionalVisitPageWidget extends StatefulWidget { class _ScheduleProvisionalVisitPageWidgetState extends State { - late ScheduleProvisionalVisitPageModel _model; + late ScheduleProvisionalVisitPageModel model; @override void initState() { super.initState(); - _model = createModel(context, () => ScheduleProvisionalVisitPageModel()); - - _model.personNameTextController ??= TextEditingController(); - _model.personNameFocusNode ??= FocusNode(); - - _model.dateTimeTextController ??= TextEditingController(); - _model.dateTimeFocusNode ??= FocusNode(); - - _model.notesTextController ??= TextEditingController(); - _model.notesFocusNode ??= FocusNode(); + model = createModel(context, () => ScheduleProvisionalVisitPageModel()); + model.setState = () => safeSetState(() {}); } @override void dispose() { - _model.dispose(); + model.dispose(); super.dispose(); } - bool _isFormValid() { - if (_model.personNameTextController.text == '' || - _model.personNameTextController.text.length > 80) { - return false; - } - - if (_model.dateTimeTextController.text == '') { - return false; - } - - return true; - } - @override Widget build(BuildContext context) { context.watch(); @@ -78,7 +56,7 @@ class _ScheduleProvisionalVisitPageWidgetState mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Form( - key: _model.formKey, + key: model.formKey, autovalidateMode: AutovalidateMode.onUserInteraction, child: SingleChildScrollView( child: Column( @@ -183,7 +161,7 @@ class _ScheduleProvisionalVisitPageWidgetState fadeOutDuration: const Duration( milliseconds: 200), imageUrl: - 'https://freaccess.com.br/freaccess/Images/Clients/${_model.cliUUID}.png', + 'https://freaccess.com.br/freaccess/Images/Clients/${model.cliUUID}.png', width: 35.0, height: 35.0, fit: BoxFit.contain, @@ -195,7 +173,7 @@ class _ScheduleProvisionalVisitPageWidgetState padding: const EdgeInsetsDirectional .fromSTEB(15.0, 0.0, 0.0, 0.0), child: Text( - _model.cliName, + model.cliName, style: FlutterFlowTheme.of(context) .bodyMedium .override( @@ -269,12 +247,12 @@ class _ScheduleProvisionalVisitPageWidgetState width: double.infinity, child: TextFormField( controller: - _model.personNameTextController, + model.personNameTextController, focusNode: - _model.personNameFocusNode, + model.personNameFocusNode, onChanged: (_) => EasyDebounce.debounce( - '_model.personNameTextController', + 'model.personNameTextController', const Duration(milliseconds: 500), () => setState(() {}), ), @@ -397,7 +375,7 @@ class _ScheduleProvisionalVisitPageWidgetState ), textAlign: TextAlign.start, maxLines: null, - validator: _model + validator: model .personNameTextControllerValidator .asValidator(context), ), @@ -421,12 +399,12 @@ class _ScheduleProvisionalVisitPageWidgetState .fromSTEB(24.0, 0.0, 24.0, 0.0), child: TextFormField( controller: - _model.dateTimeTextController, + model.dateTimeTextController, focusNode: - _model.dateTimeFocusNode, + model.dateTimeFocusNode, onChanged: (_) => EasyDebounce.debounce( - '_model.dateTimeTextController', + 'model.dateTimeTextController', const Duration( milliseconds: 500), () => setState(() {}), @@ -528,7 +506,7 @@ class _ScheduleProvisionalVisitPageWidgetState .bodyMediumFamily), ), textAlign: TextAlign.start, - validator: _model + validator: model .dateTimeTextControllerValidator .asValidator(context), ), @@ -683,8 +661,7 @@ class _ScheduleProvisionalVisitPageWidgetState if (datePickedDate != null && datePickedTime != null) { safeSetState(() { - _model.datePicked = - DateTime( + model.datePicked = DateTime( datePickedDate.year, datePickedDate.month, datePickedDate.day, @@ -694,18 +671,19 @@ class _ScheduleProvisionalVisitPageWidgetState }); } setState(() { - _model.dateTimeTextController + model.dateTimeTextController ?.text = dateTimeFormat( "dd/MM/yyyy HH:mm:ss", - _model.datePicked, + model.datePicked, locale: FFLocalizations.of( context) .languageCode, ); - _model.dateTimeTextController + + model.dateTimeTextController ?.selection = TextSelection.collapsed( - offset: _model + offset: model .dateTimeTextController! .text .length); @@ -755,10 +733,10 @@ class _ScheduleProvisionalVisitPageWidgetState child: SizedBox( width: double.infinity, child: TextFormField( - controller: _model - .notesTextController, + controller: + model.notesTextController, focusNode: - _model.notesFocusNode, + model.notesFocusNode, autofocus: false, textInputAction: TextInputAction.next, @@ -895,7 +873,7 @@ class _ScheduleProvisionalVisitPageWidgetState maxLengthEnforcement: MaxLengthEnforcement .enforced, - validator: _model + validator: model .notesTextControllerValidator .asValidator(context), ), @@ -912,26 +890,21 @@ class _ScheduleProvisionalVisitPageWidgetState ), ), FFButtonWidget( - onPressed: !_isFormValid() + onPressed: !model.isFormValid() ? null : () async { try { - _model.provVisitSchedule = await PhpGroup + model.provVisitSchedule = await PhpGroup .postProvVisitSchedulingCall .call( - devUUID: _model.devUUID, - userUUID: _model.userUUID, - cliID: _model.cliUUID, - atividade: 'putAgendamentoProv', - data: _model.dateTimeTextController.text, - motivo: _model.notesTextController.text, - nome: - _model.personNameTextController.text, - proID: _model.ownerUUID, + data: model.dateTimeTextController.text, + motivo: model.notesTextController.text, + nome: model.personNameTextController.text, + proID: model.ownerUUID, ); if (PhpGroup.postProvVisitSchedulingCall - .error((_model.provVisitSchedule + .error((model.provVisitSchedule ?.jsonBody ?? '')) == false) { @@ -943,16 +916,15 @@ class _ScheduleProvisionalVisitPageWidgetState enText: "Provisional Scheduling Successfully Completed")); safeSetState(() { - _model.dateTimeTextController?.clear(); + model.dateTimeTextController?.clear(); - _model.personNameTextController - ?.clear(); - _model.notesTextController?.clear(); + model.personNameTextController?.clear(); + model.notesTextController?.clear(); }); } else { var message = PhpGroup .postProvVisitSchedulingCall - .msg((_model.provVisitSchedule + .msg((model.provVisitSchedule ?.jsonBody ?? '')); if (message != null) { diff --git a/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_model.dart b/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_model.dart index ed171aef..3e752121 100644 --- a/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_model.dart +++ b/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_model.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/validator_util.dart'; import '/backend/api_requests/api_calls.dart'; @@ -10,8 +11,11 @@ import 'regisiter_vistor_template_component_widget.dart'; class RegisiterVistorTemplateComponentModel extends FlutterFlowModel { - /// State fields for stateful widgets in this page. Timer? _debounceTimer; + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; final unfocusNode = FocusNode(); bool isDataUploading = false; @@ -25,8 +29,6 @@ class RegisiterVistorTemplateComponentModel _debounceTimer = Timer(time, fn); } - - // State field(s) for TextField widget. FocusNode? textFieldFocusNode1; TextEditingController? textController1; @@ -45,10 +47,6 @@ class RegisiterVistorTemplateComponentModel Future getVisitanteByDocument( String document, BuildContext context) async { final response = await PhpGroup.getVisitorByDocCall.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliID: AppState().cliUUID, - atividade: 'getVisitante', documento: document, ); @@ -132,6 +130,14 @@ class RegisiterVistorTemplateComponentModel textFieldFocusNode4 = FocusNode(); textController4 = TextEditingController(); textController4Validator = _textController4Validator; + + initializeDatabase(); + } + + Future initializeDatabase() async { + devUUID = await db.get(key: 'devUUID', field: 'value'); + userUUID = await db.get(key: 'userUUID', field: 'value'); + cliUUID = await db.get(key: 'cliUUID', field: 'value'); } @override diff --git a/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart b/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart index a00a9613..1d97bbf3 100644 --- a/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart +++ b/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart @@ -845,10 +845,6 @@ class _RegisiterVistorTemplateComponentWidgetState _model.scheduleVisitor = await PhpGroup.postScheduleVisitorCall .call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliID: AppState().cliUUID, - atividade: 'putVisitante', documento: _model.textController2.text, nome: _model.textController1.text, tipo: _model.dropDownValue == diff --git a/lib/components/templates_components/sign_up_template_component/sign_up_template_component_widget.dart b/lib/components/templates_components/sign_up_template_component/sign_up_template_component_widget.dart index d3b7772c..ecc3ab07 100644 --- a/lib/components/templates_components/sign_up_template_component/sign_up_template_component_widget.dart +++ b/lib/components/templates_components/sign_up_template_component/sign_up_template_component_widget.dart @@ -703,7 +703,8 @@ class _SignUpTemplateComponentWidgetState email: _model .emailRegisterFormTextController .text, - device: AppState().device, + device: + AppState().deviceType, ); shouldSetState = true; if (_model.signUp == true) { diff --git a/lib/components/templates_components/view_visit_detail/view_visit_detail_model.dart b/lib/components/templates_components/view_visit_detail/view_visit_detail_model.dart index a5726bc8..ab310d6f 100644 --- a/lib/components/templates_components/view_visit_detail/view_visit_detail_model.dart +++ b/lib/components/templates_components/view_visit_detail/view_visit_detail_model.dart @@ -1,42 +1,52 @@ +import 'package:hub/shared/helpers/db_helper.dart'; + import '/backend/api_requests/api_calls.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'view_visit_detail_widget.dart' show ViewVisitDetailWidget; import 'package:flutter/material.dart'; class ViewVisitDetailModel extends FlutterFlowModel { - /// State fields for stateful widgets in this component. + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; - // Stores action output result for [Action Block - manageStatusColorAction] action in viewVisitDetail widget. - // Color? visitStatusColor; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode1; TextEditingController? textController1; String? Function(BuildContext, String?)? textController1Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode2; TextEditingController? textController2; String? Function(BuildContext, String?)? textController2Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode3; TextEditingController? textController3; String? Function(BuildContext, String?)? textController3Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode4; TextEditingController? textController4; String? Function(BuildContext, String?)? textController4Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode5; TextEditingController? textController5; String? Function(BuildContext, String?)? textController5Validator; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode6; TextEditingController? textController6; String? Function(BuildContext, String?)? textController6Validator; - // Stores action output result for [Backend Call - API (deleteVisit)] action in IconButton widget. ApiCallResponse? deleteVisit; @override - void initState(BuildContext context) {} + void initState(BuildContext context) { + initializeDatabase(); + } + + Future initializeDatabase() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + } @override void dispose() { diff --git a/lib/components/templates_components/view_visit_detail/view_visit_detail_widget.dart b/lib/components/templates_components/view_visit_detail/view_visit_detail_widget.dart index afb609a3..65c992c0 100644 --- a/lib/components/templates_components/view_visit_detail/view_visit_detail_widget.dart +++ b/lib/components/templates_components/view_visit_detail/view_visit_detail_widget.dart @@ -822,10 +822,6 @@ class _ViewVisitDetailWidgetState extends State { onPressed: () async { _model.deleteVisit = await PhpGroup.deleteVisitCall.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliID: AppState().cliUUID, - atividade: 'cancelaVisita', idVisita: widget.visitIdStr, ); diff --git a/lib/components/templates_components/visitor_search_modal_template_component/visitor_search_modal_template_component_model.dart b/lib/components/templates_components/visitor_search_modal_template_component/visitor_search_modal_template_component_model.dart index 1b473920..ef420f06 100644 --- a/lib/components/templates_components/visitor_search_modal_template_component/visitor_search_modal_template_component_model.dart +++ b/lib/components/templates_components/visitor_search_modal_template_component/visitor_search_modal_template_component_model.dart @@ -2,12 +2,15 @@ import 'package:hub/backend/api_requests/api_manager.dart'; import 'package:hub/components/templates_components/visitor_search_modal_template_component/visitor_search_modal_template_component_widget.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; - import 'package:flutter/material.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; class VisitorSearchModalTemplateComponentModel extends FlutterFlowModel { - /// Local state fields for this component. + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; List visitors = []; void addToVisitors(dynamic item) => visitors.add(item); @@ -26,21 +29,31 @@ class VisitorSearchModalTemplateComponentModel void updateDocsAtIndex(int index, Function(String) updateFn) => docs[index] = updateFn(docs[index]); - /// State fields for stateful widgets in this component. - - // State field(s) for TextField widget. FocusNode? textFieldFocusNode; TextEditingController? textController; String? Function(BuildContext, String?)? textControllerValidator; - // Stores action output result for [Backend Call - API (getVisitorByDoc)] action in TextField widget. ApiCallResponse? getVisitorByDoc; @override - void initState(BuildContext context) {} + void initState(BuildContext context) { + initDatabase(); + } + + Future initDatabase() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + } @override void dispose() { textFieldFocusNode?.dispose(); textController?.dispose(); } -} \ No newline at end of file +} diff --git a/lib/components/templates_components/visitor_search_modal_template_component/visitor_search_modal_template_component_widget.dart b/lib/components/templates_components/visitor_search_modal_template_component/visitor_search_modal_template_component_widget.dart index d272a8d7..e1982ac3 100644 --- a/lib/components/templates_components/visitor_search_modal_template_component/visitor_search_modal_template_component_widget.dart +++ b/lib/components/templates_components/visitor_search_modal_template_component/visitor_search_modal_template_component_widget.dart @@ -268,7 +268,7 @@ class _VisitorSearchModalTemplateComponentWidgetState fadeOutDuration: const Duration( milliseconds: 500), imageUrl: - "https://freaccess.com.br/freaccess/getImage.php?devUUID=${AppState().devUUID}&userUUID=${AppState().userUUID}&cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${getJsonField( + "https://freaccess.com.br/freaccess/getImage.php?devUUID=${_model.devUUID}&userUUID=${_model.userUUID}&cliID=${_model.cliUUID}&atividade=getFoto&Documento=${getJsonField( visitorItem, r'''$.VTE_DOCUMENTO''', ).toString()}&tipo=E", @@ -440,10 +440,6 @@ class _VisitorSearchModalTemplateComponentWidgetState TextSelection.collapsed(offset: _model.textController!.text.length); }); _model.getVisitorByDoc = await PhpGroup.getVisitorByDocCall.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliID: AppState().cliUUID, - atividade: 'getVisitante', documento: _model.textController.text, ); diff --git a/lib/flutter_flow/nav/nav.dart b/lib/flutter_flow/nav/nav.dart index ae40af8f..a2f8afbc 100644 --- a/lib/flutter_flow/nav/nav.dart +++ b/lib/flutter_flow/nav/nav.dart @@ -146,9 +146,7 @@ GoRouter createRouter(AppStateNotifier appStateNotifier) => GoRouter( FFRoute( name: 'preferencesSettings', path: '/preferencesSettings', - builder: (context, params) => const PreferencesPageWidget( - key: Key('preferencesSettings'), - )), + builder: (context, params) => PreferencesPageWidget()), FFRoute( name: 'peopleOnThePropertyPage', path: '/peopleOnThePropertyPage', @@ -190,7 +188,7 @@ GoRouter createRouter(AppStateNotifier appStateNotifier) => GoRouter( FFRoute( name: 'preferencesPage', path: '/preferencesPage', - builder: (context, params) => const PreferencesPageWidget(), + builder: (context, params) => PreferencesPageWidget(), ), FFRoute( name: 'packageOrder', diff --git a/lib/main.dart b/lib/main.dart index 5eb1d40a..fdc091b4 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -106,6 +106,8 @@ class _AppState extends State { _backgroundHandleMessage(message); } }); + + // AppState().isLogged = false; } void setLocale(String language) { diff --git a/lib/pages/acess_history_page/acess_history_page_model.dart b/lib/pages/acess_history_page/acess_history_page_model.dart index 67141afb..d8402b2b 100644 --- a/lib/pages/acess_history_page/acess_history_page_model.dart +++ b/lib/pages/acess_history_page/acess_history_page_model.dart @@ -4,8 +4,14 @@ import 'package:hub/components/molecular_components/message_opt_modal/opt_modal_ import 'package:hub/flutter_flow/flutter_flow_model.dart'; import 'package:hub/flutter_flow/request_manager.dart'; import 'package:hub/pages/acess_history_page/acess_history_page_widget.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; class AcessHistoryPageModel extends FlutterFlowModel { + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; + final unfocusNode = FocusNode(); final _accessHistoryManager = FutureRequestManager(); Future accessHistory({ @@ -23,14 +29,26 @@ class AcessHistoryPageModel extends FlutterFlowModel { _accessHistoryManager.clearRequest(uniqueKey); @override - void initState(BuildContext context) {} + void initState(BuildContext context) { + initDatabase(); + } + + Future initDatabase() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + } @override void dispose() { unfocusNode.dispose(); - /// Dispose query cache managers for this widget. - clearAccessHistoryCache(); } diff --git a/lib/pages/acess_history_page/acess_history_page_widget.dart b/lib/pages/acess_history_page/acess_history_page_widget.dart index 03b6767e..d0cfcf45 100644 --- a/lib/pages/acess_history_page/acess_history_page_widget.dart +++ b/lib/pages/acess_history_page/acess_history_page_widget.dart @@ -187,10 +187,6 @@ class _AcessHistoryPageWidgetState extends State { try { setState(() => _loading = true); var response = await PhpGroup.getAccessCall.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliID: AppState().cliUUID, - atividade: 'getAcessos', pageSize: _pageSize.toString(), pageNumber: _pageNumber.toString(), pesTipo: _personType != 'E' && _personType != 'O' ? 'T' : _personType, @@ -333,7 +329,7 @@ class _AcessHistoryPageWidgetState extends State { BuildContext context, dynamic accessHistoryItem) { return CardItemTemplateComponentWidget( imagePath: - 'https://freaccess.com.br/freaccess/getImage.php?cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${accessHistoryItem['PES_ID'] ?? ''}&tipo=${accessHistoryItem['PES_TIPO'] ?? ''}', + 'https://freaccess.com.br/freaccess/getImage.php?cliID=${_model.cliUUID}&atividade=getFoto&Documento=${accessHistoryItem['PES_ID'] ?? ''}&tipo=${accessHistoryItem['PES_TIPO'] ?? ''}', labelsHashMap: Map.from({ FFLocalizations.of(context).getVariableText( ptText: 'Nome:', @@ -392,11 +388,11 @@ class _AcessHistoryPageWidgetState extends State { ], onTapCardItemAction: () async {}); } -} -String imageUrlAtomWidget(String document, String type) { - return valueOrDefault( - "https://freaccess.com.br/freaccess/getImage.php?&cliID=${AppState().cliUUID}&atividade=getFoto&Documento=$document&tipo=$type", - "https://storage.googleapis.com/flutterflow-io-6f20.appspot.com/projects/flutter-freaccess-hub-0xgz9q/assets/7ftdetkzc3s0/360_F_64676383_LdbmhiNM6Ypzb3FM4PPuFP9rHe7ri8Ju.jpg", - ); + String imageUrlAtomWidget(String document, String type) { + return valueOrDefault( + "https://freaccess.com.br/freaccess/getImage.php?&cliID=${_model.cliUUID}&atividade=getFoto&Documento=$document&tipo=$type", + "https://storage.googleapis.com/flutterflow-io-6f20.appspot.com/projects/flutter-freaccess-hub-0xgz9q/assets/7ftdetkzc3s0/360_F_64676383_LdbmhiNM6Ypzb3FM4PPuFP9rHe7ri8Ju.jpg", + ); + } } diff --git a/lib/pages/delivery_schedule_page/delivery_schedule_widget.dart b/lib/pages/delivery_schedule_page/delivery_schedule_widget.dart index 1951c608..cfe5ef5e 100644 --- a/lib/pages/delivery_schedule_page/delivery_schedule_widget.dart +++ b/lib/pages/delivery_schedule_page/delivery_schedule_widget.dart @@ -17,20 +17,15 @@ class DeliverySchedule extends StatefulWidget { } class _DeliveryScheduleState extends State { - late ScheduleProvisionalVisitPageModel _model; - final scaffoldKey = GlobalKey(); @override void initState() { super.initState(); - _model = createModel(context, () => ScheduleProvisionalVisitPageModel()); } @override void dispose() { - _model.dispose(); - super.dispose(); } diff --git a/lib/pages/fast_pass_page/fast_pass_page_widget.dart b/lib/pages/fast_pass_page/fast_pass_page_widget.dart index 6ad8a974..816f4ca7 100644 --- a/lib/pages/fast_pass_page/fast_pass_page_widget.dart +++ b/lib/pages/fast_pass_page/fast_pass_page_widget.dart @@ -5,21 +5,12 @@ import 'package:flutter/scheduler.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:hub/app_state.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/webview_util.dart'; import 'package:url_launcher/url_launcher_string.dart'; import 'package:webview_flutter/webview_flutter.dart'; class FastPassPageWidget extends StatefulWidget { - final String freToken = AppState().userUUID; - final String freUserData = "{\"name\": \"${AppState().name}\", " + - "\"email\": \"${AppState().email}\"," + - "\"dev_id\": \"${AppState().devUUID}\"," + - "\"created_at\": \"${AppState().createdAt}\"," + - "\"updated_at\": \"0000-00-00 00:00:00\"," + - "\"status\": \"A\" }"; - - final String clientId = AppState().cliUUID; - @override _FastPassPageWidgetState createState() => _FastPassPageWidgetState(); } @@ -27,102 +18,145 @@ class FastPassPageWidget extends StatefulWidget { class _FastPassPageWidgetState extends State { late InAppWebViewController _controllerIOS; late WebViewController _controllerAll; - late String url; - late String name; - late String email; - late String userUUID; - late String created_at; + final DatabaseHelper db = DatabaseHelper(); - @override - void initState() { - super.initState(); - name = AppState().name; - email = AppState().email; - userUUID = AppState().userUUID; - created_at = AppState().createdAt; - url = 'https://hub.freaccess.com.br/hub/fast-pass/${widget.clientId}'; + Future> initVariables() async { + final email = AppState().email; + final name = await db + .get(key: 'userName', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + final createdAt = await db + .get(key: 'devUUID', field: 'createdAt') + .then((value) => value.toString()); + final url = 'https://hub.freaccess.com.br/hub/fast-pass/$cliUUID'; + final freUserData = "{\"name\": \"$name\", " + + "\"email\": \"$email\"," + + "\"dev_id\": \"$devUUID\"," + + "\"created_at\": \"$createdAt\"," + + "\"updated_at\": \"0000-00-00 00:00:00\"," + + "\"status\": \"A\" }"; + + return { + 'url': url, + 'name': name, + 'email': email, + 'userUUID': userUUID, + 'devUUID': devUUID, + 'createdAt': createdAt, + 'cliUUID': cliUUID, + 'freUserData': freUserData, + }; } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( - body: Platform.isIOS - ? InAppWebView( - initialUrlRequest: URLRequest(url: WebUri(url)), - initialSettings: InAppWebViewSettings( - allowsBackForwardNavigationGestures: true, - javaScriptEnabled: true, - ), - onWebViewCreated: (controller) async { - _controllerIOS = controller; - }, - onLoadStop: (controller, url) async { - await controller.evaluateJavascript( - source: - "window.localStorage.setItem('fre-token', '\"${widget.freToken}\"')"); - await controller.evaluateJavascript( - source: - "window.localStorage.setItem('fre-user-data', '${widget.freUserData}')"); - await controller.evaluateJavascript( - source: - "window.localStorage.setItem('enableBackButton', 'true')"); - }, - onUpdateVisitedHistory: (controller, uri, isVisited) { - if (uri.toString().contains('/hub/home')) { - context.pop(); - } - }, - ) - : WebViewWidget( - controller: _controllerAll = WebViewController() - ..clearCache() - ..clearLocalStorage() - ..setJavaScriptMode(JavaScriptMode.unrestricted) - ..setBackgroundColor(const Color(0x00000000)) - ..setNavigationDelegate( - NavigationDelegate( - onProgress: (int progress) {}, - onPageStarted: (String url) { - final String token = - "localStorage.setItem('fre-token', '\"${widget.freToken}\"');"; - final String data = - "localStorage.setItem('fre-user-data', '${widget.freUserData}');"; - const String backNavigation = - "localStorage.setItem('enableBackButton', 'true');"; + body: FutureBuilder>( + future: initVariables(), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return Center(child: CircularProgressIndicator()); + } else if (snapshot.hasError) { + return Center(child: Text('Error: ${snapshot.error}')); + } else if (snapshot.hasData) { + final data = snapshot.data!; + final url = data['url']!; + final userUUID = data['userUUID']!; + final freUserData = data['freUserData']!; - _controllerAll.runJavaScript(token); - _controllerAll.runJavaScript(data); - _controllerAll.runJavaScript(backNavigation); - }, - onPageFinished: (String url) { - bool isDarkMode = SchedulerBinding.instance - .platformDispatcher.platformBrightness == - Brightness.dark; + return Platform.isIOS + ? InAppWebView( + initialUrlRequest: URLRequest(url: WebUri(url)), + initialSettings: InAppWebViewSettings( + allowsBackForwardNavigationGestures: true, + javaScriptEnabled: true, + ), + onWebViewCreated: (controller) async { + _controllerIOS = controller; + }, + onLoadStop: (controller, url) async { + await controller.evaluateJavascript( + source: + "window.localStorage.setItem('fre-token', '\"$userUUID\"')"); + await controller.evaluateJavascript( + source: + "window.localStorage.setItem('fre-user-data', '$freUserData')"); + await controller.evaluateJavascript( + source: + "window.localStorage.setItem('enableBackButton', 'true')"); + }, + onUpdateVisitedHistory: (controller, uri, isVisited) { + if (uri.toString().contains('/hub/home')) { + context.pop(); + } + }, + ) + : WebViewWidget( + controller: _controllerAll = WebViewController() + ..clearCache() + ..clearLocalStorage() + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setBackgroundColor(const Color(0x00000000)) + ..setNavigationDelegate( + NavigationDelegate( + onProgress: (int progress) {}, + onPageStarted: (String url) { + final String token = + "localStorage.setItem('fre-token', '\"$userUUID\"');"; + final String data = + "localStorage.setItem('fre-user-data', '$freUserData');"; + const String backNavigation = + "localStorage.setItem('enableBackButton', 'true');"; - if (isDarkMode) { - _controllerAll - .runJavaScript(WebviewUtil.jsEnableDarkMode); - } - }, - onNavigationRequest: (NavigationRequest request) { - if (request.url.startsWith('http') || - request.url.startsWith( - 'https://api.whatsapp.com/send') || - request.url.startsWith('https://wa.me')) { - launchUrlString(request.url); - return NavigationDecision.prevent; - } - return NavigationDecision.prevent; - }, - onUrlChange: (url) { - if (url.url.toString().contains('/hub/home')) { - context.pop(); - } - }), - ) - ..loadRequest(Uri.parse(url)), - ), + _controllerAll.runJavaScript(token); + _controllerAll.runJavaScript(data); + _controllerAll.runJavaScript(backNavigation); + }, + onPageFinished: (String url) { + bool isDarkMode = SchedulerBinding + .instance + .platformDispatcher + .platformBrightness == + Brightness.dark; + + if (isDarkMode) { + _controllerAll.runJavaScript( + WebviewUtil.jsEnableDarkMode); + } + }, + onNavigationRequest: (NavigationRequest request) { + if (request.url.startsWith('http') || + request.url.startsWith( + 'https://api.whatsapp.com/send') || + request.url.startsWith('https://wa.me')) { + launchUrlString(request.url); + return NavigationDecision.prevent; + } + return NavigationDecision.prevent; + }, + onUrlChange: (url) { + if (url.url.toString().contains('/hub/home')) { + context.pop(); + } + }), + ) + ..loadRequest(Uri.parse(url)), + ); + } else { + return Center(child: Text('Unexpected error')); + } + }, + ), ), ); } diff --git a/lib/pages/home_page/home_page_model.dart b/lib/pages/home_page/home_page_model.dart index b5c45af4..1f989aa3 100644 --- a/lib/pages/home_page/home_page_model.dart +++ b/lib/pages/home_page/home_page_model.dart @@ -1,12 +1,20 @@ import 'package:flutter/material.dart'; +import 'package:hub/app_state.dart'; import 'package:hub/components/organism_components/local_profile_component/local_profile_component_model.dart'; import 'package:hub/components/organism_components/menu_component/menu_component_model.dart'; import 'package:hub/components/organism_components/message_well_component/message_well_component_model.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; import 'package:hub/pages/home_page/home_page_widget.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; class HomePageModel extends FlutterFlowModel { bool isGrid = false; + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String cliUUID; + late final String userUUID; + late final String userName; + late final String userEmail; final unfocusNode = FocusNode(); FocusNode? textFieldFocusNode; @@ -16,8 +24,25 @@ class HomePageModel extends FlutterFlowModel { late MenuComponentModel menuComponentModel; late MessageWellComponentModel messageWellComponentModel; + Future _initVariable() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + userName = await db + .get(key: 'userName', field: 'value') + .then((value) => value.toString()); + userEmail = AppState().email; + } + @override void initState(BuildContext context) { + _initVariable(); localComponentModel = createModel(context, () => LocalProfileComponentModel()); menuComponentModel = createModel(context, () => MenuComponentModel()); diff --git a/lib/pages/home_page/home_page_widget.dart b/lib/pages/home_page/home_page_widget.dart index 095c9f0b..be2f828b 100644 --- a/lib/pages/home_page/home_page_widget.dart +++ b/lib/pages/home_page/home_page_widget.dart @@ -1,13 +1,10 @@ -import 'dart:async'; import 'dart:developer'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/notifications/firebase_messaging_service.dart'; import 'package:hub/backend/schema/enums/enums.dart'; -import 'package:hub/components/organism_components/bottom_arrow_linked_locals_component/bottom_arrow_linked_locals_component_widget.dart'; import 'package:hub/components/organism_components/local_profile_component/local_profile_component_widget.dart'; import 'package:hub/components/organism_components/menu_component/menu_component_widget.dart'; import 'package:hub/flutter_flow/flutter_flow_icon_button.dart'; @@ -15,9 +12,7 @@ import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/pages/home_page/home_page_model.dart'; import 'package:hub/shared/helpers/db_helper.dart'; -import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/widgets/drawer_widget/drawer_widget.dart'; -import 'package:sqflite/sqflite.dart'; class HomePageWidget extends StatefulWidget { const HomePageWidget({Key? key}) : super(key: key); @@ -33,99 +28,7 @@ class _HomePageWidgetState extends State { final DatabaseHelper db = DatabaseHelper(); _HomePageWidgetState() { - _localProfileComponentWidget = - LocalProfileComponentWidget(showBottomSheet: showModalSelectLocal); - } - - Future processData() async { - try { - final GetDadosCall callback = PhpGroup.getDadosCall; - final DatabaseHelper db = DatabaseHelper(); - final devUUID = await db.get(key: 'devUUID', field: 'value'); - final userUUID = await db.get(key: 'userUUID', field: 'value'); - final cliUUID = await db.get(key: 'cliUUID', field: 'value'); - - var response = await callback.call( - devUUID: devUUID, - userUUID: userUUID, - cliUUID: cliUUID, - ); - - final error = response.jsonBody['error']; - // final errorMsg = response.jsonBody['error_msg']; - - if (error == false) { - final whatsapp = response.jsonBody['whatsapp'] ?? false; - final provisional = response.jsonBody['provisional'] ?? false; - final pets = response.jsonBody['pet'] ?? false; - final petAmountRegister = response.jsonBody['petAmountRegister'] ?? '0'; - final name = response.jsonBody['visitado']['VDO_NOME']; - - await db.update('whatsapp', whatsapp.toString(), 'local'); - await db.update('provisional', provisional.toString(), 'local'); - await db.update('pets', pets.toString(), 'local'); - await db.update('petAmountRegister', petAmountRegister, 'local'); - await db.update('name', name, 'local'); - - safeSetState(() {}); - return; - } - - DialogUtil.warningDefault(context).whenComplete(() => processLocals()); - safeSetState(() {}); - return; - } catch (e, s) { - DialogUtil.warningDefault(context).whenComplete(() => processLocals()); - } - } - - Future processLocals() async { - try { - final GetLocalsCall callback = PhpGroup.getLocalsCall; - final devUUID = await db.get(key: 'devUUID', field: 'value'); - final userUUID = await db.get(key: 'userUUID', field: 'value'); - final cliUUID = await db - .get(key: 'cliUUID', field: 'value') - .then((value) => value.toString()); - var response = await callback.call( - devUUID: devUUID, - userUUID: userUUID, - ); - - List locals = response.jsonBody['locais'] ?? []; - - final activeLocals = - locals.where((local) => local['CLU_STATUS'] == 'A').toList(); - - if (activeLocals.isEmpty || cliUUID.isEmpty) { - await showModalSelectLocal(); - } else { - await processData(); - } - } catch (e) { - await showModalSelectLocal(); - } - } - - Future showModalSelectLocal() async { - await showModalBottomSheet( - isScrollControlled: true, - backgroundColor: Colors.transparent, - enableDrag: false, - isDismissible: false, - context: context, - builder: (context) => Padding( - padding: MediaQuery.viewInsetsOf(context), - child: const BottomArrowLinkedLocalsComponentWidget(), - ), - ).then((_) async { - _model.updatePage(() => safeSetState(() { - _localProfileComponentWidget = LocalProfileComponentWidget( - showBottomSheet: showModalSelectLocal); - })); - - await processData(); - }); + _localProfileComponentWidget = LocalProfileComponentWidget(); } @override @@ -143,16 +46,6 @@ class _HomePageWidgetState extends State { FirebaseMessagingService().updateDeviceToken(); - () async { - final cliUUID = await db - .get(key: 'cliUUID', field: 'value') - .then((value) => value.toString()); - if (cliUUID.isEmpty) { - log('No cliUUID found'); - await processLocals(); - } - }(); - _model.textController ??= TextEditingController(); _model.textFieldFocusNode ??= FocusNode(); } diff --git a/lib/pages/liberation_history/liberation_history_model.dart b/lib/pages/liberation_history/liberation_history_model.dart index a26534bb..7eb11c14 100644 --- a/lib/pages/liberation_history/liberation_history_model.dart +++ b/lib/pages/liberation_history/liberation_history_model.dart @@ -2,21 +2,21 @@ import 'package:hub/backend/api_requests/api_manager.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; import 'package:hub/flutter_flow/request_manager.dart'; - import 'package:flutter/material.dart'; import 'package:hub/pages/liberation_history/liberation_history_widget.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; class LiberationHistoryModel extends FlutterFlowModel { - /// State fields for stateful widgets in this page. + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; final unfocusNode = FocusNode(); - // State field(s) for TextField widget. FocusNode? textFieldFocusNode; TextEditingController? textController; String? Function(BuildContext, String?)? textControllerValidator; - /// Query cache managers for this widget. - final _getLiberationsManager = StreamRequestManager(); Stream getLiberations({ String? uniqueQueryKey, @@ -33,7 +33,21 @@ class LiberationHistoryModel extends FlutterFlowModel { _getLiberationsManager.clearRequest(uniqueKey); @override - void initState(BuildContext context) {} + void initState(BuildContext context) { + init(); + } + + Future init() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + } @override void dispose() { @@ -41,8 +55,6 @@ class LiberationHistoryModel extends FlutterFlowModel { textFieldFocusNode?.dispose(); textController?.dispose(); - /// Dispose query cache managers for this widget. - clearGetLiberationsCache(); } -} \ No newline at end of file +} diff --git a/lib/pages/liberation_history/liberation_history_widget.dart b/lib/pages/liberation_history/liberation_history_widget.dart index 25975d1c..ebaa4be7 100644 --- a/lib/pages/liberation_history/liberation_history_widget.dart +++ b/lib/pages/liberation_history/liberation_history_widget.dart @@ -11,6 +11,7 @@ import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; +import 'package:hub/pages/liberation_history/liberation_history_model.dart'; import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/validator_util.dart'; @@ -25,6 +26,7 @@ class LiberationHistoryWidget extends StatefulWidget { } class _LiberationHistoryWidgetState extends State { + late LiberationHistoryModel _model; final scaffoldKey = GlobalKey(); bool _hasData = false; bool _loading = false; @@ -35,6 +37,7 @@ class _LiberationHistoryWidgetState extends State { @override void initState() { _requestFuture = _fetchRequests(); + _model = createModel(context, () => LiberationHistoryModel()); super.initState(); } @@ -49,7 +52,7 @@ class _LiberationHistoryWidgetState extends State { } String _imagePath(dynamic request) { - return 'https://freaccess.com.br/freaccess/getImage.php?cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${request['VTE_ID'] ?? ''}&tipo=E'; + return 'https://freaccess.com.br/freaccess/getImage.php?cliID=${_model.cliUUID}&atividade=getFoto&Documento=${request['VTE_ID'] ?? ''}&tipo=E'; } Map _labelsHashMap(dynamic request, bool details) { @@ -326,14 +329,7 @@ class _LiberationHistoryWidgetState extends State { Future _fetchRequests() async { try { setState(() => _loading = true); - var response = await PhpGroup.getLiberationsCall - .call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliID: AppState().cliUUID, - atividade: 'getSolicitacoes', - ) - .first; + var response = await PhpGroup.getLiberationsCall.call().first; final List requests = response.jsonBody['solicitacoes'] ?? []; diff --git a/lib/pages/message_history_page/message_history_page_model.dart b/lib/pages/message_history_page/message_history_page_model.dart index 8d11df7b..8c410e87 100644 --- a/lib/pages/message_history_page/message_history_page_model.dart +++ b/lib/pages/message_history_page/message_history_page_model.dart @@ -5,16 +5,16 @@ import 'package:hub/flutter_flow/request_manager.dart'; import 'package:flutter/material.dart'; import 'package:hub/pages/message_history_page/message_history_page_widget.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; class MessageHistoryPageModel extends FlutterFlowModel { - /// State fields for stateful widgets in this page. - /// - - //copyWith + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; final unfocusNode = FocusNode(); - // State field(s) for TextField widget. FocusNode? textFieldFocusNode; TextEditingController? textController; String? Function(BuildContext, String?)? textControllerValidator; @@ -23,8 +23,6 @@ class MessageHistoryPageModel int get tabBarCurrentIndex => tabBarController != null ? tabBarController!.index : 0; - /// Query cache managers for this widget. - final _getLiberationsManager = StreamRequestManager(); Stream getLiberations({ String? uniqueQueryKey, @@ -41,7 +39,21 @@ class MessageHistoryPageModel _getLiberationsManager.clearRequest(uniqueKey); @override - void initState(BuildContext context) {} + void initState(BuildContext context) { + init(); + } + + Future init() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + } @override void dispose() { @@ -50,8 +62,6 @@ class MessageHistoryPageModel textController?.dispose(); tabBarController?.dispose(); - /// Dispose query cache managers for this widget. - clearGetLiberationsCache(); } } diff --git a/lib/pages/message_history_page/message_history_page_widget.dart b/lib/pages/message_history_page/message_history_page_widget.dart index 817340ea..12407eed 100644 --- a/lib/pages/message_history_page/message_history_page_widget.dart +++ b/lib/pages/message_history_page/message_history_page_widget.dart @@ -99,10 +99,6 @@ class _MessageHistoryPageWidgetState extends State setState(() => _loading = true); var response = await PhpGroup.getMessagesCall.call( - devUUID: AppState().devUUID.toString(), - userUUID: AppState().userUUID.toString(), - cliID: AppState().cliUUID.toString(), - atividade: 'getMensagens', pageSize: _pageSize.toString(), pageNumber: _pageNumber.toString(), tipoDestino: _destinyType, diff --git a/lib/pages/package_order_page/package_order_page.dart b/lib/pages/package_order_page/package_order_page.dart index 83d28dc9..b9746a13 100644 --- a/lib/pages/package_order_page/package_order_page.dart +++ b/lib/pages/package_order_page/package_order_page.dart @@ -9,6 +9,7 @@ import 'package:hub/components/templates_components/details_component/details_co import 'package:hub/flutter_flow/flutter_flow_icon_button.dart'; import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/validator_util.dart'; @@ -27,6 +28,8 @@ class _PackageOrderPage extends State { final int _pageSize = 10; bool _hasData = false; bool _loading = false; + final DatabaseHelper db = DatabaseHelper(); + late final String cliUUID; late Future _orderFuture; List _orderList = []; @@ -57,6 +60,13 @@ class _PackageOrderPage extends State { _loadMoreOrders(); } }); + initDatabase(); + } + + Future initDatabase() async { + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); } @override @@ -85,10 +95,6 @@ class _PackageOrderPage extends State { setState(() => _loading = true); var response = await PhpGroup.buscaEnconcomendas.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliID: AppState().cliUUID, - atividade: 'getEncomendas', pageSize: _pageSize.toString(), page: _pageNumber.toString(), adresseeType: _adresseeType == '.*' ? 'TOD' : _adresseeType, @@ -300,7 +306,7 @@ class _PackageOrderPage extends State { } String _imagePath(dynamic order) { - return '${PhpGroup.getBaseUrl()}/getImage.php?cliID=${AppState().cliUUID}&atividade=getFotoEncomenda&orderId=${order['id'] ?? ''}'; + return '${PhpGroup.getBaseUrl()}/getImage.php?cliID=$cliUUID&atividade=getFotoEncomenda&orderId=${order['id'] ?? ''}'; } Map _labelsHashMap(dynamic order) { diff --git a/lib/pages/people_on_the_property_page/people_on_the_property_page_widget.dart b/lib/pages/people_on_the_property_page/people_on_the_property_page_widget.dart index e9ba900c..04097a0d 100644 --- a/lib/pages/people_on_the_property_page/people_on_the_property_page_widget.dart +++ b/lib/pages/people_on_the_property_page/people_on_the_property_page_widget.dart @@ -84,12 +84,7 @@ class _PeopleOnThePropertyPageWidgetState body: SafeArea( top: true, child: FutureBuilder( - future: PhpGroup.getPessoasLocalCall.call( - cliID: AppState().cliUUID, - ownID: AppState().ownerUUID, - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - ), + future: PhpGroup.getPessoasLocalCall.call(), builder: (context, snapshot) { // Customize what your widget looks like when it's loading. if (!snapshot.hasData) { diff --git a/lib/pages/pets_page/pets_history_screen.dart b/lib/pages/pets_page/pets_history_screen.dart index 53660722..fbabbb47 100644 --- a/lib/pages/pets_page/pets_history_screen.dart +++ b/lib/pages/pets_page/pets_history_screen.dart @@ -5,13 +5,18 @@ import 'package:hub/components/templates_components/card_item_template_component import 'package:hub/components/templates_components/details_component/details_component_action.dart'; import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; +import 'package:hub/pages/liberation_history/liberation_history_model.dart'; +import 'package:hub/pages/pets_page/pets_page_model.dart'; import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/validator_util.dart'; class PetsHistoryScreen extends StatefulWidget { - PetsHistoryScreen({Key? key}) : super(key: key); + PetsHistoryScreen({Key? key, required this.model}) : super(key: key); + + final PetsPageModel model; @override _PetsHistoryScreenState createState() => _PetsHistoryScreenState(); @@ -20,6 +25,7 @@ class PetsHistoryScreen extends StatefulWidget { class _PetsHistoryScreenState extends State with TickerProviderStateMixin { late ScrollController _scrollController; + int _pageNumber = 1; final int _pageSize = 10; bool _hasData = false; @@ -32,6 +38,7 @@ class _PetsHistoryScreenState extends State @override void initState() { super.initState(); + _petsFuture = _fetchVisits(); _scrollController = ScrollController() @@ -54,10 +61,6 @@ class _PetsHistoryScreenState extends State setState(() => _loading = true); var response = await PhpGroup.getPets.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliID: AppState().cliUUID, - atividade: 'consultaPets', pageSize: _pageSize, page: _pageNumber, ); @@ -151,10 +154,10 @@ class _PetsHistoryScreenState extends State return Padding( padding: EdgeInsets.only(right: 30, top: 10), child: Text( - AppState().petAmountRegister == 0 + widget.model.petAmountRegister == '0' ? FFLocalizations.of(context).getVariableText( ptText: "Ilimitado", enText: "Unlimited") - : "${FFLocalizations.of(context).getVariableText(ptText: "Quantidade de Pets: ", enText: "Amount of Pets: ")}${count}/${AppState().petAmountRegister}", + : "${FFLocalizations.of(context).getVariableText(ptText: "Quantidade de Pets: ", enText: "Amount of Pets: ")}$count/${widget.model.petAmountRegister}", textAlign: TextAlign.right, ), ); @@ -183,7 +186,7 @@ class _PetsHistoryScreenState extends State Widget _item(BuildContext context, dynamic uItem) { return CardItemTemplateComponentWidget( imagePath: - 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${AppState().devUUID}&userUUID=${AppState().userUUID}&cliID=${AppState().cliUUID}&atividade=consultaFotoPet&petId=${uItem['id'] ?? ''}', + 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${widget.model.devUUID}&userUUID=${widget.model.userUUID}&cliID=${widget.model.cliUUID}&atividade=consultaFotoPet&petId=${uItem['id'] ?? ''}', labelsHashMap: { '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:': uItem['name'] ?? '', @@ -242,6 +245,19 @@ class _PetsHistoryScreenState extends State } ], onTapCardItemAction: () async { + final DatabaseHelper db = DatabaseHelper(); + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + final cliName = await db + .get(key: 'cliName', field: 'value') + .then((value) => value.toString()); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); await showDialog( useSafeArea: true, context: context, @@ -249,9 +265,14 @@ class _PetsHistoryScreenState extends State return Dialog( alignment: Alignment.center, child: buildPetDetails( - uItem, - context, - changeStatusAction, + item: uItem, + context: context, + changeStatusAction: changeStatusAction, + devUUID: devUUID, + userUUID: userUUID, + cliUUID: cliUUID, + cliName: cliName, + model: widget.model, ), ); }, diff --git a/lib/pages/pets_page/pets_page_model.dart b/lib/pages/pets_page/pets_page_model.dart index 11963e0e..dbd834f3 100644 --- a/lib/pages/pets_page/pets_page_model.dart +++ b/lib/pages/pets_page/pets_page_model.dart @@ -1,19 +1,32 @@ +import 'dart:convert'; import 'dart:developer'; import 'package:flutter/material.dart'; +import 'package:http/http.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_manager.dart'; +import 'package:hub/custom_code/actions/convert_to_upload_file.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/form_field_controller.dart'; import 'package:hub/pages/pets_page/pets_page_widget.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/log_util.dart'; +import 'package:hub/shared/utils/validator_util.dart'; import '/custom_code/actions/index.dart' as actions; class PetsPageModel extends FlutterFlowModel { + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; + late final String petAmountRegister; + dynamic item; + late final TabController tabBarController; VoidCallback? onUpdatePet; VoidCallback? onRegisterPet; VoidCallback? safeSetState; + VoidCallback? updateImage; final GlobalKey registerFormKey = GlobalKey(); final GlobalKey updateFormKey = GlobalKey(); @@ -23,19 +36,17 @@ class PetsPageModel extends FlutterFlowModel { BuildContext? buildContext; bool isEditing = false; - // Controller para o Upload de Arquivos bool isDataUploading = false; FFUploadedFile? uploadedLocalFile; + FFUploadedFile? uploadedTempFile; String? imgBase64; - // Controller para o DropDown String? dropDownValue1; FormFieldController? dropDownValueController1; String? dropDownValue2; FormFieldController? dropDownValueController2; - // Controller para o TextField FocusNode? textFieldFocusName; TextEditingController? textControllerName; String? textControllerNameValidator(BuildContext context, String? val) { @@ -87,9 +98,25 @@ class PetsPageModel extends FlutterFlowModel { TextEditingController? textControllerObservation; String? Function(BuildContext, String?)? textControllerObservationValidator; + Future initAsync() async { + devUUID = await db.get(key: 'devUUID', field: 'value').then((value) { + return value.toString(); + }); + userUUID = await db.get(key: 'userUUID', field: 'value').then((value) { + return value.toString(); + }); + cliUUID = await db.get(key: 'cliUUID', field: 'value').then((value) { + return value.toString(); + }); + petAmountRegister = await db + .get(key: 'petAmountRegister', field: 'value') + .then((value) => value.toString()); + + safeSetState?.call(); + } + @override void initState(BuildContext context) { - // Se liga! Esse é o controller do TabBar tabBarController = TabController( vsync: Navigator.of(context), length: 2, @@ -97,8 +124,6 @@ class PetsPageModel extends FlutterFlowModel { textFieldFocusName = FocusNode(); textControllerName = TextEditingController(); - // textControllerNameValidator = - // (context, value) => _textControllerNameValidator(context, value); textFieldFocusSpecies = FocusNode(); textControllerSpecies = TextEditingController(); @@ -124,6 +149,66 @@ class PetsPageModel extends FlutterFlowModel { dropDownValueController2 = FormFieldController(dropDownValue2 ??= 'Selecione uma opção'); + + initAsync(); + } + + void setEditForm() { + log('item: $item'); + + if (item != null) petId = item['id']; + + // updateImage!(); + (() async { + Response response = await get(Uri.parse( + 'https://freaccess.com.br/freaccess/getImage.php?devUUID=$devUUID&userUUID=$userUUID&cliID=$cliUUID&atividade=consultaFotoPet&petId=$petId')); + String base64 = base64Encode(response.bodyBytes); + uploadedTempFile = await convertToUploadFile(base64); + updateImage?.call(); + })(); + + textControllerName = + TextEditingController(text: item != null ? item['name'] ?? '' : ''); + textFieldFocusName = FocusNode(); + + textControllerSpecies = + TextEditingController(text: item != null ? item['species'] ?? '' : ''); + textFieldFocusSpecies = FocusNode(); + + textControllerRace = + TextEditingController(text: item != null ? item['breed'] ?? '' : ''); + textFieldFocusRace = FocusNode(); + + textControllerColor = + TextEditingController(text: item != null ? item['color'] ?? '' : ''); + textFieldFocusColor = FocusNode(); + + textControllerData = TextEditingController( + text: item != null + ? item['birthdayDate'] != null + ? ValidatorUtil.formatDateTimePicker(item['birthdayDate']) + : dateTimeFormat( + 'dd/MM/yyyy', + DateTime.now(), + ) + : dateTimeFormat( + 'dd/MM/yyyy', + DateTime.now(), + )); + + textFieldFocusData = FocusNode(); + + textControllerObservation = + TextEditingController(text: item != null ? item['notes'] ?? '' : ''); + textFieldFocusObservation = FocusNode(); + + item != null ? dropDownValue1 = item['gender'] ?? '' : dropDownValue1 = ''; + + item != null ? dropDownValue2 = item['size'] ?? '' : dropDownValue2 = ''; + + dropDownValueController1 = FormFieldController(dropDownValue1); + + dropDownValueController2 = FormFieldController(dropDownValue2); } @override @@ -152,7 +237,6 @@ class PetsPageModel extends FlutterFlowModel { dropDownValueController2?.dispose(); } - // Validador do formulário bool isFormValid(BuildContext context) { if (uploadedLocalFile == null || uploadedLocalFile!.bytes!.isEmpty) { return false; @@ -188,9 +272,6 @@ class PetsPageModel extends FlutterFlowModel { img = "base64;jpeg,$img"; await PhpGroup.updatePet .call( - cliID: AppState().cliUUID, - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, petID: petId, image: img, birthdayDate: textControllerData!.text, @@ -224,9 +305,6 @@ class PetsPageModel extends FlutterFlowModel { img = "base64;jpeg,$img"; await PhpGroup.registerPet .call( - cliID: AppState().cliUUID, - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, image: img, birthdayDate: textControllerData!.text, color: textControllerColor!.text, @@ -270,6 +348,7 @@ class PetsPageModel extends FlutterFlowModel { void switchTab(int index) { tabBarController.animateTo(index); if (index == 1) handleEditingChanged(false); + safeSetState?.call(); } void handleUploadComplete(FFUploadedFile uploadedFile) { diff --git a/lib/pages/pets_page/pets_page_widget.dart b/lib/pages/pets_page/pets_page_widget.dart index dc5df7df..4132f447 100644 --- a/lib/pages/pets_page/pets_page_widget.dart +++ b/lib/pages/pets_page/pets_page_widget.dart @@ -55,8 +55,9 @@ class _PetsPageWidgetState extends State @override void initState() { super.initState(); - _model = PetsPageModel(); - _model.tabBarController = TabController(length: 2, vsync: this); + _model = createModel(context, () => PetsPageModel()); + _model.updateOnChange = true; + _model.onUpdatePet = () { safeSetState(() { _model.clearFields(); @@ -70,10 +71,9 @@ class _PetsPageWidgetState extends State _model.safeSetState = () { safeSetState(() {}); }; - - widget.pet != null ? _model.isEditing = true : _model.isEditing = false; - - // _handleUploadComplete(actions.convertToUploadFile()) + _model.updateImage = () => setState(() { + _model.handleUploadComplete(_model.uploadedTempFile!); + }); if (widget.pet != null) { int petId = widget.pet['id']; @@ -81,7 +81,7 @@ class _PetsPageWidgetState extends State (() async { Response response = await get(Uri.parse( - 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${AppState().devUUID}&userUUID=${AppState().userUUID}&cliID=${AppState().cliUUID}&atividade=consultaFotoPet&petId=$petId')); + 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${_model.devUUID}&userUUID=${_model.userUUID}&cliID=${_model.cliUUID}&atividade=consultaFotoPet&petId=$petId')); String base64 = base64Encode(response.bodyBytes); FFUploadedFile uploadedFile = await convertToUploadFile(base64); setState(() { @@ -178,7 +178,7 @@ class _PetsPageWidgetState extends State widget1: _model.isEditing ? _buildEditForm(context) : _buildRegisterForm(context), - widget2: PetsHistoryScreen(), + widget2: PetsHistoryScreen(model: _model), onEditingChanged: onEditingChanged, ); } diff --git a/lib/pages/preferences_settings_page/preferences_settings_model.dart b/lib/pages/preferences_settings_page/preferences_settings_model.dart index cf64f7c7..6df152e5 100644 --- a/lib/pages/preferences_settings_page/preferences_settings_model.dart +++ b/lib/pages/preferences_settings_page/preferences_settings_model.dart @@ -1,5 +1,4 @@ import 'dart:developer'; - import 'package:flutter/material.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/templates_components/change_passs_qr_code_pass_key_template_component/change_pass_widget.dart'; @@ -7,751 +6,224 @@ import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:share_plus/share_plus.dart'; +import 'package:sqflite/sqflite.dart'; class PreferencesPageModel with ChangeNotifier { final unfocusNode = FocusNode(); + final DatabaseHelper db = DatabaseHelper(); + bool fingerprint = false; + bool person = false; + bool notify = false; + bool access = false; + bool panic = false; - Future toggleFingerprint(BuildContext context) async { - // AppState().checkBiometrics() - // .then((value) => AppState().authenticateBiometric() - // .then( (value) { - // AppState().fingerprint = !AppState().fingerprint; - - // }) - // .whenComplete(() => notifyListeners())); - - if (AppState().fingerprint) { - AppState().fingerprint = false; - AppState().deleteFingerprintPass(); - notifyListeners(); - } else { - await showModalBottomSheet( - isScrollControlled: true, - backgroundColor: Colors.transparent, - useSafeArea: true, - context: context, - builder: (context) { - return Padding( - padding: MediaQuery.viewInsetsOf(context), - child: PassKeyTemplateWidget( - toggleActionStatus: (key) async { - AppState().fingerprintPass = key; - AppState().fingerprint = true; - }, - ), - ); - }, - ).then((value) { - if (value) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Fingerprint changed successfully', - ptText: 'Impressão digital alterada com sucesso', - ), - style: TextStyle(color: FlutterFlowTheme.of(context).info)), - backgroundColor: FlutterFlowTheme.of(context).success, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - } - }).catchError((err, stack) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - ptText: 'Erro ao alterar impressão digital', - enText: 'Error changing fingerprint', - ), - style: TextStyle(color: FlutterFlowTheme.of(context).info)), - backgroundColor: FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - }).whenComplete(() => notifyListeners()); - } + PreferencesPageModel() { + initVariables(); } - void enablePerson(BuildContext context) { + Future enablePerson(BuildContext context) async { + final String userDevUUID = await db.get(key: 'userDevUUID', field: 'value'); notifyListeners(); Share.share( FFLocalizations.of(context).getVariableText( - ptText: - 'Este é o meu identificador de acesso: ${AppState().userDevUUID}', - enText: 'This is my access identifier: ${AppState().userDevUUID}', + ptText: 'Este é o meu identificador de acesso: $userDevUUID', + enText: 'This is my access identifier: $userDevUUID', ), ); } - void toggleNotify(BuildContext context) { - showDialog( - context: context, - builder: (context) { - return AlertDialog( - backgroundColor: FlutterFlowTheme.of(context).primaryBackground, - title: Text( - FFLocalizations.of(context).getVariableText( - enText: AppState().notify - ? 'Disable Access Notification' - : 'Access Notification', - ptText: AppState().notify - ? 'Desativar notificação de acesso' - : 'Notificação de acesso'), - ), - content: Text( - FFLocalizations.of(context).getVariableText( - ptText: AppState().notify - ? 'Tem certeza que deseja desativar as suas notificações de acesso?' - : 'Tem certeza que deseja receber as suas notificações de acesso?', - enText: AppState().notify - ? 'Are you sure you want to disable your access notifications?' - : 'Are you sure you want to receive your access notifications?'), - ), - actions: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - mainAxisSize: MainAxisSize.max, - children: [ - FFButtonWidget( - text: FFLocalizations.of(context).getVariableText( - enText: 'No', - ptText: 'Não', - ), - onPressed: () { - context.pop(); - }, - options: FFButtonOptions( - elevation: 0, - width: MediaQuery.of(context).size.width * 0.3, - height: MediaQuery.of(context).size.height * 0.05, - color: FlutterFlowTheme.of(context).primaryBackground, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - borderRadius: BorderRadius.circular(10)), - ), - FFButtonWidget( - onPressed: () async { - try { - PhpGroup.changeNotifica - .call( - userUUID: AppState().userUUID, - devUUID: AppState().devUUID, - cliID: AppState().cliUUID, - atividade: 'updVisitado', - notifica: AppState().notify ? 'S' : 'N', - ) - .then((value) { - if (value.jsonBody['error'] == false) { - context.pop(); - - AppState().notify = !AppState().notify; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - ptText: - 'Notificação alterada com sucesso', - enText: - 'Notification changed successfully', - ), - style: TextStyle( - color: - FlutterFlowTheme.of(context).info)), - backgroundColor: - FlutterFlowTheme.of(context).success, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - } else { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - ptText: 'Erro ao alterar notificação', - enText: 'Error changing notification', - ), - style: TextStyle( - color: - FlutterFlowTheme.of(context).info)), - backgroundColor: - FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - } - }).catchError((err) { - context.pop(); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Error changing notification', - ptText: 'Erro ao alterar notificação', - ), - style: TextStyle( - color: - FlutterFlowTheme.of(context).info)), - backgroundColor: - FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - }).whenComplete(() => notifyListeners()); - } on Exception catch (e) { - context.pop(); - } - }, - text: FFLocalizations.of(context).getVariableText( - enText: 'Yes', - ptText: 'Sim', - ), - options: FFButtonOptions( - elevation: 0, - width: MediaQuery.of(context).size.width * 0.3, - height: MediaQuery.of(context).size.height * 0.05, - color: FlutterFlowTheme.of(context).primaryBackground, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - borderRadius: BorderRadius.circular(10), - ), - ), - ], - ), - ], - ); - }); - notifyListeners(); - } - - void localUnlink(BuildContext context) { - showDialog( - context: context, - builder: (context) { - return AlertDialog( - backgroundColor: FlutterFlowTheme.of(context).primaryBackground, - title: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Unlink device', - ptText: 'Desvincular dispositivo', - ), - ), - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Are you sure you want to unlink this device?', - ptText: 'Tem certeza que deseja desvincular este dispositivo?', - ), - ), - actions: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - mainAxisSize: MainAxisSize.max, - children: [ - FFButtonWidget( - text: FFLocalizations.of(context).getVariableText( - enText: 'Cancel', - ptText: 'Cancelar', - ), - onPressed: () { - context.pop(); - }, - options: FFButtonOptions( - width: MediaQuery.of(context).size.width * 0.3, - height: MediaQuery.of(context).size.height * 0.05, - color: FlutterFlowTheme.of(context).primaryBackground, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - borderRadius: BorderRadius.circular(10)), - ), - FFButtonWidget( - onPressed: () async { - try { - await PhpGroup.resopndeVinculo - .call( - userUUID: AppState().userUUID, - devUUID: AppState().devUUID, - cliID: AppState().cliUUID, - tarefa: 'I', - ) - .then((value) { - if (value.jsonBody['error'] == false) { - AppState().deleteCliUUID(); - AppState().deleteLocal(); - AppState().deleteOwnerUUID(); - - context.pop(); - - context.go( - '/homePage', - extra: { - kTransitionInfoKey: const TransitionInfo( - hasTransition: true, - transitionType: PageTransitionType.scale, - alignment: Alignment.bottomCenter, - ), - }, - ); - - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Device unlinked successfully', - ptText: - 'Dispositivo desvinculado com sucesso', - ), - style: TextStyle( - color: - FlutterFlowTheme.of(context).info)), - backgroundColor: - FlutterFlowTheme.of(context).success, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - } - }) - // ignore: body_might_complete_normally_catch_error - .catchError((err, stack) { - context.pop(); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Error unlinking device', - ptText: 'Erro ao desvincular dispositivo', - ), - style: TextStyle( - color: - FlutterFlowTheme.of(context).info)), - backgroundColor: - FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - }); - // notifyListeners(); - } catch (err, stack) { - context.pop(); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Error unlinking device', - ptText: 'Erro ao desvincular dispositivo', - ), - style: TextStyle( - color: FlutterFlowTheme.of(context).info)), - backgroundColor: FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - } - }, - text: FFLocalizations.of(context).getVariableText( - enText: 'Unlink', - ptText: 'Desvincular', - ), - options: FFButtonOptions( - width: MediaQuery.of(context).size.width * 0.3, - height: MediaQuery.of(context).size.height * 0.05, - color: FlutterFlowTheme.of(context).primaryBackground, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - borderRadius: BorderRadius.circular(10), - ), - ), - ], - ), - ], - ); - }); - // notifyListeners(); - } - - void deleteAccount(BuildContext context) { - showDialog( - context: context, - builder: (context) { - return AlertDialog( - backgroundColor: FlutterFlowTheme.of(context).primaryBackground, - title: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Delete account', - ptText: 'Deletar conta', - ), - ), - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Are you sure you want to delete your account?', - ptText: 'Tem certeza que deseja deletar sua conta?', - ), - ), - actions: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - mainAxisSize: MainAxisSize.max, - children: [ - FFButtonWidget( - onPressed: () => context.pop(), // Navigator.pop(context), - options: FFButtonOptions( - width: MediaQuery.of(context).size.width * 0.3, - height: MediaQuery.of(context).size.height * 0.05, - color: FlutterFlowTheme.of(context).primaryBackground, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - borderRadius: BorderRadius.circular(10), - ), - text: FFLocalizations.of(context).getVariableText( - enText: 'Cancel', - ptText: 'Cancelar', - ), - ), - FFButtonWidget( - onPressed: () async { - try { - await PhpGroup.deleteAccount - .call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - ) - .then((value) { - if (value.jsonBody['error'] == false) { - AppState().deleteAll(); - AppState().isLogged = false; - context.go( - '/welcomePage', - extra: { - kTransitionInfoKey: const TransitionInfo( - hasTransition: true, - transitionType: PageTransitionType.scale, - alignment: Alignment.bottomCenter, - ), - }, - ); - } - }).catchError((err) { - context.pop(); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Error deleting account', - ptText: 'Erro ao deletar conta', - ), - style: TextStyle( - color: - FlutterFlowTheme.of(context).info)), - backgroundColor: - FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - }); - notifyListeners(); - } catch (err, stack) { - context.pop(); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Error deleting account', - ptText: 'Erro ao deletar conta', - ), - style: TextStyle( - color: FlutterFlowTheme.of(context).info)), - backgroundColor: FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - } - }, - options: FFButtonOptions( - width: MediaQuery.of(context).size.width * 0.3, - height: MediaQuery.of(context).size.height * 0.05, - color: FlutterFlowTheme.of(context).primaryBackground, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - borderRadius: BorderRadius.circular(10), - ), - text: FFLocalizations.of(context).getVariableText( - enText: 'Delete', - ptText: 'Deletar', - ), - ), - ], - ), - ], - ); - }); - notifyListeners(); - } - - Future togglePass(BuildContext context) async { - // if (AppState().pass) { - // AppState().pass = false; - // AppState().deleteAccessPass(); - // notifyListeners(); - // } else { - await showModalBottomSheet( - isScrollControlled: true, - backgroundColor: Colors.transparent, - useSafeArea: true, - context: context, - builder: (context) { - return Padding( - padding: MediaQuery.viewInsetsOf(context), - child: PassKeyTemplateWidget( - toggleActionStatus: (key) async { - AppState().accessPass = key; - notifyListeners(); - await PhpGroup.changePass - .call( - userUUID: AppState().userUUID, - devUUID: AppState().devUUID, - cliID: AppState().cliUUID, - atividade: 'updVisitado', - newSenha: AppState().accessPass, - ) - .then((value) { - // var error = jsonDecode(value.jsonBody['error'].toString()); - if (jsonDecode(value.jsonBody['error'].toString()) == false) { - AppState().pass = true; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Access password changed successfully', - ptText: 'Senha de acesso alterada com sucesso', - ), - style: TextStyle( - color: FlutterFlowTheme.of(context).info)), - backgroundColor: FlutterFlowTheme.of(context).success, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - } else { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - ptText: 'Erro ao alterar senha de acesso', - enText: 'Error changing access password', - ), - style: TextStyle( - color: FlutterFlowTheme.of(context).info)), - backgroundColor: FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - // AppState().pass = false; - } - }).catchError((error, StackTrace) { - // AppState().pass = false; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - ptText: 'Erro ao alterar senha de acesso', - enText: 'Error changing access password', - ), - style: TextStyle( - color: FlutterFlowTheme.of(context).info)), - backgroundColor: FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - }).whenComplete(() => notifyListeners()); - }, - ), - ); - }, + Future toggleNotify(BuildContext context) async { + final String title = FFLocalizations.of(context).getVariableText( + enText: 'Change notification', + ptText: 'Alterar notificação', ); - // } + final String content = FFLocalizations.of(context).getVariableText( + enText: 'Are you sure you want to change your notification?', + ptText: 'Tem certeza que deseja alterar sua notificação?', + ); + onConfirm() async { + String content; + try { + content = FFLocalizations.of(context).getVariableText( + enText: 'Notification changed successfully', + ptText: 'Notificação alterada com sucesso', + ); + context.pop(); + _showSnackBar(context, content); + notify = await _toggleBoolInDb('notify'); + notifyListeners(); + } catch (err) { + content = FFLocalizations.of(context).getVariableText( + enText: 'Error changing notification', + ptText: 'Erro ao alterar notificação', + ); + context.pop(); + _showSnackBar(context, content, isError: true); + } + } + + showAlertDialog(context, title, content, onConfirm); + } + + Future toggleAccess(BuildContext context) async { + onChange(String key) async { + AppState().accessPass = key; + await PhpGroup.changePass + .call( + newSenha: key, + ) + .then((value) async { + final String content; + if (jsonDecode(value.jsonBody['error'].toString()) == false) { + if (!access) access = await _toggleBoolInDb('access'); + notifyListeners(); + content = FFLocalizations.of(context).getVariableText( + enText: 'Access pass changed successfully', + ptText: 'Senha de acesso alterada com sucesso', + ); + _showSnackBar(context, content); + } else { + content = FFLocalizations.of(context).getVariableText( + ptText: 'Erro ao alterar senha de acesso', + enText: 'Error changing access pass', + ); + _showSnackBar(context, content, isError: true); + } + }).catchError((e, s) { + final String content = FFLocalizations.of(context).getVariableText( + ptText: 'Erro ao alterar senha de acesso', + enText: 'Error changing access pass', + ); + _showSnackBar(context, content, isError: true); + }).whenComplete(() => notifyListeners()); + } + + _showPassKey(context, onChange); } Future togglePanic(BuildContext context) async { - await showModalBottomSheet( - isScrollControlled: true, - backgroundColor: Colors.transparent, - useSafeArea: true, - context: context, - builder: (context) { - return Padding( - padding: MediaQuery.viewInsetsOf(context), - child: PassKeyTemplateWidget( - toggleActionStatus: (key) async { - AppState().panicPass = key; - notifyListeners(); - await PhpGroup.changePanic - .call( - userUUID: AppState().userUUID, - devUUID: AppState().devUUID, - cliID: AppState().cliUUID, - atividade: 'updVisitado', - newSenhaPanico: AppState().panicPass, - ) - .then((value) { - AppState().panic = true; - if (jsonDecode(value.jsonBody['error'].toString()) == false) { - AppState().panic = true; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - enText: 'Panic password changed successfully', - ptText: 'Senha de pânico alterada com sucesso', - ), - style: TextStyle( - color: FlutterFlowTheme.of(context).info)), - backgroundColor: FlutterFlowTheme.of(context).success, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - } else { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - ptText: 'Erro ao alterar senha de pânico', - enText: 'Error changing panic password', - ), - style: TextStyle( - color: FlutterFlowTheme.of(context).info)), - backgroundColor: FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - // AppState().panic = false; - } - }).catchError((e, s) { - // AppState().panic = false; - - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - ptText: 'Erro ao alterar senha de pânico', - enText: 'Error changing panic password', - ), - style: TextStyle( - color: FlutterFlowTheme.of(context).info)), - backgroundColor: FlutterFlowTheme.of(context).error, - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(30), - ), - ), - ); - }).whenComplete(() => notifyListeners()); - }, - ), + onChange(String key) async { + AppState().panicPass = key; + await PhpGroup.changePanic + .call( + newSenhaPanico: AppState().panicPass, + ) + .then((value) async { + final String content; + if (jsonDecode(value.jsonBody['error'].toString()) == false) { + if (!panic) panic = await _toggleBoolInDb('panic'); + notifyListeners(); + content = FFLocalizations.of(context).getVariableText( + enText: 'Panic password changed successfully', + ptText: 'Senha de pânico alterada com sucesso', + ); + _showSnackBar(context, content); + } else { + content = FFLocalizations.of(context).getVariableText( + ptText: 'Erro ao alterar senha de pânico', + enText: 'Error changing panic password', + ); + _showSnackBar(context, content, isError: true); + } + }).catchError((e, s) { + final String content = FFLocalizations.of(context).getVariableText( + ptText: 'Erro ao alterar senha de pânico', + enText: 'Error changing panic password', ); - }, + _showSnackBar(context, content, isError: true); + }).whenComplete(() => notifyListeners()); + } + + _showPassKey(context, onChange); + } + + Future toggleFingerprint(BuildContext context) async { + final String content = FFLocalizations.of(context).getVariableText( + enText: 'Fingerprint changed successfully', + ptText: 'Impressão digital alterada com sucesso', ); + + onChange(String? key) async { + if (!fingerprint) AppState().fingerprintPass = key ?? ''; + if (fingerprint) AppState().deleteFingerprintPass(); + + fingerprint = await _toggleBoolInDb('fingerprint'); + notifyListeners(); + + _showSnackBar(context, content); + } + + fingerprint ? onChange(null) : _showPassKey(context, onChange); + } + + Future deleteAccount(BuildContext context) async { + final String title = FFLocalizations.of(context).getVariableText( + enText: 'Delete account', + ptText: 'Deletar conta', + ); + final String content = FFLocalizations.of(context).getVariableText( + enText: 'Are you sure you want to delete your account?', + ptText: 'Tem certeza que deseja deletar sua conta?', + ); + onConfirm() async { + String content; + try { + await PhpGroup.deleteAccount.call().then((value) { + if (value.jsonBody['error'] == false) { + content = FFLocalizations.of(context).getVariableText( + enText: 'Account deleted successfully', + ptText: 'Conta deletada com sucesso', + ); + + AppState().deleteAll(); + + context.pop(); + context.go( + '/welcomePage', + extra: { + kTransitionInfoKey: const TransitionInfo( + hasTransition: true, + transitionType: PageTransitionType.scale, + alignment: Alignment.bottomCenter, + ), + }, + ); + } + }).catchError((err) { + context.pop(); + content = FFLocalizations.of(context).getVariableText( + enText: 'Error deleting account', + ptText: 'Erro ao deletar conta', + ); + _showSnackBar(context, content); + }); + notifyListeners(); + } catch (err) { + context.pop(); + content = FFLocalizations.of(context).getVariableText( + enText: 'Error deleting account', + ptText: 'Erro ao deletar conta', + ); + _showSnackBar(context, content, isError: true); + } + } + + showAlertDialog(context, title, content, onConfirm); } void logout(BuildContext context) async { - showAlertDialog( - context, - 'Logout', - FFLocalizations.of(context).getVariableText( - enText: 'Are you sure you want to logout?', - ptText: 'Tem certeza', - ), () async { + final String title = FFLocalizations.of(context).getVariableText( + enText: 'Logout', + ptText: 'Sair', + ); + final String content = FFLocalizations.of(context).getVariableText( + enText: 'Are you sure you want to logout?', + ptText: 'Tem certeza que deseja sair?', + ); + onConfirm() async { AppState().deleteAll(); - // setState(() {}); context.go( '/welcomePage', @@ -763,12 +235,145 @@ class PreferencesPageModel with ChangeNotifier { ), }, ); - }); + } + + showAlertDialog(context, title, content, onConfirm); } - @override - void dispose() { - unfocusNode.dispose(); - super.dispose(); + void localUnlink(BuildContext context) { + final String title = FFLocalizations.of(context).getVariableText( + enText: 'Unlink device', + ptText: 'Desvincular dispositivo', + ); + final String content = FFLocalizations.of(context).getVariableText( + enText: 'Are you sure you want to unlink your device?', + ptText: 'Tem certeza que deseja desvincular seu dispositivo?', + ); + onConfirm() async { + String content; + try { + content = FFLocalizations.of(context).getVariableText( + enText: 'Device unlinked successfully', + ptText: 'Dispositivo desvinculado com sucesso', + ); + + await PhpGroup.resopndeVinculo.call(tarefa: 'I').then((value) { + if (value.jsonBody['error'] == false) { + db.clear('cliName'); + db.clear('cliUUID'); + db.clear('ownerUUID'); + + context.pop(); + + context.go( + '/homePage', + extra: { + kTransitionInfoKey: const TransitionInfo( + hasTransition: true, + transitionType: PageTransitionType.scale, + alignment: Alignment.bottomCenter, + ), + }, + ); + + _showSnackBar(context, content); + } + }).catchError((err, stack) { + context.pop(); + content = FFLocalizations.of(context).getVariableText( + enText: 'Error unlinking device', + ptText: 'Erro ao desvincular dispositivo', + ); + _showSnackBar(context, content, isError: true); + }); + } catch (err, stack) { + context.pop(); + log(err.toString(), stackTrace: stack); + content = FFLocalizations.of(context).getVariableText( + enText: 'Error unlinking device', + ptText: 'Erro ao desvincular dispositivo', + ); + _showSnackBar(context, content, isError: true); + } + } + + showAlertDialog(context, title, content, onConfirm); + } + + Future initVariables() async { + fingerprint = await _getBoolFromDb('fingerprint'); + person = await _getBoolFromDb('person'); + notify = await _getBoolFromDb('notify'); + access = await _getBoolFromDb('pass'); + panic = await _getBoolFromDb('panic'); + notifyListeners(); + } + + Future _getBoolFromDb(String key) async { + final value = await db.get(key: key, field: 'value'); + return value.toString() == 'true'; + } + + Future _toggleBoolInDb(String key) async { + final currentValue = await _getBoolFromDb(key); + final newValue = !currentValue; + await db.update(key, newValue.toString(), 'util'); + return newValue; + } + + void _showAlertDialog(BuildContext context, String title, String content, + Function() onConfirm) { + showAlertDialog( + context, + 'Delete account', + 'Are you sure you want to delete your account?', + onConfirm(), + ); + } + + void _showSnackBar(BuildContext context, String text, + {bool isError = false}) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + text, + style: TextStyle(color: FlutterFlowTheme.of(context).info), + ), + backgroundColor: isError + ? FlutterFlowTheme.of(context).error + : FlutterFlowTheme.of(context).success, + duration: const Duration(seconds: 3), + behavior: SnackBarBehavior.floating, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(30), + ), + ), + ); + } + + void _showPassKey( + BuildContext context, void Function(String) onChange) async { + await showModalBottomSheet( + isScrollControlled: true, + backgroundColor: Colors.transparent, + useSafeArea: true, + context: context, + builder: (context) { + return Padding( + padding: MediaQuery.viewInsetsOf(context), + child: PassKeyTemplateWidget( + toggleActionStatus: (key) async { + onChange.call(key); + }, + ), + ); + }, + ).catchError((err, stack) { + final String content = FFLocalizations.of(context).getVariableText( + enText: 'Error changing key', + ptText: 'Erro ao alterar senha', + ); + _showSnackBar(context, content, isError: true); + }).whenComplete(() => notifyListeners()); } } diff --git a/lib/pages/preferences_settings_page/preferences_settings_widget.dart b/lib/pages/preferences_settings_page/preferences_settings_widget.dart index c493bbf6..47a17c81 100644 --- a/lib/pages/preferences_settings_page/preferences_settings_widget.dart +++ b/lib/pages/preferences_settings_page/preferences_settings_widget.dart @@ -1,15 +1,28 @@ import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:hub/app_state.dart'; import 'package:hub/flutter_flow/flutter_flow_icon_button.dart'; import 'package:hub/flutter_flow/flutter_flow_theme.dart'; +import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/internationalization.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/pages/preferences_settings_page/preferences_settings_model.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:provider/provider.dart'; -class PreferencesPageWidget extends StatelessWidget { - const PreferencesPageWidget({super.key}); +class PreferencesPageWidget extends StatefulWidget { + PreferencesPageWidget(); + + @override + _PreferencesPageWidgetState createState() => _PreferencesPageWidgetState(); +} + +class _PreferencesPageWidgetState extends State { + final DatabaseHelper db = DatabaseHelper(); + + @override + void initState() { + super.initState(); + } @override Widget build(BuildContext context) { @@ -65,7 +78,7 @@ class PreferencesPageWidget extends StatelessWidget { Expanded( flex: 2, child: ListView.builder( - itemCount: 7, // Assuming 4 items for simplicity + itemCount: 7, // Assuming 7 items for simplicity padding: const EdgeInsets.symmetric(horizontal: 20.0), physics: const AlwaysScrollableScrollPhysics(), itemBuilder: (BuildContext context, int index) { @@ -91,9 +104,8 @@ class PreferencesPageWidget extends StatelessWidget { switch (index) { case 0: icon = Icons.fingerprint; - onPressed = () => - model.toggleFingerprint(context); // Disable if fingerprint is false - isEnabled = AppState().fingerprint; + onPressed = () => model.toggleFingerprint(context); + isEnabled = model.fingerprint; content = FFLocalizations.of(context).getVariableText( ptText: 'Ative a autenticação por impressão digital para login seguro.', @@ -103,7 +115,7 @@ class PreferencesPageWidget extends StatelessWidget { case 1: icon = Icons.person; onPressed = () => model.enablePerson(context); - isEnabled = AppState().person; + isEnabled = model.person; content = FFLocalizations.of(context).getVariableText( ptText: 'Compartilhe o código de identificação remota', enText: 'Share the remote identification code', @@ -112,7 +124,7 @@ class PreferencesPageWidget extends StatelessWidget { case 2: icon = Icons.notifications; onPressed = () => model.toggleNotify(context); - isEnabled = AppState().notify; + isEnabled = model.notify; content = FFLocalizations.of(context).getVariableText( ptText: 'Ative para receber sua notificação de acesso', enText: 'Enable to receive your access notification', @@ -120,8 +132,8 @@ class PreferencesPageWidget extends StatelessWidget { break; case 3: icon = Icons.lock; - // onLongPress = model.togglePass(context, model); - isEnabled = AppState().pass; + onPressed = () => model.toggleAccess(context); + isEnabled = model.access; content = FFLocalizations.of(context).getVariableText( ptText: 'Ative para inserir uma credencial de acesso para o QRCode', enText: 'Enable to enter an access credential for the QRCode', @@ -129,11 +141,11 @@ class PreferencesPageWidget extends StatelessWidget { break; case 4: icon = Icons.lock_clock_sharp; - // onLongPress = model.togglePass(context, model); - isEnabled = AppState().panic; + onPressed = () => model.togglePanic(context); + isEnabled = model.panic; content = FFLocalizations.of(context).getVariableText( ptText: 'Ative para inserir uma credencial de pânico para o QRCode', - enText: 'Enable to enter an panic credential for the QRCode', + enText: 'Enable to enter a panic credential for the QRCode', ); break; case 5: @@ -177,7 +189,7 @@ class PreferencesPageWidget extends StatelessWidget { onTap: () { switch (index) { case 3: - model.togglePass(context); + model.toggleAccess(context); break; case 4: model.togglePanic(context); @@ -197,14 +209,6 @@ class PreferencesPageWidget extends StatelessWidget { color: isEnabled ? FlutterFlowTheme.of(context).primaryBackground : FlutterFlowTheme.of(context).primary, - // icon: Icon(icon, color: isEnabled ? FlutterFlowTheme.of(context).primaryBackground : FlutterFlowTheme.of(context).primary, size: 40.0), - // onPressed: index != 3 ? onPressed : () {model.togglePass(context);}, - // borderRadius: 20.0, - // borderWidth: 1.0, - // buttonSize: 40.0, - // fillColor: isEnabled ? FlutterFlowTheme.of(context).primary : FlutterFlowTheme.of(context).alternate, - // disabledColor: FlutterFlowTheme.of(context).alternate, - // disabledIconColor: FlutterFlowTheme.of(context).primary, ), ), SizedBox(width: 8.0), @@ -227,4 +231,28 @@ class PreferencesPageWidget extends StatelessWidget { ), ); } + + void logout(BuildContext context) async { + showAlertDialog( + context, + 'Logout', + FFLocalizations.of(context).getVariableText( + enText: 'Are you sure you want to logout?', + ptText: 'Tem certeza', + ), () async { + AppState().deleteAll(); + // setState(() {}); + + context.go( + '/welcomePage', + extra: { + kTransitionInfoKey: const TransitionInfo( + hasTransition: true, + transitionType: PageTransitionType.scale, + alignment: Alignment.bottomCenter, + ), + }, + ); + }); + } } diff --git a/lib/pages/provisional_schedule_page/provisional_schedule_widget.dart b/lib/pages/provisional_schedule_page/provisional_schedule_widget.dart index 00c5c596..42afd259 100644 --- a/lib/pages/provisional_schedule_page/provisional_schedule_widget.dart +++ b/lib/pages/provisional_schedule_page/provisional_schedule_widget.dart @@ -17,20 +17,15 @@ class ProvisionalSchedule extends StatefulWidget { } class _ProvisionalScheduleState extends State { - late ScheduleProvisionalVisitPageModel _model; - final scaffoldKey = GlobalKey(); @override void initState() { super.initState(); - _model = createModel(context, () => ScheduleProvisionalVisitPageModel()); } @override void dispose() { - _model.dispose(); - super.dispose(); } diff --git a/lib/pages/qr_code_page/qr_code_page_model.dart b/lib/pages/qr_code_page/qr_code_page_model.dart index 40e016ab..da5b873a 100644 --- a/lib/pages/qr_code_page/qr_code_page_model.dart +++ b/lib/pages/qr_code_page/qr_code_page_model.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; import 'package:hub/pages/qr_code_page/qr_code_page_widget.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; class QrCodePageModel extends FlutterFlowModel { /// Local state fields for this page. @@ -11,13 +12,27 @@ class QrCodePageModel extends FlutterFlowModel { String? key = null; DateTime? time; + final DatabaseHelper db = DatabaseHelper(); + late final bool isFingerprint; + late final String userDevUUID; /// State fields for stateful widgets in this page. final unfocusNode = FocusNode(); @override - void initState(BuildContext context) {} + void initState(BuildContext context) { + initVariable(); + } + + Future initVariable() async { + isFingerprint = await db + .get(key: 'fingerprint', field: 'value') + .then((value) => value.toString() == 'true'); + userDevUUID = await db + .get(key: 'userDevUUID', field: 'value') + .then((value) => value.toString()); + } @override void dispose() { @@ -29,4 +44,4 @@ class QrCodePageModel extends FlutterFlowModel { BuildContext context, { required String? key, }) async {} -} \ No newline at end of file +} diff --git a/lib/pages/qr_code_page/qr_code_page_widget.dart b/lib/pages/qr_code_page/qr_code_page_widget.dart index 36e99e85..0b6e3f29 100644 --- a/lib/pages/qr_code_page/qr_code_page_widget.dart +++ b/lib/pages/qr_code_page/qr_code_page_widget.dart @@ -16,6 +16,7 @@ import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/pages/qr_code_page/qr_code_page_model.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:percent_indicator/circular_percent_indicator.dart'; // import 'package:percent_indicator/percent_indicator.dart'; @@ -140,14 +141,15 @@ class _QrCodePageWidgetState extends State safeSetState(() async { _resetAnimationAndToggleAccess(); }); - AppState().fingerprint + + _model.isFingerprint ? await _showBiometricsAuth(context) : await _showQrCodeBottomSheet(context); }, child: buildQrCode( dimension: dimension, errorCorrectLevel: QrErrorCorrectLevel.M, - identifier: AppState().userDevUUID, + identifier: _model.userDevUUID, pass: _model.key!, direction: 5, ), @@ -195,7 +197,7 @@ class _QrCodePageWidgetState extends State alignment: const AlignmentDirectional(0.0, 0.0), child: FFButtonWidget( onPressed: () async { - AppState().fingerprint + _model.isFingerprint ? await _showBiometricsAuth(context) : await _showQrCodeBottomSheet(context); }, diff --git a/lib/pages/reception_page/reception_page_model.dart b/lib/pages/reception_page/reception_page_model.dart index 47dc15a9..93bd6ae6 100644 --- a/lib/pages/reception_page/reception_page_model.dart +++ b/lib/pages/reception_page/reception_page_model.dart @@ -1,16 +1,21 @@ import 'package:flutter/material.dart'; import 'package:hub/app_state.dart'; import 'package:hub/flutter_flow/internationalization.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:share_plus/share_plus.dart'; class ReceptionPageModel with ChangeNotifier { - void getIdenfifier(BuildContext context) { + Future getIdenfifier(BuildContext context) async { + final DatabaseHelper db = DatabaseHelper(); + final String userDevUUID = await db + .get(key: 'userDevUUID', field: 'value') + .then((value) => value.toString()); + notifyListeners(); Share.share( FFLocalizations.of(context).getVariableText( - ptText: - 'Este é o meu identificador de acesso: ${AppState().userDevUUID}', - enText: 'This is my access identifier: ${AppState().userDevUUID}', + ptText: 'Este é o meu identificador de acesso: ${userDevUUID}', + enText: 'This is my access identifier: ${userDevUUID}', ), ); } diff --git a/lib/pages/reception_page/reception_page_widget.dart b/lib/pages/reception_page/reception_page_widget.dart index b4c40118..aa0cc481 100644 --- a/lib/pages/reception_page/reception_page_widget.dart +++ b/lib/pages/reception_page/reception_page_widget.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; +import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/atomic_components/shared_components_atoms/atom_image_svg_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; @@ -141,6 +142,7 @@ class _ReceptionPageWidgetState extends State { padding: const EdgeInsets.fromLTRB(60, 0, 60, 0), child: FFButtonWidget( onPressed: () async { + PhpGroup.unregisterDevice(); AppState().deleteAll(); setState(() {}); diff --git a/lib/pages/reservation_page/reservation_page_widget.dart b/lib/pages/reservation_page/reservation_page_widget.dart index 3a631a51..ea7f37fb 100644 --- a/lib/pages/reservation_page/reservation_page_widget.dart +++ b/lib/pages/reservation_page/reservation_page_widget.dart @@ -5,124 +5,163 @@ import 'package:flutter/scheduler.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:hub/app_state.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/webview_util.dart'; +import 'package:sqflite/sqflite.dart'; import 'package:url_launcher/url_launcher_string.dart'; import 'package:webview_flutter/webview_flutter.dart'; class ReservationPageWidget extends StatefulWidget { - final String freToken = AppState().userUUID; - final String freUserData = "{\"name\": \"${AppState().name}\", " + - "\"email\": \"${AppState().email}\"," + - "\"dev_id\": \"${AppState().devUUID}\"," + - "\"created_at\": \"${AppState().createdAt}\"," + - "\"updated_at\": \"0000-00-00 00:00:00\"," + - "\"status\": \"A\" }"; - - final String clientId = AppState().cliUUID; - @override _ReservationPageWidgetState createState() => _ReservationPageWidgetState(); } class _ReservationPageWidgetState extends State { + final DatabaseHelper db = DatabaseHelper(); late InAppWebViewController _controllerIOS; late WebViewController _controllerAll; - late String url; - late String name; - late String email; - late String userUUID; - late String created_at; - @override - void initState() { - super.initState(); - name = AppState().name; - email = AppState().email; - userUUID = AppState().userUUID; - created_at = AppState().createdAt; - url = 'https://hub.freaccess.com.br/hub/reservation/${widget.clientId}'; + Future> initVariables() async { + final email = await db + .get(key: 'email', field: 'value') + .then((value) => value.toString()); + final name = await db + .get(key: 'userName', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final createdAt = await db + .get(key: 'devUUID', field: 'createdAt') + .then((value) => value.toString()); + final clientId = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + + final url = 'https://hub.freaccess.com.br/hub/reservation/$clientId'; + + final freUserData = "{\"name\": \"$name\", " + + "\"email\": \"$email\"," + + "\"dev_id\": \"$devUUID\"," + + "\"created_at\": \"$createdAt\"," + + "\"updated_at\": \"0000-00-00 00:00:00\"," + + "\"status\": \"A\" }"; + + return { + 'url': url, + 'name': name, + 'email': email, + 'userUUID': userUUID, + 'devUUID': devUUID, + 'createdAt': createdAt, + 'clientId': clientId, + 'freUserData': freUserData, + }; } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( - body: Platform.isIOS - ? InAppWebView( - initialUrlRequest: URLRequest(url: WebUri(url)), - initialSettings: InAppWebViewSettings( - allowsBackForwardNavigationGestures: true, - javaScriptEnabled: true, - ), - onWebViewCreated: (controller) async { - _controllerIOS = controller; - }, - onLoadStop: (controller, url) async { - await controller.evaluateJavascript( - source: - "window.localStorage.setItem('fre-token', '\"${widget.freToken}\"')"); - await controller.evaluateJavascript( - source: - "window.localStorage.setItem('fre-user-data', '${widget.freUserData}')"); - await controller.evaluateJavascript( - source: - "window.localStorage.setItem('enableBackButton', 'true')"); - }, - onUpdateVisitedHistory: (controller, uri, isVisited) { - if (uri.toString().contains('/hub/home')) { - context.pop(); - } - }, - ) - : WebViewWidget( - controller: _controllerAll = WebViewController() - ..clearCache() - ..clearLocalStorage() - ..setJavaScriptMode(JavaScriptMode.unrestricted) - ..setBackgroundColor(const Color(0x00000000)) - ..setNavigationDelegate( - NavigationDelegate( - onProgress: (int progress) {}, - onPageStarted: (String url) { - final String token = - "localStorage.setItem('fre-token', '\"${widget.freToken}\"');"; - final String data = - "localStorage.setItem('fre-user-data', '${widget.freUserData}');"; - const String backNavigation = - "localStorage.setItem('enableBackButton', 'true');"; + body: FutureBuilder>( + future: initVariables(), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return Center(child: CircularProgressIndicator()); + } else if (snapshot.hasError) { + return Center(child: Text('Error: ${snapshot.error}')); + } else if (snapshot.hasData) { + final data = snapshot.data!; + final url = data['url']!; + final userUUID = data['userUUID']!; + final freUserData = data['freUserData']!; - _controllerAll.runJavaScript(token); - _controllerAll.runJavaScript(data); - _controllerAll.runJavaScript(backNavigation); - }, - onPageFinished: (String url) { - bool isDarkMode = SchedulerBinding.instance - .platformDispatcher.platformBrightness == - Brightness.dark; + return Platform.isIOS + ? InAppWebView( + initialUrlRequest: URLRequest(url: WebUri(url)), + initialSettings: InAppWebViewSettings( + allowsBackForwardNavigationGestures: true, + javaScriptEnabled: true, + ), + onWebViewCreated: (controller) async { + _controllerIOS = controller; + }, + onLoadStop: (controller, url) async { + await controller.evaluateJavascript( + source: + "window.localStorage.setItem('fre-token', '\"$userUUID\"')"); + await controller.evaluateJavascript( + source: + "window.localStorage.setItem('fre-user-data', '$freUserData')"); + await controller.evaluateJavascript( + source: + "window.localStorage.setItem('enableBackButton', 'true')"); + }, + onUpdateVisitedHistory: (controller, uri, isVisited) { + if (uri.toString().contains('/hub/home')) { + context.pop(); + } + }, + ) + : WebViewWidget( + controller: _controllerAll = WebViewController() + ..clearCache() + ..clearLocalStorage() + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setBackgroundColor(const Color(0x00000000)) + ..setNavigationDelegate( + NavigationDelegate( + onProgress: (int progress) {}, + onPageStarted: (String url) { + final String token = + "localStorage.setItem('fre-token', '\"$userUUID\"');"; + final String data = + "localStorage.setItem('fre-user-data', '$freUserData');"; + const String backNavigation = + "localStorage.setItem('enableBackButton', 'true');"; - if (isDarkMode) { - _controllerAll - .runJavaScript(WebviewUtil.jsEnableDarkMode); - } - }, - onNavigationRequest: (NavigationRequest request) { - if (request.url.startsWith('http') || - request.url.startsWith( - 'https://api.whatsapp.com/send') || - request.url.startsWith('https://wa.me')) { - launchUrlString(request.url); - return NavigationDecision.prevent; - } - return NavigationDecision.prevent; - }, - onUrlChange: (url) { - if (url.url.toString().contains('/hub/home')) { - context.pop(); - } - }), - ) - ..loadRequest(Uri.parse(url)), - ), + _controllerAll.runJavaScript(token); + _controllerAll.runJavaScript(data); + _controllerAll.runJavaScript(backNavigation); + }, + onPageFinished: (String url) { + bool isDarkMode = SchedulerBinding + .instance + .platformDispatcher + .platformBrightness == + Brightness.dark; + + if (isDarkMode) { + _controllerAll.runJavaScript( + WebviewUtil.jsEnableDarkMode); + } + }, + onNavigationRequest: (NavigationRequest request) { + if (request.url.startsWith('http') || + request.url.startsWith( + 'https://api.whatsapp.com/send') || + request.url.startsWith('https://wa.me')) { + launchUrlString(request.url); + return NavigationDecision.prevent; + } + return NavigationDecision.prevent; + }, + onUrlChange: (url) { + if (url.url.toString().contains('/hub/home')) { + context.pop(); + } + }), + ) + ..loadRequest(Uri.parse(url)), + ); + } else { + return Center(child: Text('Unexpected error')); + } + }, + ), ), ); } diff --git a/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart b/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart index f41a44f8..914aee21 100644 --- a/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart +++ b/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart @@ -9,11 +9,17 @@ import 'package:hub/flutter_flow/request_manager.dart'; import 'package:flutter/material.dart'; import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:intl/intl.dart'; class ScheduleCompleteVisitPageModel extends FlutterFlowModel { final _visitHistoryManager = FutureRequestManager(); + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String cliUUID; + late final String userUUID; + Future visitHistory({ String? uniqueQueryKey, bool? overrideCache, @@ -187,8 +193,21 @@ class ScheduleCompleteVisitPageModel return null; } + Future _initVariables() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + } + @override void initState(BuildContext context) { + _initVariables(); tabBarController = TabController( vsync: Navigator.of(context), length: 2, diff --git a/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart b/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart index 0f56c366..9e0ae402 100644 --- a/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart +++ b/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart @@ -868,7 +868,7 @@ Widget scheduleVisit(BuildContext context, fadeOutDuration: const Duration(milliseconds: 500), imageUrl: - "https://freaccess.com.br/freaccess/getImage.php?devUUID=${AppState().devUUID}&userUUID=${AppState().userUUID}&cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${getJsonField(visitorListViewItem, r'''$.VTE_DOCUMENTO''').toString()}&tipo=E", + "https://freaccess.com.br/freaccess/getImage.php?devUUID=${_model.devUUID}&userUUID=${_model.userUUID}&cliID=${_model.cliUUID}&atividade=getFoto&Documento=${getJsonField(visitorListViewItem, r'''$.VTE_DOCUMENTO''').toString()}&tipo=E", fit: BoxFit.cover, ), ), @@ -1081,12 +1081,7 @@ Widget scheduleVisit(BuildContext context, height: 45.0, decoration: const BoxDecoration(), child: FutureBuilder( - future: PhpGroup.getDadosCall.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliUUID: AppState().cliUUID, - atividade: 'getDados', - ), + future: PhpGroup.getDadosCall.call(), builder: (context, snapshot) { if (!snapshot.hasData) { return Center( @@ -1232,12 +1227,7 @@ Widget scheduleVisit(BuildContext context, height: 45.0, decoration: const BoxDecoration(), child: FutureBuilder( - future: PhpGroup.getDadosCall.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliUUID: AppState().cliUUID, - atividade: 'getDados', - ), + future: PhpGroup.getDadosCall.call(), builder: (context, snapshot) { // Customize what your widget looks like when it's loading. if (!snapshot.hasData) { @@ -1612,9 +1602,6 @@ Widget scheduleVisit(BuildContext context, Future scheduleVisit() async { await PhpGroup.postScheduleVisitCall .call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - atividade: 'putVisita', devDesc: _model.textController3.text, idVisitante: _model.visitorStrList, dtInicio: _model @@ -1625,7 +1612,6 @@ Widget scheduleVisit(BuildContext context, idMotivo: extractIdToStr(_model.dropDownValue1!), idNAC: extractIdToStr(_model.dropDownValue2!), obs: _model.textController3.text, - cliID: AppState().cliUUID, ) .catchError((e) async { await DialogUtil.errorDefault(context); @@ -1719,7 +1705,7 @@ Widget scheduleVisit(BuildContext context, ), ], imagePath: - 'https://freaccess.com.br/freaccess/getImage.php?cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${_model.visitorJsonList[0]['VTE_DOCUMENTO'] ?? ''}&tipo=E', + 'https://freaccess.com.br/freaccess/getImage.php?cliID=${_model.cliUUID}&atividade=getFoto&Documento=${_model.visitorJsonList[0]['VTE_DOCUMENTO'] ?? ''}&tipo=E', labelsHashMap: { 'Nome': _model.visitorJsonList[0]['VTE_NOME'], 'Start': _model.textController1.text, diff --git a/lib/pages/visit_history_page/visit_history_page_widget.dart b/lib/pages/visit_history_page/visit_history_page_widget.dart index 94e39606..45072dfb 100644 --- a/lib/pages/visit_history_page/visit_history_page_widget.dart +++ b/lib/pages/visit_history_page/visit_history_page_widget.dart @@ -6,6 +6,7 @@ import 'package:hub/components/templates_components/details_component/details_co import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/validator_util.dart'; @@ -19,6 +20,10 @@ class VisitHistoryWidget extends StatefulWidget { class _VisitHistoryWidgetState extends State with TickerProviderStateMixin { + final DatabaseHelper db = DatabaseHelper(); + late final String devUUID; + late final String userUUID; + late final String cliUUID; late ScrollController _scrollController; int _pageNumber = 1; final int _pageSize = 10; @@ -28,9 +33,22 @@ class _VisitHistoryWidgetState extends State late Future _visitFuture; List _visitWrap = []; + Future _initVariables() async { + devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); + cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + } + @override void initState() { super.initState(); + _initVariables(); _visitFuture = _fetchVisits(); _scrollController = ScrollController() @@ -54,10 +72,6 @@ class _VisitHistoryWidgetState extends State var response = await ScheduleCompleteVisitPageModel().visitHistory( requestFn: () => PhpGroup.getVisitsCall.call( - devUUID: AppState().devUUID, - userUUID: AppState().userUUID, - cliID: AppState().cliUUID, - atividade: 'getVisitas', pageSize: _pageSize, pageNumber: _pageNumber, ), @@ -168,7 +182,7 @@ class _VisitHistoryWidgetState extends State Widget _item(BuildContext context, dynamic visitaWrapItem) { return CardItemTemplateComponentWidget( imagePath: - 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${AppState().devUUID}&userUUID=${AppState().userUUID}&cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${visitaWrapItem['VTE_DOCUMENTO'] ?? ''}&tipo=E', + 'https://freaccess.com.br/freaccess/getImage.php?devUUID=$devUUID&userUUID=$userUUID&cliID=$cliUUID&atividade=getFoto&Documento=${visitaWrapItem['VTE_DOCUMENTO'] ?? ''}&tipo=E', labelsHashMap: { '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:': visitaWrapItem['VTE_NOME'] ?? '', @@ -230,6 +244,19 @@ class _VisitHistoryWidgetState extends State }, ], onTapCardItemAction: () async { + final DatabaseHelper db = DatabaseHelper(); + final cliUUID = await db + .get(key: 'cliUUID', field: 'value') + .then((value) => value.toString()); + final cliName = await db + .get(key: 'cliName', field: 'value') + .then((value) => value.toString()); + final devUUID = await db + .get(key: 'devUUID', field: 'value') + .then((value) => value.toString()); + final userUUID = await db + .get(key: 'userUUID', field: 'value') + .then((value) => value.toString()); await showDialog( useSafeArea: true, context: context, @@ -237,9 +264,13 @@ class _VisitHistoryWidgetState extends State return Dialog( alignment: Alignment.center, child: buildVisitDetails( - visitaWrapItem, - context, - changeStatusAction, + item: visitaWrapItem, + context: context, + changeStatusAction: changeStatusAction, + devUUID: devUUID, + userUUID: userUUID, + cliUUID: cliUUID, + cliName: cliName, ), ); }, diff --git a/lib/pages/welcome_page/welcome_page_widget.dart b/lib/pages/welcome_page/welcome_page_widget.dart index b0c8af92..9df3c31b 100644 --- a/lib/pages/welcome_page/welcome_page_widget.dart +++ b/lib/pages/welcome_page/welcome_page_widget.dart @@ -28,13 +28,13 @@ class _WelcomePageWidgetState extends State { // On page load action. SchedulerBinding.instance.addPostFrameCallback((_) async { if (isAndroid == true) { - AppState().device = 'Android'; + AppState().deviceType = 'Android'; setState(() {}); } else if (isiOS == true) { - AppState().device = 'iOS'; + AppState().deviceType = 'iOS'; setState(() {}); } else { - AppState().device = 'Web'; + AppState().deviceType = 'Web'; setState(() {}); } }); diff --git a/lib/shared/helpers/db_helper.dart b/lib/shared/helpers/db_helper.dart index 7fa8c0a9..055cadbb 100644 --- a/lib/shared/helpers/db_helper.dart +++ b/lib/shared/helpers/db_helper.dart @@ -19,6 +19,22 @@ class DatabaseHelper { return _database!; } + Future _onUpgrade(Database db, int oldVersion, int newVersion) async { + log('Upgrading database from version $oldVersion to $newVersion'); + + // if (oldVersion < 2) { + // // await db.execute('ALTER TABLE keychain ADD COLUMN newColumn TEXT'); + // } + } + + Future _onDowngrade(Database db, int oldVersion, int newVersion) async { + log('Downgrading database from version $oldVersion to $newVersion'); + } + + Future _onConfigure(Database db) async { + log('Configuring database...'); + } + Future _initDatabase() async { final path = await _getDatabasePath(); log('Database path: $path'); @@ -27,6 +43,9 @@ class DatabaseHelper { version: 1, onCreate: _onCreate, onOpen: _onOpen, + onUpgrade: _onUpgrade, + onDowngrade: _onDowngrade, + onConfigure: _onConfigure, ).catchError((error) { throw error; }).whenComplete(() => log('Database initialized')); @@ -45,23 +64,29 @@ class DatabaseHelper { createdAt TEXT ); '''); - - insert('email', '', 'user'); - insert('passwd', '', 'user'); - insert('devUUID', '', 'user'); - insert('userUUID', '', 'user'); - insert('userDevUUID', '', 'user'); - insert('status', '', 'user'); - - insert('cliUUID', '', 'local'); - insert('ownerUUID', '', 'local'); - insert('cliName', '', 'local'); - - insert('whatsapp', '', 'local'); - insert('provisional', '', 'local'); - insert('pets', '', 'local'); - insert('petAmountRegister', '', 'local'); - +// ---------------------------------------------- + await insert('devUUID', '', 'user'); + await insert('userUUID', '', 'user'); + await insert('userDevUUID', '', 'user'); + await insert('status', '', 'user'); + await insert('userName', '', 'user'); +// ---------------------------------------------- + await insert('cliUUID', '', 'local'); + await insert('ownerUUID', '', 'local'); + await insert('cliName', '', 'local'); +// ---------------------------------------------- + await insert('whatsapp', 'false', 'util'); + await insert('provisional', 'false', 'util'); + await insert('pets', 'false', 'util'); + await insert('local', 'false', 'util'); + await insert('notify', 'false', 'util'); + await insert('fingerprint', 'false', 'util'); + await insert('access', 'false', 'util'); + await insert('panic', 'false', 'util'); + await insert('person', 'false', 'util'); + await insert('requestOSnotification', 'false', 'util'); + await insert('petAmountRegister', '', 'local'); +// ---------------------------------------------- log('Tables created'); } @@ -173,15 +198,36 @@ class DatabaseHelper { ); } - Future delete(int id) async { + Future clear(String key) async { final db = await database; - log('Deleting with id: $id'); - return await db.delete('keychain', where: 'id = ?', whereArgs: [id]); + + log('Setting value of key: $key to empty string'); + return await db.update( + 'keychain', + {'value': ''}, + where: 'key = ?', + whereArgs: [key], + ); } - Future purge() async { + Future delete(String key) async { final db = await database; - log('Deleting all'); - return await db.delete('keychain'); + + log('Deleting key: $key'); + return await db.delete( + 'keychain', + where: 'key = ?', + whereArgs: [key], + ); + } + + Future purge() async { + final DatabaseHelper helper = DatabaseHelper(); + + await helper.deleteDatabaseDB(); + await helper.database; + await database; + + log('Purge'); } } diff --git a/lib/shared/widgets/drawer_widget/drawer_widget.dart b/lib/shared/widgets/drawer_widget/drawer_widget.dart index eff34735..0a4ad55a 100644 --- a/lib/shared/widgets/drawer_widget/drawer_widget.dart +++ b/lib/shared/widgets/drawer_widget/drawer_widget.dart @@ -58,7 +58,7 @@ class CustomDrawer extends StatelessWidget { child: CachedNetworkImage( imageUrl: valueOrDefault( 'assets/images/person.jpg', - 'https://freaccess.com.br/freaccess/Images/Clients/${AppState().cliUUID}.png', + 'https://freaccess.com.br/freaccess/Images/Clients/${model.cliUUID}.png', ), width: 80.0, height: 80.0, @@ -79,7 +79,7 @@ class CustomDrawer extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - convertToUppercase(AppState().name) ?? '', + convertToUppercase(model.userName) ?? '', style: FlutterFlowTheme.of(context).bodyLarge.override( fontFamily: 'Nunito Sans', color: FlutterFlowTheme.of(context).primaryText, @@ -89,7 +89,7 @@ class CustomDrawer extends StatelessWidget { ), ), Text( - AppState().email, + model.userEmail, style: FlutterFlowTheme.of(context).bodySmall.override( fontFamily: 'Nunito Sans', color: FlutterFlowTheme.of(context).primaryText,