diff --git a/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart b/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart index c02604d..9cbcc07 100644 --- a/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart +++ b/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart @@ -51,10 +51,13 @@ class LearningDevelopmentBloc attachmentCategories = await AttachmentServices.instance.getCategories(); } - List learnings = await LearningDevelopmentServices + if(learningsAndDevelopments.isEmpty){ + List learnings = await LearningDevelopmentServices .instance .getLearningDevelopments(event.profileId, event.token); learningsAndDevelopments = learnings; + } + emit(LearningDevelopmentLoadedState( learningsAndDevelopment: learningsAndDevelopments,attachmentCategory: attachmentCategories)); } catch (e) { diff --git a/lib/bloc/profile/profile_bloc.dart b/lib/bloc/profile/profile_bloc.dart index 6600285..dbe1e4c 100644 --- a/lib/bloc/profile/profile_bloc.dart +++ b/lib/bloc/profile/profile_bloc.dart @@ -64,6 +64,7 @@ class ProfileBloc extends Bloc { primaryBasicInformation: globalCurrentProfile!)); } else { currentProfileInformation = event.primaryBasicInformation; + globalCurrentProfile = currentProfileInformation; emit(BasicInformationProfileLoaded( primaryBasicInformation: currentProfileInformation!)); } @@ -108,7 +109,7 @@ class ProfileBloc extends Bloc { 0, ProfileOtherInfo(id: null, name: "NONE", description: null)); } emit(BasicInformationEditingState( - primaryInformation: currentProfileInformation!, + primaryInformation: globalCurrentProfile!, extensions: nameExtensions, sexes: sexes, bloodTypes: bloodType, diff --git a/lib/bloc/rbac/rbac_operations/agency/agency_event.dart b/lib/bloc/rbac/rbac_operations/agency/agency_event.dart index fece6bc..936e2d1 100644 --- a/lib/bloc/rbac/rbac_operations/agency/agency_event.dart +++ b/lib/bloc/rbac/rbac_operations/agency/agency_event.dart @@ -13,9 +13,12 @@ class GetAgencies extends AgencyEvent{ class AddAgency extends AgencyEvent{ final Agency agency; const AddAgency({required this.agency}); + List get props => [agency + ]; } class GetEstPointPersonAgencies extends AgencyEvent{ final List? assignedAreas; const GetEstPointPersonAgencies({required this.assignedAreas}); + } diff --git a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart index b302617..925e294 100644 --- a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart @@ -60,7 +60,7 @@ class AssignAreaBloc extends Bloc { } }); on((event, emit) async { - // try { + try { emit(AssignAreaLoadingState()); Map response = await RbacAssignedAreaServices.instance .add( @@ -77,11 +77,6 @@ class AssignAreaBloc extends Bloc { break; } } - // newAssignArea = userAssignedAreas.firstWhere((var element) { - // return element.assignedRole?.role?.id == event.roleId && - // element.assignedRole?.user?.id == event.userId; - // }); - if (newAssignArea?.assignedArea != null) { userAssignedAreas.removeWhere((element) => element.assignedRole!.role!.id == event.roleId && @@ -120,8 +115,8 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); //// purok } if (event.areaTypeId == 2) { @@ -149,8 +144,8 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } ////statiom if (event.areaTypeId == 4) { @@ -200,8 +195,8 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } ////agency if (event.areaTypeId == 3) { @@ -231,16 +226,16 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } emit(AssignAreaAddedState(response: response)); } else { emit(AssignAreaAddedState(response: response)); } - // } catch (e) { - // emit(AssignAreaErorState(message: e.toString())); - // } + } catch (e) { + emit(AssignAreaErorState(message: e.toString())); + } }); on((event, emit) async { emit(AssignedAreaLoadedState( diff --git a/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart b/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart index 3f52bd4..36ace5d 100644 --- a/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart @@ -11,7 +11,7 @@ part 'role_module_state.dart'; class RoleModuleBloc extends Bloc { RoleModuleBloc() : super(RoleModuleInitial()) { List roleModules = []; - List roles = []; + List roles = []; List modules = []; on((event, emit) async { emit(RoleModuleLoadingState()); @@ -19,18 +19,19 @@ class RoleModuleBloc extends Bloc { if (roleModules.isEmpty) { roleModules = await RbacRoleModuleServices.instance.getRoleModules(); } - if (modules.isEmpty) { + if (modules.isEmpty) { modules = await RbacModuleServices.instance.getRbacModule(); } - if (roles.isEmpty) { + if (roles.isEmpty) { roles = await RbacRoleServices.instance.getRbacRoles(); } - emit(RoleModuleLoadedState(roleModules: roleModules,modules: modules,roles: roles)); + emit(RoleModuleLoadedState( + roleModules: roleModules, modules: modules, roles: roles)); } catch (e) { emit(RoleModuleErrorState(message: e.toString())); } }); - on((event, emit) async { + on((event, emit) async { try { emit(RoleModuleLoadingState()); Map statusResponse = @@ -40,9 +41,12 @@ class RoleModuleBloc extends Bloc { moduleIds: event.moduleIds); if (statusResponse['success']) { + List ids = roleModules.map((e) => e.id).toList(); statusResponse['data'].forEach((var roleMod) { RoleModules newRoleModule = RoleModules.fromJson(roleMod); - roleModules.add(newRoleModule); + if (!ids.contains(newRoleModule.id)) { + roleModules.add(newRoleModule); + } emit(RoleModuleAddedState(response: statusResponse)); }); } else { diff --git a/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart index f8fc508..ba17ba3 100644 --- a/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart @@ -36,11 +36,14 @@ class RolesUnderBloc extends Bloc { .add(roleId: event.roleId, rolesId: event.roleUnderIds); if (statusResponse['success']) { + List ids = rolesUnder.map((e) => e.id).toList(); statusResponse['data'].forEach((var roleMod) { RolesUnder newRoleUnder = RolesUnder.fromJson(roleMod); - rolesUnder.add(newRoleUnder); - emit(RoleUnderAddedState(response: statusResponse)); + if (!ids.contains(newRoleUnder.id)) { + rolesUnder.add(newRoleUnder); + } }); + emit(RoleUnderAddedState(response: statusResponse)); } else { emit(RoleUnderAddedState(response: statusResponse)); } diff --git a/lib/screens/profile/components/basic_information/citizenship_screen.dart b/lib/screens/profile/components/basic_information/citizenship_screen.dart index 3980950..913913c 100644 --- a/lib/screens/profile/components/basic_information/citizenship_screen.dart +++ b/lib/screens/profile/components/basic_information/citizenship_screen.dart @@ -23,9 +23,9 @@ import '../../../../utils/alerts.dart'; class CitizenShipScreen extends StatefulWidget { final int profileId; final String token; - + final List citizenships; const CitizenShipScreen( - {super.key, required this.profileId, required this.token}); + {super.key, required this.profileId, required this.token , required this.citizenships}); @override State createState() => _CitizenShipScreenState(); @@ -421,7 +421,9 @@ class _CitizenShipScreenState extends State { if (state is CitizenshipErrorState) { return Scaffold( body: SomethingWentWrong( - message: state.message, onpressed: () {})); + message: state.message, onpressed: () { + context.read().add(GetCitizenship(citizenship: widget.citizenships)); + })); } return Container(); }, diff --git a/lib/screens/profile/components/basic_information/contact_information/add_modal.dart b/lib/screens/profile/components/basic_information/contact_information/add_modal.dart index 0d7d0c2..49be54c 100644 --- a/lib/screens/profile/components/basic_information/contact_information/add_modal.dart +++ b/lib/screens/profile/components/basic_information/contact_information/add_modal.dart @@ -10,6 +10,7 @@ import 'package:unit2/sevices/profile/contact_services.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; import 'package:unit2/theme-data.dart/form-style.dart'; import 'package:unit2/utils/global.dart'; +import 'package:unit2/utils/global_context.dart'; import 'package:unit2/utils/text_container.dart'; import '../../../../../theme-data.dart/colors.dart'; @@ -84,7 +85,7 @@ class _AddContactInformationScreenState serviceTypeId: selectedServiceType!.id!); } catch (e) { - context + NavigationService.navigatorKey.currentContext! .read() .add(CallErrorEvent(message: e.toString())); } @@ -129,6 +130,7 @@ class _AddContactInformationScreenState ? selectedServiceType?.id == 2 //// Landline ? FormBuilderTextField( + keyboardType: TextInputType.number, controller: numberMailController, inputFormatters: [landLineFormatter], name: 'number-mail', @@ -150,7 +152,7 @@ class _AddContactInformationScreenState errorText: "This field is required"), decoration: normalTextFieldStyle( "Mobile number *", - "+63 (9xx) xxx - xxxx"), + "+63 (9xx) xxx - xxxx").copyWith(helperText: "Please input your mobile number excluding the 0"), ) : selectedServiceType!.id == 4 ////Social Media @@ -167,6 +169,7 @@ class _AddContactInformationScreenState : selectedServiceType!.id == 3 ////Email Address ? FormBuilderTextField( + keyboardType: TextInputType.emailAddress, controller: numberMailController, name: 'number-mail', validator: FormBuilderValidators diff --git a/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart b/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart index f2e713d..e1c9187 100644 --- a/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart +++ b/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart @@ -37,7 +37,7 @@ class _EditContactInformationScreenState var mobileFormatter = MaskTextInputFormatter( mask: "+63 (###) ###-####", - filter: {"#": RegExp(r"^[1-9][0-9]*$")}, + filter: {"#": RegExp(r'^[0-9][0-9]*$')}, type: MaskAutoCompletionType.lazy, initialText: "0"); @@ -149,6 +149,7 @@ class _EditContactInformationScreenState ? selectedServiceType?.id == 2 //// Landline ? FormBuilderTextField( + keyboardType: TextInputType.number, controller: numberMailController, name: 'number-mail', inputFormatters: [landLineFormatter], @@ -162,6 +163,7 @@ class _EditContactInformationScreenState selectedServiceType!.id == 19 //// Mobile number ? FormBuilderTextField( + keyboardType: TextInputType.number, controller: numberMailController, name: 'number-mail', inputFormatters: [mobileFormatter], @@ -172,10 +174,12 @@ class _EditContactInformationScreenState decoration: normalTextFieldStyle( "Mobile number *", "+63 (9xx) xxx - xxxx"), + ) : selectedServiceType!.id == 4 ////Social Media ? FormBuilderTextField( + controller: numberMailController, name: 'number-mail', validator: @@ -188,6 +192,7 @@ class _EditContactInformationScreenState : selectedServiceType!.id == 3 ////Email Address ? FormBuilderTextField( + keyboardType: TextInputType.emailAddress, controller: numberMailController, name: 'number-mail', diff --git a/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart b/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart index 21b1560..226b39a 100644 --- a/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart +++ b/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart @@ -1,10 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:flutter/src/widgets/framework.dart'; -import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; - -import '../../../../../bloc/profile/family/family_bloc.dart'; import '../../../../../theme-data.dart/btn-style.dart'; import '../../../../../theme-data.dart/colors.dart'; import '../../../../../theme-data.dart/form-style.dart'; @@ -26,6 +22,7 @@ class AddMobileNumber extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ FormBuilderTextField( + keyboardType: TextInputType.number, name: 'number_mail', inputFormatters: [mobileFormatter], validator: FormBuilderValidators.required( diff --git a/lib/screens/profile/components/learning_and_development_screen.dart b/lib/screens/profile/components/learning_and_development_screen.dart index 1fe52ba..e528c3d 100644 --- a/lib/screens/profile/components/learning_and_development_screen.dart +++ b/lib/screens/profile/components/learning_and_development_screen.dart @@ -45,7 +45,7 @@ class LearningAndDevelopmentScreen extends StatelessWidget { AttachmentCategory? selectedAttachmentCategory; List attachmentCategories = []; return Scaffold( - resizeToAvoidBottomInset: true, + appBar: AppBar( title: context.watch().state is LearningDevelopmentAddingState diff --git a/lib/screens/profile/components/learning_development/add_modal.dart b/lib/screens/profile/components/learning_development/add_modal.dart index facf278..32756bd 100644 --- a/lib/screens/profile/components/learning_development/add_modal.dart +++ b/lib/screens/profile/components/learning_development/add_modal.dart @@ -107,19 +107,6 @@ class _AddLearningAndDevelopmentScreenState final selectedTrainingController = TextEditingController(); DateTime? from; DateTime? to; - @override - void dispose() { - // fromDateController.dispose(); - // toDateController.dispose(); - // addTrainingController.dispose(); - // addTopicController.dispose(); - // topicFocusNode.dispose(); - - // addSponsorAgencyController.dispose(); - // sponsorByFocusNode.dispose(); - // sponsorAgencyCategoryFocusNode.dispose(); - super.dispose(); - } @override Widget build(BuildContext context) { @@ -132,37 +119,25 @@ class _AddLearningAndDevelopmentScreenState padding: const EdgeInsets.all(24), child: StatefulBuilder(builder: (context, setState) { return ListView( + shrinkWrap: true, children: [ ////Training SearchField SizedBox( child: show ? SearchableDropdownFormField.paginated( errorWidget: (value) { - return SomethingWentWrong( - message: value, - onpressed: () { - context - .read< - LearningDevelopmentBloc>() - .add( - GetLearningDevelopments( - profileId: widget - .profileId, - token: - widget.token)); - }); + return Text(value!); }, noRecordTex: SizedBox( width: double.infinity, - height: 300, + height: 100, child: EmptyWidget( controller: addTrainingController, onpressed: () { setState(() { show = false; showOtherInputs = true; - selectedTrainingController - .text = + selectedTrainingController.text = addTrainingController.text .toUpperCase(); selectedTraining = @@ -171,8 +146,7 @@ class _AddLearningAndDevelopmentScreenState title: selectedTrainingController .text); - addTrainingController.text = - ""; + addTrainingController.text = ""; Navigator.of(context).pop(); Navigator.of(context).pop(); }); @@ -187,20 +161,16 @@ class _AddLearningAndDevelopmentScreenState width: double.infinity, child: Card( child: Padding( - padding: - const EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: child), ), ); }, - validator: - FormBuilderValidators.required( - errorText: - "This field is required"), - paginatedRequest: (int page, - String? searchKey) async { - List - paginatedList=[]; + validator: FormBuilderValidators.required( + errorText: "This field is required"), + paginatedRequest: + (int page, String? searchKey) async { + List paginatedList = []; try { paginatedList = await LearningDevelopmentServices @@ -209,12 +179,9 @@ class _AddLearningAndDevelopmentScreenState page: page, key: searchKey ??= ""); } catch (e) { - context - .read() - .add(CallErrorState( - message: e.toString())); + debugPrint(e.toString()); } - return paginatedList.map((e) { + return paginatedList.map((e) { return SearchableDropdownMenuItem( value: e, onTap: () {}, @@ -234,17 +201,14 @@ class _AddLearningAndDevelopmentScreenState selectedTraining = LearningDevelopmentType( id: null, - title: e.title! - .title); + title: e.title!.title); } show = false; showOtherInputs = true; - selectedTrainingController - .text = + selectedTrainingController.text = e.title!.title!; - Navigator.of(context) - .pop(); + Navigator.of(context).pop(); }); }, e: e, @@ -276,31 +240,25 @@ class _AddLearningAndDevelopmentScreenState ? FormBuilderTextField( maxLines: 5, readOnly: true, - controller: - selectedTrainingController, + controller: selectedTrainingController, name: "", decoration: - normalTextFieldStyle("", "") - .copyWith( - labelText: "Training", - suffixIcon: IconButton( - onPressed: () { - setState(() { - selectedConductedTraining = - null; - selectedTrainingController - .text = ""; - show = true; - showTrainingDetails = - false; - showOtherInputs = - false; - selectedTraining = - null; - }); - }, - icon: const Icon( - Icons.close))), + normalTextFieldStyle("", "").copyWith( + labelText: "Training", + suffixIcon: IconButton( + onPressed: () { + setState(() { + selectedConductedTraining = + null; + selectedTrainingController + .text = ""; + show = true; + showTrainingDetails = false; + showOtherInputs = false; + selectedTraining = null; + }); + }, + icon: const Icon(Icons.close))), ) : const SizedBox()), @@ -308,20 +266,15 @@ class _AddLearningAndDevelopmentScreenState SizedBox( child: showTrainingDetails ? TrainingDetails( - trainingTitle: - selectedConductedTraining! - .learningDevelopmentType! - .title!, - totalHours: selectedConductedTraining! - .totalHours!, + trainingTitle: selectedConductedTraining! + .learningDevelopmentType!.title!, + totalHours: + selectedConductedTraining!.totalHours!, trainingTopic: - selectedConductedTraining! - .topic!.title!, - toDate: selectedConductedTraining! - .toDate + selectedConductedTraining!.topic!.title!, + toDate: selectedConductedTraining!.toDate .toString(), - fromDate: selectedConductedTraining! - .fromDate! + fromDate: selectedConductedTraining!.fromDate! .toString(), conductedBy: selectedConductedTraining! .conductedBy!.name!) @@ -340,22 +293,17 @@ class _AddLearningAndDevelopmentScreenState FormBuilderDropdown< LearningDevelopmentType>( decoration: normalTextFieldStyle( - "Learning Development Type *", - ""), - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), + "Learning Development Type *", ""), + validator: FormBuilderValidators.required( + errorText: "This field is required"), name: "types", items: state.types .map((e) => DropdownMenuItem< LearningDevelopmentType>( - value: e, - child: Text(e.title!))) + value: e, child: Text(e.title!))) .toList(), onChanged: (value) { - selectedLearningDevelopmentType = - value; + selectedLearningDevelopmentType = value; }, ), @@ -371,7 +319,8 @@ class _AddLearningAndDevelopmentScreenState ], focusNode: topicFocusNode, itemHeight: 100, - suggestionsDecoration: searchFieldDecoration(), + suggestionsDecoration: + searchFieldDecoration(), suggestions: state.topics .map((LearningDevelopmentType topic) => @@ -379,28 +328,24 @@ class _AddLearningAndDevelopmentScreenState topic.title!, item: topic, child: Padding( - padding: const EdgeInsets + padding: + const EdgeInsets .symmetric( - horizontal: - 10), + horizontal: 10), child: ListTile( title: Text( - topic - .title!, - softWrap: - true, + topic.title!, + softWrap: true, ), )))) .toList(), searchInputDecoration: - normalTextFieldStyle( - "Topic *", "") + normalTextFieldStyle("Topic *", "") .copyWith( - suffixIcon: - IconButton( - icon: const Icon( - Icons.arrow_drop_down), + suffixIcon: IconButton( + icon: + const Icon(Icons.arrow_drop_down), onPressed: () { topicFocusNode.unfocus(); }, @@ -415,8 +360,7 @@ class _AddLearningAndDevelopmentScreenState selectedTopic = LearningDevelopmentType( id: null, - title: topic - .item!.title); + title: topic.item!.title); } setState(() { topicFocusNode.unfocus(); @@ -425,23 +369,21 @@ class _AddLearningAndDevelopmentScreenState ////EMPTY WIDGET emptyWidget: EmptyWidget( title: "Add Topic", - controller: - addTopicController, + controller: addTopicController, onpressed: () { setState(() { LearningDevelopmentType newTopic = LearningDevelopmentType( id: null, - title: addTopicController - .text - .toUpperCase()); - state.topics.insert( - 0, newTopic); - topicFocusNode - .unfocus(); - addTopicController - .text = ""; + title: + addTopicController + .text + .toUpperCase()); + state.topics + .insert(0, newTopic); + topicFocusNode.unfocus(); + addTopicController.text = ""; Navigator.pop(context); }); }), @@ -461,56 +403,47 @@ class _AddLearningAndDevelopmentScreenState width: screenWidth, child: StatefulBuilder( builder: (context, setState) { - return StatefulBuilder(builder: - (context, setState) { + return StatefulBuilder( + builder: (context, setState) { return Row( children: [ //// FROM DATE Flexible( flex: 1, child: DateTimePicker( - validator: - FormBuilderValidators - .required( - errorText: - "This field is required"), - use24HourFormat: - false, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + use24HourFormat: false, icon: const Icon( - Icons - .date_range), + Icons.date_range), controller: fromDateController, - firstDate: - DateTime(1990), - lastDate: - DateTime(2100), - + firstDate: DateTime(1990), + lastDate: DateTime(2100), onChanged: (value) { setState(() { - from = DateTime - .parse( - value); + from = DateTime.parse( + value); }); }, - initialDate: to == - null + initialDate: to == null ? DateTime.now() : to!.subtract( const Duration( - days: - 1)), + days: 1)), timeHintText: "Date of Examination/Conferment", - decoration: normalTextFieldStyle( - "From *", - "From *") - .copyWith( - prefixIcon: - const Icon( + decoration: + normalTextFieldStyle( + "From *", + "From *") + .copyWith( + prefixIcon: + const Icon( Icons.date_range, - color: Colors - .black87, + color: Colors.black87, )), initialValue: null, )), @@ -521,40 +454,31 @@ class _AddLearningAndDevelopmentScreenState Flexible( flex: 1, child: DateTimePicker( - validator: - FormBuilderValidators - .required( - errorText: - "This field is required"), - controller: - toDateController, - firstDate: - DateTime(1990), - + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + controller: toDateController, + firstDate: DateTime(1990), onChanged: (value) { setState(() { - to = DateTime - .parse(value); + to = + DateTime.parse(value); }); }, - initialDate: from == - null + initialDate: from == null ? DateTime.now() : from!.add( const Duration( days: 1)), - lastDate: - DateTime(2100), + lastDate: DateTime(2100), decoration: normalTextFieldStyle( - "To *", - "To *") + "To *", "To *") .copyWith( - prefixIcon: - const Icon( + prefixIcon: const Icon( Icons.date_range, - color: Colors - .black87, + color: Colors.black87, ), ), initialValue: null, @@ -573,10 +497,8 @@ class _AddLearningAndDevelopmentScreenState validator: numericRequired, name: "total_hours", decoration: normalTextFieldStyle( - "Total Hours Conducted *", - "0"), - keyboardType: - TextInputType.number, + "Total Hours Conducted *", "0"), + keyboardType: TextInputType.number, ), const SizedBox( height: 12, @@ -595,19 +517,14 @@ class _AddLearningAndDevelopmentScreenState overseas = value!; }); }, - decoration: - normalTextFieldStyle( - "Overseas Address?", - ''), + decoration: normalTextFieldStyle( + "Overseas Address?", ''), name: 'overseas', - title: Text(overseas - ? "YES" - : "NO"), + title: + Text(overseas ? "YES" : "NO"), ), SizedBox( - height: overseas == true - ? 8 - : 0, + height: overseas == true ? 8 : 0, ), SizedBox( child: overseas == false @@ -622,16 +539,16 @@ class _AddLearningAndDevelopmentScreenState autovalidateMode: AutovalidateMode .onUserInteraction, - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), onChanged: (Region? region) async { if (selectedRegion != region) { - setState( - () { + setState(() { provinceCall = true; }); @@ -640,8 +557,7 @@ class _AddLearningAndDevelopmentScreenState getProvinces(); } }, - initialValue: - null, + initialValue: null, decoration: normalTextFieldStyle( "Region*", @@ -653,11 +569,9 @@ class _AddLearningAndDevelopmentScreenState region) { return DropdownMenuItem< Region>( - value: - region, - child: Text( - region - .description!)); + value: region, + child: Text(region + .description!)); }).toList(), ), const SizedBox( @@ -666,8 +580,7 @@ class _AddLearningAndDevelopmentScreenState //// PROVINCE DROPDOWN SizedBox( height: 60, - child: - ModalProgressHUD( + child: ModalProgressHUD( color: Colors .transparent, inAsyncCall: @@ -677,11 +590,11 @@ class _AddLearningAndDevelopmentScreenState autovalidateMode: AutovalidateMode .onUserInteraction, - validator: (value) => value == null - ? 'required' - : null, - isExpanded: - true, + validator: (value) => + value == null + ? 'required' + : null, + isExpanded: true, value: selectedProvince, onChanged: @@ -689,8 +602,7 @@ class _AddLearningAndDevelopmentScreenState province) { if (selectedProvince != province) { - setState( - () { + setState(() { cityCall = true; }); @@ -702,42 +614,45 @@ class _AddLearningAndDevelopmentScreenState items: provinces == null ? [] - : provinces!.map>((Province + : provinces!.map< + DropdownMenuItem< + Province>>((Province province) { return DropdownMenuItem( - value: province, - child: FittedBox( - child: Text(province.description!), + value: + province, + child: + FittedBox( + child: + Text(province.description!), )); }).toList(), - decoration: normalTextFieldStyle( - "Province*", - "Province")), + decoration: + normalTextFieldStyle( + "Province*", + "Province")), ), ), ////CITY MUNICIPALITY SizedBox( height: 60, - child: - ModalProgressHUD( - color: Colors - .white, - inAsyncCall: - cityCall, + child: ModalProgressHUD( + color: Colors.white, + inAsyncCall: cityCall, child: DropdownButtonFormField< CityMunicipality>( - validator: FormBuilderValidators.required( - errorText: - "This field is required"), - isExpanded: - true, + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + isExpanded: true, onChanged: (CityMunicipality? city) { if (selectedMunicipality != city) { - setState( - () { + setState(() { barangayCall = true; }); @@ -755,12 +670,15 @@ class _AddLearningAndDevelopmentScreenState null ? [] : citymuns!.map< - DropdownMenuItem< - CityMunicipality>>((CityMunicipality - c) { + DropdownMenuItem< + CityMunicipality>>( + (CityMunicipality + c) { return DropdownMenuItem( - value: c, - child: Text(c.description!)); + value: + c, + child: Text( + c.description!)); }).toList(), ), ), @@ -768,25 +686,24 @@ class _AddLearningAndDevelopmentScreenState //// BARANGAY SizedBox( height: 60, - child: - ModalProgressHUD( - color: Colors - .white, + child: ModalProgressHUD( + color: Colors.white, inAsyncCall: barangayCall, - child: DropdownButtonFormField< - Barangay>( - isExpanded: - true, + child: + DropdownButtonFormField< + Barangay>( + isExpanded: true, onChanged: (Barangay? baragay) { selectedBarangay = baragay; }, - decoration: normalTextFieldStyle( - "Barangay*", - "Barangay"), + decoration: + normalTextFieldStyle( + "Barangay*", + "Barangay"), value: selectedBarangay, items: barangays == @@ -797,8 +714,10 @@ class _AddLearningAndDevelopmentScreenState Barangay>>((Barangay barangay) { return DropdownMenuItem( - value: barangay, - child: Text(barangay.description!)); + value: + barangay, + child: Text( + barangay.description!)); }).toList(), ), ), @@ -808,28 +727,25 @@ class _AddLearningAndDevelopmentScreenState //// COUNTRY DROPDOWN : SizedBox( height: 60, - child: - FormBuilderDropdown< - Country>( - initialValue: - null, - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), - items: state - .countries - .map< + child: FormBuilderDropdown< + Country>( + initialValue: null, + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + items: state.countries.map< DropdownMenuItem< - Country>>((Country - country) { + Country>>( + (Country country) { return DropdownMenuItem< Country>( - value: - country, + value: country, child: FittedBox( child: Text( - country.name!))); + country + .name!))); }).toList(), name: 'country', decoration: @@ -837,10 +753,8 @@ class _AddLearningAndDevelopmentScreenState "Country*", "Country"), onChanged: - (Country? - value) { - selectedCountry = - value; + (Country? value) { + selectedCountry = value; }, ), ), @@ -866,28 +780,24 @@ class _AddLearningAndDevelopmentScreenState itemHeight: 100, focusNode: conductedByFocusNode, - suggestions: state - .conductedBy - .map((Agency - agency) => + suggestions: state.conductedBy + .map((Agency agency) => SearchFieldListItem( - agency - .name!, - item: - agency, - child: - ListTile( - title: - Text( - agency - .name!, + agency.name!, + item: agency, + child: ListTile( + title: Text( + agency.name!, overflow: - TextOverflow.visible, + TextOverflow + .visible, ), - subtitle: Text(agency.privateEntity == + subtitle: Text(agency + .privateEntity == true ? "Private" - : agency.privateEntity == false + : agency.privateEntity == + false ? "Government" : ""), ))) @@ -900,33 +810,29 @@ class _AddLearningAndDevelopmentScreenState suffixIcon: GestureDetector( child: const Icon( - Icons - .arrow_drop_down, + Icons.arrow_drop_down, ), onTap: () => conductedByFocusNode .unfocus(), )), ////SELETECTED - onSuggestionTap: - (agency) { + onSuggestionTap: (agency) { setState(() { - if (agency.item - ?.id != + if (agency.item?.id != null) { selectedConductedByAgency = Agency( - name: - null, + name: null, id: agency - .item! - .id); + .item!.id); } else { - selectedConductedByAgency = Agency( - id: null, - name: agency - .item! - .name); + selectedConductedByAgency = + Agency( + id: null, + name: agency + .item! + .name); } if (agency.item! @@ -947,45 +853,37 @@ class _AddLearningAndDevelopmentScreenState }); }, validator: (agency) { - if (agency! - .isEmpty) { + if (agency!.isEmpty) { return "This field is required"; } return null; }, ////conducter empty widget - emptyWidget: - EmptyWidget( - controller: - addConductedByController, - onpressed: - () { - setState( - () { - Agency newAgency = Agency( - id: - null, - name: addConductedByController - .text - .toUpperCase(), - category: - null, - privateEntity: - null); - state - .conductedBy - .insert( - 0, - newAgency); + emptyWidget: EmptyWidget( + controller: + addConductedByController, + onpressed: () { + setState(() { + Agency newAgency = Agency( + id: null, + name: addConductedByController + .text + .toUpperCase(), + category: null, + privateEntity: + null); + state.conductedBy + .insert( + 0, newAgency); - addConductedByController - .text = ""; - Navigator.pop( - context); - }); - }, - title: - "Add Conducted By Agency")), + addConductedByController + .text = ""; + Navigator.pop( + context); + }); + }, + title: + "Add Conducted By Agency")), SizedBox( height: showConductedByAgencyCategory @@ -1002,37 +900,40 @@ class _AddLearningAndDevelopmentScreenState .up, focusNode: conductedByAgencyCategoryFocusNode, - itemHeight: - 70, + itemHeight: 70, suggestions: state .agencyCategory - .map((Category category) => SearchFieldListItem( - category - .name!, - item: - category, - child: - ListTile( - title: Text(category.name!), - subtitle: Text(category.industryClass!.name!), - ))) + .map((Category + category) => + SearchFieldListItem( + category + .name!, + item: + category, + child: + ListTile( + title: + Text(category.name!), + subtitle: Text(category + .industryClass! + .name!), + ))) .toList(), emptyWidget: Container( - height: - 100, + height: 100, decoration: box1(), child: const Center( - child: - Text("No result found ...")), + child: Text( + "No result found ...")), ), onSuggestionTap: (agencyCategory) { - setState( - () { + setState(() { selectedConductedByAgencyCategory = - agencyCategory.item; + agencyCategory + .item; selectedConductedByAgency = Agency( id: selectedConductedByAgency ?.id, @@ -1046,23 +947,21 @@ class _AddLearningAndDevelopmentScreenState .unfocus(); }); }, - searchInputDecoration: normalTextFieldStyle( - "Category *", - "") - .copyWith( - suffixIcon: - IconButton( - icon: const Icon( - Icons - .arrow_drop_down), - onPressed: - () { + searchInputDecoration: + normalTextFieldStyle( + "Category *", + "") + .copyWith( + suffixIcon: + IconButton( + icon: const Icon(Icons + .arrow_drop_down), + onPressed: () { conductedByAgencyCategoryFocusNode .unfocus(); }, )), - validator: - (value) { + validator: (value) { if (value! .isEmpty) { return "This field is required"; @@ -1080,45 +979,46 @@ class _AddLearningAndDevelopmentScreenState ? 12 : 0), SizedBox( - child: showConductedByAgencyPrivateRadio - ? FormBuilderSwitch( - initialValue: - conductedByCategoryIsPrivate, - title: Text( - conductedByCategoryIsPrivate - ? "YES" - : "NO"), - decoration: normalTextFieldStyle( - "Private Entity?", - 'Private Entity?'), + child: + showConductedByAgencyPrivateRadio + ? FormBuilderSwitch( + initialValue: + conductedByCategoryIsPrivate, + title: Text( + conductedByCategoryIsPrivate + ? "YES" + : "NO"), + decoration: normalTextFieldStyle( + "Private Entity?", + 'Private Entity?'), - ////onvhange private sector - onChanged: - (value) { - setState( - () { - conductedByCategoryIsPrivate = - value!; - selectedConductedByAgency = Agency( - category: selectedConductedByAgency - ?.category, - id: selectedConductedByAgency - ?.id, - name: selectedConductedByAgency! - .name, - privateEntity: - conductedByCategoryIsPrivate); - conductedByAgencyCategoryFocusNode - .unfocus(); - }); - }, - name: - 'sponsorAgencyPrivate', - validator: - FormBuilderValidators - .required(), - ) - : const SizedBox()), + ////onvhange private sector + onChanged: + (value) { + setState(() { + conductedByCategoryIsPrivate = + value!; + selectedConductedByAgency = Agency( + category: + selectedConductedByAgency + ?.category, + id: selectedConductedByAgency + ?.id, + name: selectedConductedByAgency! + .name, + privateEntity: + conductedByCategoryIsPrivate); + conductedByAgencyCategoryFocusNode + .unfocus(); + }); + }, + name: + 'sponsorAgencyPrivate', + validator: + FormBuilderValidators + .required(), + ) + : const SizedBox()), ]), )), ], @@ -1144,8 +1044,8 @@ class _AddLearningAndDevelopmentScreenState hasSponsor = value!; }); }, - decoration: normalTextFieldStyle( - "Has Sponsor?", ''), + decoration: + normalTextFieldStyle("Has Sponsor?", ''), name: 'sponsor', title: Text(hasSponsor ? "YES" : "NO"), ), @@ -1162,18 +1062,15 @@ class _AddLearningAndDevelopmentScreenState UpperCaseTextFormatter() ], itemHeight: 110, - focusNode: - sponsorByFocusNode, - suggestions: state - .sponsorAgencies + focusNode: sponsorByFocusNode, + suggestions: state.sponsorAgencies .map((Agency agency) => SearchFieldListItem( agency.name!, item: agency, child: ListTile( title: Text( - agency - .name!, + agency.name!, overflow: TextOverflow .visible, @@ -1190,8 +1087,7 @@ class _AddLearningAndDevelopmentScreenState .toList(), searchInputDecoration: normalTextFieldStyle( - " Sponsor Agency *", - "") + " Sponsor Agency *", "") .copyWith( suffixIcon: GestureDetector( @@ -1199,30 +1095,25 @@ class _AddLearningAndDevelopmentScreenState Icons.arrow_drop_down, ), onTap: () => - sponsorByFocusNode - .unfocus(), + sponsorByFocusNode.unfocus(), )), ////SELETECTED onSuggestionTap: (agency) { setState(() { - if (agency.item?.id != - null) { + if (agency.item?.id != null) { selectedSponsorAgency = Agency( name: null, - id: agency - .item! - .id); + id: agency.item!.id); } else { selectedSponsorAgency = Agency( id: null, name: agency - .item! - .name); + .item!.name); } - if (agency.item! - .privateEntity == + if (agency + .item!.privateEntity == null) { showSponsorCategoryAgency = true; @@ -1234,8 +1125,7 @@ class _AddLearningAndDevelopmentScreenState showSponsorAgencyPrivateRadio = false; } - sponsorByFocusNode - .unfocus(); + sponsorByFocusNode.unfocus(); }); }, validator: (agency) { @@ -1252,112 +1142,99 @@ class _AddLearningAndDevelopmentScreenState setState(() { Agency newAgency = Agency( id: null, - name: addSponsorAgencyController - .text - .toUpperCase(), + name: + addSponsorAgencyController + .text + .toUpperCase(), category: null, - privateEntity: - null); - state - .sponsorAgencies - .insert(0, - newAgency); + privateEntity: null); + state.sponsorAgencies + .insert(0, newAgency); addSponsorAgencyController .text = ""; - Navigator.pop( - context); + Navigator.pop(context); }); }, - title: - "Add Sponsor Agency")), + title: "Add Sponsor Agency")), SizedBox( - height: - showSponsorCategoryAgency - ? 12 - : 0, + height: showSponsorCategoryAgency + ? 12 + : 0, ), ////Sponsor Agency Category SizedBox( - child: - showSponsorCategoryAgency - ? SearchField( - suggestionDirection: - SuggestionDirection - .up, - focusNode: - sponsorAgencyCategoryFocusNode, - itemHeight: 70, - suggestions: state - .agencyCategory - .map((Category - category) => - SearchFieldListItem( - category - .name!, - item: - category, - child: - ListTile( - title: - Text(category.name!), - subtitle: - Text(category.industryClass!.name!), - ))) - .toList(), - emptyWidget: - Container( - height: 100, - decoration: - box1(), - child: const Center( - child: Text( - "No result found ...")), - ), - onSuggestionTap: - (agencyCategory) { - setState(() { - selectedSponsorAgencyCategory = - agencyCategory - .item; - selectedSponsorAgency = Agency( - id: selectedSponsorAgency - ?.id, - name: selectedSponsorAgency! + child: showSponsorCategoryAgency + ? SearchField( + suggestionDirection: + SuggestionDirection.up, + focusNode: + sponsorAgencyCategoryFocusNode, + itemHeight: 70, + suggestions: state + .agencyCategory + .map((Category + category) => + SearchFieldListItem( + category.name!, + item: category, + child: ListTile( + title: Text( + category + .name!), + subtitle: Text( + category + .industryClass! + .name!), + ))) + .toList(), + emptyWidget: Container( + height: 100, + decoration: box1(), + child: const Center( + child: Text( + "No result found ...")), + ), + onSuggestionTap: + (agencyCategory) { + setState(() { + selectedSponsorAgencyCategory = + agencyCategory.item; + selectedSponsorAgency = Agency( + id: selectedSponsorAgency + ?.id, + name: + selectedSponsorAgency! .name, - category: - selectedSponsorAgencyCategory, - privateEntity: - sponsorAgencyIsPrivate); - sponsorAgencyCategoryFocusNode - .unfocus(); - }); - }, - searchInputDecoration: - normalTextFieldStyle( - "Category *", - "") - .copyWith( - suffixIcon: - IconButton( - icon: const Icon( - Icons - .arrow_drop_down), - onPressed: () { - sponsorAgencyCategoryFocusNode - .unfocus(); - }, - )), - validator: - (value) { - if (value! - .isEmpty) { - return "This field is required"; - } - return null; - }, - ) - : const SizedBox(), + category: + selectedSponsorAgencyCategory, + privateEntity: + sponsorAgencyIsPrivate); + sponsorAgencyCategoryFocusNode + .unfocus(); + }); + }, + searchInputDecoration: + normalTextFieldStyle( + "Category *", "") + .copyWith( + suffixIcon: + IconButton( + icon: const Icon( + Icons.arrow_drop_down), + onPressed: () { + sponsorAgencyCategoryFocusNode + .unfocus(); + }, + )), + validator: (value) { + if (value!.isEmpty) { + return "This field is required"; + } + return null; + }, + ) + : const SizedBox(), ), ////Sponsor Agency Private Radio @@ -1367,47 +1244,48 @@ class _AddLearningAndDevelopmentScreenState ? 12 : 0), SizedBox( - child: - showSponsorAgencyPrivateRadio - ? FormBuilderSwitch( - initialValue: - sponsorAgencyIsPrivate, - title: Text( - sponsorAgencyIsPrivate - ? "YES" - : "NO"), - decoration: normalTextFieldStyle( + child: showSponsorAgencyPrivateRadio + ? FormBuilderSwitch( + initialValue: + sponsorAgencyIsPrivate, + title: Text( + sponsorAgencyIsPrivate + ? "YES" + : "NO"), + decoration: + normalTextFieldStyle( "Private Entity?", 'Private Entity?'), - ////onvhange private sector - onChanged: - (value) { - setState(() { - sponsorAgencyIsPrivate = - value!; - selectedSponsorAgency = Agency( - category: - selectedSponsorAgency - ?.category, - id: selectedSponsorAgency - ?.id, - name: selectedSponsorAgency! + ////onvhange private sector + onChanged: (value) { + setState(() { + sponsorAgencyIsPrivate = + value!; + selectedSponsorAgency = Agency( + category: + selectedSponsorAgency + ?.category, + id: selectedSponsorAgency + ?.id, + name: + selectedSponsorAgency! .name, - privateEntity: - selectedSponsorAgency?.privateEntity); - sponsorAgencyCategoryFocusNode - .unfocus(); - }); - }, + privateEntity: + selectedSponsorAgency + ?.privateEntity); + sponsorAgencyCategoryFocusNode + .unfocus(); + }); + }, - name: - 'sponsorAgencyPrivate', - validator: - FormBuilderValidators - .required(), - ) - : const SizedBox()), + name: + 'sponsorAgencyPrivate', + validator: + FormBuilderValidators + .required(), + ) + : const SizedBox()), ]), ) : const SizedBox(), @@ -1424,16 +1302,17 @@ class _AddLearningAndDevelopmentScreenState name: "total_hours_attended", keyboardType: TextInputType.number, decoration: normalTextFieldStyle( - "Total Hours Attended *", - "Total Hours Attended *"), + "Total Hours Attended *", "Total Hours Attended *"), ), - const SizedBox(height: 16,), - SizedBox( + const SizedBox( + height: 16, + ), + SizedBox( width: double.infinity, height: 60, child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), + style: + mainBtnStyle(primary, Colors.transparent, second), child: const Text(submit), onPressed: () { if (formKey.currentState!.saveAndValidate()) { @@ -1477,8 +1356,8 @@ class _AddLearningAndDevelopmentScreenState venue: venue, toDate: DateTime.parse(toDateController.text), - fromDate: DateTime.parse( - fromDateController.text), + fromDate: + DateTime.parse(fromDateController.text), totalHours: double.parse(formKey .currentState!.value['total_hours']), conductedBy: selectedConductedByAgency, diff --git a/lib/screens/profile/profile.dart b/lib/screens/profile/profile.dart index fe9d5a4..f6c9840 100644 --- a/lib/screens/profile/profile.dart +++ b/lib/screens/profile/profile.dart @@ -48,360 +48,378 @@ import '../unit2/homepage.dart/components/menu.dart'; import 'components/main_menu.dart'; import 'components/submenu.dart'; -class ProfileInfo extends StatelessWidget { +class ProfileInfo extends StatefulWidget { const ProfileInfo({super.key}); + @override + State createState() => _ProfileInfoState(); +} + +class _ProfileInfoState extends State { @override Widget build(BuildContext context) { int? profileId; String? token; Profile profile; - return Scaffold( - appBar: AppBar( - backgroundColor: primary, - centerTitle: true, - title: const Text('Profile'), - ), - body: ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocBuilder(builder: (context, state) { - if (state is UserLoggedIn) { - profileId = state.userData!.user!.login!.user!.profileId; - token = state.userData!.user!.login!.token!; - if (globalCurrentProfile == null) { - profile = state.userData!.employeeInfo!.profile!; - } else { - profile = globalCurrentProfile!; + return WillPopScope( + onWillPop: () async{ + setState(() { + + }); + return true; + }, + child: Scaffold( + appBar: AppBar( + backgroundColor: primary, + centerTitle: true, + title: const Text('Profile'), + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocBuilder(builder: (context, state) { + if (state is UserLoggedIn) { + profileId = state.userData!.user!.login!.user!.profileId; + token = state.userData!.user!.login!.token!; + if (globalCurrentProfile == null) { + + profile = state.userData!.employeeInfo!.profile!; + globalCurrentProfile = profile; + } else { + profile = globalCurrentProfile!; + } + return BlocConsumer( + listener: ( + context, + state, + ) { + if (state is ProfileLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is ProfileLoaded || + state is ProfileErrorState || + state is BasicInformationEditingState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + }, + builder: (context, state) { + if (state is ProfileLoaded) { + return Container( + padding: const EdgeInsets.symmetric( + vertical: 12, horizontal: 12), + child: ListView( + children: [ + Text( + "View and Update your Profile Information", + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyLarge, + ), + ExpandableGroup( + collapsedIcon: + const Icon(Icons.keyboard_arrow_down), + expandedIcon: const Icon(Icons.keyboard_arrow_up), + header: const ListTile( + leading: Icon( + Elusive.address_book, + color: primary, + ), + title: Text( + "Basic Information", + style: TextStyle(fontWeight: FontWeight.bold), + ), + ), + items: [ + subMenu(Icons.person, "Primary", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider.value( + value: ProfileBloc() + ..add(GetPrimaryBasicInfo( + primaryBasicInformation: profile)), + child: PrimaryInfo( + token: token!, + profileId: profileId!, + ), + ); + })); + }), + subMenu(Icons.home, "Addresses", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => AddressBloc() + ..add(GetAddress( + addresses: state.profileInformation + .basicInfo.addresses)), + child: const AddressScreen(), + ); + })); + }), + subMenu(Icons.contact_mail, "Identifications", + () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => IdentificationBloc() + ..add(GetIdentifications( + identificationInformation: state + .profileInformation + .basicInfo + .identifications)), + child: const IdentificationsScreen(), + ); + })); + }), + subMenu(Icons.contact_phone, "Contact Info", + () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => ContactBloc() + ..add(GetContacts( + contactInformations: state + .profileInformation + .basicInfo + .contactInformation)), + child: const ContactInformationScreen(), + ); + })); + }), + subMenu(Icons.flag, "Citizenships", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => CitizenshipBloc() + ..add(GetCitizenship( + citizenship: state + .profileInformation + .basicInfo + .citizenships)), + child: CitizenShipScreen( + citizenships: state + .profileInformation + .basicInfo + .citizenships, + profileId: profileId!, token: token!), + ); + })); + }), + ]), + const Divider(), + MainMenu( + icon: Elusive.group, + title: "Family", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => FamilyBloc() + ..add(GetFamilies( + profileId: profileId!, token: token!)), + child: const FamilyBackgroundScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: FontAwesome5.graduation_cap, + title: "Education", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => EducationBloc() + ..add(GetEducationalBackground( + profileId: profileId!, token: token!)), + child: const EducationScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Icons.stars, + title: "Eligibility", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => EligibilityBloc() + ..add(GetEligibilities( + profileId: profileId!, token: token!)), + child: const EligibiltyScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: FontAwesome5.shopping_bag, + title: "Work History", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => WorkHistoryBloc() + ..add(GetWorkHistories( + profileId: profileId!, token: token!)), + child: const WorkHistoryScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: FontAwesome5.walking, + title: "Voluntary Work & Civic Services", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => VoluntaryWorkBloc() + ..add(GetVoluntarWorks( + profileId: profileId!, token: token!)), + child: const VolunataryWorkScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.lightbulb, + title: "Learning & Development", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => LearningDevelopmentBloc() + ..add(GetLearningDevelopments( + profileId: profileId!, token: token!)), + child: const LearningAndDevelopmentScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Brandico.codepen, + title: "Personal References", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => ReferencesBloc() + ..add(GetReferences( + profileId: profileId!, token: token!)), + child: const ReferencesScreen(), + ); + })); + }, + ), + ExpandableGroup( + collapsedIcon: + const Icon(Icons.keyboard_arrow_down), + expandedIcon: const Icon(Icons.keyboard_arrow_up), + header: const ListTile( + leading: Icon( + Icons.info, + color: primary, + ), + title: Text( + "Other Information", + style: TextStyle(fontWeight: FontWeight.bold), + ), + ), + items: [ + subMenu( + Icons.fitness_center, "Skills & Hobbies", + () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => HoobiesBloc() + ..add(GetSkillsHobbies( + profileId: profileId!, + token: token!)), + child: const SkillHobbiesScreen(), + ); + })); + }), + subMenu(FontAwesome5.certificate, + "Organization Memberships", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + OrganizationMembershipBloc() + ..add(GetOrganizationMembership( + profileId: profileId!, + token: token!)), + child: const OrgMembershipsScreen(), + ); + })); + }), + subMenu(Entypo.doc_text, + "Non-Academic Recognitions", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + NonAcademicRecognitionBloc() + ..add(GetNonAcademicRecognition( + profileId: profileId!, + token: token!)), + child: + const NonAcademicRecognitionScreen(), + ); + })); + }), + ]), + ExpandableGroup( + collapsedIcon: + const Icon(Icons.keyboard_arrow_down), + expandedIcon: const Icon(Icons.keyboard_arrow_up), + header: const ListTile( + leading: Icon( + FontAwesome5.laptop_house, + color: primary, + ), + title: Text( + "Assets", + style: TextStyle(fontWeight: FontWeight.bold), + ), + ), + items: [ + subMenu(ModernPictograms.home, + "Real Property Tax", () {}), + ]), + ], + ), + ); + } + if (state is ProfileLoading) { + return const LoadingScreen(); + } + if (state is ProfileErrorState) { + return SomethingWentWrong( + message: state.mesage, + onpressed: () { + BlocProvider.of(context).add( + LoadProfile(token: token!, userID: profileId!)); + }); + } + + return Container(); + }, + ); } - print(profile.lastName); - return BlocConsumer( - listener: ( - context, - state, - ) { - if (state is ProfileLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is ProfileLoaded || - state is ProfileErrorState || - state is BasicInformationEditingState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - builder: (context, state) { - if (state is ProfileLoaded) { - return Container( - padding: const EdgeInsets.symmetric( - vertical: 12, horizontal: 12), - child: ListView( - children: [ - Text( - "View and Update your Profile Information", - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodyLarge, - ), - ExpandableGroup( - collapsedIcon: - const Icon(Icons.keyboard_arrow_down), - expandedIcon: const Icon(Icons.keyboard_arrow_up), - header: const ListTile( - leading: Icon( - Elusive.address_book, - color: primary, - ), - title: Text( - "Basic Information", - style: TextStyle(fontWeight: FontWeight.bold), - ), - ), - items: [ - subMenu(Icons.person, "Primary", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider.value( - value: ProfileBloc() - ..add(GetPrimaryBasicInfo( - primaryBasicInformation: profile)), - child: PrimaryInfo( - token: token!, - profileId: profileId!, - ), - ); - })); - }), - subMenu(Icons.home, "Addresses", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => AddressBloc() - ..add(GetAddress( - addresses: state.profileInformation - .basicInfo.addresses)), - child: const AddressScreen(), - ); - })); - }), - subMenu(Icons.contact_mail, "Identifications", - () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => IdentificationBloc() - ..add(GetIdentifications( - identificationInformation: state - .profileInformation - .basicInfo - .identifications)), - child: const IdentificationsScreen(), - ); - })); - }), - subMenu(Icons.contact_phone, "Contact Info", - () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => ContactBloc() - ..add(GetContacts( - contactInformations: state - .profileInformation - .basicInfo - .contactInformation)), - child: const ContactInformationScreen(), - ); - })); - }), - subMenu(Icons.flag, "Citizenships", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => CitizenshipBloc() - ..add(GetCitizenship( - citizenship: state - .profileInformation - .basicInfo - .citizenships)), - child: CitizenShipScreen( - profileId: profileId!, token: token!), - ); - })); - }), - ]), - const Divider(), - MainMenu( - icon: Elusive.group, - title: "Family", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => FamilyBloc() - ..add(GetFamilies( - profileId: profileId!, token: token!)), - child: const FamilyBackgroundScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: FontAwesome5.graduation_cap, - title: "Education", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => EducationBloc() - ..add(GetEducationalBackground( - profileId: profileId!, token: token!)), - child: const EducationScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: Icons.stars, - title: "Eligibility", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => EligibilityBloc() - ..add(GetEligibilities( - profileId: profileId!, token: token!)), - child: const EligibiltyScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: FontAwesome5.shopping_bag, - title: "Work History", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => WorkHistoryBloc() - ..add(GetWorkHistories( - profileId: profileId!, token: token!)), - child: const WorkHistoryScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: FontAwesome5.walking, - title: "Voluntary Work & Civic Services", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => VoluntaryWorkBloc() - ..add(GetVoluntarWorks( - profileId: profileId!, token: token!)), - child: const VolunataryWorkScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: Elusive.lightbulb, - title: "Learning & Development", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => LearningDevelopmentBloc() - ..add(GetLearningDevelopments( - profileId: profileId!, token: token!)), - child: const LearningAndDevelopmentScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: Brandico.codepen, - title: "Personal References", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => ReferencesBloc() - ..add(GetReferences( - profileId: profileId!, token: token!)), - child: const ReferencesScreen(), - ); - })); - }, - ), - ExpandableGroup( - collapsedIcon: - const Icon(Icons.keyboard_arrow_down), - expandedIcon: const Icon(Icons.keyboard_arrow_up), - header: const ListTile( - leading: Icon( - Icons.info, - color: primary, - ), - title: Text( - "Other Information", - style: TextStyle(fontWeight: FontWeight.bold), - ), - ), - items: [ - subMenu( - Icons.fitness_center, "Skills & Hobbies", - () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => HoobiesBloc() - ..add(GetSkillsHobbies( - profileId: profileId!, - token: token!)), - child: const SkillHobbiesScreen(), - ); - })); - }), - subMenu(FontAwesome5.certificate, - "Organization Memberships", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => - OrganizationMembershipBloc() - ..add(GetOrganizationMembership( - profileId: profileId!, - token: token!)), - child: const OrgMembershipsScreen(), - ); - })); - }), - subMenu(Entypo.doc_text, - "Non-Academic Recognitions", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => - NonAcademicRecognitionBloc() - ..add(GetNonAcademicRecognition( - profileId: profileId!, - token: token!)), - child: - const NonAcademicRecognitionScreen(), - ); - })); - }), - ]), - ExpandableGroup( - collapsedIcon: - const Icon(Icons.keyboard_arrow_down), - expandedIcon: const Icon(Icons.keyboard_arrow_up), - header: const ListTile( - leading: Icon( - FontAwesome5.laptop_house, - color: primary, - ), - title: Text( - "Assets", - style: TextStyle(fontWeight: FontWeight.bold), - ), - ), - items: [ - subMenu(ModernPictograms.home, - "Real Property Tax", () {}), - ]), - ], - ), - ); - } - if (state is ProfileLoading) { - return const LoadingScreen(); - } - if (state is ProfileErrorState) { - return SomethingWentWrong( - message: state.mesage, - onpressed: () { - BlocProvider.of(context).add( - LoadProfile(token: token!, userID: profileId!)); - }); - } - - return Container(); - }, - ); - } - return Container(); - }), - )); + return Container(); + }), + )), + ); } } diff --git a/lib/screens/superadmin/agency/agency_screen.dart b/lib/screens/superadmin/agency/agency_screen.dart index 57c88dc..d2eaf07 100644 --- a/lib/screens/superadmin/agency/agency_screen.dart +++ b/lib/screens/superadmin/agency/agency_screen.dart @@ -5,6 +5,7 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:fluttericon/font_awesome_icons.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:searchfield/searchfield.dart'; import 'package:unit2/bloc/rbac/rbac_operations/agency/agency_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; @@ -28,6 +29,7 @@ class RbacAgencyScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + List agencies = []; List agencyCategory = []; Category? selectedAgencyCategory; bool? isPrivate; @@ -38,7 +40,37 @@ class RbacAgencyScreen extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("Agencies"), - actions: [ + actions: context.watch().state is AgencyLoadingState || context.watch().state is AgencyErrorState || context.watch().state is AgencyAddesState?[]:[ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: primary), + builder: (Agency rbac) { + return Column( + children: [ + ListTile( + title: Text(rbac.name!), + ), + const Divider(), + ], + ); + }, + filter: (Agency rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Agency found :("), + ), + items: agencies, + searchLabel: "Search Agency", + suggestion: const Center( + child: Text("Search agency by name"), + )), + ); + }, + icon: const Icon(Icons.search)), AddLeading(onPressed: () { parent = context; showDialog( @@ -220,6 +252,7 @@ class RbacAgencyScreen extends StatelessWidget { builder: (context, state) { final parent = context; if (state is AgenciesLoaded) { + agencies = state.agencies; agencyCategory = state.agencyCategory; if (state.agencies.isNotEmpty) { return ListView.builder( @@ -262,7 +295,7 @@ class RbacAgencyScreen extends StatelessWidget { }); } else { return const EmptyData( - message: "No Object available. Please click + to add."); + message: "No Agency available. Please click + to add."); } }if (state is AgencyErrorState) { return SomethingWentWrong( diff --git a/lib/screens/superadmin/assign_area/assign_area_screen.dart b/lib/screens/superadmin/assign_area/assign_area_screen.dart index c9fcd6d..0293f21 100644 --- a/lib/screens/superadmin/assign_area/assign_area_screen.dart +++ b/lib/screens/superadmin/assign_area/assign_area_screen.dart @@ -82,7 +82,7 @@ class _RbacAssignedAreaScreenState extends State { areaType = null; return AlertDialog( - title: const Text("Add New Role"), + title: const Text("Add New Assigned area"), content: FormBuilder( key: formKey, child: StatefulBuilder(builder: (context, setState) { @@ -1005,7 +1005,7 @@ class _RbacAssignedAreaScreenState extends State { if (state is AssignedAreaDeletedState) { if (state.success) { successAlert(context, "Delete Successfull!", - "Role Module Deleted Successfully", () { + "Assign Area Deleted Successfully", () { Navigator.of(context).pop(); context .read() @@ -1013,7 +1013,7 @@ class _RbacAssignedAreaScreenState extends State { }); } else { errorAlert( - context, "Delete Failed", "Role Module Delete Failed", + context, "Delete Failed", "Assign Area Deletion Failed", () { Navigator.of(context).pop(); context diff --git a/lib/screens/superadmin/module/module_screen.dart b/lib/screens/superadmin/module/module_screen.dart index 98d287f..554f1e4 100644 --- a/lib/screens/superadmin/module/module_screen.dart +++ b/lib/screens/superadmin/module/module_screen.dart @@ -5,7 +5,9 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/module/module_bloc.dart'; +import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/widgets/Leadings/add_leading.dart'; import 'package:unit2/widgets/error_state.dart'; @@ -23,83 +25,283 @@ class RbacModuleScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + final bloc = BlocProvider.of(context); + List modules = []; return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: primary, title: const Text("Module Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Module"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Module name *", "Module name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add( - AddRbacModule( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + actions: + context.watch().state is ModuleLoadingState || + context.watch().state is ModuleErrorState || + context.watch().state is ModuleAddedState || + context.watch().state is ModuleDeletedState || + context.watch().state is ModuleAddedState || + context.watch().state is ModuleUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + const SizedBox( + width: 12, + ), + Expanded( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext + context) { + return AlertDialog( + title: const Text( + "Update Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize + .min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Module name *", + "Module name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.shorthand, + validator: FormBuilderValidators + .maxLength( + 50, + errorText: + "Max characters only 50"), + name: + "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + ////Update + bloc.add(UpdateRbacModule( + moduleId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text("Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + ////delete + Navigator.pop(context); + confirmAlert(context, () { + context + .read() + .add(DeleteRbacModule( + moduleId: + rbac.id!)); + }, "Delete?", + "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Module found :("), + ), + items: modules, + searchLabel: "Search Module", + suggestion: const Center( + child: Text("Search module by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Module name *", "Module name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: + FormBuilderValidators.maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value['object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacModule( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -162,7 +364,7 @@ class RbacModuleScreen extends StatelessWidget { context.read().add(GetModule()); }); } else { - errorAlert(context, "Delete Failed", "Module Delete Failed", + errorAlert(context, "Delete Failed", "Module Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetModule()); @@ -174,6 +376,7 @@ class RbacModuleScreen extends StatelessWidget { final parent = context; if (state is ModuleLoaded) { if (state.module.isNotEmpty) { + modules = state.module; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), @@ -190,18 +393,22 @@ class RbacModuleScreen extends StatelessWidget { children: [ Expanded( child: Row( - children: [ - CircleAvatar(child: Text('${index+1}'),), - const SizedBox(width: 12,), - Text(state.module[index].name!, - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500, - color: primary)), - ], - )), + children: [ + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Text(state.module[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ], + )), AppPopupMenu( offset: const Offset(-10, -10), elevation: 3, @@ -211,7 +418,8 @@ class RbacModuleScreen extends StatelessWidget { context: context, builder: (BuildContext context) { return AlertDialog( - title: const Text("Update Module"), + title: + const Text("Update Module"), content: FormBuilder( key: formKey, child: Column( @@ -355,7 +563,7 @@ class RbacModuleScreen extends StatelessWidget { }); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: "No Module available. Please click + to add."); } } if (state is ModuleErrorState) { diff --git a/lib/screens/superadmin/module_objects/module_objects_screen.dart b/lib/screens/superadmin/module_objects/module_objects_screen.dart index 30007d0..9cf11bb 100644 --- a/lib/screens/superadmin/module_objects/module_objects_screen.dart +++ b/lib/screens/superadmin/module_objects/module_objects_screen.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; @@ -33,106 +32,121 @@ class RbacModuleObjectsScreen extends StatelessWidget { List selectedValueItemObjects = []; final formKey = GlobalKey(); return Scaffold( - appBar: AppBar( centerTitle: true, elevation: 0, backgroundColor: primary, title: const Text("Module Object Screen"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemObjects = objects.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add New Module Object"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "module", - decoration: - normalTextFieldStyle("Module", "Module"), - items: modules.isEmpty - ? [] - : modules.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? object) { - selectedModule = object; - }, - ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemObjects = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Objects", - padding: const EdgeInsets.all(8), - options: valueItemObjects, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemObjects.isNotEmpty) { - int assignerId = id; - int moduleId = selectedModule!.id!; - List objectId = []; - for (var object in objects) { - selectedValueItemObjects - .forEach((element) { - if (element.label.toLowerCase() == - object.name?.toLowerCase()) { - objectId.add(object.id!); + actions: context.watch().state + is ModuleObjectLoadingState || + context.watch().state + is ModuleObjectsErrorState || + context.watch().state + is ModuleObjectAddedState || + context.watch().state + is ModuleObjectDeletedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemObjects = objects.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add New Module Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "module", + decoration: normalTextFieldStyle( + "Module", "Module"), + items: modules.isEmpty + ? [] + : modules.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? object) { + selectedModule = object; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemObjects = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Objects", + padding: const EdgeInsets.all(8), + options: valueItemObjects, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemObjects + .isNotEmpty) { + int assignerId = id; + int moduleId = selectedModule!.id!; + List objectId = []; + for (var object in objects) { + selectedValueItemObjects + .forEach((element) { + if (element.label + .toLowerCase() == + object.name + ?.toLowerCase()) { + objectId.add(object.id!); + } + }); + } + Navigator.of(context).pop(); + parent + .read() + .add(AddRbacModuleObjects( + assignerId: assignerId, + moduleId: moduleId, + objectsId: objectId)); } - }); - } - Navigator.of(context).pop(); - parent.read().add( - AddRbacModuleObjects( - assignerId: assignerId, - moduleId: moduleId, - objectsId: objectId)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -140,7 +154,6 @@ class RbacModuleObjectsScreen extends StatelessWidget { indicatorWidget: const SpinKitFadingCircle(color: Colors.white), child: BlocConsumer( listener: (context, state) { - if (state is ModuleObjectLoadingState) { final progress = ProgressHUD.of(context); progress!.showWithText("Please wait..."); @@ -157,13 +170,13 @@ class RbacModuleObjectsScreen extends StatelessWidget { if (state is ModuleObjectDeletedState) { if (state.success) { successAlert( - context, "Delete Successfull!", "Role Deleted Successfully", + context, "Delete Successfull!", "Module Object Deleted Successfully", () { Navigator.of(context).pop(); context.read().add(GetModuleObjects()); }); } else { - errorAlert(context, "Delete Failed", "Role Delete Failed", () { + errorAlert(context, "Delete Failed", "Module Object Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetModuleObjects()); }); @@ -270,20 +283,23 @@ class RbacModuleObjectsScreen extends StatelessWidget { style: Theme.of(context) .textTheme .titleMedium! - .copyWith(color: primary,fontWeight: FontWeight.bold), + .copyWith( + color: primary, fontWeight: FontWeight.bold), ), ); }, ); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: + "No Module Object available. Please click + to add."); } } if (state is ModuleObjectsErrorState) { return SomethingWentWrong( - message: state.message, onpressed: () { - parent.read().add(GetModuleObjects()); + message: state.message, + onpressed: () { + parent.read().add(GetModuleObjects()); }); } return Container(); diff --git a/lib/screens/superadmin/object/object_screen.dart b/lib/screens/superadmin/object/object_screen.dart index 7a4640c..a042645 100644 --- a/lib/screens/superadmin/object/object_screen.dart +++ b/lib/screens/superadmin/object/object_screen.dart @@ -5,7 +5,9 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; +import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/widgets/error_state.dart'; import '../../../theme-data.dart/box_shadow.dart'; @@ -24,83 +26,274 @@ class RbacObjectScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + final bloc = BlocProvider.of(context); + List objects = []; return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: primary, title: const Text("Objects Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Object"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Object name *", "Object name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add( - AddRbacObject( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + actions: + context.watch().state is ObjectLoadingState || + context.watch().state is ObjectAddedState || + context.watch().state is ObjectErrorState || + context.watch().state is ObjectDeletedState || + context.watch().state is ObjectUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext + context) { + return AlertDialog( + title: const Text( + "Update Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize + .min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Object name *", + "Object name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.shorthand, + validator: FormBuilderValidators + .maxLength( + 50, + errorText: + "Max characters only 50"), + name: + "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + bloc.add(UpdateRbacObject( + objectId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text("Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + bloc.add(DeleteRbacObject( + objectId: rbac.id!)); + }, "Delete?", + "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Role found :("), + ), + items: objects, + searchLabel: "Search Object", + suggestion: const Center( + child: Text("Search object by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Object name *", "Object name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: + FormBuilderValidators.maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value['object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacObject( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -162,7 +355,7 @@ class RbacObjectScreen extends StatelessWidget { context.read().add(GetObjects()); }); } else { - errorAlert(context, "Delete Failed", "Object Delete Failed", + errorAlert(context, "Delete Failed", "Object Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetObjects()); @@ -174,6 +367,7 @@ class RbacObjectScreen extends StatelessWidget { final parent = context; if (state is ObjectLoaded) { if (state.objects.isNotEmpty) { + objects = state.objects; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), diff --git a/lib/screens/superadmin/operation/operation_screen.dart b/lib/screens/superadmin/operation/operation_screen.dart index 6b4a6bb..f00a3c9 100644 --- a/lib/screens/superadmin/operation/operation_screen.dart +++ b/lib/screens/superadmin/operation/operation_screen.dart @@ -5,7 +5,9 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/operation/operation_bloc.dart'; +import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/widgets/error_state.dart'; import '../../../theme-data.dart/box_shadow.dart'; @@ -24,82 +26,276 @@ class RbacOperationScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + final bloc = BlocProvider.of(context); + List operations = []; return Scaffold( appBar: AppBar( backgroundColor: primary, title: const Text("Operations Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Operation"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Operation name *", "Operation name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), + centerTitle: true, + actions: context.watch().state + is OperationLoadingState || + context.watch().state is OperationErrorState || + context.watch().state is OperationAddedState || + context.watch().state is OperationDeletedState || + context.watch().state is OperationUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: + (BuildContext context) { + return AlertDialog( + title: const Text( + "Update Operation"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Operation name *", + "Operation name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: rbac + .shorthand, + validator: FormBuilderValidators + .maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: + ElevatedButton( + style: mainBtnStyle( + primary, + Colors + .transparent, + second), + onPressed: + () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + bloc.add(UpdateRbacOperation( + operationId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text( + "Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + context + .read() + .add(DeleteRbacOperation( + operationId: rbac.id!)); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Operation found :("), + ), + items: operations, + searchLabel: "Search Operation", + suggestion: const Center( + child: Text("Search operation by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Operation"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Operation name *", "Operation name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: FormBuilderValidators.maxLength(50, + errorText: "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey.currentState! + .value['object_name']; + String? slug = formKey + .currentState!.value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacOperation( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add( - AddRbacOperation( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -162,8 +358,8 @@ class RbacOperationScreen extends StatelessWidget { context.read().add(GetOperations()); }); } else { - errorAlert(context, "Delete Failed", "Operation Delete Failed", - () { + errorAlert( + context, "Delete Failed", "Operation Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetOperations()); }); @@ -174,6 +370,7 @@ class RbacOperationScreen extends StatelessWidget { final parent = context; if (state is OperationsLoaded) { if (state.operations.isNotEmpty) { + operations = state.operations; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), @@ -190,18 +387,22 @@ class RbacOperationScreen extends StatelessWidget { children: [ Expanded( child: Row( - children: [ - CircleAvatar(child: Text('${index+1}'),), - const SizedBox(width: 12,), - Text(state.operations[index].name!, - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500, - color: primary)), - ], - )), + children: [ + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Text(state.operations[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ], + )), AppPopupMenu( offset: const Offset(-10, -10), elevation: 3, @@ -211,7 +412,8 @@ class RbacOperationScreen extends StatelessWidget { context: context, builder: (BuildContext context) { return AlertDialog( - title: const Text("Update Operation"), + title: const Text( + "Update Operation"), content: FormBuilder( key: formKey, child: Column( @@ -355,7 +557,7 @@ class RbacOperationScreen extends StatelessWidget { }); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: "No Operation available. Please click + to add."); } } if (state is OperationErrorState) { diff --git a/lib/screens/superadmin/permission/permission_screen.dart b/lib/screens/superadmin/permission/permission_screen.dart index 7d3550a..90d25ea 100644 --- a/lib/screens/superadmin/permission/permission_screen.dart +++ b/lib/screens/superadmin/permission/permission_screen.dart @@ -7,7 +7,9 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/permission/permission_bloc.dart'; +import 'package:unit2/model/rbac/permission.dart'; import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; @@ -32,6 +34,8 @@ class RbacPermissionScreen extends StatelessWidget { List operations = []; List valueItemOperations = []; List selectedValueItemOperations = []; + List permissions = []; + final bloc = BlocProvider.of(context); final formKey = GlobalKey(); BuildContext? parent; return Scaffold( @@ -39,103 +43,189 @@ class RbacPermissionScreen extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("Permissions Screen"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemOperations = operations.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add Permission"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "object", - decoration: - normalTextFieldStyle("Permission", "Permission"), - items: objects.isEmpty - ? [] - : objects.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? object) { - selectedObject = object; - }, + actions: context.watch().state is PermissonLoadingState || + context.watch().state is PermissionErrorState || + context.watch().state is PermissionDeletedState || + context.watch().state is PermissionAddedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBACPermission rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Text( + "${rbac.object?.name} - ${rbac.operation?.name}", + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + bloc.add(DeleteRbacPermission( + permissionId: rbac.id!)); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBACPermission rbac) { + return [ + rbac.object!.name! + rbac.operation!.name! + ]; + }, + failure: const Center( + child: Text("No permission found :("), ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemOperations = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Operations", - padding: const EdgeInsets.all(8), - options: valueItemOperations, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemOperations - .isNotEmpty) { - int assignerId = id; - int objectId = selectedObject!.id!; + items: permissions, + searchLabel: "Search Permission", + suggestion: const Center( + child: Text("Search permission by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemOperations = operations.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Permission"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "object", + decoration: normalTextFieldStyle( + "Permission", "Permission"), + items: objects.isEmpty + ? [] + : objects.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? object) { + selectedObject = object; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemOperations = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Operations", + padding: const EdgeInsets.all(8), + options: valueItemOperations, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemOperations + .isNotEmpty) { + int assignerId = id; + int objectId = selectedObject!.id!; - List opIds = []; - for (var operation in operations) { - selectedValueItemOperations - .forEach((element) { - if (element.label.toLowerCase() == - operation.name?.toLowerCase()) { - opIds.add(operation.id!); + List opIds = []; + for (var operation in operations) { + selectedValueItemOperations + .forEach((element) { + if (element.label + .toLowerCase() == + operation.name + ?.toLowerCase()) { + opIds.add(operation.id!); + } + }); + } + + Navigator.pop(context); + parent!.read().add( + AddRbacPermission( + assignerId: assignerId, + objectId: objectId, + operationIds: opIds)); } - }); - } - - Navigator.pop(context); - parent!.read().add( - AddRbacPermission( - assignerId: assignerId, - objectId: objectId, - operationIds: opIds)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -179,8 +269,8 @@ class RbacPermissionScreen extends StatelessWidget { context.read().add(GetPermissions()); }); } else { - errorAlert(context, "Delete Failed", "Permission Delete Failed", - () { + errorAlert( + context, "Delete Failed", "Permission Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetPermissions()); }); @@ -193,6 +283,7 @@ class RbacPermissionScreen extends StatelessWidget { objects = state.objects; operations = state.operations; if (state.permissions.isNotEmpty) { + permissions = state.permissions; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), @@ -209,41 +300,39 @@ class RbacPermissionScreen extends StatelessWidget { children: [ Expanded( child: Row( - children: [ - CircleAvatar( + children: [ + CircleAvatar( child: Text('${index + 1}'), ), const SizedBox( width: 12, ), - Flexible( - child: Text( - "${state.permissions[index].object?.name} - ${state.permissions[index].operation?.name}", - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500, - color: primary)), - ), - ], - )), + Flexible( + child: Text( + "${state.permissions[index].object?.name} - ${state.permissions[index].operation?.name}", + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ), + ], + )), AppPopupMenu( offset: const Offset(-10, -10), elevation: 3, onSelected: (value) { - if (value == 1) { - + if (value == 1) { confirmAlert(context, () { - context.read().add( - DeleteRbacPermission( - permissionId: state.permissions[index].id!)); + context.read().add( + DeleteRbacPermission( + permissionId: state + .permissions[index].id!)); }, "Delete?", "Confirm Delete?"); - } }, menuItems: [ - popMenuItem( text: "Remove", value: 1, @@ -271,8 +360,9 @@ class RbacPermissionScreen extends StatelessWidget { } if (state is PermissionErrorState) { return SomethingWentWrong( - message: state.message, onpressed: () { - parent!.read().add(GetPermissions()); + message: state.message, + onpressed: () { + parent!.read().add(GetPermissions()); }); } return Container(); diff --git a/lib/screens/superadmin/permission_assignment/permission_assignment_screen.dart b/lib/screens/superadmin/permission_assignment/permission_assignment_screen.dart index 1eb6467..07aa98d 100644 --- a/lib/screens/superadmin/permission_assignment/permission_assignment_screen.dart +++ b/lib/screens/superadmin/permission_assignment/permission_assignment_screen.dart @@ -5,9 +5,7 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:group_list_view/group_list_view.dart'; -import 'package:multi_dropdown/models/value_item.dart'; import 'package:multi_dropdown/multiselect_dropdown.dart'; -import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart'; import 'package:unit2/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart'; import 'package:unit2/model/rbac/permission.dart'; import 'package:unit2/model/rbac/rbac.dart'; @@ -15,7 +13,6 @@ import 'package:unit2/theme-data.dart/btn-style.dart'; import 'package:unit2/theme-data.dart/colors.dart'; import 'package:unit2/theme-data.dart/form-style.dart'; import 'package:unit2/utils/alerts.dart'; -import 'package:unit2/utils/global_context.dart'; import 'package:unit2/widgets/Leadings/add_leading.dart'; import 'package:unit2/widgets/empty_data.dart'; import 'package:unit2/widgets/error_state.dart'; @@ -40,91 +37,111 @@ class RbacPermissionAssignmentScreen extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("Permission Assignment"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: context, - builder: (BuildContext context) { - valueItemPermission = permissions.map((e) { - return ValueItem( - label: "${e.object!.name} - ${e.operation!.name}", - value: e.id.toString()); - }).toList(); - return AlertDialog( - title: const Text("Add Permission"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "role", - decoration: normalTextFieldStyle("Role", "Role"), - items: roles.isEmpty - ? [] - : roles.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? role) { - selectedRole = role; - }, - ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: (List selectedOptions) { - selectedValueItemPermission = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Operations", - padding: const EdgeInsets.all(8), - options: valueItemPermission, - selectionType: SelectionType.multi, - chipConfig: const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState!.saveAndValidate() && - selectedValueItemPermission.isNotEmpty) { - int assignerId = id; - int roleId = selectedRole!.id!; - List opIds = - selectedValueItemPermission.map((e) { - return int.parse(e.value!); - }).toList(); - Navigator.pop(context); - parent.read().add( - AddPersmissionAssignment( - assignerId: assignerId, - opsId: opIds, - roleId: roleId)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], + actions: context.watch().state + is PermissionAssignmentLoadingScreen || + context.watch().state + is PermissionAssignmentErrorState || + context.watch().state + is PermissionAssignmentAddedState || + context.watch().state + is PermissionAssignmentDeletedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: context, + builder: (BuildContext context) { + valueItemPermission = permissions.map((e) { + return ValueItem( + label: "${e.object!.name} - ${e.operation!.name}", + value: e.id.toString()); + }).toList(); + return AlertDialog( + title: const Text("Add Permission"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: + normalTextFieldStyle("Role", "Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemPermission = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Operations", + padding: const EdgeInsets.all(8), + options: valueItemPermission, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemPermission + .isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List opIds = + selectedValueItemPermission + .map((e) { + return int.parse(e.value!); + }).toList(); + Navigator.pop(context); + parent + .read< + PermissionAssignmentBloc>() + .add(AddPersmissionAssignment( + assignerId: assignerId, + opsId: opIds, + roleId: roleId)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -183,7 +200,6 @@ class RbacPermissionAssignmentScreen extends StatelessWidget { } }, builder: (context, state) { - if (state is PermissionAssignmentLoadedState) { if (state.permissionAssignments.isNotEmpty) { permissions = state.permissions; diff --git a/lib/screens/superadmin/role/role_screen.dart b/lib/screens/superadmin/role/role_screen.dart index 03e055c..f6553e9 100644 --- a/lib/screens/superadmin/role/role_screen.dart +++ b/lib/screens/superadmin/role/role_screen.dart @@ -25,6 +25,7 @@ class RbacRoleScreen extends StatelessWidget { @override Widget build(BuildContext context) { + final bloc = BlocProvider.of(context); final formKey = GlobalKey(); List roles = []; return Scaffold( @@ -32,102 +33,274 @@ class RbacRoleScreen extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("Role Screen"), - actions: [ - IconButton( - onPressed: () { - showSearch( - context: context, - delegate: SearchPage( - barTheme: ThemeData(cardColor: primary), - builder: (RBAC rbac) { - return ListTile( - title: Text(rbac.name!), - ); - }, - filter: (RBAC rbac) { - return [rbac.name]; - }, - failure: const Center( - child: Text("No Role found :("), - ), - items: roles, - searchLabel: "Search Role", - suggestion: const Center( - child: Text("Search role by name"), - )), - ); - }, - icon: const Icon(Icons.search)), - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Role"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Role name *", "Role name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add(AddRbacRole( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + actions: + context.watch().state is RoleLoadingState || + context.watch().state is RoleErrorState || + context.watch().state is RoleDeletedState? || + context.watch().state is RoleAddedState? || + context.watch().state is RoleUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + Flexible( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight + .w500, + color: primary)), + ), + ], + )), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext + context) { + return AlertDialog( + title: const Text( + "Update Role"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize + .min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Role name *", + "Role name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.shorthand, + validator: FormBuilderValidators + .maxLength( + 50, + errorText: + "Max characters only 50"), + name: + "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + bloc.add(UpdateRbacRole( + roleId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text("Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + bloc + .add(DeleteRbacRole( + roleId: rbac.id!)); + }, "Delete?", + "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Role found :("), + ), + items: roles, + searchLabel: "Search Role", + suggestion: const Center( + child: Text("Search role by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Role"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Role name *", "Role name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: + FormBuilderValidators.maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value['object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacRole( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), diff --git a/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart b/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart index b09f086..39004ea 100644 --- a/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart +++ b/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart @@ -36,7 +36,7 @@ class RbacRoleAssignment extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("User Roles Screens"), - actions: [ + actions: context.watch().state is RoleAssignmentLoadingState || context.watch().state is RoleAssignmentErrorState || context.watch().state is UserNotExistError || context.watch().state is RoleAddedState? []: [ AddLeading(onPressed: () { BuildContext parent = context; showDialog( @@ -131,13 +131,13 @@ class RbacRoleAssignment extends StatelessWidget { if (state is AssignedRoleDeletedState) { if (state.success) { successAlert(context, "Delete Successfull!", - "Role Module Deleted Successfully", () { + "Role Deleted Successfully", () { Navigator.of(context).pop(); context.read().add(LoadAssignedRole()); }); } else { errorAlert( - context, "Delete Failed", "Role Module Delete Failed", () { + context, "Delete Failed", "Role Deletion Failed", () { Navigator.of(context).pop(); context.read().add(LoadAssignedRole()); }); diff --git a/lib/screens/superadmin/role_extend/role_extend_screen.dart b/lib/screens/superadmin/role_extend/role_extend_screen.dart index e4d3bd5..3c5787a 100644 --- a/lib/screens/superadmin/role_extend/role_extend_screen.dart +++ b/lib/screens/superadmin/role_extend/role_extend_screen.dart @@ -36,7 +36,7 @@ class RbacRoleExtendScreen extends StatelessWidget { elevation: 0, backgroundColor: primary, title: const Text("Role Extend"), - actions: [ + actions: context.watch().state is RoleExtendLoadingState || context.watch().state is RoleExtendErrorState || context.watch().state is RoleExtendAddedState || context.watch().state is RoleExtendDeletedState? []:[ AddLeading(onPressed: () { showDialog( context: NavigationService.navigatorKey.currentState!.context, diff --git a/lib/screens/superadmin/role_module/role_module_scree.dart b/lib/screens/superadmin/role_module/role_module_scree.dart index a71ae81..8a97b7f 100644 --- a/lib/screens/superadmin/role_module/role_module_scree.dart +++ b/lib/screens/superadmin/role_module/role_module_scree.dart @@ -34,100 +34,114 @@ class RbacRoleModuleScreen extends StatelessWidget { return Scaffold( appBar: AppBar( backgroundColor: primary, - title: const Text("Role Modules Screen"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemModules = modules.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add Role Module"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "role", - decoration: normalTextFieldStyle("Role", "Role"), - items: roles.isEmpty - ? [] - : roles.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? role) { - selectedRole = role; - }, - ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemModules = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Modules", - padding: const EdgeInsets.all(8), - options: valueItemModules, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemModules.isNotEmpty) { - int assignerId = id; - int roleId = selectedRole!.id!; - List modulesId = []; - for (var module in modules) { - selectedValueItemModules - .forEach((element) { - if (element.label.toLowerCase() == - module.name?.toLowerCase()) { - modulesId.add(module.id!); + title: const Text("Role Module Screen" ), + centerTitle: true, + actions: context.watch().state + is RoleModuleLoadingState || + context.watch().state is RoleModuleErrorState || + context.watch().state is RoleModuleAddedState || + context.watch().state is RoleModuleDeletedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemModules = modules.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Role Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: + normalTextFieldStyle("Role", "Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemModules = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Modules", + padding: const EdgeInsets.all(8), + options: valueItemModules, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemModules + .isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List modulesId = []; + for (var module in modules) { + selectedValueItemModules + .forEach((element) { + if (element.label + .toLowerCase() == + module.name + ?.toLowerCase()) { + modulesId.add(module.id!); + } + }); + } + Navigator.of(context).pop(); + parent.read().add( + AddRoleModule( + assignerId: assignerId, + roleId: roleId, + moduleIds: modulesId)); } - }); - } - Navigator.of(context).pop(); - parent.read().add( - AddRoleModule( - assignerId: assignerId, - roleId: roleId, - moduleIds: modulesId)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -156,7 +170,7 @@ class RbacRoleModuleScreen extends StatelessWidget { }); } else { errorAlert( - context, "Delete Failed", "Role Module Delete Failed", () { + context, "Delete Failed", "Role Module Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetRoleModules()); }); @@ -258,20 +272,22 @@ class RbacRoleModuleScreen extends StatelessWidget { style: Theme.of(context) .textTheme .titleMedium! - .copyWith(color: primary,fontWeight: FontWeight.bold), + .copyWith( + color: primary, fontWeight: FontWeight.bold), ), ); }, ); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: "No Role Module available. Please click + to add."); } } if (state is RoleModuleErrorState) { return SomethingWentWrong( - message: state.message, onpressed: () { - context.read().add(GetRoleModules()); + message: state.message, + onpressed: () { + context.read().add(GetRoleModules()); }); } return Container(); diff --git a/lib/screens/superadmin/roles_under/assignable_roles.dart b/lib/screens/superadmin/roles_under/assignable_roles.dart new file mode 100644 index 0000000..5698cc7 --- /dev/null +++ b/lib/screens/superadmin/roles_under/assignable_roles.dart @@ -0,0 +1,307 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:group_list_view/group_list_view.dart'; +import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../model/rbac/rbac.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global_context.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacRoleUnderScreen extends StatelessWidget { + final int id; + const RbacRoleUnderScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final parent = context; + Map> rolesUnder = {}; + List roles = []; + RBAC? selectedRole; + List valueItemRoles = []; + List selectedValueItemRoles = []; + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: const Text("Assignable Roles"), + actions: context.watch().state + is RoleUnderLoadingState? || + context.watch().state is RoleUnderErrorState || + context.watch().state + is RoleUnderDeletedState || + context.watch().state is RoleUnderAddedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemRoles = roles.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Role Under"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: normalTextFieldStyle( + "Main Role", "Main Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemRoles = selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Roles Under", + padding: const EdgeInsets.all(8), + options: valueItemRoles, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemRoles + .isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List rolesId = []; + for (var role in roles) { + selectedValueItemRoles + .forEach((element) { + if (element.label + .toLowerCase() == + role.name?.toLowerCase()) { + rolesId.add(role.id!); + } + }); + } + Navigator.of(context).pop(); + parent.read().add( + AddRoleUnder( + roleId: roleId, + roleUnderIds: rolesId)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is RoleUnderLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is RoleUnderLoadedState || + state is RoleUnderErrorState || + state is RoleUnderDeletedState || + state is RoleUnderAddedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + + ////Deleted State + if (state is RoleUnderDeletedState) { + if (state.success) { + successAlert( + context, "Delete Successfull!", "Role Deleted Successfully", + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } else { + errorAlert( + context, "Delete Failed", "Role Module Delete Failed", () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } + } + ////Added State + if (state is RoleUnderAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } + } + }, + builder: (context, state) { + if (state is RoleUnderLoadedState) { + rolesUnder = {}; + roles = state.roles; + + if (state.rolesUnder.isNotEmpty) { + for (var roleUnder in state.rolesUnder) { + if (!rolesUnder.keys + .contains(roleUnder.roleUnderMain.name!.toLowerCase())) { + rolesUnder.addAll( + {roleUnder.roleUnderMain.name!.toLowerCase(): []}); + rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! + .add(Content( + id: roleUnder.id, + name: roleUnder.roleUnderChild.name!)); + } else { + rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! + .add(Content( + id: roleUnder.id, + name: roleUnder.roleUnderChild.name!)); + } + } + } + + if (state.rolesUnder.isNotEmpty) { + return GroupListView( + sectionsCount: rolesUnder.keys.toList().length, + countOfItemInSection: (int section) { + return rolesUnder.values.toList()[section].length; + }, + itemBuilder: (BuildContext context, IndexPath index) { + return ListTile( + trailing: IconButton( + color: Colors.grey.shade500, + icon: const Icon(Icons.delete), + onPressed: () { + confirmAlert(context,(){ + context.read().add(DeleteRoleUnder(roleUnderId:rolesUnder.values .toList()[index.section][index.index].id)); + }, "Delete", "Delete Role?"); + }, + ), + title: Row( + children: [ + CircleAvatar( + child: Text("${index.index + 1}", + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: Colors.white))), + const SizedBox( + width: 20, + ), + Expanded( + child: Text( + rolesUnder.values + .toList()[index.section][index.index] + .name + .toUpperCase(), + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ), + ], + ), + ); + }, + separatorBuilder: (context, index) { + return const Divider(); + }, + groupHeaderBuilder: (BuildContext context, int section) { + return ListTile( + tileColor: Colors.white, + dense: true, + title: Text( + rolesUnder.keys.toList()[section].toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + color: primary, fontWeight: FontWeight.bold), + ), + ); + }, + ); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is RoleUnderErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context.read().add(GetRolesUnder()); + }); + } + return Container(); + }, + ), + ), + ); + } +} + +class Content { + final int id; + final String name; + const Content({required this.id, required this.name}); +} diff --git a/lib/screens/superadmin/roles_under/roles_under_screen.dart b/lib/screens/superadmin/roles_under/roles_under_screen.dart deleted file mode 100644 index 6f82a78..0000000 --- a/lib/screens/superadmin/roles_under/roles_under_screen.dart +++ /dev/null @@ -1,296 +0,0 @@ - -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package:form_builder_validators/form_builder_validators.dart'; -import 'package:group_list_view/group_list_view.dart'; -import 'package:multi_dropdown/multiselect_dropdown.dart'; -import 'package:unit2/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart'; -import 'package:unit2/widgets/Leadings/add_leading.dart'; -import 'package:unit2/widgets/error_state.dart'; -import '../../../model/rbac/rbac.dart'; -import '../../../theme-data.dart/btn-style.dart'; -import '../../../theme-data.dart/colors.dart'; -import '../../../theme-data.dart/form-style.dart'; -import '../../../utils/alerts.dart'; -import '../../../utils/global_context.dart'; -import '../../../widgets/empty_data.dart'; - -class RbacRoleUnderScreen extends StatelessWidget { - final int id; - const RbacRoleUnderScreen({super.key, required this.id}); - - @override - Widget build(BuildContext context) { - final parent = context; - Map> rolesUnder = {}; - List roles = []; - RBAC? selectedRole; - List valueItemRoles = []; - List selectedValueItemRoles = []; - final formKey = GlobalKey(); - return Scaffold( - appBar: AppBar( - centerTitle: true, - backgroundColor: primary, - title: const Text("Assignable Roles"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemRoles = roles.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add Role Under"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "role", - decoration: normalTextFieldStyle( - "Main Role", "Main Role"), - items: roles.isEmpty - ? [] - : roles.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? role) { - selectedRole = role; - }, - ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemRoles = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Roles Under", - padding: const EdgeInsets.all(8), - options: valueItemRoles, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemRoles.isNotEmpty) { - int assignerId = id; - int roleId = selectedRole!.id!; - List rolesId = []; - for (var role in roles) { - selectedValueItemRoles - .forEach((element) { - if (element.label.toLowerCase() == - role.name?.toLowerCase()) { - rolesId.add(role.id!); - } - }); - } - Navigator.of(context).pop(); - parent.read().add( - AddRoleUnder( - roleId: roleId, - roleUnderIds: rolesId)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], - ), - body: ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocConsumer( - listener: (context, state) { - if (state is RoleUnderLoadingState) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is RoleUnderLoadedState || - state is RoleUnderErrorState || - state is RoleUnderDeletedState || - state is RoleUnderAddedState) { - final progress = ProgressHUD.of(context); - progress!.dismiss(); - } - - ////Deleted State - if (state is RoleUnderDeletedState) { - if (state.success) { - successAlert(context, "Delete Successfull!", - "Role Deleted Successfully", () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } else { - errorAlert( - context, "Delete Failed", "Role Module Delete Failed", () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } - } - ////Added State - if (state is RoleUnderAddedState) { - if (state.response['success']) { - successAlert( - context, "Adding Successfull!", state.response['message'], - () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } else { - errorAlert(context, "Adding Failed", state.response['message'], - () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } - } - }, - builder: (context, state) { - if (state is RoleUnderLoadedState) { - rolesUnder = {}; - roles = state.roles; - - if (state.rolesUnder.isNotEmpty) { - for (var roleUnder in state.rolesUnder) { - if (!rolesUnder.keys - .contains(roleUnder.roleUnderMain.name!.toLowerCase())) { - rolesUnder.addAll( - {roleUnder.roleUnderMain.name!.toLowerCase(): []}); - rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! - .add(Content( - id: roleUnder.id, - name: roleUnder.roleUnderChild.name!)); - } else { - rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! - .add(Content( - id: roleUnder.id, - name: roleUnder.roleUnderChild.name!)); - } - } - } - - if (state.rolesUnder.isNotEmpty) { - return GroupListView( - sectionsCount: rolesUnder.keys.toList().length, - countOfItemInSection: (int section) { - return rolesUnder.values.toList()[section].length; - }, - itemBuilder: (BuildContext context, IndexPath index) { - return ListTile( - trailing: IconButton( - color: Colors.grey.shade500, - icon: const Icon(Icons.delete), - onPressed: () { - context.read().add(DeleteRoleUnder( - roleUnderId: rolesUnder.values - .toList()[index.section][index.index] - .id)); - }, - ), - title: Row( - children: [ - CircleAvatar( - child: Text("${index.index + 1}", - style: Theme.of(context) - .textTheme - .labelLarge! - .copyWith(color: Colors.white))), - const SizedBox( - width: 20, - ), - Expanded( - child: Text( - rolesUnder.values - .toList()[index.section][index.index] - .name - .toUpperCase(), - style: Theme.of(context) - .textTheme - .labelLarge! - .copyWith( - fontWeight: FontWeight.w500, - color: primary) - ), - ), - ], - ), - ); - }, - separatorBuilder: (context, index) { - return const Divider(); - }, - groupHeaderBuilder: (BuildContext context, int section) { - return ListTile( -tileColor: Colors.white, - dense: true, - title: Text( - rolesUnder.keys.toList()[section].toUpperCase(), - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith(color: primary,fontWeight: FontWeight.bold), - ), - ); - }, - ); - } else { - return const EmptyData( - message: "No Role available. Please click + to add."); - } - } - if (state is RoleUnderErrorState) { - return SomethingWentWrong( - message: state.message, onpressed: () { - context.read().add(GetRolesUnder()); - }); - } - return Container(); - }, - ), - ), - ); - } -} - -class Content { - final int id; - final String name; - const Content({required this.id, required this.name}); -} diff --git a/lib/screens/superadmin/stations/stations_screen.dart b/lib/screens/superadmin/stations/stations_screen.dart index a26e34b..533e55a 100644 --- a/lib/screens/superadmin/stations/stations_screen.dart +++ b/lib/screens/superadmin/stations/stations_screen.dart @@ -5,7 +5,6 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:searchfield/searchfield.dart'; -import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/station/station_bloc.dart'; import 'package:unit2/model/rbac/rbac_station.dart'; import 'package:unit2/model/utils/agency.dart'; @@ -62,436 +61,469 @@ class _RbacStationScreenState extends State { centerTitle: true, backgroundColor: primary, title: const Text("Station Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - mainParentStations = []; - mainParent = stations.isEmpty ? true : false; - for (RbacStation station in stations) { - if (station.hierarchyOrderNo == 1) { - mainParentStations.add(station); - } - } + actions: context.watch().state is StationLoadingState || + context.watch().state is StationErrorState || + context.watch().state is RbacStationAddedState || + context.watch().state is FilterStationState + ? [] + : [ + AddLeading(onPressed: () { + BuildContext parent = context; + mainParentStations = []; + mainParent = stations.isEmpty ? true : false; + for (RbacStation station in stations) { + if (station.hierarchyOrderNo == 1) { + mainParentStations.add(station); + } + } - /////Add new tation - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Station"), - content: SingleChildScrollView( - child: FormBuilder( - key: formKey, - child: StatefulBuilder(builder: (context, setState) { - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - ////is main parent - FormBuilderSwitch( - initialValue: mainParent, - activeColor: second, - onChanged: (value) { - setState(() { - mainParent = !mainParent; - }); - }, - decoration: normalTextFieldStyle( - "is Main Parent?", 'is Main Parent?'), - name: 'main-parent', - title: Text(mainParent ? "YES" : "NO"), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - SizedBox( - height: mainParent ? 0 : 8, - ), - //// selected main parent - SizedBox( - child: mainParent == true - ? const SizedBox.shrink() - : FormBuilderDropdown( - decoration: normalTextFieldStyle( - "Main Parent Station", - "Main Parent Station"), - name: "parent-stations", - items: mainParentStations.isEmpty - ? [] - : mainParentStations.map((e) { - return DropdownMenuItem( - value: e, - child: Text(e.stationName!), - ); - }).toList(), - onChanged: (RbacStation? e) { - setState(() { - selectedMainParentStation = e; - parentStations = []; - for (RbacStation station - in stations) { - if (station.mainParentStation == - selectedMainParentStation! - .id) { - parentStations.add(station); - } - } - parentStations.add( - selectedMainParentStation!); - }); - }, - validator: - FormBuilderValidators.required( - errorText: - "This field is required"), - ), - ), - SizedBox( - height: mainParent ? 0 : 8, - ), - ////parent station - SizedBox( - child: mainParent == true - ? const SizedBox.shrink() - : FormBuilderDropdown( - decoration: normalTextFieldStyle( - "Parent Station", "Parent Station"), - name: "parent-stations", - onChanged: (RbacStation? e) { - setState(() { - selectedParentStation = e; - }); - }, - items: parentStations.isEmpty - ? [] - : parentStations.map((e) { - return DropdownMenuItem( - value: e, - child: Text(e.stationName!), - ); - }).toList(), - validator: - FormBuilderValidators.required( - errorText: - "This field is required"), - ), - ), - const SizedBox( - height: 12, - ), - ////Station Type - SearchField( - itemHeight: 50, - suggestionsDecoration: searchFieldDecoration(), - - suggestions: stationTypes - .map((StationType stationType) => - SearchFieldListItem( - stationType.typeName!, - item: stationType, - child: Padding( - padding: - const EdgeInsets.symmetric( - horizontal: 10), - child: ListTile( - title: Text( - stationType.typeName!, - overflow: TextOverflow.visible, - )), - ))) - .toList(), - validator: (station) { - if (station!.isEmpty) { - return "This field is required"; - } - return null; - }, - focusNode: stationTypeFocusNode, - searchInputDecoration: - normalTextFieldStyle("Station Type *", "") - .copyWith( - suffixIcon: GestureDetector( - onTap: () => stationTypeFocusNode.unfocus(), - child: const Icon(Icons.arrow_drop_down), - )), - onSuggestionTap: (position) { - setState(() { - selectedStationType = position.item!; - stationTypeFocusNode.unfocus(); - }); - }, - emptyWidget: EmptyWidget( - title: "Add StationType", - controller: addStationTypeController, - onpressed: () { - setState(() { - StationType stationType = StationType( - id: null, - typeName: - addStationTypeController.text, - color: null, - order: null, - isActive: null, - group: null); - stationTypes.add(stationType); - Navigator.pop(context); - }); - }), - ), - const SizedBox( - height: 12, - ), - ////Position title - FormBuilderDropdown( - decoration: normalTextFieldStyle( - "Head Position", "Head Position"), - name: "head-position", - items: positions.map((e) { - return DropdownMenuItem( - value: e, - child: Text(e.title!), - ); - }).toList(), - onChanged: (title) { - selectedPositiontitle = title; - }, - ), - const SizedBox( - height: 12, - ), - ////is within parent - FormBuilderSwitch( - initialValue: true, - activeColor: second, - onChanged: (value) { - setState(() { - isWithinParent = value!; - }); - }, - decoration: normalTextFieldStyle( - "Location of the station within this parent?", - 'Location of the station within this parent?'), - name: 'isWithinParent', - title: Text(isWithinParent ? "YES" : "NO"), - ), - const SizedBox( - height: 12, - ), - Row( - //// Station Name - children: [ - Flexible( - child: FormBuilderTextField( - validator: - FormBuilderValidators.required( - errorText: - "This Field is required"), - decoration: normalTextFieldStyle( - "Station name", "Station name"), - name: "station-name"), - ), - const SizedBox( - width: 12, - ), - //// Acronym - Flexible( - child: FormBuilderTextField( - validator: - FormBuilderValidators.required( - errorText: - "This Field is required"), - decoration: normalTextFieldStyle( - "Acronym", "Acronym"), - name: "acronym"), - ), - ], - ), - const SizedBox( - height: 12, - ), - FormBuilderTextField( - ////Description - decoration: normalTextFieldStyle( - "Station description", - "Station description"), - name: "station-description"), - const SizedBox( - height: 12, - ), - Row( - children: [ - Flexible( - ////Code - child: FormBuilderTextField( - decoration: normalTextFieldStyle( - "Code", "Code"), - name: "code"), - ), - const SizedBox( - width: 12, - ), - Flexible( - //// Full Code - child: FormBuilderTextField( - decoration: normalTextFieldStyle( - "Full Code", "Full Code"), - name: "fullcode"), - ), - ], - ), - const SizedBox( - height: 12, - ), - ////is Hospital - FormBuilderSwitch( - initialValue: isHospital, - activeColor: second, - onChanged: (value) { - setState(() { - isHospital = !isHospital; - }); - }, - decoration: - normalTextFieldStyle("Is Hospital", ''), - name: 'isHospital', - title: Text(isHospital == true ? "YES" : "NO"), - ), - const SizedBox( - height: 20, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - RbacStation? newStation; - if (formKey.currentState! - .saveAndValidate()) { - String? stationName = formKey - .currentState! - .value['station-name']; - String? acronym = formKey - .currentState!.value['acronym']; - String? code = formKey - .currentState!.value['code']; - String? fullcode = formKey - .currentState!.value['fullcode']; - String? description = formKey - .currentState! - .value['station-description']; - newStation = RbacStation( - id: null, - stationName: stationName, - stationType: selectedStationType, - hierarchyOrderNo: mainParent - ? 1 - : selectedParentStation! - .hierarchyOrderNo! + - 1, - headPosition: - selectedPositiontitle?.title, - governmentAgency: - GovernmentAgency( - agencyid: - selectedAgencyId, - agencyname: null, - agencycatid: null, - privateEntity: null, - contactinfoid: null), - acronym: acronym, - parentStation: mainParent - ? null - : selectedParentStation!.id!, - code: code, - fullcode: fullcode, - childStationInfo: null, - islocationUnderParent: - isWithinParent, - mainParentStation: mainParent - ? null - : selectedMainParentStation! - .id!, - description: description, - ishospital: isHospital, - isactive: true, - sellingStation: null); - Navigator.pop(context); - rbacStationBloc.add(AddRbacStation( - station: newStation)); - } + /////Add new tation + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Station"), + content: SingleChildScrollView( + child: FormBuilder( + key: formKey, + child: + StatefulBuilder(builder: (context, setState) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + ////is main parent + FormBuilderSwitch( + initialValue: mainParent, + activeColor: second, + onChanged: (value) { + setState(() { + mainParent = !mainParent; + }); }, - child: const Text("Add"))), - ], - ); - }), - ), - ), - ); - }); - }), - ////Filter - IconButton( - onPressed: () { - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text( - "Select agency to filter stations", - textAlign: TextAlign.center, - ), - content: SizedBox( - child: // //// Filter Agencies - Padding( - padding: const EdgeInsets.all(8), - child: SearchField( - inputFormatters: [UpperCaseTextFormatter()], - itemHeight: 100, - focusNode: agencyFocusNode, - suggestions: agencies - .map((Agency agency) => - SearchFieldListItem(agency.name!, - item: agency, - child: ListTile( - title: Text( - agency.name!, - overflow: TextOverflow.visible, - ), - ))) - .toList(), - searchInputDecoration: - normalTextFieldStyle("Filter", "").copyWith( - suffixIcon: IconButton( - icon: const Icon(Icons.arrow_drop_down), - onPressed: () { - agencyFocusNode.unfocus(); - }, - )), - onSuggestionTap: (agency) { - agencyFocusNode.unfocus(); - - selectedAgencyId = agency.item!.id!; - print(selectedAgencyId); - Navigator.pop(context); - rbacStationBloc.add(FilterStation( - agencyId: selectedAgencyId)); - }, - validator: (agency) { - if (agency!.isEmpty) { - return "This field is required"; - } - return null; - }, - emptyWidget: const Center( - child: Text("No result found..."), - )), + decoration: normalTextFieldStyle( + "is Main Parent?", 'is Main Parent?'), + name: 'main-parent', + title: Text(mainParent ? "YES" : "NO"), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + SizedBox( + height: mainParent ? 0 : 8, + ), + //// selected main parent + SizedBox( + child: mainParent == true + ? const SizedBox.shrink() + : FormBuilderDropdown( + decoration: normalTextFieldStyle( + "Main Parent Station", + "Main Parent Station"), + name: "parent-stations", + items: mainParentStations.isEmpty + ? [] + : mainParentStations.map((e) { + return DropdownMenuItem( + value: e, + child: Text( + e.stationName!), + ); + }).toList(), + onChanged: (RbacStation? e) { + setState(() { + selectedMainParentStation = e; + parentStations = []; + for (RbacStation station + in stations) { + if (station + .mainParentStation == + selectedMainParentStation! + .id) { + parentStations + .add(station); + } + } + parentStations.add( + selectedMainParentStation!); + }); + }, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + ), + SizedBox( + height: mainParent ? 0 : 8, + ), + ////parent station + SizedBox( + child: mainParent == true + ? const SizedBox.shrink() + : FormBuilderDropdown( + decoration: normalTextFieldStyle( + "Parent Station", + "Parent Station"), + name: "parent-stations", + onChanged: (RbacStation? e) { + setState(() { + selectedParentStation = e; + }); + }, + items: parentStations.isEmpty + ? [] + : parentStations.map((e) { + return DropdownMenuItem( + value: e, + child: Text( + e.stationName!), + ); + }).toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + ), + const SizedBox( + height: 12, + ), + ////Station Type + SearchField( + itemHeight: 50, + suggestionsDecoration: + searchFieldDecoration(), + suggestions: stationTypes + .map((StationType stationType) => + SearchFieldListItem( + stationType.typeName!, + item: stationType, + child: Padding( + padding: const EdgeInsets + .symmetric( + horizontal: 10), + child: ListTile( + title: Text( + stationType.typeName!, + overflow: + TextOverflow.visible, + )), + ))) + .toList(), + validator: (station) { + if (station!.isEmpty) { + return "This field is required"; + } + return null; + }, + focusNode: stationTypeFocusNode, + searchInputDecoration: + normalTextFieldStyle( + "Station Type *", "") + .copyWith( + suffixIcon: GestureDetector( + onTap: () => + stationTypeFocusNode.unfocus(), + child: + const Icon(Icons.arrow_drop_down), + )), + onSuggestionTap: (position) { + setState(() { + selectedStationType = position.item!; + stationTypeFocusNode.unfocus(); + }); + }, + emptyWidget: EmptyWidget( + title: "Add StationType", + controller: addStationTypeController, + onpressed: () { + setState(() { + StationType stationType = + StationType( + id: null, + typeName: + addStationTypeController + .text, + color: null, + order: null, + isActive: null, + group: null); + stationTypes.add(stationType); + Navigator.pop(context); + }); + }), + ), + const SizedBox( + height: 12, + ), + ////Position title + FormBuilderDropdown( + decoration: normalTextFieldStyle( + "Head Position", "Head Position"), + name: "head-position", + items: positions.map((e) { + return DropdownMenuItem( + value: e, + child: Text(e.title!), + ); + }).toList(), + onChanged: (title) { + selectedPositiontitle = title; + }, + ), + const SizedBox( + height: 12, + ), + ////is within parent + FormBuilderSwitch( + initialValue: true, + activeColor: second, + onChanged: (value) { + setState(() { + isWithinParent = value!; + }); + }, + decoration: normalTextFieldStyle( + "Location of the station within this parent?", + 'Location of the station within this parent?'), + name: 'isWithinParent', + title: + Text(isWithinParent ? "YES" : "NO"), + ), + const SizedBox( + height: 12, + ), + Row( + //// Station Name + children: [ + Flexible( + child: FormBuilderTextField( + validator: FormBuilderValidators + .required( + errorText: + "This Field is required"), + decoration: normalTextFieldStyle( + "Station name", + "Station name"), + name: "station-name"), + ), + const SizedBox( + width: 12, + ), + //// Acronym + Flexible( + child: FormBuilderTextField( + validator: FormBuilderValidators + .required( + errorText: + "This Field is required"), + decoration: normalTextFieldStyle( + "Acronym", "Acronym"), + name: "acronym"), + ), + ], + ), + const SizedBox( + height: 12, + ), + FormBuilderTextField( + ////Description + decoration: normalTextFieldStyle( + "Station description", + "Station description"), + name: "station-description"), + const SizedBox( + height: 12, + ), + Row( + children: [ + Flexible( + ////Code + child: FormBuilderTextField( + decoration: normalTextFieldStyle( + "Code", "Code"), + name: "code"), + ), + const SizedBox( + width: 12, + ), + Flexible( + //// Full Code + child: FormBuilderTextField( + decoration: normalTextFieldStyle( + "Full Code", "Full Code"), + name: "fullcode"), + ), + ], + ), + const SizedBox( + height: 12, + ), + ////is Hospital + FormBuilderSwitch( + initialValue: isHospital, + activeColor: second, + onChanged: (value) { + setState(() { + isHospital = !isHospital; + }); + }, + decoration: normalTextFieldStyle( + "Is Hospital", ''), + name: 'isHospital', + title: Text( + isHospital == true ? "YES" : "NO"), + ), + const SizedBox( + height: 20, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + RbacStation? newStation; + if (formKey.currentState! + .saveAndValidate()) { + String? stationName = formKey + .currentState! + .value['station-name']; + String? acronym = formKey + .currentState! + .value['acronym']; + String? code = formKey + .currentState! + .value['code']; + String? fullcode = formKey + .currentState! + .value['fullcode']; + String? description = + formKey.currentState!.value[ + 'station-description']; + newStation = RbacStation( + id: null, + stationName: stationName, + stationType: + selectedStationType, + hierarchyOrderNo: mainParent + ? 1 + : selectedParentStation! + .hierarchyOrderNo! + + 1, + headPosition: + selectedPositiontitle + ?.title, + governmentAgency: + GovernmentAgency( + agencyid: + selectedAgencyId, + agencyname: null, + agencycatid: null, + privateEntity: null, + contactinfoid: + null), + acronym: acronym, + parentStation: + mainParent + ? null + : selectedParentStation! + .id!, + code: code, + fullcode: fullcode, + childStationInfo: null, + islocationUnderParent: + isWithinParent, + mainParentStation: mainParent + ? null + : selectedMainParentStation! + .id!, + description: description, + ishospital: isHospital, + isactive: true, + sellingStation: null); + Navigator.pop(context); + rbacStationBloc.add( + AddRbacStation( + station: newStation)); + } + }, + child: const Text("Add"))), + ], + ); + }), + ), ), - ), - ); - }); - }, - icon: const Icon(Icons.filter_list)) - ], + ); + }); + }), + ////Filter + IconButton( + onPressed: () { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text( + "Select agency to filter stations", + textAlign: TextAlign.center, + ), + content: SizedBox( + child: // //// Filter Agencies + Padding( + padding: const EdgeInsets.all(8), + child: SearchField( + inputFormatters: [ + UpperCaseTextFormatter() + ], + itemHeight: 100, + focusNode: agencyFocusNode, + suggestions: agencies + .map((Agency agency) => + SearchFieldListItem(agency.name!, + item: agency, + child: ListTile( + title: Text( + agency.name!, + overflow: + TextOverflow.visible, + ), + ))) + .toList(), + searchInputDecoration: + normalTextFieldStyle("Filter", "") + .copyWith( + suffixIcon: IconButton( + icon: const Icon(Icons.arrow_drop_down), + onPressed: () { + agencyFocusNode.unfocus(); + }, + )), + onSuggestionTap: (agency) { + agencyFocusNode.unfocus(); + + selectedAgencyId = agency.item!.id!; + print(selectedAgencyId); + Navigator.pop(context); + rbacStationBloc.add(FilterStation( + agencyId: selectedAgencyId)); + }, + validator: (agency) { + if (agency!.isEmpty) { + return "This field is required"; + } + return null; + }, + emptyWidget: const Center( + child: Text("No result found..."), + )), + ), + ), + ); + }); + }, + icon: const Icon(Icons.filter_list)) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -643,7 +675,7 @@ class _RbacStationScreenState extends State { boxShadow: []), padding: const EdgeInsets - .only( + .only( left: 30), child: Row( children: [ @@ -652,7 +684,8 @@ class _RbacStationScreenState extends State { children: [ Padding( padding: - const EdgeInsets.all( + const EdgeInsets + .all( 6), child: Text( @@ -720,7 +753,7 @@ class _RbacStationScreenState extends State { box1() .copyWith(boxShadow: []), padding: const EdgeInsets - .only( + .only( left: 50), child: @@ -873,7 +906,9 @@ class _RbacStationScreenState extends State { return SomethingWentWrong( message: state.message, onpressed: () { - context.read().add(GetStations(agencyId: selectedAgencyId)); + context + .read() + .add(GetStations(agencyId: selectedAgencyId)); }); } diff --git a/lib/screens/unit2/basic-info/basic-info.dart b/lib/screens/unit2/basic-info/basic-info.dart index 6d80128..a75f9a2 100644 --- a/lib/screens/unit2/basic-info/basic-info.dart +++ b/lib/screens/unit2/basic-info/basic-info.dart @@ -1,7 +1,8 @@ - +import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_svg/svg.dart'; import 'package:fluttericon/font_awesome5_icons.dart'; import 'package:intl/intl.dart'; import 'package:qr_flutter/qr_flutter.dart'; @@ -44,45 +45,45 @@ class BasicInfo extends StatelessWidget { alignment: Alignment.center, children: [ const CoverImage(), - // Positioned( - // top: blockSizeVertical * 15.5, - // child: Stack( - // alignment: Alignment.center, - // children: [ - // CachedNetworkImage( - // imageUrl: fileUrl, - // imageBuilder: (context, imageProvider) => - // Container( - // width: 160, - // height: 160, - // decoration: BoxDecoration( - // border: Border.all( - // color: Colors.black26, width: 3), - // shape: BoxShape.circle, - // image: DecorationImage( - // image: imageProvider, - // fit: BoxFit.cover), - // ), - // ), - // placeholder: (context, url) => - // const CircularProgressIndicator(), - // errorWidget: (context, url, error) => - // Container( - // width: 160, - // height: 160, - // decoration: BoxDecoration( - // border: Border.all( - // color: Colors.white, width: 3), - // shape: BoxShape.circle, - // ), - // child: SvgPicture.asset( - // 'assets/svgs/male.svg', - // ), - // ), - // ), - // ], - // ), - // ), + Positioned( + top: blockSizeVertical * 15.5, + child: Stack( + alignment: Alignment.center, + children: [ + CachedNetworkImage( + imageUrl: fileUrl, + imageBuilder: (context, imageProvider) => + Container( + width: 160, + height: 160, + decoration: BoxDecoration( + border: Border.all( + color: Colors.black26, width: 3), + shape: BoxShape.circle, + image: DecorationImage( + image: imageProvider, + fit: BoxFit.cover), + ), + ), + placeholder: (context, url) => + const CircularProgressIndicator(), + errorWidget: (context, url, error) => + Container( + width: 160, + height: 160, + decoration: BoxDecoration( + border: Border.all( + color: Colors.white, width: 3), + shape: BoxShape.circle, + ), + child: SvgPicture.asset( + 'assets/svgs/male.svg', + ), + ), + ), + ], + ), + ), Positioned( top: 10, left: 20, @@ -135,13 +136,14 @@ class BuildInformation extends StatelessWidget { @override Widget build(BuildContext context) { DateFormat dteFormat2 = DateFormat.yMMMMd('en_US'); - globalFistname = globalFistname ?? userData.user!.login!.user!.firstName!.toUpperCase(); - globalLastname =globalLastname ?? userData.user!.login!.user!.lastName!.toUpperCase(); - globalMiddleName = globalMiddleName == null - ? (userData.employeeInfo == null + globalFistname = + globalFistname ?? userData.employeeInfo!.profile!.firstName!.toUpperCase(); + globalLastname = + globalLastname ?? userData.employeeInfo!.profile!.lastName!.toUpperCase(); + globalMiddleName = globalMiddleName ?? + (userData.employeeInfo == null ? '' - : userData.employeeInfo!.profile?.middleName?.toUpperCase()) - : ''; + : userData.employeeInfo!.profile?.middleName?.toUpperCase()); globalSex = globalSex ?? userData.employeeInfo!.profile!.sex!.toUpperCase(); globalBday = globalBday ?? userData.employeeInfo!.profile!.birthdate; final uuid = userData.employeeInfo!.uuid; diff --git a/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart b/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart index ca65099..64c287a 100644 --- a/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart +++ b/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart @@ -26,7 +26,7 @@ import 'package:unit2/screens/superadmin/permission_assignment/permission_assign import 'package:unit2/screens/superadmin/role/role_screen.dart'; import 'package:unit2/screens/superadmin/role_assignment.dart/role_assignment_screen.dart'; import 'package:unit2/screens/superadmin/role_extend/role_extend_screen.dart'; -import 'package:unit2/screens/superadmin/roles_under/roles_under_screen.dart'; +import 'package:unit2/screens/superadmin/roles_under/assignable_roles.dart'; import 'package:unit2/screens/superadmin/stations/stations_screen.dart'; import 'package:unit2/screens/unit2/homepage.dart/module-screen.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; diff --git a/lib/screens/unit2/homepage.dart/components/menu-screen.dart b/lib/screens/unit2/homepage.dart/components/menu-screen.dart index fe13218..b5a0888 100644 --- a/lib/screens/unit2/homepage.dart/components/menu-screen.dart +++ b/lib/screens/unit2/homepage.dart/components/menu-screen.dart @@ -18,9 +18,9 @@ class _MenuScreenState extends State { @override Widget build(BuildContext context) { final String firstName =globalFistname?? - widget.userData!.user!.login!.user!.firstName!.toUpperCase(); + widget.userData!.employeeInfo!.profile!.firstName!.toUpperCase(); final String lastname = globalLastname?? - widget.userData!.user!.login!.user!.lastName!.toUpperCase(); + widget.userData!.employeeInfo!.profile!.lastName!.toUpperCase(); return Drawer( child: SizedBox( height: screenHeight, diff --git a/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart b/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart index f773615..213aab0 100644 --- a/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart +++ b/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart @@ -1,5 +1,6 @@ import 'package:assets_audio_player/assets_audio_player.dart'; import 'package:audioplayers/audioplayers.dart'; +import 'package:awesome_dialog/awesome_dialog.dart'; import 'package:cool_alert/cool_alert.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -35,13 +36,13 @@ class _QRCodeScannerState extends State { player = AudioPlayer(); super.initState(); } + @override void dispose() { player?.dispose(); super.dispose(); } - @override Widget build(BuildContext context) { return Scaffold( @@ -73,83 +74,86 @@ class _QRCodeScannerState extends State { progress!.dismiss(); } if (state is ScanSuccess) { - Future.delayed(const Duration(seconds: 1), () async{ - await player?.play(AssetSource("success.mp3")); + Future.delayed(const Duration(seconds: 1), () async { + await player?.play(AssetSource("success.mp3")); }); context.read().add(ScanQr(token: state.token)); } if (state is QRInvalid) { - Future.delayed(const Duration(seconds: 1), ()async { + Future.delayed(const Duration(seconds: 1), () async { await player?.play(AssetSource("invalid.mp3")); }); context.read().add(ScanQr(token: state.token)); } if (state is ScanFailed) { - Future.delayed(const Duration(seconds: 1), ()async { - await player?.play(AssetSource("fail.mp3")); + Future.delayed(const Duration(seconds: 1), () async { + await player?.play(AssetSource("fail.mp3")); }); - + context.read().add(ScanQr(token: state.token)); } if (state is IncomingScanState) { - CoolAlert.show( - barrierDismissible: false, - context: context, - type: CoolAlertType.loading, - text: "Enter Temperature", - widget: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24), - child: FormBuilder( - key: formKey, - child: Column( - children: [ - const SizedBox( - height: 24, + AwesomeDialog( + dismissOnBackKeyPress: false, + context: context, + dialogType: DialogType.info, + dismissOnTouchOutside: false, + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24), + child: FormBuilder( + key: formKey, + child: Column( + children: [ + const Text("Enter Temperature",style: TextStyle(color: Colors.black),), + const SizedBox( + height: 24, + ), + FormBuilderTextField( + keyboardType: TextInputType.number, + name: "temp", + decoration: + normalTextFieldStyle("Temperature", ""), + validator: numericRequired), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.infinity, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + child: const Text(submit), + onPressed: () { + if (formKey.currentState!.saveAndValidate()) { + double temperature = double.parse( + formKey.currentState!.value['temp']); + context.read().add( + PerformIncomingPostLog( + temp: temperature)); + Navigator.of(context).pop(); + } + }, ), - FormBuilderTextField( - keyboardType: TextInputType.number, - name: "temp", - decoration: - normalTextFieldStyle("Temperature", ""), - validator: numericRequired), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.infinity, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - child: const Text(submit), - onPressed: () { - if (formKey.currentState!.saveAndValidate()) { - double temperature = double.parse( - formKey.currentState!.value['temp']); - context.read().add( - PerformIncomingPostLog( - temp: temperature)); - Navigator.of(context).pop(); - } - }, - ), - ) - ], - )), - )); + ) + ], + )), + ), + ).show(); } if (state is OutGoingScanState) { - CoolAlert.show( - barrierDismissible: false, - context: context, - type: CoolAlertType.loading, - text: "Enter Destination", - widget: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24), + AwesomeDialog( + dismissOnBackKeyPress: false, + context: context, + dialogType: DialogType.info, + dismissOnTouchOutside: false, + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24,vertical: 24), child: FormBuilder( key: formKey, child: Column( children: [ + const Text("Enter Destination"), const SizedBox( height: 24, ), @@ -185,7 +189,8 @@ class _QRCodeScannerState extends State { ) ], )), - )); + )).show(); + } }, builder: (context, state) { @@ -302,28 +307,56 @@ class _QRCodeScannerState extends State { children: [ SelectedState( //TODO add api data - title: state.roleIdRoleName.roleName.toLowerCase() == "41" || - state.roleIdRoleName.roleName.toLowerCase() == 'qr code scanner' || - state.roleIdRoleName.roleName.toLowerCase() == 'office/branch chief' || - state.roleIdRoleName.roleName.toLowerCase() == 'registration in-charge' + title: state.roleIdRoleName.roleName + .toLowerCase() == + "41" || + state.roleIdRoleName.roleName + .toLowerCase() == + 'qr code scanner' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'office/branch chief' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'registration in-charge' ? state.assignedArea.stationName - : state.roleIdRoleName.roleName.toLowerCase() == 'barangay chairperson' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'barangay chairperson' ? state.assignedArea.brgydesc - : state.roleIdRoleName.roleName.toLowerCase() == 'purok president' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'purok president' ? state.assignedArea.purokdesc - : state.roleIdRoleName.roleName.toLowerCase() == 'establishment point-person' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'establishment point-person' ? "Agency" : "", - subtitle: state.roleIdRoleName.roleName.toLowerCase() == "41" || - state.roleIdRoleName.roleName.toLowerCase() == 'qr code scanner' || - state.roleIdRoleName.roleName.toLowerCase() == 'office/branch chief' || - state.roleIdRoleName.roleName.toLowerCase() == 'registration in-charge' + subtitle: state.roleIdRoleName.roleName + .toLowerCase() == + "41" || + state.roleIdRoleName.roleName + .toLowerCase() == + 'qr code scanner' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'office/branch chief' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'registration in-charge' ? "Station" - : state.roleIdRoleName.roleName.toLowerCase() == 'barangay chairperson' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'barangay chairperson' ? "Barangay" - : state.roleIdRoleName.roleName.toLowerCase() == 'purok president' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'purok president' ? "Purok" - : state.roleIdRoleName.roleName.toLowerCase() == 'establishment point-person' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'establishment point-person' ? "Agency" : "", ), diff --git a/lib/sevices/roles/rbac_operations/agency_services.dart b/lib/sevices/roles/rbac_operations/agency_services.dart index 12d33d0..380223a 100644 --- a/lib/sevices/roles/rbac_operations/agency_services.dart +++ b/lib/sevices/roles/rbac_operations/agency_services.dart @@ -14,7 +14,7 @@ class AgencyServices { 'X-Client-Key': xClientKey, 'X-Client-Secret': xClientSecret }; - String path = Url.instance.postAgencies(); + String path = Url.instance.agencies(); Future> getAgencies() async { List agencies = []; diff --git a/lib/sevices/roles/rbac_operations/module_services.dart b/lib/sevices/roles/rbac_operations/module_services.dart index f62415a..1020b70 100644 --- a/lib/sevices/roles/rbac_operations/module_services.dart +++ b/lib/sevices/roles/rbac_operations/module_services.dart @@ -111,7 +111,6 @@ class RbacModuleServices { Future deleteRbacModule({required int moduleId}) async { bool success = false; - String path = "${Url.instance.getModules()}$moduleId/"; try { http.Response response = await Request.instance .deleteRequest(path: '${path+moduleId.toString()}/', headers: headers, body: {}, param: {}); diff --git a/lib/sevices/roles/rbac_operations/role_extend_services.dart b/lib/sevices/roles/rbac_operations/role_extend_services.dart index ad36166..8200111 100644 --- a/lib/sevices/roles/rbac_operations/role_extend_services.dart +++ b/lib/sevices/roles/rbac_operations/role_extend_services.dart @@ -67,7 +67,6 @@ class RbacRoleExtendServices { Future delete({required int roleExtendId}) async { bool success = false; - String path = "${Url.instance.getRoleExtend()}$roleExtendId/"; try { http.Response response = await Request.instance.deleteRequest( path: '${path + roleExtendId.toString()}/', diff --git a/lib/utils/formatters.dart b/lib/utils/formatters.dart index 4db4cd8..154e478 100644 --- a/lib/utils/formatters.dart +++ b/lib/utils/formatters.dart @@ -3,7 +3,8 @@ import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; var mobileFormatter = MaskTextInputFormatter( mask: "+63 (###) ###-####", - filter: {"#": RegExp(r"^[1-9][0-9]*$")}, + filter: {"#": RegExp(r'^[0-9][0-9]*$') +}, type: MaskAutoCompletionType.lazy, initialText: "0"); diff --git a/lib/utils/request.dart b/lib/utils/request.dart index 4a5345f..80d771f 100644 --- a/lib/utils/request.dart +++ b/lib/utils/request.dart @@ -18,7 +18,7 @@ class Request { Map? param}) async { Response response; try { - response = await get(Uri.http(host, path!, param), headers: headers) + response = await get(Uri.https(host, path!, param), headers: headers) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { // Fluttertoast.showToast( @@ -60,7 +60,7 @@ class Request { Map? param}) async { Response response; try { - response = await post(Uri.http(host, path!, param), + response = await post(Uri.https(host, path!, param), headers: headers, body: jsonEncode(body)) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { @@ -103,7 +103,7 @@ class Request { required Map? param}) async { Response response; try { - response = await put(Uri.http(host, path, param), + response = await put(Uri.https(host, path, param), headers: headers, body: jsonEncode(body)); } on TimeoutException catch (_) { // Fluttertoast.showToast( @@ -187,7 +187,7 @@ class Request { required Map? param}) async { Response response; try { - response = await delete(Uri.http(host, path, param), + response = await delete(Uri.https(host, path, param), headers: headers, body: jsonEncode(body)) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { diff --git a/lib/utils/urls.dart b/lib/utils/urls.dart index 52e5f27..bf1db5d 100644 --- a/lib/utils/urls.dart +++ b/lib/utils/urls.dart @@ -5,8 +5,8 @@ class Url { String host() { // return '192.168.10.183:3000'; - // return 'agusandelnorte.gov.ph'; - return "192.168.10.219:3000"; + return 'agusandelnorte.gov.ph'; + // return "192.168.10.219:3000"; // return "192.168.10.241"; // return "192.168.10.221:3004"; // return "playweb.agusandelnorte.gov.ph"; @@ -15,8 +15,8 @@ class Url { } String prefixHost() { - // return "https"; - return "http"; + return "https"; + // return "http"; } String authentication() {