Merge pull request #40 from FRE-Informatica/fix/fd-392

Fix/fd 392 - Implementar mecanismo de cache com SQLite no aplicativo
This commit is contained in:
Jônatas Antunes Messias 2024-09-23 14:04:21 -03:00 committed by GitHub
commit 5031565ec9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
64 changed files with 2176 additions and 2588 deletions

View File

@ -9,6 +9,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_util.dart';
import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/flutter_flow/random_data_util.dart'; import 'package:hub/flutter_flow/random_data_util.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/dialog_util.dart';
import 'package:qr_flutter/qr_flutter.dart'; import 'package:qr_flutter/qr_flutter.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
@ -65,80 +66,69 @@ Future<Color> manageStatusColorAction(
return FlutterFlowTheme.of(context).warning; return FlutterFlowTheme.of(context).warning;
} }
Future singInLoginAction( Future signInLoginAction(
BuildContext context, BuildContext context,
FlutterFlowModel model, { FlutterFlowModel model, {
String? emailAdress, String? emailAdress,
String? password, String? password,
}) async { }) async {
try { try {
String? devUUID; final ApiCallResponse? response;
ApiCallResponse? loginCall; final DatabaseHelper db = DatabaseHelper();
final LoginCall callback = PhpGroup.loginCall;
await Future.wait([ AppState().deviceDescription = randomString(
Future(() async {
AppState().email = emailAdress!;
}),
Future(() async {
AppState().passwd = password!;
}),
]);
if ((AppState().email != '') && (AppState().passwd != '')) {
devUUID = await getDevUUID();
AppState().devUUID = devUUID!;
loginCall = await PhpGroup.loginCall.call(
email: AppState().email,
password: AppState().passwd,
uuid: AppState().devUUID,
type: AppState().device,
description: randomString(
10, 10,
10, 10,
true, true,
false, false,
false, false,
),
); );
if (PhpGroup.loginCall.error((loginCall.jsonBody ?? '')) == false) { final String? devUUID;
AppState().userUUID = PhpGroup.loginCall.userUUID( final String userUUID;
(loginCall.jsonBody ?? ''), final String status;
)!; final String userDevUUID;
AppState().createdAt = dateTimeFormat( final String userName;
'd/M/y H:mm:ss', final String email;
getCurrentTimestamp, final String passwd;
locale: FFLocalizations.of(context).languageCode, final bool isLogged;
);
AppState().updatedAt = '00/00/0000 00:00:00';
AppState().status =
PhpGroup.loginCall.userStatus((loginCall.jsonBody ?? ''))!;
AppState().userDevUUID =
PhpGroup.loginCall.userDeviceId((loginCall.jsonBody ?? ''))!;
PhpGroup.loginCall.userName((loginCall.jsonBody ?? ''))!;
AppState().serialNumber = await getSerialNumber() ?? '';
AppState().isLogged = true;
AppState().haveLocal = email = emailAdress!;
await checkLocals(context: context, model: model); passwd = password!;
toggleApp(context, AppState().haveLocal!);
devUUID = await getDevUUID();
if ((email != '') && (passwd != '')) {
AppState().email = email;
AppState().passwd = passwd;
response = await callback.call();
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('devUUID', devUUID, 'user');
db.update('userUUID', userUUID, 'user');
db.update('userDevUUID', userDevUUID, 'user');
db.update('status', status, 'user');
db.update('userName', userName, 'user');
isLogged = true;
await checkLocals(context: context, model: model).then((value) {
AppState().haveLocal = value;
AppState().isLogged = isLogged;
AppState().update(() {});
toggleApp(context);
});
} else { } else {
if (PhpGroup.loginCall.msg((loginCall?.jsonBody ?? '')) == null) { if (response.jsonBody['error'] == null) {
DialogUtil.errorDefault(context); DialogUtil.errorDefault(context);
} else { } else {
DialogUtil.error(context, DialogUtil.error(context, response.jsonBody['error_msg'].toString());
PhpGroup.loginCall.msg((loginCall?.jsonBody ?? '')).toString());
} }
AppState().deleteEmail();
AppState().email = '';
AppState().deletePasswd();
AppState().passwd = '';
AppState().update(() {});
} }
} }
@ -158,11 +148,12 @@ Future<bool> signUpRegisterAction(
String? device, String? device,
}) async { }) async {
try { try {
ApiCallResponse? registerCall; ApiCallResponse? response;
if ((email != null && email != '') && if ((email != null && email != '') &&
(passwd != null && passwd != '' && passwd.length > 7) && (passwd != null && passwd != '' && passwd.length > 7) &&
(name != null && name != '')) { (name != null && name != '')) {
registerCall = await PhpGroup.registerCall.call( response = await PhpGroup.registerCall.call(
name: name, name: name,
password: passwd, password: passwd,
email: email, email: email,
@ -190,14 +181,10 @@ Future<bool> signUpRegisterAction(
), ),
); );
if (PhpGroup.registerCall.error( if (response.jsonBody['error'] == false) {
(registerCall.jsonBody ?? ''),
) ==
false) {
return true; return true;
} }
final errorMessage = registerCall?.jsonBody['error_msg']; DialogUtil.error(context, response.jsonBody['error_msg']);
DialogUtil.error(context, errorMessage);
return false; return false;
} else { } else {
DialogUtil.errorDefault(context); DialogUtil.errorDefault(context);
@ -215,16 +202,14 @@ Future forgotPasswdAction(
BuildContext context, { BuildContext context, {
required String? email, required String? email,
}) async { }) async {
ApiCallResponse? forgotPasswd; ApiCallResponse? response;
ForgotPasswordCall callback = PhpGroup.forgotPasswordCall;
forgotPasswd = await PhpGroup.forgotPasswordCall.call( response = await PhpGroup.forgotPasswordCall.call(
email: email, email: email,
); );
if (PhpGroup.forgotPasswordCall.error( if (response.jsonBody['error'] != false) {
(forgotPasswd.jsonBody ?? ''),
) !=
false) {
return; return;
} }
} }
@ -253,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) { if (haveLocal == true) {
context.go('/homePage'); context.go('/homePage');
} else if (haveLocal == false) { } else if (haveLocal == false) {
@ -274,13 +260,10 @@ Future<bool> visitCancelAction(BuildContext context,
required int? idVisita, required int? idVisita,
required String? accessKey, required String? accessKey,
required String? email}) async { required String? email}) async {
ApiCallResponse? apiCallResponse; final ApiCallResponse? response;
final CancelaVisita callback = PhpGroup.cancelaVisita;
apiCallResponse = await PhpGroup.cancelaVisita.call( response = await callback.call(
userUUID: AppState().userUUID,
devUUID: AppState().devUUID,
cliID: AppState().cliUUID,
atividade: 'cancelaVisita',
idDestino: idDestino, idDestino: idDestino,
idVisita: idVisita, idVisita: idVisita,
AccessKey: accessKey, AccessKey: accessKey,
@ -288,8 +271,8 @@ Future<bool> visitCancelAction(BuildContext context,
DevDesc: '', DevDesc: '',
); );
if (apiCallResponse.statusCode == 200) { if (response.statusCode == 200) {
return !apiCallResponse.jsonBody['error']; return !response.jsonBody['error'];
} else { } else {
return false; return false;
} }
@ -327,12 +310,10 @@ Future<bool> checkLocals({
required BuildContext context, required BuildContext context,
required FlutterFlowModel model, required FlutterFlowModel model,
}) async { }) async {
final response = await PhpGroup.getLocalsCall.call( final GetLocalsCall callback = PhpGroup.getLocalsCall;
devUUID: AppState().devUUID,
userUUID: AppState().userUUID, final response = await callback.call();
);
// Verificação rápida de erro para evitar processamento desnecessário.
if (response.jsonBody['error']) { if (response.jsonBody['error']) {
DialogUtil.errorDefault(context); DialogUtil.errorDefault(context);
return false; return false;
@ -347,15 +328,23 @@ Future<bool> checkLocals({
} }
Future<void> showShare(payload) async { Future<void> showShare(payload) async {
final DatabaseHelper db = DatabaseHelper();
final cliName = await db
.get(key: 'cliName', field: 'value')
.then((value) => value.toString());
final cliUUID = await db
.get(key: 'cliUUID', field: 'value')
.then((value) => value.toString());
for (var i = 0; i < payload['convites'].length; i++) { for (var i = 0; i < payload['convites'].length; i++) {
await Share.share(''' await Share.share('''
Olá, \*${payload['convites'][i]['VTE_NOME']}\*! Você foi convidado para \*${AppState().local}\*. Olá, \*${payload['convites'][i]['VTE_NOME']}\*! Você foi convidado para \*$cliName\*.
\*Validade do Convite\*: \*Validade do Convite\*:
- Início: ${payload['convites'][i]['VAW_DTINICIO']} - Início: ${payload['convites'][i]['VAW_DTINICIO']}
- Fim: ${payload['convites'][i]['VAW_DTFIM']} - Fim: ${payload['convites'][i]['VAW_DTFIM']}
URL do Convite: https://visita.freaccess.com.br/${payload['convites'][i]['VAW_ID']}/${AppState().cliUUID}/${payload['convites'][i]['VAW_CHAVE']} URL do Convite: https://visita.freaccess.com.br/${payload['convites'][i]['VAW_ID']}/$cliUUID/${payload['convites'][i]['VAW_CHAVE']}
'''); ''');
} }
} }
@ -366,13 +355,10 @@ Future answersRequest(
required String? task, required String? task,
required String? response, required String? response,
required String? id}) async { required String? id}) async {
ApiCallResponse? respondeSolicitacaoCall; final ApiCallResponse? respondeSolicitacaoCall;
final RespondeSolicitacaoCall callback = PhpGroup.respondeSolicitacaoCall;
respondeSolicitacaoCall = await PhpGroup.respondeSolicitacaoCall.call( respondeSolicitacaoCall = await callback.call(
userUUID: AppState().userUUID,
devUUID: AppState().devUUID,
cliUUID: AppState().cliUUID,
atividade: 'respondeSolicitacao',
referencia: ref, referencia: ref,
tarefa: task, tarefa: task,
resposta: response, resposta: response,
@ -510,59 +496,6 @@ Widget buildQrCode(
} }
} }
// // Retorna o conteúdo a ser codificado no QR Code.
// String getContents() {
// return data;
// }
// // Retorna uma versão do conteúdo otimizada para exibição.
// String getDisplayContents() {
// return data.trim();
// }
// // Retorna o título baseado no tipo de conteúdo.
// String getTitle() {
// return type;
// }
// // Codifica o conteúdo em uma string adequada para o QR Code.
// Future<String> encodeContents() async {
// // Implementação específica para codificar o conteúdo.
// return data; // Exemplo simplificado.
// }
// // Codifica o conteúdo específico do QR Code.
// Future<Widget> encodeQRCodeContents() async {
// return getQrCode();
// }
// // Gera o QR Code como um widget.
// // Codifica o conteúdo como um bitmap (pode ser útil para operações de baixo nível).
// // Future<Image> encodeAsBitmap() async {
// // // Implementação para codificar como bitmap.
// // return Image(image); // Exemplo simplificado.
// // }
// // Adivinha a codificação apropriada para o conteúdo.
// String guessAppropriateEncoding(String content) {
// // Implementação para adivinhar a codificação.
// return "UTF-8"; // Exemplo simplificado.
// }
// // Remove espaços em branco do início e do fim do conteúdo.
// String trim(String content) {
// return content.trim();
// }
// // Escapa caracteres especiais para o formato MECARD.
// String escapeMECARD(String content) {
// // Implementação para escapar caracteres.
// return content.replaceAll(':', '\\:'); // Exemplo simplificado.
// }
/// menu
Future scheduleVisitOptAction(BuildContext context) async { Future scheduleVisitOptAction(BuildContext context) async {
await showAdaptiveDialog( await showAdaptiveDialog(
context: context, context: context,

View File

@ -73,20 +73,6 @@ class AppState extends ChangeNotifier {
Future initializePersistedState() async { Future initializePersistedState() async {
secureStorage = const FlutterSecureStorage(); 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 { await _safeInitAsync(() async {
_email = await secureStorage.getString('ff_email') ?? _email; _email = await secureStorage.getString('ff_email') ?? _email;
}); });
@ -94,56 +80,17 @@ class AppState extends ChangeNotifier {
_passwd = await secureStorage.getString('ff_passwd') ?? _passwd; _passwd = await secureStorage.getString('ff_passwd') ?? _passwd;
}); });
await _safeInitAsync(() async { await _safeInitAsync(() async {
_device = await secureStorage.getString('ff_device') ?? _device; _deviceType =
await secureStorage.getString('ff_deviceType') ?? _deviceType;
}); });
await _safeInitAsync(() async { await _safeInitAsync(() async {
_isLogged = await secureStorage.getBool('ff_isLogged') ?? _isLogged; _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 { await _safeInitAsync(() async {
_tokenAPNS = await secureStorage.getString('ff_tokenAPNS') ?? _tokenAPNS; _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 { await _safeInitAsync(() async {
_accessPass = await secureStorage.getString('accessPass') ?? _accessPass; _accessPass = await secureStorage.getString('accessPass') ?? _accessPass;
}); });
@ -157,38 +104,18 @@ class AppState extends ChangeNotifier {
await _safeInitAsync(() async { await _safeInitAsync(() async {
_context = await secureStorage.getObject('ff_context') ?? _context; _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 { await _safeInitAsync(() async {
_haveLocal = await secureStorage.getBool('ff_have_local') ?? _haveLocal; _haveLocal = await secureStorage.getBool('ff_have_local') ?? _haveLocal;
}); });
await _safeInitAsync(() async {
_petAmountRegister =
await secureStorage.getInt('petAmountRegister') ?? _petAmountRegister;
});
await _safeInitAsync(() async { await _safeInitAsync(() async {
_isRequestOSNotification = _deviceDescription = await secureStorage.getString('deviceDescription') ??
await secureStorage.getBool('ff_request_os_notification') ?? _deviceDescription;
_isRequestOSNotification;
}); });
await loadFirstRun(); await loadFirstRun();
} }
void update(VoidCallback callback) {
callback();
notifyListeners();
}
late FlutterSecureStorage secureStorage;
bool _firstRun = true; bool _firstRun = true;
bool get firstRun => _firstRun; bool get firstRun => _firstRun;
@ -212,60 +139,22 @@ class AppState extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
int _petAmountRegister = 0; void update(VoidCallback callback) {
int get petAmountRegister => _petAmountRegister; callback();
set petAmountRegister(int value) { notifyListeners();
_petAmountRegister = value;
secureStorage.setInt('petAmountRegister', value);
} }
void deletePetAmountRegister() { late FlutterSecureStorage secureStorage;
secureStorage.delete(key: 'petAmountRegister');
String _deviceDescription = '';
String get deviceDescription => _deviceDescription;
set deviceDescription(String value) {
_deviceDescription = value;
secureStorage.setString('deviceDescription', value);
} }
bool _isRequestOSNotification = false; void deleteDeviceDescription() {
bool get isRequestOSNotification => _isRequestOSNotification; secureStorage.delete(key: 'deviceDescription');
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');
} }
BuildContext? _context; BuildContext? _context;
@ -279,17 +168,6 @@ class AppState extends ChangeNotifier {
secureStorage.delete(key: 'ff_context'); 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? _haveLocal = null;
bool? get haveLocal => _haveLocal; bool? get haveLocal => _haveLocal;
set haveLocal(bool? value) { set haveLocal(bool? value) {
@ -334,88 +212,11 @@ class AppState extends ChangeNotifier {
secureStorage.delete(key: 'panicPass'); 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? _tokenAPNS = '';
String? get tokenAPNS => _tokenAPNS; String? get tokenAPNS => _tokenAPNS;
set tokenAPNS(String? value) { set tokenAPNS(String? value) {
_tokenAPNS = value; _tokenAPNS = value;
// Verifica se o valor é nulo antes de tentar salvar no secureStorage
if (value != null) { if (value != null) {
secureStorage.setString('ff_tokenAPNS', value); secureStorage.setString('ff_tokenAPNS', value);
} else { } else {
@ -428,42 +229,6 @@ class AppState extends ChangeNotifier {
AppState().tokenAPNS = ''; 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 _email = '';
String get email => _email; String get email => _email;
set email(String value) { set email(String value) {
@ -488,16 +253,16 @@ class AppState extends ChangeNotifier {
AppState().passwd = ''; AppState().passwd = '';
} }
String _device = ''; String _deviceType = '';
String get device => _device; String get deviceType => _deviceType;
set device(String value) { set deviceType(String value) {
_device = value; _deviceType = value;
secureStorage.setString('ff_device', value); secureStorage.setString('ff_deviceType', value);
} }
void deleteDevice() { void deleteDevice() {
secureStorage.delete(key: 'ff_device'); secureStorage.delete(key: 'ff_deviceType');
AppState().device = ''; AppState().deviceType = '';
} }
bool _isLogged = false; bool _isLogged = false;
@ -511,18 +276,6 @@ class AppState extends ChangeNotifier {
secureStorage.delete(key: 'ff_isLogged'); 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 _token = '';
String get token => _token; String get token => _token;
set token(String value) { set token(String value) {
@ -535,82 +288,17 @@ class AppState extends ChangeNotifier {
AppState().token = ''; 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() { void deleteAll() {
AppState().deleteAccessPass(); AppState().deleteAccessPass();
AppState().deleteCliUUID();
AppState().deleteCreatedAt();
AppState().deleteDevUUID();
AppState().deleteDevice(); AppState().deleteDevice();
AppState().deleteEmail(); AppState().deleteEmail();
AppState().deleteFingerprint();
AppState().deleteFingerprintPass(); AppState().deleteFingerprintPass();
AppState().deleteIsLogged(); AppState().deleteIsLogged();
AppState().deleteLocal();
AppState().deleteName();
AppState().deleteOwnerUUID();
AppState().deletePass();
AppState().deletePasswd(); AppState().deletePasswd();
AppState().deletePerson();
AppState().deletePanic();
AppState().deletePanicPass(); AppState().deletePanicPass();
AppState().deleteProvisional();
AppState().deleteStatus();
AppState().deleteToken(); AppState().deleteToken();
AppState().deleteTokenAPNS(); AppState().deleteTokenAPNS();
AppState().deleteUpdatedAt();
AppState().deleteUserUUID();
AppState().deleteWhatsapp();
AppState().deleteContext(); AppState().deleteContext();
AppState().deleteRemoteId();
AppState().deleteSerialNumber();
secureStorage.deleteAll(); secureStorage.deleteAll();
AppState().isLogged = false; AppState().isLogged = false;

File diff suppressed because it is too large Load Diff

View File

@ -4,6 +4,7 @@ import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:hub/app_state.dart'; import 'package:hub/app_state.dart';
import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_calls.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/log_util.dart';
import 'notification_service.dart'; import 'notification_service.dart';
@ -61,16 +62,14 @@ class FirebaseMessagingService {
if (deviceToken != null) { if (deviceToken != null) {
AppState().token = deviceToken; AppState().token = deviceToken;
final ApiCallResponse? response;
final ApiCallResponse? response = await PhpGroup.updToken.call( response = await PhpGroup.updToken.call();
token: AppState().token,
devid: AppState().devUUID,
useruuid: AppState().userUUID);
if (PhpGroup.updToken.error((response?.jsonBody ?? '')) == false) { if (response.jsonBody['error'] == false) {
log('Token Atualizado com Sucesso!'); log('Token Atualizado com Sucesso!');
} else { } else {
log('Falha ao Atualizar Token: ${response?.jsonBody}'); log('Falha ao Atualizar Token: ${response.jsonBody}');
} }
} else { } else {
log('Falha ao Pegar Token do Firebase'); log('Falha ao Pegar Token do Firebase');

View File

@ -12,11 +12,17 @@ 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_util.dart';
import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; import 'package:hub/flutter_flow/flutter_flow_widgets.dart';
import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/dialog_util.dart';
import 'package:sqflite/sqflite.dart';
Future<void> onMessageReceived( Future<void> onMessageReceived(
Map<String, dynamic> payload, String? extra, String? handleClick) async { Map<String, dynamic> payload, String? extra, String? handleClick) async {
final localId = jsonDecode(payload['local']!)['CLI_ID']; final localId = jsonDecode(payload['local']!)['CLI_ID'];
final DatabaseHelper db = DatabaseHelper();
final cliUUID = await db
.get(key: 'cliUUID', field: 'value')
.then((value) => value.toString());
switch (handleClick) { switch (handleClick) {
case 'visit_request': case 'visit_request':
@ -127,7 +133,7 @@ Future<void> onMessageReceived(
): payload['mensagem'], ): payload['mensagem'],
}), }),
imagePath: imagePath:
'https://freaccess.com.br/freaccess/getImage.php?cliID=${AppState().cliUUID}&atividade=getFoto&Documento=${payload['documento'] ?? ''}&tipo=E', 'https://freaccess.com.br/freaccess/getImage.php?cliID=$cliUUID&atividade=getFoto&Documento=${payload['documento'] ?? ''}&tipo=E',
statusHashMap: [ statusHashMap: [
{ {
FFLocalizations.of(context).getVariableText( FFLocalizations.of(context).getVariableText(
@ -160,7 +166,7 @@ Future<void> onMessageReceived(
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
child: DetailsComponentWidget( child: DetailsComponentWidget(
imagePath: imagePath:
'https://freaccess.com.br/freaccess/getImage.php?cliID=${AppState().cliUUID}&atividade=getFoto&Documento=$id&tipo=$type', 'https://freaccess.com.br/freaccess/getImage.php?cliID=$cliUUID&atividade=getFoto&Documento=$id&tipo=$type',
labelsHashMap: Map<String, String>.from({ labelsHashMap: Map<String, String>.from({
FFLocalizations.of(context).getVariableText( FFLocalizations.of(context).getVariableText(
enText: 'Name', enText: 'Name',
@ -230,8 +236,6 @@ Future<void> onMessageReceived(
default: default:
break; break;
} }
// showAlertDialog(AppState().context!, 'Test', 'Test', () async {});
} }
class NotificationService { class NotificationService {
@ -263,9 +267,14 @@ class NotificationService {
await AwesomeNotifications() await AwesomeNotifications()
.isNotificationAllowed() .isNotificationAllowed()
.then((isAllowed) async { .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) { if (!isAllowed) {
AppState().isRequestOSNotification = true; await db.update('requestOSnotification', 'true', 'util');
await AwesomeNotifications().requestPermissionToSendNotifications(); await AwesomeNotifications().requestPermissionToSendNotifications();
} }
} }

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart'; import 'package:google_fonts/google_fonts.dart';
import 'package:hub/components/molecular_components/menu_item/menu_item.dart'; import 'package:hub/components/molecular_components/menu_item/menu_item.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/dialog_util.dart';
import '../../../app_state.dart'; import '../../../app_state.dart';
@ -33,7 +34,12 @@ class _MenuButtonWidgetState extends State<MenuButtonWidget> {
hoverColor: Colors.transparent, hoverColor: Colors.transparent,
highlightColor: Colors.transparent, highlightColor: Colors.transparent,
onTap: () async { onTap: () async {
if (AppState().cliUUID.isEmpty) { final DatabaseHelper db = DatabaseHelper();
final cliUUID = await db
.get(key: 'cliUUID', field: 'value')
.then((value) => value.toString());
if (cliUUID.isEmpty) {
return DialogUtil.warningDefault(context); return DialogUtil.warningDefault(context);
} else { } else {
await widget.action?.call(); await widget.action?.call();

View File

@ -3,6 +3,7 @@ import 'package:hub/components/organism_components/bottom_arrow_linked_locals_co
import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.dart'; import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/dialog_util.dart';
import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/log_util.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@ -64,11 +65,12 @@ class _BottomArrowLinkedLocalsComponentWidgetState
Future<ApiCallResponse?> _fetchLocals() async { Future<ApiCallResponse?> _fetchLocals() async {
try { try {
final DatabaseHelper db = DatabaseHelper();
final devUUID = await db.get(key: 'devUUID', field: 'value');
final userUUID = await db.get(key: 'userUUID', field: 'value');
setState(() => _loading = true); setState(() => _loading = true);
var response = await PhpGroup.getLocalsCall.call( var response = await PhpGroup.getLocalsCall.call();
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
);
final List<dynamic> locals = response.jsonBody['locais'] ?? []; final List<dynamic> locals = response.jsonBody['locais'] ?? [];
@ -82,9 +84,10 @@ class _BottomArrowLinkedLocalsComponentWidgetState
// Verifica se apenas um local e se o status é 'A' // Verifica se apenas um local e se o status é 'A'
if (locals.length == 1 && locals[0]['CLU_STATUS'] == 'A') { if (locals.length == 1 && locals[0]['CLU_STATUS'] == 'A') {
final local = locals[0]; final local = locals[0];
AppState().cliUUID = local['CLI_ID']; db.update('cliUUID', local['CLI_ID'], 'local');
AppState().local = local['CLI_NOME']; db.update('cliName', local['CLI_NOME'], 'local');
AppState().ownerUUID = local['CLU_OWNER_ID']; db.update('ownerUUID', local['CLU_OWNER_ID'], 'local');
context.pop(); context.pop();
} }
@ -109,11 +112,8 @@ class _BottomArrowLinkedLocalsComponentWidgetState
Future<dynamic> _fetchResponseLink(String status, String cliID) async { Future<dynamic> _fetchResponseLink(String status, String cliID) async {
try { try {
var response = await PhpGroup.resopndeVinculo.call( var response =
devUUID: AppState().devUUID, await PhpGroup.resopndeVinculo.call(tarefa: status, cliID: cliID);
userUUID: AppState().userUUID,
cliID: cliID,
tarefa: status);
if (response.jsonBody['error'] == false) { if (response.jsonBody['error'] == false) {
return { return {
@ -173,10 +173,13 @@ class _BottomArrowLinkedLocalsComponentWidgetState
labelsHashMap: _labelsHashMap(local), labelsHashMap: _labelsHashMap(local),
statusHashMap: [_statusHashMap(local)], statusHashMap: [_statusHashMap(local)],
onTapCardItemAction: () async { onTapCardItemAction: () async {
final DatabaseHelper db = DatabaseHelper();
if (local['CLU_STATUS'] == 'A') { if (local['CLU_STATUS'] == 'A') {
AppState().cliUUID = local['CLI_ID']; db.update('cliUUID', local['CLI_ID'], 'local');
AppState().local = local['CLI_NOME']; db.update('cliName', local['CLI_NOME'], 'local');
AppState().ownerUUID = local['CLU_OWNER_ID']; db.update('ownerUUID', local['CLU_OWNER_ID'], 'local');
context.pop(); context.pop();
} else if (local['CLU_STATUS'] == 'B') { } else if (local['CLU_STATUS'] == 'B') {
String message = FFLocalizations.of(context).getVariableText( String message = FFLocalizations.of(context).getVariableText(

View File

@ -1,3 +1,8 @@
import 'dart:ffi';
import 'dart:math';
import 'package:hub/shared/helpers/db_helper.dart';
import '/flutter_flow/flutter_flow_util.dart'; import '/flutter_flow/flutter_flow_util.dart';
import 'local_profile_component_widget.dart' show LocalProfileComponentWidget; import 'local_profile_component_widget.dart' show LocalProfileComponentWidget;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -6,8 +11,25 @@ import 'package:flutter/material.dart';
class LocalProfileComponentModel class LocalProfileComponentModel
extends FlutterFlowModel<LocalProfileComponentWidget> { extends FlutterFlowModel<LocalProfileComponentWidget> {
final DatabaseHelper db = DatabaseHelper();
String cliName = '';
String cliUUID = '';
VoidCallback? setStateCallback;
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
getData();
}
Future<void> 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 @override
void dispose() {} void dispose() {}

View File

@ -1,6 +1,12 @@
import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.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 'package:provider/provider.dart';
import '/flutter_flow/custom_functions.dart' as functions; import '/flutter_flow/custom_functions.dart' as functions;
@ -13,10 +19,7 @@ export 'local_profile_component_model.dart';
//// ////
class LocalProfileComponentWidget extends StatefulWidget { class LocalProfileComponentWidget extends StatefulWidget {
LocalProfileComponentWidget({Key? key, required this.showBottomSheet}) LocalProfileComponentWidget({Key? key}) : super(key: key);
: super(key: key);
VoidCallback showBottomSheet;
@override @override
State<LocalProfileComponentWidget> createState() => State<LocalProfileComponentWidget> createState() =>
@ -26,6 +29,7 @@ class LocalProfileComponentWidget extends StatefulWidget {
class _LocalProfileComponentWidgetState class _LocalProfileComponentWidgetState
extends State<LocalProfileComponentWidget> { extends State<LocalProfileComponentWidget> {
late LocalProfileComponentModel _model; late LocalProfileComponentModel _model;
final DatabaseHelper db = DatabaseHelper();
@override @override
void setState(VoidCallback callback) { void setState(VoidCallback callback) {
@ -37,6 +41,18 @@ class _LocalProfileComponentWidgetState
void initState() { void initState() {
super.initState(); super.initState();
_model = createModel(context, () => LocalProfileComponentModel()); _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 @override
@ -46,6 +62,88 @@ class _LocalProfileComponentWidgetState
super.dispose(); super.dispose();
} }
Future<void> 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<void> 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<dynamic> 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<void> 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
context.watch<AppState>(); context.watch<AppState>();
@ -79,7 +177,7 @@ class _LocalProfileComponentWidgetState
hoverColor: Colors.transparent, hoverColor: Colors.transparent,
highlightColor: Colors.transparent, highlightColor: Colors.transparent,
onTap: () async { onTap: () async {
widget.showBottomSheet(); showModalSelectLocal();
}, },
child: ClipRRect( child: ClipRRect(
borderRadius: BorderRadius.circular(200.0), borderRadius: BorderRadius.circular(200.0),
@ -93,7 +191,7 @@ class _LocalProfileComponentWidgetState
), ),
), ),
imageUrl: valueOrDefault( imageUrl: valueOrDefault(
'https://freaccess.com.br/freaccess/Images/Clients/${AppState().cliUUID}.png', 'https://freaccess.com.br/freaccess/Images/Clients/${_model.cliUUID}.png',
'assets/images/home.png'), 'assets/images/home.png'),
width: 80.0, width: 80.0,
height: 80.0, height: 80.0,
@ -111,11 +209,12 @@ class _LocalProfileComponentWidgetState
), ),
Text( Text(
valueOrDefault<String>( valueOrDefault<String>(
functions.convertToUppercase(AppState().local), functions.convertToUppercase(_model.cliName),
FFLocalizations.of(context).getVariableText( FFLocalizations.of(context).getVariableText(
ptText: 'SEM LOCAL VINCULADO', ptText: 'SEM LOCAL VINCULADO',
enText: 'NO LINKED LOCAL', enText: 'NO LINKED LOCAL',
)), ),
),
style: FlutterFlowTheme.of(context).labelMedium.override( style: FlutterFlowTheme.of(context).labelMedium.override(
fontFamily: 'Nunito', fontFamily: 'Nunito',
color: FlutterFlowTheme.of(context).info, color: FlutterFlowTheme.of(context).info,

View File

@ -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/components/organism_components/menu_staggered_view_component/menu_staggered_view_component_model.dart';
import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/extensions/dialog_extensions.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/molecular_components/option_selection_modal/option_selection_modal_widget.dart';
import '/components/organism_components/menu_list_view_component/menu_list_view_component_widget.dart'; import '/components/organism_components/menu_list_view_component/menu_list_view_component_widget.dart';
@ -68,7 +70,12 @@ class MenuComponentModel extends FlutterFlowModel<MenuComponentWidget> {
} }
Future deliverySchedule(BuildContext context) async { 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) { if (isProvisional == true) {
context.push( context.push(
'/deliverySchedule', '/deliverySchedule',
@ -86,7 +93,11 @@ class MenuComponentModel extends FlutterFlowModel<MenuComponentWidget> {
} }
Future provisionalSchedule(BuildContext context) async { 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) { if (isProvisional == true) {
context.push( context.push(
'/provisionalSchedule', '/provisionalSchedule',
@ -104,7 +115,10 @@ class MenuComponentModel extends FlutterFlowModel<MenuComponentWidget> {
} }
Future fastPassAction(BuildContext context) async { 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) { if (isWpp) {
context.push( context.push(
'/fastPassPage', '/fastPassPage',
@ -188,6 +202,8 @@ class MenuComponentModel extends FlutterFlowModel<MenuComponentWidget> {
} }
Future<void> signOut(BuildContext context) async { Future<void> signOut(BuildContext context) async {
final DatabaseHelper db = DatabaseHelper();
showAlertDialog( showAlertDialog(
context, context,
'Logout', 'Logout',
@ -195,10 +211,7 @@ class MenuComponentModel extends FlutterFlowModel<MenuComponentWidget> {
enText: 'Are you sure you want to logout?', enText: 'Are you sure you want to logout?',
ptText: 'Tem certeza', ptText: 'Tem certeza',
), () async { ), () async {
PhpGroup.unregisterDevice.call( PhpGroup.unregisterDevice.call();
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
);
AppState().deleteAll(); AppState().deleteAll();
context.go( context.go(
@ -211,6 +224,7 @@ class MenuComponentModel extends FlutterFlowModel<MenuComponentWidget> {
), ),
}, },
); );
await db.purge();
}); });
} }
@ -228,7 +242,10 @@ class MenuComponentModel extends FlutterFlowModel<MenuComponentWidget> {
} }
Future packageOrder(BuildContext context) async { 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) { if (isWpp) {
context.push( context.push(
@ -247,7 +264,10 @@ class MenuComponentModel extends FlutterFlowModel<MenuComponentWidget> {
} }
Future reservation(BuildContext context) async { 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) { if (isWpp) {
context.push( context.push(
'/reservation', '/reservation',
@ -363,7 +383,10 @@ class MenuComponentModel extends FlutterFlowModel<MenuComponentWidget> {
} }
Future petsAction(BuildContext context) async { 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) { if (isPet) {
context.push( context.push(
'/petsPage', '/petsPage',

View File

@ -3,6 +3,7 @@ import 'package:hub/backend/schema/enums/enums.dart';
import 'package:hub/components/atomic_components/menu_button_item/menu_button_item_widget.dart'; import 'package:hub/components/atomic_components/menu_button_item/menu_button_item_widget.dart';
import 'package:hub/components/atomic_components/menu_card_item/menu_card_item.dart'; import 'package:hub/components/atomic_components/menu_card_item/menu_card_item.dart';
import 'package:hub/components/molecular_components/menu_item/menu_item.dart'; import 'package:hub/components/molecular_components/menu_item/menu_item.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import '/components/organism_components/menu_list_view_component/menu_list_view_component_widget.dart'; import '/components/organism_components/menu_list_view_component/menu_list_view_component_widget.dart';
import '/components/organism_components/menu_staggered_view_component/menu_staggered_view_component_widget.dart'; import '/components/organism_components/menu_staggered_view_component/menu_staggered_view_component_widget.dart';

View File

@ -8,6 +8,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hub/backend/api_requests/api_calls.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_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.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:provider/provider.dart';
import 'package:rxdart/rxdart.dart'; import 'package:rxdart/rxdart.dart';
@ -338,6 +339,7 @@ class MessageWellState {
class MessageWellNotifier extends StateNotifier<MessageWellState> { class MessageWellNotifier extends StateNotifier<MessageWellState> {
var _totalPageNumber = 1; var _totalPageNumber = 1;
int get totalPageNumber => _totalPageNumber; int get totalPageNumber => _totalPageNumber;
final DatabaseHelper db = DatabaseHelper();
set totalPageNumber(int value) { set totalPageNumber(int value) {
_totalPageNumber = value; _totalPageNumber = value;
@ -355,10 +357,6 @@ class MessageWellNotifier extends StateNotifier<MessageWellState> {
if (state.pageNumber <= totalPageNumber) { if (state.pageNumber <= totalPageNumber) {
var apiCall = GetMessagesCall(); var apiCall = GetMessagesCall();
var response = await apiCall.call( var response = await apiCall.call(
devUUID: AppState().devUUID.toString(),
userUUID: AppState().userUUID.toString(),
cliID: AppState().cliUUID.toString(),
atividade: 'getMensagens',
pageSize: '100', pageSize: '100',
pageNumber: state.pageNumber.toString(), pageNumber: state.pageNumber.toString(),
tipoDestino: dropdown.value.values.first, tipoDestino: dropdown.value.values.first,

View File

@ -5,66 +5,65 @@ import 'package:hub/backend/api_requests/api_manager.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hub/components/organism_components/schedule_visit_detail/schedule_visit_detail_widget.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/flutter_flow/flutter_flow_model.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
class ScheduleVisitDetailModel class ScheduleVisitDetailModel
extends FlutterFlowModel<ScheduleVisitDetailWidget> { extends FlutterFlowModel<ScheduleVisitDetailWidget> {
/// 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; FocusNode? textFieldFocusNode1;
TextEditingController? textController1; TextEditingController? textController1;
String? Function(BuildContext, String?)? textController1Validator; String? Function(BuildContext, String?)? textController1Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode2; FocusNode? textFieldFocusNode2;
TextEditingController? textController2; TextEditingController? textController2;
String? Function(BuildContext, String?)? textController2Validator; String? Function(BuildContext, String?)? textController2Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode3; FocusNode? textFieldFocusNode3;
TextEditingController? textController3; TextEditingController? textController3;
String? Function(BuildContext, String?)? textController3Validator; String? Function(BuildContext, String?)? textController3Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode4; FocusNode? textFieldFocusNode4;
TextEditingController? textController4; TextEditingController? textController4;
String? Function(BuildContext, String?)? textController4Validator; String? Function(BuildContext, String?)? textController4Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode5; FocusNode? textFieldFocusNode5;
TextEditingController? textController5; TextEditingController? textController5;
String? Function(BuildContext, String?)? textController5Validator; String? Function(BuildContext, String?)? textController5Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode6; FocusNode? textFieldFocusNode6;
TextEditingController? textController6; TextEditingController? textController6;
String? Function(BuildContext, String?)? textController6Validator; String? Function(BuildContext, String?)? textController6Validator;
// Stores action output result for [Backend Call - API (postScheduleVisit)] action in Icon widget.
ApiCallResponse? postScheduleVisit; ApiCallResponse? postScheduleVisit;
String convertDateFormat(String dateStr) { String convertDateFormat(String dateStr) {
try { try {
// Formato original
DateFormat originalFormat = DateFormat('d/M/y H:mm:ss'); DateFormat originalFormat = DateFormat('d/M/y H:mm:ss');
// Novo formato
DateFormat newFormat = DateFormat('y-M-d H:mm:ss'); 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}$') if (!RegExp(r'^\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2}:\d{2}$')
.hasMatch(dateStr)) { .hasMatch(dateStr)) {
return 'Invalid date format'; return 'Invalid date format';
} }
// Converte a string para DateTime
DateTime dateTime = originalFormat.parse(dateStr); DateTime dateTime = originalFormat.parse(dateStr);
// Converte DateTime para a nova string formatada
String formattedDate = newFormat.format(dateTime); String formattedDate = newFormat.format(dateTime);
return formattedDate; return formattedDate;
} catch (e) { } catch (e) {
// Handle the exception by returning an error message or a default value
return 'Invalid date format'; return 'Invalid date format';
} }
} }
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
initDB();
}
Future<void> 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 @override
void dispose() { void dispose() {

View File

@ -173,7 +173,7 @@ class _ScheduleVisitDetailWidgetState extends State<ScheduleVisitDetailWidget> {
fadeInDuration: const Duration(milliseconds: 500), fadeInDuration: const Duration(milliseconds: 500),
fadeOutDuration: const Duration(milliseconds: 500), fadeOutDuration: const Duration(milliseconds: 500),
imageUrl: valueOrDefault<String>( imageUrl: valueOrDefault<String>(
"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, visitorsDataItem,
r'''$.VTE_DOCUMENTO''', r'''$.VTE_DOCUMENTO''',
).toString()}&tipo=E", ).toString()}&tipo=E",
@ -784,9 +784,6 @@ class _ScheduleVisitDetailWidgetState extends State<ScheduleVisitDetailWidget> {
onPressed: () async { onPressed: () async {
_model.postScheduleVisit = _model.postScheduleVisit =
await PhpGroup.postScheduleVisitCall.call( await PhpGroup.postScheduleVisitCall.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
atividade: 'putVisita',
devDesc: widget.visitObsStr, devDesc: widget.visitObsStr,
idVisitante: widget.visitorStrList, idVisitante: widget.visitorStrList,
dtInicio: dtInicio:
@ -796,7 +793,6 @@ class _ScheduleVisitDetailWidgetState extends State<ScheduleVisitDetailWidget> {
idMotivo: extractIdToStr(widget.visitResonStr!), idMotivo: extractIdToStr(widget.visitResonStr!),
idNAC: extractIdToStr(widget.visitLevelStr!), idNAC: extractIdToStr(widget.visitLevelStr!),
obs: widget.visitObsStr, obs: widget.visitObsStr,
cliID: AppState().cliUUID,
); );
if (PhpGroup.postScheduleVisitCall.error( if (PhpGroup.postScheduleVisitCall.error(

View File

@ -1,13 +1,36 @@
import 'package:hub/components/organism_components/up_arrow_linked_locals_component/up_arrow_linked_locals_component_widget.dart'; 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:hub/flutter_flow/flutter_flow_model.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hub/shared/helpers/db_helper.dart';
class UpArrowLinkedLocalsComponentModel class UpArrowLinkedLocalsComponentModel
extends FlutterFlowModel<UpArrowLinkedLocalsComponentWidget> { extends FlutterFlowModel<UpArrowLinkedLocalsComponentWidget> {
final DatabaseHelper db = DatabaseHelper();
late final String devUUID;
late final String userUUID;
late final String cliUUID;
late final String cliName;
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
initDB();
}
Future<void> 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 @override
void dispose() {} void dispose() {}

View File

@ -78,10 +78,7 @@ class _UpArrowLinkedLocalsComponentWidgetState
), ),
), ),
child: FutureBuilder<ApiCallResponse>( child: FutureBuilder<ApiCallResponse>(
future: PhpGroup.getLocalsCall.call( future: PhpGroup.getLocalsCall.call(),
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
),
builder: (context, snapshot) { builder: (context, snapshot) {
// Customize what your widget looks like when it's loading. // Customize what your widget looks like when it's loading.
if (!snapshot.hasData) { if (!snapshot.hasData) {
@ -131,12 +128,12 @@ class _UpArrowLinkedLocalsComponentWidgetState
hoverColor: Colors.transparent, hoverColor: Colors.transparent,
highlightColor: Colors.transparent, highlightColor: Colors.transparent,
onTap: () async { onTap: () async {
AppState().cliUUID = getJsonField( _model.cliUUID = getJsonField(
eachLocalsItem, eachLocalsItem,
r'''$.CLI_ID''', r'''$.CLI_ID''',
).toString(); ).toString();
setState(() {}); setState(() {});
AppState().local = getJsonField( _model.cliName = getJsonField(
eachLocalsItem, eachLocalsItem,
r'''$.CLI_NOME''', r'''$.CLI_NOME''',
).toString(); ).toString();

View File

@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hub/flutter_flow/nav/nav.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 '/backend/api_requests/api_calls.dart';
import '/flutter_flow/flutter_flow_util.dart'; import '/flutter_flow/flutter_flow_util.dart';
@ -8,27 +9,40 @@ import 'access_notification_modal_template_component_widget.dart'
class AccessNotificationModalTemplateComponentModel class AccessNotificationModalTemplateComponentModel
extends FlutterFlowModel<AccessNotificationModalTemplateComponentWidget> { extends FlutterFlowModel<AccessNotificationModalTemplateComponentWidget> {
/// 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; FocusNode? textFieldFocusNode1;
TextEditingController? textController1; TextEditingController? textController1;
String? Function(BuildContext, String?)? textController1Validator; String? Function(BuildContext, String?)? textController1Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode2; FocusNode? textFieldFocusNode2;
TextEditingController? textController2; TextEditingController? textController2;
String? Function(BuildContext, String?)? textController2Validator; String? Function(BuildContext, String?)? textController2Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode3; FocusNode? textFieldFocusNode3;
TextEditingController? textController3; TextEditingController? textController3;
String? Function(BuildContext, String?)? textController3Validator; String? Function(BuildContext, String?)? textController3Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode4; FocusNode? textFieldFocusNode4;
TextEditingController? textController4; TextEditingController? textController4;
String? Function(BuildContext, String?)? textController4Validator; String? Function(BuildContext, String?)? textController4Validator;
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
initDB();
}
Future<void> 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 @override
void dispose() { void dispose() {
@ -45,7 +59,6 @@ class AccessNotificationModalTemplateComponentModel
textController4?.dispose(); textController4?.dispose();
} }
/// Action blocks.
Future<bool> visitRequestComponentAction( Future<bool> visitRequestComponentAction(
BuildContext context, { BuildContext context, {
required String? actionValue, required String? actionValue,
@ -56,10 +69,6 @@ class AccessNotificationModalTemplateComponentModel
ApiCallResponse? visitRequest; ApiCallResponse? visitRequest;
visitRequest = await PhpGroup.respondeSolicitacaoCall.call( visitRequest = await PhpGroup.respondeSolicitacaoCall.call(
userUUID: AppState().userUUID,
devUUID: AppState().devUUID,
cliUUID: AppState().cliUUID,
atividade: 'respondeSolicitacao',
referencia: refUUID, referencia: refUUID,
tarefa: actionValue, tarefa: actionValue,
resposta: responseValue, resposta: responseValue,

View File

@ -110,10 +110,7 @@ class _AccessNotificationModalTemplateComponentWidgetState
fadeInDuration: const Duration(milliseconds: 100), fadeInDuration: const Duration(milliseconds: 100),
fadeOutDuration: const Duration(milliseconds: 100), fadeOutDuration: const Duration(milliseconds: 100),
imageUrl: valueOrDefault<String>( imageUrl: valueOrDefault<String>(
// widget.type == 'O' 'https://freaccess.com.br/freaccess/getImage.php?cliID=${_model.cliUUID}&atividade=getFoto&Documento=${widget.id}&tipo=${widget.type}',
// ? '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://storage.googleapis.com/flutterflow-io-6f20.appspot.com/projects/flutter-freaccess-hub-0xgz9q/assets/7ftdetkzc3s0/360_F_64676383_LdbmhiNM6Ypzb3FM4PPuFP9rHe7ri8Ju.jpg', 'https://storage.googleapis.com/flutterflow-io-6f20.appspot.com/projects/flutter-freaccess-hub-0xgz9q/assets/7ftdetkzc3s0/360_F_64676383_LdbmhiNM6Ypzb3FM4PPuFP9rHe7ri8Ju.jpg',
), ),
fit: BoxFit.cover, fit: BoxFit.cover,

View File

@ -1,21 +1,31 @@
import 'dart:convert';
import 'dart:developer'; import 'dart:developer';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:hub/actions/actions.dart'; import 'package:hub/actions/actions.dart';
import 'package:hub/backend/api_requests/api_calls.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/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_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/flutter_flow_widgets.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/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:hub/shared/utils/validator_util.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
Widget buildVisitDetails( Widget buildVisitDetails({
dynamic item, required dynamic item,
BuildContext context, required BuildContext context,
Future<dynamic> Function(BuildContext, int, int, String, String)? required Future<dynamic> Function(BuildContext, int, int, String, String)
changeStatusAction) { changeStatusAction,
required String devUUID,
required String userUUID,
required String cliUUID,
required String cliName,
}) {
return DetailsComponentWidget( return DetailsComponentWidget(
buttons: [ buttons: [
if (getStatus(item['VAW_STATUS']) == status.active) // REJECT ACTION if (getStatus(item['VAW_STATUS']) == status.active) // REJECT ACTION
@ -137,13 +147,13 @@ Widget buildVisitDetails(
icon: const Icon(Icons.share), icon: const Icon(Icons.share),
onPressed: () async { onPressed: () async {
Share.share(''' Share.share('''
Olá, \*${item['VTE_NOME']}\*! Você foi convidado para \*${AppState().local}\*. Olá, \*${item['VTE_NOME']}\*! Você foi convidado para \*${cliName}\*.
\*Validade do Convite\*: \*Validade do Convite\*:
- Início: ${item['VAW_DTINICIO']} - Início: ${item['VAW_DTINICIO']}
- Fim: ${item['VAW_DTFIM']} - 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( options: FFButtonOptions(
@ -177,7 +187,7 @@ URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/${AppState().c
: '', : '',
}), }),
imagePath: 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: [ statusHashMap: [
if (getStatus(item['VAW_STATUS']) == status.active) if (getStatus(item['VAW_STATUS']) == status.active)
Map<String, Color>.from({ Map<String, Color>.from({
@ -225,11 +235,17 @@ URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/${AppState().c
); );
} }
Widget buildPetDetails( Widget buildPetDetails({
dynamic item, required dynamic item,
BuildContext context, required BuildContext context,
Future<dynamic> Function(BuildContext, int, int, String, String)? required Future<dynamic> Function(BuildContext, int, int, String, String)
changeStatusAction) { changeStatusAction,
required String devUUID,
required String userUUID,
required String cliUUID,
required String cliName,
required PetsPageModel model,
}) {
return DetailsComponentWidget( return DetailsComponentWidget(
buttons: [ buttons: [
// EDIT ACTION // EDIT ACTION
@ -241,11 +257,12 @@ Widget buildPetDetails(
icon: const Icon(Icons.edit), icon: const Icon(Icons.edit),
onPressed: () async { onPressed: () async {
context.pop(); context.pop();
context.pop();
context.pushNamed('petsPage', extra: { model.isEditing = true;
'pet': item, model.item = item;
}); model.switchTab(0);
model.setEditForm();
// model.safeSetState!();
}, },
options: FFButtonOptions( options: FFButtonOptions(
width: 130, width: 130,
@ -284,9 +301,6 @@ Widget buildPetDetails(
int id = item['id']; int id = item['id'];
await PhpGroup.deletePet await PhpGroup.deletePet
.call( .call(
userUUID: AppState().userUUID,
devUUID: AppState().devUUID,
cliID: AppState().cliUUID,
petID: id, petID: id,
) )
.then((value) { .then((value) {
@ -386,7 +400,7 @@ Widget buildPetDetails(
item['notes'] ?? '', item['notes'] ?? '',
}), }),
imagePath: 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: [ statusHashMap: [
if (item['gender'] == "MAC") if (item['gender'] == "MAC")
Map<String, Color>.from({ Map<String, Color>.from({

View File

@ -265,9 +265,7 @@ class _ForgotPasswordTemplateComponentWidgetState
email: _model.emailAddressTextController.text, email: _model.emailAddressTextController.text,
); );
if (PhpGroup.forgotPasswordCall if (_model.req?.jsonBody['error'] == false) {
.error((_model.req?.jsonBody ?? '')) ==
false) {
await DialogUtil.success( await DialogUtil.success(
context, context,
FFLocalizations.of(context).getVariableText( FFLocalizations.of(context).getVariableText(
@ -276,9 +274,7 @@ class _ForgotPasswordTemplateComponentWidgetState
context.pop(); context.pop();
} else { } else {
await DialogUtil.error( await DialogUtil.error(
context, context, _model.req?.jsonBody['error_msg']);
PhpGroup.forgotPasswordCall
.msg((_model.req?.jsonBody ?? ''))!);
} }
setState(() {}); setState(() {});

View File

@ -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/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/flutter_flow_model.dart';
import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/helpers/db_helper.dart';
class LiberationHistoryItemDetailsTemplateComponentModel class LiberationHistoryItemDetailsTemplateComponentModel
extends FlutterFlowModel< extends FlutterFlowModel<
LiberationHistoryItemDetailsTemplateComponentWidget> { 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; FocusNode? textFieldFocusNode1;
TextEditingController? textController1; TextEditingController? textController1;
String? Function(BuildContext, String?)? textController1Validator; String? Function(BuildContext, String?)? textController1Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode2; FocusNode? textFieldFocusNode2;
TextEditingController? textController2; TextEditingController? textController2;
String? Function(BuildContext, String?)? textController2Validator; String? Function(BuildContext, String?)? textController2Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode3; FocusNode? textFieldFocusNode3;
TextEditingController? textController3; TextEditingController? textController3;
String? Function(BuildContext, String?)? textController3Validator; String? Function(BuildContext, String?)? textController3Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode4; FocusNode? textFieldFocusNode4;
TextEditingController? textController4; TextEditingController? textController4;
String? Function(BuildContext, String?)? textController4Validator; String? Function(BuildContext, String?)? textController4Validator;
@ -30,6 +30,18 @@ class LiberationHistoryItemDetailsTemplateComponentModel
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {}
Future<void> 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 @override
void dispose() { void dispose() {
textFieldFocusNode1?.dispose(); textFieldFocusNode1?.dispose();
@ -44,36 +56,4 @@ class LiberationHistoryItemDetailsTemplateComponentModel
textFieldFocusNode4?.dispose(); textFieldFocusNode4?.dispose();
textController4?.dispose(); textController4?.dispose();
} }
/// Action blocks.
Future<bool> 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;
}
}
} }

View File

@ -105,7 +105,7 @@ class _LiberationHistoryItemDetailsTemplateComponentWidgetState
fadeInDuration: const Duration(milliseconds: 100), fadeInDuration: const Duration(milliseconds: 100),
fadeOutDuration: const Duration(milliseconds: 100), fadeOutDuration: const Duration(milliseconds: 100),
imageUrl: valueOrDefault<String>( imageUrl: valueOrDefault<String>(
'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', 'https://storage.googleapis.com/flutterflow-io-6f20.appspot.com/projects/flutter-freaccess-hub-0xgz9q/assets/7ftdetkzc3s0/360_F_64676383_LdbmhiNM6Ypzb3FM4PPuFP9rHe7ri8Ju.jpg',
), ),
fit: BoxFit.cover, fit: BoxFit.cover,

View File

@ -43,36 +43,4 @@ class MessageNotificationModalTemplateComponentModel
textFieldFocusNode4?.dispose(); textFieldFocusNode4?.dispose();
textController4?.dispose(); textController4?.dispose();
} }
/// Action blocks.
Future<bool> 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;
}
}
} }

View File

@ -2,10 +2,18 @@ import 'package:flutter/material.dart';
import 'package:hub/backend/api_requests/api_manager.dart'; import 'package:hub/backend/api_requests/api_manager.dart';
import 'package:hub/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart'; import 'package:hub/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:sqflite/sqflite.dart';
class ScheduleProvisionalVisitPageModel class ScheduleProvisionalVisitPageModel
extends FlutterFlowModel<ScheduleProvisionalVisitPageWidget> { extends FlutterFlowModel<ScheduleProvisionalVisitPageWidget> {
/// Local state fields for this page. final DatabaseHelper db = DatabaseHelper();
String cliUUID = '';
String devUUID = '';
String userUUID = '';
String cliName = '';
String ownerUUID = '';
VoidCallback? setState;
bool toggleIdx = false; bool toggleIdx = false;
@ -26,10 +34,7 @@ class ScheduleProvisionalVisitPageModel
void updateDocsAtIndex(int index, Function(String) updateFn) => void updateDocsAtIndex(int index, Function(String) updateFn) =>
docs[index] = updateFn(docs[index]); docs[index] = updateFn(docs[index]);
/// State fields for stateful widgets in this page.
final formKey = GlobalKey<FormState>(); final formKey = GlobalKey<FormState>();
// State field(s) for personName widget.
FocusNode? personNameFocusNode; FocusNode? personNameFocusNode;
TextEditingController? personNameTextController; TextEditingController? personNameTextController;
String? Function(BuildContext, String?)? personNameTextControllerValidator; String? Function(BuildContext, String?)? personNameTextControllerValidator;
@ -37,27 +42,26 @@ class ScheduleProvisionalVisitPageModel
BuildContext context, String? val) { BuildContext context, String? val) {
if (val == null || val.isEmpty) { if (val == null || val.isEmpty) {
return FFLocalizations.of(context).getText( return FFLocalizations.of(context).getText(
'3hqg8buh' /* Nome é Obrigatório */, '3hqg8buh',
); );
} }
if (val.length > 80) { if (val.length > 80) {
return FFLocalizations.of(context).getText( return FFLocalizations.of(context).getText(
'l0b0zr50' /* Máximo 80 caracteres */, 'l0b0zr50',
); );
} }
return null; return null;
} }
// State field(s) for dateTime widget.
FocusNode? dateTimeFocusNode; FocusNode? dateTimeFocusNode;
TextEditingController? dateTimeTextController; TextEditingController? dateTimeTextController;
String? Function(BuildContext, String?)? dateTimeTextControllerValidator; String? Function(BuildContext, String?)? dateTimeTextControllerValidator;
String? _dateTimeTextControllerValidator(BuildContext context, String? val) { String? _dateTimeTextControllerValidator(BuildContext context, String? val) {
if (val == null || val.isEmpty) { if (val == null || val.isEmpty) {
return FFLocalizations.of(context).getText( return FFLocalizations.of(context).getText(
'uzefkuf9' /* Data / Hora é Obrigatório */, 'uzefkuf9',
); );
} }
@ -85,17 +89,48 @@ class ScheduleProvisionalVisitPageModel
} }
DateTime? datePicked; DateTime? datePicked;
// State field(s) for notes widget.
FocusNode? notesFocusNode; FocusNode? notesFocusNode;
TextEditingController? notesTextController; TextEditingController? notesTextController;
String? Function(BuildContext, String?)? notesTextControllerValidator; String? Function(BuildContext, String?)? notesTextControllerValidator;
// Stores action output result for [Backend Call - API (postProvVisitScheduling)] action in btnSend widget.
ApiCallResponse? provVisitSchedule; ApiCallResponse? provVisitSchedule;
@override @override
void initState(BuildContext context) { void initState(BuildContext context) {
personNameTextControllerValidator = _personNameTextControllerValidator; personNameTextControllerValidator = _personNameTextControllerValidator;
dateTimeTextControllerValidator = _dateTimeTextControllerValidator; 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<void> 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 @override

View File

@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.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/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/dialog_util.dart';
import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/log_util.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@ -14,9 +15,7 @@ import '/flutter_flow/flutter_flow_util.dart';
import '/flutter_flow/flutter_flow_widgets.dart'; import '/flutter_flow/flutter_flow_widgets.dart';
class ScheduleProvisionalVisitPageWidget extends StatefulWidget { class ScheduleProvisionalVisitPageWidget extends StatefulWidget {
const ScheduleProvisionalVisitPageWidget({ const ScheduleProvisionalVisitPageWidget({super.key});
super.key,
});
@override @override
State<ScheduleProvisionalVisitPageWidget> createState() => State<ScheduleProvisionalVisitPageWidget> createState() =>
@ -25,43 +24,22 @@ class ScheduleProvisionalVisitPageWidget extends StatefulWidget {
class _ScheduleProvisionalVisitPageWidgetState class _ScheduleProvisionalVisitPageWidgetState
extends State<ScheduleProvisionalVisitPageWidget> { extends State<ScheduleProvisionalVisitPageWidget> {
late ScheduleProvisionalVisitPageModel _model; late ScheduleProvisionalVisitPageModel model;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_model = createModel(context, () => ScheduleProvisionalVisitPageModel()); model = createModel(context, () => ScheduleProvisionalVisitPageModel());
model.setState = () => safeSetState(() {});
_model.personNameTextController ??= TextEditingController();
_model.personNameFocusNode ??= FocusNode();
_model.dateTimeTextController ??= TextEditingController();
_model.dateTimeFocusNode ??= FocusNode();
_model.notesTextController ??= TextEditingController();
_model.notesFocusNode ??= FocusNode();
} }
@override @override
void dispose() { void dispose() {
_model.dispose(); model.dispose();
super.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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
context.watch<AppState>(); context.watch<AppState>();
@ -78,7 +56,7 @@ class _ScheduleProvisionalVisitPageWidgetState
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Form( Form(
key: _model.formKey, key: model.formKey,
autovalidateMode: AutovalidateMode.onUserInteraction, autovalidateMode: AutovalidateMode.onUserInteraction,
child: SingleChildScrollView( child: SingleChildScrollView(
child: Column( child: Column(
@ -183,7 +161,7 @@ class _ScheduleProvisionalVisitPageWidgetState
fadeOutDuration: const Duration( fadeOutDuration: const Duration(
milliseconds: 200), milliseconds: 200),
imageUrl: imageUrl:
'https://freaccess.com.br/freaccess/Images/Clients/${AppState().cliUUID}.png', 'https://freaccess.com.br/freaccess/Images/Clients/${model.cliUUID}.png',
width: 35.0, width: 35.0,
height: 35.0, height: 35.0,
fit: BoxFit.contain, fit: BoxFit.contain,
@ -195,7 +173,7 @@ class _ScheduleProvisionalVisitPageWidgetState
padding: const EdgeInsetsDirectional padding: const EdgeInsetsDirectional
.fromSTEB(15.0, 0.0, 0.0, 0.0), .fromSTEB(15.0, 0.0, 0.0, 0.0),
child: Text( child: Text(
AppState().local, model.cliName,
style: FlutterFlowTheme.of(context) style: FlutterFlowTheme.of(context)
.bodyMedium .bodyMedium
.override( .override(
@ -269,12 +247,12 @@ class _ScheduleProvisionalVisitPageWidgetState
width: double.infinity, width: double.infinity,
child: TextFormField( child: TextFormField(
controller: controller:
_model.personNameTextController, model.personNameTextController,
focusNode: focusNode:
_model.personNameFocusNode, model.personNameFocusNode,
onChanged: (_) => onChanged: (_) =>
EasyDebounce.debounce( EasyDebounce.debounce(
'_model.personNameTextController', 'model.personNameTextController',
const Duration(milliseconds: 500), const Duration(milliseconds: 500),
() => setState(() {}), () => setState(() {}),
), ),
@ -397,7 +375,7 @@ class _ScheduleProvisionalVisitPageWidgetState
), ),
textAlign: TextAlign.start, textAlign: TextAlign.start,
maxLines: null, maxLines: null,
validator: _model validator: model
.personNameTextControllerValidator .personNameTextControllerValidator
.asValidator(context), .asValidator(context),
), ),
@ -421,12 +399,12 @@ class _ScheduleProvisionalVisitPageWidgetState
.fromSTEB(24.0, 0.0, 24.0, 0.0), .fromSTEB(24.0, 0.0, 24.0, 0.0),
child: TextFormField( child: TextFormField(
controller: controller:
_model.dateTimeTextController, model.dateTimeTextController,
focusNode: focusNode:
_model.dateTimeFocusNode, model.dateTimeFocusNode,
onChanged: (_) => onChanged: (_) =>
EasyDebounce.debounce( EasyDebounce.debounce(
'_model.dateTimeTextController', 'model.dateTimeTextController',
const Duration( const Duration(
milliseconds: 500), milliseconds: 500),
() => setState(() {}), () => setState(() {}),
@ -528,7 +506,7 @@ class _ScheduleProvisionalVisitPageWidgetState
.bodyMediumFamily), .bodyMediumFamily),
), ),
textAlign: TextAlign.start, textAlign: TextAlign.start,
validator: _model validator: model
.dateTimeTextControllerValidator .dateTimeTextControllerValidator
.asValidator(context), .asValidator(context),
), ),
@ -683,8 +661,7 @@ class _ScheduleProvisionalVisitPageWidgetState
if (datePickedDate != null && if (datePickedDate != null &&
datePickedTime != null) { datePickedTime != null) {
safeSetState(() { safeSetState(() {
_model.datePicked = model.datePicked = DateTime(
DateTime(
datePickedDate.year, datePickedDate.year,
datePickedDate.month, datePickedDate.month,
datePickedDate.day, datePickedDate.day,
@ -694,18 +671,19 @@ class _ScheduleProvisionalVisitPageWidgetState
}); });
} }
setState(() { setState(() {
_model.dateTimeTextController model.dateTimeTextController
?.text = dateTimeFormat( ?.text = dateTimeFormat(
"dd/MM/yyyy HH:mm:ss", "dd/MM/yyyy HH:mm:ss",
_model.datePicked, model.datePicked,
locale: FFLocalizations.of( locale: FFLocalizations.of(
context) context)
.languageCode, .languageCode,
); );
_model.dateTimeTextController
model.dateTimeTextController
?.selection = ?.selection =
TextSelection.collapsed( TextSelection.collapsed(
offset: _model offset: model
.dateTimeTextController! .dateTimeTextController!
.text .text
.length); .length);
@ -755,10 +733,10 @@ class _ScheduleProvisionalVisitPageWidgetState
child: SizedBox( child: SizedBox(
width: double.infinity, width: double.infinity,
child: TextFormField( child: TextFormField(
controller: _model controller:
.notesTextController, model.notesTextController,
focusNode: focusNode:
_model.notesFocusNode, model.notesFocusNode,
autofocus: false, autofocus: false,
textInputAction: textInputAction:
TextInputAction.next, TextInputAction.next,
@ -895,7 +873,7 @@ class _ScheduleProvisionalVisitPageWidgetState
maxLengthEnforcement: maxLengthEnforcement:
MaxLengthEnforcement MaxLengthEnforcement
.enforced, .enforced,
validator: _model validator: model
.notesTextControllerValidator .notesTextControllerValidator
.asValidator(context), .asValidator(context),
), ),
@ -912,26 +890,21 @@ class _ScheduleProvisionalVisitPageWidgetState
), ),
), ),
FFButtonWidget( FFButtonWidget(
onPressed: !_isFormValid() onPressed: !model.isFormValid()
? null ? null
: () async { : () async {
try { try {
_model.provVisitSchedule = await PhpGroup model.provVisitSchedule = await PhpGroup
.postProvVisitSchedulingCall .postProvVisitSchedulingCall
.call( .call(
devUUID: AppState().devUUID, data: model.dateTimeTextController.text,
userUUID: AppState().userUUID, motivo: model.notesTextController.text,
cliID: AppState().cliUUID, nome: model.personNameTextController.text,
atividade: 'putAgendamentoProv', proID: model.ownerUUID,
data: _model.dateTimeTextController.text,
motivo: _model.notesTextController.text,
nome:
_model.personNameTextController.text,
proID: AppState().ownerUUID,
); );
if (PhpGroup.postProvVisitSchedulingCall if (PhpGroup.postProvVisitSchedulingCall
.error((_model.provVisitSchedule .error((model.provVisitSchedule
?.jsonBody ?? ?.jsonBody ??
'')) == '')) ==
false) { false) {
@ -943,16 +916,15 @@ class _ScheduleProvisionalVisitPageWidgetState
enText: enText:
"Provisional Scheduling Successfully Completed")); "Provisional Scheduling Successfully Completed"));
safeSetState(() { safeSetState(() {
_model.dateTimeTextController?.clear(); model.dateTimeTextController?.clear();
_model.personNameTextController model.personNameTextController?.clear();
?.clear(); model.notesTextController?.clear();
_model.notesTextController?.clear();
}); });
} else { } else {
var message = PhpGroup var message = PhpGroup
.postProvVisitSchedulingCall .postProvVisitSchedulingCall
.msg((_model.provVisitSchedule .msg((model.provVisitSchedule
?.jsonBody ?? ?.jsonBody ??
'')); ''));
if (message != null) { if (message != null) {

View File

@ -1,6 +1,7 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/utils/validator_util.dart'; import 'package:hub/shared/utils/validator_util.dart';
import '/backend/api_requests/api_calls.dart'; import '/backend/api_requests/api_calls.dart';
@ -10,8 +11,11 @@ import 'regisiter_vistor_template_component_widget.dart';
class RegisiterVistorTemplateComponentModel class RegisiterVistorTemplateComponentModel
extends FlutterFlowModel<RegisiterVistorTemplateComponentWidget> { extends FlutterFlowModel<RegisiterVistorTemplateComponentWidget> {
/// State fields for stateful widgets in this page.
Timer? _debounceTimer; Timer? _debounceTimer;
final DatabaseHelper db = DatabaseHelper();
late final String devUUID;
late final String userUUID;
late final String cliUUID;
final unfocusNode = FocusNode(); final unfocusNode = FocusNode();
bool isDataUploading = false; bool isDataUploading = false;
@ -25,8 +29,6 @@ class RegisiterVistorTemplateComponentModel
_debounceTimer = Timer(time, fn); _debounceTimer = Timer(time, fn);
} }
// State field(s) for TextField widget. // State field(s) for TextField widget.
FocusNode? textFieldFocusNode1; FocusNode? textFieldFocusNode1;
TextEditingController? textController1; TextEditingController? textController1;
@ -45,10 +47,6 @@ class RegisiterVistorTemplateComponentModel
Future<bool> getVisitanteByDocument( Future<bool> getVisitanteByDocument(
String document, BuildContext context) async { String document, BuildContext context) async {
final response = await PhpGroup.getVisitorByDocCall.call( final response = await PhpGroup.getVisitorByDocCall.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliID: AppState().cliUUID,
atividade: 'getVisitante',
documento: document, documento: document,
); );
@ -132,6 +130,14 @@ class RegisiterVistorTemplateComponentModel
textFieldFocusNode4 = FocusNode(); textFieldFocusNode4 = FocusNode();
textController4 = TextEditingController(); textController4 = TextEditingController();
textController4Validator = _textController4Validator; textController4Validator = _textController4Validator;
initializeDatabase();
}
Future<void> 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 @override

View File

@ -845,10 +845,6 @@ class _RegisiterVistorTemplateComponentWidgetState
_model.scheduleVisitor = _model.scheduleVisitor =
await PhpGroup.postScheduleVisitorCall await PhpGroup.postScheduleVisitorCall
.call( .call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliID: AppState().cliUUID,
atividade: 'putVisitante',
documento: _model.textController2.text, documento: _model.textController2.text,
nome: _model.textController1.text, nome: _model.textController1.text,
tipo: _model.dropDownValue == tipo: _model.dropDownValue ==

View File

@ -550,7 +550,7 @@ class _SignInTemplateComponentWidgetState
? null ? null
: () async { : () async {
await action_blocks await action_blocks
.singInLoginAction( .signInLoginAction(
context, context,
_model, _model,
emailAdress: _model emailAdress: _model
@ -710,7 +710,7 @@ class _SignInTemplateComponentWidgetState
: () async { : () async {
try { try {
await action_blocks await action_blocks
.singInLoginAction( .signInLoginAction(
context, context,
_model, _model,
emailAdress: _model emailAdress: _model

View File

@ -703,7 +703,8 @@ class _SignUpTemplateComponentWidgetState
email: _model email: _model
.emailRegisterFormTextController .emailRegisterFormTextController
.text, .text,
device: AppState().device, device:
AppState().deviceType,
); );
shouldSetState = true; shouldSetState = true;
if (_model.signUp == true) { if (_model.signUp == true) {

View File

@ -1,42 +1,52 @@
import 'package:hub/shared/helpers/db_helper.dart';
import '/backend/api_requests/api_calls.dart'; import '/backend/api_requests/api_calls.dart';
import '/flutter_flow/flutter_flow_util.dart'; import '/flutter_flow/flutter_flow_util.dart';
import 'view_visit_detail_widget.dart' show ViewVisitDetailWidget; import 'view_visit_detail_widget.dart' show ViewVisitDetailWidget;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class ViewVisitDetailModel extends FlutterFlowModel<ViewVisitDetailWidget> { class ViewVisitDetailModel extends FlutterFlowModel<ViewVisitDetailWidget> {
/// 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; FocusNode? textFieldFocusNode1;
TextEditingController? textController1; TextEditingController? textController1;
String? Function(BuildContext, String?)? textController1Validator; String? Function(BuildContext, String?)? textController1Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode2; FocusNode? textFieldFocusNode2;
TextEditingController? textController2; TextEditingController? textController2;
String? Function(BuildContext, String?)? textController2Validator; String? Function(BuildContext, String?)? textController2Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode3; FocusNode? textFieldFocusNode3;
TextEditingController? textController3; TextEditingController? textController3;
String? Function(BuildContext, String?)? textController3Validator; String? Function(BuildContext, String?)? textController3Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode4; FocusNode? textFieldFocusNode4;
TextEditingController? textController4; TextEditingController? textController4;
String? Function(BuildContext, String?)? textController4Validator; String? Function(BuildContext, String?)? textController4Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode5; FocusNode? textFieldFocusNode5;
TextEditingController? textController5; TextEditingController? textController5;
String? Function(BuildContext, String?)? textController5Validator; String? Function(BuildContext, String?)? textController5Validator;
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode6; FocusNode? textFieldFocusNode6;
TextEditingController? textController6; TextEditingController? textController6;
String? Function(BuildContext, String?)? textController6Validator; String? Function(BuildContext, String?)? textController6Validator;
// Stores action output result for [Backend Call - API (deleteVisit)] action in IconButton widget.
ApiCallResponse? deleteVisit; ApiCallResponse? deleteVisit;
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
initializeDatabase();
}
Future<void> 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 @override
void dispose() { void dispose() {

View File

@ -822,10 +822,6 @@ class _ViewVisitDetailWidgetState extends State<ViewVisitDetailWidget> {
onPressed: () async { onPressed: () async {
_model.deleteVisit = _model.deleteVisit =
await PhpGroup.deleteVisitCall.call( await PhpGroup.deleteVisitCall.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliID: AppState().cliUUID,
atividade: 'cancelaVisita',
idVisita: widget.visitIdStr, idVisita: widget.visitIdStr,
); );

View File

@ -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/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:hub/flutter_flow/flutter_flow_model.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hub/shared/helpers/db_helper.dart';
class VisitorSearchModalTemplateComponentModel class VisitorSearchModalTemplateComponentModel
extends FlutterFlowModel<VisitorSearchModalTemplateComponentWidget> { extends FlutterFlowModel<VisitorSearchModalTemplateComponentWidget> {
/// Local state fields for this component. final DatabaseHelper db = DatabaseHelper();
late final String devUUID;
late final String userUUID;
late final String cliUUID;
List<dynamic> visitors = []; List<dynamic> visitors = [];
void addToVisitors(dynamic item) => visitors.add(item); void addToVisitors(dynamic item) => visitors.add(item);
@ -26,17 +29,27 @@ class VisitorSearchModalTemplateComponentModel
void updateDocsAtIndex(int index, Function(String) updateFn) => void updateDocsAtIndex(int index, Function(String) updateFn) =>
docs[index] = updateFn(docs[index]); docs[index] = updateFn(docs[index]);
/// State fields for stateful widgets in this component.
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode; FocusNode? textFieldFocusNode;
TextEditingController? textController; TextEditingController? textController;
String? Function(BuildContext, String?)? textControllerValidator; String? Function(BuildContext, String?)? textControllerValidator;
// Stores action output result for [Backend Call - API (getVisitorByDoc)] action in TextField widget.
ApiCallResponse? getVisitorByDoc; ApiCallResponse? getVisitorByDoc;
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
initDatabase();
}
Future<void> 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 @override
void dispose() { void dispose() {

View File

@ -268,7 +268,7 @@ class _VisitorSearchModalTemplateComponentWidgetState
fadeOutDuration: const Duration( fadeOutDuration: const Duration(
milliseconds: 500), milliseconds: 500),
imageUrl: 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, visitorItem,
r'''$.VTE_DOCUMENTO''', r'''$.VTE_DOCUMENTO''',
).toString()}&tipo=E", ).toString()}&tipo=E",
@ -440,10 +440,6 @@ class _VisitorSearchModalTemplateComponentWidgetState
TextSelection.collapsed(offset: _model.textController!.text.length); TextSelection.collapsed(offset: _model.textController!.text.length);
}); });
_model.getVisitorByDoc = await PhpGroup.getVisitorByDocCall.call( _model.getVisitorByDoc = await PhpGroup.getVisitorByDocCall.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliID: AppState().cliUUID,
atividade: 'getVisitante',
documento: _model.textController.text, documento: _model.textController.text,
); );

View File

@ -146,9 +146,7 @@ GoRouter createRouter(AppStateNotifier appStateNotifier) => GoRouter(
FFRoute( FFRoute(
name: 'preferencesSettings', name: 'preferencesSettings',
path: '/preferencesSettings', path: '/preferencesSettings',
builder: (context, params) => const PreferencesPageWidget( builder: (context, params) => PreferencesPageWidget()),
key: Key('preferencesSettings'),
)),
FFRoute( FFRoute(
name: 'peopleOnThePropertyPage', name: 'peopleOnThePropertyPage',
path: '/peopleOnThePropertyPage', path: '/peopleOnThePropertyPage',
@ -190,7 +188,7 @@ GoRouter createRouter(AppStateNotifier appStateNotifier) => GoRouter(
FFRoute( FFRoute(
name: 'preferencesPage', name: 'preferencesPage',
path: '/preferencesPage', path: '/preferencesPage',
builder: (context, params) => const PreferencesPageWidget(), builder: (context, params) => PreferencesPageWidget(),
), ),
FFRoute( FFRoute(
name: 'packageOrder', name: 'packageOrder',

View File

@ -15,6 +15,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_util.dart';
import 'package:hub/flutter_flow/internationalization.dart'; import 'package:hub/flutter_flow/internationalization.dart';
import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:responsive_framework/responsive_framework.dart'; import 'package:responsive_framework/responsive_framework.dart';
@ -22,6 +23,7 @@ final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
Future<void> initializeApp() async { Future<void> initializeApp() async {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
await DatabaseHelper().database;
final status = await AppTrackingTransparency.requestTrackingAuthorization(); final status = await AppTrackingTransparency.requestTrackingAuthorization();
@ -109,42 +111,6 @@ class _AppState extends State<App> {
}); });
} }
//
// Future<void> showCustomTrackingDialog(BuildContext context) async {
// await showDialog<void>(
// context: context,
// builder: (context) => AlertDialog(
// title: const Text('Dear User'),
// content: const Text(
// 'We care about your privacy and data security. We keep this app free by showing ads. '
// 'Can we continue to use your data to tailor ads for you?\n\nYou can change your choice anytime in the app settings. '
// 'Our partners will collect data and use a unique identifier on your device to show you ads.',
// ),
// actions: [
// TextButton(
// onPressed: () => Navigator.pop(context),
// child: const Text('Continue'),
// ),
// ],
// ),
// );
// }
//
// Future<void> initializeTracking() async {
// if (await AppTrackingTransparency.trackingAuthorizationStatus ==
// TrackingStatus.notDetermined) {
// // Show a custom explainer dialog before the system dialog
// await showCustomTrackingDialog(context);
// // Wait for dialog popping animation
// await Future.delayed(const Duration(milliseconds: 200));
// // Request system's tracking authorization dialog
// await AppTrackingTransparency.requestTrackingAuthorization();
// }
//
// final uuid = await AppTrackingTransparency.getAdvertisingIdentifier();
// log("UUID de Publicidade: $uuid");
// }
void setLocale(String language) { void setLocale(String language) {
setState(() => _locale = createLocale(language)); setState(() => _locale = createLocale(language));
FFLocalizations.storeLocale(language); FFLocalizations.storeLocale(language);

View File

@ -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/flutter_flow_model.dart';
import 'package:hub/flutter_flow/request_manager.dart'; import 'package:hub/flutter_flow/request_manager.dart';
import 'package:hub/pages/acess_history_page/acess_history_page_widget.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<AcessHistoryPageWidget> { class AcessHistoryPageModel extends FlutterFlowModel<AcessHistoryPageWidget> {
final DatabaseHelper db = DatabaseHelper();
late final String devUUID;
late final String userUUID;
late final String cliUUID;
final unfocusNode = FocusNode(); final unfocusNode = FocusNode();
final _accessHistoryManager = FutureRequestManager<ApiCallResponse>(); final _accessHistoryManager = FutureRequestManager<ApiCallResponse>();
Future<ApiCallResponse> accessHistory({ Future<ApiCallResponse> accessHistory({
@ -23,14 +29,26 @@ class AcessHistoryPageModel extends FlutterFlowModel<AcessHistoryPageWidget> {
_accessHistoryManager.clearRequest(uniqueKey); _accessHistoryManager.clearRequest(uniqueKey);
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
initDatabase();
}
Future<void> 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 @override
void dispose() { void dispose() {
unfocusNode.dispose(); unfocusNode.dispose();
/// Dispose query cache managers for this widget.
clearAccessHistoryCache(); clearAccessHistoryCache();
} }

View File

@ -187,10 +187,6 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
try { try {
setState(() => _loading = true); setState(() => _loading = true);
var response = await PhpGroup.getAccessCall.call( var response = await PhpGroup.getAccessCall.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliID: AppState().cliUUID,
atividade: 'getAcessos',
pageSize: _pageSize.toString(), pageSize: _pageSize.toString(),
pageNumber: _pageNumber.toString(), pageNumber: _pageNumber.toString(),
pesTipo: _personType != 'E' && _personType != 'O' ? 'T' : _personType, pesTipo: _personType != 'E' && _personType != 'O' ? 'T' : _personType,
@ -333,7 +329,7 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
BuildContext context, dynamic accessHistoryItem) { BuildContext context, dynamic accessHistoryItem) {
return CardItemTemplateComponentWidget( return CardItemTemplateComponentWidget(
imagePath: 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<String, String>.from({ labelsHashMap: Map<String, String>.from({
FFLocalizations.of(context).getVariableText( FFLocalizations.of(context).getVariableText(
ptText: 'Nome:', ptText: 'Nome:',
@ -392,11 +388,11 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
], ],
onTapCardItemAction: () async {}); onTapCardItemAction: () async {});
} }
}
String imageUrlAtomWidget(String document, String type) { String imageUrlAtomWidget(String document, String type) {
return valueOrDefault<String>( return valueOrDefault<String>(
"https://freaccess.com.br/freaccess/getImage.php?&cliID=${AppState().cliUUID}&atividade=getFoto&Documento=$document&tipo=$type", "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", "https://storage.googleapis.com/flutterflow-io-6f20.appspot.com/projects/flutter-freaccess-hub-0xgz9q/assets/7ftdetkzc3s0/360_F_64676383_LdbmhiNM6Ypzb3FM4PPuFP9rHe7ri8Ju.jpg",
); );
} }
}

View File

@ -17,20 +17,15 @@ class DeliverySchedule extends StatefulWidget {
} }
class _DeliveryScheduleState extends State<DeliverySchedule> { class _DeliveryScheduleState extends State<DeliverySchedule> {
late ScheduleProvisionalVisitPageModel _model;
final scaffoldKey = GlobalKey<ScaffoldState>(); final scaffoldKey = GlobalKey<ScaffoldState>();
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_model = createModel(context, () => ScheduleProvisionalVisitPageModel());
} }
@override @override
void dispose() { void dispose() {
_model.dispose();
super.dispose(); super.dispose();
} }

View File

@ -4,22 +4,14 @@ import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart'; import 'package:flutter/scheduler.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:hub/app_state.dart'; import 'package:hub/app_state.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/nav/nav.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:hub/shared/utils/webview_util.dart';
import 'package:url_launcher/url_launcher_string.dart'; import 'package:url_launcher/url_launcher_string.dart';
import 'package:webview_flutter/webview_flutter.dart'; import 'package:webview_flutter/webview_flutter.dart';
class FastPassPageWidget extends StatefulWidget { 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 @override
_FastPassPageWidgetState createState() => _FastPassPageWidgetState(); _FastPassPageWidgetState createState() => _FastPassPageWidgetState();
} }
@ -27,27 +19,67 @@ class FastPassPageWidget extends StatefulWidget {
class _FastPassPageWidgetState extends State<FastPassPageWidget> { class _FastPassPageWidgetState extends State<FastPassPageWidget> {
late InAppWebViewController _controllerIOS; late InAppWebViewController _controllerIOS;
late WebViewController _controllerAll; late WebViewController _controllerAll;
late String url; final DatabaseHelper db = DatabaseHelper();
late String name;
late String email;
late String userUUID;
late String created_at;
@override Future<Map<String, String>> initVariables() async {
void initState() { final email = AppState().email;
super.initState(); final name = await db
name = AppState().name; .get(key: 'userName', field: 'value')
email = AppState().email; .then((value) => value.toString());
userUUID = AppState().userUUID; final userUUID = await db
created_at = AppState().createdAt; .get(key: 'userUUID', field: 'value')
url = 'https://hub.freaccess.com.br/hub/fast-pass/${widget.clientId}'; .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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return SafeArea( return SafeArea(
child: Scaffold( child: Scaffold(
body: Platform.isIOS body: FutureBuilder<Map<String, String>>(
future: initVariables(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError ||
snapshot.hasData == false ||
snapshot.data!.isEmpty) {
return Center(
child: Text(FFLocalizations.of(context).getVariableText(
enText: 'Unexpected error', ptText: 'Erro inesperado')));
} else if (snapshot.hasData) {
final data = snapshot.data!;
final url = data['url']!;
final userUUID = data['userUUID']!;
final freUserData = data['freUserData']!;
return Platform.isIOS
? InAppWebView( ? InAppWebView(
initialUrlRequest: URLRequest(url: WebUri(url)), initialUrlRequest: URLRequest(url: WebUri(url)),
initialSettings: InAppWebViewSettings( initialSettings: InAppWebViewSettings(
@ -60,10 +92,10 @@ class _FastPassPageWidgetState extends State<FastPassPageWidget> {
onLoadStop: (controller, url) async { onLoadStop: (controller, url) async {
await controller.evaluateJavascript( await controller.evaluateJavascript(
source: source:
"window.localStorage.setItem('fre-token', '\"${widget.freToken}\"')"); "window.localStorage.setItem('fre-token', '\"$userUUID\"')");
await controller.evaluateJavascript( await controller.evaluateJavascript(
source: source:
"window.localStorage.setItem('fre-user-data', '${widget.freUserData}')"); "window.localStorage.setItem('fre-user-data', '$freUserData')");
await controller.evaluateJavascript( await controller.evaluateJavascript(
source: source:
"window.localStorage.setItem('enableBackButton', 'true')"); "window.localStorage.setItem('enableBackButton', 'true')");
@ -85,9 +117,9 @@ class _FastPassPageWidgetState extends State<FastPassPageWidget> {
onProgress: (int progress) {}, onProgress: (int progress) {},
onPageStarted: (String url) { onPageStarted: (String url) {
final String token = final String token =
"localStorage.setItem('fre-token', '\"${widget.freToken}\"');"; "localStorage.setItem('fre-token', '\"$userUUID\"');";
final String data = final String data =
"localStorage.setItem('fre-user-data', '${widget.freUserData}');"; "localStorage.setItem('fre-user-data', '$freUserData');";
const String backNavigation = const String backNavigation =
"localStorage.setItem('enableBackButton', 'true');"; "localStorage.setItem('enableBackButton', 'true');";
@ -96,13 +128,15 @@ class _FastPassPageWidgetState extends State<FastPassPageWidget> {
_controllerAll.runJavaScript(backNavigation); _controllerAll.runJavaScript(backNavigation);
}, },
onPageFinished: (String url) { onPageFinished: (String url) {
bool isDarkMode = SchedulerBinding.instance bool isDarkMode = SchedulerBinding
.platformDispatcher.platformBrightness == .instance
.platformDispatcher
.platformBrightness ==
Brightness.dark; Brightness.dark;
if (isDarkMode) { if (isDarkMode) {
_controllerAll _controllerAll.runJavaScript(
.runJavaScript(WebviewUtil.jsEnableDarkMode); WebviewUtil.jsEnableDarkMode);
} }
}, },
onNavigationRequest: (NavigationRequest request) { onNavigationRequest: (NavigationRequest request) {
@ -122,6 +156,11 @@ class _FastPassPageWidgetState extends State<FastPassPageWidget> {
}), }),
) )
..loadRequest(Uri.parse(url)), ..loadRequest(Uri.parse(url)),
);
} else {
return Center(child: Text('Unexpected error'));
}
},
), ),
), ),
); );

View File

@ -1,31 +1,48 @@
import 'package:flutter/material.dart'; 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/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/menu_component/menu_component_model.dart';
import 'package:hub/components/organism_components/message_well_component/message_well_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/flutter_flow/flutter_flow_model.dart';
import 'package:hub/pages/home_page/home_page_widget.dart'; import 'package:hub/pages/home_page/home_page_widget.dart';
import 'package:hub/shared/helpers/db_helper.dart';
class HomePageModel extends FlutterFlowModel<HomePageWidget> { class HomePageModel extends FlutterFlowModel<HomePageWidget> {
/// Local state fields for this page.
bool isGrid = false; bool isGrid = false;
final DatabaseHelper db = DatabaseHelper();
/// State fields for stateful widgets in this page. late final String devUUID;
late final String cliUUID;
late final String userUUID;
late final String userName;
late final String userEmail;
final unfocusNode = FocusNode(); final unfocusNode = FocusNode();
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode; FocusNode? textFieldFocusNode;
TextEditingController? textController; TextEditingController? textController;
String? Function(BuildContext, String?)? textControllerValidator; String? Function(BuildContext, String?)? textControllerValidator;
// Model for localComponent.
late LocalProfileComponentModel localComponentModel; late LocalProfileComponentModel localComponentModel;
// Model for menuComponent component.
late MenuComponentModel menuComponentModel; late MenuComponentModel menuComponentModel;
// Model for messageWellComponent component.
late MessageWellComponentModel messageWellComponentModel; late MessageWellComponentModel messageWellComponentModel;
Future<void> _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 @override
void initState(BuildContext context) { void initState(BuildContext context) {
_initVariable();
localComponentModel = localComponentModel =
createModel(context, () => LocalProfileComponentModel()); createModel(context, () => LocalProfileComponentModel());
menuComponentModel = createModel(context, () => MenuComponentModel()); menuComponentModel = createModel(context, () => MenuComponentModel());

View File

@ -1,20 +1,17 @@
import 'dart:async';
import 'dart:developer'; import 'dart:developer';
import 'package:flutter/gestures.dart'; import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.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/notifications/firebase_messaging_service.dart';
import 'package:hub/backend/schema/enums/enums.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/local_profile_component/local_profile_component_widget.dart';
import 'package:hub/components/organism_components/menu_component/menu_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'; 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_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/pages/home_page/home_page_model.dart'; import 'package:hub/pages/home_page/home_page_model.dart';
import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/widgets/drawer_widget/drawer_widget.dart'; import 'package:hub/shared/widgets/drawer_widget/drawer_widget.dart';
class HomePageWidget extends StatefulWidget { class HomePageWidget extends StatefulWidget {
@ -28,84 +25,10 @@ class _HomePageWidgetState extends State<HomePageWidget> {
late HomePageModel _model; late HomePageModel _model;
final scaffoldKey = GlobalKey<ScaffoldState>(); final scaffoldKey = GlobalKey<ScaffoldState>();
late LocalProfileComponentWidget _localProfileComponentWidget; late LocalProfileComponentWidget _localProfileComponentWidget;
final DatabaseHelper db = DatabaseHelper();
_HomePageWidgetState() { _HomePageWidgetState() {
_localProfileComponentWidget = _localProfileComponentWidget = LocalProfileComponentWidget();
LocalProfileComponentWidget(showBottomSheet: showModalSelectLocal);
}
Future<void> processData() async {
try {
var response = await PhpGroup.getDadosCall.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliUUID: AppState().cliUUID,
atividade: 'getDados',
);
final error = response.jsonBody['error'];
final errorMsg = response.jsonBody['error_msg'];
if (error == false) {
AppState().whatsapp = response.jsonBody['whatsapp'] ?? false;
AppState().provisional = response.jsonBody['provisional'] ?? false;
AppState().pets = response.jsonBody['pet'] ?? false;
AppState().petAmountRegister =
response.jsonBody['petAmountRegister'] ?? '0';
AppState().name = response.jsonBody['visitado']['VDO_NOME'];
safeSetState(() {});
return;
}
DialogUtil.warningDefault(context).whenComplete(() => processLocals());
safeSetState(() {});
return;
} catch (e, s) {
DialogUtil.warningDefault(context).whenComplete(() => processLocals());
}
}
Future<void> processLocals() async {
try {
var response = await PhpGroup.getLocalsCall.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
);
List<dynamic> locals = response.jsonBody['locais'] ?? [];
final activeLocals =
locals.where((local) => local['CLU_STATUS'] == 'A').toList();
if (activeLocals.isEmpty || AppState().cliUUID.isEmpty) {
await showModalSelectLocal();
} else {
await processData();
}
} catch (e) {
await showModalSelectLocal();
}
}
Future<void> 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();
});
} }
@override @override
@ -123,12 +46,6 @@ class _HomePageWidgetState extends State<HomePageWidget> {
FirebaseMessagingService().updateDeviceToken(); FirebaseMessagingService().updateDeviceToken();
() async {
if (AppState().cliUUID.isEmpty) {
await processLocals();
}
}();
_model.textController ??= TextEditingController(); _model.textController ??= TextEditingController();
_model.textFieldFocusNode ??= FocusNode(); _model.textFieldFocusNode ??= FocusNode();
} }
@ -218,8 +135,8 @@ class _HomePageWidgetState extends State<HomePageWidget> {
verticalDirection: VerticalDirection.down, verticalDirection: VerticalDirection.down,
clipBehavior: Clip.none, clipBehavior: Clip.none,
children: [ children: [
createLocal(), buildLocal(),
createBody(), buildBody(),
], ],
), ),
], ],
@ -228,7 +145,7 @@ class _HomePageWidgetState extends State<HomePageWidget> {
); );
} }
Widget createBody() { Widget buildBody() {
return Container( return Container(
color: FlutterFlowTheme.of(context).primaryBackground, color: FlutterFlowTheme.of(context).primaryBackground,
child: wrapWithModel( child: wrapWithModel(
@ -246,7 +163,7 @@ class _HomePageWidgetState extends State<HomePageWidget> {
); );
} }
Widget createLocal() { Widget buildLocal() {
return wrapWithModel( return wrapWithModel(
model: _model.localComponentModel, model: _model.localComponentModel,
updateCallback: () => safeSetState(() {}), updateCallback: () => safeSetState(() {}),

View File

@ -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/flutter_flow_model.dart';
import 'package:hub/flutter_flow/request_manager.dart'; import 'package:hub/flutter_flow/request_manager.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hub/pages/liberation_history/liberation_history_widget.dart'; import 'package:hub/pages/liberation_history/liberation_history_widget.dart';
import 'package:hub/shared/helpers/db_helper.dart';
class LiberationHistoryModel extends FlutterFlowModel<LiberationHistoryWidget> { class LiberationHistoryModel extends FlutterFlowModel<LiberationHistoryWidget> {
/// 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(); final unfocusNode = FocusNode();
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode; FocusNode? textFieldFocusNode;
TextEditingController? textController; TextEditingController? textController;
String? Function(BuildContext, String?)? textControllerValidator; String? Function(BuildContext, String?)? textControllerValidator;
/// Query cache managers for this widget.
final _getLiberationsManager = StreamRequestManager<ApiCallResponse>(); final _getLiberationsManager = StreamRequestManager<ApiCallResponse>();
Stream<ApiCallResponse> getLiberations({ Stream<ApiCallResponse> getLiberations({
String? uniqueQueryKey, String? uniqueQueryKey,
@ -33,7 +33,21 @@ class LiberationHistoryModel extends FlutterFlowModel<LiberationHistoryWidget> {
_getLiberationsManager.clearRequest(uniqueKey); _getLiberationsManager.clearRequest(uniqueKey);
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
init();
}
Future<void> 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 @override
void dispose() { void dispose() {
@ -41,8 +55,6 @@ class LiberationHistoryModel extends FlutterFlowModel<LiberationHistoryWidget> {
textFieldFocusNode?.dispose(); textFieldFocusNode?.dispose();
textController?.dispose(); textController?.dispose();
/// Dispose query cache managers for this widget.
clearGetLiberationsCache(); clearGetLiberationsCache();
} }
} }

View File

@ -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_util.dart';
import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; import 'package:hub/flutter_flow/flutter_flow_widgets.dart';
import 'package:hub/flutter_flow/nav/nav.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/dialog_util.dart';
import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/log_util.dart';
import 'package:hub/shared/utils/validator_util.dart'; import 'package:hub/shared/utils/validator_util.dart';
@ -25,6 +26,7 @@ class LiberationHistoryWidget extends StatefulWidget {
} }
class _LiberationHistoryWidgetState extends State<LiberationHistoryWidget> { class _LiberationHistoryWidgetState extends State<LiberationHistoryWidget> {
late LiberationHistoryModel _model;
final scaffoldKey = GlobalKey<ScaffoldState>(); final scaffoldKey = GlobalKey<ScaffoldState>();
bool _hasData = false; bool _hasData = false;
bool _loading = false; bool _loading = false;
@ -35,6 +37,7 @@ class _LiberationHistoryWidgetState extends State<LiberationHistoryWidget> {
@override @override
void initState() { void initState() {
_requestFuture = _fetchRequests(); _requestFuture = _fetchRequests();
_model = createModel(context, () => LiberationHistoryModel());
super.initState(); super.initState();
} }
@ -49,7 +52,7 @@ class _LiberationHistoryWidgetState extends State<LiberationHistoryWidget> {
} }
String _imagePath(dynamic request) { 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<String, String> _labelsHashMap(dynamic request, bool details) { Map<String, String> _labelsHashMap(dynamic request, bool details) {
@ -326,14 +329,7 @@ class _LiberationHistoryWidgetState extends State<LiberationHistoryWidget> {
Future<ApiCallResponse?> _fetchRequests() async { Future<ApiCallResponse?> _fetchRequests() async {
try { try {
setState(() => _loading = true); setState(() => _loading = true);
var response = await PhpGroup.getLiberationsCall var response = await PhpGroup.getLiberationsCall.call().first;
.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliID: AppState().cliUUID,
atividade: 'getSolicitacoes',
)
.first;
final List<dynamic> requests = response.jsonBody['solicitacoes'] ?? []; final List<dynamic> requests = response.jsonBody['solicitacoes'] ?? [];

View File

@ -5,16 +5,16 @@ import 'package:hub/flutter_flow/request_manager.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hub/pages/message_history_page/message_history_page_widget.dart'; import 'package:hub/pages/message_history_page/message_history_page_widget.dart';
import 'package:hub/shared/helpers/db_helper.dart';
class MessageHistoryPageModel class MessageHistoryPageModel
extends FlutterFlowModel<MessageHistoryPageWidget> { extends FlutterFlowModel<MessageHistoryPageWidget> {
/// State fields for stateful widgets in this page. final DatabaseHelper db = DatabaseHelper();
/// late final String devUUID;
late final String userUUID;
//copyWith late final String cliUUID;
final unfocusNode = FocusNode(); final unfocusNode = FocusNode();
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode; FocusNode? textFieldFocusNode;
TextEditingController? textController; TextEditingController? textController;
String? Function(BuildContext, String?)? textControllerValidator; String? Function(BuildContext, String?)? textControllerValidator;
@ -23,8 +23,6 @@ class MessageHistoryPageModel
int get tabBarCurrentIndex => int get tabBarCurrentIndex =>
tabBarController != null ? tabBarController!.index : 0; tabBarController != null ? tabBarController!.index : 0;
/// Query cache managers for this widget.
final _getLiberationsManager = StreamRequestManager<ApiCallResponse>(); final _getLiberationsManager = StreamRequestManager<ApiCallResponse>();
Stream<ApiCallResponse> getLiberations({ Stream<ApiCallResponse> getLiberations({
String? uniqueQueryKey, String? uniqueQueryKey,
@ -41,7 +39,21 @@ class MessageHistoryPageModel
_getLiberationsManager.clearRequest(uniqueKey); _getLiberationsManager.clearRequest(uniqueKey);
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
init();
}
Future<void> 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 @override
void dispose() { void dispose() {
@ -50,8 +62,6 @@ class MessageHistoryPageModel
textController?.dispose(); textController?.dispose();
tabBarController?.dispose(); tabBarController?.dispose();
/// Dispose query cache managers for this widget.
clearGetLiberationsCache(); clearGetLiberationsCache();
} }
} }

View File

@ -99,10 +99,6 @@ class _MessageHistoryPageWidgetState extends State<MessageHistoryPageWidget>
setState(() => _loading = true); setState(() => _loading = true);
var response = await PhpGroup.getMessagesCall.call( var response = await PhpGroup.getMessagesCall.call(
devUUID: AppState().devUUID.toString(),
userUUID: AppState().userUUID.toString(),
cliID: AppState().cliUUID.toString(),
atividade: 'getMensagens',
pageSize: _pageSize.toString(), pageSize: _pageSize.toString(),
pageNumber: _pageNumber.toString(), pageNumber: _pageNumber.toString(),
tipoDestino: _destinyType, tipoDestino: _destinyType,

View File

@ -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_icon_button.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.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_util.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/dialog_util.dart';
import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/log_util.dart';
import 'package:hub/shared/utils/validator_util.dart'; import 'package:hub/shared/utils/validator_util.dart';
@ -27,6 +28,8 @@ class _PackageOrderPage extends State<PackageOrderPage> {
final int _pageSize = 10; final int _pageSize = 10;
bool _hasData = false; bool _hasData = false;
bool _loading = false; bool _loading = false;
final DatabaseHelper db = DatabaseHelper();
late final String cliUUID;
late Future<void> _orderFuture; late Future<void> _orderFuture;
List<dynamic> _orderList = []; List<dynamic> _orderList = [];
@ -57,6 +60,13 @@ class _PackageOrderPage extends State<PackageOrderPage> {
_loadMoreOrders(); _loadMoreOrders();
} }
}); });
initDatabase();
}
Future<void> initDatabase() async {
cliUUID = await db
.get(key: 'cliUUID', field: 'value')
.then((value) => value.toString());
} }
@override @override
@ -85,10 +95,6 @@ class _PackageOrderPage extends State<PackageOrderPage> {
setState(() => _loading = true); setState(() => _loading = true);
var response = await PhpGroup.buscaEnconcomendas.call( var response = await PhpGroup.buscaEnconcomendas.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliID: AppState().cliUUID,
atividade: 'getEncomendas',
pageSize: _pageSize.toString(), pageSize: _pageSize.toString(),
page: _pageNumber.toString(), page: _pageNumber.toString(),
adresseeType: _adresseeType == '.*' ? 'TOD' : _adresseeType, adresseeType: _adresseeType == '.*' ? 'TOD' : _adresseeType,
@ -300,7 +306,7 @@ class _PackageOrderPage extends State<PackageOrderPage> {
} }
String _imagePath(dynamic order) { 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<String, String> _labelsHashMap(dynamic order) { Map<String, String> _labelsHashMap(dynamic order) {

View File

@ -84,12 +84,7 @@ class _PeopleOnThePropertyPageWidgetState
body: SafeArea( body: SafeArea(
top: true, top: true,
child: FutureBuilder<ApiCallResponse>( child: FutureBuilder<ApiCallResponse>(
future: PhpGroup.getPessoasLocalCall.call( future: PhpGroup.getPessoasLocalCall.call(),
cliID: AppState().cliUUID,
ownID: AppState().ownerUUID,
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
),
builder: (context, snapshot) { builder: (context, snapshot) {
// Customize what your widget looks like when it's loading. // Customize what your widget looks like when it's loading.
if (!snapshot.hasData) { if (!snapshot.hasData) {

View File

@ -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/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_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.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/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/dialog_util.dart';
import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/log_util.dart';
import 'package:hub/shared/utils/validator_util.dart'; import 'package:hub/shared/utils/validator_util.dart';
class PetsHistoryScreen extends StatefulWidget { class PetsHistoryScreen extends StatefulWidget {
PetsHistoryScreen({Key? key}) : super(key: key); PetsHistoryScreen({Key? key, required this.model}) : super(key: key);
final PetsPageModel model;
@override @override
_PetsHistoryScreenState createState() => _PetsHistoryScreenState(); _PetsHistoryScreenState createState() => _PetsHistoryScreenState();
@ -20,6 +25,7 @@ class PetsHistoryScreen extends StatefulWidget {
class _PetsHistoryScreenState extends State<PetsHistoryScreen> class _PetsHistoryScreenState extends State<PetsHistoryScreen>
with TickerProviderStateMixin { with TickerProviderStateMixin {
late ScrollController _scrollController; late ScrollController _scrollController;
int _pageNumber = 1; int _pageNumber = 1;
final int _pageSize = 10; final int _pageSize = 10;
bool _hasData = false; bool _hasData = false;
@ -32,6 +38,7 @@ class _PetsHistoryScreenState extends State<PetsHistoryScreen>
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_petsFuture = _fetchVisits(); _petsFuture = _fetchVisits();
_scrollController = ScrollController() _scrollController = ScrollController()
@ -54,10 +61,6 @@ class _PetsHistoryScreenState extends State<PetsHistoryScreen>
setState(() => _loading = true); setState(() => _loading = true);
var response = await PhpGroup.getPets.call( var response = await PhpGroup.getPets.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliID: AppState().cliUUID,
atividade: 'consultaPets',
pageSize: _pageSize, pageSize: _pageSize,
page: _pageNumber, page: _pageNumber,
); );
@ -151,10 +154,10 @@ class _PetsHistoryScreenState extends State<PetsHistoryScreen>
return Padding( return Padding(
padding: EdgeInsets.only(right: 30, top: 10), padding: EdgeInsets.only(right: 30, top: 10),
child: Text( child: Text(
AppState().petAmountRegister == 0 widget.model.petAmountRegister == '0'
? FFLocalizations.of(context).getVariableText( ? FFLocalizations.of(context).getVariableText(
ptText: "Ilimitado", enText: "Unlimited") 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, textAlign: TextAlign.right,
), ),
); );
@ -183,7 +186,7 @@ class _PetsHistoryScreenState extends State<PetsHistoryScreen>
Widget _item(BuildContext context, dynamic uItem) { Widget _item(BuildContext context, dynamic uItem) {
return CardItemTemplateComponentWidget( return CardItemTemplateComponentWidget(
imagePath: 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: { labelsHashMap: {
'${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:': '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:':
uItem['name'] ?? '', uItem['name'] ?? '',
@ -242,6 +245,19 @@ class _PetsHistoryScreenState extends State<PetsHistoryScreen>
} }
], ],
onTapCardItemAction: () async { 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( await showDialog(
useSafeArea: true, useSafeArea: true,
context: context, context: context,
@ -249,9 +265,14 @@ class _PetsHistoryScreenState extends State<PetsHistoryScreen>
return Dialog( return Dialog(
alignment: Alignment.center, alignment: Alignment.center,
child: buildPetDetails( child: buildPetDetails(
uItem, item: uItem,
context, context: context,
changeStatusAction, changeStatusAction: changeStatusAction,
devUUID: devUUID,
userUUID: userUUID,
cliUUID: cliUUID,
cliName: cliName,
model: widget.model,
), ),
); );
}, },

View File

@ -1,20 +1,33 @@
import 'dart:convert';
import 'dart:developer'; import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart'; 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_calls.dart';
import 'package:hub/backend/api_requests/api_manager.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/flutter_flow_util.dart';
import 'package:hub/flutter_flow/form_field_controller.dart'; import 'package:hub/flutter_flow/form_field_controller.dart';
import 'package:hub/pages/pets_page/pets_page_widget.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/dialog_util.dart';
import 'package:hub/shared/utils/log_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; import '/custom_code/actions/index.dart' as actions;
class PetsPageModel extends FlutterFlowModel<PetsPageWidget> { class PetsPageModel extends FlutterFlowModel<PetsPageWidget> {
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; late final TabController tabBarController;
VoidCallback? onUpdatePet; VoidCallback? onUpdatePet;
VoidCallback? onRegisterPet; VoidCallback? onRegisterPet;
VoidCallback? safeSetState; VoidCallback? safeSetState;
VoidCallback? updateImage;
final GlobalKey<FormState> registerFormKey = GlobalKey<FormState>(); final GlobalKey<FormState> registerFormKey = GlobalKey<FormState>();
final GlobalKey<FormState> updateFormKey = GlobalKey<FormState>(); final GlobalKey<FormState> updateFormKey = GlobalKey<FormState>();
@ -24,19 +37,17 @@ class PetsPageModel extends FlutterFlowModel<PetsPageWidget> {
BuildContext? buildContext; BuildContext? buildContext;
bool isEditing = false; bool isEditing = false;
// Controller para o Upload de Arquivos
bool isDataUploading = false; bool isDataUploading = false;
FFUploadedFile? uploadedLocalFile; FFUploadedFile? uploadedLocalFile;
FFUploadedFile? uploadedTempFile;
String? imgBase64; String? imgBase64;
// Controller para o DropDown
String? dropDownValue1; String? dropDownValue1;
FormFieldController<String>? dropDownValueController1; FormFieldController<String>? dropDownValueController1;
String? dropDownValue2; String? dropDownValue2;
FormFieldController<String>? dropDownValueController2; FormFieldController<String>? dropDownValueController2;
// Controller para o TextField
FocusNode? textFieldFocusName; FocusNode? textFieldFocusName;
TextEditingController? textControllerName; TextEditingController? textControllerName;
String? textControllerNameValidator(BuildContext context, String? val) { String? textControllerNameValidator(BuildContext context, String? val) {
@ -88,9 +99,25 @@ class PetsPageModel extends FlutterFlowModel<PetsPageWidget> {
TextEditingController? textControllerObservation; TextEditingController? textControllerObservation;
String? Function(BuildContext, String?)? textControllerObservationValidator; String? Function(BuildContext, String?)? textControllerObservationValidator;
Future<void> 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 @override
void initState(BuildContext context) { void initState(BuildContext context) {
// Se liga! Esse é o controller do TabBar
tabBarController = TabController( tabBarController = TabController(
vsync: Navigator.of(context), vsync: Navigator.of(context),
length: 2, length: 2,
@ -98,8 +125,6 @@ class PetsPageModel extends FlutterFlowModel<PetsPageWidget> {
textFieldFocusName = FocusNode(); textFieldFocusName = FocusNode();
textControllerName = TextEditingController(); textControllerName = TextEditingController();
// textControllerNameValidator =
// (context, value) => _textControllerNameValidator(context, value);
textFieldFocusSpecies = FocusNode(); textFieldFocusSpecies = FocusNode();
textControllerSpecies = TextEditingController(); textControllerSpecies = TextEditingController();
@ -125,6 +150,66 @@ class PetsPageModel extends FlutterFlowModel<PetsPageWidget> {
dropDownValueController2 = dropDownValueController2 =
FormFieldController<String>(dropDownValue2 ??= 'Selecione uma opção'); FormFieldController<String>(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<String>(dropDownValue1);
dropDownValueController2 = FormFieldController<String>(dropDownValue2);
} }
@override @override
@ -153,7 +238,6 @@ class PetsPageModel extends FlutterFlowModel<PetsPageWidget> {
dropDownValueController2?.dispose(); dropDownValueController2?.dispose();
} }
// Validador do formulário
bool isFormValid(BuildContext context) { bool isFormValid(BuildContext context) {
if (uploadedLocalFile == null || uploadedLocalFile!.bytes!.isEmpty) { if (uploadedLocalFile == null || uploadedLocalFile!.bytes!.isEmpty) {
return false; return false;
@ -185,15 +269,11 @@ class PetsPageModel extends FlutterFlowModel<PetsPageWidget> {
} }
Future<void> updatePet() async { Future<void> updatePet() async {
final img = await actions.convertImageFileToBase64(uploadedLocalFile!); var img = await actions.convertImageFileToBase64(uploadedLocalFile!);
final imgBase64 = "base64;jpeg,$img"; img = "base64;jpeg,$img";
final url = final url =
'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=${devUUID}&userUUID=${userUUID}&cliID=${cliUUID}&atividade=consultaFotoPet&petId=$petId';
final response = await PhpGroup.updatePet.call( final response = await PhpGroup.updatePet.call(
cliID: AppState().cliUUID,
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
petID: petId, petID: petId,
image: imgBase64, image: imgBase64,
birthdayDate: textControllerData!.text, birthdayDate: textControllerData!.text,
@ -234,14 +314,10 @@ class PetsPageModel extends FlutterFlowModel<PetsPageWidget> {
} }
Future<void> registerPet() async { Future<void> registerPet() async {
final img = await actions.convertImageFileToBase64(uploadedLocalFile!); var img = await actions.convertImageFileToBase64(uploadedLocalFile!);
final imgBase64 = "base64;jpeg,$img"; img = "base64;jpeg,$img";
final response = await PhpGroup.registerPet.call( final response = await PhpGroup.registerPet.call(
cliID: AppState().cliUUID, image: img,
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
image: imgBase64,
birthdayDate: textControllerData!.text, birthdayDate: textControllerData!.text,
color: textControllerColor!.text, color: textControllerColor!.text,
breed: textControllerRace!.text, breed: textControllerRace!.text,
@ -283,6 +359,7 @@ class PetsPageModel extends FlutterFlowModel<PetsPageWidget> {
void switchTab(int index) { void switchTab(int index) {
tabBarController.animateTo(index); tabBarController.animateTo(index);
if (index == 1) handleEditingChanged(false); if (index == 1) handleEditingChanged(false);
safeSetState?.call();
} }
void handleUploadComplete(FFUploadedFile uploadedFile) { void handleUploadComplete(FFUploadedFile uploadedFile) {

View File

@ -55,8 +55,9 @@ class _PetsPageWidgetState extends State<PetsPageWidget>
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_model = PetsPageModel(); _model = createModel(context, () => PetsPageModel());
_model.tabBarController = TabController(length: 2, vsync: this); _model.updateOnChange = true;
_model.onUpdatePet = () { _model.onUpdatePet = () {
safeSetState(() { safeSetState(() {
_model.clearFields(); _model.clearFields();
@ -70,10 +71,9 @@ class _PetsPageWidgetState extends State<PetsPageWidget>
_model.safeSetState = () { _model.safeSetState = () {
safeSetState(() {}); safeSetState(() {});
}; };
_model.updateImage = () => setState(() {
widget.pet != null ? _model.isEditing = true : _model.isEditing = false; _model.handleUploadComplete(_model.uploadedTempFile!);
});
// _handleUploadComplete(actions.convertToUploadFile())
if (widget.pet != null) { if (widget.pet != null) {
int petId = widget.pet['id']; int petId = widget.pet['id'];
@ -81,7 +81,7 @@ class _PetsPageWidgetState extends State<PetsPageWidget>
(() async { (() async {
Response response = await get(Uri.parse( 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); String base64 = base64Encode(response.bodyBytes);
FFUploadedFile uploadedFile = await convertToUploadFile(base64); FFUploadedFile uploadedFile = await convertToUploadFile(base64);
setState(() { setState(() {
@ -178,7 +178,7 @@ class _PetsPageWidgetState extends State<PetsPageWidget>
widget1: _model.isEditing widget1: _model.isEditing
? _buildEditForm(context) ? _buildEditForm(context)
: _buildRegisterForm(context), : _buildRegisterForm(context),
widget2: PetsHistoryScreen(), widget2: PetsHistoryScreen(model: _model),
onEditingChanged: onEditingChanged, onEditingChanged: onEditingChanged,
); );
} }

View File

@ -1,15 +1,28 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.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_icon_button.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.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/internationalization.dart';
import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/pages/preferences_settings_page/preferences_settings_model.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'; import 'package:provider/provider.dart';
class PreferencesPageWidget extends StatelessWidget { class PreferencesPageWidget extends StatefulWidget {
const PreferencesPageWidget({super.key}); PreferencesPageWidget();
@override
_PreferencesPageWidgetState createState() => _PreferencesPageWidgetState();
}
class _PreferencesPageWidgetState extends State<PreferencesPageWidget> {
final DatabaseHelper db = DatabaseHelper();
@override
void initState() {
super.initState();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -65,7 +78,7 @@ class PreferencesPageWidget extends StatelessWidget {
Expanded( Expanded(
flex: 2, flex: 2,
child: ListView.builder( child: ListView.builder(
itemCount: 7, // Assuming 4 items for simplicity itemCount: 7, // Assuming 7 items for simplicity
padding: const EdgeInsets.symmetric(horizontal: 20.0), padding: const EdgeInsets.symmetric(horizontal: 20.0),
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
itemBuilder: (BuildContext context, int index) { itemBuilder: (BuildContext context, int index) {
@ -91,9 +104,8 @@ class PreferencesPageWidget extends StatelessWidget {
switch (index) { switch (index) {
case 0: case 0:
icon = Icons.fingerprint; icon = Icons.fingerprint;
onPressed = () => onPressed = () => model.toggleFingerprint(context);
model.toggleFingerprint(context); // Disable if fingerprint is false isEnabled = model.fingerprint;
isEnabled = AppState().fingerprint;
content = FFLocalizations.of(context).getVariableText( content = FFLocalizations.of(context).getVariableText(
ptText: ptText:
'Ative a autenticação por impressão digital para login seguro.', 'Ative a autenticação por impressão digital para login seguro.',
@ -103,7 +115,7 @@ class PreferencesPageWidget extends StatelessWidget {
case 1: case 1:
icon = Icons.person; icon = Icons.person;
onPressed = () => model.enablePerson(context); onPressed = () => model.enablePerson(context);
isEnabled = AppState().person; isEnabled = model.person;
content = FFLocalizations.of(context).getVariableText( content = FFLocalizations.of(context).getVariableText(
ptText: 'Compartilhe o código de identificação remota', ptText: 'Compartilhe o código de identificação remota',
enText: 'Share the remote identification code', enText: 'Share the remote identification code',
@ -112,7 +124,7 @@ class PreferencesPageWidget extends StatelessWidget {
case 2: case 2:
icon = Icons.notifications; icon = Icons.notifications;
onPressed = () => model.toggleNotify(context); onPressed = () => model.toggleNotify(context);
isEnabled = AppState().notify; isEnabled = model.notify;
content = FFLocalizations.of(context).getVariableText( content = FFLocalizations.of(context).getVariableText(
ptText: 'Ative para receber sua notificação de acesso', ptText: 'Ative para receber sua notificação de acesso',
enText: 'Enable to receive your access notification', enText: 'Enable to receive your access notification',
@ -120,8 +132,8 @@ class PreferencesPageWidget extends StatelessWidget {
break; break;
case 3: case 3:
icon = Icons.lock; icon = Icons.lock;
// onLongPress = model.togglePass(context, model); onPressed = () => model.toggleAccess(context);
isEnabled = AppState().pass; isEnabled = model.access;
content = FFLocalizations.of(context).getVariableText( content = FFLocalizations.of(context).getVariableText(
ptText: 'Ative para inserir uma credencial de acesso para o QRCode', ptText: 'Ative para inserir uma credencial de acesso para o QRCode',
enText: 'Enable to enter an access credential for the QRCode', enText: 'Enable to enter an access credential for the QRCode',
@ -129,11 +141,11 @@ class PreferencesPageWidget extends StatelessWidget {
break; break;
case 4: case 4:
icon = Icons.lock_clock_sharp; icon = Icons.lock_clock_sharp;
// onLongPress = model.togglePass(context, model); onPressed = () => model.togglePanic(context);
isEnabled = AppState().panic; isEnabled = model.panic;
content = FFLocalizations.of(context).getVariableText( content = FFLocalizations.of(context).getVariableText(
ptText: 'Ative para inserir uma credencial de pânico para o QRCode', 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; break;
case 5: case 5:
@ -177,7 +189,7 @@ class PreferencesPageWidget extends StatelessWidget {
onTap: () { onTap: () {
switch (index) { switch (index) {
case 3: case 3:
model.togglePass(context); model.toggleAccess(context);
break; break;
case 4: case 4:
model.togglePanic(context); model.togglePanic(context);
@ -197,14 +209,6 @@ class PreferencesPageWidget extends StatelessWidget {
color: isEnabled color: isEnabled
? FlutterFlowTheme.of(context).primaryBackground ? FlutterFlowTheme.of(context).primaryBackground
: FlutterFlowTheme.of(context).primary, : 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), 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: <String, dynamic>{
kTransitionInfoKey: const TransitionInfo(
hasTransition: true,
transitionType: PageTransitionType.scale,
alignment: Alignment.bottomCenter,
),
},
);
});
}
} }

View File

@ -17,20 +17,15 @@ class ProvisionalSchedule extends StatefulWidget {
} }
class _ProvisionalScheduleState extends State<ProvisionalSchedule> { class _ProvisionalScheduleState extends State<ProvisionalSchedule> {
late ScheduleProvisionalVisitPageModel _model;
final scaffoldKey = GlobalKey<ScaffoldState>(); final scaffoldKey = GlobalKey<ScaffoldState>();
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_model = createModel(context, () => ScheduleProvisionalVisitPageModel());
} }
@override @override
void dispose() { void dispose() {
_model.dispose();
super.dispose(); super.dispose();
} }

View File

@ -2,6 +2,7 @@ import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hub/flutter_flow/flutter_flow_model.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/pages/qr_code_page/qr_code_page_widget.dart';
import 'package:hub/shared/helpers/db_helper.dart';
class QrCodePageModel extends FlutterFlowModel<QrCodePageWidget> { class QrCodePageModel extends FlutterFlowModel<QrCodePageWidget> {
/// Local state fields for this page. /// Local state fields for this page.
@ -11,13 +12,27 @@ class QrCodePageModel extends FlutterFlowModel<QrCodePageWidget> {
String? key = null; String? key = null;
DateTime? time; DateTime? time;
final DatabaseHelper db = DatabaseHelper();
late final bool isFingerprint;
late final String userDevUUID;
/// State fields for stateful widgets in this page. /// State fields for stateful widgets in this page.
final unfocusNode = FocusNode(); final unfocusNode = FocusNode();
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
initVariable();
}
Future<void> 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 @override
void dispose() { void dispose() {

View File

@ -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/flutter_flow_widgets.dart';
import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/pages/qr_code_page/qr_code_page_model.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/circular_percent_indicator.dart';
// import 'package:percent_indicator/percent_indicator.dart'; // import 'package:percent_indicator/percent_indicator.dart';
@ -140,14 +141,15 @@ class _QrCodePageWidgetState extends State<QrCodePageWidget>
safeSetState(() async { safeSetState(() async {
_resetAnimationAndToggleAccess(); _resetAnimationAndToggleAccess();
}); });
AppState().fingerprint
_model.isFingerprint
? await _showBiometricsAuth(context) ? await _showBiometricsAuth(context)
: await _showQrCodeBottomSheet(context); : await _showQrCodeBottomSheet(context);
}, },
child: buildQrCode( child: buildQrCode(
dimension: dimension, dimension: dimension,
errorCorrectLevel: QrErrorCorrectLevel.M, errorCorrectLevel: QrErrorCorrectLevel.M,
identifier: AppState().userDevUUID, identifier: _model.userDevUUID,
pass: _model.key!, pass: _model.key!,
direction: 5, direction: 5,
), ),
@ -195,7 +197,7 @@ class _QrCodePageWidgetState extends State<QrCodePageWidget>
alignment: const AlignmentDirectional(0.0, 0.0), alignment: const AlignmentDirectional(0.0, 0.0),
child: FFButtonWidget( child: FFButtonWidget(
onPressed: () async { onPressed: () async {
AppState().fingerprint _model.isFingerprint
? await _showBiometricsAuth(context) ? await _showBiometricsAuth(context)
: await _showQrCodeBottomSheet(context); : await _showQrCodeBottomSheet(context);
}, },

View File

@ -1,16 +1,21 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hub/app_state.dart'; import 'package:hub/app_state.dart';
import 'package:hub/flutter_flow/internationalization.dart'; import 'package:hub/flutter_flow/internationalization.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
class ReceptionPageModel with ChangeNotifier { class ReceptionPageModel with ChangeNotifier {
void getIdenfifier(BuildContext context) { Future<void> getIdenfifier(BuildContext context) async {
final DatabaseHelper db = DatabaseHelper();
final String userDevUUID = await db
.get(key: 'userDevUUID', field: 'value')
.then((value) => value.toString());
notifyListeners(); notifyListeners();
Share.share( Share.share(
FFLocalizations.of(context).getVariableText( FFLocalizations.of(context).getVariableText(
ptText: ptText: 'Este é o meu identificador de acesso: ${userDevUUID}',
'Este é o meu identificador de acesso: ${AppState().userDevUUID}', enText: 'This is my access identifier: ${userDevUUID}',
enText: 'This is my access identifier: ${AppState().userDevUUID}',
), ),
); );
} }

View File

@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.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/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_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart';
@ -141,6 +142,7 @@ class _ReceptionPageWidgetState extends State<ReceptionPageWidget> {
padding: const EdgeInsets.fromLTRB(60, 0, 60, 0), padding: const EdgeInsets.fromLTRB(60, 0, 60, 0),
child: FFButtonWidget( child: FFButtonWidget(
onPressed: () async { onPressed: () async {
PhpGroup.unregisterDevice();
AppState().deleteAll(); AppState().deleteAll();
setState(() {}); setState(() {});

View File

@ -4,50 +4,87 @@ import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart'; import 'package:flutter/scheduler.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:hub/app_state.dart'; import 'package:hub/app_state.dart';
import 'package:hub/flutter_flow/internationalization.dart';
import 'package:hub/flutter_flow/nav/nav.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:hub/shared/utils/webview_util.dart';
import 'package:sqflite/sqflite.dart';
import 'package:url_launcher/url_launcher_string.dart'; import 'package:url_launcher/url_launcher_string.dart';
import 'package:webview_flutter/webview_flutter.dart'; import 'package:webview_flutter/webview_flutter.dart';
class ReservationPageWidget extends StatefulWidget { 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 @override
_ReservationPageWidgetState createState() => _ReservationPageWidgetState(); _ReservationPageWidgetState createState() => _ReservationPageWidgetState();
} }
class _ReservationPageWidgetState extends State<ReservationPageWidget> { class _ReservationPageWidgetState extends State<ReservationPageWidget> {
final DatabaseHelper db = DatabaseHelper();
late InAppWebViewController _controllerIOS; late InAppWebViewController _controllerIOS;
late WebViewController _controllerAll; late WebViewController _controllerAll;
late String url;
late String name;
late String email;
late String userUUID;
late String created_at;
@override Future<Map<String, String>> initVariables() async {
void initState() { final email = await db
super.initState(); .get(key: 'email', field: 'value')
name = AppState().name; .then((value) => value.toString());
email = AppState().email; final name = await db
userUUID = AppState().userUUID; .get(key: 'userName', field: 'value')
created_at = AppState().createdAt; .then((value) => value.toString());
url = 'https://hub.freaccess.com.br/hub/reservation/${widget.clientId}'; 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return SafeArea( return SafeArea(
child: Scaffold( child: Scaffold(
body: Platform.isIOS body: FutureBuilder<Map<String, String>>(
future: initVariables(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError ||
snapshot.hasData == false ||
snapshot.data!.isEmpty) {
return Center(
child: Text(FFLocalizations.of(context).getVariableText(
enText: 'Unexpected error', ptText: 'Erro inesperado')));
} else if (snapshot.hasData) {
final data = snapshot.data!;
final url = data['url']!;
final userUUID = data['userUUID']!;
final freUserData = data['freUserData']!;
return Platform.isIOS
? InAppWebView( ? InAppWebView(
initialUrlRequest: URLRequest(url: WebUri(url)), initialUrlRequest: URLRequest(url: WebUri(url)),
initialSettings: InAppWebViewSettings( initialSettings: InAppWebViewSettings(
@ -60,10 +97,10 @@ class _ReservationPageWidgetState extends State<ReservationPageWidget> {
onLoadStop: (controller, url) async { onLoadStop: (controller, url) async {
await controller.evaluateJavascript( await controller.evaluateJavascript(
source: source:
"window.localStorage.setItem('fre-token', '\"${widget.freToken}\"')"); "window.localStorage.setItem('fre-token', '\"$userUUID\"')");
await controller.evaluateJavascript( await controller.evaluateJavascript(
source: source:
"window.localStorage.setItem('fre-user-data', '${widget.freUserData}')"); "window.localStorage.setItem('fre-user-data', '$freUserData')");
await controller.evaluateJavascript( await controller.evaluateJavascript(
source: source:
"window.localStorage.setItem('enableBackButton', 'true')"); "window.localStorage.setItem('enableBackButton', 'true')");
@ -85,9 +122,9 @@ class _ReservationPageWidgetState extends State<ReservationPageWidget> {
onProgress: (int progress) {}, onProgress: (int progress) {},
onPageStarted: (String url) { onPageStarted: (String url) {
final String token = final String token =
"localStorage.setItem('fre-token', '\"${widget.freToken}\"');"; "localStorage.setItem('fre-token', '\"$userUUID\"');";
final String data = final String data =
"localStorage.setItem('fre-user-data', '${widget.freUserData}');"; "localStorage.setItem('fre-user-data', '$freUserData');";
const String backNavigation = const String backNavigation =
"localStorage.setItem('enableBackButton', 'true');"; "localStorage.setItem('enableBackButton', 'true');";
@ -96,13 +133,15 @@ class _ReservationPageWidgetState extends State<ReservationPageWidget> {
_controllerAll.runJavaScript(backNavigation); _controllerAll.runJavaScript(backNavigation);
}, },
onPageFinished: (String url) { onPageFinished: (String url) {
bool isDarkMode = SchedulerBinding.instance bool isDarkMode = SchedulerBinding
.platformDispatcher.platformBrightness == .instance
.platformDispatcher
.platformBrightness ==
Brightness.dark; Brightness.dark;
if (isDarkMode) { if (isDarkMode) {
_controllerAll _controllerAll.runJavaScript(
.runJavaScript(WebviewUtil.jsEnableDarkMode); WebviewUtil.jsEnableDarkMode);
} }
}, },
onNavigationRequest: (NavigationRequest request) { onNavigationRequest: (NavigationRequest request) {
@ -122,6 +161,11 @@ class _ReservationPageWidgetState extends State<ReservationPageWidget> {
}), }),
) )
..loadRequest(Uri.parse(url)), ..loadRequest(Uri.parse(url)),
);
} else {
return Center(child: Text('Unexpected error'));
}
},
), ),
), ),
); );

View File

@ -9,11 +9,17 @@ import 'package:hub/flutter_flow/request_manager.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.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'; import 'package:intl/intl.dart';
class ScheduleCompleteVisitPageModel class ScheduleCompleteVisitPageModel
extends FlutterFlowModel<ScheduleCompleteVisitPageWidget> { extends FlutterFlowModel<ScheduleCompleteVisitPageWidget> {
final _visitHistoryManager = FutureRequestManager<ApiCallResponse>(); final _visitHistoryManager = FutureRequestManager<ApiCallResponse>();
final DatabaseHelper db = DatabaseHelper();
late final String devUUID;
late final String cliUUID;
late final String userUUID;
Future<ApiCallResponse> visitHistory({ Future<ApiCallResponse> visitHistory({
String? uniqueQueryKey, String? uniqueQueryKey,
bool? overrideCache, bool? overrideCache,
@ -187,8 +193,21 @@ class ScheduleCompleteVisitPageModel
return null; return null;
} }
Future<void> _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 @override
void initState(BuildContext context) { void initState(BuildContext context) {
_initVariables();
tabBarController = TabController( tabBarController = TabController(
vsync: Navigator.of(context), vsync: Navigator.of(context),
length: 2, length: 2,

View File

@ -868,7 +868,7 @@ Widget scheduleVisit(BuildContext context,
fadeOutDuration: fadeOutDuration:
const Duration(milliseconds: 500), const Duration(milliseconds: 500),
imageUrl: 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, fit: BoxFit.cover,
), ),
), ),
@ -1081,12 +1081,7 @@ Widget scheduleVisit(BuildContext context,
height: 45.0, height: 45.0,
decoration: const BoxDecoration(), decoration: const BoxDecoration(),
child: FutureBuilder<ApiCallResponse>( child: FutureBuilder<ApiCallResponse>(
future: PhpGroup.getDadosCall.call( future: PhpGroup.getDadosCall.call(),
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliUUID: AppState().cliUUID,
atividade: 'getDados',
),
builder: (context, snapshot) { builder: (context, snapshot) {
if (!snapshot.hasData) { if (!snapshot.hasData) {
return Center( return Center(
@ -1232,12 +1227,7 @@ Widget scheduleVisit(BuildContext context,
height: 45.0, height: 45.0,
decoration: const BoxDecoration(), decoration: const BoxDecoration(),
child: FutureBuilder<ApiCallResponse>( child: FutureBuilder<ApiCallResponse>(
future: PhpGroup.getDadosCall.call( future: PhpGroup.getDadosCall.call(),
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliUUID: AppState().cliUUID,
atividade: 'getDados',
),
builder: (context, snapshot) { builder: (context, snapshot) {
// Customize what your widget looks like when it's loading. // Customize what your widget looks like when it's loading.
if (!snapshot.hasData) { if (!snapshot.hasData) {
@ -1612,9 +1602,6 @@ Widget scheduleVisit(BuildContext context,
Future<void> scheduleVisit() async { Future<void> scheduleVisit() async {
await PhpGroup.postScheduleVisitCall await PhpGroup.postScheduleVisitCall
.call( .call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
atividade: 'putVisita',
devDesc: _model.textController3.text, devDesc: _model.textController3.text,
idVisitante: _model.visitorStrList, idVisitante: _model.visitorStrList,
dtInicio: _model dtInicio: _model
@ -1625,7 +1612,6 @@ Widget scheduleVisit(BuildContext context,
idMotivo: extractIdToStr(_model.dropDownValue1!), idMotivo: extractIdToStr(_model.dropDownValue1!),
idNAC: extractIdToStr(_model.dropDownValue2!), idNAC: extractIdToStr(_model.dropDownValue2!),
obs: _model.textController3.text, obs: _model.textController3.text,
cliID: AppState().cliUUID,
) )
.catchError((e) async { .catchError((e) async {
await DialogUtil.errorDefault(context); await DialogUtil.errorDefault(context);
@ -1719,7 +1705,7 @@ Widget scheduleVisit(BuildContext context,
), ),
], ],
imagePath: 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: { labelsHashMap: {
'Nome': _model.visitorJsonList[0]['VTE_NOME'], 'Nome': _model.visitorJsonList[0]['VTE_NOME'],
'Start': _model.textController1.text, 'Start': _model.textController1.text,

View File

@ -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_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.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/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/dialog_util.dart';
import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/log_util.dart';
import 'package:hub/shared/utils/validator_util.dart'; import 'package:hub/shared/utils/validator_util.dart';
@ -19,6 +20,10 @@ class VisitHistoryWidget extends StatefulWidget {
class _VisitHistoryWidgetState extends State<VisitHistoryWidget> class _VisitHistoryWidgetState extends State<VisitHistoryWidget>
with TickerProviderStateMixin { with TickerProviderStateMixin {
final DatabaseHelper db = DatabaseHelper();
late final String devUUID;
late final String userUUID;
late final String cliUUID;
late ScrollController _scrollController; late ScrollController _scrollController;
int _pageNumber = 1; int _pageNumber = 1;
final int _pageSize = 10; final int _pageSize = 10;
@ -28,9 +33,22 @@ class _VisitHistoryWidgetState extends State<VisitHistoryWidget>
late Future<void> _visitFuture; late Future<void> _visitFuture;
List<dynamic> _visitWrap = []; List<dynamic> _visitWrap = [];
Future<void> _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 @override
void initState() { void initState() {
super.initState(); super.initState();
_initVariables();
_visitFuture = _fetchVisits(); _visitFuture = _fetchVisits();
_scrollController = ScrollController() _scrollController = ScrollController()
@ -54,10 +72,6 @@ class _VisitHistoryWidgetState extends State<VisitHistoryWidget>
var response = await ScheduleCompleteVisitPageModel().visitHistory( var response = await ScheduleCompleteVisitPageModel().visitHistory(
requestFn: () => PhpGroup.getVisitsCall.call( requestFn: () => PhpGroup.getVisitsCall.call(
devUUID: AppState().devUUID,
userUUID: AppState().userUUID,
cliID: AppState().cliUUID,
atividade: 'getVisitas',
pageSize: _pageSize, pageSize: _pageSize,
pageNumber: _pageNumber, pageNumber: _pageNumber,
), ),
@ -168,7 +182,7 @@ class _VisitHistoryWidgetState extends State<VisitHistoryWidget>
Widget _item(BuildContext context, dynamic visitaWrapItem) { Widget _item(BuildContext context, dynamic visitaWrapItem) {
return CardItemTemplateComponentWidget( return CardItemTemplateComponentWidget(
imagePath: 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: { labelsHashMap: {
'${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:': '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:':
visitaWrapItem['VTE_NOME'] ?? '', visitaWrapItem['VTE_NOME'] ?? '',
@ -230,6 +244,19 @@ class _VisitHistoryWidgetState extends State<VisitHistoryWidget>
}, },
], ],
onTapCardItemAction: () async { 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( await showDialog(
useSafeArea: true, useSafeArea: true,
context: context, context: context,
@ -237,9 +264,13 @@ class _VisitHistoryWidgetState extends State<VisitHistoryWidget>
return Dialog( return Dialog(
alignment: Alignment.center, alignment: Alignment.center,
child: buildVisitDetails( child: buildVisitDetails(
visitaWrapItem, item: visitaWrapItem,
context, context: context,
changeStatusAction, changeStatusAction: changeStatusAction,
devUUID: devUUID,
userUUID: userUUID,
cliUUID: cliUUID,
cliName: cliName,
), ),
); );
}, },

View File

@ -28,13 +28,13 @@ class _WelcomePageWidgetState extends State<WelcomePageWidget> {
// On page load action. // On page load action.
SchedulerBinding.instance.addPostFrameCallback((_) async { SchedulerBinding.instance.addPostFrameCallback((_) async {
if (isAndroid == true) { if (isAndroid == true) {
AppState().device = 'Android'; AppState().deviceType = 'Android';
setState(() {}); setState(() {});
} else if (isiOS == true) { } else if (isiOS == true) {
AppState().device = 'iOS'; AppState().deviceType = 'iOS';
setState(() {}); setState(() {});
} else { } else {
AppState().device = 'Web'; AppState().deviceType = 'Web';
setState(() {}); setState(() {});
} }
}); });

View File

@ -0,0 +1,240 @@
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseConfig {
static const String dbName = 'database.db';
static const int dbVersion = 1;
static const String tableKeychain = 'keychain';
static const String columnKey = 'key';
static const String columnValue = 'value';
static const String columnType = 'type';
static const String columnUpdateAt = 'updateAt';
static const String columnResolvedAt = 'resolvedAt';
static const String columnCreatedAt = 'createdAt';
}
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
static Database? _database;
factory DatabaseHelper() => _instance;
DatabaseHelper._internal();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
final path = await _getDatabasePath();
log('Database path: $path');
return await openDatabase(
path,
version: DatabaseConfig.dbVersion,
onCreate: _onCreate,
onOpen: _onOpen,
onUpgrade: _onUpgrade,
onDowngrade: _onDowngrade,
onConfigure: _onConfigure,
).catchError((error) {
throw error;
}).whenComplete(() => log('Database initialized'));
}
Future<String> _getDatabasePath() async {
final databasesPath = await getDatabasesPath();
final path = join(databasesPath, DatabaseConfig.dbName);
log('Database path: $path');
return path;
}
Future<void> _onCreate(Database db, int version) async {
log('Creating tables...');
await db.execute('''
CREATE TABLE ${DatabaseConfig.tableKeychain} (
${DatabaseConfig.columnKey} TEXT UNIQUE,
${DatabaseConfig.columnValue} TEXT,
${DatabaseConfig.columnType} TEXT,
${DatabaseConfig.columnUpdateAt} TEXT,
${DatabaseConfig.columnResolvedAt} TEXT,
${DatabaseConfig.columnCreatedAt} TEXT
);
''');
await _insertInitialData(db);
log('Tables created');
}
Future<void> _insertInitialData(Database db) async {
final initialData = [
{'key': 'devUUID', 'value': '', 'type': 'user'},
{'key': 'userUUID', 'value': '', 'type': 'user'},
{'key': 'userDevUUID', 'value': '', 'type': 'user'},
{'key': 'status', 'value': '', 'type': 'user'},
{'key': 'userName', 'value': '', 'type': 'user'},
{'key': 'cliUUID', 'value': '', 'type': 'local'},
{'key': 'ownerUUID', 'value': '', 'type': 'local'},
{'key': 'cliName', 'value': '', 'type': 'local'},
{'key': 'whatsapp', 'value': 'false', 'type': 'util'},
{'key': 'provisional', 'value': 'false', 'type': 'util'},
{'key': 'pets', 'value': 'false', 'type': 'util'},
{'key': 'local', 'value': 'false', 'type': 'util'},
{'key': 'notify', 'value': 'false', 'type': 'util'},
{'key': 'fingerprint', 'value': 'false', 'type': 'util'},
{'key': 'access', 'value': 'false', 'type': 'util'},
{'key': 'panic', 'value': 'false', 'type': 'util'},
{'key': 'person', 'value': 'false', 'type': 'util'},
{'key': 'requestOSnotification', 'value': 'false', 'type': 'util'},
{'key': 'petAmountRegister', 'value': '', 'type': 'local'},
];
for (var data in initialData) {
await db.insert(DatabaseConfig.tableKeychain, data);
}
}
Future<void> _onOpen(Database db) async {
log('Checking existing data...');
await _checkExistingData(db);
}
Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
log('Upgrading database from version $oldVersion to $newVersion');
}
Future<void> _onDowngrade(Database db, int oldVersion, int newVersion) async {
log('Downgrading database from version $oldVersion to $newVersion');
}
Future<void> _onConfigure(Database db) async {
log('Configuring database...');
}
Future<void> _checkExistingData(Database db) async {
try {
final maps = await db.query(DatabaseConfig.tableKeychain);
log('Existing data: $maps');
} catch (error) {
log('Error checking existing data: $error');
}
}
Future<void> deleteDatabaseDB() async {
final path = await _getDatabasePath();
await deleteDatabase(path);
log('Database deleted');
_database = null;
}
Future<dynamic> get({String? key, String? field}) async {
try {
final db = await database;
List<Map<String, dynamic>> queryResult;
if (field != null && key != null) {
queryResult = await db.query(
DatabaseConfig.tableKeychain,
columns: [field],
where: '${DatabaseConfig.columnKey} = ?',
whereArgs: [key],
);
} else if (field != null) {
queryResult = await db.query(
DatabaseConfig.tableKeychain,
columns: [field],
);
} else if (key != null) {
field = DatabaseConfig.columnValue;
queryResult = await db.query(
DatabaseConfig.tableKeychain,
columns: [field],
where: '${DatabaseConfig.columnKey} = ?',
whereArgs: [key],
);
} else {
queryResult = await db.query(DatabaseConfig.tableKeychain);
}
log('Query result for key: $key, field: $field -> $queryResult');
if (queryResult.isNotEmpty) {
return queryResult.first[field];
} else {
return null;
}
} catch (error) {
log('Error getting: $error');
return null;
}
}
Future<int> insert(String key, dynamic value, String? type) async {
final db = await database;
final Map<String, dynamic> data = {
DatabaseConfig.columnKey: key,
DatabaseConfig.columnValue: value.toString(),
DatabaseConfig.columnType: type,
DatabaseConfig.columnUpdateAt: DateTime.now().toIso8601String(),
DatabaseConfig.columnResolvedAt: null,
DatabaseConfig.columnCreatedAt: DateTime.now().toIso8601String(),
};
log('Inserting: $data');
return await db.insert(DatabaseConfig.tableKeychain, data);
}
Future<int> update(String key, dynamic value, String? type) async {
final db = await database;
final Map<String, dynamic> data = {
DatabaseConfig.columnKey: key,
if (value != null) DatabaseConfig.columnValue: value.toString(),
if (type != null) DatabaseConfig.columnType: type,
DatabaseConfig.columnUpdateAt: DateTime.now().toIso8601String(),
DatabaseConfig.columnResolvedAt: null,
DatabaseConfig.columnCreatedAt: DateTime.now().toIso8601String(),
};
log('Updating: $data');
return await db.update(
DatabaseConfig.tableKeychain,
data,
where: '${DatabaseConfig.columnKey} = ?',
whereArgs: [key],
);
}
Future<int> clear(String key) async {
final db = await database;
log('Setting value of key: $key to empty string');
return await db.update(
DatabaseConfig.tableKeychain,
{DatabaseConfig.columnValue: ''},
where: '${DatabaseConfig.columnKey} = ?',
whereArgs: [key],
);
}
Future<int> delete(String key) async {
final db = await database;
log('Deleting key: $key');
return await db.delete(
DatabaseConfig.tableKeychain,
where: '${DatabaseConfig.columnKey} = ?',
whereArgs: [key],
);
}
Future<void> purge() async {
await deleteDatabaseDB();
await database;
log('Purge');
}
}

View File

@ -58,7 +58,7 @@ class CustomDrawer extends StatelessWidget {
child: CachedNetworkImage( child: CachedNetworkImage(
imageUrl: valueOrDefault( imageUrl: valueOrDefault(
'assets/images/person.jpg', '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, width: 80.0,
height: 80.0, height: 80.0,
@ -79,7 +79,7 @@ class CustomDrawer extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
convertToUppercase(AppState().name) ?? '', convertToUppercase(model.userName) ?? '',
style: FlutterFlowTheme.of(context).bodyLarge.override( style: FlutterFlowTheme.of(context).bodyLarge.override(
fontFamily: 'Nunito Sans', fontFamily: 'Nunito Sans',
color: FlutterFlowTheme.of(context).primaryText, color: FlutterFlowTheme.of(context).primaryText,
@ -89,7 +89,7 @@ class CustomDrawer extends StatelessWidget {
), ),
), ),
Text( Text(
AppState().email, model.userEmail,
style: FlutterFlowTheme.of(context).bodySmall.override( style: FlutterFlowTheme.of(context).bodySmall.override(
fontFamily: 'Nunito Sans', fontFamily: 'Nunito Sans',
color: FlutterFlowTheme.of(context).primaryText, color: FlutterFlowTheme.of(context).primaryText,