This commit is contained in:
J. A. Messias 2024-09-17 13:07:24 -03:00
parent a9135c5f58
commit e4e6529bf5
16 changed files with 456 additions and 234 deletions

View File

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

View File

@ -1317,7 +1317,7 @@ class GetDadosCall {
String? devUUID = '', String? devUUID = '',
String? userUUID = '', String? userUUID = '',
String? cliUUID = '', String? cliUUID = '',
String? atividade = '', String? atividade = 'getDados',
}) async { }) async {
final baseUrl = PhpGroup.getBaseUrl(); final baseUrl = PhpGroup.getBaseUrl();

View File

@ -4,6 +4,7 @@ import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:hub/app_state.dart'; import 'package:hub/app_state.dart';
import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_calls.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/utils/log_util.dart'; import 'package:hub/shared/utils/log_util.dart';
import 'notification_service.dart'; import 'notification_service.dart';
@ -61,11 +62,13 @@ class FirebaseMessagingService {
if (deviceToken != null) { if (deviceToken != null) {
AppState().token = deviceToken; AppState().token = deviceToken;
final ApiCallResponse? response;
final DatabaseHelper db = DatabaseHelper();
final devUUID = await db.get(key: 'devUUID', field: 'value');
final userUUID = await db.get(key: 'userUUID', field: 'value');
final ApiCallResponse? response = await PhpGroup.updToken.call( response = await PhpGroup.updToken
token: AppState().token, .call(token: AppState().token, devid: devUUID, useruuid: userUUID);
devid: AppState().devUUID,
useruuid: AppState().userUUID);
if (PhpGroup.updToken.error((response?.jsonBody ?? '')) == false) { if (PhpGroup.updToken.error((response?.jsonBody ?? '')) == false) {
log('Token Atualizado com Sucesso!'); log('Token Atualizado com Sucesso!');

View File

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

View File

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

View File

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

View File

@ -1,3 +1,5 @@
import 'package:hub/shared/helpers/db_helper.dart';
import '/flutter_flow/flutter_flow_util.dart'; import '/flutter_flow/flutter_flow_util.dart';
import 'local_profile_component_widget.dart' show LocalProfileComponentWidget; import 'local_profile_component_widget.dart' show LocalProfileComponentWidget;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -6,9 +8,24 @@ import 'package:flutter/material.dart';
class LocalProfileComponentModel class LocalProfileComponentModel
extends FlutterFlowModel<LocalProfileComponentWidget> { extends FlutterFlowModel<LocalProfileComponentWidget> {
final DatabaseHelper db = DatabaseHelper();
String cliName = '';
String cliUUID = '';
@override @override
void initState(BuildContext context) {} void initState(BuildContext context) {
init();
}
Future<void> init() async {
cliName = await db
.get(key: 'cliName', field: 'value')
.then((value) => value.toString());
cliUUID = await db
.get(key: 'cliUUID', field: 'value')
.then((value) => value.toString());
}
@override @override
void dispose() {} void dispose() {}
} }

View File

@ -93,7 +93,7 @@ class _LocalProfileComponentWidgetState
), ),
), ),
imageUrl: valueOrDefault( imageUrl: valueOrDefault(
'https://freaccess.com.br/freaccess/Images/Clients/${AppState().cliUUID}.png', 'https://freaccess.com.br/freaccess/Images/Clients/${_model.cliUUID}.png',
'assets/images/home.png'), 'assets/images/home.png'),
width: 80.0, width: 80.0,
height: 80.0, height: 80.0,
@ -111,11 +111,12 @@ class _LocalProfileComponentWidgetState
), ),
Text( Text(
valueOrDefault<String>( valueOrDefault<String>(
functions.convertToUppercase(AppState().local), functions.convertToUppercase(_model.cliName),
FFLocalizations.of(context).getVariableText( FFLocalizations.of(context).getVariableText(
ptText: 'SEM LOCAL VINCULADO', ptText: 'SEM LOCAL VINCULADO',
enText: 'NO LINKED LOCAL', enText: 'NO LINKED LOCAL',
)), ),
),
style: FlutterFlowTheme.of(context).labelMedium.override( style: FlutterFlowTheme.of(context).labelMedium.override(
fontFamily: 'Nunito', fontFamily: 'Nunito',
color: FlutterFlowTheme.of(context).info, color: FlutterFlowTheme.of(context).info,

View File

@ -3,6 +3,7 @@ import 'package:hub/backend/schema/enums/enums.dart';
import 'package:hub/components/atomic_components/menu_button_item/menu_button_item_widget.dart'; import 'package:hub/components/atomic_components/menu_button_item/menu_button_item_widget.dart';
import 'package:hub/components/atomic_components/menu_card_item/menu_card_item.dart'; import 'package:hub/components/atomic_components/menu_card_item/menu_card_item.dart';
import 'package:hub/components/molecular_components/menu_item/menu_item.dart'; import 'package:hub/components/molecular_components/menu_item/menu_item.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import '/components/organism_components/menu_list_view_component/menu_list_view_component_widget.dart'; import '/components/organism_components/menu_list_view_component/menu_list_view_component_widget.dart';
import '/components/organism_components/menu_staggered_view_component/menu_staggered_view_component_widget.dart'; import '/components/organism_components/menu_staggered_view_component/menu_staggered_view_component_widget.dart';
@ -52,6 +53,21 @@ class _MenuComponentWidgetState extends State<MenuComponentWidget> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final DatabaseHelper db = DatabaseHelper();
final cliUUID = db
.get(key: 'cliUUID', field: 'value')
.then((value) => value.toString());
final userUUID = db
.get(key: 'userUUID', field: 'value')
.then((value) => value.toString());
final devUUID = db
.get(key: 'devUUID', field: 'value')
.then((value) => value.toString());
final provisional =
db.get(key: 'cliName', field: 'value').then((value) => value);
final whatsapp =
db.get(key: 'whatsapp', field: 'value').then((value) => value);
final options = () { final options = () {
if (widget.item == MenuItem.button) { if (widget.item == MenuItem.button) {
if (_model.isGrid == true) if (_model.isGrid == true)

View File

@ -2,10 +2,17 @@ import 'package:flutter/material.dart';
import 'package:hub/backend/api_requests/api_manager.dart'; import 'package:hub/backend/api_requests/api_manager.dart';
import 'package:hub/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart'; import 'package:hub/components/templates_components/provisional_schedule_template/provisional_shcedule_template_widget.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:sqflite/sqflite.dart';
class ScheduleProvisionalVisitPageModel class ScheduleProvisionalVisitPageModel
extends FlutterFlowModel<ScheduleProvisionalVisitPageWidget> { extends FlutterFlowModel<ScheduleProvisionalVisitPageWidget> {
/// Local state fields for this page. final DatabaseHelper db = DatabaseHelper();
String cliUUID = '';
String devUUID = '';
String userUUID = '';
String cliName = '';
String ownerUUID = '';
bool toggleIdx = false; bool toggleIdx = false;
@ -96,6 +103,15 @@ class ScheduleProvisionalVisitPageModel
void initState(BuildContext context) { void initState(BuildContext context) {
personNameTextControllerValidator = _personNameTextControllerValidator; personNameTextControllerValidator = _personNameTextControllerValidator;
dateTimeTextControllerValidator = _dateTimeTextControllerValidator; dateTimeTextControllerValidator = _dateTimeTextControllerValidator;
init();
}
Future<void> init() async {
cliUUID = await db.get(key: 'cliUUID', field: 'value');
devUUID = await db.get(key: 'devUUID', field: 'value');
userUUID = await db.get(key: 'userUUID', field: 'value');
cliName = await db.get(key: 'cliName', field: 'value');
ownerUUID = await db.get(key: 'ownerUUID', field: 'value');
} }
@override @override

View File

@ -183,7 +183,7 @@ class _ScheduleProvisionalVisitPageWidgetState
fadeOutDuration: const Duration( fadeOutDuration: const Duration(
milliseconds: 200), milliseconds: 200),
imageUrl: imageUrl:
'https://freaccess.com.br/freaccess/Images/Clients/${AppState().cliUUID}.png', 'https://freaccess.com.br/freaccess/Images/Clients/${_model.cliUUID}.png',
width: 35.0, width: 35.0,
height: 35.0, height: 35.0,
fit: BoxFit.contain, fit: BoxFit.contain,
@ -195,7 +195,7 @@ class _ScheduleProvisionalVisitPageWidgetState
padding: const EdgeInsetsDirectional padding: const EdgeInsetsDirectional
.fromSTEB(15.0, 0.0, 0.0, 0.0), .fromSTEB(15.0, 0.0, 0.0, 0.0),
child: Text( child: Text(
AppState().local, _model.cliName,
style: FlutterFlowTheme.of(context) style: FlutterFlowTheme.of(context)
.bodyMedium .bodyMedium
.override( .override(
@ -919,15 +919,15 @@ class _ScheduleProvisionalVisitPageWidgetState
_model.provVisitSchedule = await PhpGroup _model.provVisitSchedule = await PhpGroup
.postProvVisitSchedulingCall .postProvVisitSchedulingCall
.call( .call(
devUUID: AppState().devUUID, devUUID: _model.devUUID,
userUUID: AppState().userUUID, userUUID: _model.userUUID,
cliID: AppState().cliUUID, cliID: _model.cliUUID,
atividade: 'putAgendamentoProv', atividade: 'putAgendamentoProv',
data: _model.dateTimeTextController.text, data: _model.dateTimeTextController.text,
motivo: _model.notesTextController.text, motivo: _model.notesTextController.text,
nome: nome:
_model.personNameTextController.text, _model.personNameTextController.text,
proID: AppState().ownerUUID, proID: _model.ownerUUID,
); );
if (PhpGroup.postProvVisitSchedulingCall if (PhpGroup.postProvVisitSchedulingCall

View File

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

View File

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

View File

@ -6,22 +6,14 @@ import 'package:hub/flutter_flow/flutter_flow_model.dart';
import 'package:hub/pages/home_page/home_page_widget.dart'; import 'package:hub/pages/home_page/home_page_widget.dart';
class HomePageModel extends FlutterFlowModel<HomePageWidget> { class HomePageModel extends FlutterFlowModel<HomePageWidget> {
/// Local state fields for this page.
bool isGrid = false; bool isGrid = false;
/// State fields for stateful widgets in this page.
final unfocusNode = FocusNode(); final unfocusNode = FocusNode();
// State field(s) for TextField widget.
FocusNode? textFieldFocusNode; FocusNode? textFieldFocusNode;
TextEditingController? textController; TextEditingController? textController;
String? Function(BuildContext, String?)? textControllerValidator; String? Function(BuildContext, String?)? textControllerValidator;
// Model for localComponent.
late LocalProfileComponentModel localComponentModel; late LocalProfileComponentModel localComponentModel;
// Model for menuComponent component.
late MenuComponentModel menuComponentModel; late MenuComponentModel menuComponentModel;
// Model for messageWellComponent component.
late MessageWellComponentModel messageWellComponentModel; late MessageWellComponentModel messageWellComponentModel;
@override @override

View File

@ -14,8 +14,10 @@ import 'package:hub/flutter_flow/flutter_flow_icon_button.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart'; import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart'; import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/pages/home_page/home_page_model.dart'; import 'package:hub/pages/home_page/home_page_model.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/utils/dialog_util.dart'; import 'package:hub/shared/utils/dialog_util.dart';
import 'package:hub/shared/widgets/drawer_widget/drawer_widget.dart'; import 'package:hub/shared/widgets/drawer_widget/drawer_widget.dart';
import 'package:sqflite/sqflite.dart';
class HomePageWidget extends StatefulWidget { class HomePageWidget extends StatefulWidget {
const HomePageWidget({Key? key}) : super(key: key); const HomePageWidget({Key? key}) : super(key: key);
@ -28,6 +30,7 @@ class _HomePageWidgetState extends State<HomePageWidget> {
late HomePageModel _model; late HomePageModel _model;
final scaffoldKey = GlobalKey<ScaffoldState>(); final scaffoldKey = GlobalKey<ScaffoldState>();
late LocalProfileComponentWidget _localProfileComponentWidget; late LocalProfileComponentWidget _localProfileComponentWidget;
final DatabaseHelper db = DatabaseHelper();
_HomePageWidgetState() { _HomePageWidgetState() {
_localProfileComponentWidget = _localProfileComponentWidget =
@ -36,23 +39,34 @@ class _HomePageWidgetState extends State<HomePageWidget> {
Future<void> processData() async { Future<void> processData() async {
try { try {
var response = await PhpGroup.getDadosCall.call( final GetDadosCall callback = PhpGroup.getDadosCall;
devUUID: AppState().devUUID, final DatabaseHelper db = DatabaseHelper();
userUUID: AppState().userUUID, final devUUID = await db.get(key: 'devUUID', field: 'value');
cliUUID: AppState().cliUUID, final userUUID = await db.get(key: 'userUUID', field: 'value');
atividade: 'getDados', final cliUUID = await db.get(key: 'cliUUID', field: 'value');
var response = await callback.call(
devUUID: devUUID,
userUUID: userUUID,
cliUUID: cliUUID,
); );
final error = response.jsonBody['error']; final error = response.jsonBody['error'];
final errorMsg = response.jsonBody['error_msg']; // final errorMsg = response.jsonBody['error_msg'];
if (error == false) { if (error == false) {
AppState().whatsapp = response.jsonBody['whatsapp'] ?? false; final whatsapp = response.jsonBody['whatsapp'] ?? false;
AppState().provisional = response.jsonBody['provisional'] ?? false; final provisional = response.jsonBody['provisional'] ?? false;
AppState().pets = response.jsonBody['pet'] ?? false; final pets = response.jsonBody['pet'] ?? false;
AppState().petAmountRegister = final petAmountRegister = response.jsonBody['petAmountRegister'] ?? '0';
response.jsonBody['petAmountRegister'] ?? '0'; final name = response.jsonBody['visitado']['VDO_NOME'];
AppState().name = response.jsonBody['visitado']['VDO_NOME'];
await db.update('whatsapp', whatsapp.toString(), 'local');
await db.update('provisional', provisional.toString(), 'local');
await db.update('pets', pets.toString(), 'local');
await db.update('petAmountRegister', petAmountRegister, 'local');
await db.update('name', name, 'local');
safeSetState(() {}); safeSetState(() {});
return; return;
} }
@ -67,9 +81,15 @@ class _HomePageWidgetState extends State<HomePageWidget> {
Future<void> processLocals() async { Future<void> processLocals() async {
try { try {
var response = await PhpGroup.getLocalsCall.call( final GetLocalsCall callback = PhpGroup.getLocalsCall;
devUUID: AppState().devUUID, final devUUID = await db.get(key: 'devUUID', field: 'value');
userUUID: AppState().userUUID, final userUUID = await db.get(key: 'userUUID', field: 'value');
final cliUUID = await db
.get(key: 'cliUUID', field: 'value')
.then((value) => value.toString());
var response = await callback.call(
devUUID: devUUID,
userUUID: userUUID,
); );
List<dynamic> locals = response.jsonBody['locais'] ?? []; List<dynamic> locals = response.jsonBody['locais'] ?? [];
@ -77,7 +97,7 @@ class _HomePageWidgetState extends State<HomePageWidget> {
final activeLocals = final activeLocals =
locals.where((local) => local['CLU_STATUS'] == 'A').toList(); locals.where((local) => local['CLU_STATUS'] == 'A').toList();
if (activeLocals.isEmpty || AppState().cliUUID.isEmpty) { if (activeLocals.isEmpty || cliUUID.isEmpty) {
await showModalSelectLocal(); await showModalSelectLocal();
} else { } else {
await processData(); await processData();
@ -124,7 +144,11 @@ class _HomePageWidgetState extends State<HomePageWidget> {
FirebaseMessagingService().updateDeviceToken(); FirebaseMessagingService().updateDeviceToken();
() async { () async {
if (AppState().cliUUID.isEmpty) { final cliUUID = await db
.get(key: 'cliUUID', field: 'value')
.then((value) => value.toString());
if (cliUUID.isEmpty) {
log('No cliUUID found');
await processLocals(); await processLocals();
} }
}(); }();
@ -218,8 +242,8 @@ class _HomePageWidgetState extends State<HomePageWidget> {
verticalDirection: VerticalDirection.down, verticalDirection: VerticalDirection.down,
clipBehavior: Clip.none, clipBehavior: Clip.none,
children: [ children: [
createLocal(), buildLocal(),
createBody(), buildBody(),
], ],
), ),
], ],
@ -228,7 +252,7 @@ class _HomePageWidgetState extends State<HomePageWidget> {
); );
} }
Widget createBody() { Widget buildBody() {
return Container( return Container(
color: FlutterFlowTheme.of(context).primaryBackground, color: FlutterFlowTheme.of(context).primaryBackground,
child: wrapWithModel( child: wrapWithModel(
@ -246,7 +270,7 @@ class _HomePageWidgetState extends State<HomePageWidget> {
); );
} }
Widget createLocal() { Widget buildLocal() {
return wrapWithModel( return wrapWithModel(
model: _model.localComponentModel, model: _model.localComponentModel,
updateCallback: () => safeSetState(() {}), updateCallback: () => safeSetState(() {}),

View File

@ -0,0 +1,187 @@
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
static Database? _database;
factory DatabaseHelper() => _instance;
DatabaseHelper._internal();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
final path = await _getDatabasePath();
log('Database path: $path');
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
onOpen: _onOpen,
).catchError((error) {
throw error;
}).whenComplete(() => log('Database initialized'));
}
Future<void> _onCreate(Database db, int version) async {
log('Creating tables...');
await db.execute('''
CREATE TABLE keychain (
key TEXT,
value TEXT,
type TEXT,
updateAt TEXT,
resolvedAt TEXT,
createdAt TEXT
);
''');
insert('email', '', 'user');
insert('passwd', '', 'user');
insert('devUUID', '', 'user');
insert('userUUID', '', 'user');
insert('userDevUUID', '', 'user');
insert('status', '', 'user');
insert('cliUUID', '', 'local');
insert('ownerUUID', '', 'local');
insert('cliName', '', 'local');
insert('whatsapp', '', 'local');
insert('provisional', '', 'local');
insert('pets', '', 'local');
insert('petAmountRegister', '', 'local');
log('Tables created');
}
Future<void> _onOpen(Database db) async {
log('Checking existing data...');
await _checkExistingData(db);
}
Future<void> deleteDatabaseDB() async {
final path = await _getDatabasePath();
await deleteDatabase(path);
log('Database deleted');
_database = null;
}
Future<String> _getDatabasePath() async {
final databasesPath = await getDatabasesPath();
final path = join(databasesPath, 'database.db');
log('Database path: $path');
return path;
}
Future<void> _checkExistingData(Database db) async {
try {
final maps = await db.query('keychain');
log('Existing data: $maps');
} catch (error) {
log('Error checking existing data: $error');
}
}
Future<dynamic> get({String? key, String? field}) async {
try {
final db = await database;
List<Map<String, dynamic>> queryResult;
if (field != null && key != null) {
queryResult = await db.query(
'keychain',
columns: [field],
where: 'key = ?',
whereArgs: [key],
);
} else if (field != null) {
queryResult = await db.query(
'keychain',
columns: [field],
);
} else if (key != null) {
field = 'value';
queryResult = await db.query(
'keychain',
columns: [field],
where: 'key = ?',
whereArgs: [key],
);
} else {
queryResult = await db.query('keychain');
}
log('Query result for key: $key, field: $field -> $queryResult');
if (queryResult.isNotEmpty) {
return queryResult.first[field];
} else {
return null;
}
} catch (error) {
log('Error getting: $error');
return null;
}
}
Future<int> insert(String key, dynamic value, String? type) async {
final db = await database;
final Map<String, dynamic> data = {
'key': key,
'value': value.toString(),
'type': type,
'updateAt': DateTime.now().toIso8601String(),
'resolvedAt': null,
'createdAt': DateTime.now().toIso8601String(),
};
log('Inserting: $data');
return await db.insert('keychain', data);
}
Future<int> update(String key, dynamic value, String? type) async {
final db = await database;
final Map<String, dynamic> data = {
'key': key,
if (value != null) 'value': value.toString(),
if (type != null) 'type': type,
'updateAt': DateTime.now().toIso8601String(),
'resolvedAt': null,
'createdAt': DateTime.now().toIso8601String(),
};
log('Updating: $data');
return await db.update(
'keychain',
data,
where: 'key = ?',
whereArgs: [key],
);
}
Future<int> delete(int id) async {
final db = await database;
log('Deleting with id: $id');
return await db.delete('keychain', where: 'id = ?', whereArgs: [id]);
}
Future<int> purge() async {
final db = await database;
log('Deleting all');
return await db.delete('keychain');
}
}