add search functions to superadmin screens

feature/passo/PASSO-#1-Sync-data-from-device-to-postgre-and-vice-versa
PGAN-MIS 2023-10-03 08:33:10 +08:00
parent ba89592496
commit deeca18962
38 changed files with 3517 additions and 2576 deletions

View File

@ -51,10 +51,13 @@ class LearningDevelopmentBloc
attachmentCategories = attachmentCategories =
await AttachmentServices.instance.getCategories(); await AttachmentServices.instance.getCategories();
} }
if(learningsAndDevelopments.isEmpty){
List<LearningDevelopement> learnings = await LearningDevelopmentServices List<LearningDevelopement> learnings = await LearningDevelopmentServices
.instance .instance
.getLearningDevelopments(event.profileId, event.token); .getLearningDevelopments(event.profileId, event.token);
learningsAndDevelopments = learnings; learningsAndDevelopments = learnings;
}
emit(LearningDevelopmentLoadedState( emit(LearningDevelopmentLoadedState(
learningsAndDevelopment: learningsAndDevelopments,attachmentCategory: attachmentCategories)); learningsAndDevelopment: learningsAndDevelopments,attachmentCategory: attachmentCategories));
} catch (e) { } catch (e) {

View File

@ -64,6 +64,7 @@ class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
primaryBasicInformation: globalCurrentProfile!)); primaryBasicInformation: globalCurrentProfile!));
} else { } else {
currentProfileInformation = event.primaryBasicInformation; currentProfileInformation = event.primaryBasicInformation;
globalCurrentProfile = currentProfileInformation;
emit(BasicInformationProfileLoaded( emit(BasicInformationProfileLoaded(
primaryBasicInformation: currentProfileInformation!)); primaryBasicInformation: currentProfileInformation!));
} }
@ -108,7 +109,7 @@ class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
0, ProfileOtherInfo(id: null, name: "NONE", description: null)); 0, ProfileOtherInfo(id: null, name: "NONE", description: null));
} }
emit(BasicInformationEditingState( emit(BasicInformationEditingState(
primaryInformation: currentProfileInformation!, primaryInformation: globalCurrentProfile!,
extensions: nameExtensions, extensions: nameExtensions,
sexes: sexes, sexes: sexes,
bloodTypes: bloodType, bloodTypes: bloodType,

View File

@ -13,9 +13,12 @@ class GetAgencies extends AgencyEvent{
class AddAgency extends AgencyEvent{ class AddAgency extends AgencyEvent{
final Agency agency; final Agency agency;
const AddAgency({required this.agency}); const AddAgency({required this.agency});
List<Object> get props => [agency
];
} }
class GetEstPointPersonAgencies extends AgencyEvent{ class GetEstPointPersonAgencies extends AgencyEvent{
final List<AssignedArea>? assignedAreas; final List<AssignedArea>? assignedAreas;
const GetEstPointPersonAgencies({required this.assignedAreas}); const GetEstPointPersonAgencies({required this.assignedAreas});
} }

View File

@ -60,7 +60,7 @@ class AssignAreaBloc extends Bloc<AssignAreaEvent, AssignAreaState> {
} }
}); });
on<AddAssignArea>((event, emit) async { on<AddAssignArea>((event, emit) async {
// try { try {
emit(AssignAreaLoadingState()); emit(AssignAreaLoadingState());
Map<dynamic, dynamic> response = await RbacAssignedAreaServices.instance Map<dynamic, dynamic> response = await RbacAssignedAreaServices.instance
.add( .add(
@ -77,11 +77,6 @@ class AssignAreaBloc extends Bloc<AssignAreaEvent, AssignAreaState> {
break; break;
} }
} }
// newAssignArea = userAssignedAreas.firstWhere((var element) {
// return element.assignedRole?.role?.id == event.roleId &&
// element.assignedRole?.user?.id == event.userId;
// });
if (newAssignArea?.assignedArea != null) { if (newAssignArea?.assignedArea != null) {
userAssignedAreas.removeWhere((element) => userAssignedAreas.removeWhere((element) =>
element.assignedRole!.role!.id == event.roleId && element.assignedRole!.role!.id == event.roleId &&
@ -120,8 +115,8 @@ class AssignAreaBloc extends Bloc<AssignAreaEvent, AssignAreaState> {
newAreas.add(newArea); newAreas.add(newArea);
} }
} }
newAssignArea?.assignedArea = newAreas; newAssignArea.assignedArea = newAreas;
userAssignedAreas.add(newAssignArea!); userAssignedAreas.add(newAssignArea);
//// purok //// purok
} }
if (event.areaTypeId == 2) { if (event.areaTypeId == 2) {
@ -149,8 +144,8 @@ class AssignAreaBloc extends Bloc<AssignAreaEvent, AssignAreaState> {
newAreas.add(newArea); newAreas.add(newArea);
} }
} }
newAssignArea?.assignedArea = newAreas; newAssignArea.assignedArea = newAreas;
userAssignedAreas.add(newAssignArea!); userAssignedAreas.add(newAssignArea);
} }
////statiom ////statiom
if (event.areaTypeId == 4) { if (event.areaTypeId == 4) {
@ -200,8 +195,8 @@ class AssignAreaBloc extends Bloc<AssignAreaEvent, AssignAreaState> {
newAreas.add(newArea); newAreas.add(newArea);
} }
} }
newAssignArea?.assignedArea = newAreas; newAssignArea.assignedArea = newAreas;
userAssignedAreas.add(newAssignArea!); userAssignedAreas.add(newAssignArea);
} }
////agency ////agency
if (event.areaTypeId == 3) { if (event.areaTypeId == 3) {
@ -231,16 +226,16 @@ class AssignAreaBloc extends Bloc<AssignAreaEvent, AssignAreaState> {
newAreas.add(newArea); newAreas.add(newArea);
} }
} }
newAssignArea?.assignedArea = newAreas; newAssignArea.assignedArea = newAreas;
userAssignedAreas.add(newAssignArea!); userAssignedAreas.add(newAssignArea);
} }
emit(AssignAreaAddedState(response: response)); emit(AssignAreaAddedState(response: response));
} else { } else {
emit(AssignAreaAddedState(response: response)); emit(AssignAreaAddedState(response: response));
} }
// } catch (e) { } catch (e) {
// emit(AssignAreaErorState(message: e.toString())); emit(AssignAreaErorState(message: e.toString()));
// } }
}); });
on<LoadAssignedAreas>((event, emit) async { on<LoadAssignedAreas>((event, emit) async {
emit(AssignedAreaLoadedState( emit(AssignedAreaLoadedState(

View File

@ -25,7 +25,8 @@ class RoleModuleBloc extends Bloc<RoleModuleEvent, RoleModuleState> {
if (roles.isEmpty) { if (roles.isEmpty) {
roles = await RbacRoleServices.instance.getRbacRoles(); roles = await RbacRoleServices.instance.getRbacRoles();
} }
emit(RoleModuleLoadedState(roleModules: roleModules,modules: modules,roles: roles)); emit(RoleModuleLoadedState(
roleModules: roleModules, modules: modules, roles: roles));
} catch (e) { } catch (e) {
emit(RoleModuleErrorState(message: e.toString())); emit(RoleModuleErrorState(message: e.toString()));
} }
@ -40,9 +41,12 @@ class RoleModuleBloc extends Bloc<RoleModuleEvent, RoleModuleState> {
moduleIds: event.moduleIds); moduleIds: event.moduleIds);
if (statusResponse['success']) { if (statusResponse['success']) {
List<int?> ids = roleModules.map((e) => e.id).toList();
statusResponse['data'].forEach((var roleMod) { statusResponse['data'].forEach((var roleMod) {
RoleModules newRoleModule = RoleModules.fromJson(roleMod); RoleModules newRoleModule = RoleModules.fromJson(roleMod);
if (!ids.contains(newRoleModule.id)) {
roleModules.add(newRoleModule); roleModules.add(newRoleModule);
}
emit(RoleModuleAddedState(response: statusResponse)); emit(RoleModuleAddedState(response: statusResponse));
}); });
} else { } else {

View File

@ -36,11 +36,14 @@ class RolesUnderBloc extends Bloc<RolesUnderEvent, RolesUnderState> {
.add(roleId: event.roleId, rolesId: event.roleUnderIds); .add(roleId: event.roleId, rolesId: event.roleUnderIds);
if (statusResponse['success']) { if (statusResponse['success']) {
List<int> ids = rolesUnder.map((e) => e.id).toList();
statusResponse['data'].forEach((var roleMod) { statusResponse['data'].forEach((var roleMod) {
RolesUnder newRoleUnder = RolesUnder.fromJson(roleMod); RolesUnder newRoleUnder = RolesUnder.fromJson(roleMod);
if (!ids.contains(newRoleUnder.id)) {
rolesUnder.add(newRoleUnder); rolesUnder.add(newRoleUnder);
emit(RoleUnderAddedState(response: statusResponse)); }
}); });
emit(RoleUnderAddedState(response: statusResponse));
} else { } else {
emit(RoleUnderAddedState(response: statusResponse)); emit(RoleUnderAddedState(response: statusResponse));
} }

View File

@ -23,9 +23,9 @@ import '../../../../utils/alerts.dart';
class CitizenShipScreen extends StatefulWidget { class CitizenShipScreen extends StatefulWidget {
final int profileId; final int profileId;
final String token; final String token;
final List<Citizenship> citizenships;
const CitizenShipScreen( const CitizenShipScreen(
{super.key, required this.profileId, required this.token}); {super.key, required this.profileId, required this.token , required this.citizenships});
@override @override
State<CitizenShipScreen> createState() => _CitizenShipScreenState(); State<CitizenShipScreen> createState() => _CitizenShipScreenState();
@ -421,7 +421,9 @@ class _CitizenShipScreenState extends State<CitizenShipScreen> {
if (state is CitizenshipErrorState) { if (state is CitizenshipErrorState) {
return Scaffold( return Scaffold(
body: SomethingWentWrong( body: SomethingWentWrong(
message: state.message, onpressed: () {})); message: state.message, onpressed: () {
context.read<CitizenshipBloc>().add(GetCitizenship(citizenship: widget.citizenships));
}));
} }
return Container(); return Container();
}, },

View File

@ -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/btn-style.dart';
import 'package:unit2/theme-data.dart/form-style.dart'; import 'package:unit2/theme-data.dart/form-style.dart';
import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/global.dart';
import 'package:unit2/utils/global_context.dart';
import 'package:unit2/utils/text_container.dart'; import 'package:unit2/utils/text_container.dart';
import '../../../../../theme-data.dart/colors.dart'; import '../../../../../theme-data.dart/colors.dart';
@ -84,7 +85,7 @@ class _AddContactInformationScreenState
serviceTypeId: serviceTypeId:
selectedServiceType!.id!); selectedServiceType!.id!);
} catch (e) { } catch (e) {
context NavigationService.navigatorKey.currentContext!
.read<ContactBloc>() .read<ContactBloc>()
.add(CallErrorEvent(message: e.toString())); .add(CallErrorEvent(message: e.toString()));
} }
@ -129,6 +130,7 @@ class _AddContactInformationScreenState
? selectedServiceType?.id == 2 ? selectedServiceType?.id == 2
//// Landline //// Landline
? FormBuilderTextField( ? FormBuilderTextField(
keyboardType: TextInputType.number,
controller: numberMailController, controller: numberMailController,
inputFormatters: [landLineFormatter], inputFormatters: [landLineFormatter],
name: 'number-mail', name: 'number-mail',
@ -150,7 +152,7 @@ class _AddContactInformationScreenState
errorText: "This field is required"), errorText: "This field is required"),
decoration: normalTextFieldStyle( decoration: normalTextFieldStyle(
"Mobile number *", "Mobile number *",
"+63 (9xx) xxx - xxxx"), "+63 (9xx) xxx - xxxx").copyWith(helperText: "Please input your mobile number excluding the 0"),
) )
: selectedServiceType!.id == 4 : selectedServiceType!.id == 4
////Social Media ////Social Media
@ -167,6 +169,7 @@ class _AddContactInformationScreenState
: selectedServiceType!.id == 3 : selectedServiceType!.id == 3
////Email Address ////Email Address
? FormBuilderTextField( ? FormBuilderTextField(
keyboardType: TextInputType.emailAddress,
controller: numberMailController, controller: numberMailController,
name: 'number-mail', name: 'number-mail',
validator: FormBuilderValidators validator: FormBuilderValidators

View File

@ -37,7 +37,7 @@ class _EditContactInformationScreenState
var mobileFormatter = MaskTextInputFormatter( var mobileFormatter = MaskTextInputFormatter(
mask: "+63 (###) ###-####", mask: "+63 (###) ###-####",
filter: {"#": RegExp(r"^[1-9][0-9]*$")}, filter: {"#": RegExp(r'^[0-9][0-9]*$')},
type: MaskAutoCompletionType.lazy, type: MaskAutoCompletionType.lazy,
initialText: "0"); initialText: "0");
@ -149,6 +149,7 @@ class _EditContactInformationScreenState
? selectedServiceType?.id == 2 ? selectedServiceType?.id == 2
//// Landline //// Landline
? FormBuilderTextField( ? FormBuilderTextField(
keyboardType: TextInputType.number,
controller: numberMailController, controller: numberMailController,
name: 'number-mail', name: 'number-mail',
inputFormatters: [landLineFormatter], inputFormatters: [landLineFormatter],
@ -162,6 +163,7 @@ class _EditContactInformationScreenState
selectedServiceType!.id == 19 selectedServiceType!.id == 19
//// Mobile number //// Mobile number
? FormBuilderTextField( ? FormBuilderTextField(
keyboardType: TextInputType.number,
controller: numberMailController, controller: numberMailController,
name: 'number-mail', name: 'number-mail',
inputFormatters: [mobileFormatter], inputFormatters: [mobileFormatter],
@ -172,10 +174,12 @@ class _EditContactInformationScreenState
decoration: normalTextFieldStyle( decoration: normalTextFieldStyle(
"Mobile number *", "Mobile number *",
"+63 (9xx) xxx - xxxx"), "+63 (9xx) xxx - xxxx"),
) )
: selectedServiceType!.id == 4 : selectedServiceType!.id == 4
////Social Media ////Social Media
? FormBuilderTextField( ? FormBuilderTextField(
controller: numberMailController, controller: numberMailController,
name: 'number-mail', name: 'number-mail',
validator: validator:
@ -188,6 +192,7 @@ class _EditContactInformationScreenState
: selectedServiceType!.id == 3 : selectedServiceType!.id == 3
////Email Address ////Email Address
? FormBuilderTextField( ? FormBuilderTextField(
keyboardType: TextInputType.emailAddress,
controller: controller:
numberMailController, numberMailController,
name: 'number-mail', name: 'number-mail',

View File

@ -1,10 +1,6 @@
import 'package:flutter/material.dart'; 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:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.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/btn-style.dart';
import '../../../../../theme-data.dart/colors.dart'; import '../../../../../theme-data.dart/colors.dart';
import '../../../../../theme-data.dart/form-style.dart'; import '../../../../../theme-data.dart/form-style.dart';
@ -26,6 +22,7 @@ class AddMobileNumber extends StatelessWidget {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
FormBuilderTextField( FormBuilderTextField(
keyboardType: TextInputType.number,
name: 'number_mail', name: 'number_mail',
inputFormatters: [mobileFormatter], inputFormatters: [mobileFormatter],
validator: FormBuilderValidators.required( validator: FormBuilderValidators.required(

View File

@ -45,7 +45,7 @@ class LearningAndDevelopmentScreen extends StatelessWidget {
AttachmentCategory? selectedAttachmentCategory; AttachmentCategory? selectedAttachmentCategory;
List<AttachmentCategory> attachmentCategories = []; List<AttachmentCategory> attachmentCategories = [];
return Scaffold( return Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar( appBar: AppBar(
title: context.watch<LearningDevelopmentBloc>().state title: context.watch<LearningDevelopmentBloc>().state
is LearningDevelopmentAddingState is LearningDevelopmentAddingState

View File

@ -48,15 +48,27 @@ import '../unit2/homepage.dart/components/menu.dart';
import 'components/main_menu.dart'; import 'components/main_menu.dart';
import 'components/submenu.dart'; import 'components/submenu.dart';
class ProfileInfo extends StatelessWidget { class ProfileInfo extends StatefulWidget {
const ProfileInfo({super.key}); const ProfileInfo({super.key});
@override
State<ProfileInfo> createState() => _ProfileInfoState();
}
class _ProfileInfoState extends State<ProfileInfo> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
int? profileId; int? profileId;
String? token; String? token;
Profile profile; Profile profile;
return Scaffold( return WillPopScope(
onWillPop: () async{
setState(() {
});
return true;
},
child: Scaffold(
appBar: AppBar( appBar: AppBar(
backgroundColor: primary, backgroundColor: primary,
centerTitle: true, centerTitle: true,
@ -71,11 +83,12 @@ class ProfileInfo extends StatelessWidget {
profileId = state.userData!.user!.login!.user!.profileId; profileId = state.userData!.user!.login!.user!.profileId;
token = state.userData!.user!.login!.token!; token = state.userData!.user!.login!.token!;
if (globalCurrentProfile == null) { if (globalCurrentProfile == null) {
profile = state.userData!.employeeInfo!.profile!; profile = state.userData!.employeeInfo!.profile!;
globalCurrentProfile = profile;
} else { } else {
profile = globalCurrentProfile!; profile = globalCurrentProfile!;
} }
print(profile.lastName);
return BlocConsumer<ProfileBloc, ProfileState>( return BlocConsumer<ProfileBloc, ProfileState>(
listener: ( listener: (
context, context,
@ -186,6 +199,10 @@ class ProfileInfo extends StatelessWidget {
.basicInfo .basicInfo
.citizenships)), .citizenships)),
child: CitizenShipScreen( child: CitizenShipScreen(
citizenships: state
.profileInformation
.basicInfo
.citizenships,
profileId: profileId!, token: token!), profileId: profileId!, token: token!),
); );
})); }));
@ -402,6 +419,7 @@ class ProfileInfo extends StatelessWidget {
} }
return Container(); return Container();
}), }),
)); )),
);
} }
} }

View File

@ -5,6 +5,7 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttericon/font_awesome_icons.dart'; import 'package:fluttericon/font_awesome_icons.dart';
import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:search_page/search_page.dart';
import 'package:searchfield/searchfield.dart'; import 'package:searchfield/searchfield.dart';
import 'package:unit2/bloc/rbac/rbac_operations/agency/agency_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/agency/agency_bloc.dart';
import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart';
@ -28,6 +29,7 @@ class RbacAgencyScreen extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final formKey = GlobalKey<FormBuilderState>(); final formKey = GlobalKey<FormBuilderState>();
List<Agency> agencies = [];
List<Category> agencyCategory = []; List<Category> agencyCategory = [];
Category? selectedAgencyCategory; Category? selectedAgencyCategory;
bool? isPrivate; bool? isPrivate;
@ -38,7 +40,37 @@ class RbacAgencyScreen extends StatelessWidget {
centerTitle: true, centerTitle: true,
backgroundColor: primary, backgroundColor: primary,
title: const Text("Agencies"), title: const Text("Agencies"),
actions: [ actions: context.watch<AgencyBloc>().state is AgencyLoadingState || context.watch<AgencyBloc>().state is AgencyErrorState || context.watch<AgencyBloc>().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: () { AddLeading(onPressed: () {
parent = context; parent = context;
showDialog( showDialog(
@ -220,6 +252,7 @@ class RbacAgencyScreen extends StatelessWidget {
builder: (context, state) { builder: (context, state) {
final parent = context; final parent = context;
if (state is AgenciesLoaded) { if (state is AgenciesLoaded) {
agencies = state.agencies;
agencyCategory = state.agencyCategory; agencyCategory = state.agencyCategory;
if (state.agencies.isNotEmpty) { if (state.agencies.isNotEmpty) {
return ListView.builder( return ListView.builder(
@ -262,7 +295,7 @@ class RbacAgencyScreen extends StatelessWidget {
}); });
} else { } else {
return const EmptyData( return const EmptyData(
message: "No Object available. Please click + to add."); message: "No Agency available. Please click + to add.");
} }
}if (state is AgencyErrorState) { }if (state is AgencyErrorState) {
return SomethingWentWrong( return SomethingWentWrong(

View File

@ -82,7 +82,7 @@ class _RbacAssignedAreaScreenState extends State<RbacAssignedAreaScreen> {
areaType = null; areaType = null;
return AlertDialog( return AlertDialog(
title: const Text("Add New Role"), title: const Text("Add New Assigned area"),
content: FormBuilder( content: FormBuilder(
key: formKey, key: formKey,
child: StatefulBuilder(builder: (context, setState) { child: StatefulBuilder(builder: (context, setState) {
@ -1005,7 +1005,7 @@ class _RbacAssignedAreaScreenState extends State<RbacAssignedAreaScreen> {
if (state is AssignedAreaDeletedState) { if (state is AssignedAreaDeletedState) {
if (state.success) { if (state.success) {
successAlert(context, "Delete Successfull!", successAlert(context, "Delete Successfull!",
"Role Module Deleted Successfully", () { "Assign Area Deleted Successfully", () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context context
.read<AssignAreaBloc>() .read<AssignAreaBloc>()
@ -1013,7 +1013,7 @@ class _RbacAssignedAreaScreenState extends State<RbacAssignedAreaScreen> {
}); });
} else { } else {
errorAlert( errorAlert(
context, "Delete Failed", "Role Module Delete Failed", context, "Delete Failed", "Assign Area Deletion Failed",
() { () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context context

View File

@ -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_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:form_builder_validators/form_builder_validators.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/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/screens/superadmin/role/shared_pop_up_menu.dart';
import 'package:unit2/widgets/Leadings/add_leading.dart'; import 'package:unit2/widgets/Leadings/add_leading.dart';
import 'package:unit2/widgets/error_state.dart'; import 'package:unit2/widgets/error_state.dart';
@ -23,12 +25,206 @@ class RbacModuleScreen extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final formKey = GlobalKey<FormBuilderState>(); final formKey = GlobalKey<FormBuilderState>();
final bloc = BlocProvider.of<ModuleBloc>(context);
List<RBAC> modules = [];
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
centerTitle: true, centerTitle: true,
backgroundColor: primary, backgroundColor: primary,
title: const Text("Module Screen"), title: const Text("Module Screen"),
actions: [ actions:
context.watch<ModuleBloc>().state is ModuleLoadingState ||
context.watch<ModuleBloc>().state is ModuleErrorState ||
context.watch<ModuleBloc>().state is ModuleAddedState ||
context.watch<ModuleBloc>().state is ModuleDeletedState ||
context.watch<ModuleBloc>().state is ModuleAddedState ||
context.watch<ModuleBloc>().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<int>(
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<ModuleBloc>()
.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: () { AddLeading(onPressed: () {
BuildContext parent = context; BuildContext parent = context;
showDialog( showDialog(
@ -53,17 +249,20 @@ class RbacModuleScreen extends StatelessWidget {
), ),
FormBuilderTextField( FormBuilderTextField(
name: "slug", name: "slug",
decoration: normalTextFieldStyle("Slug ", "Slug"), decoration:
normalTextFieldStyle("Slug ", "Slug"),
), ),
const SizedBox( const SizedBox(
height: 8, height: 8,
), ),
FormBuilderTextField( FormBuilderTextField(
validator: FormBuilderValidators.maxLength(50, validator:
errorText: "Max characters only 50"), FormBuilderValidators.maxLength(50,
errorText:
"Max characters only 50"),
name: "shorthand", name: "shorthand",
decoration: decoration: normalTextFieldStyle(
normalTextFieldStyle("Shorthand ", "Shorthand"), "Shorthand ", "Shorthand"),
), ),
const SizedBox( const SizedBox(
height: 12, height: 12,
@ -72,17 +271,20 @@ class RbacModuleScreen extends StatelessWidget {
width: double.infinity, width: double.infinity,
height: 50, height: 50,
child: ElevatedButton( child: ElevatedButton(
style: mainBtnStyle( style: mainBtnStyle(primary,
primary, Colors.transparent, second), Colors.transparent, second),
onPressed: () { onPressed: () {
if (formKey.currentState! if (formKey.currentState!
.saveAndValidate()) { .saveAndValidate()) {
String name = formKey String name = formKey
.currentState!.value['object_name']; .currentState!
String? slug = .value['object_name'];
formKey.currentState!.value['slug']; String? slug = formKey
.currentState!
.value['slug'];
String? short = formKey String? short = formKey
.currentState!.value['shorthand']; .currentState!
.value['shorthand'];
parent.read<ModuleBloc>().add( parent.read<ModuleBloc>().add(
AddRbacModule( AddRbacModule(
id: id, id: id,
@ -162,7 +364,7 @@ class RbacModuleScreen extends StatelessWidget {
context.read<ModuleBloc>().add(GetModule()); context.read<ModuleBloc>().add(GetModule());
}); });
} else { } else {
errorAlert(context, "Delete Failed", "Module Delete Failed", errorAlert(context, "Delete Failed", "Module Deletion Failed",
() { () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context.read<ModuleBloc>().add(GetModule()); context.read<ModuleBloc>().add(GetModule());
@ -174,6 +376,7 @@ class RbacModuleScreen extends StatelessWidget {
final parent = context; final parent = context;
if (state is ModuleLoaded) { if (state is ModuleLoaded) {
if (state.module.isNotEmpty) { if (state.module.isNotEmpty) {
modules = state.module;
return ListView.builder( return ListView.builder(
padding: padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 10), const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
@ -191,8 +394,12 @@ class RbacModuleScreen extends StatelessWidget {
Expanded( Expanded(
child: Row( child: Row(
children: [ children: [
CircleAvatar(child: Text('${index+1}'),), CircleAvatar(
const SizedBox(width: 12,), child: Text('${index + 1}'),
),
const SizedBox(
width: 12,
),
Text(state.module[index].name!, Text(state.module[index].name!,
style: Theme.of(context) style: Theme.of(context)
.textTheme .textTheme
@ -211,7 +418,8 @@ class RbacModuleScreen extends StatelessWidget {
context: context, context: context,
builder: (BuildContext context) { builder: (BuildContext context) {
return AlertDialog( return AlertDialog(
title: const Text("Update Module"), title:
const Text("Update Module"),
content: FormBuilder( content: FormBuilder(
key: formKey, key: formKey,
child: Column( child: Column(
@ -355,7 +563,7 @@ class RbacModuleScreen extends StatelessWidget {
}); });
} else { } else {
return const EmptyData( return const EmptyData(
message: "No Role available. Please click + to add."); message: "No Module available. Please click + to add.");
} }
} }
if (state is ModuleErrorState) { if (state is ModuleErrorState) {

View File

@ -1,4 +1,3 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart';
@ -33,16 +32,25 @@ class RbacModuleObjectsScreen extends StatelessWidget {
List<ValueItem> selectedValueItemObjects = []; List<ValueItem> selectedValueItemObjects = [];
final formKey = GlobalKey<FormBuilderState>(); final formKey = GlobalKey<FormBuilderState>();
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
centerTitle: true, centerTitle: true,
elevation: 0, elevation: 0,
backgroundColor: primary, backgroundColor: primary,
title: const Text("Module Object Screen"), title: const Text("Module Object Screen"),
actions: [ actions: context.watch<ModuleObjectsBloc>().state
is ModuleObjectLoadingState ||
context.watch<ModuleObjectsBloc>().state
is ModuleObjectsErrorState ||
context.watch<ModuleObjectsBloc>().state
is ModuleObjectAddedState ||
context.watch<ModuleObjectsBloc>().state
is ModuleObjectDeletedState
? []
: [
AddLeading(onPressed: () { AddLeading(onPressed: () {
showDialog( showDialog(
context: NavigationService.navigatorKey.currentState!.context, context:
NavigationService.navigatorKey.currentState!.context,
builder: (BuildContext context) { builder: (BuildContext context) {
valueItemObjects = objects.map((e) { valueItemObjects = objects.map((e) {
return ValueItem(label: e.name!, value: e.name); return ValueItem(label: e.name!, value: e.name);
@ -58,8 +66,8 @@ class RbacModuleObjectsScreen extends StatelessWidget {
validator: FormBuilderValidators.required( validator: FormBuilderValidators.required(
errorText: "This field is required"), errorText: "This field is required"),
name: "module", name: "module",
decoration: decoration: normalTextFieldStyle(
normalTextFieldStyle("Module", "Module"), "Module", "Module"),
items: modules.isEmpty items: modules.isEmpty
? [] ? []
: modules.map((e) { : modules.map((e) {
@ -76,7 +84,8 @@ class RbacModuleObjectsScreen extends StatelessWidget {
MultiSelectDropDown( MultiSelectDropDown(
onOptionSelected: onOptionSelected:
(List<ValueItem> selectedOptions) { (List<ValueItem> selectedOptions) {
selectedValueItemObjects = selectedOptions; selectedValueItemObjects =
selectedOptions;
}, },
borderColor: Colors.grey, borderColor: Colors.grey,
borderWidth: 1, borderWidth: 1,
@ -85,10 +94,11 @@ class RbacModuleObjectsScreen extends StatelessWidget {
padding: const EdgeInsets.all(8), padding: const EdgeInsets.all(8),
options: valueItemObjects, options: valueItemObjects,
selectionType: SelectionType.multi, selectionType: SelectionType.multi,
chipConfig: chipConfig: const ChipConfig(
const ChipConfig(wrapType: WrapType.wrap), wrapType: WrapType.wrap),
dropdownHeight: 300, dropdownHeight: 300,
optionTextStyle: const TextStyle(fontSize: 16), optionTextStyle:
const TextStyle(fontSize: 16),
selectedOptionIcon: selectedOptionIcon:
const Icon(Icons.check_circle), const Icon(Icons.check_circle),
), ),
@ -99,27 +109,31 @@ class RbacModuleObjectsScreen extends StatelessWidget {
height: 50, height: 50,
width: double.maxFinite, width: double.maxFinite,
child: ElevatedButton( child: ElevatedButton(
style: mainBtnStyle( style: mainBtnStyle(primary,
primary, Colors.transparent, second), Colors.transparent, second),
onPressed: () { onPressed: () {
if (formKey.currentState! if (formKey.currentState!
.saveAndValidate() && .saveAndValidate() &&
selectedValueItemObjects.isNotEmpty) { selectedValueItemObjects
.isNotEmpty) {
int assignerId = id; int assignerId = id;
int moduleId = selectedModule!.id!; int moduleId = selectedModule!.id!;
List<int> objectId = []; List<int> objectId = [];
for (var object in objects) { for (var object in objects) {
selectedValueItemObjects selectedValueItemObjects
.forEach((element) { .forEach((element) {
if (element.label.toLowerCase() == if (element.label
object.name?.toLowerCase()) { .toLowerCase() ==
object.name
?.toLowerCase()) {
objectId.add(object.id!); objectId.add(object.id!);
} }
}); });
} }
Navigator.of(context).pop(); Navigator.of(context).pop();
parent.read<ModuleObjectsBloc>().add( parent
AddRbacModuleObjects( .read<ModuleObjectsBloc>()
.add(AddRbacModuleObjects(
assignerId: assignerId, assignerId: assignerId,
moduleId: moduleId, moduleId: moduleId,
objectsId: objectId)); objectsId: objectId));
@ -140,7 +154,6 @@ class RbacModuleObjectsScreen extends StatelessWidget {
indicatorWidget: const SpinKitFadingCircle(color: Colors.white), indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
child: BlocConsumer<ModuleObjectsBloc, ModuleObjectsState>( child: BlocConsumer<ModuleObjectsBloc, ModuleObjectsState>(
listener: (context, state) { listener: (context, state) {
if (state is ModuleObjectLoadingState) { if (state is ModuleObjectLoadingState) {
final progress = ProgressHUD.of(context); final progress = ProgressHUD.of(context);
progress!.showWithText("Please wait..."); progress!.showWithText("Please wait...");
@ -157,13 +170,13 @@ class RbacModuleObjectsScreen extends StatelessWidget {
if (state is ModuleObjectDeletedState) { if (state is ModuleObjectDeletedState) {
if (state.success) { if (state.success) {
successAlert( successAlert(
context, "Delete Successfull!", "Role Deleted Successfully", context, "Delete Successfull!", "Module Object Deleted Successfully",
() { () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context.read<ModuleObjectsBloc>().add(GetModuleObjects()); context.read<ModuleObjectsBloc>().add(GetModuleObjects());
}); });
} else { } else {
errorAlert(context, "Delete Failed", "Role Delete Failed", () { errorAlert(context, "Delete Failed", "Module Object Deletion Failed", () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context.read<ModuleObjectsBloc>().add(GetModuleObjects()); context.read<ModuleObjectsBloc>().add(GetModuleObjects());
}); });
@ -270,19 +283,22 @@ class RbacModuleObjectsScreen extends StatelessWidget {
style: Theme.of(context) style: Theme.of(context)
.textTheme .textTheme
.titleMedium! .titleMedium!
.copyWith(color: primary,fontWeight: FontWeight.bold), .copyWith(
color: primary, fontWeight: FontWeight.bold),
), ),
); );
}, },
); );
} else { } else {
return const EmptyData( return const EmptyData(
message: "No Role available. Please click + to add."); message:
"No Module Object available. Please click + to add.");
} }
} }
if (state is ModuleObjectsErrorState) { if (state is ModuleObjectsErrorState) {
return SomethingWentWrong( return SomethingWentWrong(
message: state.message, onpressed: () { message: state.message,
onpressed: () {
parent.read<ModuleObjectsBloc>().add(GetModuleObjects()); parent.read<ModuleObjectsBloc>().add(GetModuleObjects());
}); });
} }

View File

@ -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_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:form_builder_validators/form_builder_validators.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/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/screens/superadmin/role/shared_pop_up_menu.dart';
import 'package:unit2/widgets/error_state.dart'; import 'package:unit2/widgets/error_state.dart';
import '../../../theme-data.dart/box_shadow.dart'; import '../../../theme-data.dart/box_shadow.dart';
@ -24,12 +26,197 @@ class RbacObjectScreen extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final formKey = GlobalKey<FormBuilderState>(); final formKey = GlobalKey<FormBuilderState>();
final bloc = BlocProvider.of<ObjectBloc>(context);
List<RBAC> objects = [];
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
centerTitle: true, centerTitle: true,
backgroundColor: primary, backgroundColor: primary,
title: const Text("Objects Screen"), title: const Text("Objects Screen"),
actions: [ actions:
context.watch<ObjectBloc>().state is ObjectLoadingState ||
context.watch<ObjectBloc>().state is ObjectAddedState ||
context.watch<ObjectBloc>().state is ObjectErrorState ||
context.watch<ObjectBloc>().state is ObjectDeletedState ||
context.watch<ObjectBloc>().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<int>(
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: () { AddLeading(onPressed: () {
BuildContext parent = context; BuildContext parent = context;
showDialog( showDialog(
@ -54,17 +241,20 @@ class RbacObjectScreen extends StatelessWidget {
), ),
FormBuilderTextField( FormBuilderTextField(
name: "slug", name: "slug",
decoration: normalTextFieldStyle("Slug ", "Slug"), decoration:
normalTextFieldStyle("Slug ", "Slug"),
), ),
const SizedBox( const SizedBox(
height: 8, height: 8,
), ),
FormBuilderTextField( FormBuilderTextField(
validator: FormBuilderValidators.maxLength(50, validator:
errorText: "Max characters only 50"), FormBuilderValidators.maxLength(50,
errorText:
"Max characters only 50"),
name: "shorthand", name: "shorthand",
decoration: decoration: normalTextFieldStyle(
normalTextFieldStyle("Shorthand ", "Shorthand"), "Shorthand ", "Shorthand"),
), ),
const SizedBox( const SizedBox(
height: 12, height: 12,
@ -73,17 +263,20 @@ class RbacObjectScreen extends StatelessWidget {
width: double.infinity, width: double.infinity,
height: 50, height: 50,
child: ElevatedButton( child: ElevatedButton(
style: mainBtnStyle( style: mainBtnStyle(primary,
primary, Colors.transparent, second), Colors.transparent, second),
onPressed: () { onPressed: () {
if (formKey.currentState! if (formKey.currentState!
.saveAndValidate()) { .saveAndValidate()) {
String name = formKey String name = formKey
.currentState!.value['object_name']; .currentState!
String? slug = .value['object_name'];
formKey.currentState!.value['slug']; String? slug = formKey
.currentState!
.value['slug'];
String? short = formKey String? short = formKey
.currentState!.value['shorthand']; .currentState!
.value['shorthand'];
parent.read<ObjectBloc>().add( parent.read<ObjectBloc>().add(
AddRbacObject( AddRbacObject(
id: id, id: id,
@ -162,7 +355,7 @@ class RbacObjectScreen extends StatelessWidget {
context.read<ObjectBloc>().add(GetObjects()); context.read<ObjectBloc>().add(GetObjects());
}); });
} else { } else {
errorAlert(context, "Delete Failed", "Object Delete Failed", errorAlert(context, "Delete Failed", "Object Deletion Failed",
() { () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context.read<ObjectBloc>().add(GetObjects()); context.read<ObjectBloc>().add(GetObjects());
@ -174,6 +367,7 @@ class RbacObjectScreen extends StatelessWidget {
final parent = context; final parent = context;
if (state is ObjectLoaded) { if (state is ObjectLoaded) {
if (state.objects.isNotEmpty) { if (state.objects.isNotEmpty) {
objects = state.objects;
return ListView.builder( return ListView.builder(
padding: padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 10), const EdgeInsets.symmetric(vertical: 8, horizontal: 10),

View File

@ -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_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:form_builder_validators/form_builder_validators.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/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/screens/superadmin/role/shared_pop_up_menu.dart';
import 'package:unit2/widgets/error_state.dart'; import 'package:unit2/widgets/error_state.dart';
import '../../../theme-data.dart/box_shadow.dart'; import '../../../theme-data.dart/box_shadow.dart';
@ -24,11 +26,203 @@ class RbacOperationScreen extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final formKey = GlobalKey<FormBuilderState>(); final formKey = GlobalKey<FormBuilderState>();
final bloc = BlocProvider.of<OperationBloc>(context);
List<RBAC> operations = [];
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
backgroundColor: primary, backgroundColor: primary,
title: const Text("Operations Screen"), title: const Text("Operations Screen"),
actions: [ centerTitle: true,
actions: context.watch<OperationBloc>().state
is OperationLoadingState ||
context.watch<OperationBloc>().state is OperationErrorState ||
context.watch<OperationBloc>().state is OperationAddedState ||
context.watch<OperationBloc>().state is OperationDeletedState ||
context.watch<OperationBloc>().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<int>(
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<OperationBloc>()
.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: () { AddLeading(onPressed: () {
BuildContext parent = context; BuildContext parent = context;
showDialog( showDialog(
@ -53,7 +247,8 @@ class RbacOperationScreen extends StatelessWidget {
), ),
FormBuilderTextField( FormBuilderTextField(
name: "slug", name: "slug",
decoration: normalTextFieldStyle("Slug ", "Slug"), decoration:
normalTextFieldStyle("Slug ", "Slug"),
), ),
const SizedBox( const SizedBox(
height: 8, height: 8,
@ -62,8 +257,8 @@ class RbacOperationScreen extends StatelessWidget {
validator: FormBuilderValidators.maxLength(50, validator: FormBuilderValidators.maxLength(50,
errorText: "Max characters only 50"), errorText: "Max characters only 50"),
name: "shorthand", name: "shorthand",
decoration: decoration: normalTextFieldStyle(
normalTextFieldStyle("Shorthand ", "Shorthand"), "Shorthand ", "Shorthand"),
), ),
const SizedBox( const SizedBox(
height: 12, height: 12,
@ -72,17 +267,18 @@ class RbacOperationScreen extends StatelessWidget {
width: double.infinity, width: double.infinity,
height: 50, height: 50,
child: ElevatedButton( child: ElevatedButton(
style: mainBtnStyle( style: mainBtnStyle(primary,
primary, Colors.transparent, second), Colors.transparent, second),
onPressed: () { onPressed: () {
if (formKey.currentState! if (formKey.currentState!
.saveAndValidate()) { .saveAndValidate()) {
String name = formKey String name = formKey.currentState!
.currentState!.value['object_name']; .value['object_name'];
String? slug = String? slug = formKey
formKey.currentState!.value['slug']; .currentState!.value['slug'];
String? short = formKey String? short = formKey
.currentState!.value['shorthand']; .currentState!
.value['shorthand'];
parent.read<OperationBloc>().add( parent.read<OperationBloc>().add(
AddRbacOperation( AddRbacOperation(
id: id, id: id,
@ -162,8 +358,8 @@ class RbacOperationScreen extends StatelessWidget {
context.read<OperationBloc>().add(GetOperations()); context.read<OperationBloc>().add(GetOperations());
}); });
} else { } else {
errorAlert(context, "Delete Failed", "Operation Delete Failed", errorAlert(
() { context, "Delete Failed", "Operation Deletion Failed", () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context.read<OperationBloc>().add(GetOperations()); context.read<OperationBloc>().add(GetOperations());
}); });
@ -174,6 +370,7 @@ class RbacOperationScreen extends StatelessWidget {
final parent = context; final parent = context;
if (state is OperationsLoaded) { if (state is OperationsLoaded) {
if (state.operations.isNotEmpty) { if (state.operations.isNotEmpty) {
operations = state.operations;
return ListView.builder( return ListView.builder(
padding: padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 10), const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
@ -191,8 +388,12 @@ class RbacOperationScreen extends StatelessWidget {
Expanded( Expanded(
child: Row( child: Row(
children: [ children: [
CircleAvatar(child: Text('${index+1}'),), CircleAvatar(
const SizedBox(width: 12,), child: Text('${index + 1}'),
),
const SizedBox(
width: 12,
),
Text(state.operations[index].name!, Text(state.operations[index].name!,
style: Theme.of(context) style: Theme.of(context)
.textTheme .textTheme
@ -211,7 +412,8 @@ class RbacOperationScreen extends StatelessWidget {
context: context, context: context,
builder: (BuildContext context) { builder: (BuildContext context) {
return AlertDialog( return AlertDialog(
title: const Text("Update Operation"), title: const Text(
"Update Operation"),
content: FormBuilder( content: FormBuilder(
key: formKey, key: formKey,
child: Column( child: Column(
@ -355,7 +557,7 @@ class RbacOperationScreen extends StatelessWidget {
}); });
} else { } else {
return const EmptyData( return const EmptyData(
message: "No Role available. Please click + to add."); message: "No Operation available. Please click + to add.");
} }
} }
if (state is OperationErrorState) { if (state is OperationErrorState) {

View File

@ -7,7 +7,9 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:multi_dropdown/multiselect_dropdown.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/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/model/rbac/rbac.dart';
import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart';
import 'package:unit2/theme-data.dart/btn-style.dart'; import 'package:unit2/theme-data.dart/btn-style.dart';
@ -32,6 +34,8 @@ class RbacPermissionScreen extends StatelessWidget {
List<RBAC> operations = []; List<RBAC> operations = [];
List<ValueItem> valueItemOperations = []; List<ValueItem> valueItemOperations = [];
List<ValueItem> selectedValueItemOperations = []; List<ValueItem> selectedValueItemOperations = [];
List<RBACPermission> permissions = [];
final bloc = BlocProvider.of<PermissionBloc>(context);
final formKey = GlobalKey<FormBuilderState>(); final formKey = GlobalKey<FormBuilderState>();
BuildContext? parent; BuildContext? parent;
return Scaffold( return Scaffold(
@ -39,10 +43,92 @@ class RbacPermissionScreen extends StatelessWidget {
centerTitle: true, centerTitle: true,
backgroundColor: primary, backgroundColor: primary,
title: const Text("Permissions Screen"), title: const Text("Permissions Screen"),
actions: [ actions: context.watch<PermissionBloc>().state is PermissonLoadingState ||
context.watch<PermissionBloc>().state is PermissionErrorState ||
context.watch<PermissionBloc>().state is PermissionDeletedState ||
context.watch<PermissionBloc>().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<int>(
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 :("),
),
items: permissions,
searchLabel: "Search Permission",
suggestion: const Center(
child: Text("Search permission by name"),
)),
);
},
icon: const Icon(Icons.search)),
AddLeading(onPressed: () { AddLeading(onPressed: () {
showDialog( showDialog(
context: NavigationService.navigatorKey.currentState!.context, context:
NavigationService.navigatorKey.currentState!.context,
builder: (BuildContext context) { builder: (BuildContext context) {
valueItemOperations = operations.map((e) { valueItemOperations = operations.map((e) {
return ValueItem(label: e.name!, value: e.name); return ValueItem(label: e.name!, value: e.name);
@ -58,8 +144,8 @@ class RbacPermissionScreen extends StatelessWidget {
validator: FormBuilderValidators.required( validator: FormBuilderValidators.required(
errorText: "This field is required"), errorText: "This field is required"),
name: "object", name: "object",
decoration: decoration: normalTextFieldStyle(
normalTextFieldStyle("Permission", "Permission"), "Permission", "Permission"),
items: objects.isEmpty items: objects.isEmpty
? [] ? []
: objects.map((e) { : objects.map((e) {
@ -76,7 +162,8 @@ class RbacPermissionScreen extends StatelessWidget {
MultiSelectDropDown( MultiSelectDropDown(
onOptionSelected: onOptionSelected:
(List<ValueItem> selectedOptions) { (List<ValueItem> selectedOptions) {
selectedValueItemOperations = selectedOptions; selectedValueItemOperations =
selectedOptions;
}, },
borderColor: Colors.grey, borderColor: Colors.grey,
borderWidth: 1, borderWidth: 1,
@ -85,10 +172,11 @@ class RbacPermissionScreen extends StatelessWidget {
padding: const EdgeInsets.all(8), padding: const EdgeInsets.all(8),
options: valueItemOperations, options: valueItemOperations,
selectionType: SelectionType.multi, selectionType: SelectionType.multi,
chipConfig: chipConfig: const ChipConfig(
const ChipConfig(wrapType: WrapType.wrap), wrapType: WrapType.wrap),
dropdownHeight: 300, dropdownHeight: 300,
optionTextStyle: const TextStyle(fontSize: 16), optionTextStyle:
const TextStyle(fontSize: 16),
selectedOptionIcon: selectedOptionIcon:
const Icon(Icons.check_circle), const Icon(Icons.check_circle),
), ),
@ -99,8 +187,8 @@ class RbacPermissionScreen extends StatelessWidget {
height: 50, height: 50,
width: double.maxFinite, width: double.maxFinite,
child: ElevatedButton( child: ElevatedButton(
style: mainBtnStyle( style: mainBtnStyle(primary,
primary, Colors.transparent, second), Colors.transparent, second),
onPressed: () { onPressed: () {
if (formKey.currentState! if (formKey.currentState!
.saveAndValidate() && .saveAndValidate() &&
@ -113,8 +201,10 @@ class RbacPermissionScreen extends StatelessWidget {
for (var operation in operations) { for (var operation in operations) {
selectedValueItemOperations selectedValueItemOperations
.forEach((element) { .forEach((element) {
if (element.label.toLowerCase() == if (element.label
operation.name?.toLowerCase()) { .toLowerCase() ==
operation.name
?.toLowerCase()) {
opIds.add(operation.id!); opIds.add(operation.id!);
} }
}); });
@ -179,8 +269,8 @@ class RbacPermissionScreen extends StatelessWidget {
context.read<PermissionBloc>().add(GetPermissions()); context.read<PermissionBloc>().add(GetPermissions());
}); });
} else { } else {
errorAlert(context, "Delete Failed", "Permission Delete Failed", errorAlert(
() { context, "Delete Failed", "Permission Deletion Failed", () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context.read<PermissionBloc>().add(GetPermissions()); context.read<PermissionBloc>().add(GetPermissions());
}); });
@ -193,6 +283,7 @@ class RbacPermissionScreen extends StatelessWidget {
objects = state.objects; objects = state.objects;
operations = state.operations; operations = state.operations;
if (state.permissions.isNotEmpty) { if (state.permissions.isNotEmpty) {
permissions = state.permissions;
return ListView.builder( return ListView.builder(
padding: padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 10), const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
@ -233,17 +324,15 @@ class RbacPermissionScreen extends StatelessWidget {
elevation: 3, elevation: 3,
onSelected: (value) { onSelected: (value) {
if (value == 1) { if (value == 1) {
confirmAlert(context, () { confirmAlert(context, () {
context.read<PermissionBloc>().add( context.read<PermissionBloc>().add(
DeleteRbacPermission( DeleteRbacPermission(
permissionId: state.permissions[index].id!)); permissionId: state
.permissions[index].id!));
}, "Delete?", "Confirm Delete?"); }, "Delete?", "Confirm Delete?");
} }
}, },
menuItems: [ menuItems: [
popMenuItem( popMenuItem(
text: "Remove", text: "Remove",
value: 1, value: 1,
@ -271,7 +360,8 @@ class RbacPermissionScreen extends StatelessWidget {
} }
if (state is PermissionErrorState) { if (state is PermissionErrorState) {
return SomethingWentWrong( return SomethingWentWrong(
message: state.message, onpressed: () { message: state.message,
onpressed: () {
parent!.read<PermissionBloc>().add(GetPermissions()); parent!.read<PermissionBloc>().add(GetPermissions());
}); });
} }

View File

@ -5,9 +5,7 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:group_list_view/group_list_view.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: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/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart';
import 'package:unit2/model/rbac/permission.dart'; import 'package:unit2/model/rbac/permission.dart';
import 'package:unit2/model/rbac/rbac.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/colors.dart';
import 'package:unit2/theme-data.dart/form-style.dart'; import 'package:unit2/theme-data.dart/form-style.dart';
import 'package:unit2/utils/alerts.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/Leadings/add_leading.dart';
import 'package:unit2/widgets/empty_data.dart'; import 'package:unit2/widgets/empty_data.dart';
import 'package:unit2/widgets/error_state.dart'; import 'package:unit2/widgets/error_state.dart';
@ -40,7 +37,16 @@ class RbacPermissionAssignmentScreen extends StatelessWidget {
centerTitle: true, centerTitle: true,
backgroundColor: primary, backgroundColor: primary,
title: const Text("Permission Assignment"), title: const Text("Permission Assignment"),
actions: [ actions: context.watch<PermissionAssignmentBloc>().state
is PermissionAssignmentLoadingScreen ||
context.watch<PermissionAssignmentBloc>().state
is PermissionAssignmentErrorState ||
context.watch<PermissionAssignmentBloc>().state
is PermissionAssignmentAddedState ||
context.watch<PermissionAssignmentBloc>().state
is PermissionAssignmentDeletedState
? []
: [
AddLeading(onPressed: () { AddLeading(onPressed: () {
showDialog( showDialog(
context: context, context: context,
@ -61,7 +67,8 @@ class RbacPermissionAssignmentScreen extends StatelessWidget {
validator: FormBuilderValidators.required( validator: FormBuilderValidators.required(
errorText: "This field is required"), errorText: "This field is required"),
name: "role", name: "role",
decoration: normalTextFieldStyle("Role", "Role"), decoration:
normalTextFieldStyle("Role", "Role"),
items: roles.isEmpty items: roles.isEmpty
? [] ? []
: roles.map((e) { : roles.map((e) {
@ -76,8 +83,10 @@ class RbacPermissionAssignmentScreen extends StatelessWidget {
height: 12, height: 12,
), ),
MultiSelectDropDown( MultiSelectDropDown(
onOptionSelected: (List<ValueItem> selectedOptions) { onOptionSelected:
selectedValueItemPermission = selectedOptions; (List<ValueItem> selectedOptions) {
selectedValueItemPermission =
selectedOptions;
}, },
borderColor: Colors.grey, borderColor: Colors.grey,
borderWidth: 1, borderWidth: 1,
@ -86,10 +95,13 @@ class RbacPermissionAssignmentScreen extends StatelessWidget {
padding: const EdgeInsets.all(8), padding: const EdgeInsets.all(8),
options: valueItemPermission, options: valueItemPermission,
selectionType: SelectionType.multi, selectionType: SelectionType.multi,
chipConfig: const ChipConfig(wrapType: WrapType.wrap), chipConfig: const ChipConfig(
wrapType: WrapType.wrap),
dropdownHeight: 300, dropdownHeight: 300,
optionTextStyle: const TextStyle(fontSize: 16), optionTextStyle:
selectedOptionIcon: const Icon(Icons.check_circle), const TextStyle(fontSize: 16),
selectedOptionIcon:
const Icon(Icons.check_circle),
), ),
const SizedBox( const SizedBox(
height: 12, height: 12,
@ -98,20 +110,25 @@ class RbacPermissionAssignmentScreen extends StatelessWidget {
height: 50, height: 50,
width: double.maxFinite, width: double.maxFinite,
child: ElevatedButton( child: ElevatedButton(
style: mainBtnStyle( style: mainBtnStyle(primary,
primary, Colors.transparent, second), Colors.transparent, second),
onPressed: () { onPressed: () {
if (formKey.currentState!.saveAndValidate() && if (formKey.currentState!
selectedValueItemPermission.isNotEmpty) { .saveAndValidate() &&
selectedValueItemPermission
.isNotEmpty) {
int assignerId = id; int assignerId = id;
int roleId = selectedRole!.id!; int roleId = selectedRole!.id!;
List<int> opIds = List<int> opIds =
selectedValueItemPermission.map((e) { selectedValueItemPermission
.map((e) {
return int.parse(e.value!); return int.parse(e.value!);
}).toList(); }).toList();
Navigator.pop(context); Navigator.pop(context);
parent.read<PermissionAssignmentBloc>().add( parent
AddPersmissionAssignment( .read<
PermissionAssignmentBloc>()
.add(AddPersmissionAssignment(
assignerId: assignerId, assignerId: assignerId,
opsId: opIds, opsId: opIds,
roleId: roleId)); roleId: roleId));
@ -183,7 +200,6 @@ class RbacPermissionAssignmentScreen extends StatelessWidget {
} }
}, },
builder: (context, state) { builder: (context, state) {
if (state is PermissionAssignmentLoadedState) { if (state is PermissionAssignmentLoadedState) {
if (state.permissionAssignments.isNotEmpty) { if (state.permissionAssignments.isNotEmpty) {
permissions = state.permissions; permissions = state.permissions;

View File

@ -25,6 +25,7 @@ class RbacRoleScreen extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final bloc = BlocProvider.of<RoleBloc>(context);
final formKey = GlobalKey<FormBuilderState>(); final formKey = GlobalKey<FormBuilderState>();
List<RBAC> roles = []; List<RBAC> roles = [];
return Scaffold( return Scaffold(
@ -32,16 +33,181 @@ class RbacRoleScreen extends StatelessWidget {
centerTitle: true, centerTitle: true,
backgroundColor: primary, backgroundColor: primary,
title: const Text("Role Screen"), title: const Text("Role Screen"),
actions: [ actions:
context.watch<RoleBloc>().state is RoleLoadingState ||
context.watch<RoleBloc>().state is RoleErrorState ||
context.watch<RoleBloc>().state is RoleDeletedState? ||
context.watch<RoleBloc>().state is RoleAddedState? ||
context.watch<RoleBloc>().state is RoleUpdatedState
? []
: [
IconButton( IconButton(
onPressed: () { onPressed: () {
showSearch( showSearch(
context: context, context: context,
delegate: SearchPage( delegate: SearchPage(
barTheme: ThemeData(cardColor: primary), barTheme: ThemeData(cardColor: Colors.white),
builder: (RBAC rbac) { builder: (RBAC rbac) {
return ListTile( return Column(
title: Text(rbac.name!), 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<int>(
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) { filter: (RBAC rbac) {
@ -82,17 +248,20 @@ class RbacRoleScreen extends StatelessWidget {
), ),
FormBuilderTextField( FormBuilderTextField(
name: "slug", name: "slug",
decoration: normalTextFieldStyle("Slug ", "Slug"), decoration:
normalTextFieldStyle("Slug ", "Slug"),
), ),
const SizedBox( const SizedBox(
height: 8, height: 8,
), ),
FormBuilderTextField( FormBuilderTextField(
validator: FormBuilderValidators.maxLength(50, validator:
errorText: "Max characters only 50"), FormBuilderValidators.maxLength(50,
errorText:
"Max characters only 50"),
name: "shorthand", name: "shorthand",
decoration: decoration: normalTextFieldStyle(
normalTextFieldStyle("Shorthand ", "Shorthand"), "Shorthand ", "Shorthand"),
), ),
const SizedBox( const SizedBox(
height: 12, height: 12,
@ -101,18 +270,22 @@ class RbacRoleScreen extends StatelessWidget {
width: double.infinity, width: double.infinity,
height: 50, height: 50,
child: ElevatedButton( child: ElevatedButton(
style: mainBtnStyle( style: mainBtnStyle(primary,
primary, Colors.transparent, second), Colors.transparent, second),
onPressed: () { onPressed: () {
if (formKey.currentState! if (formKey.currentState!
.saveAndValidate()) { .saveAndValidate()) {
String name = formKey String name = formKey
.currentState!.value['object_name']; .currentState!
String? slug = .value['object_name'];
formKey.currentState!.value['slug']; String? slug = formKey
.currentState!
.value['slug'];
String? short = formKey String? short = formKey
.currentState!.value['shorthand']; .currentState!
parent.read<RoleBloc>().add(AddRbacRole( .value['shorthand'];
parent.read<RoleBloc>().add(
AddRbacRole(
id: id, id: id,
name: name, name: name,
shorthand: short, shorthand: short,

View File

@ -36,7 +36,7 @@ class RbacRoleAssignment extends StatelessWidget {
centerTitle: true, centerTitle: true,
backgroundColor: primary, backgroundColor: primary,
title: const Text("User Roles Screens"), title: const Text("User Roles Screens"),
actions: [ actions: context.watch<RoleAssignmentBloc>().state is RoleAssignmentLoadingState || context.watch<RoleAssignmentBloc>().state is RoleAssignmentErrorState || context.watch<RoleAssignmentBloc>().state is UserNotExistError || context.watch<RoleAssignmentBloc>().state is RoleAddedState? []: [
AddLeading(onPressed: () { AddLeading(onPressed: () {
BuildContext parent = context; BuildContext parent = context;
showDialog( showDialog(
@ -131,13 +131,13 @@ class RbacRoleAssignment extends StatelessWidget {
if (state is AssignedRoleDeletedState) { if (state is AssignedRoleDeletedState) {
if (state.success) { if (state.success) {
successAlert(context, "Delete Successfull!", successAlert(context, "Delete Successfull!",
"Role Module Deleted Successfully", () { "Role Deleted Successfully", () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context.read<RoleAssignmentBloc>().add(LoadAssignedRole()); context.read<RoleAssignmentBloc>().add(LoadAssignedRole());
}); });
} else { } else {
errorAlert( errorAlert(
context, "Delete Failed", "Role Module Delete Failed", () { context, "Delete Failed", "Role Deletion Failed", () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context.read<RoleAssignmentBloc>().add(LoadAssignedRole()); context.read<RoleAssignmentBloc>().add(LoadAssignedRole());
}); });

View File

@ -36,7 +36,7 @@ class RbacRoleExtendScreen extends StatelessWidget {
elevation: 0, elevation: 0,
backgroundColor: primary, backgroundColor: primary,
title: const Text("Role Extend"), title: const Text("Role Extend"),
actions: [ actions: context.watch<RoleExtendBloc>().state is RoleExtendLoadingState || context.watch<RoleExtendBloc>().state is RoleExtendErrorState || context.watch<RoleExtendBloc>().state is RoleExtendAddedState || context.watch<RoleExtendBloc>().state is RoleExtendDeletedState? []:[
AddLeading(onPressed: () { AddLeading(onPressed: () {
showDialog( showDialog(
context: NavigationService.navigatorKey.currentState!.context, context: NavigationService.navigatorKey.currentState!.context,

View File

@ -34,11 +34,19 @@ class RbacRoleModuleScreen extends StatelessWidget {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
backgroundColor: primary, backgroundColor: primary,
title: const Text("Role Modules Screen"), title: const Text("Role Module Screen" ),
actions: [ centerTitle: true,
actions: context.watch<RoleModuleBloc>().state
is RoleModuleLoadingState ||
context.watch<RoleModuleBloc>().state is RoleModuleErrorState ||
context.watch<RoleModuleBloc>().state is RoleModuleAddedState ||
context.watch<RoleModuleBloc>().state is RoleModuleDeletedState
? []
: [
AddLeading(onPressed: () { AddLeading(onPressed: () {
showDialog( showDialog(
context: NavigationService.navigatorKey.currentState!.context, context:
NavigationService.navigatorKey.currentState!.context,
builder: (BuildContext context) { builder: (BuildContext context) {
valueItemModules = modules.map((e) { valueItemModules = modules.map((e) {
return ValueItem(label: e.name!, value: e.name); return ValueItem(label: e.name!, value: e.name);
@ -54,7 +62,8 @@ class RbacRoleModuleScreen extends StatelessWidget {
validator: FormBuilderValidators.required( validator: FormBuilderValidators.required(
errorText: "This field is required"), errorText: "This field is required"),
name: "role", name: "role",
decoration: normalTextFieldStyle("Role", "Role"), decoration:
normalTextFieldStyle("Role", "Role"),
items: roles.isEmpty items: roles.isEmpty
? [] ? []
: roles.map((e) { : roles.map((e) {
@ -71,7 +80,8 @@ class RbacRoleModuleScreen extends StatelessWidget {
MultiSelectDropDown( MultiSelectDropDown(
onOptionSelected: onOptionSelected:
(List<ValueItem> selectedOptions) { (List<ValueItem> selectedOptions) {
selectedValueItemModules = selectedOptions; selectedValueItemModules =
selectedOptions;
}, },
borderColor: Colors.grey, borderColor: Colors.grey,
borderWidth: 1, borderWidth: 1,
@ -80,10 +90,11 @@ class RbacRoleModuleScreen extends StatelessWidget {
padding: const EdgeInsets.all(8), padding: const EdgeInsets.all(8),
options: valueItemModules, options: valueItemModules,
selectionType: SelectionType.multi, selectionType: SelectionType.multi,
chipConfig: chipConfig: const ChipConfig(
const ChipConfig(wrapType: WrapType.wrap), wrapType: WrapType.wrap),
dropdownHeight: 300, dropdownHeight: 300,
optionTextStyle: const TextStyle(fontSize: 16), optionTextStyle:
const TextStyle(fontSize: 16),
selectedOptionIcon: selectedOptionIcon:
const Icon(Icons.check_circle), const Icon(Icons.check_circle),
), ),
@ -94,20 +105,23 @@ class RbacRoleModuleScreen extends StatelessWidget {
height: 50, height: 50,
width: double.maxFinite, width: double.maxFinite,
child: ElevatedButton( child: ElevatedButton(
style: mainBtnStyle( style: mainBtnStyle(primary,
primary, Colors.transparent, second), Colors.transparent, second),
onPressed: () { onPressed: () {
if (formKey.currentState! if (formKey.currentState!
.saveAndValidate() && .saveAndValidate() &&
selectedValueItemModules.isNotEmpty) { selectedValueItemModules
.isNotEmpty) {
int assignerId = id; int assignerId = id;
int roleId = selectedRole!.id!; int roleId = selectedRole!.id!;
List<int> modulesId = []; List<int> modulesId = [];
for (var module in modules) { for (var module in modules) {
selectedValueItemModules selectedValueItemModules
.forEach((element) { .forEach((element) {
if (element.label.toLowerCase() == if (element.label
module.name?.toLowerCase()) { .toLowerCase() ==
module.name
?.toLowerCase()) {
modulesId.add(module.id!); modulesId.add(module.id!);
} }
}); });
@ -156,7 +170,7 @@ class RbacRoleModuleScreen extends StatelessWidget {
}); });
} else { } else {
errorAlert( errorAlert(
context, "Delete Failed", "Role Module Delete Failed", () { context, "Delete Failed", "Role Module Deletion Failed", () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context.read<RoleModuleBloc>().add(GetRoleModules()); context.read<RoleModuleBloc>().add(GetRoleModules());
}); });
@ -258,19 +272,21 @@ class RbacRoleModuleScreen extends StatelessWidget {
style: Theme.of(context) style: Theme.of(context)
.textTheme .textTheme
.titleMedium! .titleMedium!
.copyWith(color: primary,fontWeight: FontWeight.bold), .copyWith(
color: primary, fontWeight: FontWeight.bold),
), ),
); );
}, },
); );
} else { } else {
return const EmptyData( return const EmptyData(
message: "No Role available. Please click + to add."); message: "No Role Module available. Please click + to add.");
} }
} }
if (state is RoleModuleErrorState) { if (state is RoleModuleErrorState) {
return SomethingWentWrong( return SomethingWentWrong(
message: state.message, onpressed: () { message: state.message,
onpressed: () {
context.read<RoleModuleBloc>().add(GetRoleModules()); context.read<RoleModuleBloc>().add(GetRoleModules());
}); });
} }

View File

@ -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<String, List<Content>> rolesUnder = {};
List<RBAC> roles = [];
RBAC? selectedRole;
List<ValueItem> valueItemRoles = [];
List<ValueItem> selectedValueItemRoles = [];
final formKey = GlobalKey<FormBuilderState>();
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: primary,
title: const Text("Assignable Roles"),
actions: context.watch<RolesUnderBloc>().state
is RoleUnderLoadingState? ||
context.watch<RolesUnderBloc>().state is RoleUnderErrorState ||
context.watch<RolesUnderBloc>().state
is RoleUnderDeletedState ||
context.watch<RolesUnderBloc>().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<RBAC>(
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<ValueItem> 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<int> 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<RolesUnderBloc>().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<RolesUnderBloc, RolesUnderState>(
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<RolesUnderBloc>().add(GetRolesUnder());
});
} else {
errorAlert(
context, "Delete Failed", "Role Module Delete Failed", () {
Navigator.of(context).pop();
context.read<RolesUnderBloc>().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<RolesUnderBloc>().add(GetRolesUnder());
});
} else {
errorAlert(context, "Adding Failed", state.response['message'],
() {
Navigator.of(context).pop();
context.read<RolesUnderBloc>().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<RolesUnderBloc>().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<RolesUnderBloc>().add(GetRolesUnder());
});
}
return Container();
},
),
),
);
}
}
class Content {
final int id;
final String name;
const Content({required this.id, required this.name});
}

View File

@ -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<String, List<Content>> rolesUnder = {};
List<RBAC> roles = [];
RBAC? selectedRole;
List<ValueItem> valueItemRoles = [];
List<ValueItem> selectedValueItemRoles = [];
final formKey = GlobalKey<FormBuilderState>();
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<RBAC>(
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<ValueItem> 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<int> 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<RolesUnderBloc>().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<RolesUnderBloc, RolesUnderState>(
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<RolesUnderBloc>().add(GetRolesUnder());
});
} else {
errorAlert(
context, "Delete Failed", "Role Module Delete Failed", () {
Navigator.of(context).pop();
context.read<RolesUnderBloc>().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<RolesUnderBloc>().add(GetRolesUnder());
});
} else {
errorAlert(context, "Adding Failed", state.response['message'],
() {
Navigator.of(context).pop();
context.read<RolesUnderBloc>().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<RolesUnderBloc>().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<RolesUnderBloc>().add(GetRolesUnder());
});
}
return Container();
},
),
),
);
}
}
class Content {
final int id;
final String name;
const Content({required this.id, required this.name});
}

View File

@ -5,7 +5,6 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:searchfield/searchfield.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/bloc/rbac/rbac_operations/station/station_bloc.dart';
import 'package:unit2/model/rbac/rbac_station.dart'; import 'package:unit2/model/rbac/rbac_station.dart';
import 'package:unit2/model/utils/agency.dart'; import 'package:unit2/model/utils/agency.dart';
@ -62,7 +61,12 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
centerTitle: true, centerTitle: true,
backgroundColor: primary, backgroundColor: primary,
title: const Text("Station Screen"), title: const Text("Station Screen"),
actions: [ actions: context.watch<StationBloc>().state is StationLoadingState ||
context.watch<StationBloc>().state is StationErrorState ||
context.watch<StationBloc>().state is RbacStationAddedState ||
context.watch<StationBloc>().state is FilterStationState
? []
: [
AddLeading(onPressed: () { AddLeading(onPressed: () {
BuildContext parent = context; BuildContext parent = context;
mainParentStations = []; mainParentStations = [];
@ -82,7 +86,8 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
content: SingleChildScrollView( content: SingleChildScrollView(
child: FormBuilder( child: FormBuilder(
key: formKey, key: formKey,
child: StatefulBuilder(builder: (context, setState) { child:
StatefulBuilder(builder: (context, setState) {
return Column( return Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
@ -119,7 +124,8 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
: mainParentStations.map((e) { : mainParentStations.map((e) {
return DropdownMenuItem( return DropdownMenuItem(
value: e, value: e,
child: Text(e.stationName!), child: Text(
e.stationName!),
); );
}).toList(), }).toList(),
onChanged: (RbacStation? e) { onChanged: (RbacStation? e) {
@ -128,18 +134,20 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
parentStations = []; parentStations = [];
for (RbacStation station for (RbacStation station
in stations) { in stations) {
if (station.mainParentStation == if (station
.mainParentStation ==
selectedMainParentStation! selectedMainParentStation!
.id) { .id) {
parentStations.add(station); parentStations
.add(station);
} }
} }
parentStations.add( parentStations.add(
selectedMainParentStation!); selectedMainParentStation!);
}); });
}, },
validator: validator: FormBuilderValidators
FormBuilderValidators.required( .required(
errorText: errorText:
"This field is required"), "This field is required"),
), ),
@ -153,7 +161,8 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
? const SizedBox.shrink() ? const SizedBox.shrink()
: FormBuilderDropdown<RbacStation>( : FormBuilderDropdown<RbacStation>(
decoration: normalTextFieldStyle( decoration: normalTextFieldStyle(
"Parent Station", "Parent Station"), "Parent Station",
"Parent Station"),
name: "parent-stations", name: "parent-stations",
onChanged: (RbacStation? e) { onChanged: (RbacStation? e) {
setState(() { setState(() {
@ -165,11 +174,12 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
: parentStations.map((e) { : parentStations.map((e) {
return DropdownMenuItem( return DropdownMenuItem(
value: e, value: e,
child: Text(e.stationName!), child: Text(
e.stationName!),
); );
}).toList(), }).toList(),
validator: validator: FormBuilderValidators
FormBuilderValidators.required( .required(
errorText: errorText:
"This field is required"), "This field is required"),
), ),
@ -180,21 +190,22 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
////Station Type ////Station Type
SearchField( SearchField(
itemHeight: 50, itemHeight: 50,
suggestionsDecoration: searchFieldDecoration(), suggestionsDecoration:
searchFieldDecoration(),
suggestions: stationTypes suggestions: stationTypes
.map((StationType stationType) => .map((StationType stationType) =>
SearchFieldListItem( SearchFieldListItem(
stationType.typeName!, stationType.typeName!,
item: stationType, item: stationType,
child: Padding( child: Padding(
padding: padding: const EdgeInsets
const EdgeInsets.symmetric( .symmetric(
horizontal: 10), horizontal: 10),
child: ListTile( child: ListTile(
title: Text( title: Text(
stationType.typeName!, stationType.typeName!,
overflow: TextOverflow.visible, overflow:
TextOverflow.visible,
)), )),
))) )))
.toList(), .toList(),
@ -206,11 +217,14 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
}, },
focusNode: stationTypeFocusNode, focusNode: stationTypeFocusNode,
searchInputDecoration: searchInputDecoration:
normalTextFieldStyle("Station Type *", "") normalTextFieldStyle(
"Station Type *", "")
.copyWith( .copyWith(
suffixIcon: GestureDetector( suffixIcon: GestureDetector(
onTap: () => stationTypeFocusNode.unfocus(), onTap: () =>
child: const Icon(Icons.arrow_drop_down), stationTypeFocusNode.unfocus(),
child:
const Icon(Icons.arrow_drop_down),
)), )),
onSuggestionTap: (position) { onSuggestionTap: (position) {
setState(() { setState(() {
@ -223,10 +237,12 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
controller: addStationTypeController, controller: addStationTypeController,
onpressed: () { onpressed: () {
setState(() { setState(() {
StationType stationType = StationType( StationType stationType =
StationType(
id: null, id: null,
typeName: typeName:
addStationTypeController.text, addStationTypeController
.text,
color: null, color: null,
order: null, order: null,
isActive: null, isActive: null,
@ -270,7 +286,8 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
"Location of the station within this parent?", "Location of the station within this parent?",
'Location of the station within this parent?'), 'Location of the station within this parent?'),
name: 'isWithinParent', name: 'isWithinParent',
title: Text(isWithinParent ? "YES" : "NO"), title:
Text(isWithinParent ? "YES" : "NO"),
), ),
const SizedBox( const SizedBox(
height: 12, height: 12,
@ -280,12 +297,13 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
children: [ children: [
Flexible( Flexible(
child: FormBuilderTextField( child: FormBuilderTextField(
validator: validator: FormBuilderValidators
FormBuilderValidators.required( .required(
errorText: errorText:
"This Field is required"), "This Field is required"),
decoration: normalTextFieldStyle( decoration: normalTextFieldStyle(
"Station name", "Station name"), "Station name",
"Station name"),
name: "station-name"), name: "station-name"),
), ),
const SizedBox( const SizedBox(
@ -294,8 +312,8 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
//// Acronym //// Acronym
Flexible( Flexible(
child: FormBuilderTextField( child: FormBuilderTextField(
validator: validator: FormBuilderValidators
FormBuilderValidators.required( .required(
errorText: errorText:
"This Field is required"), "This Field is required"),
decoration: normalTextFieldStyle( decoration: normalTextFieldStyle(
@ -349,10 +367,11 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
isHospital = !isHospital; isHospital = !isHospital;
}); });
}, },
decoration: decoration: normalTextFieldStyle(
normalTextFieldStyle("Is Hospital", ''), "Is Hospital", ''),
name: 'isHospital', name: 'isHospital',
title: Text(isHospital == true ? "YES" : "NO"), title: Text(
isHospital == true ? "YES" : "NO"),
), ),
const SizedBox( const SizedBox(
height: 20, height: 20,
@ -361,8 +380,8 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
width: double.infinity, width: double.infinity,
height: 50, height: 50,
child: ElevatedButton( child: ElevatedButton(
style: mainBtnStyle( style: mainBtnStyle(primary,
primary, Colors.transparent, second), Colors.transparent, second),
onPressed: () { onPressed: () {
RbacStation? newStation; RbacStation? newStation;
if (formKey.currentState! if (formKey.currentState!
@ -371,25 +390,30 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
.currentState! .currentState!
.value['station-name']; .value['station-name'];
String? acronym = formKey String? acronym = formKey
.currentState!.value['acronym'];
String? code = formKey
.currentState!.value['code'];
String? fullcode = formKey
.currentState!.value['fullcode'];
String? description = formKey
.currentState! .currentState!
.value['station-description']; .value['acronym'];
String? code = formKey
.currentState!
.value['code'];
String? fullcode = formKey
.currentState!
.value['fullcode'];
String? description =
formKey.currentState!.value[
'station-description'];
newStation = RbacStation( newStation = RbacStation(
id: null, id: null,
stationName: stationName, stationName: stationName,
stationType: selectedStationType, stationType:
selectedStationType,
hierarchyOrderNo: mainParent hierarchyOrderNo: mainParent
? 1 ? 1
: selectedParentStation! : selectedParentStation!
.hierarchyOrderNo! + .hierarchyOrderNo! +
1, 1,
headPosition: headPosition:
selectedPositiontitle?.title, selectedPositiontitle
?.title,
governmentAgency: governmentAgency:
GovernmentAgency( GovernmentAgency(
agencyid: agencyid:
@ -397,11 +421,14 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
agencyname: null, agencyname: null,
agencycatid: null, agencycatid: null,
privateEntity: null, privateEntity: null,
contactinfoid: null), contactinfoid:
null),
acronym: acronym, acronym: acronym,
parentStation: mainParent parentStation:
mainParent
? null ? null
: selectedParentStation!.id!, : selectedParentStation!
.id!,
code: code, code: code,
fullcode: fullcode, fullcode: fullcode,
childStationInfo: null, childStationInfo: null,
@ -416,7 +443,8 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
isactive: true, isactive: true,
sellingStation: null); sellingStation: null);
Navigator.pop(context); Navigator.pop(context);
rbacStationBloc.add(AddRbacStation( rbacStationBloc.add(
AddRbacStation(
station: newStation)); station: newStation));
} }
}, },
@ -445,7 +473,9 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
Padding( Padding(
padding: const EdgeInsets.all(8), padding: const EdgeInsets.all(8),
child: SearchField( child: SearchField(
inputFormatters: [UpperCaseTextFormatter()], inputFormatters: [
UpperCaseTextFormatter()
],
itemHeight: 100, itemHeight: 100,
focusNode: agencyFocusNode, focusNode: agencyFocusNode,
suggestions: agencies suggestions: agencies
@ -455,12 +485,14 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
child: ListTile( child: ListTile(
title: Text( title: Text(
agency.name!, agency.name!,
overflow: TextOverflow.visible, overflow:
TextOverflow.visible,
), ),
))) )))
.toList(), .toList(),
searchInputDecoration: searchInputDecoration:
normalTextFieldStyle("Filter", "").copyWith( normalTextFieldStyle("Filter", "")
.copyWith(
suffixIcon: IconButton( suffixIcon: IconButton(
icon: const Icon(Icons.arrow_drop_down), icon: const Icon(Icons.arrow_drop_down),
onPressed: () { onPressed: () {
@ -652,7 +684,8 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
children: [ children: [
Padding( Padding(
padding: padding:
const EdgeInsets.all( const EdgeInsets
.all(
6), 6),
child: child:
Text( Text(
@ -873,7 +906,9 @@ class _RbacStationScreenState extends State<RbacStationScreen> {
return SomethingWentWrong( return SomethingWentWrong(
message: state.message, message: state.message,
onpressed: () { onpressed: () {
context.read<StationBloc>().add(GetStations(agencyId: selectedAgencyId)); context
.read<StationBloc>()
.add(GetStations(agencyId: selectedAgencyId));
}); });
} }

View File

@ -1,7 +1,8 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.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:fluttericon/font_awesome5_icons.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:qr_flutter/qr_flutter.dart'; import 'package:qr_flutter/qr_flutter.dart';
@ -44,45 +45,45 @@ class BasicInfo extends StatelessWidget {
alignment: Alignment.center, alignment: Alignment.center,
children: [ children: [
const CoverImage(), const CoverImage(),
// Positioned( Positioned(
// top: blockSizeVertical * 15.5, top: blockSizeVertical * 15.5,
// child: Stack( child: Stack(
// alignment: Alignment.center, alignment: Alignment.center,
// children: [ children: [
// CachedNetworkImage( CachedNetworkImage(
// imageUrl: fileUrl, imageUrl: fileUrl,
// imageBuilder: (context, imageProvider) => imageBuilder: (context, imageProvider) =>
// Container( Container(
// width: 160, width: 160,
// height: 160, height: 160,
// decoration: BoxDecoration( decoration: BoxDecoration(
// border: Border.all( border: Border.all(
// color: Colors.black26, width: 3), color: Colors.black26, width: 3),
// shape: BoxShape.circle, shape: BoxShape.circle,
// image: DecorationImage( image: DecorationImage(
// image: imageProvider, image: imageProvider,
// fit: BoxFit.cover), fit: BoxFit.cover),
// ), ),
// ), ),
// placeholder: (context, url) => placeholder: (context, url) =>
// const CircularProgressIndicator(), const CircularProgressIndicator(),
// errorWidget: (context, url, error) => errorWidget: (context, url, error) =>
// Container( Container(
// width: 160, width: 160,
// height: 160, height: 160,
// decoration: BoxDecoration( decoration: BoxDecoration(
// border: Border.all( border: Border.all(
// color: Colors.white, width: 3), color: Colors.white, width: 3),
// shape: BoxShape.circle, shape: BoxShape.circle,
// ), ),
// child: SvgPicture.asset( child: SvgPicture.asset(
// 'assets/svgs/male.svg', 'assets/svgs/male.svg',
// ), ),
// ), ),
// ), ),
// ], ],
// ), ),
// ), ),
Positioned( Positioned(
top: 10, top: 10,
left: 20, left: 20,
@ -135,13 +136,14 @@ class BuildInformation extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
DateFormat dteFormat2 = DateFormat.yMMMMd('en_US'); DateFormat dteFormat2 = DateFormat.yMMMMd('en_US');
globalFistname = globalFistname ?? userData.user!.login!.user!.firstName!.toUpperCase(); globalFistname =
globalLastname =globalLastname ?? userData.user!.login!.user!.lastName!.toUpperCase(); globalFistname ?? userData.employeeInfo!.profile!.firstName!.toUpperCase();
globalMiddleName = globalMiddleName == null globalLastname =
? (userData.employeeInfo == null 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(); globalSex = globalSex ?? userData.employeeInfo!.profile!.sex!.toUpperCase();
globalBday = globalBday ?? userData.employeeInfo!.profile!.birthdate; globalBday = globalBday ?? userData.employeeInfo!.profile!.birthdate;
final uuid = userData.employeeInfo!.uuid; final uuid = userData.employeeInfo!.uuid;

View File

@ -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/role_screen.dart';
import 'package:unit2/screens/superadmin/role_assignment.dart/role_assignment_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/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/superadmin/stations/stations_screen.dart';
import 'package:unit2/screens/unit2/homepage.dart/module-screen.dart'; import 'package:unit2/screens/unit2/homepage.dart/module-screen.dart';
import 'package:unit2/theme-data.dart/btn-style.dart'; import 'package:unit2/theme-data.dart/btn-style.dart';

View File

@ -18,9 +18,9 @@ class _MenuScreenState extends State<MenuScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final String firstName =globalFistname?? final String firstName =globalFistname??
widget.userData!.user!.login!.user!.firstName!.toUpperCase(); widget.userData!.employeeInfo!.profile!.firstName!.toUpperCase();
final String lastname = globalLastname?? final String lastname = globalLastname??
widget.userData!.user!.login!.user!.lastName!.toUpperCase(); widget.userData!.employeeInfo!.profile!.lastName!.toUpperCase();
return Drawer( return Drawer(
child: SizedBox( child: SizedBox(
height: screenHeight, height: screenHeight,

View File

@ -1,5 +1,6 @@
import 'package:assets_audio_player/assets_audio_player.dart'; import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:audioplayers/audioplayers.dart'; import 'package:audioplayers/audioplayers.dart';
import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:cool_alert/cool_alert.dart'; import 'package:cool_alert/cool_alert.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
@ -35,13 +36,13 @@ class _QRCodeScannerState extends State<QRCodeScanner> {
player = AudioPlayer(); player = AudioPlayer();
super.initState(); super.initState();
} }
@override @override
void dispose() { void dispose() {
player?.dispose(); player?.dispose();
super.dispose(); super.dispose();
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
@ -73,36 +74,37 @@ class _QRCodeScannerState extends State<QRCodeScanner> {
progress!.dismiss(); progress!.dismiss();
} }
if (state is ScanSuccess) { if (state is ScanSuccess) {
Future.delayed(const Duration(seconds: 1), () async{ Future.delayed(const Duration(seconds: 1), () async {
await player?.play(AssetSource("success.mp3")); await player?.play(AssetSource("success.mp3"));
}); });
context.read<PassCheckBloc>().add(ScanQr(token: state.token)); context.read<PassCheckBloc>().add(ScanQr(token: state.token));
} }
if (state is QRInvalid) { if (state is QRInvalid) {
Future.delayed(const Duration(seconds: 1), ()async { Future.delayed(const Duration(seconds: 1), () async {
await player?.play(AssetSource("invalid.mp3")); await player?.play(AssetSource("invalid.mp3"));
}); });
context.read<PassCheckBloc>().add(ScanQr(token: state.token)); context.read<PassCheckBloc>().add(ScanQr(token: state.token));
} }
if (state is ScanFailed) { if (state is ScanFailed) {
Future.delayed(const Duration(seconds: 1), ()async { Future.delayed(const Duration(seconds: 1), () async {
await player?.play(AssetSource("fail.mp3")); await player?.play(AssetSource("fail.mp3"));
}); });
context.read<PassCheckBloc>().add(ScanQr(token: state.token)); context.read<PassCheckBloc>().add(ScanQr(token: state.token));
} }
if (state is IncomingScanState) { if (state is IncomingScanState) {
CoolAlert.show( AwesomeDialog(
barrierDismissible: false, dismissOnBackKeyPress: false,
context: context, context: context,
type: CoolAlertType.loading, dialogType: DialogType.info,
text: "Enter Temperature", dismissOnTouchOutside: false,
widget: Padding( body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24), padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24),
child: FormBuilder( child: FormBuilder(
key: formKey, key: formKey,
child: Column( child: Column(
children: [ children: [
const Text("Enter Temperature",style: TextStyle(color: Colors.black),),
const SizedBox( const SizedBox(
height: 24, height: 24,
), ),
@ -136,20 +138,22 @@ class _QRCodeScannerState extends State<QRCodeScanner> {
) )
], ],
)), )),
)); ),
).show();
} }
if (state is OutGoingScanState) { if (state is OutGoingScanState) {
CoolAlert.show( AwesomeDialog(
barrierDismissible: false, dismissOnBackKeyPress: false,
context: context, context: context,
type: CoolAlertType.loading, dialogType: DialogType.info,
text: "Enter Destination", dismissOnTouchOutside: false,
widget: Padding( body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24), padding: const EdgeInsets.symmetric(horizontal: 24,vertical: 24),
child: FormBuilder( child: FormBuilder(
key: formKey, key: formKey,
child: Column( child: Column(
children: [ children: [
const Text("Enter Destination"),
const SizedBox( const SizedBox(
height: 24, height: 24,
), ),
@ -185,7 +189,8 @@ class _QRCodeScannerState extends State<QRCodeScanner> {
) )
], ],
)), )),
)); )).show();
} }
}, },
builder: (context, state) { builder: (context, state) {
@ -302,28 +307,56 @@ class _QRCodeScannerState extends State<QRCodeScanner> {
children: [ children: [
SelectedState( SelectedState(
//TODO add api data //TODO add api data
title: state.roleIdRoleName.roleName.toLowerCase() == "41" || title: state.roleIdRoleName.roleName
state.roleIdRoleName.roleName.toLowerCase() == 'qr code scanner' || .toLowerCase() ==
state.roleIdRoleName.roleName.toLowerCase() == 'office/branch chief' || "41" ||
state.roleIdRoleName.roleName.toLowerCase() == 'registration in-charge' 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.assignedArea.stationName
: state.roleIdRoleName.roleName.toLowerCase() == 'barangay chairperson' : state.roleIdRoleName.roleName
.toLowerCase() ==
'barangay chairperson'
? state.assignedArea.brgydesc ? state.assignedArea.brgydesc
: state.roleIdRoleName.roleName.toLowerCase() == 'purok president' : state.roleIdRoleName.roleName
.toLowerCase() ==
'purok president'
? state.assignedArea.purokdesc ? state.assignedArea.purokdesc
: state.roleIdRoleName.roleName.toLowerCase() == 'establishment point-person' : state.roleIdRoleName.roleName
.toLowerCase() ==
'establishment point-person'
? "Agency" ? "Agency"
: "", : "",
subtitle: state.roleIdRoleName.roleName.toLowerCase() == "41" || subtitle: state.roleIdRoleName.roleName
state.roleIdRoleName.roleName.toLowerCase() == 'qr code scanner' || .toLowerCase() ==
state.roleIdRoleName.roleName.toLowerCase() == 'office/branch chief' || "41" ||
state.roleIdRoleName.roleName.toLowerCase() == 'registration in-charge' state.roleIdRoleName.roleName
.toLowerCase() ==
'qr code scanner' ||
state.roleIdRoleName.roleName
.toLowerCase() ==
'office/branch chief' ||
state.roleIdRoleName.roleName
.toLowerCase() ==
'registration in-charge'
? "Station" ? "Station"
: state.roleIdRoleName.roleName.toLowerCase() == 'barangay chairperson' : state.roleIdRoleName.roleName
.toLowerCase() ==
'barangay chairperson'
? "Barangay" ? "Barangay"
: state.roleIdRoleName.roleName.toLowerCase() == 'purok president' : state.roleIdRoleName.roleName
.toLowerCase() ==
'purok president'
? "Purok" ? "Purok"
: state.roleIdRoleName.roleName.toLowerCase() == 'establishment point-person' : state.roleIdRoleName.roleName
.toLowerCase() ==
'establishment point-person'
? "Agency" ? "Agency"
: "", : "",
), ),

View File

@ -14,7 +14,7 @@ class AgencyServices {
'X-Client-Key': xClientKey, 'X-Client-Key': xClientKey,
'X-Client-Secret': xClientSecret 'X-Client-Secret': xClientSecret
}; };
String path = Url.instance.postAgencies(); String path = Url.instance.agencies();
Future<List<Agency>> getAgencies() async { Future<List<Agency>> getAgencies() async {
List<Agency> agencies = []; List<Agency> agencies = [];

View File

@ -111,7 +111,6 @@ class RbacModuleServices {
Future<bool> deleteRbacModule({required int moduleId}) async { Future<bool> deleteRbacModule({required int moduleId}) async {
bool success = false; bool success = false;
String path = "${Url.instance.getModules()}$moduleId/";
try { try {
http.Response response = await Request.instance http.Response response = await Request.instance
.deleteRequest(path: '${path+moduleId.toString()}/', headers: headers, body: {}, param: {}); .deleteRequest(path: '${path+moduleId.toString()}/', headers: headers, body: {}, param: {});

View File

@ -67,7 +67,6 @@ class RbacRoleExtendServices {
Future<bool> delete({required int roleExtendId}) async { Future<bool> delete({required int roleExtendId}) async {
bool success = false; bool success = false;
String path = "${Url.instance.getRoleExtend()}$roleExtendId/";
try { try {
http.Response response = await Request.instance.deleteRequest( http.Response response = await Request.instance.deleteRequest(
path: '${path + roleExtendId.toString()}/', path: '${path + roleExtendId.toString()}/',

View File

@ -3,7 +3,8 @@ import 'package:mask_text_input_formatter/mask_text_input_formatter.dart';
var mobileFormatter = MaskTextInputFormatter( var mobileFormatter = MaskTextInputFormatter(
mask: "+63 (###) ###-####", mask: "+63 (###) ###-####",
filter: {"#": RegExp(r"^[1-9][0-9]*$")}, filter: {"#": RegExp(r'^[0-9][0-9]*$')
},
type: MaskAutoCompletionType.lazy, type: MaskAutoCompletionType.lazy,
initialText: "0"); initialText: "0");

View File

@ -18,7 +18,7 @@ class Request {
Map<String, String>? param}) async { Map<String, String>? param}) async {
Response response; Response response;
try { 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)); .timeout(Duration(seconds: requestTimeout));
} on TimeoutException catch (_) { } on TimeoutException catch (_) {
// Fluttertoast.showToast( // Fluttertoast.showToast(
@ -60,7 +60,7 @@ class Request {
Map<String, String>? param}) async { Map<String, String>? param}) async {
Response response; Response response;
try { try {
response = await post(Uri.http(host, path!, param), response = await post(Uri.https(host, path!, param),
headers: headers, body: jsonEncode(body)) headers: headers, body: jsonEncode(body))
.timeout(Duration(seconds: requestTimeout)); .timeout(Duration(seconds: requestTimeout));
} on TimeoutException catch (_) { } on TimeoutException catch (_) {
@ -103,7 +103,7 @@ class Request {
required Map<String, dynamic>? param}) async { required Map<String, dynamic>? param}) async {
Response response; Response response;
try { try {
response = await put(Uri.http(host, path, param), response = await put(Uri.https(host, path, param),
headers: headers, body: jsonEncode(body)); headers: headers, body: jsonEncode(body));
} on TimeoutException catch (_) { } on TimeoutException catch (_) {
// Fluttertoast.showToast( // Fluttertoast.showToast(
@ -187,7 +187,7 @@ class Request {
required Map<String, dynamic>? param}) async { required Map<String, dynamic>? param}) async {
Response response; Response response;
try { try {
response = await delete(Uri.http(host, path, param), response = await delete(Uri.https(host, path, param),
headers: headers, body: jsonEncode(body)) headers: headers, body: jsonEncode(body))
.timeout(Duration(seconds: requestTimeout)); .timeout(Duration(seconds: requestTimeout));
} on TimeoutException catch (_) { } on TimeoutException catch (_) {

View File

@ -5,8 +5,8 @@ class Url {
String host() { String host() {
// return '192.168.10.183:3000'; // return '192.168.10.183:3000';
// return 'agusandelnorte.gov.ph'; return 'agusandelnorte.gov.ph';
return "192.168.10.219:3000"; // return "192.168.10.219:3000";
// return "192.168.10.241"; // return "192.168.10.241";
// return "192.168.10.221:3004"; // return "192.168.10.221:3004";
// return "playweb.agusandelnorte.gov.ph"; // return "playweb.agusandelnorte.gov.ph";
@ -15,8 +15,8 @@ class Url {
} }
String prefixHost() { String prefixHost() {
// return "https"; return "https";
return "http"; // return "http";
} }
String authentication() { String authentication() {