From 67edb919a0054c44b888759c190cffb2fbb29ab3 Mon Sep 17 00:00:00 2001 From: "J. A. Messias" Date: Thu, 19 Sep 2024 16:08:06 -0300 Subject: [PATCH 1/3] fix cursorColor in TextFormFields --- lib/actions/actions.dart | 650 ------------------ .../notifications/notification_service.dart | 25 +- .../shared_components_atoms/custom_input.dart | 1 + .../details_component_action.dart | 25 +- .../provisional_shcedule_template_widget.dart | 17 +- ...de_pass_key_template_component_widget.dart | 2 +- ...iter_vistor_template_component_widget.dart | 4 + .../sign_in_template_component_model.dart | 122 ++++ .../sign_in_template_component_widget.dart | 13 +- .../sign_up_template_component_model.dart | 64 ++ .../sign_up_template_component_widget.dart | 6 +- .../actions/convert_to_upload_file.dart | 4 +- lib/custom_code/actions/get_dev_u_u_i_d.dart | 1 - lib/custom_code/widgets/image_cropper.dart | 1 - .../liberation_history_model.dart | 24 + .../liberation_history_widget.dart | 5 +- lib/pages/pets_page/pets_history_screen.dart | 2 - lib/pages/pets_page/pets_page_widget.dart | 4 + .../qr_code_page/qr_code_page_model.dart | 96 +++ .../qr_code_page/qr_code_page_widget.dart | 3 +- .../schedule_complete_visit_page_widget.dart | 5 +- .../sign_in_page/sign_in_page_widget.dart | 9 +- .../sign_up_page/sign_up_page_widget.dart | 9 +- .../visit_history_page_model.dart | 66 ++ .../visit_history_page_widget.dart | 27 +- .../welcome_page/welcome_page_widget.dart | 9 +- lib/shared/mixins/status_mixin.dart | 20 + lib/shared/mixins/switcher_mixin.dart | 29 + lib/shared/utils/share_util.dart | 26 + 29 files changed, 560 insertions(+), 709 deletions(-) delete mode 100644 lib/actions/actions.dart create mode 100644 lib/shared/mixins/status_mixin.dart create mode 100644 lib/shared/mixins/switcher_mixin.dart create mode 100644 lib/shared/utils/share_util.dart diff --git a/lib/actions/actions.dart b/lib/actions/actions.dart deleted file mode 100644 index d4953428..00000000 --- a/lib/actions/actions.dart +++ /dev/null @@ -1,650 +0,0 @@ -import 'dart:developer'; - -import 'package:flutter/material.dart'; -// import 'package:hub/components/organisms/bottom_arrow_linked_locals/bottom_arrow_linked_locals_component_widget.dart'; -import 'package:hub/backend/api_requests/api_calls.dart'; -import 'package:hub/components/molecular_components/option_selection_modal/option_selection_modal_widget.dart'; -import 'package:hub/custom_code/actions/get_dev_u_u_i_d.dart'; -import 'package:hub/flutter_flow/flutter_flow_theme.dart'; -import 'package:hub/flutter_flow/flutter_flow_util.dart'; -import 'package:hub/flutter_flow/nav/nav.dart'; -import 'package:hub/flutter_flow/random_data_util.dart'; -import 'package:hub/shared/helpers/db_helper.dart'; -import 'package:hub/shared/utils/dialog_util.dart'; -import 'package:qr_flutter/qr_flutter.dart'; -import 'package:share_plus/share_plus.dart'; -import 'package:url_launcher/url_launcher.dart'; - -import '../shared/utils/log_util.dart'; - -Future openTermsOfUse(BuildContext context) async { - final Uri url = Uri.parse('https://freaccess.com.br/pp/'); - if (!await launchUrl(url)) { - throw Exception('Could not launch $url'); - } -} - -Future repeatVisitScheduleAction( - BuildContext context, { - List? visitorJsonList, - String? visitorStrList, - String? visitStartDateStr, - String? visitEndDateStr, - String? visitReasonStr, - String? visitLevelStr, - bool? visitTempBol, - String? visitObsStr, -}) async { - context.go( - '/scheduleCompleteVisitPage', - extra: { - 'visitStartDateStr': visitStartDateStr, - 'visitEndDateStr': visitEndDateStr, - 'visitReasonStr': visitReasonStr, - 'visitLevelStr': visitLevelStr, - 'visitTempBol': visitTempBol, - 'visitObsStr': visitObsStr, - 'visitorStrList': visitorStrList, - 'visitorJsonList': visitorJsonList, - }, - ); -} - -Future manageStatusColorAction( - BuildContext context, { - required String? visitStatusStr, -}) async { - if (visitStatusStr == 'A') { - return FlutterFlowTheme.of(context).success; - } else if ((visitStatusStr == 'C') || - (visitStatusStr == 'F') || - (visitStatusStr == 'B') || - (visitStatusStr == 'I')) { - return FlutterFlowTheme.of(context).error; - } - - return FlutterFlowTheme.of(context).warning; -} - -Future signInLoginAction( - BuildContext context, - FlutterFlowModel model, { - String? emailAdress, - String? password, -}) async { - try { - final ApiCallResponse? response; - final DatabaseHelper db = DatabaseHelper(); - final LoginCall callback = PhpGroup.loginCall; - AppState().deviceDescription = randomString( - 10, - 10, - true, - false, - false, - ); - - final String? devUUID; - final String userUUID; - final String status; - final String userDevUUID; - final String userName; - final String email; - final String passwd; - final bool isLogged; - - email = emailAdress!; - passwd = password!; - - devUUID = await getDevUUID(); - - if ((email != '') && (passwd != '')) { - 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 { - if (response.jsonBody['error'] == null) { - DialogUtil.errorDefault(context); - } else { - DialogUtil.error(context, response.jsonBody['error_msg'].toString()); - } - } - } - - return; - } catch (e, s) { - DialogUtil.errorDefault(context); - LogUtil.requestAPIFailed( - 'login.php', emailAdress.toString(), "Login", e, s); - } -} - -Future signUpRegisterAction( - BuildContext context, { - required String? name, - String? passwd, - required String? email, - String? device, -}) async { - try { - ApiCallResponse? response; - - if ((email != null && email != '') && - (passwd != null && passwd != '' && passwd.length > 7) && - (name != null && name != '')) { - response = await PhpGroup.registerCall.call( - name: name, - password: passwd, - email: email, - token: randomString( - 36, - 36, - false, - false, - true, - ), - uuid: randomString( - 36, - 36, - false, - false, - true, - ), - tipo: device, - descricao: randomString( - 36, - 36, - true, - false, - false, - ), - ); - - if (response.jsonBody['error'] == false) { - return true; - } - DialogUtil.error(context, response.jsonBody['error_msg']); - return false; - } else { - DialogUtil.errorDefault(context); - return false; - } - } catch (e, s) { - DialogUtil.errorDefault(context); - LogUtil.requestAPIFailed( - 'registro.php', email.toString(), "Register", e, s); - return false; - } -} - -Future forgotPasswdAction( - BuildContext context, { - required String? email, -}) async { - ApiCallResponse? response; - ForgotPasswordCall callback = PhpGroup.forgotPasswordCall; - - response = await PhpGroup.forgotPasswordCall.call( - email: email, - ); - - if (response.jsonBody['error'] != false) { - return; - } -} - -Future toggleSignInPage(BuildContext context) async { - context.go( - '/signInPage', - extra: { - kTransitionInfoKey: const TransitionInfo( - hasTransition: true, - transitionType: PageTransitionType.fade, - ), - }, - ); -} - -Future toggleSignUpPage(BuildContext context) async { - context.go( - '/signUpPage', - extra: { - kTransitionInfoKey: const TransitionInfo( - hasTransition: true, - transitionType: PageTransitionType.fade, - ), - }, - ); -} - -Future toggleApp(BuildContext context) async { - final haveLocal = AppState().haveLocal; - if (haveLocal == true) { - context.go('/homePage'); - } else if (haveLocal == false) { - context.go( - '/receptionPage', - extra: { - kTransitionInfoKey: const TransitionInfo( - hasTransition: true, - transitionType: PageTransitionType.fade, - ) - }, - ); - } -} - -Future visitCancelAction(BuildContext context, - {required int? idDestino, - required int? idVisita, - required String? accessKey, - required String? email}) async { - final ApiCallResponse? response; - final CancelaVisita callback = PhpGroup.cancelaVisita; - - response = await callback.call( - idDestino: idDestino, - idVisita: idVisita, - AccessKey: accessKey, - UsuEmail: email, - DevDesc: '', - ); - - if (response.statusCode == 200) { - return !response.jsonBody['error']; - } else { - return false; - } -} - -Future snackbar(BuildContext context, {required bool opt}) async { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - elevation: 10, - margin: const EdgeInsets.all(50), - content: Center( - child: Text( - opt - ? FFLocalizations.of(context).getText('asjd2q3k2j4l21') - : FFLocalizations.of(context).getText('asda2e42fafa'), - style: TextStyle( - fontSize: 16.0, - fontWeight: FontWeight.normal, - color: FlutterFlowTheme.of(context).info, - ), - ), - ), - backgroundColor: opt - ? FlutterFlowTheme.of(context).success.withOpacity(0.5) - : FlutterFlowTheme.of(context).error.withOpacity(0.5), - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), - ), - ); -} - -Future checkLocals({ - String? cliUUID, - required BuildContext context, - required FlutterFlowModel model, -}) async { - final GetLocalsCall callback = PhpGroup.getLocalsCall; - - final response = await callback.call(); - - if (response.jsonBody['error']) { - DialogUtil.errorDefault(context); - return false; - } - List locals = response.jsonBody['locais'] ?? []; - - if (locals.isEmpty) { - return false; - } else { - return true; - } -} - -Future 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++) { - await Share.share(''' -Olá, \*${payload['convites'][i]['VTE_NOME']}\*! Você foi convidado para \*$cliName\*. - -\*Validade do Convite\*: -- Início: ${payload['convites'][i]['VAW_DTINICIO']} -- Fim: ${payload['convites'][i]['VAW_DTFIM']} - -URL do Convite: https://visita.freaccess.com.br/${payload['convites'][i]['VAW_ID']}/$cliUUID/${payload['convites'][i]['VAW_CHAVE']} - '''); - } -} - -Future answersRequest( - {required BuildContext context, - required String? ref, - required String? task, - required String? response, - required String? id}) async { - final ApiCallResponse? respondeSolicitacaoCall; - final RespondeSolicitacaoCall callback = PhpGroup.respondeSolicitacaoCall; - - respondeSolicitacaoCall = await callback.call( - referencia: ref, - tarefa: task, - resposta: response, - idVisitante: id, - ); - - if (respondeSolicitacaoCall.statusCode == 200) { - return !respondeSolicitacaoCall.jsonBody['error']; - } else { - return false; - } -} - -Future changeStatusAction( - BuildContext context, - int idDestino, - int idVisita, - String accessKey, - String email, -) async { - // Navigator.pop(context, true); - context.pop(true); - - bool? blockVisitRequest; - blockVisitRequest = await visitCancelAction( - context, - accessKey: accessKey, - idDestino: idDestino, - idVisita: idVisita, - email: email, - ); - if (!context.mounted) return; - if (blockVisitRequest == true) { - return true; - } else { - return false; - } -} - -/// QR Code - -Uint8List assembleQRPacket(int direction, String identifier, String password) { - List packet = [direction]; - - String paddedBadge = identifier.padLeft(30, '0'); - - for (var i = 0; i < paddedBadge.length; i += 2) { - packet.add(int.parse(paddedBadge.substring(i, i + 2), radix: 16)); - } - - DateTime now = DateTime.now(); - int year = now.year % 100; - int month = now.month; - int day = now.day; - int hour = now.hour; - int minute = now.minute; - - int sum = year + month + day + hour + minute; - - if (sum == int.parse('0D', radix: 16) || sum == int.parse('0A', radix: 16)) { - packet.add(int.parse('FF', radix: 16)); - } else { - packet.add(sum); - } - - String paddedPassword = password.length != 4 ? 'FFFF' : password; - - for (var i = 0; i < paddedPassword.length; i += 2) { - packet.add(int.parse(paddedPassword.substring(i, i + 2), radix: 16)); - } - - int check = 0x00; - - for (var b in packet) { - check ^= b; - } - - if (check == int.parse('0D', radix: 16) || - check == int.parse('0A', radix: 16)) { - packet.add(int.parse('FF', radix: 16)); - } else { - packet.add(check); - } - - var bytes = - packet.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join((' ')); - - return Uint8List.fromList(packet); -} - -Uint8List hexStringToByteArray(String s) { - int len = s.length; - Uint8List data = Uint8List(len ~/ 2); - for (int i = 0; i < len; i += 2) { - data[i ~/ 2] = - ((int.parse(s[i], radix: 16) << 4) + int.parse(s[i + 1], radix: 16)); - } - return data; -} - -String byteToHexa(Uint8List pDados) { - return pDados - .map((byte) => byte.toRadixString(16).padLeft(2, '0').toUpperCase()) - .join(); -} - -Future byteToString(Uint8List bytes) async { - return String.fromCharCodes(bytes); -} - -Widget buildQrCode( - { - // required String data, - // required String type, - // required int version, - // required int maskPattern, - required int errorCorrectLevel, - required double dimension, - required String identifier, - required String pass, - required int direction}) { - try { - const Color backgroundColor = Colors.white; - const Color foregroundColor = Colors.black; - return QrImageView.withQr( - qr: QrCode.fromUint8List( - data: assembleQRPacket(direction, identifier, pass), - errorCorrectLevel: errorCorrectLevel), - size: dimension, - padding: const EdgeInsets.all(10), - backgroundColor: backgroundColor, - foregroundColor: foregroundColor); - } catch (e) { - return Text("Erro ao gerar QR Code: ${e.toString()}"); - } -} - -Future scheduleVisitOptAction(BuildContext context) async { - await showAdaptiveDialog( - context: context, - builder: (context) { - return Padding( - padding: MediaQuery.viewInsetsOf(context), - child: OptionSelectionModalWidget( - routesListStr: [ - 'scheduleCompleteVisitPage', - 'scheduleProvisionalVisitPage', - 'fastPassPage', - ], - iconsListIcon: [ - Icons.date_range_rounded, - Icons.date_range_rounded, - Icons.date_range_rounded, - ], - nameListStr: [ - FFLocalizations.of(context).getVariableText( - ptText: 'Visita\nCompleta', - enText: 'Complete\nSchedule', - ), - FFLocalizations.of(context).getVariableText( - ptText: 'Visita\nProvisória', - enText: 'Provisional\nSchedule', - ), - FFLocalizations.of(context).getVariableText( - ptText: 'Visita\nRápida', - enText: 'Fast\nSchedule', - ), - ], - ), - ); - }, - ); -} - -Future registerVisitorOptAction(BuildContext context) async { - context.go( - '/registerVisitorPage', - extra: { - kTransitionInfoKey: const TransitionInfo( - hasTransition: true, - transitionType: PageTransitionType.scale, - alignment: Alignment.bottomCenter, - ), - }, - ); -} - -Future peopleOnThePropertyAction(BuildContext context) async { - context.go( - '/peopleOnThePropertyPage', - extra: { - kTransitionInfoKey: const TransitionInfo( - hasTransition: true, - transitionType: PageTransitionType.fade, - ), - }, - ); -} - -Future preferencesSettings(BuildContext context) async { - context.go( - '/preferencesSettings', - extra: { - kTransitionInfoKey: const TransitionInfo( - hasTransition: true, - transitionType: PageTransitionType.scale, - alignment: Alignment.bottomCenter, - ), - }, - ); -} - -Future liberationHistoryOptAction(BuildContext context) async { - await showAdaptiveDialog( - // isScrollControlled: true, - // backgroundColor: Colors.transparent, - // enableDrag: false, - context: context, - builder: (context) { - return Padding( - padding: MediaQuery.viewInsetsOf(context), - child: OptionSelectionModalWidget( - routesListStr: [ - 'liberationHistory', - 'acessHistoryPage', - 'scheduleCompleteVisitPage', - // 'messageHistoryPage', - ], - iconsListIcon: [ - Icons.history_rounded, - Icons.history_rounded, - Icons.history_rounded, - // Icons.history_rounded, - ], - nameListStr: [ - FFLocalizations.of(context).getVariableText( - ptText: 'Histórico\nde Liberação', - enText: 'Liberation\nHistory', - ), - FFLocalizations.of(context).getVariableText( - ptText: 'Histórico\nde Acesso', - enText: 'Access\nHistory', - ), - FFLocalizations.of(context).getVariableText( - ptText: 'Histórico\nde Visita', - enText: 'Visit\nHistory', - ), - // FFLocalizations.of(context).getVariableText( - // ptText: 'Histórico\nde Mensagens', - // enText: 'Message\nHistory', - // ), - ], - ), - ); - }, - ); -} - -Future accessQRCodeOptAction(BuildContext context) async { - context.go( - '/qrCodePage', - extra: { - kTransitionInfoKey: const TransitionInfo( - hasTransition: true, - transitionType: PageTransitionType.scale, - alignment: Alignment.bottomCenter, - ), - }, - ); -} - -enum status { active, unknown, canceled, finished, blocked, inactive } - -status? getStatus(dynamic data) { - switch (data) { - case 'A': - return status.active; - case 'F': - return status.finished; - case 'B': - return status.blocked; - case 'C': - return status.canceled; - case 'I': - return status.inactive; - default: - return status.unknown; - } -} diff --git a/lib/backend/notifications/notification_service.dart b/lib/backend/notifications/notification_service.dart index 424cdb2a..32398ec5 100644 --- a/lib/backend/notifications/notification_service.dart +++ b/lib/backend/notifications/notification_service.dart @@ -3,7 +3,8 @@ import 'dart:developer'; import 'package:awesome_notifications/awesome_notifications.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'package:hub/actions/actions.dart'; +import 'package:hub/backend/api_requests/api_calls.dart'; +import 'package:hub/backend/api_requests/api_manager.dart'; import 'package:hub/components/templates_components/access_notification_modal_template_component/access_notification_modal_template_component_widget.dart'; import 'package:hub/components/templates_components/details_component/details_component_widget.dart'; import 'package:hub/components/templates_components/message_notificaion_modal_template_component/message_notification_widget.dart'; @@ -23,6 +24,28 @@ Future onMessageReceived( final cliUUID = await db .get(key: 'cliUUID', field: 'value') .then((value) => value.toString()); + answersRequest( + {required BuildContext context, + required String? ref, + required String? task, + required String? response, + required String? id}) async { + final ApiCallResponse? respondeSolicitacaoCall; + final RespondeSolicitacaoCall callback = PhpGroup.respondeSolicitacaoCall; + + respondeSolicitacaoCall = await callback.call( + referencia: ref, + tarefa: task, + resposta: response, + idVisitante: id, + ); + + if (respondeSolicitacaoCall.statusCode == 200) { + return !respondeSolicitacaoCall.jsonBody['error']; + } else { + return false; + } + } switch (handleClick) { case 'visit_request': diff --git a/lib/components/atomic_components/shared_components_atoms/custom_input.dart b/lib/components/atomic_components/shared_components_atoms/custom_input.dart index 608f60af..b9878f1c 100644 --- a/lib/components/atomic_components/shared_components_atoms/custom_input.dart +++ b/lib/components/atomic_components/shared_components_atoms/custom_input.dart @@ -58,6 +58,7 @@ class _CustomInputUtilState extends State { controller: widget.controller, autovalidateMode: AutovalidateMode.onUserInteraction, validator: widget.validator, + cursorColor: FlutterFlowTheme.of(context).primary, autofocus: widget.autoFocus, focusNode: widget.focusNode, onChanged: (value) { diff --git a/lib/components/templates_components/details_component/details_component_action.dart b/lib/components/templates_components/details_component/details_component_action.dart index 6cf56968..48dbabee 100644 --- a/lib/components/templates_components/details_component/details_component_action.dart +++ b/lib/components/templates_components/details_component/details_component_action.dart @@ -3,7 +3,6 @@ import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:http/http.dart'; -import 'package:hub/actions/actions.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/templates_components/details_component/details_component_widget.dart'; import 'package:hub/custom_code/actions/convert_to_upload_file.dart'; @@ -13,6 +12,7 @@ import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; import 'package:hub/flutter_flow/form_field_controller.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/pages/pets_page/pets_page_model.dart'; +import 'package:hub/shared/mixins/status_mixin.dart'; import 'package:hub/shared/utils/validator_util.dart'; import 'package:share_plus/share_plus.dart'; @@ -28,7 +28,8 @@ Widget buildVisitDetails({ }) { return DetailsComponentWidget( buttons: [ - if (getStatus(item['VAW_STATUS']) == status.active) // REJECT ACTION + if (Status.getStatus(item['VAW_STATUS']) == + StatusEnum.active) // REJECT ACTION FFButtonWidget( text: FFLocalizations.of(context).getVariableText( ptText: 'Cancelar', @@ -105,7 +106,8 @@ Widget buildVisitDetails({ // borderRadius: 12, ), ), - if (getStatus(item['VAW_STATUS']) != status.active) // RECALL ACTION + if (Status.getStatus(item['VAW_STATUS']) != + StatusEnum.active) // RECALL ACTION FFButtonWidget( text: FFLocalizations.of(context).getVariableText( ptText: 'Reagendar', @@ -138,7 +140,8 @@ Widget buildVisitDetails({ // borderRadius: 12, ), ), - if (getStatus(item['VAW_STATUS']) == status.active) // SHARE ACTION + if (Status.getStatus(item['VAW_STATUS']) == + StatusEnum.active) // SHARE ACTION FFButtonWidget( text: FFLocalizations.of(context).getVariableText( ptText: 'Compartilhar', @@ -189,42 +192,42 @@ URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/${cliUUID}/${i imagePath: 'https://freaccess.com.br/freaccess/getImage.php?cliID=${cliUUID}&atividade=getFoto&Documento=${item['VTE_DOCUMENTO'] ?? ''}&tipo=E', statusHashMap: [ - if (getStatus(item['VAW_STATUS']) == status.active) + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.active) Map.from({ FFLocalizations.of(context).getVariableText( ptText: 'Ativo', enText: 'Active', ): FlutterFlowTheme.of(context).warning, }), - if (getStatus(item['VAW_STATUS']) == status.unknown) + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.unknown) Map.from({ FFLocalizations.of(context).getVariableText( ptText: 'Pendente', enText: 'Pending', ): FlutterFlowTheme.of(context).alternate, }), - if (getStatus(item['VAW_STATUS']) == status.canceled) + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.canceled) Map.from({ FFLocalizations.of(context).getVariableText( ptText: 'Cancelado', enText: 'Canceled', ): FlutterFlowTheme.of(context).error, }), - if (getStatus(item['VAW_STATUS']) == status.finished) + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.finished) Map.from({ FFLocalizations.of(context).getVariableText( ptText: 'Finalizado', enText: 'Finished', ): FlutterFlowTheme.of(context).success, }), - if (getStatus(item['VAW_STATUS']) == status.blocked) + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.blocked) Map.from({ FFLocalizations.of(context).getVariableText( ptText: 'Bloqueado', enText: 'Blocked', ): FlutterFlowTheme.of(context).error, }), - if (getStatus(item['VAW_STATUS']) == status.inactive) + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.inactive) Map.from({ FFLocalizations.of(context).getVariableText( ptText: 'Inativo', @@ -238,8 +241,6 @@ URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/${cliUUID}/${i Widget buildPetDetails({ required dynamic item, required BuildContext context, - required Future Function(BuildContext, int, int, String, String) - changeStatusAction, required String devUUID, required String userUUID, required String cliUUID, diff --git a/lib/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart b/lib/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart index f68c3264..68f8a91f 100644 --- a/lib/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart +++ b/lib/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart @@ -250,6 +250,9 @@ class _ScheduleProvisionalVisitPageWidgetState model.personNameTextController, focusNode: model.personNameFocusNode, + cursorColor: + FlutterFlowTheme.of(context) + .primary, onChanged: (_) => EasyDebounce.debounce( 'model.personNameTextController', @@ -261,7 +264,7 @@ class _ScheduleProvisionalVisitPageWidgetState TextInputAction.next, obscureText: false, decoration: InputDecoration( - isDense: false, + isDense: true, labelText: FFLocalizations.of(context) .getText( @@ -402,6 +405,9 @@ class _ScheduleProvisionalVisitPageWidgetState model.dateTimeTextController, focusNode: model.dateTimeFocusNode, + cursorColor: + FlutterFlowTheme.of(context) + .primary, onChanged: (_) => EasyDebounce.debounce( 'model.dateTimeTextController', @@ -413,7 +419,7 @@ class _ScheduleProvisionalVisitPageWidgetState autofocus: false, obscureText: false, decoration: InputDecoration( - isDense: false, + isDense: true, labelText: FFLocalizations.of(context) .getText( @@ -738,11 +744,16 @@ class _ScheduleProvisionalVisitPageWidgetState focusNode: model.notesFocusNode, autofocus: false, + showCursor: true, + cursorColor: + FlutterFlowTheme.of( + context) + .primary, textInputAction: TextInputAction.next, obscureText: false, decoration: InputDecoration( - isDense: false, + isDense: true, labelText: FFLocalizations.of( context) diff --git a/lib/components/templates_components/qr_code_pass_key_template_component/qr_code_pass_key_template_component_widget.dart b/lib/components/templates_components/qr_code_pass_key_template_component/qr_code_pass_key_template_component_widget.dart index dd902f7c..cc89233e 100644 --- a/lib/components/templates_components/qr_code_pass_key_template_component/qr_code_pass_key_template_component_widget.dart +++ b/lib/components/templates_components/qr_code_pass_key_template_component/qr_code_pass_key_template_component_widget.dart @@ -170,6 +170,7 @@ class _QrCodePassKeyTemplateComponentWidgetState child: TextFormField( controller: _model.keyTextFieldTextController, focusNode: _model.keyTextFieldFocusNode, + cursorColor: FlutterFlowTheme.of(context).primary, onChanged: (_) => EasyDebounce.debounce( '_model.keyTextFieldTextController', const Duration(milliseconds: 2000), @@ -271,7 +272,6 @@ class _QrCodePassKeyTemplateComponentWidgetState maxLength}) => null, keyboardType: TextInputType.number, - cursorColor: FlutterFlowTheme.of(context).primary, validator: _model.keyTextFieldTextControllerValidator .asValidator(context), inputFormatters: [ diff --git a/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart b/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart index 1d97bbf3..3abfdf48 100644 --- a/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart +++ b/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart @@ -171,6 +171,7 @@ class _RegisiterVistorTemplateComponentWidgetState TextFormField( controller: _model.textController2, focusNode: _model.textFieldFocusNode2, + cursorColor: FlutterFlowTheme.of(context).primary, autovalidateMode: AutovalidateMode.onUserInteraction, autofocus: true, textCapitalization: TextCapitalization.none, @@ -307,6 +308,7 @@ class _RegisiterVistorTemplateComponentWidgetState child: TextFormField( controller: _model.textController1, autovalidateMode: AutovalidateMode.onUserInteraction, + cursorColor: FlutterFlowTheme.of(context).primary, focusNode: _model.textFieldFocusNode1, onChanged: (_) => EasyDebounce.debounce( '_model.textFieldFocusNode1', @@ -661,6 +663,7 @@ class _RegisiterVistorTemplateComponentWidgetState child: TextFormField( controller: _model.textController3, focusNode: _model.textFieldFocusNode3, + cursorColor: FlutterFlowTheme.of(context).primary, autovalidateMode: AutovalidateMode.onUserInteraction, autofocus: false, textInputAction: TextInputAction.next, @@ -749,6 +752,7 @@ class _RegisiterVistorTemplateComponentWidgetState 24.0, 0.0, 24.0, 0.0), child: TextFormField( controller: _model.textController4, + cursorColor: FlutterFlowTheme.of(context).primary, focusNode: _model.textFieldFocusNode4, autovalidateMode: AutovalidateMode.onUserInteraction, autofocus: true, diff --git a/lib/components/templates_components/sign_in_template_component/sign_in_template_component_model.dart b/lib/components/templates_components/sign_in_template_component/sign_in_template_component_model.dart index 165de263..4869dc1f 100644 --- a/lib/components/templates_components/sign_in_template_component/sign_in_template_component_model.dart +++ b/lib/components/templates_components/sign_in_template_component/sign_in_template_component_model.dart @@ -1,4 +1,12 @@ +import 'package:hub/backend/api_requests/api_calls.dart'; +import 'package:hub/backend/api_requests/api_manager.dart'; +import 'package:hub/custom_code/actions/get_dev_u_u_i_d.dart'; +import 'package:hub/flutter_flow/nav/nav.dart'; +import 'package:hub/flutter_flow/random_data_util.dart'; import 'package:hub/pages/home_page/home_page_model.dart'; +import 'package:hub/shared/helpers/db_helper.dart'; +import 'package:hub/shared/utils/dialog_util.dart'; +import 'package:hub/shared/utils/log_util.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'sign_in_template_component_widget.dart' @@ -48,6 +56,120 @@ class SignInTemplateComponentModel return null; } + Future checkLocals({ + String? cliUUID, + required BuildContext context, + required FlutterFlowModel model, + }) async { + final GetLocalsCall callback = PhpGroup.getLocalsCall; + + final response = await callback.call(); + + if (response.jsonBody['error']) { + DialogUtil.errorDefault(context); + return false; + } + List locals = response.jsonBody['locais'] ?? []; + + if (locals.isEmpty) { + return false; + } else { + return true; + } + } + + Future signInLoginAction( + BuildContext context, + FlutterFlowModel model, { + String? emailAdress, + String? password, + }) async { + try { + final ApiCallResponse? response; + final DatabaseHelper db = DatabaseHelper(); + final LoginCall callback = PhpGroup.loginCall; + AppState().deviceDescription = randomString( + 10, + 10, + true, + false, + false, + ); + + final String? devUUID; + final String userUUID; + final String status; + final String userDevUUID; + final String userName; + final String email; + final String passwd; + final bool isLogged; + + email = emailAdress!; + passwd = password!; + + devUUID = await getDevUUID(); + + if ((email != '') && (passwd != '')) { + 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 { + if (response.jsonBody['error'] == null) { + DialogUtil.errorDefault(context); + } else { + DialogUtil.error( + context, response.jsonBody['error_msg'].toString()); + } + } + } + + return; + } catch (e, s) { + DialogUtil.errorDefault(context); + LogUtil.requestAPIFailed( + 'login.php', emailAdress.toString(), "Login", e, s); + } + } + + Future toggleApp(BuildContext context) async { + final haveLocal = AppState().haveLocal; + if (haveLocal == true) { + context.go('/homePage'); + } else if (haveLocal == false) { + context.go( + '/receptionPage', + extra: { + kTransitionInfoKey: const TransitionInfo( + hasTransition: true, + transitionType: PageTransitionType.fade, + ) + }, + ); + } + } + @override void initState(BuildContext context) { emailAddressTextControllerValidator = _emailAddressTextControllerValidator; diff --git a/lib/components/templates_components/sign_in_template_component/sign_in_template_component_widget.dart b/lib/components/templates_components/sign_in_template_component/sign_in_template_component_widget.dart index bebc5c10..945fa394 100644 --- a/lib/components/templates_components/sign_in_template_component/sign_in_template_component_widget.dart +++ b/lib/components/templates_components/sign_in_template_component/sign_in_template_component_widget.dart @@ -8,7 +8,6 @@ import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/validator_util.dart'; -import '/actions/actions.dart' as action_blocks; import '/components/templates_components/forgot_password_template_component/forgot_password_template_component_widget.dart'; import '/flutter_flow/flutter_flow_animations.dart'; import '/flutter_flow/flutter_flow_theme.dart'; @@ -241,6 +240,10 @@ class _SignInTemplateComponentWidgetState .emailAddressTextController, focusNode: _model .emailAddressFocusNode, + cursorColor: + FlutterFlowTheme.of( + context) + .primary, onChanged: (_) => EasyDebounce.debounce( '_model.emailAddressTextController', @@ -382,6 +385,10 @@ class _SignInTemplateComponentWidgetState child: TextFormField( controller: _model .passwordTextController, + cursorColor: + FlutterFlowTheme.of( + context) + .primary, focusNode: _model.passwordFocusNode, onChanged: (_) => @@ -549,7 +556,7 @@ class _SignInTemplateComponentWidgetState onPressed: _isFormInvalid() ? null : () async { - await action_blocks + await _model .signInLoginAction( context, _model, @@ -709,7 +716,7 @@ class _SignInTemplateComponentWidgetState ? null : () async { try { - await action_blocks + await _model .signInLoginAction( context, _model, diff --git a/lib/components/templates_components/sign_up_template_component/sign_up_template_component_model.dart b/lib/components/templates_components/sign_up_template_component/sign_up_template_component_model.dart index 370ff262..57fc1e84 100644 --- a/lib/components/templates_components/sign_up_template_component/sign_up_template_component_model.dart +++ b/lib/components/templates_components/sign_up_template_component/sign_up_template_component_model.dart @@ -1,3 +1,9 @@ +import 'package:hub/backend/api_requests/api_calls.dart'; +import 'package:hub/backend/api_requests/api_manager.dart'; +import 'package:hub/flutter_flow/random_data_util.dart'; +import 'package:hub/shared/utils/dialog_util.dart'; +import 'package:hub/shared/utils/log_util.dart'; + import '/flutter_flow/flutter_flow_util.dart'; import 'sign_up_template_component_widget.dart' show SignUpTemplateComponentWidget; @@ -93,4 +99,62 @@ class SignUpTemplateComponentModel passwordRegisterFormFocusNode?.dispose(); passwordRegisterFormTextController?.dispose(); } + + Future signUpRegisterAction( + BuildContext context, { + required String? name, + String? passwd, + required String? email, + String? device, + }) async { + try { + ApiCallResponse? response; + + if ((email != null && email != '') && + (passwd != null && passwd != '' && passwd.length > 7) && + (name != null && name != '')) { + response = await PhpGroup.registerCall.call( + name: name, + password: passwd, + email: email, + token: randomString( + 36, + 36, + false, + false, + true, + ), + uuid: randomString( + 36, + 36, + false, + false, + true, + ), + tipo: device, + descricao: randomString( + 36, + 36, + true, + false, + false, + ), + ); + + if (response.jsonBody['error'] == false) { + return true; + } + DialogUtil.error(context, response.jsonBody['error_msg']); + return false; + } else { + DialogUtil.errorDefault(context); + return false; + } + } catch (e, s) { + DialogUtil.errorDefault(context); + LogUtil.requestAPIFailed( + 'registro.php', email.toString(), "Register", e, s); + return false; + } + } } diff --git a/lib/components/templates_components/sign_up_template_component/sign_up_template_component_widget.dart b/lib/components/templates_components/sign_up_template_component/sign_up_template_component_widget.dart index ecc3ab07..fe35911d 100644 --- a/lib/components/templates_components/sign_up_template_component/sign_up_template_component_widget.dart +++ b/lib/components/templates_components/sign_up_template_component/sign_up_template_component_widget.dart @@ -7,7 +7,6 @@ import 'package:hub/shared/components/atoms/atom_terms_of_use.dart'; import 'package:hub/shared/utils/validator_util.dart'; import 'package:provider/provider.dart'; -import '/actions/actions.dart' as action_blocks; import '/flutter_flow/flutter_flow_animations.dart'; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; @@ -690,9 +689,8 @@ class _SignUpTemplateComponentWidgetState ? null : () async { var shouldSetState = false; - _model.signUp = - await action_blocks - .signUpRegisterAction( + _model.signUp = await _model + .signUpRegisterAction( context, name: _model .nameRegisterFormTextController diff --git a/lib/custom_code/actions/convert_to_upload_file.dart b/lib/custom_code/actions/convert_to_upload_file.dart index e72f0efe..709be7ad 100644 --- a/lib/custom_code/actions/convert_to_upload_file.dart +++ b/lib/custom_code/actions/convert_to_upload_file.dart @@ -1,7 +1,6 @@ // Automatic FlutterFlow imports import '/backend/schema/structs/index.dart'; import '/backend/schema/enums/enums.dart'; -import '/actions/actions.dart' as action_blocks; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'index.dart'; // Imports other custom actions @@ -14,7 +13,6 @@ import 'dart:convert'; // Import for base64 decoding import 'dart:io'; // Import for file operations import 'package:path_provider/path_provider.dart'; // Import for temporary directory - Future convertToUploadFile(String img) async { // Decode the base64 string into bytes Uint8List bytes = base64.decode(img); @@ -30,4 +28,4 @@ Future convertToUploadFile(String img) async { bytes: bytes, name: 'image.jpg', ); -} \ No newline at end of file +} diff --git a/lib/custom_code/actions/get_dev_u_u_i_d.dart b/lib/custom_code/actions/get_dev_u_u_i_d.dart index 3e70fa5d..1be7def9 100644 --- a/lib/custom_code/actions/get_dev_u_u_i_d.dart +++ b/lib/custom_code/actions/get_dev_u_u_i_d.dart @@ -1,7 +1,6 @@ import '/backend/schema/structs/index.dart'; import 'dart:developer'; import '/backend/schema/enums/enums.dart'; -import '/actions/actions.dart' as action_blocks; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'index.dart'; // Imports other custom actions diff --git a/lib/custom_code/widgets/image_cropper.dart b/lib/custom_code/widgets/image_cropper.dart index 9b79b434..36cefae4 100644 --- a/lib/custom_code/widgets/image_cropper.dart +++ b/lib/custom_code/widgets/image_cropper.dart @@ -1,7 +1,6 @@ // // Automatic FlutterFlow imports // import '/backend/schema/structs/index.dart'; // import '/backend/schema/enums/enums.dart'; -// import '/actions/actions.dart' as action_blocks; // import '/flutter_flow/flutter_flow_theme.dart'; // import '/flutter_flow/flutter_flow_util.dart'; // import 'index.dart'; // Imports other custom widgets diff --git a/lib/pages/liberation_history/liberation_history_model.dart b/lib/pages/liberation_history/liberation_history_model.dart index 7eb11c14..493b34e9 100644 --- a/lib/pages/liberation_history/liberation_history_model.dart +++ b/lib/pages/liberation_history/liberation_history_model.dart @@ -1,3 +1,4 @@ +import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_manager.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; import 'package:hub/flutter_flow/request_manager.dart'; @@ -49,6 +50,29 @@ class LiberationHistoryModel extends FlutterFlowModel { .then((value) => value.toString()); } + Future answersRequest( + {required BuildContext context, + required String? ref, + required String? task, + required String? response, + required String? id}) async { + final ApiCallResponse? respondeSolicitacaoCall; + final RespondeSolicitacaoCall callback = PhpGroup.respondeSolicitacaoCall; + + respondeSolicitacaoCall = await callback.call( + referencia: ref, + tarefa: task, + resposta: response, + idVisitante: id, + ); + + if (respondeSolicitacaoCall.statusCode == 200) { + return !respondeSolicitacaoCall.jsonBody['error']; + } else { + return false; + } + } + @override void dispose() { unfocusNode.dispose(); diff --git a/lib/pages/liberation_history/liberation_history_widget.dart b/lib/pages/liberation_history/liberation_history_widget.dart index ebaa4be7..42bda80d 100644 --- a/lib/pages/liberation_history/liberation_history_widget.dart +++ b/lib/pages/liberation_history/liberation_history_widget.dart @@ -2,7 +2,6 @@ import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:hub/actions/actions.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.dart'; import 'package:hub/components/templates_components/details_component/details_component_widget.dart'; @@ -234,7 +233,7 @@ class _LiberationHistoryWidgetState extends State { ), icon: const Icon(Icons.done), onPressed: () async { - answersRequest + _model.answersRequest .call( context: context, ref: liberationHistoryItem['NOT_ID'].toString(), @@ -286,7 +285,7 @@ class _LiberationHistoryWidgetState extends State { ), icon: const Icon(Icons.close), onPressed: () async { - return answersRequest + return _model.answersRequest .call( context: context, ref: liberationHistoryItem['NOT_ID'].toString(), diff --git a/lib/pages/pets_page/pets_history_screen.dart b/lib/pages/pets_page/pets_history_screen.dart index fbabbb47..18ff3e77 100644 --- a/lib/pages/pets_page/pets_history_screen.dart +++ b/lib/pages/pets_page/pets_history_screen.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'package:hub/actions/actions.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.dart'; import 'package:hub/components/templates_components/details_component/details_component_action.dart'; @@ -267,7 +266,6 @@ class _PetsHistoryScreenState extends State child: buildPetDetails( item: uItem, context: context, - changeStatusAction: changeStatusAction, devUUID: devUUID, userUUID: userUUID, cliUUID: cliUUID, diff --git a/lib/pages/pets_page/pets_page_widget.dart b/lib/pages/pets_page/pets_page_widget.dart index 4132f447..e704d5a6 100644 --- a/lib/pages/pets_page/pets_page_widget.dart +++ b/lib/pages/pets_page/pets_page_widget.dart @@ -309,6 +309,8 @@ class _PetsPageWidgetState extends State child: TextFormField( controller: _model.textControllerData, focusNode: _model.textFieldFocusData, + cursorColor: + FlutterFlowTheme.of(context).primary, readOnly: true, autovalidateMode: AutovalidateMode.onUserInteraction, @@ -772,6 +774,8 @@ class _PetsPageWidgetState extends State child: TextFormField( controller: _model.textControllerData, focusNode: _model.textFieldFocusData, + cursorColor: + FlutterFlowTheme.of(context).primary, readOnly: true, autovalidateMode: AutovalidateMode.onUserInteraction, diff --git a/lib/pages/qr_code_page/qr_code_page_model.dart b/lib/pages/qr_code_page/qr_code_page_model.dart index da5b873a..bfe62ece 100644 --- a/lib/pages/qr_code_page/qr_code_page_model.dart +++ b/lib/pages/qr_code_page/qr_code_page_model.dart @@ -1,8 +1,10 @@ import 'dart:async'; +import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; import 'package:hub/pages/qr_code_page/qr_code_page_widget.dart'; import 'package:hub/shared/helpers/db_helper.dart'; +import 'package:qr_flutter/qr_flutter.dart'; class QrCodePageModel extends FlutterFlowModel { /// Local state fields for this page. @@ -39,6 +41,100 @@ class QrCodePageModel extends FlutterFlowModel { unfocusNode.dispose(); } + Uint8List assembleQRPacket( + int direction, String identifier, String password) { + List packet = [direction]; + + String paddedBadge = identifier.padLeft(30, '0'); + + for (var i = 0; i < paddedBadge.length; i += 2) { + packet.add(int.parse(paddedBadge.substring(i, i + 2), radix: 16)); + } + + DateTime now = DateTime.now(); + int year = now.year % 100; + int month = now.month; + int day = now.day; + int hour = now.hour; + int minute = now.minute; + + int sum = year + month + day + hour + minute; + + if (sum == int.parse('0D', radix: 16) || + sum == int.parse('0A', radix: 16)) { + packet.add(int.parse('FF', radix: 16)); + } else { + packet.add(sum); + } + + String paddedPassword = password.length != 4 ? 'FFFF' : password; + + for (var i = 0; i < paddedPassword.length; i += 2) { + packet.add(int.parse(paddedPassword.substring(i, i + 2), radix: 16)); + } + + int check = 0x00; + + for (var b in packet) { + check ^= b; + } + + if (check == int.parse('0D', radix: 16) || + check == int.parse('0A', radix: 16)) { + packet.add(int.parse('FF', radix: 16)); + } else { + packet.add(check); + } + + var bytes = packet + .map((byte) => byte.toRadixString(16).padLeft(2, '0')) + .join((' ')); + + return Uint8List.fromList(packet); + } + + Uint8List hexStringToByteArray(String s) { + int len = s.length; + Uint8List data = Uint8List(len ~/ 2); + for (int i = 0; i < len; i += 2) { + data[i ~/ 2] = + ((int.parse(s[i], radix: 16) << 4) + int.parse(s[i + 1], radix: 16)); + } + return data; + } + + String byteToHexa(Uint8List pDados) { + return pDados + .map((byte) => byte.toRadixString(16).padLeft(2, '0').toUpperCase()) + .join(); + } + + Future byteToString(Uint8List bytes) async { + return String.fromCharCodes(bytes); + } + + Widget buildQrCode( + {required int errorCorrectLevel, + required double dimension, + required String identifier, + required String pass, + required int direction}) { + try { + const Color backgroundColor = Colors.white; + const Color foregroundColor = Colors.black; + return QrImageView.withQr( + qr: QrCode.fromUint8List( + data: assembleQRPacket(direction, identifier, pass), + errorCorrectLevel: errorCorrectLevel), + size: dimension, + padding: const EdgeInsets.all(10), + backgroundColor: backgroundColor, + foregroundColor: foregroundColor); + } catch (e) { + return Text("Erro ao gerar QR Code: ${e.toString()}"); + } + } + /// Action blocks. Future qrCodeEncoder( BuildContext context, { diff --git a/lib/pages/qr_code_page/qr_code_page_widget.dart b/lib/pages/qr_code_page/qr_code_page_widget.dart index 0b6e3f29..c2aae8b3 100644 --- a/lib/pages/qr_code_page/qr_code_page_widget.dart +++ b/lib/pages/qr_code_page/qr_code_page_widget.dart @@ -6,7 +6,6 @@ import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:hub/actions/actions.dart'; import 'package:hub/components/templates_components/qr_code_pass_key_template_component/qr_code_pass_key_template_component_widget.dart'; import 'package:hub/flutter_flow/custom_functions.dart'; import 'package:hub/flutter_flow/flutter_flow_animations.dart'; @@ -146,7 +145,7 @@ class _QrCodePageWidgetState extends State ? await _showBiometricsAuth(context) : await _showQrCodeBottomSheet(context); }, - child: buildQrCode( + child: _model.buildQrCode( dimension: dimension, errorCorrectLevel: QrErrorCorrectLevel.M, identifier: _model.userDevUUID, diff --git a/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart b/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart index 9e0ae402..625efa57 100644 --- a/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart +++ b/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart @@ -5,7 +5,6 @@ import 'package:flutter/scheduler.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:hub/actions/actions.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/atomic_components/shared_components_atoms/toast.dart'; import 'package:hub/components/templates_components/details_component/details_component_widget.dart'; @@ -21,6 +20,7 @@ import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart'; import 'package:hub/pages/visit_history_page/visit_history_page_widget.dart'; import 'package:hub/shared/utils/dialog_util.dart'; +import 'package:hub/shared/utils/share_util.dart'; import 'package:provider/provider.dart'; class ScheduleCompleteVisitPageWidget extends StatefulWidget { @@ -1500,6 +1500,7 @@ Widget scheduleVisit(BuildContext context, controller: _model.textController3, focusNode: _model.textFieldFocusNode3, autofocus: false, + cursorColor: FlutterFlowTheme.of(context).primary, textInputAction: TextInputAction.next, obscureText: false, decoration: InputDecoration( @@ -1640,7 +1641,7 @@ Widget scheduleVisit(BuildContext context, gravity: ToastGravity.TOP, backgroundColor: Colors.green); - await showShare(value.jsonBody); + await ShareUtil.showShare(value.jsonBody); } else { await DialogUtil.errorDefault(context); context.pop(); diff --git a/lib/pages/sign_in_page/sign_in_page_widget.dart b/lib/pages/sign_in_page/sign_in_page_widget.dart index 23b13170..ecb7180d 100644 --- a/lib/pages/sign_in_page/sign_in_page_widget.dart +++ b/lib/pages/sign_in_page/sign_in_page_widget.dart @@ -1,12 +1,13 @@ +import 'package:hub/shared/mixins/switcher_mixin.dart'; + import '/components/templates_components/sign_in_template_component/sign_in_template_component_widget.dart'; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; -import '/actions/actions.dart' as action_blocks; import 'package:flutter/material.dart'; import 'sign_in_page_model.dart'; export 'sign_in_page_model.dart'; -class SignInPageWidget extends StatefulWidget { +class SignInPageWidget extends StatefulWidget with Switcher { const SignInPageWidget({super.key}); @override @@ -48,7 +49,7 @@ class _SignInPageWidgetState extends State { updateOnChange: true, child: SignInTemplateComponentWidget( toggleSignUpPage: () async { - await action_blocks.toggleSignUpPage(context); + await Switcher.toggleSignUpPage(context); }, ), ), @@ -56,4 +57,4 @@ class _SignInPageWidgetState extends State { ), ); } -} \ No newline at end of file +} diff --git a/lib/pages/sign_up_page/sign_up_page_widget.dart b/lib/pages/sign_up_page/sign_up_page_widget.dart index 8d68605b..4af08b3a 100644 --- a/lib/pages/sign_up_page/sign_up_page_widget.dart +++ b/lib/pages/sign_up_page/sign_up_page_widget.dart @@ -1,12 +1,13 @@ +import 'package:hub/shared/mixins/switcher_mixin.dart'; + import '/components/templates_components/sign_up_template_component/sign_up_template_component_widget.dart'; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; -import '/actions/actions.dart' as action_blocks; import 'package:flutter/material.dart'; import 'sign_up_page_model.dart'; export 'sign_up_page_model.dart'; -class SignUpPageWidget extends StatefulWidget { +class SignUpPageWidget extends StatefulWidget with Switcher { const SignUpPageWidget({super.key}); @override @@ -48,7 +49,7 @@ class _SignUpPageWidgetState extends State { updateOnChange: true, child: SignUpTemplateComponentWidget( toggleSignInPage: () async { - await action_blocks.toggleSignInPage(context); + await Switcher.toggleSignInPage(context); setState(() {}); }, ), @@ -57,4 +58,4 @@ class _SignUpPageWidgetState extends State { ), ); } -} \ No newline at end of file +} diff --git a/lib/pages/visit_history_page/visit_history_page_model.dart b/lib/pages/visit_history_page/visit_history_page_model.dart index 8b137891..574a33e3 100644 --- a/lib/pages/visit_history_page/visit_history_page_model.dart +++ b/lib/pages/visit_history_page/visit_history_page_model.dart @@ -1 +1,67 @@ +import 'package:flutter/src/widgets/framework.dart'; +import 'package:hub/backend/api_requests/api_calls.dart'; +import 'package:hub/backend/api_requests/api_manager.dart'; +import 'package:hub/flutter_flow/flutter_flow_model.dart'; +import 'package:hub/flutter_flow/nav/nav.dart'; +import 'package:hub/pages/visit_history_page/visit_history_page_widget.dart'; +class VisitHistoryModel extends FlutterFlowModel { + @override + void dispose() { + // TODO: implement dispose + } + + @override + void initState(BuildContext context) { + // TODO: implement initState + } + + Future changeStatusAction( + BuildContext context, + int idDestino, + int idVisita, + String accessKey, + String email, + ) async { + // Navigator.pop(context, true); + context.pop(true); + + bool? blockVisitRequest; + blockVisitRequest = await visitCancelAction( + context, + accessKey: accessKey, + idDestino: idDestino, + idVisita: idVisita, + email: email, + ); + if (!context.mounted) return; + if (blockVisitRequest == true) { + return true; + } else { + return false; + } + } + + Future visitCancelAction(BuildContext context, + {required int? idDestino, + required int? idVisita, + required String? accessKey, + required String? email}) async { + final ApiCallResponse? response; + final CancelaVisita callback = PhpGroup.cancelaVisita; + + response = await callback.call( + idDestino: idDestino, + idVisita: idVisita, + AccessKey: accessKey, + UsuEmail: email, + DevDesc: '', + ); + + if (response.statusCode == 200) { + return !response.jsonBody['error']; + } else { + return false; + } + } +} diff --git a/lib/pages/visit_history_page/visit_history_page_widget.dart b/lib/pages/visit_history_page/visit_history_page_widget.dart index 45072dfb..f7773f11 100644 --- a/lib/pages/visit_history_page/visit_history_page_widget.dart +++ b/lib/pages/visit_history_page/visit_history_page_widget.dart @@ -1,12 +1,13 @@ import 'package:flutter/material.dart'; -import 'package:hub/actions/actions.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.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_util.dart'; import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart'; +import 'package:hub/pages/visit_history_page/visit_history_page_model.dart'; import 'package:hub/shared/helpers/db_helper.dart'; +import 'package:hub/shared/mixins/status_mixin.dart'; import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/validator_util.dart'; @@ -19,7 +20,7 @@ class VisitHistoryWidget extends StatefulWidget { } class _VisitHistoryWidgetState extends State - with TickerProviderStateMixin { + with TickerProviderStateMixin, Status { final DatabaseHelper db = DatabaseHelper(); late final String devUUID; late final String userUUID; @@ -29,6 +30,7 @@ class _VisitHistoryWidgetState extends State final int _pageSize = 10; bool _hasData = false; bool _loading = false; + late VisitHistoryModel _model; late Future _visitFuture; List _visitWrap = []; @@ -48,6 +50,8 @@ class _VisitHistoryWidgetState extends State @override void initState() { super.initState(); + + _model = createModel(context, () => VisitHistoryModel()); _initVariables(); _visitFuture = _fetchVisits(); @@ -200,42 +204,47 @@ class _VisitHistoryWidgetState extends State : '', }, statusHashMap: [ - if (getStatus(visitaWrapItem['VAW_STATUS']) == status.active) + if (Status.getStatus(visitaWrapItem['VAW_STATUS']) == StatusEnum.active) { FFLocalizations.of(context).getVariableText( ptText: 'Ativo', enText: 'Active', ): FlutterFlowTheme.of(context).warning, }, - if (getStatus(visitaWrapItem['VAW_STATUS']) == status.finished) + if (Status.getStatus(visitaWrapItem['VAW_STATUS']) == + StatusEnum.finished) { FFLocalizations.of(context).getVariableText( ptText: 'Finalizado', enText: 'Finished', ): FlutterFlowTheme.of(context).success, }, - if (getStatus(visitaWrapItem['VAW_STATUS']) == status.unknown) + if (Status.getStatus(visitaWrapItem['VAW_STATUS']) == + StatusEnum.unknown) { FFLocalizations.of(context).getVariableText( ptText: 'Desconhecido', enText: 'Unknown', ): FlutterFlowTheme.of(context).alternate, }, - if (getStatus(visitaWrapItem['VAW_STATUS']) == status.canceled) + if (Status.getStatus(visitaWrapItem['VAW_STATUS']) == + StatusEnum.canceled) { FFLocalizations.of(context).getVariableText( ptText: 'Cancelado', enText: 'Canceled', ): FlutterFlowTheme.of(context).error, }, - if (getStatus(visitaWrapItem['VAW_STATUS']) == status.blocked) + if (Status.getStatus(visitaWrapItem['VAW_STATUS']) == + StatusEnum.blocked) { FFLocalizations.of(context).getVariableText( ptText: 'Bloqueado', enText: 'Blocked', ): FlutterFlowTheme.of(context).error, }, - if (getStatus(visitaWrapItem['VAW_STATUS']) == status.inactive) + if (Status.getStatus(visitaWrapItem['VAW_STATUS']) == + StatusEnum.inactive) { FFLocalizations.of(context).getVariableText( ptText: 'Inativo', @@ -266,7 +275,7 @@ class _VisitHistoryWidgetState extends State child: buildVisitDetails( item: visitaWrapItem, context: context, - changeStatusAction: changeStatusAction, + changeStatusAction: _model.changeStatusAction, devUUID: devUUID, userUUID: userUUID, cliUUID: cliUUID, diff --git a/lib/pages/welcome_page/welcome_page_widget.dart b/lib/pages/welcome_page/welcome_page_widget.dart index 9df3c31b..6b74a753 100644 --- a/lib/pages/welcome_page/welcome_page_widget.dart +++ b/lib/pages/welcome_page/welcome_page_widget.dart @@ -1,14 +1,15 @@ +import 'package:hub/shared/mixins/switcher_mixin.dart'; + import '/components/templates_components/welcome_template_component/welcome_template_component_widget.dart'; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; -import '/actions/actions.dart' as action_blocks; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:provider/provider.dart'; import 'welcome_page_model.dart'; export 'welcome_page_model.dart'; -class WelcomePageWidget extends StatefulWidget { +class WelcomePageWidget extends StatefulWidget with Switcher { const WelcomePageWidget({super.key}); @override @@ -66,10 +67,10 @@ class _WelcomePageWidgetState extends State { updateOnChange: true, child: WelcomeTemplateComponentWidget( toggleSignUpPage: () async { - await action_blocks.toggleSignUpPage(context); + await Switcher.toggleSignUpPage(context); }, toggleSignInPage: () async { - await action_blocks.toggleSignInPage(context); + await Switcher.toggleSignInPage(context); }, ), ), diff --git a/lib/shared/mixins/status_mixin.dart b/lib/shared/mixins/status_mixin.dart new file mode 100644 index 00000000..8167f449 --- /dev/null +++ b/lib/shared/mixins/status_mixin.dart @@ -0,0 +1,20 @@ +enum StatusEnum { active, unknown, canceled, finished, blocked, inactive } + +mixin Status { + static StatusEnum? getStatus(dynamic data) { + switch (data) { + case 'A': + return StatusEnum.active; + case 'F': + return StatusEnum.finished; + case 'B': + return StatusEnum.blocked; + case 'C': + return StatusEnum.canceled; + case 'I': + return StatusEnum.inactive; + default: + return StatusEnum.unknown; + } + } +} diff --git a/lib/shared/mixins/switcher_mixin.dart b/lib/shared/mixins/switcher_mixin.dart new file mode 100644 index 00000000..ef0ed7e2 --- /dev/null +++ b/lib/shared/mixins/switcher_mixin.dart @@ -0,0 +1,29 @@ +import 'package:flutter/material.dart'; +import 'package:hub/flutter_flow/flutter_flow_util.dart'; +import 'package:hub/flutter_flow/nav/nav.dart'; + +mixin Switcher { + static Future toggleSignInPage(BuildContext context) async { + context.go( + '/signInPage', + extra: { + kTransitionInfoKey: const TransitionInfo( + hasTransition: true, + transitionType: PageTransitionType.fade, + ), + }, + ); + } + + static Future toggleSignUpPage(BuildContext context) async { + context.go( + '/signUpPage', + extra: { + kTransitionInfoKey: const TransitionInfo( + hasTransition: true, + transitionType: PageTransitionType.fade, + ), + }, + ); + } +} diff --git a/lib/shared/utils/share_util.dart b/lib/shared/utils/share_util.dart new file mode 100644 index 00000000..bfcb1cec --- /dev/null +++ b/lib/shared/utils/share_util.dart @@ -0,0 +1,26 @@ +import 'package:hub/shared/helpers/db_helper.dart'; +import 'package:share_plus/share_plus.dart'; + +class ShareUtil { + static Future 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++) { + await Share.share(''' +Olá, \*${payload['convites'][i]['VTE_NOME']}\*! Você foi convidado para \*$cliName\*. + +\*Validade do Convite\*: +- Início: ${payload['convites'][i]['VAW_DTINICIO']} +- Fim: ${payload['convites'][i]['VAW_DTFIM']} + +URL do Convite: https://visita.freaccess.com.br/${payload['convites'][i]['VAW_ID']}/$cliUUID/${payload['convites'][i]['VAW_CHAVE']} + '''); + } + } +} From f493c0744e965bac8ab14f2fff849a77d06e6678 Mon Sep 17 00:00:00 2001 From: "J. A. Messias" Date: Thu, 19 Sep 2024 17:44:28 -0300 Subject: [PATCH 2/3] WIP --- lib/backend/api_requests/api_manager.dart | 17 +- .../details_component_action.dart | 1 - ...iter_vistor_template_component_widget.dart | 4 +- .../sign_in_template_component_model.dart | 4 +- .../actions/convert_image_file_to_base64.dart | 17 -- .../actions/convert_to_upload_file.dart | 31 --- lib/custom_code/actions/get_dev_u_u_i_d.dart | 34 --- lib/custom_code/actions/index.dart | 3 - lib/custom_code/widgets/index.dart | 1 - lib/custom_code/widgets/menu.dart | 61 ----- lib/flutter_flow/custom_functions.dart | 33 +-- lib/flutter_flow/nav/nav.dart | 2 +- lib/index.dart | 24 +- .../acess_history_page_model.dart | 137 +++++++++- .../acess_history_page_widget.dart | 248 +++++++++--------- .../people_on_the_property_page_model.dart | 3 +- lib/pages/pets_page/pets_page_model.dart | 9 +- lib/pages/pets_page/pets_page_widget.dart | 8 +- lib/shared/utils/device_util.dart | 35 +++ lib/shared/utils/image_util.dart | 38 +++ .../image_cropper_widget}/image_cropper.dart | 0 lib/shared/widgets/menu.dart | 58 ++++ 22 files changed, 415 insertions(+), 353 deletions(-) delete mode 100644 lib/custom_code/actions/convert_image_file_to_base64.dart delete mode 100644 lib/custom_code/actions/convert_to_upload_file.dart delete mode 100644 lib/custom_code/actions/get_dev_u_u_i_d.dart delete mode 100644 lib/custom_code/actions/index.dart delete mode 100644 lib/custom_code/widgets/index.dart delete mode 100644 lib/custom_code/widgets/menu.dart create mode 100644 lib/shared/utils/device_util.dart create mode 100644 lib/shared/utils/image_util.dart rename lib/{custom_code/widgets => shared/widgets/image_cropper_widget}/image_cropper.dart (100%) create mode 100644 lib/shared/widgets/menu.dart diff --git a/lib/backend/api_requests/api_manager.dart b/lib/backend/api_requests/api_manager.dart index 57c421d5..aaaef549 100644 --- a/lib/backend/api_requests/api_manager.dart +++ b/lib/backend/api_requests/api_manager.dart @@ -15,22 +15,9 @@ import 'package:mime_type/mime_type.dart'; import '/flutter_flow/uploaded_file.dart'; import 'get_streamed_response.dart'; -enum ApiCallType { - GET, - POST, - DELETE, - PUT, - PATCH, -} +enum ApiCallType { GET, POST, DELETE, PUT, PATCH } -enum BodyType { - NONE, - JSON, - TEXT, - X_WWW_FORM_URL_ENCODED, - MULTIPART, - BLOB, -} +enum BodyType { NONE, JSON, TEXT, X_WWW_FORM_URL_ENCODED, MULTIPART, BLOB } class ApiCallOptions extends Equatable { const ApiCallOptions({ diff --git a/lib/components/templates_components/details_component/details_component_action.dart b/lib/components/templates_components/details_component/details_component_action.dart index 48dbabee..d4c2d9a3 100644 --- a/lib/components/templates_components/details_component/details_component_action.dart +++ b/lib/components/templates_components/details_component/details_component_action.dart @@ -5,7 +5,6 @@ import 'package:flutter/material.dart'; import 'package:http/http.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/templates_components/details_component/details_component_widget.dart'; -import 'package:hub/custom_code/actions/convert_to_upload_file.dart'; import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; diff --git a/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart b/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart index 3abfdf48..f1988f78 100644 --- a/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart +++ b/lib/components/templates_components/regisiter_vistor_template_component/regisiter_vistor_template_component_widget.dart @@ -3,12 +3,12 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:hub/shared/utils/dialog_util.dart'; +import 'package:hub/shared/utils/image_util.dart'; import 'package:hub/shared/utils/validator_util.dart'; import 'package:provider/provider.dart'; import 'package:rxdart/rxdart.dart'; import '/backend/api_requests/api_calls.dart'; -import '/custom_code/actions/index.dart' as actions; import '/flutter_flow/flutter_flow_drop_down.dart'; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; @@ -843,7 +843,7 @@ class _RegisiterVistorTemplateComponentWidgetState onPressed: _isFormValid(context) ? () async { _model.imgBase64 = - await actions.convertImageFileToBase64( + await ImageUtils.convertImageFileToBase64( _model.uploadedLocalFile, ); _model.scheduleVisitor = diff --git a/lib/components/templates_components/sign_in_template_component/sign_in_template_component_model.dart b/lib/components/templates_components/sign_in_template_component/sign_in_template_component_model.dart index 4869dc1f..e17c09d5 100644 --- a/lib/components/templates_components/sign_in_template_component/sign_in_template_component_model.dart +++ b/lib/components/templates_components/sign_in_template_component/sign_in_template_component_model.dart @@ -1,10 +1,10 @@ import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_manager.dart'; -import 'package:hub/custom_code/actions/get_dev_u_u_i_d.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/random_data_util.dart'; import 'package:hub/pages/home_page/home_page_model.dart'; import 'package:hub/shared/helpers/db_helper.dart'; +import 'package:hub/shared/utils/device_util.dart'; import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/log_util.dart'; @@ -108,7 +108,7 @@ class SignInTemplateComponentModel email = emailAdress!; passwd = password!; - devUUID = await getDevUUID(); + devUUID = await DeviceUtil.getDevUUID(); if ((email != '') && (passwd != '')) { AppState().email = email; diff --git a/lib/custom_code/actions/convert_image_file_to_base64.dart b/lib/custom_code/actions/convert_image_file_to_base64.dart deleted file mode 100644 index 33f4fd83..00000000 --- a/lib/custom_code/actions/convert_image_file_to_base64.dart +++ /dev/null @@ -1,17 +0,0 @@ - - -// Automatic FlutterFlow imports - -import 'index.dart'; // Imports other custom actions -import 'package:flutter/material.dart'; -import 'dart:convert'; -import 'dart:typed_data'; -import '../../flutter_flow/uploaded_file.dart'; - -Future convertImageFileToBase64(FFUploadedFile imageFile) async { - List? imageBytes = imageFile.bytes; - if (imageBytes != null) { - String base64Image = base64Encode(imageBytes); - return base64Image; - } -} \ No newline at end of file diff --git a/lib/custom_code/actions/convert_to_upload_file.dart b/lib/custom_code/actions/convert_to_upload_file.dart deleted file mode 100644 index 709be7ad..00000000 --- a/lib/custom_code/actions/convert_to_upload_file.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Automatic FlutterFlow imports -import '/backend/schema/structs/index.dart'; -import '/backend/schema/enums/enums.dart'; -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'index.dart'; // Imports other custom actions -import '/flutter_flow/custom_functions.dart'; // Imports custom functions -import 'package:flutter/material.dart'; -// Begin custom action code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -import 'dart:convert'; // Import for base64 decoding -import 'dart:io'; // Import for file operations -import 'package:path_provider/path_provider.dart'; // Import for temporary directory - -Future convertToUploadFile(String img) async { - // Decode the base64 string into bytes - Uint8List bytes = base64.decode(img); - - // Create a temporary file to store the image - final tempDir = await getTemporaryDirectory(); - final tempPath = tempDir.path; - final tempFile = await File('$tempPath/image.jpg').create(); - await tempFile.writeAsBytes(bytes); - - // Create an FFUploadedFile object using the temporary file - return FFUploadedFile( - bytes: bytes, - name: 'image.jpg', - ); -} diff --git a/lib/custom_code/actions/get_dev_u_u_i_d.dart b/lib/custom_code/actions/get_dev_u_u_i_d.dart deleted file mode 100644 index 1be7def9..00000000 --- a/lib/custom_code/actions/get_dev_u_u_i_d.dart +++ /dev/null @@ -1,34 +0,0 @@ -import '/backend/schema/structs/index.dart'; -import 'dart:developer'; -import '/backend/schema/enums/enums.dart'; -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'index.dart'; // Imports other custom actions -import '/flutter_flow/custom_functions.dart'; // Imports custom functions -import 'package:flutter/material.dart'; -import 'dart:io'; -import 'package:device_info_plus/device_info_plus.dart'; - -Future getDevUUID() async { - var deviceInfo = DeviceInfoPlugin(); - if (Platform.isIOS) { - // import 'dart:io' - var iosDeviceInfo = await deviceInfo.iosInfo; - return iosDeviceInfo.identifierForVendor; // unique ID on iOS - } else if (Platform.isAndroid) { - var androidDeviceInfo = await deviceInfo.androidInfo; - return androidDeviceInfo.id; // unique ID on Android - } -} - -Future getSerialNumber() async { - var deviceInfo = DeviceInfoPlugin(); - if (Platform.isIOS) { - // import 'dart:io' - var iosDeviceInfo = await deviceInfo.iosInfo; - return iosDeviceInfo.identifierForVendor; // unique ID on iOS - } else if (Platform.isAndroid) { - var androidDeviceInfo = await deviceInfo.androidInfo; - return androidDeviceInfo.serialNumber; // unique ID on Android - } -} diff --git a/lib/custom_code/actions/index.dart b/lib/custom_code/actions/index.dart deleted file mode 100644 index 2110f043..00000000 --- a/lib/custom_code/actions/index.dart +++ /dev/null @@ -1,3 +0,0 @@ -export 'convert_image_file_to_base64.dart' show convertImageFileToBase64; -export 'convert_to_upload_file.dart' show convertToUploadFile; -export 'get_dev_u_u_i_d.dart' show getDevUUID; diff --git a/lib/custom_code/widgets/index.dart b/lib/custom_code/widgets/index.dart deleted file mode 100644 index ec35fd3e..00000000 --- a/lib/custom_code/widgets/index.dart +++ /dev/null @@ -1 +0,0 @@ -export 'image_cropper.dart' show ImageCropper; diff --git a/lib/custom_code/widgets/menu.dart b/lib/custom_code/widgets/menu.dart deleted file mode 100644 index b3fa00c7..00000000 --- a/lib/custom_code/widgets/menu.dart +++ /dev/null @@ -1,61 +0,0 @@ - -import 'dart:collection'; - -import 'package:flutter/material.dart'; - -LinkedHashMap menu = LinkedHashMap.from({ - "Schedule": - [{ - "title": "Schedule\nVisit", - "icon": Icons.settings, - "route": "/Schedule", - }, - { - "title": "Complete\Schedule", - "icon": Icons.calendar_today, - "route": "/Complete", - }, - { - "title": "Provisional\Schedule", - "icon": Icons.calendar_today, - "route": "/Provisional", - }, - { - "title": "Fast\Schedule", - "icon": Icons.calendar_today, - "route": "/Fast", - }], - "Consult": - [{ - "title": "Consult", - "icon": Icons.search, - "route": "/consult", - }, - { - "title": "Liberation\nConsult", - "icon": Icons.search, - "route": "/Liberation", - }, - { - "title": "Access\nConsult", - "icon": Icons.search, - "route": "/Access", - }, - { - "title": "Poeple\nConsult", - "icon": Icons.search, - "route": "/Poeple", - }, - { - "title": "QR Code\nConsult", - "icon": Icons.search, - "route": "/qrcode", - }], - "Preferences": - [{ - "title": "Preferences", - "icon": Icons.settings, - "route": "/preferences", - }], - -}); \ No newline at end of file diff --git a/lib/flutter_flow/custom_functions.dart b/lib/flutter_flow/custom_functions.dart index f33176c1..ddd01694 100644 --- a/lib/flutter_flow/custom_functions.dart +++ b/lib/flutter_flow/custom_functions.dart @@ -9,48 +9,23 @@ import 'lat_lng.dart'; import 'place.dart'; import 'uploaded_file.dart'; - -String? isOneAcliID(String jsonString) { - // Converte o JSON em um Map - final Map data = jsonDecode(jsonString); - - // Extrai a lista de locais - final List locais = data['locais']; - - // Filtra os locais onde CLU_STATUS é igual a "A" - final List locaisAtivos = - locais.where((local) => local['CLU_STATUS'] == 'A').toList(); - - // Verifica se existe somente um local ativo - if (locaisAtivos.length == 1) { - return locaisAtivos.first['CLI_ID']; - } else { - return null; - } -} - String? convertToUppercase(String input) { - // recebe uuma string qualquer e retorna ela em uppercase return input.toUpperCase(); } String? uploadFileToBase64(String? uploadFile) { - // takes an UploadFile of an image as an argument and returns a base64 string of that image if (uploadFile == null) { return null; } - // Converte a string em uma lista de inteiros final List bytes = uploadFile.codeUnits; - // Converte os bytes em uma string base64 final String base64String = base64.encode(bytes); return base64String; } String jsonListToStr(List visitorList) { - // rece um json list e retorna uma string de $.visitante.VTE_DOCUMENTO separado por virgula String result = ''; for (var visitor in visitorList) { result += '${visitor['VTE_DOCUMENTO']},'; @@ -62,7 +37,6 @@ List listStrJsonToJsonList( dynamic jsonList, List strList, ) { - // Recebe um jsonList e uma stringList como argumento e retorna uma nova jsonList associando cada item List result = []; for (int i = 0; i < jsonList.length; i++) { @@ -79,13 +53,10 @@ List listStrJsonToJsonList( } String strListToStr(List strList) { - // recebe uma stringList como argumento e retorna uma str com cada item da strList separado por virgula - return strList.join(','); } int extractIdToStr(String str) { - // recebe um uma string e retorna um inteiro com o valor entre '_ID:' e a próxima vírgula ',' final idStart = str.indexOf('_ID:') + 4; final idEnd = str.indexOf(',', idStart); final idStr = str.substring(idStart, idEnd); @@ -93,14 +64,12 @@ int extractIdToStr(String str) { } String extractDescToStr(String str) { - // recebe um uma string e retorna uma string com o valor entre '_DESCRICAO' e a próxima vírgula ',' final startIndex = str.indexOf('_DESCRICAO:') + '_DESCRICAO:'.length; final endIndex = str.indexOf(',', startIndex); return str.substring(startIndex, endIndex); } String jsonToStr(dynamic json) { - // recebe um json como parametro, converte-o em string e retorna essa string String jsonString = jsonEncode(json); return jsonString; } @@ -115,4 +84,4 @@ Stream getProgressValue() { final progress = math.max(0.0, 1.0 - (elapsedTime / (endTime - startTime))); return progress; }); -} \ No newline at end of file +} diff --git a/lib/flutter_flow/nav/nav.dart b/lib/flutter_flow/nav/nav.dart index a2f8afbc..a10061f8 100644 --- a/lib/flutter_flow/nav/nav.dart +++ b/lib/flutter_flow/nav/nav.dart @@ -155,7 +155,7 @@ GoRouter createRouter(AppStateNotifier appStateNotifier) => GoRouter( FFRoute( name: 'acessHistoryPage', path: '/acessHistoryPage', - builder: (context, params) => AcessHistoryPageWidget(opt: const { + builder: (context, params) => AccessHistoryScreen(opt: const { 'personType': '.*', 'accessType': '.*', 'search': '.*', diff --git a/lib/index.dart b/lib/index.dart index 28c34aa1..3278d9b5 100644 --- a/lib/index.dart +++ b/lib/index.dart @@ -1,17 +1,17 @@ -export '/pages/acess_history_page/acess_history_page_widget.dart' - show AcessHistoryPageWidget; -export '/pages/home_page/home_page_widget.dart' show HomePageWidget; -export '/pages/liberation_history/liberation_history_widget.dart' +export 'pages/acess_history_page/acess_history_page_widget.dart' + show AccessHistoryScreen; +export 'pages/home_page/home_page_widget.dart' show HomePageWidget; +export 'pages/liberation_history/liberation_history_widget.dart' show LiberationHistoryWidget; -export '/pages/people_on_the_property_page/people_on_the_property_page_widget.dart' +export 'pages/people_on_the_property_page/people_on_the_property_page_widget.dart' show PeopleOnThePropertyPageWidget; -export '/pages/preferences_settings_page/preferences_settings_widget.dart' +export 'pages/preferences_settings_page/preferences_settings_widget.dart' show PreferencesPageWidget; -export '/pages/qr_code_page/qr_code_page_widget.dart' show QrCodePageWidget; -export '/pages/register_visitor_page/register_visitor_page_widget.dart' +export 'pages/qr_code_page/qr_code_page_widget.dart' show QrCodePageWidget; +export 'pages/register_visitor_page/register_visitor_page_widget.dart' show RegisterVisitorPageWidget; -export '/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart' +export 'pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart' show ScheduleCompleteVisitPageWidget; -export '/pages/sign_in_page/sign_in_page_widget.dart' show SignInPageWidget; -export '/pages/sign_up_page/sign_up_page_widget.dart' show SignUpPageWidget; -export '/pages/welcome_page/welcome_page_widget.dart' show WelcomePageWidget; +export 'pages/sign_in_page/sign_in_page_widget.dart' show SignInPageWidget; +export 'pages/sign_up_page/sign_up_page_widget.dart' show SignUpPageWidget; +export 'pages/welcome_page/welcome_page_widget.dart' show WelcomePageWidget; diff --git a/lib/pages/acess_history_page/acess_history_page_model.dart b/lib/pages/acess_history_page/acess_history_page_model.dart index d8402b2b..fcfbb302 100644 --- a/lib/pages/acess_history_page/acess_history_page_model.dart +++ b/lib/pages/acess_history_page/acess_history_page_model.dart @@ -1,16 +1,48 @@ import 'package:flutter/material.dart'; +import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_manager.dart'; import 'package:hub/components/molecular_components/message_opt_modal/opt_modal_widget.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; +import 'package:hub/flutter_flow/flutter_flow_theme.dart'; +import 'package:hub/flutter_flow/internationalization.dart'; import 'package:hub/flutter_flow/request_manager.dart'; import 'package:hub/pages/acess_history_page/acess_history_page_widget.dart'; import 'package:hub/shared/helpers/db_helper.dart'; +import 'package:hub/shared/utils/dialog_util.dart'; +import 'package:hub/shared/utils/log_util.dart'; +import 'package:rxdart/rxdart.dart'; + +class AccessHistoryModel extends FlutterFlowModel { + // Singleton instance + static final AccessHistoryModel _instance = AccessHistoryModel._internal(); + + // Private constructor + AccessHistoryModel._internal() : super(); + + // Factory constructor to return the singleton instance + factory AccessHistoryModel() { + return _instance; + } -class AcessHistoryPageModel extends FlutterFlowModel { final DatabaseHelper db = DatabaseHelper(); late final String devUUID; late final String userUUID; late final String cliUUID; + final BehaviorSubject> selectedTypeSubject; + bool isSubjectClosed = false; + final scaffoldKey = GlobalKey(); + late Function(Function) safeSetState; + + late ScrollController scrollController; + int pageNumber = 1; + final int pageSize = 10; + bool hasData = false; + bool loading = false; + + String personType = '.*'; + + late Future accessFuture; + List accessWrap = []; final unfocusNode = FocusNode(); final _accessHistoryManager = FutureRequestManager(); @@ -30,10 +62,10 @@ class AcessHistoryPageModel extends FlutterFlowModel { @override void initState(BuildContext context) { - initDatabase(); + _initAsync(); } - Future initDatabase() async { + Future _initAsync() async { devUUID = await db .get(key: 'devUUID', field: 'value') .then((value) => value.toString()); @@ -45,11 +77,95 @@ class AcessHistoryPageModel extends FlutterFlowModel { .then((value) => value.toString()); } - @override - void dispose() { - unfocusNode.dispose(); + void _updateAccessHistoryAction( + Map newType, BuildContext context) { + if (!isSubjectClosed) { + final currentType = selectedTypeSubject.value; + final updatedType = Map.from(currentType); + bool needsUpdate = false; + newType.forEach((key, newValue) { + if (currentType[key] != newValue) { + updatedType[key] = newValue; + needsUpdate = true; + } + }); + if (needsUpdate) { + selectedTypeSubject.add(updatedType); + fetchCardListViewService(updatedType, context); + safeSetState?.call(() {}); + } + } + } - clearAccessHistoryCache(); + Future fetchAccessHistoryService( + BuildContext context) async { + try { + safeSetState.call(() => loading = true); + var response = await PhpGroup.getAccessCall.call( + pageSize: pageSize.toString(), + pageNumber: pageNumber.toString(), + pesTipo: personType != 'E' && personType != 'O' ? 'T' : personType, + ); + + final List accessHistory = response.jsonBody['acessos'] ?? []; + + List filteredAccess = accessHistory.where((item) { + final personTypeMatches = + personType == '.*' || item["PES_TIPO"].toString() == personType; + return personTypeMatches; + }).toList(); + + if (filteredAccess != null && filteredAccess.isNotEmpty) { + safeSetState.call(() { + accessWrap.addAll(filteredAccess); + hasData = true; + loading = false; + }); + return response; + } + _showNoMoreDataSnackbar(context); + safeSetState.call(() { + hasData = false; + loading = false; + }); + return null; + } catch (e, s) { + DialogUtil.errorDefault(context); + LogUtil.requestAPIFailed('processRequest', "", "Busca Acesso", e, s); + safeSetState.call(() { + hasData = false; + loading = false; + }); + } + return null; + } + + void _showNoMoreDataSnackbar(BuildContext context) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + FFLocalizations.of(context).getVariableText( + ptText: "Não há mais dados.", enText: "No more data."), + ), + duration: const Duration(seconds: 3), + backgroundColor: FlutterFlowTheme.of(context).primary, + ), + ); + } + + void _loadMoreAccess(BuildContext context) { + if (hasData == true) { + pageNumber++; + accessFuture = fetchAccessHistoryService(context); + } + } + + void fetchCardListViewService( + Map select, BuildContext context) { + personType = select['personType']!; + accessWrap = []; + pageNumber = 1; + accessFuture = fetchAccessHistoryService(context); } Future toggleOptionsAction(BuildContext context) async { @@ -71,4 +187,11 @@ class AcessHistoryPageModel extends FlutterFlowModel { }, ); } + + @override + void dispose() { + unfocusNode.dispose(); + + clearAccessHistoryCache(); + } } diff --git a/lib/pages/acess_history_page/acess_history_page_widget.dart b/lib/pages/acess_history_page/acess_history_page_widget.dart index d0cfcf45..4876f91c 100644 --- a/lib/pages/acess_history_page/acess_history_page_widget.dart +++ b/lib/pages/acess_history_page/acess_history_page_widget.dart @@ -15,36 +15,22 @@ import 'package:hub/shared/utils/log_util.dart'; import 'package:rxdart/rxdart.dart'; @immutable -class AcessHistoryPageWidget extends StatefulWidget { +// ignore: must_be_immutable +class AccessHistoryScreen extends StatefulWidget { late Map opt = { 'personType': '.*', 'accessType': '.*', 'search': '.*', }; - AcessHistoryPageWidget({super.key, required this.opt}); + AccessHistoryScreen({super.key, required this.opt}); @override - State createState() => - _AcessHistoryPageWidgetState(opt); + State createState() => _AccessHistoryScreenState(opt); } -class _AcessHistoryPageWidgetState extends State { - late AcessHistoryPageModel _model; - final BehaviorSubject> selectedTypeSubject; - bool _isSubjectClosed = false; - final scaffoldKey = GlobalKey(); +class _AccessHistoryScreenState extends State { + late AccessHistoryModel _model; - late ScrollController _scrollController; - int _pageNumber = 1; - final int _pageSize = 10; - bool _hasData = false; - bool _loading = false; - - String _personType = '.*'; - - late Future _accessFuture; - List _accessWrap = []; - - _AcessHistoryPageWidgetState(Map opt) + _AccessHistoryScreenState(Map opt) : selectedTypeSubject = BehaviorSubject.seeded(opt) { selectedTypeSubject.listen((value) {}); } @@ -52,13 +38,13 @@ class _AcessHistoryPageWidgetState extends State { @override void initState() { super.initState(); - _model = createModel(context, () => AcessHistoryPageModel()); - _accessFuture = fetchAccessHistoryService(); + _model = createModel(context, () => AccessHistoryModel()); + _model.accessFuture = fetchAccessHistoryService(); - _scrollController = ScrollController() + _model.scrollController = ScrollController() ..addListener(() { - if (_scrollController.position.atEdge && - _scrollController.position.pixels != 0) { + if (_model.scrollController.position.atEdge && + _model.scrollController.position.pixels != 0) { _loadMoreAccess(); } }); @@ -67,7 +53,7 @@ class _AcessHistoryPageWidgetState extends State { @override void dispose() { selectedTypeSubject.close(); - _isSubjectClosed = true; + _model.isSubjectClosed = true; super.dispose(); } @@ -76,7 +62,7 @@ class _AcessHistoryPageWidgetState extends State { final theme = FlutterFlowTheme.of(context); return Scaffold( - key: scaffoldKey, + key: _model.scaffoldKey, backgroundColor: FlutterFlowTheme.of(context).primaryBackground, appBar: _appBar(context, theme), body: _body(context)); @@ -164,84 +150,13 @@ class _AcessHistoryPageWidgetState extends State { ); } - void _updateAccessHistoryAction(Map newType) { - if (!_isSubjectClosed) { - final currentType = selectedTypeSubject.value; - final updatedType = Map.from(currentType); - bool needsUpdate = false; - newType.forEach((key, newValue) { - if (currentType[key] != newValue) { - updatedType[key] = newValue; - needsUpdate = true; - } - }); - if (needsUpdate) { - selectedTypeSubject.add(updatedType); - fetchCardListViewService(updatedType); - safeSetState(() {}); - } - } - } - - Future fetchAccessHistoryService() async { - try { - setState(() => _loading = true); - var response = await PhpGroup.getAccessCall.call( - pageSize: _pageSize.toString(), - pageNumber: _pageNumber.toString(), - pesTipo: _personType != 'E' && _personType != 'O' ? 'T' : _personType, - ); - - final List accessHistory = response.jsonBody['acessos'] ?? []; - - List filteredAccess = accessHistory.where((item) { - final personTypeMatches = - _personType == '.*' || item["PES_TIPO"].toString() == _personType; - return personTypeMatches; - }).toList(); - - if (filteredAccess != null && filteredAccess.isNotEmpty) { - setState(() { - _accessWrap.addAll(filteredAccess); - _hasData = true; - _loading = false; - }); - return response; - } - _showNoMoreDataSnackbar(context); - setState(() { - _hasData = false; - _loading = false; - }); - return null; - } catch (e, s) { - DialogUtil.errorDefault(context); - LogUtil.requestAPIFailed('processRequest', "", "Busca Acesso", e, s); - setState(() { - _hasData = false; - _loading = false; - }); - } - } - - void _showNoMoreDataSnackbar(BuildContext context) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - ptText: "Não há mais dados.", enText: "No more data."), - ), - duration: const Duration(seconds: 3), - backgroundColor: FlutterFlowTheme.of(context).primary, - ), - ); - } - Widget _body(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ - if (_hasData == false && _pageNumber <= 1 && _loading == false) + if (_model.hasData == false && + _model.pageNumber <= 1 && + _model.loading == false) Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -256,9 +171,9 @@ class _AcessHistoryPageWidgetState extends State { ], ), ) - else if (_hasData || _pageNumber >= 1) + else if (_model.hasData || _model.pageNumber >= 1) Expanded(child: _cardListViewOrganismWidget()), - if (_hasData == true && _loading) + if (_model.hasData == true && _model.loading) Container( padding: const EdgeInsets.only(top: 15, bottom: 15), child: Center( @@ -273,26 +188,12 @@ class _AcessHistoryPageWidgetState extends State { ); } - void _loadMoreAccess() { - if (_hasData == true) { - _pageNumber++; - _accessFuture = fetchAccessHistoryService(); - } - } - - void fetchCardListViewService(Map select) { - _personType = select['personType']!; - _accessWrap = []; - _pageNumber = 1; - _accessFuture = fetchAccessHistoryService(); - } - Widget _cardListViewOrganismWidget() { return FutureBuilder( - future: _accessFuture, + future: _model.accessFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting && - _accessWrap.isEmpty) { + _model.accessWrap.isEmpty) { return Center( child: SizedBox( width: 50.0, @@ -314,10 +215,10 @@ class _AcessHistoryPageWidgetState extends State { return ListView.builder( shrinkWrap: true, physics: const BouncingScrollPhysics(), - controller: _scrollController, - itemCount: _accessWrap.length, + controller: _model.scrollController, + itemCount: _model.accessWrap.length, itemBuilder: (context, index) { - final accessHistoryItem = _accessWrap[index]; + final accessHistoryItem = _model.accessWrap[index]; return _accessHistoryCardMoleculeWidget(context, accessHistoryItem); }, ); @@ -396,3 +297,104 @@ class _AcessHistoryPageWidgetState extends State { ); } } + +class AccessHistoryAppBar extends StatelessWidget { + AccessHistoryAppBar(this.model, this.selectedTypeSubject); + final AccessHistoryModel model; + final BehaviorSubject> selectedTypeSubject; + + late final FlutterFlowTheme theme; + + @override + Widget build(BuildContext context) { + theme = FlutterFlowTheme.of(context); + + return AppBar( + backgroundColor: theme.primaryBackground, + automaticallyImplyLeading: false, + leading: _backButton(context, theme), + title: _title(context, theme), + centerTitle: true, + elevation: 0.0, + actions: [_filterButton(context)], + ); + } + + Widget _backButton(BuildContext context, FlutterFlowTheme theme) { + return FlutterFlowIconButton( + borderColor: Colors.transparent, + borderRadius: 30.0, + borderWidth: 1.0, + buttonSize: 60.0, + icon: Icon( + Icons.keyboard_arrow_left, + color: theme.primaryText, + size: 30.0, + ), + onPressed: () => Navigator.of(context).pop(), + ); + } + + Widget _title(BuildContext context, FlutterFlowTheme theme) { + return Text( + FFLocalizations.of(context).getText('ch8qymga'), + style: theme.headlineMedium.override( + fontFamily: theme.headlineMediumFamily, + color: theme.primaryText, + fontSize: 16.0, + letterSpacing: 0.0, + useGoogleFonts: + GoogleFonts.asMap().containsKey(theme.headlineMediumFamily), + ), + ); + } + + Widget _filterButton(BuildContext context) { + return Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(0, 0, 10, 0), + child: IconButton( + icon: const Icon(Icons.filter_list), + onPressed: () async { + final Map? selectedFilter = + await showModalBottomSheet>( + isScrollControlled: true, + backgroundColor: Colors.transparent, + context: context, + builder: (context) { + return GestureDetector( + onTap: () => Navigator.of(context).pop(), + child: Container( + color: Colors.transparent, + child: GestureDetector( + onTap: () {}, + child: OptModalWidget( + defaultPersonType: + selectedTypeSubject.value['personType'] ?? + '.*', + ), + ), + ), + ); + }); + + if (selectedFilter != null) { + _updateAccessHistoryAction(selectedFilter); + } + }, + ), + ), + ], + ); + } +} + +class AccessHistoryList extends StatelessWidget { + @override + Widget build(BuildContext context) { + // TODO: implement build + throw UnimplementedError(); + } +} diff --git a/lib/pages/people_on_the_property_page/people_on_the_property_page_model.dart b/lib/pages/people_on_the_property_page/people_on_the_property_page_model.dart index cc62f4f5..b33ee6b3 100644 --- a/lib/pages/people_on_the_property_page/people_on_the_property_page_model.dart +++ b/lib/pages/people_on_the_property_page/people_on_the_property_page_model.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; import 'package:hub/pages/people_on_the_property_page/people_on_the_property_page_widget.dart'; @@ -16,4 +15,4 @@ class PeopleOnThePropertyPageModel void dispose() { unfocusNode.dispose(); } -} \ No newline at end of file +} diff --git a/lib/pages/pets_page/pets_page_model.dart b/lib/pages/pets_page/pets_page_model.dart index e16b9c1d..68d21a7c 100644 --- a/lib/pages/pets_page/pets_page_model.dart +++ b/lib/pages/pets_page/pets_page_model.dart @@ -5,15 +5,14 @@ import 'package:flutter/material.dart'; import 'package:http/http.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_manager.dart'; -import 'package:hub/custom_code/actions/convert_to_upload_file.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/form_field_controller.dart'; import 'package:hub/pages/pets_page/pets_page_widget.dart'; import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/dialog_util.dart'; +import 'package:hub/shared/utils/image_util.dart'; import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/validator_util.dart'; -import '/custom_code/actions/index.dart' as actions; class PetsPageModel extends FlutterFlowModel { final DatabaseHelper db = DatabaseHelper(); @@ -164,7 +163,7 @@ class PetsPageModel extends FlutterFlowModel { 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); + uploadedTempFile = await ImageUtils.convertToUploadFile(base64); updateImage?.call(); })(); @@ -269,7 +268,7 @@ class PetsPageModel extends FlutterFlowModel { } Future updatePet() async { - var img = await actions.convertImageFileToBase64(uploadedLocalFile!); + var img = await ImageUtils.convertImageFileToBase64(uploadedLocalFile!); img = "base64;jpeg,$img"; final url = 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${devUUID}&userUUID=${userUUID}&cliID=${cliUUID}&atividade=consultaFotoPet&petId=$petId'; @@ -314,7 +313,7 @@ class PetsPageModel extends FlutterFlowModel { } Future registerPet() async { - var img = await actions.convertImageFileToBase64(uploadedLocalFile!); + var img = await ImageUtils.convertImageFileToBase64(uploadedLocalFile!); img = "base64;jpeg,$img"; final response = await PhpGroup.registerPet.call( image: img, diff --git a/lib/pages/pets_page/pets_page_widget.dart b/lib/pages/pets_page/pets_page_widget.dart index e704d5a6..c12af2fe 100644 --- a/lib/pages/pets_page/pets_page_widget.dart +++ b/lib/pages/pets_page/pets_page_widget.dart @@ -18,7 +18,6 @@ import 'package:hub/components/atomic_components/shared_components_atoms/custom_ import 'package:hub/components/atomic_components/shared_components_atoms/media_upload_button.dart'; import 'package:hub/components/atomic_components/shared_components_atoms/submit_button.dart'; import 'package:hub/components/atomic_components/shared_components_atoms/tabview.dart'; -import 'package:hub/custom_code/actions/convert_to_upload_file.dart'; import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; @@ -28,13 +27,13 @@ import 'package:hub/flutter_flow/internationalization.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/upload_data.dart'; import 'package:hub/pages/pets_page/pets_history_screen.dart'; - import 'package:hub/pages/pets_page/pets_page_model.dart'; + import 'package:hub/shared/utils/dialog_util.dart'; +import 'package:hub/shared/utils/image_util.dart'; import 'package:hub/shared/utils/validator_util.dart'; import 'package:material_symbols_icons/symbols.dart'; import 'package:sqflite/sqflite.dart'; -import '/custom_code/actions/index.dart' as actions; class PetsPageWidget extends StatefulWidget { dynamic pet; @@ -83,7 +82,8 @@ class _PetsPageWidgetState extends State Response response = await get(Uri.parse( 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${_model.devUUID}&userUUID=${_model.userUUID}&cliID=${_model.cliUUID}&atividade=consultaFotoPet&petId=$petId')); String base64 = base64Encode(response.bodyBytes); - FFUploadedFile uploadedFile = await convertToUploadFile(base64); + FFUploadedFile uploadedFile = + await ImageUtils.convertToUploadFile(base64); setState(() { _model.handleUploadComplete(uploadedFile); }); diff --git a/lib/shared/utils/device_util.dart b/lib/shared/utils/device_util.dart new file mode 100644 index 00000000..76fb92d2 --- /dev/null +++ b/lib/shared/utils/device_util.dart @@ -0,0 +1,35 @@ +import '/backend/schema/structs/index.dart'; +import 'dart:developer'; +import '/backend/schema/enums/enums.dart'; +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import '/flutter_flow/custom_functions.dart'; // Imports custom functions +import 'package:flutter/material.dart'; +import 'dart:io'; +import 'package:device_info_plus/device_info_plus.dart'; + +class DeviceUtil { + static Future getDevUUID() async { + var deviceInfo = DeviceInfoPlugin(); + if (Platform.isIOS) { + // import 'dart:io' + var iosDeviceInfo = await deviceInfo.iosInfo; + return iosDeviceInfo.identifierForVendor; // unique ID on iOS + } else if (Platform.isAndroid) { + var androidDeviceInfo = await deviceInfo.androidInfo; + return androidDeviceInfo.id; // unique ID on Android + } + } + + static Future getSerialNumber() async { + var deviceInfo = DeviceInfoPlugin(); + if (Platform.isIOS) { + // import 'dart:io' + var iosDeviceInfo = await deviceInfo.iosInfo; + return iosDeviceInfo.identifierForVendor; // unique ID on iOS + } else if (Platform.isAndroid) { + var androidDeviceInfo = await deviceInfo.androidInfo; + return androidDeviceInfo.serialNumber; // unique ID on Android + } + } +} diff --git a/lib/shared/utils/image_util.dart b/lib/shared/utils/image_util.dart new file mode 100644 index 00000000..25c56281 --- /dev/null +++ b/lib/shared/utils/image_util.dart @@ -0,0 +1,38 @@ +// Automatic FlutterFlow imports + +import 'dart:io'; + +import 'package:path_provider/path_provider.dart'; + +import 'package:flutter/material.dart'; +import 'dart:convert'; +import 'dart:typed_data'; +import '../../flutter_flow/uploaded_file.dart'; + +class ImageUtils { + static Future convertImageFileToBase64( + FFUploadedFile imageFile) async { + List? imageBytes = imageFile.bytes; + if (imageBytes != null) { + String base64Image = base64Encode(imageBytes); + return base64Image; + } + } + + static Future convertToUploadFile(String img) async { + // Decode the base64 string into bytes + Uint8List bytes = base64.decode(img); + + // Create a temporary file to store the image + final tempDir = await getTemporaryDirectory(); + final tempPath = tempDir.path; + final tempFile = await File('$tempPath/image.jpg').create(); + await tempFile.writeAsBytes(bytes); + + // Create an FFUploadedFile object using the temporary file + return FFUploadedFile( + bytes: bytes, + name: 'image.jpg', + ); + } +} diff --git a/lib/custom_code/widgets/image_cropper.dart b/lib/shared/widgets/image_cropper_widget/image_cropper.dart similarity index 100% rename from lib/custom_code/widgets/image_cropper.dart rename to lib/shared/widgets/image_cropper_widget/image_cropper.dart diff --git a/lib/shared/widgets/menu.dart b/lib/shared/widgets/menu.dart new file mode 100644 index 00000000..affa655f --- /dev/null +++ b/lib/shared/widgets/menu.dart @@ -0,0 +1,58 @@ + + +// // LinkedHashMap menu = LinkedHashMap.from({ +// "Schedule": +// [{ +// "title": "Schedule\nVisit", +// "icon": Icons.settings, +// "route": "/Schedule", +// }, +// { +// "title": "Complete\Schedule", +// "icon": Icons.calendar_today, +// "route": "/Complete", +// }, +// { +// "title": "Provisional\Schedule", +// "icon": Icons.calendar_today, +// "route": "/Provisional", +// }, +// { +// "title": "Fast\Schedule", +// "icon": Icons.calendar_today, +// "route": "/Fast", +// }], +// "Consult": +// [{ +// "title": "Consult", +// "icon": Icons.search, +// "route": "/consult", +// }, +// { +// "title": "Liberation\nConsult", +// "icon": Icons.search, +// "route": "/Liberation", +// }, +// { +// "title": "Access\nConsult", +// "icon": Icons.search, +// "route": "/Access", +// }, +// { +// "title": "Poeple\nConsult", +// "icon": Icons.search, +// "route": "/Poeple", +// }, +// { +// "title": "QR Code\nConsult", +// "icon": Icons.search, +// "route": "/qrcode", +// }], +// "Preferences": +// [{ +// "title": "Preferences", +// "icon": Icons.settings, +// "route": "/preferences", +// }], + +// }); \ No newline at end of file From 8d829ca9977f18d299ef3124738c3467d72061de Mon Sep 17 00:00:00 2001 From: "J. A. Messias" Date: Fri, 20 Sep 2024 15:13:42 -0300 Subject: [PATCH 3/3] save for fd-374 --- .../card_item_template_component_widget.dart | 2 +- .../details_component_action.dart | 415 ------------------ lib/flutter_flow/flutter_flow_drop_down.dart | 2 + lib/flutter_flow/nav/nav.dart | 24 +- .../acess_history_page_model.dart | 137 +----- .../acess_history_page_widget.dart | 243 +++++----- lib/pages/pets_page/pets_history_screen.dart | 3 +- lib/pages/pets_page/pets_page_model.dart | 181 ++++++++ .../schedule_complete_visit_page_model.dart | 405 +++++++++++++++-- .../schedule_complete_visit_page_widget.dart | 210 +++------ .../visit_history_page_widget.dart | 13 +- .../visit_history_page_model.dart | 67 --- 12 files changed, 741 insertions(+), 961 deletions(-) delete mode 100644 lib/components/templates_components/details_component/details_component_action.dart rename lib/pages/{visit_history_page => schedule_complete_visit_page}/visit_history_page_widget.dart (95%) delete mode 100644 lib/pages/visit_history_page/visit_history_page_model.dart diff --git a/lib/components/templates_components/card_item_template_component/card_item_template_component_widget.dart b/lib/components/templates_components/card_item_template_component/card_item_template_component_widget.dart index 7dfc1d7f..01386be5 100644 --- a/lib/components/templates_components/card_item_template_component/card_item_template_component_widget.dart +++ b/lib/components/templates_components/card_item_template_component/card_item_template_component_widget.dart @@ -98,7 +98,7 @@ class _CardItemTemplateComponentWidgetState } Widget _generateImage() { - // CachedNetworkImage.evictFromCache(widget.imagePath ?? ''); + CachedNetworkImage.evictFromCache(widget.imagePath ?? ''); return ClipRRect( borderRadius: BorderRadius.circular(20), child: CachedNetworkImage( diff --git a/lib/components/templates_components/details_component/details_component_action.dart b/lib/components/templates_components/details_component/details_component_action.dart deleted file mode 100644 index d4c2d9a3..00000000 --- a/lib/components/templates_components/details_component/details_component_action.dart +++ /dev/null @@ -1,415 +0,0 @@ -import 'dart:convert'; -import 'dart:developer'; - -import 'package:flutter/material.dart'; -import 'package:http/http.dart'; -import 'package:hub/backend/api_requests/api_calls.dart'; -import 'package:hub/components/templates_components/details_component/details_component_widget.dart'; -import 'package:hub/flutter_flow/flutter_flow_theme.dart'; -import 'package:hub/flutter_flow/flutter_flow_util.dart'; -import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; -import 'package:hub/flutter_flow/form_field_controller.dart'; -import 'package:hub/flutter_flow/nav/nav.dart'; -import 'package:hub/pages/pets_page/pets_page_model.dart'; -import 'package:hub/shared/mixins/status_mixin.dart'; -import 'package:hub/shared/utils/validator_util.dart'; -import 'package:share_plus/share_plus.dart'; - -Widget buildVisitDetails({ - required dynamic item, - required BuildContext context, - required Future Function(BuildContext, int, int, String, String) - changeStatusAction, - required String devUUID, - required String userUUID, - required String cliUUID, - required String cliName, -}) { - return DetailsComponentWidget( - buttons: [ - if (Status.getStatus(item['VAW_STATUS']) == - StatusEnum.active) // REJECT ACTION - FFButtonWidget( - text: FFLocalizations.of(context).getVariableText( - ptText: 'Cancelar', - enText: 'Cancel', - ), - icon: const Icon(Icons.close), - onPressed: () async { - showAlertDialog( - context, - FFLocalizations.of(context).getVariableText( - ptText: 'Cancelar Visita', - enText: 'Cancel Visit', - ), - FFLocalizations.of(context).getVariableText( - ptText: 'Você tem certeza que deseja bloquear essa visita?', - enText: 'Are you sure you want to block this visit?', - ), () async { - await changeStatusAction - ?.call( - context, - int.parse(item['VAW_DESTINO']), - int.parse(item['VAW_ID']), - item['VAW_CHAVE'] ?? '', - item['VTE_DOCUMENTO'] ?? '', - ) - .then((value) { - // Navigator.pop(context, value); - context.pop(value); - - if (value == false) { - showSnackbar( - context, - FFLocalizations.of(context).getVariableText( - enText: 'Error blocking visit', - ptText: 'Erro ao bloquear visita', - ), - true, - ); - } else if (value == true) { - showSnackbar( - context, - FFLocalizations.of(context).getVariableText( - enText: 'Success canceling visit', - ptText: 'Succeso ao cancelar visita', - ), - false, - ); - } - }).catchError((err, stack) { - context.pop(); - showSnackbar( - context, - FFLocalizations.of(context).getVariableText( - enText: 'Error blocking visit', - ptText: 'Erro ao bloquear visita', - ), - true, - ); - }); - }); - }, - options: FFButtonOptions( - width: 130, - height: 40, - color: FlutterFlowTheme.of(context).primaryBackground, - elevation: 0, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - // borderRadius: 12, - ), - ), - if (Status.getStatus(item['VAW_STATUS']) != - StatusEnum.active) // RECALL ACTION - FFButtonWidget( - text: FFLocalizations.of(context).getVariableText( - ptText: 'Reagendar', - enText: 'Reschedule', - ), - icon: const Icon(Icons.refresh), - onPressed: () async { - context.pop(); - context.pop(); - - context.pushNamed('scheduleCompleteVisitPage', extra: { - 'dropdownValue1': item['MOT_DESCRICAO'], - 'dropdownValue2': item['NAC_DESCRICAO'], - 'visitorJsonList': [item], - 'visitorStrList': item['VTE_DOCUMENTO'], - }); - }, - options: FFButtonOptions( - width: 130, - height: 40, - color: FlutterFlowTheme.of(context).primaryBackground, - elevation: 0, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - // borderRadius: 12, - ), - ), - if (Status.getStatus(item['VAW_STATUS']) == - StatusEnum.active) // SHARE ACTION - FFButtonWidget( - text: FFLocalizations.of(context).getVariableText( - ptText: 'Compartilhar', - enText: 'Share', - ), - icon: const Icon(Icons.share), - onPressed: () async { - Share.share(''' -Olá, \*${item['VTE_NOME']}\*! Você foi convidado para \*${cliName}\*. - -\*Validade do Convite\*: -- Início: ${item['VAW_DTINICIO']} -- Fim: ${item['VAW_DTFIM']} - -URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/${cliUUID}/${item['VAW_CHAVE']} - '''); - }, - options: FFButtonOptions( - width: 130, - height: 40, - color: FlutterFlowTheme.of(context).primaryBackground, - elevation: 0, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - // borderRadius: 12, - ), - ), - ], - labelsHashMap: Map.from({ - '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:': - item['VTE_NOME'] ?? '', - '${FFLocalizations.of(context).getVariableText(ptText: "Inicio", enText: "Start")}:': - item['VAW_DTINICIO'] != '' && item['VAW_DTINICIO'] != null - ? ValidatorUtil.toLocalDateTime( - 'yyyy-MM-dd HH:mm:ss', item['VAW_DTINICIO']) - : '', - '${FFLocalizations.of(context).getVariableText(ptText: "Fim", enText: "End")}:': - item['VAW_DTFIM'] != '' && item['VAW_DTFIM'] != null - ? ValidatorUtil.toLocalDateTime( - 'yyyy-MM-dd HH:mm:ss', item['VAW_DTFIM']) - : '', - }), - imagePath: - 'https://freaccess.com.br/freaccess/getImage.php?cliID=${cliUUID}&atividade=getFoto&Documento=${item['VTE_DOCUMENTO'] ?? ''}&tipo=E', - statusHashMap: [ - if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.active) - Map.from({ - FFLocalizations.of(context).getVariableText( - ptText: 'Ativo', - enText: 'Active', - ): FlutterFlowTheme.of(context).warning, - }), - if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.unknown) - Map.from({ - FFLocalizations.of(context).getVariableText( - ptText: 'Pendente', - enText: 'Pending', - ): FlutterFlowTheme.of(context).alternate, - }), - if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.canceled) - Map.from({ - FFLocalizations.of(context).getVariableText( - ptText: 'Cancelado', - enText: 'Canceled', - ): FlutterFlowTheme.of(context).error, - }), - if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.finished) - Map.from({ - FFLocalizations.of(context).getVariableText( - ptText: 'Finalizado', - enText: 'Finished', - ): FlutterFlowTheme.of(context).success, - }), - if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.blocked) - Map.from({ - FFLocalizations.of(context).getVariableText( - ptText: 'Bloqueado', - enText: 'Blocked', - ): FlutterFlowTheme.of(context).error, - }), - if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.inactive) - Map.from({ - FFLocalizations.of(context).getVariableText( - ptText: 'Inativo', - enText: 'Inactive', - ): FlutterFlowTheme.of(context).warning, - }), - ], - ); -} - -Widget buildPetDetails({ - required dynamic item, - required BuildContext context, - required String devUUID, - required String userUUID, - required String cliUUID, - required String cliName, - required PetsPageModel model, -}) { - return DetailsComponentWidget( - buttons: [ - // EDIT ACTION - FFButtonWidget( - text: FFLocalizations.of(context).getVariableText( - ptText: 'Editar', - enText: 'Edit', - ), - icon: const Icon(Icons.edit), - onPressed: () async { - context.pop(); - - model.isEditing = true; - model.item = item; - model.switchTab(0); - model.setEditForm(); - // model.safeSetState!(); - }, - options: FFButtonOptions( - width: 130, - height: 40, - color: FlutterFlowTheme.of(context).primaryBackground, - elevation: 0, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - // borderRadius: 12, - ), - ), - - // DELETE ACTION - FFButtonWidget( - text: FFLocalizations.of(context).getVariableText( - ptText: 'Excluir', - enText: 'Delete', - ), - icon: const Icon(Icons.close), - onPressed: () async { - showAlertDialog( - context, - FFLocalizations.of(context).getVariableText( - ptText: 'Excluir Pet', - enText: 'Delete Pet', - ), - FFLocalizations.of(context).getVariableText( - ptText: 'Você tem certeza que deseja excluir esse pet?', - enText: 'Are you sure you want to delete this pet?', - ), () async { - int id = item['id']; - await PhpGroup.deletePet - .call( - petID: id, - ) - .then((value) { - // Navigator.pop(context, value); - context.pop(value); - context.pop(value); - - if (value == false) { - showSnackbar( - context, - FFLocalizations.of(context).getVariableText( - ptText: 'Erro ao excluir pet', - enText: 'Error deleting pet', - ), - true, - ); - } else if (value == true) { - showSnackbar( - context, - FFLocalizations.of(context).getVariableText( - enText: 'Success deleting pet', - ptText: 'Succeso ao excluir pet', - ), - false, - ); - } - }).catchError((err, stack) { - context.pop(); - showSnackbar( - context, - FFLocalizations.of(context).getVariableText( - enText: 'Error deleting pet', - ptText: 'Erro ao excluir pet', - ), - true, - ); - }); - }); - }, - options: FFButtonOptions( - width: 130, - height: 40, - color: FlutterFlowTheme.of(context).primaryBackground, - elevation: 0, - textStyle: TextStyle( - color: FlutterFlowTheme.of(context).primaryText, - ), - borderSide: BorderSide( - color: FlutterFlowTheme.of(context).primaryBackground, - width: 1, - ), - // borderRadius: 12, - ), - ), - ], - // 'MIN', 'PEQ', 'MED', 'GRA', 'GIG' - labelsHashMap: Map.from({ - if (item['species'] != null && item['species'] != '') - '${FFLocalizations.of(context).getVariableText(ptText: "Espécie", enText: "Species")}:': - item['species'].toString().toUpperCase(), - if (item['breed'] != null && item['breed'] != '') - '${FFLocalizations.of(context).getVariableText(ptText: "Raça", enText: "Breed")}:': - item['breed'].toString().toUpperCase(), - if (item['color'] != null && item['color'] != '') - '${FFLocalizations.of(context).getVariableText(ptText: "Cor", enText: "Color")}:': - item['color'].toString().toUpperCase(), - if (item['birthdayDate'] != null && item['birthdayDate'] != '') - '${FFLocalizations.of(context).getVariableText(ptText: "Data de Nascimento", enText: "Date of Birth")}:': - ValidatorUtil.formatDateTimePicker(item['birthdayDate']), - if (item['gender'] != null && item['gender'] != '') - '${FFLocalizations.of(context).getVariableText(ptText: "Gênero", enText: "Gender")}:': - item['gender'] == 'MAC' - ? FFLocalizations.of(context) - .getVariableText(ptText: 'MACHO', enText: 'MALE') - : FFLocalizations.of(context) - .getVariableText(enText: 'FEMALE', ptText: 'FÊMEA'), - if (item['size'] != null && item['size'] != '') - '${FFLocalizations.of(context).getVariableText(ptText: "Porte", enText: "Size")}:': - item['size'] == 'MIN' - ? FFLocalizations.of(context) - .getVariableText(ptText: 'MINI', enText: 'MINI') - : item['size'] == 'PEQ' - ? FFLocalizations.of(context) - .getVariableText(ptText: 'PEQUENO', enText: 'SMALL') - : item['size'] == 'MED' - ? FFLocalizations.of(context) - .getVariableText(ptText: 'MÉDIO', enText: 'MEDIUM') - : item['size'] == 'GRD' - ? FFLocalizations.of(context).getVariableText( - ptText: 'GRANDE', enText: 'LARGE') - : item['size'] == 'GIG' - ? FFLocalizations.of(context).getVariableText( - ptText: 'GIGANTE', enText: 'GIANT') - : '', - if (item['notes'] != null && item['notes'] != '') - '${FFLocalizations.of(context).getVariableText(ptText: "Observação", enText: "Notes")}:': - item['notes'] ?? '', - }), - imagePath: - 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${devUUID}&userUUID=${userUUID}&cliID=${cliUUID}&atividade=consultaFotoPet&petId=${item['id'] ?? ''}', - statusHashMap: [ - if (item['gender'] == "MAC") - Map.from({ - item['name']: Color(0xFF094CB0), - }), - if (item['gender'] == "FEM") - Map.from({ - item['name']: Color(0xFFE463E7), - }), - ], - ); -} diff --git a/lib/flutter_flow/flutter_flow_drop_down.dart b/lib/flutter_flow/flutter_flow_drop_down.dart index c82ebb61..35831023 100644 --- a/lib/flutter_flow/flutter_flow_drop_down.dart +++ b/lib/flutter_flow/flutter_flow_drop_down.dart @@ -3,6 +3,8 @@ import 'package:flutter/material.dart'; import 'form_field_controller.dart'; +import 'package:flutter/material.dart'; + class FlutterFlowDropDown extends StatefulWidget { const FlutterFlowDropDown({ super.key, diff --git a/lib/flutter_flow/nav/nav.dart b/lib/flutter_flow/nav/nav.dart index a10061f8..3947cd2b 100644 --- a/lib/flutter_flow/nav/nav.dart +++ b/lib/flutter_flow/nav/nav.dart @@ -104,29 +104,7 @@ GoRouter createRouter(AppStateNotifier appStateNotifier) => GoRouter( name: 'scheduleCompleteVisitPage', path: '/scheduleCompleteVisitPage', builder: (context, params) { - final dropdownValue1 = params.getParam( - 'dropdownValue1', - ParamType.String, - ); - final dropdownValue2 = params.getParam( - 'dropdownValue2', - ParamType.String, - ); - final visitorStrList = params.getParam( - 'visitorStrList', - ParamType.String, - ); - final visitorJsonList = params.getParam( - 'visitorJsonList', - ParamType.JSON, - isList: true, - ); - return ScheduleCompleteVisitPageWidget( - dropdownValue1: dropdownValue1 ?? '', - dropdownValue2: dropdownValue2 ?? '', - visitorStrList: visitorStrList ?? '', - visitorJsonList: visitorJsonList ?? [], - ); + return const ScheduleCompleteVisitPageWidget(); }), FFRoute( name: 'deliverySchedule', diff --git a/lib/pages/acess_history_page/acess_history_page_model.dart b/lib/pages/acess_history_page/acess_history_page_model.dart index fcfbb302..ca9a17ad 100644 --- a/lib/pages/acess_history_page/acess_history_page_model.dart +++ b/lib/pages/acess_history_page/acess_history_page_model.dart @@ -1,48 +1,16 @@ import 'package:flutter/material.dart'; -import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_manager.dart'; import 'package:hub/components/molecular_components/message_opt_modal/opt_modal_widget.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart'; -import 'package:hub/flutter_flow/flutter_flow_theme.dart'; -import 'package:hub/flutter_flow/internationalization.dart'; import 'package:hub/flutter_flow/request_manager.dart'; import 'package:hub/pages/acess_history_page/acess_history_page_widget.dart'; import 'package:hub/shared/helpers/db_helper.dart'; -import 'package:hub/shared/utils/dialog_util.dart'; -import 'package:hub/shared/utils/log_util.dart'; -import 'package:rxdart/rxdart.dart'; - -class AccessHistoryModel extends FlutterFlowModel { - // Singleton instance - static final AccessHistoryModel _instance = AccessHistoryModel._internal(); - - // Private constructor - AccessHistoryModel._internal() : super(); - - // Factory constructor to return the singleton instance - factory AccessHistoryModel() { - return _instance; - } +class AcessHistoryPageModel extends FlutterFlowModel { final DatabaseHelper db = DatabaseHelper(); late final String devUUID; late final String userUUID; late final String cliUUID; - final BehaviorSubject> selectedTypeSubject; - bool isSubjectClosed = false; - final scaffoldKey = GlobalKey(); - late Function(Function) safeSetState; - - late ScrollController scrollController; - int pageNumber = 1; - final int pageSize = 10; - bool hasData = false; - bool loading = false; - - String personType = '.*'; - - late Future accessFuture; - List accessWrap = []; final unfocusNode = FocusNode(); final _accessHistoryManager = FutureRequestManager(); @@ -62,10 +30,10 @@ class AccessHistoryModel extends FlutterFlowModel { @override void initState(BuildContext context) { - _initAsync(); + initDatabase(); } - Future _initAsync() async { + Future initDatabase() async { devUUID = await db .get(key: 'devUUID', field: 'value') .then((value) => value.toString()); @@ -77,95 +45,11 @@ class AccessHistoryModel extends FlutterFlowModel { .then((value) => value.toString()); } - void _updateAccessHistoryAction( - Map newType, BuildContext context) { - if (!isSubjectClosed) { - final currentType = selectedTypeSubject.value; - final updatedType = Map.from(currentType); - bool needsUpdate = false; - newType.forEach((key, newValue) { - if (currentType[key] != newValue) { - updatedType[key] = newValue; - needsUpdate = true; - } - }); - if (needsUpdate) { - selectedTypeSubject.add(updatedType); - fetchCardListViewService(updatedType, context); - safeSetState?.call(() {}); - } - } - } + @override + void dispose() { + unfocusNode.dispose(); - Future fetchAccessHistoryService( - BuildContext context) async { - try { - safeSetState.call(() => loading = true); - var response = await PhpGroup.getAccessCall.call( - pageSize: pageSize.toString(), - pageNumber: pageNumber.toString(), - pesTipo: personType != 'E' && personType != 'O' ? 'T' : personType, - ); - - final List accessHistory = response.jsonBody['acessos'] ?? []; - - List filteredAccess = accessHistory.where((item) { - final personTypeMatches = - personType == '.*' || item["PES_TIPO"].toString() == personType; - return personTypeMatches; - }).toList(); - - if (filteredAccess != null && filteredAccess.isNotEmpty) { - safeSetState.call(() { - accessWrap.addAll(filteredAccess); - hasData = true; - loading = false; - }); - return response; - } - _showNoMoreDataSnackbar(context); - safeSetState.call(() { - hasData = false; - loading = false; - }); - return null; - } catch (e, s) { - DialogUtil.errorDefault(context); - LogUtil.requestAPIFailed('processRequest', "", "Busca Acesso", e, s); - safeSetState.call(() { - hasData = false; - loading = false; - }); - } - return null; - } - - void _showNoMoreDataSnackbar(BuildContext context) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - FFLocalizations.of(context).getVariableText( - ptText: "Não há mais dados.", enText: "No more data."), - ), - duration: const Duration(seconds: 3), - backgroundColor: FlutterFlowTheme.of(context).primary, - ), - ); - } - - void _loadMoreAccess(BuildContext context) { - if (hasData == true) { - pageNumber++; - accessFuture = fetchAccessHistoryService(context); - } - } - - void fetchCardListViewService( - Map select, BuildContext context) { - personType = select['personType']!; - accessWrap = []; - pageNumber = 1; - accessFuture = fetchAccessHistoryService(context); + clearAccessHistoryCache(); } Future toggleOptionsAction(BuildContext context) async { @@ -187,11 +71,4 @@ class AccessHistoryModel extends FlutterFlowModel { }, ); } - - @override - void dispose() { - unfocusNode.dispose(); - - clearAccessHistoryCache(); - } } diff --git a/lib/pages/acess_history_page/acess_history_page_widget.dart b/lib/pages/acess_history_page/acess_history_page_widget.dart index 4876f91c..854d8eb6 100644 --- a/lib/pages/acess_history_page/acess_history_page_widget.dart +++ b/lib/pages/acess_history_page/acess_history_page_widget.dart @@ -15,7 +15,6 @@ import 'package:hub/shared/utils/log_util.dart'; import 'package:rxdart/rxdart.dart'; @immutable -// ignore: must_be_immutable class AccessHistoryScreen extends StatefulWidget { late Map opt = { 'personType': '.*', @@ -24,13 +23,27 @@ class AccessHistoryScreen extends StatefulWidget { }; AccessHistoryScreen({super.key, required this.opt}); @override - State createState() => _AccessHistoryScreenState(opt); + State createState() => _AccessHistoryState(opt); } -class _AccessHistoryScreenState extends State { - late AccessHistoryModel _model; +class _AccessHistoryState extends State { + late AcessHistoryPageModel _model; + final BehaviorSubject> selectedTypeSubject; + bool _isSubjectClosed = false; + final scaffoldKey = GlobalKey(); - _AccessHistoryScreenState(Map opt) + late ScrollController _scrollController; + int _pageNumber = 1; + final int _pageSize = 10; + bool _hasData = false; + bool _loading = false; + + String _personType = '.*'; + + late Future _accessFuture; + List _accessWrap = []; + + _AccessHistoryState(Map opt) : selectedTypeSubject = BehaviorSubject.seeded(opt) { selectedTypeSubject.listen((value) {}); } @@ -38,13 +51,13 @@ class _AccessHistoryScreenState extends State { @override void initState() { super.initState(); - _model = createModel(context, () => AccessHistoryModel()); - _model.accessFuture = fetchAccessHistoryService(); + _model = createModel(context, () => AcessHistoryPageModel()); + _accessFuture = fetchAccessHistoryService(); - _model.scrollController = ScrollController() + _scrollController = ScrollController() ..addListener(() { - if (_model.scrollController.position.atEdge && - _model.scrollController.position.pixels != 0) { + if (_scrollController.position.atEdge && + _scrollController.position.pixels != 0) { _loadMoreAccess(); } }); @@ -53,7 +66,7 @@ class _AccessHistoryScreenState extends State { @override void dispose() { selectedTypeSubject.close(); - _model.isSubjectClosed = true; + _isSubjectClosed = true; super.dispose(); } @@ -62,7 +75,7 @@ class _AccessHistoryScreenState extends State { final theme = FlutterFlowTheme.of(context); return Scaffold( - key: _model.scaffoldKey, + key: scaffoldKey, backgroundColor: FlutterFlowTheme.of(context).primaryBackground, appBar: _appBar(context, theme), body: _body(context)); @@ -150,13 +163,84 @@ class _AccessHistoryScreenState extends State { ); } + void _updateAccessHistoryAction(Map newType) { + if (!_isSubjectClosed) { + final currentType = selectedTypeSubject.value; + final updatedType = Map.from(currentType); + bool needsUpdate = false; + newType.forEach((key, newValue) { + if (currentType[key] != newValue) { + updatedType[key] = newValue; + needsUpdate = true; + } + }); + if (needsUpdate) { + selectedTypeSubject.add(updatedType); + fetchCardListViewService(updatedType); + safeSetState(() {}); + } + } + } + + Future fetchAccessHistoryService() async { + try { + setState(() => _loading = true); + var response = await PhpGroup.getAccessCall.call( + pageSize: _pageSize.toString(), + pageNumber: _pageNumber.toString(), + pesTipo: _personType != 'E' && _personType != 'O' ? 'T' : _personType, + ); + + final List accessHistory = response.jsonBody['acessos'] ?? []; + + List filteredAccess = accessHistory.where((item) { + final personTypeMatches = + _personType == '.*' || item["PES_TIPO"].toString() == _personType; + return personTypeMatches; + }).toList(); + + if (filteredAccess != null && filteredAccess.isNotEmpty) { + setState(() { + _accessWrap.addAll(filteredAccess); + _hasData = true; + _loading = false; + }); + return response; + } + _showNoMoreDataSnackbar(context); + setState(() { + _hasData = false; + _loading = false; + }); + return null; + } catch (e, s) { + DialogUtil.errorDefault(context); + LogUtil.requestAPIFailed('processRequest', "", "Busca Acesso", e, s); + setState(() { + _hasData = false; + _loading = false; + }); + } + } + + void _showNoMoreDataSnackbar(BuildContext context) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + FFLocalizations.of(context).getVariableText( + ptText: "Não há mais dados.", enText: "No more data."), + ), + duration: const Duration(seconds: 3), + backgroundColor: FlutterFlowTheme.of(context).primary, + ), + ); + } + Widget _body(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ - if (_model.hasData == false && - _model.pageNumber <= 1 && - _model.loading == false) + if (_hasData == false && _pageNumber <= 1 && _loading == false) Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -171,9 +255,9 @@ class _AccessHistoryScreenState extends State { ], ), ) - else if (_model.hasData || _model.pageNumber >= 1) + else if (_hasData || _pageNumber >= 1) Expanded(child: _cardListViewOrganismWidget()), - if (_model.hasData == true && _model.loading) + if (_hasData == true && _loading) Container( padding: const EdgeInsets.only(top: 15, bottom: 15), child: Center( @@ -188,12 +272,26 @@ class _AccessHistoryScreenState extends State { ); } + void _loadMoreAccess() { + if (_hasData == true) { + _pageNumber++; + _accessFuture = fetchAccessHistoryService(); + } + } + + void fetchCardListViewService(Map select) { + _personType = select['personType']!; + _accessWrap = []; + _pageNumber = 1; + _accessFuture = fetchAccessHistoryService(); + } + Widget _cardListViewOrganismWidget() { return FutureBuilder( - future: _model.accessFuture, + future: _accessFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting && - _model.accessWrap.isEmpty) { + _accessWrap.isEmpty) { return Center( child: SizedBox( width: 50.0, @@ -215,10 +313,10 @@ class _AccessHistoryScreenState extends State { return ListView.builder( shrinkWrap: true, physics: const BouncingScrollPhysics(), - controller: _model.scrollController, - itemCount: _model.accessWrap.length, + controller: _scrollController, + itemCount: _accessWrap.length, itemBuilder: (context, index) { - final accessHistoryItem = _model.accessWrap[index]; + final accessHistoryItem = _accessWrap[index]; return _accessHistoryCardMoleculeWidget(context, accessHistoryItem); }, ); @@ -297,104 +395,3 @@ class _AccessHistoryScreenState extends State { ); } } - -class AccessHistoryAppBar extends StatelessWidget { - AccessHistoryAppBar(this.model, this.selectedTypeSubject); - final AccessHistoryModel model; - final BehaviorSubject> selectedTypeSubject; - - late final FlutterFlowTheme theme; - - @override - Widget build(BuildContext context) { - theme = FlutterFlowTheme.of(context); - - return AppBar( - backgroundColor: theme.primaryBackground, - automaticallyImplyLeading: false, - leading: _backButton(context, theme), - title: _title(context, theme), - centerTitle: true, - elevation: 0.0, - actions: [_filterButton(context)], - ); - } - - Widget _backButton(BuildContext context, FlutterFlowTheme theme) { - return FlutterFlowIconButton( - borderColor: Colors.transparent, - borderRadius: 30.0, - borderWidth: 1.0, - buttonSize: 60.0, - icon: Icon( - Icons.keyboard_arrow_left, - color: theme.primaryText, - size: 30.0, - ), - onPressed: () => Navigator.of(context).pop(), - ); - } - - Widget _title(BuildContext context, FlutterFlowTheme theme) { - return Text( - FFLocalizations.of(context).getText('ch8qymga'), - style: theme.headlineMedium.override( - fontFamily: theme.headlineMediumFamily, - color: theme.primaryText, - fontSize: 16.0, - letterSpacing: 0.0, - useGoogleFonts: - GoogleFonts.asMap().containsKey(theme.headlineMediumFamily), - ), - ); - } - - Widget _filterButton(BuildContext context) { - return Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(0, 0, 10, 0), - child: IconButton( - icon: const Icon(Icons.filter_list), - onPressed: () async { - final Map? selectedFilter = - await showModalBottomSheet>( - isScrollControlled: true, - backgroundColor: Colors.transparent, - context: context, - builder: (context) { - return GestureDetector( - onTap: () => Navigator.of(context).pop(), - child: Container( - color: Colors.transparent, - child: GestureDetector( - onTap: () {}, - child: OptModalWidget( - defaultPersonType: - selectedTypeSubject.value['personType'] ?? - '.*', - ), - ), - ), - ); - }); - - if (selectedFilter != null) { - _updateAccessHistoryAction(selectedFilter); - } - }, - ), - ), - ], - ); - } -} - -class AccessHistoryList extends StatelessWidget { - @override - Widget build(BuildContext context) { - // TODO: implement build - throw UnimplementedError(); - } -} diff --git a/lib/pages/pets_page/pets_history_screen.dart b/lib/pages/pets_page/pets_history_screen.dart index 18ff3e77..7ab0c732 100644 --- a/lib/pages/pets_page/pets_history_screen.dart +++ b/lib/pages/pets_page/pets_history_screen.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.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_util.dart'; import 'package:hub/pages/liberation_history/liberation_history_model.dart'; @@ -263,7 +262,7 @@ class _PetsHistoryScreenState extends State builder: (context) { return Dialog( alignment: Alignment.center, - child: buildPetDetails( + child: widget.model.buildPetDetails( item: uItem, context: context, devUUID: devUUID, diff --git a/lib/pages/pets_page/pets_page_model.dart b/lib/pages/pets_page/pets_page_model.dart index 68d21a7c..06b9806f 100644 --- a/lib/pages/pets_page/pets_page_model.dart +++ b/lib/pages/pets_page/pets_page_model.dart @@ -5,8 +5,12 @@ import 'package:flutter/material.dart'; import 'package:http/http.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_manager.dart'; +import 'package:hub/components/templates_components/details_component/details_component_widget.dart'; +import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; +import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; import 'package:hub/flutter_flow/form_field_controller.dart'; +import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/pages/pets_page/pets_page_widget.dart'; import 'package:hub/shared/helpers/db_helper.dart'; import 'package:hub/shared/utils/dialog_util.dart'; @@ -388,4 +392,181 @@ class PetsPageModel extends FlutterFlowModel { dropDownValueController1 = FormFieldController(null); dropDownValueController2 = FormFieldController(null); } + + Widget buildPetDetails({ + required dynamic item, + required BuildContext context, + required String devUUID, + required String userUUID, + required String cliUUID, + required String cliName, + required PetsPageModel model, + }) { + return DetailsComponentWidget( + buttons: [ + // EDIT ACTION + FFButtonWidget( + text: FFLocalizations.of(context).getVariableText( + ptText: 'Editar', + enText: 'Edit', + ), + icon: const Icon(Icons.edit), + onPressed: () async { + context.pop(); + + model.isEditing = true; + model.item = item; + model.switchTab(0); + model.setEditForm(); + // model.safeSetState!(); + }, + options: FFButtonOptions( + width: 130, + height: 40, + color: FlutterFlowTheme.of(context).primaryBackground, + elevation: 0, + textStyle: TextStyle( + color: FlutterFlowTheme.of(context).primaryText, + ), + borderSide: BorderSide( + color: FlutterFlowTheme.of(context).primaryBackground, + width: 1, + ), + // borderRadius: 12, + ), + ), + + // DELETE ACTION + FFButtonWidget( + text: FFLocalizations.of(context).getVariableText( + ptText: 'Excluir', + enText: 'Delete', + ), + icon: const Icon(Icons.close), + onPressed: () async { + showAlertDialog( + context, + FFLocalizations.of(context).getVariableText( + ptText: 'Excluir Pet', + enText: 'Delete Pet', + ), + FFLocalizations.of(context).getVariableText( + ptText: 'Você tem certeza que deseja excluir esse pet?', + enText: 'Are you sure you want to delete this pet?', + ), () async { + int id = item['id']; + await PhpGroup.deletePet + .call( + petID: id, + ) + .then((value) { + // Navigator.pop(context, value); + context.pop(value); + context.pop(value); + + if (value == false) { + showSnackbar( + context, + FFLocalizations.of(context).getVariableText( + ptText: 'Erro ao excluir pet', + enText: 'Error deleting pet', + ), + true, + ); + } else if (value == true) { + showSnackbar( + context, + FFLocalizations.of(context).getVariableText( + enText: 'Success deleting pet', + ptText: 'Succeso ao excluir pet', + ), + false, + ); + } + }).catchError((err, stack) { + context.pop(); + showSnackbar( + context, + FFLocalizations.of(context).getVariableText( + enText: 'Error deleting pet', + ptText: 'Erro ao excluir pet', + ), + true, + ); + }); + }); + }, + options: FFButtonOptions( + width: 130, + height: 40, + color: FlutterFlowTheme.of(context).primaryBackground, + elevation: 0, + textStyle: TextStyle( + color: FlutterFlowTheme.of(context).primaryText, + ), + borderSide: BorderSide( + color: FlutterFlowTheme.of(context).primaryBackground, + width: 1, + ), + // borderRadius: 12, + ), + ), + ], + // 'MIN', 'PEQ', 'MED', 'GRA', 'GIG' + labelsHashMap: Map.from({ + if (item['species'] != null && item['species'] != '') + '${FFLocalizations.of(context).getVariableText(ptText: "Espécie", enText: "Species")}:': + item['species'].toString().toUpperCase(), + if (item['breed'] != null && item['breed'] != '') + '${FFLocalizations.of(context).getVariableText(ptText: "Raça", enText: "Breed")}:': + item['breed'].toString().toUpperCase(), + if (item['color'] != null && item['color'] != '') + '${FFLocalizations.of(context).getVariableText(ptText: "Cor", enText: "Color")}:': + item['color'].toString().toUpperCase(), + if (item['birthdayDate'] != null && item['birthdayDate'] != '') + '${FFLocalizations.of(context).getVariableText(ptText: "Data de Nascimento", enText: "Date of Birth")}:': + ValidatorUtil.formatDateTimePicker(item['birthdayDate']), + if (item['gender'] != null && item['gender'] != '') + '${FFLocalizations.of(context).getVariableText(ptText: "Gênero", enText: "Gender")}:': + item['gender'] == 'MAC' + ? FFLocalizations.of(context) + .getVariableText(ptText: 'MACHO', enText: 'MALE') + : FFLocalizations.of(context) + .getVariableText(enText: 'FEMALE', ptText: 'FÊMEA'), + if (item['size'] != null && item['size'] != '') + '${FFLocalizations.of(context).getVariableText(ptText: "Porte", enText: "Size")}:': + item['size'] == 'MIN' + ? FFLocalizations.of(context) + .getVariableText(ptText: 'MINI', enText: 'MINI') + : item['size'] == 'PEQ' + ? FFLocalizations.of(context) + .getVariableText(ptText: 'PEQUENO', enText: 'SMALL') + : item['size'] == 'MED' + ? FFLocalizations.of(context).getVariableText( + ptText: 'MÉDIO', enText: 'MEDIUM') + : item['size'] == 'GRD' + ? FFLocalizations.of(context).getVariableText( + ptText: 'GRANDE', enText: 'LARGE') + : item['size'] == 'GIG' + ? FFLocalizations.of(context).getVariableText( + ptText: 'GIGANTE', enText: 'GIANT') + : '', + if (item['notes'] != null && item['notes'] != '') + '${FFLocalizations.of(context).getVariableText(ptText: "Observação", enText: "Notes")}:': + item['notes'] ?? '', + }), + imagePath: + 'https://freaccess.com.br/freaccess/getImage.php?devUUID=${devUUID}&userUUID=${userUUID}&cliID=${cliUUID}&atividade=consultaFotoPet&petId=${item['id'] ?? ''}', + statusHashMap: [ + if (item['gender'] == "MAC") + Map.from({ + item['name']: Color(0xFF094CB0), + }), + if (item['gender'] == "FEM") + Map.from({ + item['name']: Color(0xFFE463E7), + }), + ], + ); + } } diff --git a/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart b/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart index 914aee21..dadb8b1b 100644 --- a/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart +++ b/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart @@ -1,25 +1,43 @@ +import 'dart:ffi'; + import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_manager.dart'; +import 'package:hub/components/templates_components/details_component/details_component_widget.dart'; +import 'package:hub/flutter_flow/flutter_flow_theme.dart'; -import 'package:hub/flutter_flow/flutter_flow_model.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart'; +import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; import 'package:hub/flutter_flow/form_field_controller.dart'; import 'package:hub/flutter_flow/internationalization.dart'; +import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/flutter_flow/request_manager.dart'; import 'package:flutter/material.dart'; import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart'; +import 'package:hub/pages/schedule_complete_visit_page/visit_history_page_widget.dart'; import 'package:hub/shared/helpers/db_helper.dart'; +import 'package:hub/shared/mixins/status_mixin.dart'; +import 'package:hub/shared/utils/validator_util.dart'; import 'package:intl/intl.dart'; +import 'package:share_plus/share_plus.dart'; class ScheduleCompleteVisitPageModel - extends FlutterFlowModel { + extends FlutterFlowModel { + late VoidCallback safeSetState; + late Function(Function) updateState; final _visitHistoryManager = FutureRequestManager(); final DatabaseHelper db = DatabaseHelper(); late final String devUUID; late final String cliUUID; late final String userUUID; + late final String? dropdownValue1; + late final String? dropdownValue2; + bool? dropDownValidator1; + bool? dropDownValidator2; + List visitorJsonList = []; + String visitorStrList = '0'; + Future visitHistory({ String? uniqueQueryKey, bool? overrideCache, @@ -34,34 +52,25 @@ class ScheduleCompleteVisitPageModel void clearVisitHistoryCacheKey(String? uniqueKey) => _visitHistoryManager.clearRequest(uniqueKey); - /// Local state fields for this page. - String convertDateFormat(String dateStr) { try { - // Formato original DateFormat originalFormat = DateFormat('dd/MM/yyyy HH:mm:ss'); - // Novo formato DateFormat newFormat = DateFormat('y-M-d H:mm:ss'); - // Validate the input string format if (!RegExp(r'^\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2}:\d{2}$') .hasMatch(dateStr)) { return 'Invalid date format'; } - // Converte a string para DateTime DateTime dateTime = originalFormat.parse(dateStr); - // Converte DateTime para a nova string formatada String formattedDate = newFormat.format(dateTime); return formattedDate; } catch (e) { - // Handle the exception by returning an error message or a default value return 'Invalid date format'; } } - List visitorJsonList = []; void addToVisitorJsonList(dynamic item) => visitorJsonList.add(item); void removeFromVisitorJsonList(dynamic item) => visitorJsonList.remove(item); void removeAtIndexFromVisitorJsonList(int index) => @@ -71,10 +80,6 @@ class ScheduleCompleteVisitPageModel void updateVisitorJsonListAtIndex(int index, Function(dynamic) updateFn) => visitorJsonList[index] = updateFn(visitorJsonList[index]); - String visitorStrList = '0'; - bool? dropDownValidator1; - bool? dropDownValidator2; - bool isValid() { if ((textController1!.text != '') && (textController2!.text != '') && @@ -85,15 +90,11 @@ class ScheduleCompleteVisitPageModel return false; } - /// State fields for stateful widgets in this page. - final unfocusNode = FocusNode(); - // State field(s) for TabBar widget. TabController? tabBarController; int get tabBarCurrentIndex => tabBarController != null ? tabBarController!.index : 0; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode1; TextEditingController? textController1; String? Function(BuildContext, String?)? textController1Validator; @@ -131,7 +132,6 @@ class ScheduleCompleteVisitPageModel } DateTime? datePicked1; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode2; TextEditingController? textController2; String? Function(BuildContext, String?)? textController2Validator; @@ -170,26 +170,16 @@ class ScheduleCompleteVisitPageModel } DateTime? datePicked2; - // State field(s) for DropDown widget. String? dropDownValue1; FormFieldController? dropDownValueController1; - // State field(s) for DropDown widget. String? dropDownValue2; FormFieldController? dropDownValueController2; - // State field(s) for Switch widget. bool? switchValue; - // State field(s) for TextField widget. FocusNode? textFieldFocusNode3; TextEditingController? textController3; String? Function(BuildContext, String?)? textController3Validator; String? _textController3Validator(BuildContext context, String? val) { - // if (val == null || val.isEmpty) { - // return FFLocalizations.of(context).getVariableText( - // enText: 'This field is required.', - // ptText: 'Este campo é obrigatório.', - // ); - // } return null; } @@ -217,8 +207,7 @@ class ScheduleCompleteVisitPageModel textController1 = TextEditingController( text: dateTimeFormat( 'dd/MM/yyyy HH:mm:ss', - DateTime.now().add(const Duration(minutes: 10)), - // locale: FFLocalizations.of(context).languageCode, + DateTime.now().add(const Duration(minutes: 0)), )); textController1Validator = _textController1Validator; @@ -227,13 +216,59 @@ class ScheduleCompleteVisitPageModel text: dateTimeFormat( 'dd/MM/yyyy HH:mm:ss', DateTime.now().add(const Duration(days: 1)), - // locale: FFLocalizations.of(context).languageCode, )); textController2Validator = _textController2Validator; textFieldFocusNode3 = FocusNode(); textController3 = TextEditingController(); textController3Validator = _textController3Validator; + + dropDownValueController1 ??= + FormFieldController(dropDownValue1 ??= ''); + dropDownValueController2 ??= + FormFieldController(dropDownValue2 ??= ''); + } + + // Updated variables for dropdowns + late final List reasonsDropDown1 = []; + late final List labelsDropDown1 = []; + late final List optionsDropdown1 = []; + + late final List lavelsDropDown2 = []; + late final List labelsDropDown2 = []; + late final List optionsDropdown2 = []; + + // Methods to process dropdown values + void processDropDown1(List reasonsJsonList) { + if (dropDownValue1 != null && dropDownValue1!.isNotEmpty) { + String value = dropDownValue1!; + if (!(value.contains('{') && + value.contains('}') && + value.contains(':'))) { + var item = reasonsJsonList.where((reason) => + reason['MOT_DESCRICAO'].toString().contains(dropDownValue1!)); + dropDownValue1 = item.firstOrNull?.toString() ?? ''; + dropDownValueController1?.value = dropDownValue1!; + } + } + reasonsDropDown1.clear(); + reasonsDropDown1.addAll(reasonsJsonList.map((e) => e.toString()).toList()); + } + + void processDropDown2(List lavelList) { + if (dropDownValue2 != null && dropDownValue2!.isNotEmpty) { + String value = dropDownValue2!; + if (!(value.contains('{') && + value.contains('}') && + value.contains(':'))) { + var item = lavelList.where((level) => + level['NAC_DESCRICAO'].toString().contains(dropDownValue2!)); + dropDownValue2 = item.firstOrNull?.toString() ?? ''; + dropDownValueController2?.value = dropDownValue2!; + } + } + lavelsDropDown2.clear(); + lavelsDropDown2.addAll(lavelList.map((e) => e.toString()).toList()); } @override @@ -252,7 +287,55 @@ class ScheduleCompleteVisitPageModel clearVisitHistoryCache(); } - /// Action blocks. + Future changeStatusAction( + BuildContext context, + int idDestino, + int idVisita, + String accessKey, + String email, + ) async { + // Navigator.pop(context, true); + context.pop(true); + + bool? blockVisitRequest; + blockVisitRequest = await visitCancelAction( + context, + accessKey: accessKey, + idDestino: idDestino, + idVisita: idVisita, + email: email, + ); + if (!context.mounted) return; + if (blockVisitRequest == true) { + return true; + } else { + return false; + } + } + + Future visitCancelAction(BuildContext context, + {required int? idDestino, + required int? idVisita, + required String? accessKey, + required String? email}) async { + final ApiCallResponse? response; + final CancelaVisita callback = PhpGroup.cancelaVisita; + + response = await callback.call( + idDestino: idDestino, + idVisita: idVisita, + AccessKey: accessKey, + UsuEmail: email, + DevDesc: '', + ); + + if (response.statusCode == 200) { + return !response.jsonBody['error']; + } else { + return false; + } + } + Future getVisitorsActionPage( BuildContext context, { List? visitorsJsonList, @@ -270,4 +353,258 @@ class ScheduleCompleteVisitPageModel return false; } + + void switchTab(int index) { + tabBarController?.animateTo(index); + + safeSetState.call(); + } + + void setFormField() { + // if ((visitorStrList != null && visitorStrList != '') && + // ((visitorJsonList != null && (visitorJsonList)!.isNotEmpty) != null)) { + // visitorJsonList = visitorJsonList! + // .where((e) => + // visitorStrList == + // getJsonField( + // e, + // r'''$.VTE_DOCUMENTO''', + // ).toString().toString()) + // .toList() + // .toList() + // .cast(); + // visitorStrList = visitorStrList!; + + // safeSetState.call(); + // } + + // if ((dropdownValue1 != null && dropdownValue1 != '') && + // (dropdownValue2 != null && dropdownValue2 != '')) { + // dropDownValue1 = dropdownValue1!; + // dropDownValue2 = dropdownValue2!; + // safeSetState.call(); + // } + } + + Widget buildVisitDetails({ + required dynamic item, + required BuildContext context, + required Future Function(BuildContext, int, int, String, String) + changeStatusAction, + required String devUUID, + required String userUUID, + required String cliUUID, + required String cliName, + }) { + return DetailsComponentWidget( + buttons: [ + if (Status.getStatus(item['VAW_STATUS']) == + StatusEnum.active) // REJECT ACTION + FFButtonWidget( + text: FFLocalizations.of(context).getVariableText( + ptText: 'Cancelar', + enText: 'Cancel', + ), + icon: const Icon(Icons.close), + onPressed: () async { + showAlertDialog( + context, + FFLocalizations.of(context).getVariableText( + ptText: 'Cancelar Visita', + enText: 'Cancel Visit', + ), + FFLocalizations.of(context).getVariableText( + ptText: 'Você tem certeza que deseja bloquear essa visita?', + enText: 'Are you sure you want to block this visit?', + ), () async { + await changeStatusAction + ?.call( + context, + int.parse(item['VAW_DESTINO']), + int.parse(item['VAW_ID']), + item['VAW_CHAVE'] ?? '', + item['VTE_DOCUMENTO'] ?? '', + ) + .then((value) { + // Navigator.pop(context, value); + context.pop(value); + + if (value == false) { + showSnackbar( + context, + FFLocalizations.of(context).getVariableText( + enText: 'Error blocking visit', + ptText: 'Erro ao bloquear visita', + ), + true, + ); + } else if (value == true) { + showSnackbar( + context, + FFLocalizations.of(context).getVariableText( + enText: 'Success canceling visit', + ptText: 'Succeso ao cancelar visita', + ), + false, + ); + } + }).catchError((err, stack) { + context.pop(); + showSnackbar( + context, + FFLocalizations.of(context).getVariableText( + enText: 'Error blocking visit', + ptText: 'Erro ao bloquear visita', + ), + true, + ); + }); + }); + }, + options: FFButtonOptions( + width: 130, + height: 40, + color: FlutterFlowTheme.of(context).primaryBackground, + elevation: 0, + textStyle: TextStyle( + color: FlutterFlowTheme.of(context).primaryText, + ), + borderSide: BorderSide( + color: FlutterFlowTheme.of(context).primaryBackground, + width: 1, + ), + // borderRadius: 12, + ), + ), + if (Status.getStatus(item['VAW_STATUS']) != + StatusEnum.active) // RECALL ACTION + FFButtonWidget( + text: FFLocalizations.of(context).getVariableText( + ptText: 'Reagendar', + enText: 'Reschedule', + ), + icon: const Icon(Icons.refresh), + onPressed: () async { + context.pop(); + + dropDownValue1 = item['MOT_DESCRICAO']; + dropDownValue2 = item['NAC_DESCRICAO']; + + visitorJsonList = [item]; + visitorStrList = item['VTE_DOCUMENTO']; + + switchTab(0); + }, + options: FFButtonOptions( + width: 130, + height: 40, + color: FlutterFlowTheme.of(context).primaryBackground, + elevation: 0, + textStyle: TextStyle( + color: FlutterFlowTheme.of(context).primaryText, + ), + borderSide: BorderSide( + color: FlutterFlowTheme.of(context).primaryBackground, + width: 1, + ), + // borderRadius: 12, + ), + ), + if (Status.getStatus(item['VAW_STATUS']) == + StatusEnum.active) // SHARE ACTION + FFButtonWidget( + text: FFLocalizations.of(context).getVariableText( + ptText: 'Compartilhar', + enText: 'Share', + ), + icon: const Icon(Icons.share), + onPressed: () async { + Share.share(''' +Olá, \*${item['VTE_NOME']}\*! Você foi convidado para \*${cliName}\*. + +\*Validade do Convite\*: +- Início: ${item['VAW_DTINICIO']} +- Fim: ${item['VAW_DTFIM']} + +URL do Convite: https://visita.freaccess.com.br/${item['VAW_ID']}/${cliUUID}/${item['VAW_CHAVE']} + '''); + }, + options: FFButtonOptions( + width: 130, + height: 40, + color: FlutterFlowTheme.of(context).primaryBackground, + elevation: 0, + textStyle: TextStyle( + color: FlutterFlowTheme.of(context).primaryText, + ), + borderSide: BorderSide( + color: FlutterFlowTheme.of(context).primaryBackground, + width: 1, + ), + // borderRadius: 12, + ), + ), + ], + labelsHashMap: Map.from({ + '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:': + item['VTE_NOME'] ?? '', + '${FFLocalizations.of(context).getVariableText(ptText: "Inicio", enText: "Start")}:': + item['VAW_DTINICIO'] != '' && item['VAW_DTINICIO'] != null + ? ValidatorUtil.toLocalDateTime( + 'yyyy-MM-dd HH:mm:ss', item['VAW_DTINICIO']) + : '', + '${FFLocalizations.of(context).getVariableText(ptText: "Fim", enText: "End")}:': + item['VAW_DTFIM'] != '' && item['VAW_DTFIM'] != null + ? ValidatorUtil.toLocalDateTime( + 'yyyy-MM-dd HH:mm:ss', item['VAW_DTFIM']) + : '', + }), + imagePath: + 'https://freaccess.com.br/freaccess/getImage.php?cliID=${cliUUID}&atividade=getFoto&Documento=${item['VTE_DOCUMENTO'] ?? ''}&tipo=E', + statusHashMap: [ + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.active) + Map.from({ + FFLocalizations.of(context).getVariableText( + ptText: 'Ativo', + enText: 'Active', + ): FlutterFlowTheme.of(context).warning, + }), + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.unknown) + Map.from({ + FFLocalizations.of(context).getVariableText( + ptText: 'Pendente', + enText: 'Pending', + ): FlutterFlowTheme.of(context).alternate, + }), + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.canceled) + Map.from({ + FFLocalizations.of(context).getVariableText( + ptText: 'Cancelado', + enText: 'Canceled', + ): FlutterFlowTheme.of(context).error, + }), + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.finished) + Map.from({ + FFLocalizations.of(context).getVariableText( + ptText: 'Finalizado', + enText: 'Finished', + ): FlutterFlowTheme.of(context).success, + }), + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.blocked) + Map.from({ + FFLocalizations.of(context).getVariableText( + ptText: 'Bloqueado', + enText: 'Blocked', + ): FlutterFlowTheme.of(context).error, + }), + if (Status.getStatus(item['VAW_STATUS']) == StatusEnum.inactive) + Map.from({ + FFLocalizations.of(context).getVariableText( + ptText: 'Inativo', + enText: 'Inactive', + ): FlutterFlowTheme.of(context).warning, + }), + ], + ); + } } diff --git a/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart b/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart index 625efa57..3e792ee8 100644 --- a/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart +++ b/lib/pages/schedule_complete_visit_page/schedule_complete_visit_page_widget.dart @@ -1,3 +1,5 @@ +import 'dart:developer'; + import 'package:auto_size_text/auto_size_text.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; @@ -18,24 +20,22 @@ import 'package:hub/flutter_flow/flutter_flow_widgets.dart'; import 'package:hub/flutter_flow/form_field_controller.dart'; import 'package:hub/flutter_flow/nav/nav.dart'; import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart'; -import 'package:hub/pages/visit_history_page/visit_history_page_widget.dart'; +import 'package:hub/pages/schedule_complete_visit_page/visit_history_page_widget.dart'; import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/share_util.dart'; import 'package:provider/provider.dart'; -class ScheduleCompleteVisitPageWidget extends StatefulWidget { - const ScheduleCompleteVisitPageWidget({ - super.key, - this.dropdownValue1, - this.dropdownValue2, - this.visitorStrList, - this.visitorJsonList, - }); +class ScheduleComplete extends StatefulWidget { + const ScheduleComplete({Key? key}) : super(key: key); - final String? dropdownValue1; - final String? dropdownValue2; - final String? visitorStrList; - final List? visitorJsonList; + @override + State createState() { + throw UnimplementedError(); + } +} + +class ScheduleCompleteVisitPageWidget extends ScheduleComplete { + const ScheduleCompleteVisitPageWidget(); @override State createState() => @@ -57,39 +57,9 @@ class _ScheduleCompleteVisitPageWidgetState void initState() { super.initState(); _model = createModel(context, () => ScheduleCompleteVisitPageModel()); + _model.safeSetState = () => safeSetState(() {}); + _model.updateState = (Function fn) => safeSetState(fn()); - // On page load action. - SchedulerBinding.instance.addPostFrameCallback((_) async { - if ((widget.visitorStrList != null && widget.visitorStrList != '') && - ((widget.visitorJsonList != null && - (widget.visitorJsonList)!.isNotEmpty) != - null)) { - _model.visitorJsonList = widget.visitorJsonList! - .where((e) => - widget.visitorStrList == - getJsonField( - e, - r'''$.VTE_DOCUMENTO''', - ).toString().toString()) - .toList() - .toList() - .cast(); - _model.visitorStrList = widget.visitorStrList!; - - safeSetState(() {}); - } else { - return; - } - - if ((widget.dropdownValue1 != null && widget.dropdownValue1 != '') && - (widget.dropdownValue2 != null && widget.dropdownValue2 != '')) { - _model.dropDownValue1 = widget.dropdownValue1!; - _model.dropDownValue2 = widget.dropdownValue2!; - safeSetState(() {}); - } else { - return; - } - }); _model.tabBarController = TabController( vsync: this, length: 2, @@ -107,21 +77,15 @@ class _ScheduleCompleteVisitPageWidgetState } void _loadMoreVisitHistory() async { - // Simulate fetching data from an API or database Future> fetchVisitHistory(int start, int limit) async { - // Simulate network delay await Future.delayed(const Duration(seconds: 1)); - // Generate a list of visit history items return List.generate(limit, (index) => "Item ${start + index}"); } - // Calculate the start index for the next batch of items to load final int start = _visitHistoryLoadingIdx * _visitHistoryLoadingCount; - // Fetch the next batch of items final List newItems = await fetchVisitHistory(start, _visitHistoryLoadingCount); - // If new items were fetched, add them to the list and update the index if (newItems.isNotEmpty) { _visitHistoryList.addAll(newItems); _visitHistoryLoadingIdx++; @@ -183,7 +147,7 @@ PreferredSizeWidget appBarScheduleCompleteVisit(BuildContext context) { ), title: Text( FFLocalizations.of(context).getText( - '61lcxdgm' /* Agendar Visita */, + '61lcxdgm', ), style: FlutterFlowTheme.of(context).headlineMedium.override( fontFamily: 'Nunito', @@ -223,12 +187,12 @@ Widget bodyScheduleCompleteVisit(BuildContext context, tabs: [ Tab( text: FFLocalizations.of(context).getText( - 'ueth1f4g' /* Cadastrar Visita */, + 'ueth1f4g', ), ), Tab( text: FFLocalizations.of(context).getText( - 'k4uraqam' /* Histórico de Visitas */, + 'k4uraqam', ), ), ], @@ -278,7 +242,7 @@ Widget scheduleVisit(BuildContext context, 20.0, 30.0, 0.0, 24.0), child: Text( FFLocalizations.of(context).getText( - '98evnbbe' /* Qual o período de validade da ... */, + '98evnbbe', ), textAlign: TextAlign.start, style: FlutterFlowTheme.of(context).bodyMedium.override( @@ -298,7 +262,6 @@ Widget scheduleVisit(BuildContext context, SizedBox( width: MediaQuery.of(context).size.width, height: 60.0, - // decoration: const BoxDecoration(), child: Stack( children: [ Padding( @@ -328,7 +291,7 @@ Widget scheduleVisit(BuildContext context, .labelMediumFamily), ), hintText: FFLocalizations.of(context).getText( - '53cbwqh9' /* Quando você inicia a visita? */, + '53cbwqh9', ), hintStyle: FlutterFlowTheme.of(context) .labelMedium @@ -549,7 +512,6 @@ Widget scheduleVisit(BuildContext context, SizedBox( width: MediaQuery.of(context).size.width, height: 60.0, - // decoration: const BoxDecoration(), child: Stack( children: [ Padding( @@ -579,7 +541,7 @@ Widget scheduleVisit(BuildContext context, .labelMediumFamily), ), hintText: FFLocalizations.of(context).getText( - 'xpgc5e8d' /* Quando a visita terminá? */, + 'xpgc5e8d', ), hintStyle: FlutterFlowTheme.of(context) .labelMedium @@ -793,9 +755,7 @@ Widget scheduleVisit(BuildContext context, ), ], ), - ] - // .divide(const SizedBox(height: 0.0)), - ), + ]), Column( mainAxisSize: MainAxisSize.max, children: [ @@ -806,7 +766,7 @@ Widget scheduleVisit(BuildContext context, 20.0, 24.0, 0.0, 30.0), child: Text( FFLocalizations.of(context).getText( - 'u0jocx7e' /* Quais visitantes você deseja c... */, + 'u0jocx7e', ), textAlign: TextAlign.start, style: FlutterFlowTheme.of(context).bodyMedium.override( @@ -1018,7 +978,7 @@ Widget scheduleVisit(BuildContext context, alignment: const AlignmentDirectional(0.0, 0.0), child: AutoSizeText( FFLocalizations.of(context).getText( - 'r8soavtz' /* Clique para adicionar um visit... */, + 'r8soavtz', ), style: FlutterFlowTheme.of(context) .bodyMedium @@ -1052,7 +1012,7 @@ Widget scheduleVisit(BuildContext context, 20.0, 24.0, 0.0, 24.0), child: Text( FFLocalizations.of(context).getText( - '0meymh6u' /* Quais são os motivos da visita... */, + '0meymh6u', ), textAlign: TextAlign.start, style: FlutterFlowTheme.of(context).bodyMedium.override( @@ -1097,54 +1057,23 @@ Widget scheduleVisit(BuildContext context, ); } - final dropDownGetDadosResponse = - snapshot.data!; final reasonsJsonList = PhpGroup.getDadosCall.reasonsJsonList( - dropDownGetDadosResponse.jsonBody); + snapshot.data!.jsonBody); + final reasonsOptionLabels = PhpGroup + .getDadosCall + .reasonsMotDescStrList( + snapshot.data!.jsonBody); - if (_model.dropDownValue1 != '' && - _model.dropDownValue1 != null) { - String value = - _model.dropDownValue1.toString() ?? - ''; - - if (value.contains('{') && - value.contains('}') && - value.contains(':')) { - } else { - if (reasonsJsonList != null && - reasonsJsonList.isNotEmpty) { - var item = reasonsJsonList.where( - (reason) => - reason['MOT_DESCRICAO'] - .toString() - .contains(_model - .dropDownValue1 ?? - '')); - _model.dropDownValue1 = - item.firstOrNull.toString() ?? ''; - } - } - } + _model.processDropDown1(reasonsJsonList!); return FlutterFlowDropDown( fillColor: FlutterFlowTheme.of(context) .primaryBackground, controller: - _model.dropDownValueController1 ??= - FormFieldController( - _model.dropDownValue1 ??= ''), - options: reasonsJsonList != null && - reasonsJsonList != [] - ? reasonsJsonList - .map((e) => e.toString()) - .toList() - : [], - optionLabels: PhpGroup.getDadosCall - .reasonsMotDescStrList( - dropDownGetDadosResponse - .jsonBody), + _model.dropDownValueController1, + options: _model.reasonsDropDown1, + optionLabels: reasonsOptionLabels, onChanged: (val) => safeSetState( () => _model.dropDownValue1 = val), width: double.infinity, @@ -1163,7 +1092,7 @@ Widget scheduleVisit(BuildContext context, ), hintText: FFLocalizations.of(context).getText( - '6p3e0bzr' /* Escolha um motivo aqui */, + '6p3e0bzr', ), icon: Icon( Icons.keyboard_arrow_down_rounded, @@ -1229,7 +1158,6 @@ Widget scheduleVisit(BuildContext context, child: FutureBuilder( future: PhpGroup.getDadosCall.call(), builder: (context, snapshot) { - // Customize what your widget looks like when it's loading. if (!snapshot.hasData) { return Center( child: SizedBox( @@ -1244,53 +1172,19 @@ Widget scheduleVisit(BuildContext context, ); } - final dropDownGetDadosResponse = - snapshot.data!; - final lavelList = PhpGroup.getDadosCall - .levelJsonList( - dropDownGetDadosResponse.jsonBody); - - if (_model.dropDownValue2 != '' && - _model.dropDownValue2 != null) { - String value = - _model.dropDownValue2.toString() ?? - ''; - - if (value.contains('{') && - value.contains('}') && - value.contains(':')) { - // log("Valor e um Objeto | Usuário Escolheu o Nivel ${_model.dropDownValue2}"); - } else { - // log("Valor e uma String | Usuário Escolheu o Nivel ${_model.dropDownValue2}"); - if (lavelList != null && - lavelList.isNotEmpty) { - var item = lavelList.where((level) => - level['NAC_DESCRICAO'] - .toString() - .contains( - _model.dropDownValue2 ?? - '')); - _model.dropDownValue2 = - item.firstOrNull.toString() ?? ''; - } - } - } + final lavelsJsonList = PhpGroup.getDadosCall + .levelJsonList(snapshot.data!.jsonBody); + final lavelsOptionLabels = PhpGroup + .getDadosCall + .levelNACDescricaoStrList( + snapshot.data!.jsonBody); + _model.processDropDown2(lavelsJsonList!); return FlutterFlowDropDown( controller: - _model.dropDownValueController2 ??= - FormFieldController( - _model.dropDownValue2 ??= ''), - options: - lavelList != null && lavelList != [] - ? lavelList - .map((e) => e.toString()) - .toList() - : [], - optionLabels: PhpGroup.getDadosCall - .levelNACDescricaoStrList( - dropDownGetDadosResponse - .jsonBody), + _model.dropDownValueController2, + options: _model.lavelsDropDown2, + optionLabels: lavelsOptionLabels, onChanged: (val) => safeSetState( () => _model.dropDownValue2 = val), width: double.infinity, @@ -1309,7 +1203,7 @@ Widget scheduleVisit(BuildContext context, ), hintText: FFLocalizations.of(context).getText( - '2wun8p6c' /* Escolha um nível de acesso aqu... */, + '2wun8p6c', ), icon: Icon( Icons.keyboard_arrow_down_rounded, @@ -1373,7 +1267,7 @@ Widget scheduleVisit(BuildContext context, 20.0, 24.0, 0.0, 24.0), child: Text( FFLocalizations.of(context).getText( - '8rk26eg1' /* Visita se encerra após o prime... */, + '8rk26eg1', ), textAlign: TextAlign.start, style: FlutterFlowTheme.of(context).bodyMedium.override( @@ -1402,7 +1296,7 @@ Widget scheduleVisit(BuildContext context, 0.0, 0.0, 130.0, 0.0), child: Text( FFLocalizations.of(context).getText( - 'lgv0q5ht' /* Visita única */, + 'lgv0q5ht', ), textAlign: TextAlign.start, style: FlutterFlowTheme.of(context) @@ -1476,7 +1370,7 @@ Widget scheduleVisit(BuildContext context, 20.0, 0.0, 0.0, 24.0), child: Text( FFLocalizations.of(context).getText( - 'eftcs67c' /* Você tem alguma observação sob... */, + 'eftcs67c', ), textAlign: TextAlign.start, style: FlutterFlowTheme.of(context).bodyMedium.override( @@ -1506,7 +1400,7 @@ Widget scheduleVisit(BuildContext context, decoration: InputDecoration( isDense: false, labelText: FFLocalizations.of(context).getText( - 't0q2vuup' /* Observações da Visita */, + 't0q2vuup', ), labelStyle: FlutterFlowTheme.of(context) .labelMedium @@ -1520,7 +1414,7 @@ Widget scheduleVisit(BuildContext context, .labelMediumFamily), ), hintText: FFLocalizations.of(context).getText( - 'w18iztdm' /* Escreva as suas observações aq... */, + 'w18iztdm', ), hintStyle: FlutterFlowTheme.of(context) .labelMedium @@ -1623,7 +1517,6 @@ Widget scheduleVisit(BuildContext context, false) { context.pop(); - //MILESTONE _model.dropDownValue1 = null; _model.dropDownValue2 = null; _model.dropDownValueController1 = @@ -1701,7 +1594,6 @@ Widget scheduleVisit(BuildContext context, .primaryBackground, width: 1, ), - // borderRadius: 12, ), ), ], diff --git a/lib/pages/visit_history_page/visit_history_page_widget.dart b/lib/pages/schedule_complete_visit_page/visit_history_page_widget.dart similarity index 95% rename from lib/pages/visit_history_page/visit_history_page_widget.dart rename to lib/pages/schedule_complete_visit_page/visit_history_page_widget.dart index f7773f11..208d701d 100644 --- a/lib/pages/visit_history_page/visit_history_page_widget.dart +++ b/lib/pages/schedule_complete_visit_page/visit_history_page_widget.dart @@ -1,19 +1,18 @@ import 'package:flutter/material.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.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_util.dart'; import 'package:hub/pages/schedule_complete_visit_page/schedule_complete_visit_page_model.dart'; -import 'package:hub/pages/visit_history_page/visit_history_page_model.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:hub/shared/mixins/status_mixin.dart'; import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/validator_util.dart'; -class VisitHistoryWidget extends StatefulWidget { - VisitHistoryWidget({Key? key}) : super(key: key); +class VisitHistoryWidget extends ScheduleComplete { + const VisitHistoryWidget(); @override _VisitHistoryWidgetState createState() => _VisitHistoryWidgetState(); @@ -30,7 +29,7 @@ class _VisitHistoryWidgetState extends State final int _pageSize = 10; bool _hasData = false; bool _loading = false; - late VisitHistoryModel _model; + late ScheduleCompleteVisitPageModel _model; late Future _visitFuture; List _visitWrap = []; @@ -51,7 +50,7 @@ class _VisitHistoryWidgetState extends State void initState() { super.initState(); - _model = createModel(context, () => VisitHistoryModel()); + _model = createModel(context, () => ScheduleCompleteVisitPageModel()); _initVariables(); _visitFuture = _fetchVisits(); @@ -272,7 +271,7 @@ class _VisitHistoryWidgetState extends State builder: (context) { return Dialog( alignment: Alignment.center, - child: buildVisitDetails( + child: _model.buildVisitDetails( item: visitaWrapItem, context: context, changeStatusAction: _model.changeStatusAction, diff --git a/lib/pages/visit_history_page/visit_history_page_model.dart b/lib/pages/visit_history_page/visit_history_page_model.dart deleted file mode 100644 index 574a33e3..00000000 --- a/lib/pages/visit_history_page/visit_history_page_model.dart +++ /dev/null @@ -1,67 +0,0 @@ -import 'package:flutter/src/widgets/framework.dart'; -import 'package:hub/backend/api_requests/api_calls.dart'; -import 'package:hub/backend/api_requests/api_manager.dart'; -import 'package:hub/flutter_flow/flutter_flow_model.dart'; -import 'package:hub/flutter_flow/nav/nav.dart'; -import 'package:hub/pages/visit_history_page/visit_history_page_widget.dart'; - -class VisitHistoryModel extends FlutterFlowModel { - @override - void dispose() { - // TODO: implement dispose - } - - @override - void initState(BuildContext context) { - // TODO: implement initState - } - - Future changeStatusAction( - BuildContext context, - int idDestino, - int idVisita, - String accessKey, - String email, - ) async { - // Navigator.pop(context, true); - context.pop(true); - - bool? blockVisitRequest; - blockVisitRequest = await visitCancelAction( - context, - accessKey: accessKey, - idDestino: idDestino, - idVisita: idVisita, - email: email, - ); - if (!context.mounted) return; - if (blockVisitRequest == true) { - return true; - } else { - return false; - } - } - - Future visitCancelAction(BuildContext context, - {required int? idDestino, - required int? idVisita, - required String? accessKey, - required String? email}) async { - final ApiCallResponse? response; - final CancelaVisita callback = PhpGroup.cancelaVisita; - - response = await callback.call( - idDestino: idDestino, - idVisita: idVisita, - AccessKey: accessKey, - UsuEmail: email, - DevDesc: '', - ); - - if (response.statusCode == 200) { - return !response.jsonBody['error']; - } else { - return false; - } - } -}