fix: Paginação do Historico de Acesso

This commit is contained in:
Ivan Antunes 2024-08-12 13:02:27 -03:00
parent 5d6f4209d6
commit b678ed5142
3 changed files with 173 additions and 185 deletions

View File

@ -1715,7 +1715,7 @@ class RespondeSolicitacaoCall {
} }
class GetAccessCall { class GetAccessCall {
Stream<ApiCallResponse> call({ Future<ApiCallResponse> call({
String? devUUID = '', String? devUUID = '',
String? userUUID = '', String? userUUID = '',
String? cliID = '', String? cliID = '',
@ -1725,11 +1725,8 @@ class GetAccessCall {
String? pesTipo = '', String? pesTipo = '',
}) { }) {
final baseUrl = PhpGroup.getBaseUrl(); final baseUrl = PhpGroup.getBaseUrl();
final StreamController<ApiCallResponse> controller = StreamController();
Future.microtask(() async { return ApiManager.instance.makeApiCall(
try {
final response = await ApiManager.instance.makeApiCall(
callName: 'getAccess', callName: 'getAccess',
apiUrl: '$baseUrl/processRequest.php', apiUrl: '$baseUrl/processRequest.php',
callType: ApiCallType.POST, callType: ApiCallType.POST,
@ -1753,15 +1750,6 @@ class GetAccessCall {
isStreamingApi: false, isStreamingApi: false,
alwaysAllowBody: false, alwaysAllowBody: false,
); );
controller.add(response);
await controller.close();
} catch (e) {
controller.addError(e);
await controller.close();
}
});
return controller.stream;
} }
bool? error(dynamic response) => castToType<bool>(getJsonField( bool? error(dynamic response) => castToType<bool>(getJsonField(

View File

@ -11,11 +11,11 @@ import 'package:hub/pages/liberation_history/liberation_history_model.dart';
class AcessHistoryPageModel extends FlutterFlowModel<AcessHistoryPageWidget> { class AcessHistoryPageModel extends FlutterFlowModel<AcessHistoryPageWidget> {
final unfocusNode = FocusNode(); final unfocusNode = FocusNode();
final _accessHistoryManager = StreamRequestManager<ApiCallResponse>(); final _accessHistoryManager = FutureRequestManager<ApiCallResponse>();
Stream<ApiCallResponse> accessHistory({ Future<ApiCallResponse> accessHistory({
String? uniqueQueryKey, String? uniqueQueryKey,
bool? overrideCache, bool? overrideCache,
required Stream<ApiCallResponse> Function() requestFn, required Future<ApiCallResponse> Function() requestFn,
}) => }) =>
_accessHistoryManager.performRequest( _accessHistoryManager.performRequest(
uniqueQueryKey: uniqueQueryKey, uniqueQueryKey: uniqueQueryKey,

View File

@ -1,5 +1,6 @@
import 'dart:developer'; import 'dart:developer';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:google_fonts/google_fonts.dart'; import 'package:google_fonts/google_fonts.dart';
@ -7,9 +8,7 @@ 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/backend/api_requests/api_manager.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/components/molecular_components/message_opt_modal/opt_modal_widget.dart';
import 'package:hub/components/molecular_components/option_selection_modal/option_selection_modal_widget.dart';
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/custom_functions.dart';
import 'package:hub/flutter_flow/flutter_flow_icon_button.dart'; import 'package:hub/flutter_flow/flutter_flow_icon_button.dart';
import 'package:hub/flutter_flow/flutter_flow_model.dart'; import 'package:hub/flutter_flow/flutter_flow_model.dart';
@ -17,6 +16,8 @@ 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/pages/acess_history_page/acess_history_page_model.dart'; import 'package:hub/pages/acess_history_page/acess_history_page_model.dart';
import 'package:hub/shared/utils/dialog_util.dart';
import 'package:hub/shared/utils/log_util.dart';
import 'package:rxdart/rxdart.dart'; import 'package:rxdart/rxdart.dart';
@immutable @immutable
@ -53,19 +54,34 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
bool _isSubjectClosed = false; bool _isSubjectClosed = false;
final scaffoldKey = GlobalKey<ScaffoldState>(); final scaffoldKey = GlobalKey<ScaffoldState>();
_AcessHistoryPageWidgetState(Map<String, String> opt) late ScrollController _scrollController;
: selectedTypeSubject = BehaviorSubject.seeded(opt) { int _pageNumber = 1;
selectedTypeSubject.listen((value) { final int _pageSize = 10;
log("selectedTypeSubject changed: $value"); bool _hasData = false;
}); bool _loading = false;
String _personType = '.*';
String _accessType = '.*';
String _search = '.*';
late Future<void> _accessFuture;
List<dynamic> _accessWrap = [];
_AcessHistoryPageWidgetState(Map<String, String> opt) : selectedTypeSubject = BehaviorSubject.seeded(opt) {
selectedTypeSubject.listen((value) {});
} }
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_model = createModel(context, () => AcessHistoryPageModel()); _model = createModel(context, () => AcessHistoryPageModel());
log("initState called in _AcessHistoryPageWidgetState"); _accessFuture = fetchAccessHistoryService();
_scrollController = ScrollController()..addListener(() {
if (_scrollController.position.atEdge && _scrollController.position.pixels != 0) {
_loadMoreAccess();
}
});
} }
@override @override
@ -77,31 +93,31 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = FlutterFlowTheme.of(context);
return Scaffold( return Scaffold(
key: scaffoldKey, key: scaffoldKey,
backgroundColor: FlutterFlowTheme.of(context).primaryBackground, backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
appBar: _appBarOrganismWidget(context), appBar: _appBar(context, theme),
body: _accessHistoryListOrganismWidget(context)); body: _body(context));
} }
// AppBar Widgets
PreferredSizeWidget _appBarOrganismWidget(BuildContext context) { PreferredSizeWidget _appBar(BuildContext context, FlutterFlowTheme theme) {
final theme = FlutterFlowTheme.of(context);
return AppBar( return AppBar(
backgroundColor: theme.primaryBackground, backgroundColor: theme.primaryBackground,
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
leading: _appBarBackButtonAtomWidget(context, theme), leading: _backButton(context, theme),
title: _appBarTitleMoleculeWidget(context, theme), title: _title(context, theme),
centerTitle: true, centerTitle: true,
elevation: 0.0, elevation: 0.0,
actions: [ actions: [
_appBarFilterButtonAtomWidget(context), _filterButton(context)
], ],
); );
} }
Widget _appBarBackButtonAtomWidget( Widget _backButton(BuildContext context, FlutterFlowTheme theme) {
BuildContext context, FlutterFlowTheme theme) {
return FlutterFlowIconButton( return FlutterFlowIconButton(
borderColor: Colors.transparent, borderColor: Colors.transparent,
borderRadius: 30.0, borderRadius: 30.0,
@ -116,8 +132,7 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
); );
} }
Widget _appBarTitleMoleculeWidget( Widget _title(BuildContext context, FlutterFlowTheme theme) {
BuildContext context, FlutterFlowTheme theme) {
return Text( return Text(
FFLocalizations.of(context).getText('ch8qymga'), FFLocalizations.of(context).getText('ch8qymga'),
style: theme.headlineMedium.override( style: theme.headlineMedium.override(
@ -131,8 +146,7 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
); );
} }
Widget _appBarFilterButtonAtomWidget(BuildContext context) { Widget _filterButton(BuildContext context) {
log('selectedTypeSubject: ${selectedTypeSubject.value}');
return Row( return Row(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: [
@ -141,27 +155,20 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
child: IconButton( child: IconButton(
icon: const Icon(Icons.filter_list), icon: const Icon(Icons.filter_list),
onPressed: () async { onPressed: () async {
final Map<String, String>? selectedFilter = final Map<String, String>? selectedFilter = await showModalBottomSheet<Map<String, String>>(
await showModalBottomSheet<Map<String, String>>(
isScrollControlled: true, isScrollControlled: true,
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
context: context, context: context,
builder: (context) { builder: (context) {
return GestureDetector( return GestureDetector(
onTap: () { onTap: () => Navigator.of(context).pop(),
Navigator.of(context).pop();
},
child: Container( child: Container(
color: Colors.transparent, color: Colors.transparent,
child: GestureDetector( child: GestureDetector(
onTap: () {}, onTap: () {},
child: OptModalWidget( child: OptModalWidget(
defaultAccessType: defaultAccessType: selectedTypeSubject.value['accessType'] ?? '.*',
selectedTypeSubject.value['accessType'] ?? defaultPersonType: selectedTypeSubject.value['personType'] ?? '.*',
'.*',
defaultPersonType:
selectedTypeSubject.value['personType'] ??
'.*',
), ),
), ),
), ),
@ -169,7 +176,6 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
}); });
if (selectedFilter != null) { if (selectedFilter != null) {
log('Selected Filter: $selectedFilter');
_updateAccessHistoryAction(selectedFilter); _updateAccessHistoryAction(selectedFilter);
} }
}, },
@ -192,108 +198,112 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
}); });
if (needsUpdate) { if (needsUpdate) {
selectedTypeSubject.add(updatedType); selectedTypeSubject.add(updatedType);
log("updateAccessHistory called with newType: $newType"); fetchCardListViewService(updatedType);
safeSetState(() {}); safeSetState(() {});
} }
} }
} }
Stream<ApiCallResponse> fetchAccessHistoryService(String selectedType) { Future<ApiCallResponse?> fetchAccessHistoryService() async {
log('Calling API with type: $selectedType'); try {
switch (selectedType) { setState(() => _loading = true);
case 'E': var response = await PhpGroup.getAccessCall.call(
return _model.accessHistory(
requestFn: () => PhpGroup.getAccessCall.call(
devUUID: FFAppState().devUUID, devUUID: FFAppState().devUUID,
userUUID: FFAppState().userUUID, userUUID: FFAppState().userUUID,
cliID: FFAppState().cliUUID, cliID: FFAppState().cliUUID,
atividade: 'getAcessos', atividade: 'getAcessos',
pageSize: '100', pageSize: _pageSize.toString(),
pageNumber: '1', pageNumber: _pageNumber.toString(),
pesTipo: 'E', pesTipo: _personType != 'E' && _personType != 'O' ? 'T' : _personType,
),
); );
case 'O':
return _model.accessHistory(
requestFn: () => PhpGroup.getAccessCall.call(
devUUID: FFAppState().devUUID,
userUUID: FFAppState().userUUID,
cliID: FFAppState().cliUUID,
atividade: 'getAcessos',
pageSize: '100',
pageNumber: '1',
pesTipo: 'O',
),
);
default:
return _model.accessHistory(
requestFn: () => PhpGroup.getAccessCall.call(
devUUID: FFAppState().devUUID,
userUUID: FFAppState().userUUID,
cliID: FFAppState().cliUUID,
atividade: 'getAcessos',
pageSize: '100',
pageNumber: '1',
pesTipo: 'T',
),
);
}
}
Widget _accessHistoryListOrganismWidget(BuildContext context) {
return Center(
child: SingleChildScrollView(
child: Column(
children: [
StreamBuilder<Map<String, String>>(
stream: selectedTypeSubject.stream,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
final selected = snapshot.data!;
return _cardListViewOrganismWidget(selected);
},
),
],
),
),
);
}
Future<List<dynamic>> fetchCardListViewService(
Map<String, String> select) async {
log('Fetching access history');
final response =
await fetchAccessHistoryService(select['personType']!).first;
log('Response: ${response.jsonBody}');
final List<dynamic> accessHistory = response.jsonBody['acessos'] ?? []; final List<dynamic> accessHistory = response.jsonBody['acessos'] ?? [];
log('Access History Before Filtering: $accessHistory');
log('Filtering for: Person Type - ${select['personType']}, Access Type - ${select['accessType']}, Search - ${select['search']}');
return accessHistory.where((item) { List<dynamic> filteredAccess = accessHistory.where((item) {
final personTypeMatches = select['personType'] == '.*' || final personTypeMatches = _personType == '.*' || item["PES_TIPO"].toString() == _personType;
item["PES_TIPO"].toString() == select['personType']; final accessTypeMatches = _accessType == '.*' || item["ACE_TIPO"].toString() == _accessType;
final accessTypeMatches = select['accessType'] == '.*' || final searchMatches = _search == '.*' || item["PES_NOME"].toString().toLowerCase().contains(_search.toLowerCase());
item["ACE_TIPO"].toString() == select['accessType'];
final searchMatches = select['search'] == '.*' ||
item["PES_NOME"]
.toString()
.toLowerCase()
.contains(select['search']!.toLowerCase());
log('NOMES: ${item["PES_NOME"].toString().toLowerCase()}');
return personTypeMatches && accessTypeMatches && searchMatches; return personTypeMatches && accessTypeMatches && searchMatches;
}).toList(); }).toList();
if (filteredAccess != null && filteredAccess.isNotEmpty) {
setState(() {
_accessWrap.addAll(filteredAccess);
_hasData = true;
_loading = false;
});
return response;
} }
Widget _cardListViewOrganismWidget(Map<String, String> selected) { setState(() {
log('Selected types in Card: ${selected['personType']}, ${selected['accessType']}'); _hasData = false;
log('_buildAccessHistoryList called'); _loading = false;
return FutureBuilder<List<dynamic>>( });
future: fetchCardListViewService(selected), return null;
} catch (e, s) {
DialogUtil.errorDefault(context);
LogUtil.requestAPIFailed('processRequest', "", "Busca Acesso", e, s);
setState(() {
_hasData = false;
_loading = false;
});
}
}
Widget _body(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: _cardListViewOrganismWidget()),
if (_loading) Container(
padding: const EdgeInsets.only(top: 15, bottom: 15),
color: FlutterFlowTheme.of(context).primary,
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
FlutterFlowTheme.of(context).info,
),
),
),
),
if (_hasData == false) Container(
padding: const EdgeInsets.only(top: 15, bottom: 15),
color: FlutterFlowTheme.of(context).primary,
child: Center(
child: Text(
FFLocalizations.of(context).getVariableText(
ptText: "Não há mais dados.",
enText: "No more data."
),
style: TextStyle(color: FlutterFlowTheme.of(context).info),
)
),
),
],
);
}
void _loadMoreAccess() {
if (_hasData == true) {
_pageNumber++;
_accessFuture = fetchAccessHistoryService();
}
}
void fetchCardListViewService(Map<String, String> select) {
_personType = select['personType']!;
_accessType = select['accessType']!;
_search = select['search']!;
_accessWrap = [];
_pageNumber = 1;
_accessFuture = fetchAccessHistoryService();
}
Widget _cardListViewOrganismWidget() {
return FutureBuilder<void>(
future: _accessFuture,
builder: (context, snapshot) { builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) { if (snapshot.connectionState == ConnectionState.waiting && _accessWrap.isEmpty) {
log('Waiting for data');
return Center( return Center(
child: SizedBox( child: SizedBox(
width: 50.0, width: 50.0,
@ -304,40 +314,30 @@ class _AcessHistoryPageWidgetState extends State<AcessHistoryPageWidget> {
), ),
), ),
); );
} else if (snapshot.hasData && snapshot.data!.isEmpty) {
return Center(
child: Text(FFLocalizations.of(context).getVariableText(
ptText: "Nenhum histórico encontrado!",
enText: "No history found!")),
);
} else if (snapshot.hasError) { } else if (snapshot.hasError) {
return Center( return Center(
child: Text(FFLocalizations.of(context).getVariableText( child: Text(FFLocalizations.of(context).getVariableText(
ptText: "Falha ao efetuar operação!", ptText: "Falha ao efetuar operação!",
enText: "Failed to perform operation!")), enText: "Failed to perform operation!")),
); );
} else { }
final accessHistory = snapshot.data!;
log('Access History: $accessHistory');
return ListView.builder( return ListView.builder(
shrinkWrap: true, shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(), physics: const BouncingScrollPhysics(),
itemCount: accessHistory.length, controller: _scrollController,
itemCount: _accessWrap.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final accessHistoryItem = accessHistory[index]; final accessHistoryItem = _accessWrap[index];
log('Access History Item: ${accessHistoryItem['PES_TIPO']}'); return _accessHistoryCardMoleculeWidget(context, accessHistoryItem);
return _accessHistoryCardMoleculeWidget(
context, accessHistoryItem);
}, },
); );
}
}, },
); );
} }
Widget _accessHistoryCardMoleculeWidget( Widget _accessHistoryCardMoleculeWidget(BuildContext context, dynamic accessHistoryItem) {
BuildContext context, dynamic accessHistoryItem) {
log('Access History Item: $accessHistoryItem');
return CardItemTemplateComponentWidget( return CardItemTemplateComponentWidget(
imageHashMap: Map<String, String>.from({ imageHashMap: Map<String, String>.from({
'key': accessHistoryItem['PES_ID'] ?? '', 'key': accessHistoryItem['PES_ID'] ?? '',