674 lines
18 KiB
Dart
674 lines
18 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:f_r_e_hub/components/organism_components/bottom_arrow_linked_locals_component/bottom_arrow_linked_locals_component_widget.dart';
|
|
import 'package:f_r_e_hub/custom_code/actions/get_dev_u_u_i_d.dart';
|
|
import 'package:f_r_e_hub/pages/home_page/home_page_widget.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:qr_flutter/qr_flutter.dart';
|
|
import 'dart:developer' as developer;
|
|
|
|
import '/actions/actions.dart' as action_blocks;
|
|
import '/backend/api_requests/api_calls.dart';
|
|
import '/components/molecular_components/throw_exception/throw_exception_widget.dart';
|
|
import '/custom_code/actions/index.dart' as actions;
|
|
import '/flutter_flow/flutter_flow_theme.dart';
|
|
import '/flutter_flow/flutter_flow_util.dart';
|
|
import '/flutter_flow/random_data_util.dart' as random_data;
|
|
|
|
Future repeatVisitScheduleAction(
|
|
BuildContext context, {
|
|
List<dynamic>? visitorJsonList,
|
|
String? visitorStrList,
|
|
String? visitStartDateStr,
|
|
String? visitEndDateStr,
|
|
String? visitReasonStr,
|
|
String? visitLevelStr,
|
|
bool? visitTempBol,
|
|
String? visitObsStr,
|
|
}) async {
|
|
context.pushNamed(
|
|
'scheduleCompleteVisitPage',
|
|
queryParameters: {
|
|
'visitStartDateStr': serializeParam(
|
|
visitStartDateStr,
|
|
ParamType.String,
|
|
),
|
|
'visitEndDateStr': serializeParam(
|
|
visitEndDateStr,
|
|
ParamType.String,
|
|
),
|
|
'visitReasonStr': serializeParam(
|
|
visitReasonStr,
|
|
ParamType.String,
|
|
),
|
|
'visitLevelStr': serializeParam(
|
|
visitLevelStr,
|
|
ParamType.String,
|
|
),
|
|
'visitTempBol': serializeParam(
|
|
visitTempBol,
|
|
ParamType.bool,
|
|
),
|
|
'visitObsStr': serializeParam(
|
|
visitObsStr,
|
|
ParamType.String,
|
|
),
|
|
'visitorStrList': serializeParam(
|
|
visitorStrList,
|
|
ParamType.String,
|
|
),
|
|
'visitorJsonList': serializeParam(
|
|
visitorJsonList,
|
|
ParamType.JSON,
|
|
isList: true,
|
|
),
|
|
}.withoutNulls,
|
|
extra: <String, dynamic>{
|
|
kTransitionInfoKey: const TransitionInfo(
|
|
hasTransition: true,
|
|
transitionType: PageTransitionType.fade,
|
|
),
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<Color> manageStatusColorAction(
|
|
BuildContext context, {
|
|
required String? visitStatusStr,
|
|
}) async {
|
|
debugPrint('visitStatusStr: $visitStatusStr');
|
|
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 singInLoginAction(
|
|
BuildContext context, {
|
|
String? emailAdress,
|
|
String? password,
|
|
}) async {
|
|
String? devUUID;
|
|
ApiCallResponse? loginCall;
|
|
|
|
await Future.wait([
|
|
Future(() async {
|
|
FFAppState().email = emailAdress!;
|
|
}),
|
|
Future(() async {
|
|
FFAppState().passwd = password!;
|
|
}),
|
|
]);
|
|
if ((FFAppState().email != '') && (FFAppState().passwd != '')) {
|
|
devUUID = await actions.getDevUUID();
|
|
FFAppState().devUUID = devUUID!;
|
|
loginCall = await PhpGroup.loginCall.call(
|
|
email: FFAppState().email,
|
|
password: FFAppState().passwd,
|
|
uuid: FFAppState().devUUID,
|
|
type: FFAppState().device,
|
|
description: random_data.randomString(
|
|
10,
|
|
10,
|
|
true,
|
|
false,
|
|
false,
|
|
),
|
|
);
|
|
|
|
if (PhpGroup.loginCall.error(
|
|
(loginCall.jsonBody ?? ''),
|
|
) ==
|
|
false) {
|
|
FFAppState().userUUID = PhpGroup.loginCall.userUUID(
|
|
(loginCall.jsonBody ?? ''),
|
|
)!;
|
|
// FFAppState().token = await FirebaseMessaging.instance.getToken();
|
|
FFAppState().createdAt = dateTimeFormat(
|
|
'd/M/y H:mm:ss',
|
|
getCurrentTimestamp,
|
|
locale: FFLocalizations.of(context).languageCode,
|
|
);
|
|
FFAppState().updatedAt = '00/00/0000 00:00:00';
|
|
FFAppState().status = PhpGroup.loginCall.userStatus(
|
|
(loginCall.jsonBody ?? ''),
|
|
)!;
|
|
FFAppState().userDevUUID = PhpGroup.loginCall.userDeviceId(
|
|
(loginCall.jsonBody ?? ''),
|
|
)!;
|
|
FFAppState().name = PhpGroup.loginCall.userName(
|
|
(loginCall.jsonBody ?? ''),
|
|
)!;
|
|
FFAppState().serialNumber = await getSerialNumber() ?? '';
|
|
FFAppState().isLogged = true;
|
|
await action_blocks.toggleHomePage(context);
|
|
return;
|
|
} else {
|
|
await showModalBottomSheet(
|
|
isScrollControlled: true,
|
|
backgroundColor: Colors.transparent,
|
|
useSafeArea: true,
|
|
context: context,
|
|
builder: (context) {
|
|
return Padding(
|
|
padding: MediaQuery.viewInsetsOf(context),
|
|
child: ThrowExceptionWidget(
|
|
msg: PhpGroup.loginCall.msg(
|
|
(loginCall?.jsonBody ?? ''),
|
|
)!,
|
|
),
|
|
);
|
|
},
|
|
);
|
|
|
|
FFAppState().deleteEmail();
|
|
FFAppState().email = '';
|
|
|
|
FFAppState().deletePasswd();
|
|
FFAppState().passwd = '';
|
|
|
|
FFAppState().update(() {});
|
|
}
|
|
|
|
return;
|
|
} else {
|
|
return;
|
|
}
|
|
}
|
|
|
|
Future<bool> signUpRegisterAction(
|
|
BuildContext context, {
|
|
required String? name,
|
|
String? passwd,
|
|
required String? email,
|
|
String? device,
|
|
}) async {
|
|
ApiCallResponse? registerCall;
|
|
|
|
if ((email != null && email != '') &&
|
|
(passwd != null && passwd != '') &&
|
|
(name != null && name != '')) {
|
|
registerCall = await PhpGroup.registerCall.call(
|
|
name: name,
|
|
password: passwd,
|
|
email: email,
|
|
token: random_data.randomString(
|
|
36,
|
|
36,
|
|
false,
|
|
false,
|
|
true,
|
|
),
|
|
uuid: random_data.randomString(
|
|
36,
|
|
36,
|
|
false,
|
|
false,
|
|
true,
|
|
),
|
|
tipo: device,
|
|
descricao: random_data.randomString(
|
|
36,
|
|
36,
|
|
true,
|
|
false,
|
|
false,
|
|
),
|
|
);
|
|
|
|
if (PhpGroup.registerCall.error(
|
|
(registerCall.jsonBody ?? ''),
|
|
) ==
|
|
false) {
|
|
return true;
|
|
}
|
|
|
|
await showDialog(
|
|
context: context,
|
|
builder: (alertDialogContext) {
|
|
return AlertDialog(
|
|
title: const Text('ERROR2'),
|
|
content: const Text('ERROR2'),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(alertDialogContext),
|
|
child: const Text('ERROR2 '),
|
|
),
|
|
],
|
|
);
|
|
},
|
|
);
|
|
return false;
|
|
} else {
|
|
await showDialog(
|
|
context: context,
|
|
builder: (alertDialogContext) {
|
|
return AlertDialog(
|
|
title: const Text('ERROR1'),
|
|
content: const Text('ERROR1'),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(alertDialogContext),
|
|
child: const Text('ERROR1 '),
|
|
),
|
|
],
|
|
);
|
|
},
|
|
);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
Future forgotPasswdAction(
|
|
BuildContext context, {
|
|
required String? email,
|
|
}) async {
|
|
ApiCallResponse? forgotPasswd;
|
|
|
|
forgotPasswd = await PhpGroup.forgotPasswordCall.call(
|
|
email: email,
|
|
);
|
|
|
|
if (PhpGroup.forgotPasswordCall.error(
|
|
(forgotPasswd.jsonBody ?? ''),
|
|
) !=
|
|
false) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
Future cachingLoginActionApp(BuildContext context) async {
|
|
if (FFAppState().isLogged == true) {
|
|
context.pushNamed('homePage');
|
|
} else {
|
|
if (isAndroid == true) {
|
|
FFAppState().device = 'Android';
|
|
} else if (isiOS == true) {
|
|
FFAppState().device = 'iOS';
|
|
} else {
|
|
FFAppState().device = 'Web';
|
|
}
|
|
}
|
|
}
|
|
|
|
Future toggleSignInPage(BuildContext context) async {
|
|
context.pushNamed(
|
|
'signInPage',
|
|
extra: <String, dynamic>{
|
|
kTransitionInfoKey: const TransitionInfo(
|
|
hasTransition: true,
|
|
transitionType: PageTransitionType.fade,
|
|
),
|
|
},
|
|
);
|
|
}
|
|
|
|
Future toggleSignUpPage(BuildContext context) async {
|
|
context.pushNamed(
|
|
'signUpPage',
|
|
extra: <String, dynamic>{
|
|
kTransitionInfoKey: const TransitionInfo(
|
|
hasTransition: true,
|
|
transitionType: PageTransitionType.fade,
|
|
),
|
|
},
|
|
);
|
|
}
|
|
|
|
Future toggleHomePage(BuildContext context) async {
|
|
context.goNamed(
|
|
'homePage',
|
|
extra: <String, dynamic>{
|
|
kTransitionInfoKey: const TransitionInfo(
|
|
hasTransition: true,
|
|
transitionType: PageTransitionType.fade,
|
|
),
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<bool> visitRequestComponentAction(
|
|
BuildContext context, {
|
|
required String? actionValue,
|
|
required String? refUUID,
|
|
required String? responseValue,
|
|
required String? vteUUID,
|
|
}) async {
|
|
ApiCallResponse? respondeSolicitacaoCall;
|
|
|
|
respondeSolicitacaoCall = await PhpGroup.respondeSolicitacaoCall.call(
|
|
userUUID: FFAppState().userUUID,
|
|
devUUID: FFAppState().devUUID,
|
|
cliUUID: FFAppState().cliUUID,
|
|
atividade: 'respondeSolicitacao',
|
|
referencia: refUUID,
|
|
tarefa: actionValue,
|
|
resposta: responseValue,
|
|
idVisitante: vteUUID,
|
|
);
|
|
|
|
if (respondeSolicitacaoCall.statusCode == 200) {
|
|
return true;
|
|
} else {
|
|
debugPrint('headers: ${respondeSolicitacaoCall.headers}');
|
|
debugPrint('bodyText: ${respondeSolicitacaoCall.bodyText}');
|
|
debugPrint('jsonBody: ${respondeSolicitacaoCall.jsonBody}');
|
|
debugPrint('userUUID: ${FFAppState().userUUID}');
|
|
debugPrint('devUUID: ${FFAppState().devUUID}');
|
|
debugPrint('cliUUID: ${FFAppState().cliUUID}');
|
|
debugPrint('atividade: respondeSolicitacao');
|
|
debugPrint('referencia: $refUUID');
|
|
debugPrint('tarefa: $actionValue');
|
|
debugPrint('resposta: $responseValue');
|
|
debugPrint('idVisitante: $vteUUID');
|
|
return false;
|
|
}
|
|
}
|
|
|
|
Future<void> 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<bool> checkLocals({
|
|
String? cliUUID,
|
|
required BuildContext context,
|
|
required HomePageModel model,
|
|
required void Function(void Function()) safeSetState,
|
|
}) async {
|
|
// A chamada para a API permanece a mesma, assumindo que é necessária sempre.
|
|
final response = await PhpGroup.getLocalsCall.call(
|
|
devUUID: FFAppState().devUUID,
|
|
userUUID: FFAppState().userUUID,
|
|
);
|
|
|
|
// Verificação rápida de erro para evitar processamento desnecessário.
|
|
if (response.jsonBody['error']) {
|
|
debugPrint("checkLocals => Erro encontrado na resposta");
|
|
return false;
|
|
}
|
|
|
|
// Uso eficiente de coleções para verificar a condição desejada.
|
|
final String uuid = cliUUID ?? FFAppState().cliUUID;
|
|
final bool itemFound = response.jsonBody['locais'].any(
|
|
(local) => local['CLI_ID'] == uuid && local['CLU_STATUS'] == "A",
|
|
);
|
|
|
|
// Log e retorno condicional baseado no resultado da busca.
|
|
if (itemFound) {
|
|
debugPrint("checkLocals => Item encontrado com CLI_ID $uuid e CLU_STATUS A");
|
|
return true;
|
|
} else {
|
|
debugPrint("checkLocals => Item não encontrado com CLI_ID $uuid e CLU_STATUS A");
|
|
// A chamada para showModalBottomSheet permanece, mas a atualização da UI é otimizada.
|
|
await showModalBottomSheet(
|
|
isScrollControlled: true,
|
|
backgroundColor: Colors.transparent,
|
|
enableDrag: false,
|
|
context: context,
|
|
builder: (context) => GestureDetector(
|
|
onTap: () => model.unfocusNode.canRequestFocus
|
|
? FocusScope.of(context).requestFocus(model.unfocusNode)
|
|
: FocusScope.of(context).unfocus(),
|
|
child: Padding(
|
|
padding: MediaQuery.viewInsetsOf(context),
|
|
child: const BottomArrowLinkedLocalsComponentWidget(),
|
|
),
|
|
),
|
|
);
|
|
safeSetState(() {}); // Chamada otimizada fora do then para evitar encadeamentos desnecessários.
|
|
return false;
|
|
}
|
|
}
|
|
|
|
|
|
Future changeStatusAction(
|
|
BuildContext context,
|
|
String status,
|
|
String vawREF,
|
|
String msg,
|
|
String vteUUID,
|
|
) async {
|
|
debugPrint('status: $status');
|
|
|
|
switch (status) {
|
|
case 'L':
|
|
Navigator.pop(context, true);
|
|
|
|
bool? approveVisitRequest;
|
|
approveVisitRequest = await visitRequestComponentAction(
|
|
context,
|
|
actionValue: status,
|
|
refUUID: vawREF,
|
|
responseValue: msg,
|
|
vteUUID: vteUUID,
|
|
);
|
|
if (!context.mounted) return;
|
|
if (approveVisitRequest == true) {
|
|
debugPrint('Aprovado');
|
|
} else {
|
|
debugPrint('Erro ao aprovar');
|
|
}
|
|
break;
|
|
case 'B':
|
|
Navigator.pop(context, true);
|
|
|
|
bool? blockVisitRequest;
|
|
blockVisitRequest = await visitRequestComponentAction(
|
|
context,
|
|
actionValue: status,
|
|
refUUID: vawREF,
|
|
responseValue: msg,
|
|
vteUUID: vteUUID,
|
|
);
|
|
if (!context.mounted) return;
|
|
if (blockVisitRequest == true) {
|
|
debugPrint('Bloqueado');
|
|
} else {
|
|
debugPrint('Erro ao bloquear');
|
|
}
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
/// QR Code
|
|
|
|
|
|
Uint8List assembleQRPacket(int direction, String identifier, String password) {
|
|
Uint8List packet = Uint8List(20);
|
|
int position = 0;
|
|
int check = 0;
|
|
|
|
// Direction
|
|
packet[position++] = direction;
|
|
|
|
// Identifier
|
|
Uint8List ide = hexStringToByteArray(("000000000000000000000000000000" + identifier).substring(identifier.length));
|
|
for (int i = 0; i < ide.length; i++) {
|
|
packet[position++] = ide[i];
|
|
}
|
|
|
|
// Date and time
|
|
DateTime now = DateTime.now();
|
|
int day = int.parse(DateFormat('dd').format(now));
|
|
int month = int.parse(DateFormat('MM').format(now));
|
|
int year = int.parse(DateFormat('yy').format(now));
|
|
int hour = int.parse(DateFormat('HH').format(now));
|
|
int minute = int.parse(DateFormat('mm').format(now));
|
|
|
|
int sumDate = year + month + day + hour + minute;
|
|
packet[position++] = (sumDate == 0x0D || sumDate == 0x0A) ? 0xFF : sumDate;
|
|
|
|
// Log the sumDate
|
|
developer.log("Soma Data: $sumDate", name: "ROTINAS");
|
|
|
|
// Password
|
|
Uint8List passBytes = hexStringToByteArray(password);
|
|
packet[position++] = passBytes[0];
|
|
packet[position++] = passBytes[1];
|
|
|
|
// Checksum
|
|
for (int i = 0; i < packet.length - 1; i++) {
|
|
check ^= packet[i];
|
|
}
|
|
packet[position] = (check == 0x0D || check == 0x0A) ? 0xFF : check;
|
|
|
|
// Log the checksum
|
|
developer.log("Checksum: $check", name: "ROTINAS");
|
|
|
|
// Convert packet to hex string and log it
|
|
String hexPacket = byteToHexa(packet);
|
|
developer.log("Pacote final: $hexPacket", name: "ROTINAS");
|
|
|
|
return 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(List<int> pDados) {
|
|
return pDados.map((byte) => byte.toRadixString(16).padLeft(2, '0').toUpperCase()).join();
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
String byteToString(Uint8List bytes) {
|
|
return utf8.decode(bytes);
|
|
}
|
|
|
|
Widget buildQrCode(
|
|
{
|
|
required String data,
|
|
required String type,
|
|
required double dimension,
|
|
required int errorCorrectLevel,
|
|
required int version,
|
|
required int maskPattern,
|
|
required String identifier,
|
|
required String pass,
|
|
required int direction
|
|
}
|
|
) {
|
|
debugPrint('remoteID: ${FFAppState().userDevUUID}');
|
|
debugPrint('androidId: ${FFAppState().devUUID}');
|
|
debugPrint('Serial Number: ${FFAppState().serialNumber}');
|
|
|
|
try {
|
|
// Verifica se os dados estão de acordo com as regras de negócio
|
|
if (data.isEmpty) {
|
|
throw Exception("Dados do QR Code estão vazios.");
|
|
}
|
|
// Aqui você pode adicionar mais lógica de validação conforme necessário
|
|
|
|
// Geração do QR Code com a biblioteca qr_flutter
|
|
const Color backgroundColor = Colors.white;
|
|
const Color foregroundColor = Colors.black;
|
|
return QrImageView(
|
|
data: byteToString(assembleQRPacket(direction, identifier, pass)),
|
|
version: version, //QrVersions.auto
|
|
size: dimension,
|
|
// errorCorrectionLevel: errorCorrectLevel,
|
|
backgroundColor: backgroundColor,
|
|
foregroundColor: foregroundColor,
|
|
gapless: false, // Ajuste conforme necessário
|
|
// Adicione mais customizações aqui conforme os arquivos Java
|
|
);
|
|
} catch (e) {
|
|
// Tratamento de erros
|
|
return Text("Erro ao gerar QR Code: ${e.toString()}");
|
|
}
|
|
}
|
|
|
|
|
|
// // Retorna o conteúdo a ser codificado no QR Code.
|
|
// String getContents() {
|
|
// return data;
|
|
// }
|
|
|
|
// // Retorna uma versão do conteúdo otimizada para exibição.
|
|
// String getDisplayContents() {
|
|
// return data.trim();
|
|
// }
|
|
|
|
// // Retorna o título baseado no tipo de conteúdo.
|
|
// String getTitle() {
|
|
// return type;
|
|
// }
|
|
|
|
// // Codifica o conteúdo em uma string adequada para o QR Code.
|
|
// Future<String> encodeContents() async {
|
|
// // Implementação específica para codificar o conteúdo.
|
|
// return data; // Exemplo simplificado.
|
|
// }
|
|
|
|
// // Codifica o conteúdo específico do QR Code.
|
|
// Future<Widget> encodeQRCodeContents() async {
|
|
// return getQrCode();
|
|
// }
|
|
|
|
// // Gera o QR Code como um widget.
|
|
|
|
|
|
// // Codifica o conteúdo como um bitmap (pode ser útil para operações de baixo nível).
|
|
// // Future<Image> encodeAsBitmap() async {
|
|
// // // Implementação para codificar como bitmap.
|
|
// // return Image(image); // Exemplo simplificado.
|
|
// // }
|
|
|
|
// // Adivinha a codificação apropriada para o conteúdo.
|
|
// String guessAppropriateEncoding(String content) {
|
|
// // Implementação para adivinhar a codificação.
|
|
// return "UTF-8"; // Exemplo simplificado.
|
|
// }
|
|
|
|
// // Remove espaços em branco do início e do fim do conteúdo.
|
|
// String trim(String content) {
|
|
// return content.trim();
|
|
// }
|
|
|
|
// // Escapa caracteres especiais para o formato MECARD.
|
|
// String escapeMECARD(String content) {
|
|
// // Implementação para escapar caracteres.
|
|
// return content.replaceAll(':', '\\:'); // Exemplo simplificado.
|
|
// } |