diff --git a/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart b/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart index c02604d..9cbcc07 100644 --- a/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart +++ b/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart @@ -51,10 +51,13 @@ class LearningDevelopmentBloc attachmentCategories = await AttachmentServices.instance.getCategories(); } - List learnings = await LearningDevelopmentServices + if(learningsAndDevelopments.isEmpty){ + List learnings = await LearningDevelopmentServices .instance .getLearningDevelopments(event.profileId, event.token); learningsAndDevelopments = learnings; + } + emit(LearningDevelopmentLoadedState( learningsAndDevelopment: learningsAndDevelopments,attachmentCategory: attachmentCategories)); } catch (e) { diff --git a/lib/bloc/profile/profile_bloc.dart b/lib/bloc/profile/profile_bloc.dart index 6600285..dbe1e4c 100644 --- a/lib/bloc/profile/profile_bloc.dart +++ b/lib/bloc/profile/profile_bloc.dart @@ -64,6 +64,7 @@ class ProfileBloc extends Bloc { primaryBasicInformation: globalCurrentProfile!)); } else { currentProfileInformation = event.primaryBasicInformation; + globalCurrentProfile = currentProfileInformation; emit(BasicInformationProfileLoaded( primaryBasicInformation: currentProfileInformation!)); } @@ -108,7 +109,7 @@ class ProfileBloc extends Bloc { 0, ProfileOtherInfo(id: null, name: "NONE", description: null)); } emit(BasicInformationEditingState( - primaryInformation: currentProfileInformation!, + primaryInformation: globalCurrentProfile!, extensions: nameExtensions, sexes: sexes, bloodTypes: bloodType, diff --git a/lib/bloc/rbac/rbac_operations/agency/agency_event.dart b/lib/bloc/rbac/rbac_operations/agency/agency_event.dart index fece6bc..936e2d1 100644 --- a/lib/bloc/rbac/rbac_operations/agency/agency_event.dart +++ b/lib/bloc/rbac/rbac_operations/agency/agency_event.dart @@ -13,9 +13,12 @@ class GetAgencies extends AgencyEvent{ class AddAgency extends AgencyEvent{ final Agency agency; const AddAgency({required this.agency}); + List get props => [agency + ]; } class GetEstPointPersonAgencies extends AgencyEvent{ final List? assignedAreas; const GetEstPointPersonAgencies({required this.assignedAreas}); + } diff --git a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart index b302617..925e294 100644 --- a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart @@ -60,7 +60,7 @@ class AssignAreaBloc extends Bloc { } }); on((event, emit) async { - // try { + try { emit(AssignAreaLoadingState()); Map response = await RbacAssignedAreaServices.instance .add( @@ -77,11 +77,6 @@ class AssignAreaBloc extends Bloc { break; } } - // newAssignArea = userAssignedAreas.firstWhere((var element) { - // return element.assignedRole?.role?.id == event.roleId && - // element.assignedRole?.user?.id == event.userId; - // }); - if (newAssignArea?.assignedArea != null) { userAssignedAreas.removeWhere((element) => element.assignedRole!.role!.id == event.roleId && @@ -120,8 +115,8 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); //// purok } if (event.areaTypeId == 2) { @@ -149,8 +144,8 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } ////statiom if (event.areaTypeId == 4) { @@ -200,8 +195,8 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } ////agency if (event.areaTypeId == 3) { @@ -231,16 +226,16 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } emit(AssignAreaAddedState(response: response)); } else { emit(AssignAreaAddedState(response: response)); } - // } catch (e) { - // emit(AssignAreaErorState(message: e.toString())); - // } + } catch (e) { + emit(AssignAreaErorState(message: e.toString())); + } }); on((event, emit) async { emit(AssignedAreaLoadedState( diff --git a/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart b/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart index f401b3b..4622f0b 100644 --- a/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart @@ -66,7 +66,7 @@ class ModuleObjectsBloc extends Bloc { emit(ModuleObjectLoadingState()); try { bool success = await RbacModuleObjectsServices.instance - .deleteRbacModuleObject(moduleObjectId: event.moduleObjectId); + .delete(moduleObjectId: event.moduleObjectId); if (success) { moduleObjects .removeWhere((element) => element.id == event.moduleObjectId); diff --git a/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart new file mode 100644 index 0000000..145be4c --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart @@ -0,0 +1,82 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/rbac/permission.dart'; +import 'package:unit2/model/rbac/permission_assignment.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/sevices/roles/rbac_operations/permission_assignment_services.dart'; +import 'package:unit2/sevices/roles/rbac_operations/permission_service.dart'; +import 'package:unit2/sevices/roles/rbac_operations/role_services.dart'; + +part 'permission_assignment_event.dart'; +part 'permission_assignment_state.dart'; + +class PermissionAssignmentBloc + extends Bloc { + PermissionAssignmentBloc() : super(PermissionAssignmentInitial()) { + List permissionAssignments = []; + List permissions = []; + List roles = []; + on((event, emit) async { + try { + emit(PermissionAssignmentLoadingScreen()); + if (permissionAssignments.isEmpty) { + permissionAssignments = await RbacPermissionAssignmentServices + .instance + .getPermissionAssignment(); + } + if (permissions.isEmpty) { + permissions = + await RbacPermissionServices.instance.getRbacPermission(); + } + if (roles.isEmpty) { + roles = await RbacRoleServices.instance.getRbacRoles(); + } + emit(PermissionAssignmentLoadedState( + permissionAssignments: permissionAssignments, + permissions: permissions, + roles: roles)); + } catch (e) { + emit(PermissionAssignmentErrorState(message: e.toString())); + } + }); + on((event, emit) async { + try { + emit(PermissionAssignmentLoadingScreen()); + Map statusResponse = + await RbacPermissionAssignmentServices.instance + .addPermissionAssignment( + assignerId: event.assignerId, + opsId: event.opsId, + roleId: event.roleId); + if (statusResponse['success']) { + if (statusResponse['data'] != null) { + for (var rbac in statusResponse['data']) { + PermissionAssignment permissionAssignment = + PermissionAssignment.fromJson(rbac); + permissionAssignments.add(permissionAssignment); + } + } + emit(PermissionAssignmentAddedState(status: statusResponse)); + } else { + emit(PermissionAssignmentAddedState(status: statusResponse)); + } + } catch (e) { + emit(PermissionAssignmentErrorState(message: e.toString())); + } + }); + on((event, emit) async { + try { + emit(PermissionAssignmentLoadingScreen()); + bool success = await RbacPermissionAssignmentServices.instance + .deletePermissionAssignment(id: event.id); + if (success) { + permissionAssignments + .removeWhere((element) => element.id == event.id); + } + emit(PermissionAssignmentDeletedState(success: success)); + } catch (e) { + emit(PermissionAssignmentErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_event.dart b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_event.dart new file mode 100644 index 0000000..e2d13fc --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_event.dart @@ -0,0 +1,28 @@ +part of 'permission_assignment_bloc.dart'; + +class PermissionAssignmentEvent extends Equatable { + const PermissionAssignmentEvent(); + + @override + List get props => []; +} + +class GetPermissionAssignments extends PermissionAssignmentEvent{ + +} +class DeletePermissionAssignment extends PermissionAssignmentEvent{ + final int id; + const DeletePermissionAssignment({required this.id}); + @override + List get props => [id]; +} + +class AddPersmissionAssignment extends PermissionAssignmentEvent{ + final int assignerId; + final List opsId; + final int roleId; + const AddPersmissionAssignment({required this.assignerId, required this.opsId, required this.roleId}); + @override + List get props => [assignerId,opsId,roleId]; + +} diff --git a/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_state.dart b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_state.dart new file mode 100644 index 0000000..4100b58 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_state.dart @@ -0,0 +1,45 @@ +part of 'permission_assignment_bloc.dart'; + +class PermissionAssignmentState extends Equatable { + const PermissionAssignmentState(); + + @override + List get props => []; +} + +class PermissionAssignmentInitial extends PermissionAssignmentState {} + +class PermissionAssignmentLoadingScreen extends PermissionAssignmentState {} + +class PermissionAssignmentLoadedState extends PermissionAssignmentState { + final List permissionAssignments; + final List permissions; + final List roles; + const PermissionAssignmentLoadedState( + {required this.permissionAssignments, + required this.permissions, + required this.roles}); + @override + List get props => [permissionAssignments, permissions, roles]; +} + +class PermissionAssignmentErrorState extends PermissionAssignmentState { + final String message; + const PermissionAssignmentErrorState({required this.message}); + @override + List get props => [message]; +} + +class PermissionAssignmentDeletedState extends PermissionAssignmentState { + final bool success; + const PermissionAssignmentDeletedState({required this.success}); + @override + List get props => [success]; +} + +class PermissionAssignmentAddedState extends PermissionAssignmentState { + final Map status; + const PermissionAssignmentAddedState({required this.status}); + @override + List get props => [status]; +} diff --git a/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart b/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart index 3f52bd4..36ace5d 100644 --- a/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart @@ -11,7 +11,7 @@ part 'role_module_state.dart'; class RoleModuleBloc extends Bloc { RoleModuleBloc() : super(RoleModuleInitial()) { List roleModules = []; - List roles = []; + List roles = []; List modules = []; on((event, emit) async { emit(RoleModuleLoadingState()); @@ -19,18 +19,19 @@ class RoleModuleBloc extends Bloc { if (roleModules.isEmpty) { roleModules = await RbacRoleModuleServices.instance.getRoleModules(); } - if (modules.isEmpty) { + if (modules.isEmpty) { modules = await RbacModuleServices.instance.getRbacModule(); } - if (roles.isEmpty) { + if (roles.isEmpty) { roles = await RbacRoleServices.instance.getRbacRoles(); } - emit(RoleModuleLoadedState(roleModules: roleModules,modules: modules,roles: roles)); + emit(RoleModuleLoadedState( + roleModules: roleModules, modules: modules, roles: roles)); } catch (e) { emit(RoleModuleErrorState(message: e.toString())); } }); - on((event, emit) async { + on((event, emit) async { try { emit(RoleModuleLoadingState()); Map statusResponse = @@ -40,9 +41,12 @@ class RoleModuleBloc extends Bloc { moduleIds: event.moduleIds); if (statusResponse['success']) { + List ids = roleModules.map((e) => e.id).toList(); statusResponse['data'].forEach((var roleMod) { RoleModules newRoleModule = RoleModules.fromJson(roleMod); - roleModules.add(newRoleModule); + if (!ids.contains(newRoleModule.id)) { + roleModules.add(newRoleModule); + } emit(RoleModuleAddedState(response: statusResponse)); }); } else { diff --git a/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart index f8fc508..ba17ba3 100644 --- a/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart @@ -36,11 +36,14 @@ class RolesUnderBloc extends Bloc { .add(roleId: event.roleId, rolesId: event.roleUnderIds); if (statusResponse['success']) { + List ids = rolesUnder.map((e) => e.id).toList(); statusResponse['data'].forEach((var roleMod) { RolesUnder newRoleUnder = RolesUnder.fromJson(roleMod); - rolesUnder.add(newRoleUnder); - emit(RoleUnderAddedState(response: statusResponse)); + if (!ids.contains(newRoleUnder.id)) { + rolesUnder.add(newRoleUnder); + } }); + emit(RoleUnderAddedState(response: statusResponse)); } else { emit(RoleUnderAddedState(response: statusResponse)); } diff --git a/lib/bloc/user/user_bloc.dart b/lib/bloc/user/user_bloc.dart index 475b451..da677e9 100644 --- a/lib/bloc/user/user_bloc.dart +++ b/lib/bloc/user/user_bloc.dart @@ -40,9 +40,13 @@ class UserBloc extends Bloc { final String? saved = CREDENTIALS?.get('saved'); username = CREDENTIALS?.get('username'); password = CREDENTIALS?.get('password'); - print(username); - print(password); - if (saved != null) { + if(apkVersion != _versionInfo!.id ){ + emit(VersionLoaded( + versionInfo: _versionInfo, + apkVersion: _apkVersion, + username: event.username, + password: event.password)); + }else if (saved != null) { save = true; add(UserLogin(username: username, password: password)); } else { diff --git a/lib/model/login_data/version_info.dart b/lib/model/login_data/version_info.dart index 12ae4fb..fcd00fe 100644 --- a/lib/model/login_data/version_info.dart +++ b/lib/model/login_data/version_info.dart @@ -1,6 +1,6 @@ class VersionInfo { VersionInfo({ - this.version, + this.id, this.versionInfo, this.dateReleased, this.development, @@ -11,7 +11,7 @@ class VersionInfo { this.x8664DownloadUrl, }); - String? version; + String? id; String? versionInfo; DateTime? dateReleased; bool? development; @@ -22,7 +22,7 @@ class VersionInfo { String? x8664DownloadUrl; factory VersionInfo.fromJson(Map json) => VersionInfo( - version: json["version"], + id: json["id"], versionInfo: json["version_info"], dateReleased: DateTime.parse(json["date_released"]), development: json["development"], @@ -34,7 +34,7 @@ class VersionInfo { ); Map toJson() => { - "version": version, + "version": id, "version_info": versionInfo, "date_released": "${dateReleased!.year.toString().padLeft(4, '0')}-${dateReleased!.month.toString().padLeft(2, '0')}-${dateReleased!.day.toString().padLeft(2, '0')}", diff --git a/lib/model/rbac/assigned_role.dart b/lib/model/rbac/assigned_role.dart index ca688e1..0b197bf 100644 --- a/lib/model/rbac/assigned_role.dart +++ b/lib/model/rbac/assigned_role.dart @@ -51,38 +51,4 @@ class AssignedRole { }; } -class CreatedBy { - final int id; - final String username; - final String firstName; - final String lastName; - final String email; - final bool isActive; - CreatedBy({ - required this.id, - required this.username, - required this.firstName, - required this.lastName, - required this.email, - required this.isActive, - }); - - factory CreatedBy.fromJson(Map json) => CreatedBy( - id: json["id"], - username: json["username"], - firstName: json["first_name"], - lastName: json["last_name"], - email: json["email"], - isActive: json["is_active"], - ); - - Map toJson() => { - "id": id, - "username": username, - "first_name": firstName, - "last_name": lastName, - "email": email, - "is_active": isActive, - }; -} diff --git a/lib/model/rbac/permission_assignment.dart b/lib/model/rbac/permission_assignment.dart new file mode 100644 index 0000000..1c2e06b --- /dev/null +++ b/lib/model/rbac/permission_assignment.dart @@ -0,0 +1,174 @@ +// To parse this JSON data, do +// +// final permissionAssignment = permissionAssignmentFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'package:unit2/model/rbac/permission.dart'; +import 'dart:convert'; + +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/model/rbac/user.dart'; + +PermissionAssignment permissionAssignmentFromJson(String str) => PermissionAssignment.fromJson(json.decode(str)); + +String permissionAssignmentToJson(PermissionAssignment data) => json.encode(data.toJson()); + +class PermissionAssignment { + final int? id; + final RBAC? role; + final RBACPermission? permission; + final DateTime? createdAt; + final DateTime? updatedAt; + final User? createdBy; + final User? updatedBy; + + PermissionAssignment({ + required this.id, + required this.role, + required this.permission, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory PermissionAssignment.fromJson(Map json) => PermissionAssignment( + id: json["id"], + role: json["role"] == null? null: RBAC.fromJson(json["role"]), + permission:json["permission"] == null?null: RBACPermission.fromJson(json["permission"]), + createdAt: json['created_at'] == null?null: DateTime.parse(json["created_at"]), + updatedAt:json['updated_at'] == null?null: DateTime.parse(json["updated_at"]), + createdBy:json["created_by"] == null?null: User.fromJson(json["created_by"]), + updatedBy: json["updated_by"] == null? null:User.fromJson(json["created_by"]), + ); + + Map toJson() => { + "id": id, + "role": role?.toJson(), + "permission": permission?.toJson(), + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt, + "created_by": createdBy?.toJson(), + "updated_by": updatedBy, + }; +} + +class CreatedBy { + final int id; + final String username; + final String firstName; + final String lastName; + final String email; + final bool isActive; + + CreatedBy({ + required this.id, + required this.username, + required this.firstName, + required this.lastName, + required this.email, + required this.isActive, + }); + + factory CreatedBy.fromJson(Map json) => CreatedBy( + id: json["id"], + username: json["username"], + firstName: json["first_name"], + lastName: json["last_name"], + email: json["email"], + isActive: json["is_active"], + ); + + Map toJson() => { + "id": id, + "username": username, + "first_name": firstName, + "last_name": lastName, + "email": email, + "is_active": isActive, + }; +} + +class Permission { + final int id; + final Role object; + final Role operation; + final DateTime createdAt; + final dynamic updatedAt; + final CreatedBy createdBy; + final dynamic updatedBy; + + Permission({ + required this.id, + required this.object, + required this.operation, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory Permission.fromJson(Map json) => Permission( + id: json["id"], + object: Role.fromJson(json["object"]), + operation: Role.fromJson(json["operation"]), + createdAt: DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"], + createdBy: CreatedBy.fromJson(json["created_by"]), + updatedBy: json["updated_by"], + ); + + Map toJson() => { + "id": id, + "object": object.toJson(), + "operation": operation.toJson(), + "created_at": createdAt.toIso8601String(), + "updated_at": updatedAt, + "created_by": createdBy.toJson(), + "updated_by": updatedBy, + }; +} + +class Role { + final int id; + final String name; + final String slug; + final String shorthand; + final DateTime createdAt; + final dynamic updatedAt; + final CreatedBy createdBy; + final dynamic updatedBy; + + Role({ + required this.id, + required this.name, + required this.slug, + required this.shorthand, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory Role.fromJson(Map json) => Role( + id: json["id"], + name: json["name"], + slug: json["slug"], + shorthand: json["shorthand"], + createdAt: DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"], + createdBy: CreatedBy.fromJson(json["created_by"]), + updatedBy: json["updated_by"], + ); + + Map toJson() => { + "id": id, + "name": name, + "slug": slug, + "shorthand": shorthand, + "created_at": createdAt.toIso8601String(), + "updated_at": updatedAt, + "created_by": createdBy.toJson(), + "updated_by": updatedBy, + }; +} diff --git a/lib/model/rbac/user.dart b/lib/model/rbac/user.dart new file mode 100644 index 0000000..46b1ff1 --- /dev/null +++ b/lib/model/rbac/user.dart @@ -0,0 +1,35 @@ +class User { + final int id; + final String? username; + final String? firstName; + final String? lastName; + final String? email; + final bool? isActive; + + User({ + required this.id, + required this.username, + required this.firstName, + required this.lastName, + required this.email, + required this.isActive, + }); + + factory User.fromJson(Map json) => User( + id: json["id"], + username: json["username"], + firstName: json["first_name"], + lastName: json["last_name"], + email: json["email"], + isActive: json["is_active"], + ); + + Map toJson() => { + "id": id, + "username": username, + "first_name": firstName, + "last_name": lastName, + "email": email, + "is_active": isActive, + }; +} \ No newline at end of file diff --git a/lib/screens/profile/components/basic_information/citizenship_screen.dart b/lib/screens/profile/components/basic_information/citizenship_screen.dart index 3980950..913913c 100644 --- a/lib/screens/profile/components/basic_information/citizenship_screen.dart +++ b/lib/screens/profile/components/basic_information/citizenship_screen.dart @@ -23,9 +23,9 @@ import '../../../../utils/alerts.dart'; class CitizenShipScreen extends StatefulWidget { final int profileId; final String token; - + final List citizenships; const CitizenShipScreen( - {super.key, required this.profileId, required this.token}); + {super.key, required this.profileId, required this.token , required this.citizenships}); @override State createState() => _CitizenShipScreenState(); @@ -421,7 +421,9 @@ class _CitizenShipScreenState extends State { if (state is CitizenshipErrorState) { return Scaffold( body: SomethingWentWrong( - message: state.message, onpressed: () {})); + message: state.message, onpressed: () { + context.read().add(GetCitizenship(citizenship: widget.citizenships)); + })); } return Container(); }, diff --git a/lib/screens/profile/components/basic_information/contact_information/add_modal.dart b/lib/screens/profile/components/basic_information/contact_information/add_modal.dart index 0d7d0c2..49be54c 100644 --- a/lib/screens/profile/components/basic_information/contact_information/add_modal.dart +++ b/lib/screens/profile/components/basic_information/contact_information/add_modal.dart @@ -10,6 +10,7 @@ import 'package:unit2/sevices/profile/contact_services.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; import 'package:unit2/theme-data.dart/form-style.dart'; import 'package:unit2/utils/global.dart'; +import 'package:unit2/utils/global_context.dart'; import 'package:unit2/utils/text_container.dart'; import '../../../../../theme-data.dart/colors.dart'; @@ -84,7 +85,7 @@ class _AddContactInformationScreenState serviceTypeId: selectedServiceType!.id!); } catch (e) { - context + NavigationService.navigatorKey.currentContext! .read() .add(CallErrorEvent(message: e.toString())); } @@ -129,6 +130,7 @@ class _AddContactInformationScreenState ? selectedServiceType?.id == 2 //// Landline ? FormBuilderTextField( + keyboardType: TextInputType.number, controller: numberMailController, inputFormatters: [landLineFormatter], name: 'number-mail', @@ -150,7 +152,7 @@ class _AddContactInformationScreenState errorText: "This field is required"), decoration: normalTextFieldStyle( "Mobile number *", - "+63 (9xx) xxx - xxxx"), + "+63 (9xx) xxx - xxxx").copyWith(helperText: "Please input your mobile number excluding the 0"), ) : selectedServiceType!.id == 4 ////Social Media @@ -167,6 +169,7 @@ class _AddContactInformationScreenState : selectedServiceType!.id == 3 ////Email Address ? FormBuilderTextField( + keyboardType: TextInputType.emailAddress, controller: numberMailController, name: 'number-mail', validator: FormBuilderValidators diff --git a/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart b/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart index f2e713d..e1c9187 100644 --- a/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart +++ b/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart @@ -37,7 +37,7 @@ class _EditContactInformationScreenState var mobileFormatter = MaskTextInputFormatter( mask: "+63 (###) ###-####", - filter: {"#": RegExp(r"^[1-9][0-9]*$")}, + filter: {"#": RegExp(r'^[0-9][0-9]*$')}, type: MaskAutoCompletionType.lazy, initialText: "0"); @@ -149,6 +149,7 @@ class _EditContactInformationScreenState ? selectedServiceType?.id == 2 //// Landline ? FormBuilderTextField( + keyboardType: TextInputType.number, controller: numberMailController, name: 'number-mail', inputFormatters: [landLineFormatter], @@ -162,6 +163,7 @@ class _EditContactInformationScreenState selectedServiceType!.id == 19 //// Mobile number ? FormBuilderTextField( + keyboardType: TextInputType.number, controller: numberMailController, name: 'number-mail', inputFormatters: [mobileFormatter], @@ -172,10 +174,12 @@ class _EditContactInformationScreenState decoration: normalTextFieldStyle( "Mobile number *", "+63 (9xx) xxx - xxxx"), + ) : selectedServiceType!.id == 4 ////Social Media ? FormBuilderTextField( + controller: numberMailController, name: 'number-mail', validator: @@ -188,6 +192,7 @@ class _EditContactInformationScreenState : selectedServiceType!.id == 3 ////Email Address ? FormBuilderTextField( + keyboardType: TextInputType.emailAddress, controller: numberMailController, name: 'number-mail', diff --git a/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart b/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart index 21b1560..226b39a 100644 --- a/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart +++ b/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart @@ -1,10 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:flutter/src/widgets/framework.dart'; -import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; - -import '../../../../../bloc/profile/family/family_bloc.dart'; import '../../../../../theme-data.dart/btn-style.dart'; import '../../../../../theme-data.dart/colors.dart'; import '../../../../../theme-data.dart/form-style.dart'; @@ -26,6 +22,7 @@ class AddMobileNumber extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ FormBuilderTextField( + keyboardType: TextInputType.number, name: 'number_mail', inputFormatters: [mobileFormatter], validator: FormBuilderValidators.required( diff --git a/lib/screens/profile/components/basic_information/family/spouse_add_modal.dart b/lib/screens/profile/components/basic_information/family/spouse_add_modal.dart index dca9326..99b88d7 100644 --- a/lib/screens/profile/components/basic_information/family/spouse_add_modal.dart +++ b/lib/screens/profile/components/basic_information/family/spouse_add_modal.dart @@ -349,7 +349,8 @@ class _SpouseAlertState extends State { ], itemHeight: 100, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), + suggestions: widget.positions .map((PositionTitle position) => SearchFieldListItem( diff --git a/lib/screens/profile/components/basic_information/family/spouse_edit_modal.dart b/lib/screens/profile/components/basic_information/family/spouse_edit_modal.dart index 5526016..75c04dc 100644 --- a/lib/screens/profile/components/basic_information/family/spouse_edit_modal.dart +++ b/lib/screens/profile/components/basic_information/family/spouse_edit_modal.dart @@ -383,7 +383,8 @@ class _SpouseEditAlertState extends State { suggestionDirection: SuggestionDirection.down, itemHeight: 100, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), + suggestions: widget.positions .map((PositionTitle position) => SearchFieldListItem( diff --git a/lib/screens/profile/components/education/add_modal.dart b/lib/screens/profile/components/education/add_modal.dart index 163f8fb..920e9ff 100644 --- a/lib/screens/profile/components/education/add_modal.dart +++ b/lib/screens/profile/components/education/add_modal.dart @@ -128,7 +128,8 @@ class _AddEducationScreenState extends State { return SearchField( inputFormatters: [UpperCaseTextFormatter()], itemHeight: 70, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), + suggestions: state.schools .map((School school) => SearchFieldListItem(school.name!, @@ -190,7 +191,8 @@ class _AddEducationScreenState extends State { UpperCaseTextFormatter() ], itemHeight: 100, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), + suggestions: state.programs .map((Course program) => SearchFieldListItem( diff --git a/lib/screens/profile/components/education/edit_modal.dart b/lib/screens/profile/components/education/edit_modal.dart index e5676be..1e43d2f 100644 --- a/lib/screens/profile/components/education/edit_modal.dart +++ b/lib/screens/profile/components/education/edit_modal.dart @@ -165,7 +165,8 @@ class _EditEducationScreenState extends State { }, controller: currentSchoolController, itemHeight: 70, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), + suggestions: state.schools .map((School school) => SearchFieldListItem(school.name!, @@ -230,7 +231,8 @@ class _EditEducationScreenState extends State { SuggestionAction.unfocus, controller: currentProgramController, itemHeight: 70, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), + suggestions: state.programs .map((Course program) => SearchFieldListItem( diff --git a/lib/screens/profile/components/learning_and_development_screen.dart b/lib/screens/profile/components/learning_and_development_screen.dart index 1fe52ba..e528c3d 100644 --- a/lib/screens/profile/components/learning_and_development_screen.dart +++ b/lib/screens/profile/components/learning_and_development_screen.dart @@ -45,7 +45,7 @@ class LearningAndDevelopmentScreen extends StatelessWidget { AttachmentCategory? selectedAttachmentCategory; List attachmentCategories = []; return Scaffold( - resizeToAvoidBottomInset: true, + appBar: AppBar( title: context.watch().state is LearningDevelopmentAddingState diff --git a/lib/screens/profile/components/learning_development/add_modal.dart b/lib/screens/profile/components/learning_development/add_modal.dart index e3d1e7d..32756bd 100644 --- a/lib/screens/profile/components/learning_development/add_modal.dart +++ b/lib/screens/profile/components/learning_development/add_modal.dart @@ -107,19 +107,6 @@ class _AddLearningAndDevelopmentScreenState final selectedTrainingController = TextEditingController(); DateTime? from; DateTime? to; - @override - void dispose() { - // fromDateController.dispose(); - // toDateController.dispose(); - // addTrainingController.dispose(); - // addTopicController.dispose(); - // topicFocusNode.dispose(); - - // addSponsorAgencyController.dispose(); - // sponsorByFocusNode.dispose(); - // sponsorAgencyCategoryFocusNode.dispose(); - super.dispose(); - } @override Widget build(BuildContext context) { @@ -132,37 +119,25 @@ class _AddLearningAndDevelopmentScreenState padding: const EdgeInsets.all(24), child: StatefulBuilder(builder: (context, setState) { return ListView( + shrinkWrap: true, children: [ ////Training SearchField SizedBox( child: show ? SearchableDropdownFormField.paginated( errorWidget: (value) { - return SomethingWentWrong( - message: value, - onpressed: () { - context - .read< - LearningDevelopmentBloc>() - .add( - GetLearningDevelopments( - profileId: widget - .profileId, - token: - widget.token)); - }); + return Text(value!); }, noRecordTex: SizedBox( width: double.infinity, - height: 300, + height: 100, child: EmptyWidget( controller: addTrainingController, onpressed: () { setState(() { show = false; showOtherInputs = true; - selectedTrainingController - .text = + selectedTrainingController.text = addTrainingController.text .toUpperCase(); selectedTraining = @@ -171,8 +146,7 @@ class _AddLearningAndDevelopmentScreenState title: selectedTrainingController .text); - addTrainingController.text = - ""; + addTrainingController.text = ""; Navigator.of(context).pop(); Navigator.of(context).pop(); }); @@ -187,20 +161,16 @@ class _AddLearningAndDevelopmentScreenState width: double.infinity, child: Card( child: Padding( - padding: - const EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: child), ), ); }, - validator: - FormBuilderValidators.required( - errorText: - "This field is required"), - paginatedRequest: (int page, - String? searchKey) async { - List - paginatedList=[]; + validator: FormBuilderValidators.required( + errorText: "This field is required"), + paginatedRequest: + (int page, String? searchKey) async { + List paginatedList = []; try { paginatedList = await LearningDevelopmentServices @@ -209,12 +179,9 @@ class _AddLearningAndDevelopmentScreenState page: page, key: searchKey ??= ""); } catch (e) { - context - .read() - .add(CallErrorState( - message: e.toString())); + debugPrint(e.toString()); } - return paginatedList.map((e) { + return paginatedList.map((e) { return SearchableDropdownMenuItem( value: e, onTap: () {}, @@ -234,17 +201,14 @@ class _AddLearningAndDevelopmentScreenState selectedTraining = LearningDevelopmentType( id: null, - title: e.title! - .title); + title: e.title!.title); } show = false; showOtherInputs = true; - selectedTrainingController - .text = + selectedTrainingController.text = e.title!.title!; - Navigator.of(context) - .pop(); + Navigator.of(context).pop(); }); }, e: e, @@ -276,31 +240,25 @@ class _AddLearningAndDevelopmentScreenState ? FormBuilderTextField( maxLines: 5, readOnly: true, - controller: - selectedTrainingController, + controller: selectedTrainingController, name: "", decoration: - normalTextFieldStyle("", "") - .copyWith( - labelText: "Training", - suffixIcon: IconButton( - onPressed: () { - setState(() { - selectedConductedTraining = - null; - selectedTrainingController - .text = ""; - show = true; - showTrainingDetails = - false; - showOtherInputs = - false; - selectedTraining = - null; - }); - }, - icon: const Icon( - Icons.close))), + normalTextFieldStyle("", "").copyWith( + labelText: "Training", + suffixIcon: IconButton( + onPressed: () { + setState(() { + selectedConductedTraining = + null; + selectedTrainingController + .text = ""; + show = true; + showTrainingDetails = false; + showOtherInputs = false; + selectedTraining = null; + }); + }, + icon: const Icon(Icons.close))), ) : const SizedBox()), @@ -308,20 +266,15 @@ class _AddLearningAndDevelopmentScreenState SizedBox( child: showTrainingDetails ? TrainingDetails( - trainingTitle: - selectedConductedTraining! - .learningDevelopmentType! - .title!, - totalHours: selectedConductedTraining! - .totalHours!, + trainingTitle: selectedConductedTraining! + .learningDevelopmentType!.title!, + totalHours: + selectedConductedTraining!.totalHours!, trainingTopic: - selectedConductedTraining! - .topic!.title!, - toDate: selectedConductedTraining! - .toDate + selectedConductedTraining!.topic!.title!, + toDate: selectedConductedTraining!.toDate .toString(), - fromDate: selectedConductedTraining! - .fromDate! + fromDate: selectedConductedTraining!.fromDate! .toString(), conductedBy: selectedConductedTraining! .conductedBy!.name!) @@ -340,22 +293,17 @@ class _AddLearningAndDevelopmentScreenState FormBuilderDropdown< LearningDevelopmentType>( decoration: normalTextFieldStyle( - "Learning Development Type *", - ""), - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), + "Learning Development Type *", ""), + validator: FormBuilderValidators.required( + errorText: "This field is required"), name: "types", items: state.types .map((e) => DropdownMenuItem< LearningDevelopmentType>( - value: e, - child: Text(e.title!))) + value: e, child: Text(e.title!))) .toList(), onChanged: (value) { - selectedLearningDevelopmentType = - value; + selectedLearningDevelopmentType = value; }, ), @@ -371,7 +319,8 @@ class _AddLearningAndDevelopmentScreenState ], focusNode: topicFocusNode, itemHeight: 100, - suggestionsDecoration: box1(), + suggestionsDecoration: + searchFieldDecoration(), suggestions: state.topics .map((LearningDevelopmentType topic) => @@ -379,28 +328,24 @@ class _AddLearningAndDevelopmentScreenState topic.title!, item: topic, child: Padding( - padding: const EdgeInsets + padding: + const EdgeInsets .symmetric( - horizontal: - 10), + horizontal: 10), child: ListTile( title: Text( - topic - .title!, - softWrap: - true, + topic.title!, + softWrap: true, ), )))) .toList(), searchInputDecoration: - normalTextFieldStyle( - "Topic *", "") + normalTextFieldStyle("Topic *", "") .copyWith( - suffixIcon: - IconButton( - icon: const Icon( - Icons.arrow_drop_down), + suffixIcon: IconButton( + icon: + const Icon(Icons.arrow_drop_down), onPressed: () { topicFocusNode.unfocus(); }, @@ -415,8 +360,7 @@ class _AddLearningAndDevelopmentScreenState selectedTopic = LearningDevelopmentType( id: null, - title: topic - .item!.title); + title: topic.item!.title); } setState(() { topicFocusNode.unfocus(); @@ -425,23 +369,21 @@ class _AddLearningAndDevelopmentScreenState ////EMPTY WIDGET emptyWidget: EmptyWidget( title: "Add Topic", - controller: - addTopicController, + controller: addTopicController, onpressed: () { setState(() { LearningDevelopmentType newTopic = LearningDevelopmentType( id: null, - title: addTopicController - .text - .toUpperCase()); - state.topics.insert( - 0, newTopic); - topicFocusNode - .unfocus(); - addTopicController - .text = ""; + title: + addTopicController + .text + .toUpperCase()); + state.topics + .insert(0, newTopic); + topicFocusNode.unfocus(); + addTopicController.text = ""; Navigator.pop(context); }); }), @@ -461,56 +403,47 @@ class _AddLearningAndDevelopmentScreenState width: screenWidth, child: StatefulBuilder( builder: (context, setState) { - return StatefulBuilder(builder: - (context, setState) { + return StatefulBuilder( + builder: (context, setState) { return Row( children: [ //// FROM DATE Flexible( flex: 1, child: DateTimePicker( - validator: - FormBuilderValidators - .required( - errorText: - "This field is required"), - use24HourFormat: - false, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + use24HourFormat: false, icon: const Icon( - Icons - .date_range), + Icons.date_range), controller: fromDateController, - firstDate: - DateTime(1990), - lastDate: - DateTime(2100), - + firstDate: DateTime(1990), + lastDate: DateTime(2100), onChanged: (value) { setState(() { - from = DateTime - .parse( - value); + from = DateTime.parse( + value); }); }, - initialDate: to == - null + initialDate: to == null ? DateTime.now() : to!.subtract( const Duration( - days: - 1)), + days: 1)), timeHintText: "Date of Examination/Conferment", - decoration: normalTextFieldStyle( - "From *", - "From *") - .copyWith( - prefixIcon: - const Icon( + decoration: + normalTextFieldStyle( + "From *", + "From *") + .copyWith( + prefixIcon: + const Icon( Icons.date_range, - color: Colors - .black87, + color: Colors.black87, )), initialValue: null, )), @@ -521,40 +454,31 @@ class _AddLearningAndDevelopmentScreenState Flexible( flex: 1, child: DateTimePicker( - validator: - FormBuilderValidators - .required( - errorText: - "This field is required"), - controller: - toDateController, - firstDate: - DateTime(1990), - + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + controller: toDateController, + firstDate: DateTime(1990), onChanged: (value) { setState(() { - to = DateTime - .parse(value); + to = + DateTime.parse(value); }); }, - initialDate: from == - null + initialDate: from == null ? DateTime.now() : from!.add( const Duration( days: 1)), - lastDate: - DateTime(2100), + lastDate: DateTime(2100), decoration: normalTextFieldStyle( - "To *", - "To *") + "To *", "To *") .copyWith( - prefixIcon: - const Icon( + prefixIcon: const Icon( Icons.date_range, - color: Colors - .black87, + color: Colors.black87, ), ), initialValue: null, @@ -573,10 +497,8 @@ class _AddLearningAndDevelopmentScreenState validator: numericRequired, name: "total_hours", decoration: normalTextFieldStyle( - "Total Hours Conducted *", - "0"), - keyboardType: - TextInputType.number, + "Total Hours Conducted *", "0"), + keyboardType: TextInputType.number, ), const SizedBox( height: 12, @@ -595,19 +517,14 @@ class _AddLearningAndDevelopmentScreenState overseas = value!; }); }, - decoration: - normalTextFieldStyle( - "Overseas Address?", - ''), + decoration: normalTextFieldStyle( + "Overseas Address?", ''), name: 'overseas', - title: Text(overseas - ? "YES" - : "NO"), + title: + Text(overseas ? "YES" : "NO"), ), SizedBox( - height: overseas == true - ? 8 - : 0, + height: overseas == true ? 8 : 0, ), SizedBox( child: overseas == false @@ -622,16 +539,16 @@ class _AddLearningAndDevelopmentScreenState autovalidateMode: AutovalidateMode .onUserInteraction, - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), onChanged: (Region? region) async { if (selectedRegion != region) { - setState( - () { + setState(() { provinceCall = true; }); @@ -640,8 +557,7 @@ class _AddLearningAndDevelopmentScreenState getProvinces(); } }, - initialValue: - null, + initialValue: null, decoration: normalTextFieldStyle( "Region*", @@ -653,11 +569,9 @@ class _AddLearningAndDevelopmentScreenState region) { return DropdownMenuItem< Region>( - value: - region, - child: Text( - region - .description!)); + value: region, + child: Text(region + .description!)); }).toList(), ), const SizedBox( @@ -666,8 +580,7 @@ class _AddLearningAndDevelopmentScreenState //// PROVINCE DROPDOWN SizedBox( height: 60, - child: - ModalProgressHUD( + child: ModalProgressHUD( color: Colors .transparent, inAsyncCall: @@ -677,11 +590,11 @@ class _AddLearningAndDevelopmentScreenState autovalidateMode: AutovalidateMode .onUserInteraction, - validator: (value) => value == null - ? 'required' - : null, - isExpanded: - true, + validator: (value) => + value == null + ? 'required' + : null, + isExpanded: true, value: selectedProvince, onChanged: @@ -689,8 +602,7 @@ class _AddLearningAndDevelopmentScreenState province) { if (selectedProvince != province) { - setState( - () { + setState(() { cityCall = true; }); @@ -702,42 +614,45 @@ class _AddLearningAndDevelopmentScreenState items: provinces == null ? [] - : provinces!.map>((Province + : provinces!.map< + DropdownMenuItem< + Province>>((Province province) { return DropdownMenuItem( - value: province, - child: FittedBox( - child: Text(province.description!), + value: + province, + child: + FittedBox( + child: + Text(province.description!), )); }).toList(), - decoration: normalTextFieldStyle( - "Province*", - "Province")), + decoration: + normalTextFieldStyle( + "Province*", + "Province")), ), ), ////CITY MUNICIPALITY SizedBox( height: 60, - child: - ModalProgressHUD( - color: Colors - .white, - inAsyncCall: - cityCall, + child: ModalProgressHUD( + color: Colors.white, + inAsyncCall: cityCall, child: DropdownButtonFormField< CityMunicipality>( - validator: FormBuilderValidators.required( - errorText: - "This field is required"), - isExpanded: - true, + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + isExpanded: true, onChanged: (CityMunicipality? city) { if (selectedMunicipality != city) { - setState( - () { + setState(() { barangayCall = true; }); @@ -755,12 +670,15 @@ class _AddLearningAndDevelopmentScreenState null ? [] : citymuns!.map< - DropdownMenuItem< - CityMunicipality>>((CityMunicipality - c) { + DropdownMenuItem< + CityMunicipality>>( + (CityMunicipality + c) { return DropdownMenuItem( - value: c, - child: Text(c.description!)); + value: + c, + child: Text( + c.description!)); }).toList(), ), ), @@ -768,25 +686,24 @@ class _AddLearningAndDevelopmentScreenState //// BARANGAY SizedBox( height: 60, - child: - ModalProgressHUD( - color: Colors - .white, + child: ModalProgressHUD( + color: Colors.white, inAsyncCall: barangayCall, - child: DropdownButtonFormField< - Barangay>( - isExpanded: - true, + child: + DropdownButtonFormField< + Barangay>( + isExpanded: true, onChanged: (Barangay? baragay) { selectedBarangay = baragay; }, - decoration: normalTextFieldStyle( - "Barangay*", - "Barangay"), + decoration: + normalTextFieldStyle( + "Barangay*", + "Barangay"), value: selectedBarangay, items: barangays == @@ -797,8 +714,10 @@ class _AddLearningAndDevelopmentScreenState Barangay>>((Barangay barangay) { return DropdownMenuItem( - value: barangay, - child: Text(barangay.description!)); + value: + barangay, + child: Text( + barangay.description!)); }).toList(), ), ), @@ -808,28 +727,25 @@ class _AddLearningAndDevelopmentScreenState //// COUNTRY DROPDOWN : SizedBox( height: 60, - child: - FormBuilderDropdown< - Country>( - initialValue: - null, - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), - items: state - .countries - .map< + child: FormBuilderDropdown< + Country>( + initialValue: null, + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + items: state.countries.map< DropdownMenuItem< - Country>>((Country - country) { + Country>>( + (Country country) { return DropdownMenuItem< Country>( - value: - country, + value: country, child: FittedBox( child: Text( - country.name!))); + country + .name!))); }).toList(), name: 'country', decoration: @@ -837,10 +753,8 @@ class _AddLearningAndDevelopmentScreenState "Country*", "Country"), onChanged: - (Country? - value) { - selectedCountry = - value; + (Country? value) { + selectedCountry = value; }, ), ), @@ -866,28 +780,24 @@ class _AddLearningAndDevelopmentScreenState itemHeight: 100, focusNode: conductedByFocusNode, - suggestions: state - .conductedBy - .map((Agency - agency) => + suggestions: state.conductedBy + .map((Agency agency) => SearchFieldListItem( - agency - .name!, - item: - agency, - child: - ListTile( - title: - Text( - agency - .name!, + agency.name!, + item: agency, + child: ListTile( + title: Text( + agency.name!, overflow: - TextOverflow.visible, + TextOverflow + .visible, ), - subtitle: Text(agency.privateEntity == + subtitle: Text(agency + .privateEntity == true ? "Private" - : agency.privateEntity == false + : agency.privateEntity == + false ? "Government" : ""), ))) @@ -900,33 +810,29 @@ class _AddLearningAndDevelopmentScreenState suffixIcon: GestureDetector( child: const Icon( - Icons - .arrow_drop_down, + Icons.arrow_drop_down, ), onTap: () => conductedByFocusNode .unfocus(), )), ////SELETECTED - onSuggestionTap: - (agency) { + onSuggestionTap: (agency) { setState(() { - if (agency.item - ?.id != + if (agency.item?.id != null) { selectedConductedByAgency = Agency( - name: - null, + name: null, id: agency - .item! - .id); + .item!.id); } else { - selectedConductedByAgency = Agency( - id: null, - name: agency - .item! - .name); + selectedConductedByAgency = + Agency( + id: null, + name: agency + .item! + .name); } if (agency.item! @@ -947,45 +853,37 @@ class _AddLearningAndDevelopmentScreenState }); }, validator: (agency) { - if (agency! - .isEmpty) { + if (agency!.isEmpty) { return "This field is required"; } return null; }, ////conducter empty widget - emptyWidget: - EmptyWidget( - controller: - addConductedByController, - onpressed: - () { - setState( - () { - Agency newAgency = Agency( - id: - null, - name: addConductedByController - .text - .toUpperCase(), - category: - null, - privateEntity: - null); - state - .conductedBy - .insert( - 0, - newAgency); + emptyWidget: EmptyWidget( + controller: + addConductedByController, + onpressed: () { + setState(() { + Agency newAgency = Agency( + id: null, + name: addConductedByController + .text + .toUpperCase(), + category: null, + privateEntity: + null); + state.conductedBy + .insert( + 0, newAgency); - addConductedByController - .text = ""; - Navigator.pop( - context); - }); - }, - title: - "Add Conducted By Agency")), + addConductedByController + .text = ""; + Navigator.pop( + context); + }); + }, + title: + "Add Conducted By Agency")), SizedBox( height: showConductedByAgencyCategory @@ -1002,37 +900,40 @@ class _AddLearningAndDevelopmentScreenState .up, focusNode: conductedByAgencyCategoryFocusNode, - itemHeight: - 70, + itemHeight: 70, suggestions: state .agencyCategory - .map((Category category) => SearchFieldListItem( - category - .name!, - item: - category, - child: - ListTile( - title: Text(category.name!), - subtitle: Text(category.industryClass!.name!), - ))) + .map((Category + category) => + SearchFieldListItem( + category + .name!, + item: + category, + child: + ListTile( + title: + Text(category.name!), + subtitle: Text(category + .industryClass! + .name!), + ))) .toList(), emptyWidget: Container( - height: - 100, + height: 100, decoration: box1(), child: const Center( - child: - Text("No result found ...")), + child: Text( + "No result found ...")), ), onSuggestionTap: (agencyCategory) { - setState( - () { + setState(() { selectedConductedByAgencyCategory = - agencyCategory.item; + agencyCategory + .item; selectedConductedByAgency = Agency( id: selectedConductedByAgency ?.id, @@ -1046,23 +947,21 @@ class _AddLearningAndDevelopmentScreenState .unfocus(); }); }, - searchInputDecoration: normalTextFieldStyle( - "Category *", - "") - .copyWith( - suffixIcon: - IconButton( - icon: const Icon( - Icons - .arrow_drop_down), - onPressed: - () { + searchInputDecoration: + normalTextFieldStyle( + "Category *", + "") + .copyWith( + suffixIcon: + IconButton( + icon: const Icon(Icons + .arrow_drop_down), + onPressed: () { conductedByAgencyCategoryFocusNode .unfocus(); }, )), - validator: - (value) { + validator: (value) { if (value! .isEmpty) { return "This field is required"; @@ -1080,45 +979,46 @@ class _AddLearningAndDevelopmentScreenState ? 12 : 0), SizedBox( - child: showConductedByAgencyPrivateRadio - ? FormBuilderSwitch( - initialValue: - conductedByCategoryIsPrivate, - title: Text( - conductedByCategoryIsPrivate - ? "YES" - : "NO"), - decoration: normalTextFieldStyle( - "Private Entity?", - 'Private Entity?'), + child: + showConductedByAgencyPrivateRadio + ? FormBuilderSwitch( + initialValue: + conductedByCategoryIsPrivate, + title: Text( + conductedByCategoryIsPrivate + ? "YES" + : "NO"), + decoration: normalTextFieldStyle( + "Private Entity?", + 'Private Entity?'), - ////onvhange private sector - onChanged: - (value) { - setState( - () { - conductedByCategoryIsPrivate = - value!; - selectedConductedByAgency = Agency( - category: selectedConductedByAgency - ?.category, - id: selectedConductedByAgency - ?.id, - name: selectedConductedByAgency! - .name, - privateEntity: - conductedByCategoryIsPrivate); - conductedByAgencyCategoryFocusNode - .unfocus(); - }); - }, - name: - 'sponsorAgencyPrivate', - validator: - FormBuilderValidators - .required(), - ) - : const SizedBox()), + ////onvhange private sector + onChanged: + (value) { + setState(() { + conductedByCategoryIsPrivate = + value!; + selectedConductedByAgency = Agency( + category: + selectedConductedByAgency + ?.category, + id: selectedConductedByAgency + ?.id, + name: selectedConductedByAgency! + .name, + privateEntity: + conductedByCategoryIsPrivate); + conductedByAgencyCategoryFocusNode + .unfocus(); + }); + }, + name: + 'sponsorAgencyPrivate', + validator: + FormBuilderValidators + .required(), + ) + : const SizedBox()), ]), )), ], @@ -1144,8 +1044,8 @@ class _AddLearningAndDevelopmentScreenState hasSponsor = value!; }); }, - decoration: normalTextFieldStyle( - "Has Sponsor?", ''), + decoration: + normalTextFieldStyle("Has Sponsor?", ''), name: 'sponsor', title: Text(hasSponsor ? "YES" : "NO"), ), @@ -1162,18 +1062,15 @@ class _AddLearningAndDevelopmentScreenState UpperCaseTextFormatter() ], itemHeight: 110, - focusNode: - sponsorByFocusNode, - suggestions: state - .sponsorAgencies + focusNode: sponsorByFocusNode, + suggestions: state.sponsorAgencies .map((Agency agency) => SearchFieldListItem( agency.name!, item: agency, child: ListTile( title: Text( - agency - .name!, + agency.name!, overflow: TextOverflow .visible, @@ -1190,8 +1087,7 @@ class _AddLearningAndDevelopmentScreenState .toList(), searchInputDecoration: normalTextFieldStyle( - " Sponsor Agency *", - "") + " Sponsor Agency *", "") .copyWith( suffixIcon: GestureDetector( @@ -1199,30 +1095,25 @@ class _AddLearningAndDevelopmentScreenState Icons.arrow_drop_down, ), onTap: () => - sponsorByFocusNode - .unfocus(), + sponsorByFocusNode.unfocus(), )), ////SELETECTED onSuggestionTap: (agency) { setState(() { - if (agency.item?.id != - null) { + if (agency.item?.id != null) { selectedSponsorAgency = Agency( name: null, - id: agency - .item! - .id); + id: agency.item!.id); } else { selectedSponsorAgency = Agency( id: null, name: agency - .item! - .name); + .item!.name); } - if (agency.item! - .privateEntity == + if (agency + .item!.privateEntity == null) { showSponsorCategoryAgency = true; @@ -1234,8 +1125,7 @@ class _AddLearningAndDevelopmentScreenState showSponsorAgencyPrivateRadio = false; } - sponsorByFocusNode - .unfocus(); + sponsorByFocusNode.unfocus(); }); }, validator: (agency) { @@ -1252,112 +1142,99 @@ class _AddLearningAndDevelopmentScreenState setState(() { Agency newAgency = Agency( id: null, - name: addSponsorAgencyController - .text - .toUpperCase(), + name: + addSponsorAgencyController + .text + .toUpperCase(), category: null, - privateEntity: - null); - state - .sponsorAgencies - .insert(0, - newAgency); + privateEntity: null); + state.sponsorAgencies + .insert(0, newAgency); addSponsorAgencyController .text = ""; - Navigator.pop( - context); + Navigator.pop(context); }); }, - title: - "Add Sponsor Agency")), + title: "Add Sponsor Agency")), SizedBox( - height: - showSponsorCategoryAgency - ? 12 - : 0, + height: showSponsorCategoryAgency + ? 12 + : 0, ), ////Sponsor Agency Category SizedBox( - child: - showSponsorCategoryAgency - ? SearchField( - suggestionDirection: - SuggestionDirection - .up, - focusNode: - sponsorAgencyCategoryFocusNode, - itemHeight: 70, - suggestions: state - .agencyCategory - .map((Category - category) => - SearchFieldListItem( - category - .name!, - item: - category, - child: - ListTile( - title: - Text(category.name!), - subtitle: - Text(category.industryClass!.name!), - ))) - .toList(), - emptyWidget: - Container( - height: 100, - decoration: - box1(), - child: const Center( - child: Text( - "No result found ...")), - ), - onSuggestionTap: - (agencyCategory) { - setState(() { - selectedSponsorAgencyCategory = - agencyCategory - .item; - selectedSponsorAgency = Agency( - id: selectedSponsorAgency - ?.id, - name: selectedSponsorAgency! + child: showSponsorCategoryAgency + ? SearchField( + suggestionDirection: + SuggestionDirection.up, + focusNode: + sponsorAgencyCategoryFocusNode, + itemHeight: 70, + suggestions: state + .agencyCategory + .map((Category + category) => + SearchFieldListItem( + category.name!, + item: category, + child: ListTile( + title: Text( + category + .name!), + subtitle: Text( + category + .industryClass! + .name!), + ))) + .toList(), + emptyWidget: Container( + height: 100, + decoration: box1(), + child: const Center( + child: Text( + "No result found ...")), + ), + onSuggestionTap: + (agencyCategory) { + setState(() { + selectedSponsorAgencyCategory = + agencyCategory.item; + selectedSponsorAgency = Agency( + id: selectedSponsorAgency + ?.id, + name: + selectedSponsorAgency! .name, - category: - selectedSponsorAgencyCategory, - privateEntity: - sponsorAgencyIsPrivate); - sponsorAgencyCategoryFocusNode - .unfocus(); - }); - }, - searchInputDecoration: - normalTextFieldStyle( - "Category *", - "") - .copyWith( - suffixIcon: - IconButton( - icon: const Icon( - Icons - .arrow_drop_down), - onPressed: () { - sponsorAgencyCategoryFocusNode - .unfocus(); - }, - )), - validator: - (value) { - if (value! - .isEmpty) { - return "This field is required"; - } - return null; - }, - ) - : const SizedBox(), + category: + selectedSponsorAgencyCategory, + privateEntity: + sponsorAgencyIsPrivate); + sponsorAgencyCategoryFocusNode + .unfocus(); + }); + }, + searchInputDecoration: + normalTextFieldStyle( + "Category *", "") + .copyWith( + suffixIcon: + IconButton( + icon: const Icon( + Icons.arrow_drop_down), + onPressed: () { + sponsorAgencyCategoryFocusNode + .unfocus(); + }, + )), + validator: (value) { + if (value!.isEmpty) { + return "This field is required"; + } + return null; + }, + ) + : const SizedBox(), ), ////Sponsor Agency Private Radio @@ -1367,47 +1244,48 @@ class _AddLearningAndDevelopmentScreenState ? 12 : 0), SizedBox( - child: - showSponsorAgencyPrivateRadio - ? FormBuilderSwitch( - initialValue: - sponsorAgencyIsPrivate, - title: Text( - sponsorAgencyIsPrivate - ? "YES" - : "NO"), - decoration: normalTextFieldStyle( + child: showSponsorAgencyPrivateRadio + ? FormBuilderSwitch( + initialValue: + sponsorAgencyIsPrivate, + title: Text( + sponsorAgencyIsPrivate + ? "YES" + : "NO"), + decoration: + normalTextFieldStyle( "Private Entity?", 'Private Entity?'), - ////onvhange private sector - onChanged: - (value) { - setState(() { - sponsorAgencyIsPrivate = - value!; - selectedSponsorAgency = Agency( - category: - selectedSponsorAgency - ?.category, - id: selectedSponsorAgency - ?.id, - name: selectedSponsorAgency! + ////onvhange private sector + onChanged: (value) { + setState(() { + sponsorAgencyIsPrivate = + value!; + selectedSponsorAgency = Agency( + category: + selectedSponsorAgency + ?.category, + id: selectedSponsorAgency + ?.id, + name: + selectedSponsorAgency! .name, - privateEntity: - selectedSponsorAgency?.privateEntity); - sponsorAgencyCategoryFocusNode - .unfocus(); - }); - }, + privateEntity: + selectedSponsorAgency + ?.privateEntity); + sponsorAgencyCategoryFocusNode + .unfocus(); + }); + }, - name: - 'sponsorAgencyPrivate', - validator: - FormBuilderValidators - .required(), - ) - : const SizedBox()), + name: + 'sponsorAgencyPrivate', + validator: + FormBuilderValidators + .required(), + ) + : const SizedBox()), ]), ) : const SizedBox(), @@ -1424,16 +1302,17 @@ class _AddLearningAndDevelopmentScreenState name: "total_hours_attended", keyboardType: TextInputType.number, decoration: normalTextFieldStyle( - "Total Hours Attended *", - "Total Hours Attended *"), + "Total Hours Attended *", "Total Hours Attended *"), ), - const SizedBox(height: 16,), - SizedBox( + const SizedBox( + height: 16, + ), + SizedBox( width: double.infinity, height: 60, child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), + style: + mainBtnStyle(primary, Colors.transparent, second), child: const Text(submit), onPressed: () { if (formKey.currentState!.saveAndValidate()) { @@ -1477,8 +1356,8 @@ class _AddLearningAndDevelopmentScreenState venue: venue, toDate: DateTime.parse(toDateController.text), - fromDate: DateTime.parse( - fromDateController.text), + fromDate: + DateTime.parse(fromDateController.text), totalHours: double.parse(formKey .currentState!.value['total_hours']), conductedBy: selectedConductedByAgency, diff --git a/lib/screens/profile/components/learning_development/edit_modal.dart b/lib/screens/profile/components/learning_development/edit_modal.dart index 6937150..e71edb1 100644 --- a/lib/screens/profile/components/learning_development/edit_modal.dart +++ b/lib/screens/profile/components/learning_development/edit_modal.dart @@ -267,7 +267,7 @@ class _EditLearningAndDevelopmentScreenState controller: currentTopicController, focusNode: topicFocusNode, itemHeight: 100, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), suggestions: state.topics .map((LearningDevelopmentType topic) => diff --git a/lib/screens/profile/components/voluntary_works/add_modal.dart b/lib/screens/profile/components/voluntary_works/add_modal.dart index ffea1bf..dd51b4e 100644 --- a/lib/screens/profile/components/voluntary_works/add_modal.dart +++ b/lib/screens/profile/components/voluntary_works/add_modal.dart @@ -92,7 +92,7 @@ class _AddVoluntaryWorkScreenState extends State { return SearchField( inputFormatters: [UpperCaseTextFormatter()], itemHeight: 70, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), suggestions: state.positions .map((PositionTitle position) => SearchFieldListItem(position.title!, diff --git a/lib/screens/profile/components/voluntary_works/edit_modal.dart b/lib/screens/profile/components/voluntary_works/edit_modal.dart index 29b420c..75d578c 100644 --- a/lib/screens/profile/components/voluntary_works/edit_modal.dart +++ b/lib/screens/profile/components/voluntary_works/edit_modal.dart @@ -128,7 +128,7 @@ class _EditVoluntaryWorkScreenState extends State { inputFormatters: [UpperCaseTextFormatter()], controller: positionController, itemHeight: 70, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), suggestions: state.positions .map((PositionTitle position) => SearchFieldListItem(position.title!, diff --git a/lib/screens/profile/components/work_history/add_modal.dart b/lib/screens/profile/components/work_history/add_modal.dart index 5c353b4..c536c1b 100644 --- a/lib/screens/profile/components/work_history/add_modal.dart +++ b/lib/screens/profile/components/work_history/add_modal.dart @@ -98,7 +98,7 @@ class _AddWorkHistoryScreenState extends State { return SearchField( inputFormatters: [UpperCaseTextFormatter()], itemHeight: 70, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), suggestions: state.agencyPositions .map((PositionTitle position) => SearchFieldListItem(position.title!, diff --git a/lib/screens/profile/components/work_history/edit_modal.dart b/lib/screens/profile/components/work_history/edit_modal.dart index 5e8eafd..38e0a9b 100644 --- a/lib/screens/profile/components/work_history/edit_modal.dart +++ b/lib/screens/profile/components/work_history/edit_modal.dart @@ -121,7 +121,7 @@ class _EditWorkHistoryScreenState extends State { inputFormatters: [UpperCaseTextFormatter()], controller: oldPositionController, itemHeight: 100, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), suggestions: state.agencyPositions .map((PositionTitle position) => SearchFieldListItem(position.title!, diff --git a/lib/screens/profile/profile.dart b/lib/screens/profile/profile.dart index fe9d5a4..f6c9840 100644 --- a/lib/screens/profile/profile.dart +++ b/lib/screens/profile/profile.dart @@ -48,360 +48,378 @@ import '../unit2/homepage.dart/components/menu.dart'; import 'components/main_menu.dart'; import 'components/submenu.dart'; -class ProfileInfo extends StatelessWidget { +class ProfileInfo extends StatefulWidget { const ProfileInfo({super.key}); + @override + State createState() => _ProfileInfoState(); +} + +class _ProfileInfoState extends State { @override Widget build(BuildContext context) { int? profileId; String? token; Profile profile; - return Scaffold( - appBar: AppBar( - backgroundColor: primary, - centerTitle: true, - title: const Text('Profile'), - ), - body: ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocBuilder(builder: (context, state) { - if (state is UserLoggedIn) { - profileId = state.userData!.user!.login!.user!.profileId; - token = state.userData!.user!.login!.token!; - if (globalCurrentProfile == null) { - profile = state.userData!.employeeInfo!.profile!; - } else { - profile = globalCurrentProfile!; + return WillPopScope( + onWillPop: () async{ + setState(() { + + }); + return true; + }, + child: Scaffold( + appBar: AppBar( + backgroundColor: primary, + centerTitle: true, + title: const Text('Profile'), + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocBuilder(builder: (context, state) { + if (state is UserLoggedIn) { + profileId = state.userData!.user!.login!.user!.profileId; + token = state.userData!.user!.login!.token!; + if (globalCurrentProfile == null) { + + profile = state.userData!.employeeInfo!.profile!; + globalCurrentProfile = profile; + } else { + profile = globalCurrentProfile!; + } + return BlocConsumer( + listener: ( + context, + state, + ) { + if (state is ProfileLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is ProfileLoaded || + state is ProfileErrorState || + state is BasicInformationEditingState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + }, + builder: (context, state) { + if (state is ProfileLoaded) { + return Container( + padding: const EdgeInsets.symmetric( + vertical: 12, horizontal: 12), + child: ListView( + children: [ + Text( + "View and Update your Profile Information", + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyLarge, + ), + ExpandableGroup( + collapsedIcon: + const Icon(Icons.keyboard_arrow_down), + expandedIcon: const Icon(Icons.keyboard_arrow_up), + header: const ListTile( + leading: Icon( + Elusive.address_book, + color: primary, + ), + title: Text( + "Basic Information", + style: TextStyle(fontWeight: FontWeight.bold), + ), + ), + items: [ + subMenu(Icons.person, "Primary", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider.value( + value: ProfileBloc() + ..add(GetPrimaryBasicInfo( + primaryBasicInformation: profile)), + child: PrimaryInfo( + token: token!, + profileId: profileId!, + ), + ); + })); + }), + subMenu(Icons.home, "Addresses", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => AddressBloc() + ..add(GetAddress( + addresses: state.profileInformation + .basicInfo.addresses)), + child: const AddressScreen(), + ); + })); + }), + subMenu(Icons.contact_mail, "Identifications", + () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => IdentificationBloc() + ..add(GetIdentifications( + identificationInformation: state + .profileInformation + .basicInfo + .identifications)), + child: const IdentificationsScreen(), + ); + })); + }), + subMenu(Icons.contact_phone, "Contact Info", + () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => ContactBloc() + ..add(GetContacts( + contactInformations: state + .profileInformation + .basicInfo + .contactInformation)), + child: const ContactInformationScreen(), + ); + })); + }), + subMenu(Icons.flag, "Citizenships", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => CitizenshipBloc() + ..add(GetCitizenship( + citizenship: state + .profileInformation + .basicInfo + .citizenships)), + child: CitizenShipScreen( + citizenships: state + .profileInformation + .basicInfo + .citizenships, + profileId: profileId!, token: token!), + ); + })); + }), + ]), + const Divider(), + MainMenu( + icon: Elusive.group, + title: "Family", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => FamilyBloc() + ..add(GetFamilies( + profileId: profileId!, token: token!)), + child: const FamilyBackgroundScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: FontAwesome5.graduation_cap, + title: "Education", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => EducationBloc() + ..add(GetEducationalBackground( + profileId: profileId!, token: token!)), + child: const EducationScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Icons.stars, + title: "Eligibility", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => EligibilityBloc() + ..add(GetEligibilities( + profileId: profileId!, token: token!)), + child: const EligibiltyScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: FontAwesome5.shopping_bag, + title: "Work History", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => WorkHistoryBloc() + ..add(GetWorkHistories( + profileId: profileId!, token: token!)), + child: const WorkHistoryScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: FontAwesome5.walking, + title: "Voluntary Work & Civic Services", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => VoluntaryWorkBloc() + ..add(GetVoluntarWorks( + profileId: profileId!, token: token!)), + child: const VolunataryWorkScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.lightbulb, + title: "Learning & Development", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => LearningDevelopmentBloc() + ..add(GetLearningDevelopments( + profileId: profileId!, token: token!)), + child: const LearningAndDevelopmentScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Brandico.codepen, + title: "Personal References", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => ReferencesBloc() + ..add(GetReferences( + profileId: profileId!, token: token!)), + child: const ReferencesScreen(), + ); + })); + }, + ), + ExpandableGroup( + collapsedIcon: + const Icon(Icons.keyboard_arrow_down), + expandedIcon: const Icon(Icons.keyboard_arrow_up), + header: const ListTile( + leading: Icon( + Icons.info, + color: primary, + ), + title: Text( + "Other Information", + style: TextStyle(fontWeight: FontWeight.bold), + ), + ), + items: [ + subMenu( + Icons.fitness_center, "Skills & Hobbies", + () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => HoobiesBloc() + ..add(GetSkillsHobbies( + profileId: profileId!, + token: token!)), + child: const SkillHobbiesScreen(), + ); + })); + }), + subMenu(FontAwesome5.certificate, + "Organization Memberships", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + OrganizationMembershipBloc() + ..add(GetOrganizationMembership( + profileId: profileId!, + token: token!)), + child: const OrgMembershipsScreen(), + ); + })); + }), + subMenu(Entypo.doc_text, + "Non-Academic Recognitions", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + NonAcademicRecognitionBloc() + ..add(GetNonAcademicRecognition( + profileId: profileId!, + token: token!)), + child: + const NonAcademicRecognitionScreen(), + ); + })); + }), + ]), + ExpandableGroup( + collapsedIcon: + const Icon(Icons.keyboard_arrow_down), + expandedIcon: const Icon(Icons.keyboard_arrow_up), + header: const ListTile( + leading: Icon( + FontAwesome5.laptop_house, + color: primary, + ), + title: Text( + "Assets", + style: TextStyle(fontWeight: FontWeight.bold), + ), + ), + items: [ + subMenu(ModernPictograms.home, + "Real Property Tax", () {}), + ]), + ], + ), + ); + } + if (state is ProfileLoading) { + return const LoadingScreen(); + } + if (state is ProfileErrorState) { + return SomethingWentWrong( + message: state.mesage, + onpressed: () { + BlocProvider.of(context).add( + LoadProfile(token: token!, userID: profileId!)); + }); + } + + return Container(); + }, + ); } - print(profile.lastName); - return BlocConsumer( - listener: ( - context, - state, - ) { - if (state is ProfileLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is ProfileLoaded || - state is ProfileErrorState || - state is BasicInformationEditingState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - builder: (context, state) { - if (state is ProfileLoaded) { - return Container( - padding: const EdgeInsets.symmetric( - vertical: 12, horizontal: 12), - child: ListView( - children: [ - Text( - "View and Update your Profile Information", - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodyLarge, - ), - ExpandableGroup( - collapsedIcon: - const Icon(Icons.keyboard_arrow_down), - expandedIcon: const Icon(Icons.keyboard_arrow_up), - header: const ListTile( - leading: Icon( - Elusive.address_book, - color: primary, - ), - title: Text( - "Basic Information", - style: TextStyle(fontWeight: FontWeight.bold), - ), - ), - items: [ - subMenu(Icons.person, "Primary", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider.value( - value: ProfileBloc() - ..add(GetPrimaryBasicInfo( - primaryBasicInformation: profile)), - child: PrimaryInfo( - token: token!, - profileId: profileId!, - ), - ); - })); - }), - subMenu(Icons.home, "Addresses", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => AddressBloc() - ..add(GetAddress( - addresses: state.profileInformation - .basicInfo.addresses)), - child: const AddressScreen(), - ); - })); - }), - subMenu(Icons.contact_mail, "Identifications", - () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => IdentificationBloc() - ..add(GetIdentifications( - identificationInformation: state - .profileInformation - .basicInfo - .identifications)), - child: const IdentificationsScreen(), - ); - })); - }), - subMenu(Icons.contact_phone, "Contact Info", - () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => ContactBloc() - ..add(GetContacts( - contactInformations: state - .profileInformation - .basicInfo - .contactInformation)), - child: const ContactInformationScreen(), - ); - })); - }), - subMenu(Icons.flag, "Citizenships", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => CitizenshipBloc() - ..add(GetCitizenship( - citizenship: state - .profileInformation - .basicInfo - .citizenships)), - child: CitizenShipScreen( - profileId: profileId!, token: token!), - ); - })); - }), - ]), - const Divider(), - MainMenu( - icon: Elusive.group, - title: "Family", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => FamilyBloc() - ..add(GetFamilies( - profileId: profileId!, token: token!)), - child: const FamilyBackgroundScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: FontAwesome5.graduation_cap, - title: "Education", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => EducationBloc() - ..add(GetEducationalBackground( - profileId: profileId!, token: token!)), - child: const EducationScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: Icons.stars, - title: "Eligibility", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => EligibilityBloc() - ..add(GetEligibilities( - profileId: profileId!, token: token!)), - child: const EligibiltyScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: FontAwesome5.shopping_bag, - title: "Work History", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => WorkHistoryBloc() - ..add(GetWorkHistories( - profileId: profileId!, token: token!)), - child: const WorkHistoryScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: FontAwesome5.walking, - title: "Voluntary Work & Civic Services", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => VoluntaryWorkBloc() - ..add(GetVoluntarWorks( - profileId: profileId!, token: token!)), - child: const VolunataryWorkScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: Elusive.lightbulb, - title: "Learning & Development", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => LearningDevelopmentBloc() - ..add(GetLearningDevelopments( - profileId: profileId!, token: token!)), - child: const LearningAndDevelopmentScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: Brandico.codepen, - title: "Personal References", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => ReferencesBloc() - ..add(GetReferences( - profileId: profileId!, token: token!)), - child: const ReferencesScreen(), - ); - })); - }, - ), - ExpandableGroup( - collapsedIcon: - const Icon(Icons.keyboard_arrow_down), - expandedIcon: const Icon(Icons.keyboard_arrow_up), - header: const ListTile( - leading: Icon( - Icons.info, - color: primary, - ), - title: Text( - "Other Information", - style: TextStyle(fontWeight: FontWeight.bold), - ), - ), - items: [ - subMenu( - Icons.fitness_center, "Skills & Hobbies", - () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => HoobiesBloc() - ..add(GetSkillsHobbies( - profileId: profileId!, - token: token!)), - child: const SkillHobbiesScreen(), - ); - })); - }), - subMenu(FontAwesome5.certificate, - "Organization Memberships", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => - OrganizationMembershipBloc() - ..add(GetOrganizationMembership( - profileId: profileId!, - token: token!)), - child: const OrgMembershipsScreen(), - ); - })); - }), - subMenu(Entypo.doc_text, - "Non-Academic Recognitions", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => - NonAcademicRecognitionBloc() - ..add(GetNonAcademicRecognition( - profileId: profileId!, - token: token!)), - child: - const NonAcademicRecognitionScreen(), - ); - })); - }), - ]), - ExpandableGroup( - collapsedIcon: - const Icon(Icons.keyboard_arrow_down), - expandedIcon: const Icon(Icons.keyboard_arrow_up), - header: const ListTile( - leading: Icon( - FontAwesome5.laptop_house, - color: primary, - ), - title: Text( - "Assets", - style: TextStyle(fontWeight: FontWeight.bold), - ), - ), - items: [ - subMenu(ModernPictograms.home, - "Real Property Tax", () {}), - ]), - ], - ), - ); - } - if (state is ProfileLoading) { - return const LoadingScreen(); - } - if (state is ProfileErrorState) { - return SomethingWentWrong( - message: state.mesage, - onpressed: () { - BlocProvider.of(context).add( - LoadProfile(token: token!, userID: profileId!)); - }); - } - - return Container(); - }, - ); - } - return Container(); - }), - )); + return Container(); + }), + )), + ); } } diff --git a/lib/screens/superadmin/agency/agency_screen.dart b/lib/screens/superadmin/agency/agency_screen.dart index 57c88dc..d2eaf07 100644 --- a/lib/screens/superadmin/agency/agency_screen.dart +++ b/lib/screens/superadmin/agency/agency_screen.dart @@ -5,6 +5,7 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:fluttericon/font_awesome_icons.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:searchfield/searchfield.dart'; import 'package:unit2/bloc/rbac/rbac_operations/agency/agency_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; @@ -28,6 +29,7 @@ class RbacAgencyScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + List agencies = []; List agencyCategory = []; Category? selectedAgencyCategory; bool? isPrivate; @@ -38,7 +40,37 @@ class RbacAgencyScreen extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("Agencies"), - actions: [ + actions: context.watch().state is AgencyLoadingState || context.watch().state is AgencyErrorState || context.watch().state is AgencyAddesState?[]:[ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: primary), + builder: (Agency rbac) { + return Column( + children: [ + ListTile( + title: Text(rbac.name!), + ), + const Divider(), + ], + ); + }, + filter: (Agency rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Agency found :("), + ), + items: agencies, + searchLabel: "Search Agency", + suggestion: const Center( + child: Text("Search agency by name"), + )), + ); + }, + icon: const Icon(Icons.search)), AddLeading(onPressed: () { parent = context; showDialog( @@ -220,6 +252,7 @@ class RbacAgencyScreen extends StatelessWidget { builder: (context, state) { final parent = context; if (state is AgenciesLoaded) { + agencies = state.agencies; agencyCategory = state.agencyCategory; if (state.agencies.isNotEmpty) { return ListView.builder( @@ -262,7 +295,7 @@ class RbacAgencyScreen extends StatelessWidget { }); } else { return const EmptyData( - message: "No Object available. Please click + to add."); + message: "No Agency available. Please click + to add."); } }if (state is AgencyErrorState) { return SomethingWentWrong( diff --git a/lib/screens/superadmin/assign_area/assign_area_screen.dart b/lib/screens/superadmin/assign_area/assign_area_screen.dart index c9fcd6d..0293f21 100644 --- a/lib/screens/superadmin/assign_area/assign_area_screen.dart +++ b/lib/screens/superadmin/assign_area/assign_area_screen.dart @@ -82,7 +82,7 @@ class _RbacAssignedAreaScreenState extends State { areaType = null; return AlertDialog( - title: const Text("Add New Role"), + title: const Text("Add New Assigned area"), content: FormBuilder( key: formKey, child: StatefulBuilder(builder: (context, setState) { @@ -1005,7 +1005,7 @@ class _RbacAssignedAreaScreenState extends State { if (state is AssignedAreaDeletedState) { if (state.success) { successAlert(context, "Delete Successfull!", - "Role Module Deleted Successfully", () { + "Assign Area Deleted Successfully", () { Navigator.of(context).pop(); context .read() @@ -1013,7 +1013,7 @@ class _RbacAssignedAreaScreenState extends State { }); } else { errorAlert( - context, "Delete Failed", "Role Module Delete Failed", + context, "Delete Failed", "Assign Area Deletion Failed", () { Navigator.of(context).pop(); context diff --git a/lib/screens/superadmin/module/module_screen.dart b/lib/screens/superadmin/module/module_screen.dart index 98d287f..554f1e4 100644 --- a/lib/screens/superadmin/module/module_screen.dart +++ b/lib/screens/superadmin/module/module_screen.dart @@ -5,7 +5,9 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/module/module_bloc.dart'; +import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/widgets/Leadings/add_leading.dart'; import 'package:unit2/widgets/error_state.dart'; @@ -23,83 +25,283 @@ class RbacModuleScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + final bloc = BlocProvider.of(context); + List modules = []; return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: primary, title: const Text("Module Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Module"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Module name *", "Module name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add( - AddRbacModule( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + actions: + context.watch().state is ModuleLoadingState || + context.watch().state is ModuleErrorState || + context.watch().state is ModuleAddedState || + context.watch().state is ModuleDeletedState || + context.watch().state is ModuleAddedState || + context.watch().state is ModuleUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + const SizedBox( + width: 12, + ), + Expanded( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext + context) { + return AlertDialog( + title: const Text( + "Update Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize + .min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Module name *", + "Module name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.shorthand, + validator: FormBuilderValidators + .maxLength( + 50, + errorText: + "Max characters only 50"), + name: + "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + ////Update + bloc.add(UpdateRbacModule( + moduleId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text("Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + ////delete + Navigator.pop(context); + confirmAlert(context, () { + context + .read() + .add(DeleteRbacModule( + moduleId: + rbac.id!)); + }, "Delete?", + "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Module found :("), + ), + items: modules, + searchLabel: "Search Module", + suggestion: const Center( + child: Text("Search module by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Module name *", "Module name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: + FormBuilderValidators.maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value['object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacModule( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -162,7 +364,7 @@ class RbacModuleScreen extends StatelessWidget { context.read().add(GetModule()); }); } else { - errorAlert(context, "Delete Failed", "Module Delete Failed", + errorAlert(context, "Delete Failed", "Module Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetModule()); @@ -174,6 +376,7 @@ class RbacModuleScreen extends StatelessWidget { final parent = context; if (state is ModuleLoaded) { if (state.module.isNotEmpty) { + modules = state.module; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), @@ -190,18 +393,22 @@ class RbacModuleScreen extends StatelessWidget { children: [ Expanded( child: Row( - children: [ - CircleAvatar(child: Text('${index+1}'),), - const SizedBox(width: 12,), - Text(state.module[index].name!, - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500, - color: primary)), - ], - )), + children: [ + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Text(state.module[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ], + )), AppPopupMenu( offset: const Offset(-10, -10), elevation: 3, @@ -211,7 +418,8 @@ class RbacModuleScreen extends StatelessWidget { context: context, builder: (BuildContext context) { return AlertDialog( - title: const Text("Update Module"), + title: + const Text("Update Module"), content: FormBuilder( key: formKey, child: Column( @@ -355,7 +563,7 @@ class RbacModuleScreen extends StatelessWidget { }); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: "No Module available. Please click + to add."); } } if (state is ModuleErrorState) { diff --git a/lib/screens/superadmin/module_objects/module_objects_screen.dart b/lib/screens/superadmin/module_objects/module_objects_screen.dart index 30007d0..9cf11bb 100644 --- a/lib/screens/superadmin/module_objects/module_objects_screen.dart +++ b/lib/screens/superadmin/module_objects/module_objects_screen.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; @@ -33,106 +32,121 @@ class RbacModuleObjectsScreen extends StatelessWidget { List selectedValueItemObjects = []; final formKey = GlobalKey(); return Scaffold( - appBar: AppBar( centerTitle: true, elevation: 0, backgroundColor: primary, title: const Text("Module Object Screen"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemObjects = objects.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add New Module Object"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "module", - decoration: - normalTextFieldStyle("Module", "Module"), - items: modules.isEmpty - ? [] - : modules.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? object) { - selectedModule = object; - }, - ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemObjects = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Objects", - padding: const EdgeInsets.all(8), - options: valueItemObjects, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemObjects.isNotEmpty) { - int assignerId = id; - int moduleId = selectedModule!.id!; - List objectId = []; - for (var object in objects) { - selectedValueItemObjects - .forEach((element) { - if (element.label.toLowerCase() == - object.name?.toLowerCase()) { - objectId.add(object.id!); + actions: context.watch().state + is ModuleObjectLoadingState || + context.watch().state + is ModuleObjectsErrorState || + context.watch().state + is ModuleObjectAddedState || + context.watch().state + is ModuleObjectDeletedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemObjects = objects.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add New Module Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "module", + decoration: normalTextFieldStyle( + "Module", "Module"), + items: modules.isEmpty + ? [] + : modules.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? object) { + selectedModule = object; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemObjects = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Objects", + padding: const EdgeInsets.all(8), + options: valueItemObjects, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemObjects + .isNotEmpty) { + int assignerId = id; + int moduleId = selectedModule!.id!; + List objectId = []; + for (var object in objects) { + selectedValueItemObjects + .forEach((element) { + if (element.label + .toLowerCase() == + object.name + ?.toLowerCase()) { + objectId.add(object.id!); + } + }); + } + Navigator.of(context).pop(); + parent + .read() + .add(AddRbacModuleObjects( + assignerId: assignerId, + moduleId: moduleId, + objectsId: objectId)); } - }); - } - Navigator.of(context).pop(); - parent.read().add( - AddRbacModuleObjects( - assignerId: assignerId, - moduleId: moduleId, - objectsId: objectId)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -140,7 +154,6 @@ class RbacModuleObjectsScreen extends StatelessWidget { indicatorWidget: const SpinKitFadingCircle(color: Colors.white), child: BlocConsumer( listener: (context, state) { - if (state is ModuleObjectLoadingState) { final progress = ProgressHUD.of(context); progress!.showWithText("Please wait..."); @@ -157,13 +170,13 @@ class RbacModuleObjectsScreen extends StatelessWidget { if (state is ModuleObjectDeletedState) { if (state.success) { successAlert( - context, "Delete Successfull!", "Role Deleted Successfully", + context, "Delete Successfull!", "Module Object Deleted Successfully", () { Navigator.of(context).pop(); context.read().add(GetModuleObjects()); }); } else { - errorAlert(context, "Delete Failed", "Role Delete Failed", () { + errorAlert(context, "Delete Failed", "Module Object Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetModuleObjects()); }); @@ -270,20 +283,23 @@ class RbacModuleObjectsScreen extends StatelessWidget { style: Theme.of(context) .textTheme .titleMedium! - .copyWith(color: primary,fontWeight: FontWeight.bold), + .copyWith( + color: primary, fontWeight: FontWeight.bold), ), ); }, ); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: + "No Module Object available. Please click + to add."); } } if (state is ModuleObjectsErrorState) { return SomethingWentWrong( - message: state.message, onpressed: () { - parent.read().add(GetModuleObjects()); + message: state.message, + onpressed: () { + parent.read().add(GetModuleObjects()); }); } return Container(); diff --git a/lib/screens/superadmin/object/object_screen.dart b/lib/screens/superadmin/object/object_screen.dart index 7a4640c..a042645 100644 --- a/lib/screens/superadmin/object/object_screen.dart +++ b/lib/screens/superadmin/object/object_screen.dart @@ -5,7 +5,9 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; +import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/widgets/error_state.dart'; import '../../../theme-data.dart/box_shadow.dart'; @@ -24,83 +26,274 @@ class RbacObjectScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + final bloc = BlocProvider.of(context); + List objects = []; return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: primary, title: const Text("Objects Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Object"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Object name *", "Object name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add( - AddRbacObject( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + actions: + context.watch().state is ObjectLoadingState || + context.watch().state is ObjectAddedState || + context.watch().state is ObjectErrorState || + context.watch().state is ObjectDeletedState || + context.watch().state is ObjectUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext + context) { + return AlertDialog( + title: const Text( + "Update Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize + .min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Object name *", + "Object name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.shorthand, + validator: FormBuilderValidators + .maxLength( + 50, + errorText: + "Max characters only 50"), + name: + "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + bloc.add(UpdateRbacObject( + objectId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text("Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + bloc.add(DeleteRbacObject( + objectId: rbac.id!)); + }, "Delete?", + "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Role found :("), + ), + items: objects, + searchLabel: "Search Object", + suggestion: const Center( + child: Text("Search object by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Object name *", "Object name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: + FormBuilderValidators.maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value['object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacObject( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -162,7 +355,7 @@ class RbacObjectScreen extends StatelessWidget { context.read().add(GetObjects()); }); } else { - errorAlert(context, "Delete Failed", "Object Delete Failed", + errorAlert(context, "Delete Failed", "Object Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetObjects()); @@ -174,6 +367,7 @@ class RbacObjectScreen extends StatelessWidget { final parent = context; if (state is ObjectLoaded) { if (state.objects.isNotEmpty) { + objects = state.objects; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), diff --git a/lib/screens/superadmin/operation/operation_screen.dart b/lib/screens/superadmin/operation/operation_screen.dart index 6b4a6bb..f00a3c9 100644 --- a/lib/screens/superadmin/operation/operation_screen.dart +++ b/lib/screens/superadmin/operation/operation_screen.dart @@ -5,7 +5,9 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/operation/operation_bloc.dart'; +import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/widgets/error_state.dart'; import '../../../theme-data.dart/box_shadow.dart'; @@ -24,82 +26,276 @@ class RbacOperationScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + final bloc = BlocProvider.of(context); + List operations = []; return Scaffold( appBar: AppBar( backgroundColor: primary, title: const Text("Operations Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Operation"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Operation name *", "Operation name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), + centerTitle: true, + actions: context.watch().state + is OperationLoadingState || + context.watch().state is OperationErrorState || + context.watch().state is OperationAddedState || + context.watch().state is OperationDeletedState || + context.watch().state is OperationUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: + (BuildContext context) { + return AlertDialog( + title: const Text( + "Update Operation"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Operation name *", + "Operation name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: rbac + .shorthand, + validator: FormBuilderValidators + .maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: + ElevatedButton( + style: mainBtnStyle( + primary, + Colors + .transparent, + second), + onPressed: + () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + bloc.add(UpdateRbacOperation( + operationId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text( + "Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + context + .read() + .add(DeleteRbacOperation( + operationId: rbac.id!)); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Operation found :("), + ), + items: operations, + searchLabel: "Search Operation", + suggestion: const Center( + child: Text("Search operation by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Operation"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Operation name *", "Operation name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: FormBuilderValidators.maxLength(50, + errorText: "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey.currentState! + .value['object_name']; + String? slug = formKey + .currentState!.value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacOperation( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add( - AddRbacOperation( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -162,8 +358,8 @@ class RbacOperationScreen extends StatelessWidget { context.read().add(GetOperations()); }); } else { - errorAlert(context, "Delete Failed", "Operation Delete Failed", - () { + errorAlert( + context, "Delete Failed", "Operation Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetOperations()); }); @@ -174,6 +370,7 @@ class RbacOperationScreen extends StatelessWidget { final parent = context; if (state is OperationsLoaded) { if (state.operations.isNotEmpty) { + operations = state.operations; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), @@ -190,18 +387,22 @@ class RbacOperationScreen extends StatelessWidget { children: [ Expanded( child: Row( - children: [ - CircleAvatar(child: Text('${index+1}'),), - const SizedBox(width: 12,), - Text(state.operations[index].name!, - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500, - color: primary)), - ], - )), + children: [ + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Text(state.operations[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ], + )), AppPopupMenu( offset: const Offset(-10, -10), elevation: 3, @@ -211,7 +412,8 @@ class RbacOperationScreen extends StatelessWidget { context: context, builder: (BuildContext context) { return AlertDialog( - title: const Text("Update Operation"), + title: const Text( + "Update Operation"), content: FormBuilder( key: formKey, child: Column( @@ -355,7 +557,7 @@ class RbacOperationScreen extends StatelessWidget { }); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: "No Operation available. Please click + to add."); } } if (state is OperationErrorState) { diff --git a/lib/screens/superadmin/permission/permission_screen.dart b/lib/screens/superadmin/permission/permission_screen.dart index 0400599..90d25ea 100644 --- a/lib/screens/superadmin/permission/permission_screen.dart +++ b/lib/screens/superadmin/permission/permission_screen.dart @@ -7,7 +7,9 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/permission/permission_bloc.dart'; +import 'package:unit2/model/rbac/permission.dart'; import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; @@ -32,6 +34,8 @@ class RbacPermissionScreen extends StatelessWidget { List operations = []; List valueItemOperations = []; List selectedValueItemOperations = []; + List permissions = []; + final bloc = BlocProvider.of(context); final formKey = GlobalKey(); BuildContext? parent; return Scaffold( @@ -39,105 +43,189 @@ class RbacPermissionScreen extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("Permissions Screen"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemOperations = operations.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add Permission"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "object", - decoration: - normalTextFieldStyle("Permission", "Permission"), - items: objects.isEmpty - ? [] - : objects.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? object) { - selectedObject = object; - }, + actions: context.watch().state is PermissonLoadingState || + context.watch().state is PermissionErrorState || + context.watch().state is PermissionDeletedState || + context.watch().state is PermissionAddedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBACPermission rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Text( + "${rbac.object?.name} - ${rbac.operation?.name}", + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + bloc.add(DeleteRbacPermission( + permissionId: rbac.id!)); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBACPermission rbac) { + return [ + rbac.object!.name! + rbac.operation!.name! + ]; + }, + failure: const Center( + child: Text("No permission found :("), ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemOperations = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Operations", - padding: const EdgeInsets.all(8), - options: valueItemOperations, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemOperations - .isNotEmpty) { - int assignerId = id; - int objectId = selectedObject!.id!; + items: permissions, + searchLabel: "Search Permission", + suggestion: const Center( + child: Text("Search permission by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemOperations = operations.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Permission"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "object", + decoration: normalTextFieldStyle( + "Permission", "Permission"), + items: objects.isEmpty + ? [] + : objects.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? object) { + selectedObject = object; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemOperations = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Operations", + padding: const EdgeInsets.all(8), + options: valueItemOperations, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemOperations + .isNotEmpty) { + int assignerId = id; + int objectId = selectedObject!.id!; - List opIds = []; - for (var operation in operations) { - selectedValueItemOperations - .forEach((element) { - if (element.label.toLowerCase() == - operation.name?.toLowerCase()) { - opIds.add(operation.id!); + List opIds = []; + for (var operation in operations) { + selectedValueItemOperations + .forEach((element) { + if (element.label + .toLowerCase() == + operation.name + ?.toLowerCase()) { + opIds.add(operation.id!); + } + }); + } + + Navigator.pop(context); + parent!.read().add( + AddRbacPermission( + assignerId: assignerId, + objectId: objectId, + operationIds: opIds)); } - }); - } - opIds.forEach((element) { - print(element); - }); - Navigator.pop(context); - parent!.read().add( - AddRbacPermission( - assignerId: assignerId, - objectId: objectId, - operationIds: opIds)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -181,8 +269,8 @@ class RbacPermissionScreen extends StatelessWidget { context.read().add(GetPermissions()); }); } else { - errorAlert(context, "Delete Failed", "Permission Delete Failed", - () { + errorAlert( + context, "Delete Failed", "Permission Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetPermissions()); }); @@ -195,6 +283,7 @@ class RbacPermissionScreen extends StatelessWidget { objects = state.objects; operations = state.operations; if (state.permissions.isNotEmpty) { + permissions = state.permissions; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), @@ -211,41 +300,39 @@ class RbacPermissionScreen extends StatelessWidget { children: [ Expanded( child: Row( - children: [ - CircleAvatar( + children: [ + CircleAvatar( child: Text('${index + 1}'), ), const SizedBox( width: 12, ), - Flexible( - child: Text( - "${state.permissions[index].object?.name} - ${state.permissions[index].operation?.name}", - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500, - color: primary)), - ), - ], - )), + Flexible( + child: Text( + "${state.permissions[index].object?.name} - ${state.permissions[index].operation?.name}", + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ), + ], + )), AppPopupMenu( offset: const Offset(-10, -10), elevation: 3, onSelected: (value) { - if (value == 1) { - + if (value == 1) { confirmAlert(context, () { - context.read().add( - DeleteRbacPermission( - permissionId: state.permissions[index].id!)); + context.read().add( + DeleteRbacPermission( + permissionId: state + .permissions[index].id!)); }, "Delete?", "Confirm Delete?"); - } }, menuItems: [ - popMenuItem( text: "Remove", value: 1, @@ -273,8 +360,9 @@ class RbacPermissionScreen extends StatelessWidget { } if (state is PermissionErrorState) { return SomethingWentWrong( - message: state.message, onpressed: () { - parent!.read().add(GetPermissions()); + message: state.message, + onpressed: () { + parent!.read().add(GetPermissions()); }); } return Container(); diff --git a/lib/screens/superadmin/permission_assignment/permission_assignment_screen.dart b/lib/screens/superadmin/permission_assignment/permission_assignment_screen.dart new file mode 100644 index 0000000..07aa98d --- /dev/null +++ b/lib/screens/superadmin/permission_assignment/permission_assignment_screen.dart @@ -0,0 +1,325 @@ +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/permission_assignment/permission_assignment_bloc.dart'; +import 'package:unit2/model/rbac/permission.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/theme-data.dart/btn-style.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; +import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/empty_data.dart'; +import 'package:unit2/widgets/error_state.dart'; + +class RbacPermissionAssignmentScreen extends StatelessWidget { + final int id; + const RbacPermissionAssignmentScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final parent = context; + Map> permissionAssignments = {}; + List permissions = []; + List valueItemPermission = []; + List selectedValueItemPermission = []; + List roles = []; + RBAC? selectedRole; + + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: const Text("Permission Assignment"), + actions: context.watch().state + is PermissionAssignmentLoadingScreen || + context.watch().state + is PermissionAssignmentErrorState || + context.watch().state + is PermissionAssignmentAddedState || + context.watch().state + is PermissionAssignmentDeletedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: context, + builder: (BuildContext context) { + valueItemPermission = permissions.map((e) { + return ValueItem( + label: "${e.object!.name} - ${e.operation!.name}", + value: e.id.toString()); + }).toList(); + return AlertDialog( + title: const Text("Add Permission"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: + normalTextFieldStyle("Role", "Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemPermission = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Operations", + padding: const EdgeInsets.all(8), + options: valueItemPermission, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemPermission + .isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List opIds = + selectedValueItemPermission + .map((e) { + return int.parse(e.value!); + }).toList(); + Navigator.pop(context); + parent + .read< + PermissionAssignmentBloc>() + .add(AddPersmissionAssignment( + assignerId: assignerId, + opsId: opIds, + roleId: roleId)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: + BlocConsumer( + listener: (context, state) { + if (state is PermissionAssignmentLoadingScreen) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is PermissionAssignmentErrorState || + state is PermissionAssignmentLoadedState || + state is PermissionAssignmentAddedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + if (state is PermissionAssignmentDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Permission Assignment Deleted Successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(GetPermissionAssignments()); + }); + } else { + errorAlert(context, "Delete Failed", + "Permission Assignment Deletion Failed", () { + Navigator.of(context).pop(); + context + .read() + .add(GetPermissionAssignments()); + }); + } + } + if (state is PermissionAssignmentAddedState) { + if (state.status['success']) { + successAlert(context, "Add Successfull!", + "Permission Assignment Added Successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(GetPermissionAssignments()); + }); + } else { + errorAlert(context, "Adding Failed", + "Permission Assignment Adding Failed", () { + Navigator.of(context).pop(); + context + .read() + .add(GetPermissionAssignments()); + }); + } + } + }, + builder: (context, state) { + if (state is PermissionAssignmentLoadedState) { + if (state.permissionAssignments.isNotEmpty) { + permissions = state.permissions; + roles = state.roles; + permissionAssignments = {}; + for (var permissionAssignment in state.permissionAssignments) { + if (!permissionAssignments.keys.contains( + permissionAssignment.role!.name!.toLowerCase())) { + permissionAssignments.addAll( + {permissionAssignment.role!.name!.toLowerCase(): []}); + permissionAssignments[ + permissionAssignment.role!.name!.toLowerCase()]! + .add(Content( + id: permissionAssignment.id!, + name: + "${permissionAssignment.permission!.object!.name} - ${permissionAssignment.permission!.operation!.name} ")); + } else { + permissionAssignments[ + permissionAssignment.role!.name!.toLowerCase()]! + .add(Content( + id: permissionAssignment.id!, + name: + "${permissionAssignment.permission!.object!.name} - ${permissionAssignment.permission!.operation!.name} ")); + } + } + return GroupListView( + sectionsCount: permissionAssignments.keys.toList().length, + countOfItemInSection: (int section) { + return permissionAssignments.values + .toList()[section] + .length; + }, + itemBuilder: (BuildContext context, IndexPath index) { + return ListTile( + dense: true, + trailing: IconButton( + color: Colors.grey.shade600, + icon: const Icon(Icons.delete), + onPressed: () { + confirmAlert(context, () { + context.read().add( + DeletePermissionAssignment( + id: permissionAssignments.values + .toList()[index.section][index.index] + .id)); + }, "Delete?", "Confirm Delete?"); + }, + ), + 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( + permissionAssignments.values + .toList()[index.section][index.index] + .name + .toUpperCase(), + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: primary), + ), + ), + ], + ), + ); + }, + separatorBuilder: (context, index) { + return const Divider(); + }, + groupHeaderBuilder: (BuildContext context, int section) { + return ListTile( + tileColor: Colors.white, + title: Text( + permissionAssignments.keys + .toList()[section] + .toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + color: primary, fontWeight: FontWeight.bold), + ), + ); + }, + ); + } else { + const EmptyData( + message: + "Permission Assignment available. Please click + to add", + ); + } + } + if (state is PermissionAssignmentErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context + .read() + .add(GetPermissionAssignments()); + }); + } + return Container(); + }, + ), + ), + ); + } +} + +class Content { + final int id; + final String name; + const Content({required this.id, required this.name}); +} diff --git a/lib/screens/superadmin/role/role_screen.dart b/lib/screens/superadmin/role/role_screen.dart index 03e055c..f6553e9 100644 --- a/lib/screens/superadmin/role/role_screen.dart +++ b/lib/screens/superadmin/role/role_screen.dart @@ -25,6 +25,7 @@ class RbacRoleScreen extends StatelessWidget { @override Widget build(BuildContext context) { + final bloc = BlocProvider.of(context); final formKey = GlobalKey(); List roles = []; return Scaffold( @@ -32,102 +33,274 @@ class RbacRoleScreen extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("Role Screen"), - actions: [ - IconButton( - onPressed: () { - showSearch( - context: context, - delegate: SearchPage( - barTheme: ThemeData(cardColor: primary), - builder: (RBAC rbac) { - return ListTile( - title: Text(rbac.name!), - ); - }, - filter: (RBAC rbac) { - return [rbac.name]; - }, - failure: const Center( - child: Text("No Role found :("), - ), - items: roles, - searchLabel: "Search Role", - suggestion: const Center( - child: Text("Search role by name"), - )), - ); - }, - icon: const Icon(Icons.search)), - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Role"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Role name *", "Role name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add(AddRbacRole( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + actions: + context.watch().state is RoleLoadingState || + context.watch().state is RoleErrorState || + context.watch().state is RoleDeletedState? || + context.watch().state is RoleAddedState? || + context.watch().state is RoleUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + Flexible( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight + .w500, + color: primary)), + ), + ], + )), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext + context) { + return AlertDialog( + title: const Text( + "Update Role"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize + .min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Role name *", + "Role name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.shorthand, + validator: FormBuilderValidators + .maxLength( + 50, + errorText: + "Max characters only 50"), + name: + "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + bloc.add(UpdateRbacRole( + roleId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text("Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + bloc + .add(DeleteRbacRole( + roleId: rbac.id!)); + }, "Delete?", + "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Role found :("), + ), + items: roles, + searchLabel: "Search Role", + suggestion: const Center( + child: Text("Search role by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Role"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Role name *", "Role name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: + FormBuilderValidators.maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value['object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacRole( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), diff --git a/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart b/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart index b09f086..39004ea 100644 --- a/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart +++ b/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart @@ -36,7 +36,7 @@ class RbacRoleAssignment extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("User Roles Screens"), - actions: [ + actions: context.watch().state is RoleAssignmentLoadingState || context.watch().state is RoleAssignmentErrorState || context.watch().state is UserNotExistError || context.watch().state is RoleAddedState? []: [ AddLeading(onPressed: () { BuildContext parent = context; showDialog( @@ -131,13 +131,13 @@ class RbacRoleAssignment extends StatelessWidget { if (state is AssignedRoleDeletedState) { if (state.success) { successAlert(context, "Delete Successfull!", - "Role Module Deleted Successfully", () { + "Role Deleted Successfully", () { Navigator.of(context).pop(); context.read().add(LoadAssignedRole()); }); } else { errorAlert( - context, "Delete Failed", "Role Module Delete Failed", () { + context, "Delete Failed", "Role Deletion Failed", () { Navigator.of(context).pop(); context.read().add(LoadAssignedRole()); }); diff --git a/lib/screens/superadmin/role_extend/role_extend_screen.dart b/lib/screens/superadmin/role_extend/role_extend_screen.dart index 2640660..3c5787a 100644 --- a/lib/screens/superadmin/role_extend/role_extend_screen.dart +++ b/lib/screens/superadmin/role_extend/role_extend_screen.dart @@ -36,7 +36,7 @@ class RbacRoleExtendScreen extends StatelessWidget { elevation: 0, backgroundColor: primary, title: const Text("Role Extend"), - actions: [ + actions: context.watch().state is RoleExtendLoadingState || context.watch().state is RoleExtendErrorState || context.watch().state is RoleExtendAddedState || context.watch().state is RoleExtendDeletedState? []:[ AddLeading(onPressed: () { showDialog( context: NavigationService.navigatorKey.currentState!.context, @@ -49,6 +49,7 @@ class RbacRoleExtendScreen extends StatelessWidget { content: FormBuilder( key: formKey, child: Column( + mainAxisSize: MainAxisSize.min, children: [ FormBuilderDropdown( diff --git a/lib/screens/superadmin/role_module/role_module_scree.dart b/lib/screens/superadmin/role_module/role_module_scree.dart index a71ae81..8a97b7f 100644 --- a/lib/screens/superadmin/role_module/role_module_scree.dart +++ b/lib/screens/superadmin/role_module/role_module_scree.dart @@ -34,100 +34,114 @@ class RbacRoleModuleScreen extends StatelessWidget { return Scaffold( appBar: AppBar( backgroundColor: primary, - title: const Text("Role Modules Screen"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemModules = modules.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add Role Module"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "role", - decoration: normalTextFieldStyle("Role", "Role"), - items: roles.isEmpty - ? [] - : roles.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? role) { - selectedRole = role; - }, - ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemModules = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Modules", - padding: const EdgeInsets.all(8), - options: valueItemModules, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemModules.isNotEmpty) { - int assignerId = id; - int roleId = selectedRole!.id!; - List modulesId = []; - for (var module in modules) { - selectedValueItemModules - .forEach((element) { - if (element.label.toLowerCase() == - module.name?.toLowerCase()) { - modulesId.add(module.id!); + title: const Text("Role Module Screen" ), + centerTitle: true, + actions: context.watch().state + is RoleModuleLoadingState || + context.watch().state is RoleModuleErrorState || + context.watch().state is RoleModuleAddedState || + context.watch().state is RoleModuleDeletedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemModules = modules.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Role Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: + normalTextFieldStyle("Role", "Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemModules = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Modules", + padding: const EdgeInsets.all(8), + options: valueItemModules, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemModules + .isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List modulesId = []; + for (var module in modules) { + selectedValueItemModules + .forEach((element) { + if (element.label + .toLowerCase() == + module.name + ?.toLowerCase()) { + modulesId.add(module.id!); + } + }); + } + Navigator.of(context).pop(); + parent.read().add( + AddRoleModule( + assignerId: assignerId, + roleId: roleId, + moduleIds: modulesId)); } - }); - } - Navigator.of(context).pop(); - parent.read().add( - AddRoleModule( - assignerId: assignerId, - roleId: roleId, - moduleIds: modulesId)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -156,7 +170,7 @@ class RbacRoleModuleScreen extends StatelessWidget { }); } else { errorAlert( - context, "Delete Failed", "Role Module Delete Failed", () { + context, "Delete Failed", "Role Module Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetRoleModules()); }); @@ -258,20 +272,22 @@ class RbacRoleModuleScreen extends StatelessWidget { style: Theme.of(context) .textTheme .titleMedium! - .copyWith(color: primary,fontWeight: FontWeight.bold), + .copyWith( + color: primary, fontWeight: FontWeight.bold), ), ); }, ); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: "No Role Module available. Please click + to add."); } } if (state is RoleModuleErrorState) { return SomethingWentWrong( - message: state.message, onpressed: () { - context.read().add(GetRoleModules()); + message: state.message, + onpressed: () { + context.read().add(GetRoleModules()); }); } return Container(); diff --git a/lib/screens/superadmin/roles_under/assignable_roles.dart b/lib/screens/superadmin/roles_under/assignable_roles.dart new file mode 100644 index 0000000..5698cc7 --- /dev/null +++ b/lib/screens/superadmin/roles_under/assignable_roles.dart @@ -0,0 +1,307 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:group_list_view/group_list_view.dart'; +import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../model/rbac/rbac.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global_context.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacRoleUnderScreen extends StatelessWidget { + final int id; + const RbacRoleUnderScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final parent = context; + Map> rolesUnder = {}; + List roles = []; + RBAC? selectedRole; + List valueItemRoles = []; + List selectedValueItemRoles = []; + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: const Text("Assignable Roles"), + actions: context.watch().state + is RoleUnderLoadingState? || + context.watch().state is RoleUnderErrorState || + context.watch().state + is RoleUnderDeletedState || + context.watch().state is RoleUnderAddedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemRoles = roles.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Role Under"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: normalTextFieldStyle( + "Main Role", "Main Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemRoles = selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Roles Under", + padding: const EdgeInsets.all(8), + options: valueItemRoles, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemRoles + .isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List rolesId = []; + for (var role in roles) { + selectedValueItemRoles + .forEach((element) { + if (element.label + .toLowerCase() == + role.name?.toLowerCase()) { + rolesId.add(role.id!); + } + }); + } + Navigator.of(context).pop(); + parent.read().add( + AddRoleUnder( + roleId: roleId, + roleUnderIds: rolesId)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is RoleUnderLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is RoleUnderLoadedState || + state is RoleUnderErrorState || + state is RoleUnderDeletedState || + state is RoleUnderAddedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + + ////Deleted State + if (state is RoleUnderDeletedState) { + if (state.success) { + successAlert( + context, "Delete Successfull!", "Role Deleted Successfully", + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } else { + errorAlert( + context, "Delete Failed", "Role Module Delete Failed", () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } + } + ////Added State + if (state is RoleUnderAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } + } + }, + builder: (context, state) { + if (state is RoleUnderLoadedState) { + rolesUnder = {}; + roles = state.roles; + + if (state.rolesUnder.isNotEmpty) { + for (var roleUnder in state.rolesUnder) { + if (!rolesUnder.keys + .contains(roleUnder.roleUnderMain.name!.toLowerCase())) { + rolesUnder.addAll( + {roleUnder.roleUnderMain.name!.toLowerCase(): []}); + rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! + .add(Content( + id: roleUnder.id, + name: roleUnder.roleUnderChild.name!)); + } else { + rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! + .add(Content( + id: roleUnder.id, + name: roleUnder.roleUnderChild.name!)); + } + } + } + + if (state.rolesUnder.isNotEmpty) { + return GroupListView( + sectionsCount: rolesUnder.keys.toList().length, + countOfItemInSection: (int section) { + return rolesUnder.values.toList()[section].length; + }, + itemBuilder: (BuildContext context, IndexPath index) { + return ListTile( + trailing: IconButton( + color: Colors.grey.shade500, + icon: const Icon(Icons.delete), + onPressed: () { + confirmAlert(context,(){ + context.read().add(DeleteRoleUnder(roleUnderId:rolesUnder.values .toList()[index.section][index.index].id)); + }, "Delete", "Delete Role?"); + }, + ), + title: Row( + children: [ + CircleAvatar( + child: Text("${index.index + 1}", + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: Colors.white))), + const SizedBox( + width: 20, + ), + Expanded( + child: Text( + rolesUnder.values + .toList()[index.section][index.index] + .name + .toUpperCase(), + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ), + ], + ), + ); + }, + separatorBuilder: (context, index) { + return const Divider(); + }, + groupHeaderBuilder: (BuildContext context, int section) { + return ListTile( + tileColor: Colors.white, + dense: true, + title: Text( + rolesUnder.keys.toList()[section].toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + color: primary, fontWeight: FontWeight.bold), + ), + ); + }, + ); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is RoleUnderErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context.read().add(GetRolesUnder()); + }); + } + return Container(); + }, + ), + ), + ); + } +} + +class Content { + final int id; + final String name; + const Content({required this.id, required this.name}); +} diff --git a/lib/screens/superadmin/roles_under/roles_under_screen.dart b/lib/screens/superadmin/roles_under/roles_under_screen.dart deleted file mode 100644 index 6f82a78..0000000 --- a/lib/screens/superadmin/roles_under/roles_under_screen.dart +++ /dev/null @@ -1,296 +0,0 @@ - -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package:form_builder_validators/form_builder_validators.dart'; -import 'package:group_list_view/group_list_view.dart'; -import 'package:multi_dropdown/multiselect_dropdown.dart'; -import 'package:unit2/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart'; -import 'package:unit2/widgets/Leadings/add_leading.dart'; -import 'package:unit2/widgets/error_state.dart'; -import '../../../model/rbac/rbac.dart'; -import '../../../theme-data.dart/btn-style.dart'; -import '../../../theme-data.dart/colors.dart'; -import '../../../theme-data.dart/form-style.dart'; -import '../../../utils/alerts.dart'; -import '../../../utils/global_context.dart'; -import '../../../widgets/empty_data.dart'; - -class RbacRoleUnderScreen extends StatelessWidget { - final int id; - const RbacRoleUnderScreen({super.key, required this.id}); - - @override - Widget build(BuildContext context) { - final parent = context; - Map> rolesUnder = {}; - List roles = []; - RBAC? selectedRole; - List valueItemRoles = []; - List selectedValueItemRoles = []; - final formKey = GlobalKey(); - return Scaffold( - appBar: AppBar( - centerTitle: true, - backgroundColor: primary, - title: const Text("Assignable Roles"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemRoles = roles.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add Role Under"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "role", - decoration: normalTextFieldStyle( - "Main Role", "Main Role"), - items: roles.isEmpty - ? [] - : roles.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? role) { - selectedRole = role; - }, - ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemRoles = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Roles Under", - padding: const EdgeInsets.all(8), - options: valueItemRoles, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemRoles.isNotEmpty) { - int assignerId = id; - int roleId = selectedRole!.id!; - List rolesId = []; - for (var role in roles) { - selectedValueItemRoles - .forEach((element) { - if (element.label.toLowerCase() == - role.name?.toLowerCase()) { - rolesId.add(role.id!); - } - }); - } - Navigator.of(context).pop(); - parent.read().add( - AddRoleUnder( - roleId: roleId, - roleUnderIds: rolesId)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], - ), - body: ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocConsumer( - listener: (context, state) { - if (state is RoleUnderLoadingState) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is RoleUnderLoadedState || - state is RoleUnderErrorState || - state is RoleUnderDeletedState || - state is RoleUnderAddedState) { - final progress = ProgressHUD.of(context); - progress!.dismiss(); - } - - ////Deleted State - if (state is RoleUnderDeletedState) { - if (state.success) { - successAlert(context, "Delete Successfull!", - "Role Deleted Successfully", () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } else { - errorAlert( - context, "Delete Failed", "Role Module Delete Failed", () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } - } - ////Added State - if (state is RoleUnderAddedState) { - if (state.response['success']) { - successAlert( - context, "Adding Successfull!", state.response['message'], - () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } else { - errorAlert(context, "Adding Failed", state.response['message'], - () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } - } - }, - builder: (context, state) { - if (state is RoleUnderLoadedState) { - rolesUnder = {}; - roles = state.roles; - - if (state.rolesUnder.isNotEmpty) { - for (var roleUnder in state.rolesUnder) { - if (!rolesUnder.keys - .contains(roleUnder.roleUnderMain.name!.toLowerCase())) { - rolesUnder.addAll( - {roleUnder.roleUnderMain.name!.toLowerCase(): []}); - rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! - .add(Content( - id: roleUnder.id, - name: roleUnder.roleUnderChild.name!)); - } else { - rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! - .add(Content( - id: roleUnder.id, - name: roleUnder.roleUnderChild.name!)); - } - } - } - - if (state.rolesUnder.isNotEmpty) { - return GroupListView( - sectionsCount: rolesUnder.keys.toList().length, - countOfItemInSection: (int section) { - return rolesUnder.values.toList()[section].length; - }, - itemBuilder: (BuildContext context, IndexPath index) { - return ListTile( - trailing: IconButton( - color: Colors.grey.shade500, - icon: const Icon(Icons.delete), - onPressed: () { - context.read().add(DeleteRoleUnder( - roleUnderId: rolesUnder.values - .toList()[index.section][index.index] - .id)); - }, - ), - title: Row( - children: [ - CircleAvatar( - child: Text("${index.index + 1}", - style: Theme.of(context) - .textTheme - .labelLarge! - .copyWith(color: Colors.white))), - const SizedBox( - width: 20, - ), - Expanded( - child: Text( - rolesUnder.values - .toList()[index.section][index.index] - .name - .toUpperCase(), - style: Theme.of(context) - .textTheme - .labelLarge! - .copyWith( - fontWeight: FontWeight.w500, - color: primary) - ), - ), - ], - ), - ); - }, - separatorBuilder: (context, index) { - return const Divider(); - }, - groupHeaderBuilder: (BuildContext context, int section) { - return ListTile( -tileColor: Colors.white, - dense: true, - title: Text( - rolesUnder.keys.toList()[section].toUpperCase(), - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith(color: primary,fontWeight: FontWeight.bold), - ), - ); - }, - ); - } else { - return const EmptyData( - message: "No Role available. Please click + to add."); - } - } - if (state is RoleUnderErrorState) { - return SomethingWentWrong( - message: state.message, onpressed: () { - context.read().add(GetRolesUnder()); - }); - } - return Container(); - }, - ), - ), - ); - } -} - -class Content { - final int id; - final String name; - const Content({required this.id, required this.name}); -} diff --git a/lib/screens/superadmin/stations/stations_screen.dart b/lib/screens/superadmin/stations/stations_screen.dart index 6bfa28d..533e55a 100644 --- a/lib/screens/superadmin/stations/stations_screen.dart +++ b/lib/screens/superadmin/stations/stations_screen.dart @@ -5,7 +5,6 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:searchfield/searchfield.dart'; -import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/station/station_bloc.dart'; import 'package:unit2/model/rbac/rbac_station.dart'; import 'package:unit2/model/utils/agency.dart'; @@ -62,435 +61,469 @@ class _RbacStationScreenState extends State { centerTitle: true, backgroundColor: primary, title: const Text("Station Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - mainParentStations = []; - mainParent = stations.isEmpty ? true : false; - for (RbacStation station in stations) { - if (station.hierarchyOrderNo == 1) { - mainParentStations.add(station); - } - } + actions: context.watch().state is StationLoadingState || + context.watch().state is StationErrorState || + context.watch().state is RbacStationAddedState || + context.watch().state is FilterStationState + ? [] + : [ + AddLeading(onPressed: () { + BuildContext parent = context; + mainParentStations = []; + mainParent = stations.isEmpty ? true : false; + for (RbacStation station in stations) { + if (station.hierarchyOrderNo == 1) { + mainParentStations.add(station); + } + } - /////Add new tation - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Station"), - content: SingleChildScrollView( - child: FormBuilder( - key: formKey, - child: StatefulBuilder(builder: (context, setState) { - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - ////is main parent - FormBuilderSwitch( - initialValue: mainParent, - activeColor: second, - onChanged: (value) { - setState(() { - mainParent = !mainParent; - }); - }, - decoration: normalTextFieldStyle( - "is Main Parent?", 'is Main Parent?'), - name: 'main-parent', - title: Text(mainParent ? "YES" : "NO"), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - SizedBox( - height: mainParent ? 0 : 8, - ), - //// selected main parent - SizedBox( - child: mainParent == true - ? const SizedBox.shrink() - : FormBuilderDropdown( - decoration: normalTextFieldStyle( - "Main Parent Station", - "Main Parent Station"), - name: "parent-stations", - items: mainParentStations.isEmpty - ? [] - : mainParentStations.map((e) { - return DropdownMenuItem( - value: e, - child: Text(e.stationName!), - ); - }).toList(), - onChanged: (RbacStation? e) { - setState(() { - selectedMainParentStation = e; - parentStations = []; - for (RbacStation station - in stations) { - if (station.mainParentStation == - selectedMainParentStation! - .id) { - parentStations.add(station); - } - } - parentStations.add( - selectedMainParentStation!); - }); - }, - validator: - FormBuilderValidators.required( - errorText: - "This field is required"), - ), - ), - SizedBox( - height: mainParent ? 0 : 8, - ), - ////parent station - SizedBox( - child: mainParent == true - ? const SizedBox.shrink() - : FormBuilderDropdown( - decoration: normalTextFieldStyle( - "Parent Station", "Parent Station"), - name: "parent-stations", - onChanged: (RbacStation? e) { - setState(() { - selectedParentStation = e; - }); - }, - items: parentStations.isEmpty - ? [] - : parentStations.map((e) { - return DropdownMenuItem( - value: e, - child: Text(e.stationName!), - ); - }).toList(), - validator: - FormBuilderValidators.required( - errorText: - "This field is required"), - ), - ), - const SizedBox( - height: 12, - ), - ////Station Type - SearchField( - itemHeight: 50, - suggestionsDecoration: box1(), - suggestions: stationTypes - .map((StationType stationType) => - SearchFieldListItem( - stationType.typeName!, - item: stationType, - child: Padding( - padding: - const EdgeInsets.symmetric( - horizontal: 10), - child: ListTile( - title: Text( - stationType.typeName!, - overflow: TextOverflow.visible, - )), - ))) - .toList(), - validator: (station) { - if (station!.isEmpty) { - return "This field is required"; - } - return null; - }, - focusNode: stationTypeFocusNode, - searchInputDecoration: - normalTextFieldStyle("Station Type *", "") - .copyWith( - suffixIcon: GestureDetector( - onTap: () => stationTypeFocusNode.unfocus(), - child: const Icon(Icons.arrow_drop_down), - )), - onSuggestionTap: (position) { - setState(() { - selectedStationType = position.item!; - stationTypeFocusNode.unfocus(); - }); - }, - emptyWidget: EmptyWidget( - title: "Add StationType", - controller: addStationTypeController, - onpressed: () { - setState(() { - StationType stationType = StationType( - id: null, - typeName: - addStationTypeController.text, - color: null, - order: null, - isActive: null, - group: null); - stationTypes.add(stationType); - Navigator.pop(context); - }); - }), - ), - const SizedBox( - height: 12, - ), - ////Position title - FormBuilderDropdown( - decoration: normalTextFieldStyle( - "Head Position", "Head Position"), - name: "head-position", - items: positions.map((e) { - return DropdownMenuItem( - value: e, - child: Text(e.title!), - ); - }).toList(), - onChanged: (title) { - selectedPositiontitle = title; - }, - ), - const SizedBox( - height: 12, - ), - ////is within parent - FormBuilderSwitch( - initialValue: true, - activeColor: second, - onChanged: (value) { - setState(() { - isWithinParent = value!; - }); - }, - decoration: normalTextFieldStyle( - "Location of the station within this parent?", - 'Location of the station within this parent?'), - name: 'isWithinParent', - title: Text(isWithinParent ? "YES" : "NO"), - ), - const SizedBox( - height: 12, - ), - Row( - //// Station Name - children: [ - Flexible( - child: FormBuilderTextField( - validator: - FormBuilderValidators.required( - errorText: - "This Field is required"), - decoration: normalTextFieldStyle( - "Station name", "Station name"), - name: "station-name"), - ), - const SizedBox( - width: 12, - ), - //// Acronym - Flexible( - child: FormBuilderTextField( - validator: - FormBuilderValidators.required( - errorText: - "This Field is required"), - decoration: normalTextFieldStyle( - "Acronym", "Acronym"), - name: "acronym"), - ), - ], - ), - const SizedBox( - height: 12, - ), - FormBuilderTextField( - ////Description - decoration: normalTextFieldStyle( - "Station description", - "Station description"), - name: "station-description"), - const SizedBox( - height: 12, - ), - Row( - children: [ - Flexible( - ////Code - child: FormBuilderTextField( - decoration: normalTextFieldStyle( - "Code", "Code"), - name: "code"), - ), - const SizedBox( - width: 12, - ), - Flexible( - //// Full Code - child: FormBuilderTextField( - decoration: normalTextFieldStyle( - "Full Code", "Full Code"), - name: "fullcode"), - ), - ], - ), - const SizedBox( - height: 12, - ), - ////is Hospital - FormBuilderSwitch( - initialValue: isHospital, - activeColor: second, - onChanged: (value) { - setState(() { - isHospital = !isHospital; - }); - }, - decoration: - normalTextFieldStyle("Is Hospital", ''), - name: 'isHospital', - title: Text(isHospital == true ? "YES" : "NO"), - ), - const SizedBox( - height: 20, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - RbacStation? newStation; - if (formKey.currentState! - .saveAndValidate()) { - String? stationName = formKey - .currentState! - .value['station-name']; - String? acronym = formKey - .currentState!.value['acronym']; - String? code = formKey - .currentState!.value['code']; - String? fullcode = formKey - .currentState!.value['fullcode']; - String? description = formKey - .currentState! - .value['station-description']; - newStation = RbacStation( - id: null, - stationName: stationName, - stationType: selectedStationType, - hierarchyOrderNo: mainParent - ? 1 - : selectedParentStation! - .hierarchyOrderNo! + - 1, - headPosition: - selectedPositiontitle?.title, - governmentAgency: - GovernmentAgency( - agencyid: - selectedAgencyId, - agencyname: null, - agencycatid: null, - privateEntity: null, - contactinfoid: null), - acronym: acronym, - parentStation: mainParent - ? null - : selectedParentStation!.id!, - code: code, - fullcode: fullcode, - childStationInfo: null, - islocationUnderParent: - isWithinParent, - mainParentStation: mainParent - ? null - : selectedMainParentStation! - .id!, - description: description, - ishospital: isHospital, - isactive: true, - sellingStation: null); - Navigator.pop(context); - rbacStationBloc.add(AddRbacStation( - station: newStation)); - } + /////Add new tation + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Station"), + content: SingleChildScrollView( + child: FormBuilder( + key: formKey, + child: + StatefulBuilder(builder: (context, setState) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + ////is main parent + FormBuilderSwitch( + initialValue: mainParent, + activeColor: second, + onChanged: (value) { + setState(() { + mainParent = !mainParent; + }); }, - child: const Text("Add"))), - ], - ); - }), - ), - ), - ); - }); - }), - ////Filter - IconButton( - onPressed: () { - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text( - "Select agency to filter stations", - textAlign: TextAlign.center, - ), - content: SizedBox( - child: // //// Filter Agencies - Padding( - padding: const EdgeInsets.all(8), - child: SearchField( - inputFormatters: [UpperCaseTextFormatter()], - itemHeight: 100, - focusNode: agencyFocusNode, - suggestions: agencies - .map((Agency agency) => - SearchFieldListItem(agency.name!, - item: agency, - child: ListTile( - title: Text( - agency.name!, - overflow: TextOverflow.visible, - ), - ))) - .toList(), - searchInputDecoration: - normalTextFieldStyle("Filter", "").copyWith( - suffixIcon: IconButton( - icon: const Icon(Icons.arrow_drop_down), - onPressed: () { - agencyFocusNode.unfocus(); - }, - )), - onSuggestionTap: (agency) { - agencyFocusNode.unfocus(); - - selectedAgencyId = agency.item!.id!; - print(selectedAgencyId); - Navigator.pop(context); - rbacStationBloc.add(FilterStation( - agencyId: selectedAgencyId)); - }, - validator: (agency) { - if (agency!.isEmpty) { - return "This field is required"; - } - return null; - }, - emptyWidget: const Center( - child: Text("No result found..."), - )), + decoration: normalTextFieldStyle( + "is Main Parent?", 'is Main Parent?'), + name: 'main-parent', + title: Text(mainParent ? "YES" : "NO"), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + SizedBox( + height: mainParent ? 0 : 8, + ), + //// selected main parent + SizedBox( + child: mainParent == true + ? const SizedBox.shrink() + : FormBuilderDropdown( + decoration: normalTextFieldStyle( + "Main Parent Station", + "Main Parent Station"), + name: "parent-stations", + items: mainParentStations.isEmpty + ? [] + : mainParentStations.map((e) { + return DropdownMenuItem( + value: e, + child: Text( + e.stationName!), + ); + }).toList(), + onChanged: (RbacStation? e) { + setState(() { + selectedMainParentStation = e; + parentStations = []; + for (RbacStation station + in stations) { + if (station + .mainParentStation == + selectedMainParentStation! + .id) { + parentStations + .add(station); + } + } + parentStations.add( + selectedMainParentStation!); + }); + }, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + ), + SizedBox( + height: mainParent ? 0 : 8, + ), + ////parent station + SizedBox( + child: mainParent == true + ? const SizedBox.shrink() + : FormBuilderDropdown( + decoration: normalTextFieldStyle( + "Parent Station", + "Parent Station"), + name: "parent-stations", + onChanged: (RbacStation? e) { + setState(() { + selectedParentStation = e; + }); + }, + items: parentStations.isEmpty + ? [] + : parentStations.map((e) { + return DropdownMenuItem( + value: e, + child: Text( + e.stationName!), + ); + }).toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + ), + const SizedBox( + height: 12, + ), + ////Station Type + SearchField( + itemHeight: 50, + suggestionsDecoration: + searchFieldDecoration(), + suggestions: stationTypes + .map((StationType stationType) => + SearchFieldListItem( + stationType.typeName!, + item: stationType, + child: Padding( + padding: const EdgeInsets + .symmetric( + horizontal: 10), + child: ListTile( + title: Text( + stationType.typeName!, + overflow: + TextOverflow.visible, + )), + ))) + .toList(), + validator: (station) { + if (station!.isEmpty) { + return "This field is required"; + } + return null; + }, + focusNode: stationTypeFocusNode, + searchInputDecoration: + normalTextFieldStyle( + "Station Type *", "") + .copyWith( + suffixIcon: GestureDetector( + onTap: () => + stationTypeFocusNode.unfocus(), + child: + const Icon(Icons.arrow_drop_down), + )), + onSuggestionTap: (position) { + setState(() { + selectedStationType = position.item!; + stationTypeFocusNode.unfocus(); + }); + }, + emptyWidget: EmptyWidget( + title: "Add StationType", + controller: addStationTypeController, + onpressed: () { + setState(() { + StationType stationType = + StationType( + id: null, + typeName: + addStationTypeController + .text, + color: null, + order: null, + isActive: null, + group: null); + stationTypes.add(stationType); + Navigator.pop(context); + }); + }), + ), + const SizedBox( + height: 12, + ), + ////Position title + FormBuilderDropdown( + decoration: normalTextFieldStyle( + "Head Position", "Head Position"), + name: "head-position", + items: positions.map((e) { + return DropdownMenuItem( + value: e, + child: Text(e.title!), + ); + }).toList(), + onChanged: (title) { + selectedPositiontitle = title; + }, + ), + const SizedBox( + height: 12, + ), + ////is within parent + FormBuilderSwitch( + initialValue: true, + activeColor: second, + onChanged: (value) { + setState(() { + isWithinParent = value!; + }); + }, + decoration: normalTextFieldStyle( + "Location of the station within this parent?", + 'Location of the station within this parent?'), + name: 'isWithinParent', + title: + Text(isWithinParent ? "YES" : "NO"), + ), + const SizedBox( + height: 12, + ), + Row( + //// Station Name + children: [ + Flexible( + child: FormBuilderTextField( + validator: FormBuilderValidators + .required( + errorText: + "This Field is required"), + decoration: normalTextFieldStyle( + "Station name", + "Station name"), + name: "station-name"), + ), + const SizedBox( + width: 12, + ), + //// Acronym + Flexible( + child: FormBuilderTextField( + validator: FormBuilderValidators + .required( + errorText: + "This Field is required"), + decoration: normalTextFieldStyle( + "Acronym", "Acronym"), + name: "acronym"), + ), + ], + ), + const SizedBox( + height: 12, + ), + FormBuilderTextField( + ////Description + decoration: normalTextFieldStyle( + "Station description", + "Station description"), + name: "station-description"), + const SizedBox( + height: 12, + ), + Row( + children: [ + Flexible( + ////Code + child: FormBuilderTextField( + decoration: normalTextFieldStyle( + "Code", "Code"), + name: "code"), + ), + const SizedBox( + width: 12, + ), + Flexible( + //// Full Code + child: FormBuilderTextField( + decoration: normalTextFieldStyle( + "Full Code", "Full Code"), + name: "fullcode"), + ), + ], + ), + const SizedBox( + height: 12, + ), + ////is Hospital + FormBuilderSwitch( + initialValue: isHospital, + activeColor: second, + onChanged: (value) { + setState(() { + isHospital = !isHospital; + }); + }, + decoration: normalTextFieldStyle( + "Is Hospital", ''), + name: 'isHospital', + title: Text( + isHospital == true ? "YES" : "NO"), + ), + const SizedBox( + height: 20, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + RbacStation? newStation; + if (formKey.currentState! + .saveAndValidate()) { + String? stationName = formKey + .currentState! + .value['station-name']; + String? acronym = formKey + .currentState! + .value['acronym']; + String? code = formKey + .currentState! + .value['code']; + String? fullcode = formKey + .currentState! + .value['fullcode']; + String? description = + formKey.currentState!.value[ + 'station-description']; + newStation = RbacStation( + id: null, + stationName: stationName, + stationType: + selectedStationType, + hierarchyOrderNo: mainParent + ? 1 + : selectedParentStation! + .hierarchyOrderNo! + + 1, + headPosition: + selectedPositiontitle + ?.title, + governmentAgency: + GovernmentAgency( + agencyid: + selectedAgencyId, + agencyname: null, + agencycatid: null, + privateEntity: null, + contactinfoid: + null), + acronym: acronym, + parentStation: + mainParent + ? null + : selectedParentStation! + .id!, + code: code, + fullcode: fullcode, + childStationInfo: null, + islocationUnderParent: + isWithinParent, + mainParentStation: mainParent + ? null + : selectedMainParentStation! + .id!, + description: description, + ishospital: isHospital, + isactive: true, + sellingStation: null); + Navigator.pop(context); + rbacStationBloc.add( + AddRbacStation( + station: newStation)); + } + }, + child: const Text("Add"))), + ], + ); + }), + ), ), - ), - ); - }); - }, - icon: const Icon(Icons.filter_list)) - ], + ); + }); + }), + ////Filter + IconButton( + onPressed: () { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text( + "Select agency to filter stations", + textAlign: TextAlign.center, + ), + content: SizedBox( + child: // //// Filter Agencies + Padding( + padding: const EdgeInsets.all(8), + child: SearchField( + inputFormatters: [ + UpperCaseTextFormatter() + ], + itemHeight: 100, + focusNode: agencyFocusNode, + suggestions: agencies + .map((Agency agency) => + SearchFieldListItem(agency.name!, + item: agency, + child: ListTile( + title: Text( + agency.name!, + overflow: + TextOverflow.visible, + ), + ))) + .toList(), + searchInputDecoration: + normalTextFieldStyle("Filter", "") + .copyWith( + suffixIcon: IconButton( + icon: const Icon(Icons.arrow_drop_down), + onPressed: () { + agencyFocusNode.unfocus(); + }, + )), + onSuggestionTap: (agency) { + agencyFocusNode.unfocus(); + + selectedAgencyId = agency.item!.id!; + print(selectedAgencyId); + Navigator.pop(context); + rbacStationBloc.add(FilterStation( + agencyId: selectedAgencyId)); + }, + validator: (agency) { + if (agency!.isEmpty) { + return "This field is required"; + } + return null; + }, + emptyWidget: const Center( + child: Text("No result found..."), + )), + ), + ), + ); + }); + }, + icon: const Icon(Icons.filter_list)) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -642,7 +675,7 @@ class _RbacStationScreenState extends State { boxShadow: []), padding: const EdgeInsets - .only( + .only( left: 30), child: Row( children: [ @@ -651,7 +684,8 @@ class _RbacStationScreenState extends State { children: [ Padding( padding: - const EdgeInsets.all( + const EdgeInsets + .all( 6), child: Text( @@ -719,7 +753,7 @@ class _RbacStationScreenState extends State { box1() .copyWith(boxShadow: []), padding: const EdgeInsets - .only( + .only( left: 50), child: @@ -872,7 +906,9 @@ class _RbacStationScreenState extends State { return SomethingWentWrong( message: state.message, onpressed: () { - context.read().add(GetStations(agencyId: selectedAgencyId)); + context + .read() + .add(GetStations(agencyId: selectedAgencyId)); }); } diff --git a/lib/screens/unit2/basic-info/basic-info.dart b/lib/screens/unit2/basic-info/basic-info.dart index 04d594b..a75f9a2 100644 --- a/lib/screens/unit2/basic-info/basic-info.dart +++ b/lib/screens/unit2/basic-info/basic-info.dart @@ -6,7 +6,6 @@ import 'package:flutter_svg/svg.dart'; import 'package:fluttericon/font_awesome5_icons.dart'; import 'package:intl/intl.dart'; import 'package:qr_flutter/qr_flutter.dart'; -import 'package:signature/signature.dart'; import 'package:unit2/model/login_data/user_info/user_data.dart'; import 'package:unit2/screens/unit2/basic-info/components/qr_image.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; @@ -46,45 +45,45 @@ class BasicInfo extends StatelessWidget { alignment: Alignment.center, children: [ const CoverImage(), - // Positioned( - // top: blockSizeVertical * 15.5, - // child: Stack( - // alignment: Alignment.center, - // children: [ - // CachedNetworkImage( - // imageUrl: fileUrl, - // imageBuilder: (context, imageProvider) => - // Container( - // width: 160, - // height: 160, - // decoration: BoxDecoration( - // border: Border.all( - // color: Colors.black26, width: 3), - // shape: BoxShape.circle, - // image: DecorationImage( - // image: imageProvider, - // fit: BoxFit.cover), - // ), - // ), - // placeholder: (context, url) => - // const CircularProgressIndicator(), - // errorWidget: (context, url, error) => - // Container( - // width: 160, - // height: 160, - // decoration: BoxDecoration( - // border: Border.all( - // color: Colors.white, width: 3), - // shape: BoxShape.circle, - // ), - // child: SvgPicture.asset( - // 'assets/svgs/male.svg', - // ), - // ), - // ), - // ], - // ), - // ), + Positioned( + top: blockSizeVertical * 15.5, + child: Stack( + alignment: Alignment.center, + children: [ + CachedNetworkImage( + imageUrl: fileUrl, + imageBuilder: (context, imageProvider) => + Container( + width: 160, + height: 160, + decoration: BoxDecoration( + border: Border.all( + color: Colors.black26, width: 3), + shape: BoxShape.circle, + image: DecorationImage( + image: imageProvider, + fit: BoxFit.cover), + ), + ), + placeholder: (context, url) => + const CircularProgressIndicator(), + errorWidget: (context, url, error) => + Container( + width: 160, + height: 160, + decoration: BoxDecoration( + border: Border.all( + color: Colors.white, width: 3), + shape: BoxShape.circle, + ), + child: SvgPicture.asset( + 'assets/svgs/male.svg', + ), + ), + ), + ], + ), + ), Positioned( top: 10, left: 20, @@ -137,13 +136,14 @@ class BuildInformation extends StatelessWidget { @override Widget build(BuildContext context) { DateFormat dteFormat2 = DateFormat.yMMMMd('en_US'); - globalFistname = globalFistname ?? userData.user!.login!.user!.firstName!.toUpperCase(); - globalLastname =globalLastname ?? userData.user!.login!.user!.lastName!.toUpperCase(); - globalMiddleName = globalMiddleName == null - ? (userData.employeeInfo == null + globalFistname = + globalFistname ?? userData.employeeInfo!.profile!.firstName!.toUpperCase(); + globalLastname = + globalLastname ?? userData.employeeInfo!.profile!.lastName!.toUpperCase(); + globalMiddleName = globalMiddleName ?? + (userData.employeeInfo == null ? '' - : userData.employeeInfo!.profile?.middleName?.toUpperCase()) - : ''; + : userData.employeeInfo!.profile?.middleName?.toUpperCase()); globalSex = globalSex ?? userData.employeeInfo!.profile!.sex!.toUpperCase(); globalBday = globalBday ?? userData.employeeInfo!.profile!.birthdate; final uuid = userData.employeeInfo!.uuid; diff --git a/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart b/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart index bb638b9..64c287a 100644 --- a/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart +++ b/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart @@ -10,6 +10,7 @@ import 'package:unit2/bloc/rbac/rbac_operations/module_objects/module_objects_bl import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/operation/operation_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/permission/permission_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/role_extend/role_extend_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart'; @@ -21,10 +22,11 @@ import 'package:unit2/screens/superadmin/module/module_screen.dart'; import 'package:unit2/screens/superadmin/object/object_screen.dart'; import 'package:unit2/screens/superadmin/operation/operation_screen.dart'; import 'package:unit2/screens/superadmin/permission/permission_screen.dart'; +import 'package:unit2/screens/superadmin/permission_assignment/permission_assignment_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_extend/role_extend_screen.dart'; -import 'package:unit2/screens/superadmin/roles_under/roles_under_screen.dart'; +import 'package:unit2/screens/superadmin/roles_under/assignable_roles.dart'; import 'package:unit2/screens/superadmin/stations/stations_screen.dart'; import 'package:unit2/screens/unit2/homepage.dart/module-screen.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; @@ -77,7 +79,7 @@ class SuperAdminMenu extends StatelessWidget { object.moduleName == 'superadmin' ? CardLabel( icon: iconGenerator(name: object.object.name!), - title: object.object.name!, + title: object.object.name!.toLowerCase() == 'role based access control'? 'RBAC': object.object.name!, ontap: () { if (object.object.name == 'Role') { Navigator.push(context, MaterialPageRoute( @@ -196,7 +198,21 @@ class SuperAdminMenu extends StatelessWidget { ); })); } - + if(object.object.name == 'Role Based Access Control'){ + Navigator.pushNamed(context, '/rbac'); + } + if(object.object.name == 'Permission Assignment'){ + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + PermissionAssignmentBloc()..add(GetPermissionAssignments()), + child: RbacPermissionAssignmentScreen( + id: id, + ), + ); + })); + } if (object.object.name == 'Station') { Navigator.push(context, MaterialPageRoute( builder: (BuildContext context) { diff --git a/lib/screens/unit2/homepage.dart/components/menu-screen.dart b/lib/screens/unit2/homepage.dart/components/menu-screen.dart index fe13218..b5a0888 100644 --- a/lib/screens/unit2/homepage.dart/components/menu-screen.dart +++ b/lib/screens/unit2/homepage.dart/components/menu-screen.dart @@ -18,9 +18,9 @@ class _MenuScreenState extends State { @override Widget build(BuildContext context) { final String firstName =globalFistname?? - widget.userData!.user!.login!.user!.firstName!.toUpperCase(); + widget.userData!.employeeInfo!.profile!.firstName!.toUpperCase(); final String lastname = globalLastname?? - widget.userData!.user!.login!.user!.lastName!.toUpperCase(); + widget.userData!.employeeInfo!.profile!.lastName!.toUpperCase(); return Drawer( child: SizedBox( height: screenHeight, diff --git a/lib/screens/unit2/login/components/update_required.dart b/lib/screens/unit2/login/components/update_required.dart index a5ae6b0..d2bb586 100644 --- a/lib/screens/unit2/login/components/update_required.dart +++ b/lib/screens/unit2/login/components/update_required.dart @@ -1,6 +1,8 @@ import 'dart:async'; import 'dart:io'; +import 'package:better_open_file/better_open_file.dart'; +import 'package:device_info_plus/device_info_plus.dart'; import 'package:dio/dio.dart'; import 'package:easy_app_installer/easy_app_installer.dart'; import 'package:flutter/material.dart'; @@ -9,20 +11,19 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_svg/svg.dart'; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; +import 'package:unit2/model/login_data/version_info.dart'; import 'package:unit2/screens/unit2/login/components/showAlert.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; import '../../../../bloc/user/user_bloc.dart'; import '../../../../theme-data.dart/colors.dart'; -import '../../../../utils/cpu_architecture.dart'; -import '../../../../utils/text_container.dart'; import '../../../../widgets/wave.dart'; class Update extends StatefulWidget { final String apkVersion; - final String currenVersion; + final VersionInfo versionInfo; const Update( - {super.key, required this.apkVersion, required this.currenVersion}); + {super.key, required this.apkVersion, required this.versionInfo}); @override State createState() => _UpdateState(); @@ -74,14 +75,14 @@ class _UpdateState extends State { ], ), const SizedBox( - height: 10, + height: 25, ), RichText( textAlign: TextAlign.justify, text: TextSpan( text: 'Your app version ', style: const TextStyle( - fontSize: 16, + fontSize: 14, color: Colors.black, ), children: [ @@ -95,7 +96,7 @@ class _UpdateState extends State { " did not match with the latest version ", style: TextStyle(color: Colors.black)), TextSpan( - text: widget.currenVersion.toString(), + text: widget.versionInfo.versionInfo, style: const TextStyle( color: primary, fontWeight: FontWeight.bold)), @@ -105,12 +106,12 @@ class _UpdateState extends State { style: TextStyle(color: Colors.black)), ])), const SizedBox( - height: 12.0, + height: 25, ), Container( child: downloading ? FittedBox( - child: Text( + child: Text( 'Downloading application $progressRating%', textAlign: TextAlign.center, style: Theme.of(context) @@ -130,17 +131,22 @@ class _UpdateState extends State { icon: const Icon(Icons.download), style: mainBtnStyle( primary, Colors.transparent, second), - onPressed: () async { - final progress = ProgressHUD.of(context); - progress?.showWithText( - 'Please wait...', - ); - setState(() { - downloading = true; - progressRating = '0'; - }); - await openFile(); - }, + onPressed: () async { + setState(() { + downloading = true; + progressRating = '0'; + }); + try { + await openFile(); + } catch (e) { + showAlert(context, () { + setState(() { + downloading = false; + progressRating = '0'; + }); + }); + } + }, label: const Text( "Download Latest App Version.")), ), @@ -168,9 +174,9 @@ class _UpdateState extends State { Future openFile() async { try { final filePath = await downloadFile(); - await openAPK(filePath); + await OpenFile.open(filePath); } catch (e) { - print(e.toString()); + throw e.toString(); } } @@ -181,16 +187,36 @@ class _UpdateState extends State { } } - Future downloadFile() async { - final progress = ProgressHUD.of(context); + + Future getCPUArchitecture() async { + String downloadURL = ""; + DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin(); + AndroidDeviceInfo androidDeviceInfo = await deviceInfoPlugin.androidInfo; + try{ +List cpuArchitecture = androidDeviceInfo.supportedAbis; + if (cpuArchitecture.first == 'arm64-v8a') { + downloadURL = widget.versionInfo.arm64v8aDownloadUrl!; + } + else if (cpuArchitecture.first == 'armeabi-v7a') { + downloadURL = widget.versionInfo.armeabiv7aDownloadUrl!; + } else { + downloadURL = widget.versionInfo.x8664DownloadUrl!; + } + print(downloadURL); + }catch(e){ + throw e.toString(); + } + return downloadURL; + } + + Future downloadFile() async { final appStorage = await getApplicationDocumentsDirectory(); + String? appDir; try { String url = await getCPUArchitecture(); final response = await dio.download(url, '${appStorage.path}/uniT.apk', deleteOnError: true, options: Options( - receiveTimeout: 20000, - sendTimeout: 20000, receiveDataWhenStatusError: true, responseType: ResponseType.bytes, followRedirects: false, @@ -202,47 +228,24 @@ class _UpdateState extends State { downloading = true; }); if (progressRating == '100') { - final progress = ProgressHUD.of(context); - progress!.dismiss(); setState(() { downloading = false; isDownloaded = true; }); } + appDir = '${appStorage.path}/uniT.apk'; }); - } on TimeoutException catch (_) { - progress!.dismiss(); - showAlert(context, () { - setState(() { - downloading = false; - }); - }); - throw TimeoutException(timeoutError); - } on SocketException catch (_) { - progress!.dismiss(); - showAlert(context, () { - setState(() { - downloading = false; - }); - }); - throw const SocketException(timeoutError); - } on DioError catch (_) { - progress!.dismiss(); - showAlert(context, () { - setState(() { - downloading = false; - }); - }); - throw TimeoutException(timeoutError); - } catch (_) { - progress!.dismiss(); - showAlert(context, () { - setState(() { - downloading = false; - }); - }); - throw TimeoutException(timeoutError); + } on TimeoutException catch (e) { + throw e.toString(); + } on SocketException catch (e) { + throw e.toString(); + } on Error catch (e) { + throw e.toString(); + } catch (e) { + throw e.toString(); } - return '${appStorage.path}/uniT.apk'; + + return appDir!; } + } diff --git a/lib/screens/unit2/login/login.dart b/lib/screens/unit2/login/login.dart index d11a2f4..06d94e8 100644 --- a/lib/screens/unit2/login/login.dart +++ b/lib/screens/unit2/login/login.dart @@ -108,7 +108,7 @@ class _UniT2LoginState extends State { }, builder: (context, state) { if (state is VersionLoaded) { return Builder(builder: (context) { - if (state.versionInfo?.version != state.apkVersion) { + if (state.versionInfo?.id == state.apkVersion) { return SizedBox( child: SingleChildScrollView( child: Stack( @@ -355,7 +355,7 @@ class _UniT2LoginState extends State { //New update available return Update( apkVersion: state.apkVersion!, - currenVersion: state.versionInfo!.version!, + versionInfo: state.versionInfo!, ); } }); diff --git a/lib/screens/unit2/roles/establishment_point_person/est_point_person_station.dart b/lib/screens/unit2/roles/establishment_point_person/est_point_person_station.dart index 5193ef5..7072ac8 100644 --- a/lib/screens/unit2/roles/establishment_point_person/est_point_person_station.dart +++ b/lib/screens/unit2/roles/establishment_point_person/est_point_person_station.dart @@ -171,7 +171,7 @@ class EstPointPersonStationScreen extends StatelessWidget { ////Station Type SearchField( itemHeight: 50, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), suggestions: stationTypes .map((StationType stationType) => SearchFieldListItem( diff --git a/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart b/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart index f773615..213aab0 100644 --- a/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart +++ b/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart @@ -1,5 +1,6 @@ import 'package:assets_audio_player/assets_audio_player.dart'; import 'package:audioplayers/audioplayers.dart'; +import 'package:awesome_dialog/awesome_dialog.dart'; import 'package:cool_alert/cool_alert.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -35,13 +36,13 @@ class _QRCodeScannerState extends State { player = AudioPlayer(); super.initState(); } + @override void dispose() { player?.dispose(); super.dispose(); } - @override Widget build(BuildContext context) { return Scaffold( @@ -73,83 +74,86 @@ class _QRCodeScannerState extends State { progress!.dismiss(); } if (state is ScanSuccess) { - Future.delayed(const Duration(seconds: 1), () async{ - await player?.play(AssetSource("success.mp3")); + Future.delayed(const Duration(seconds: 1), () async { + await player?.play(AssetSource("success.mp3")); }); context.read().add(ScanQr(token: state.token)); } if (state is QRInvalid) { - Future.delayed(const Duration(seconds: 1), ()async { + Future.delayed(const Duration(seconds: 1), () async { await player?.play(AssetSource("invalid.mp3")); }); context.read().add(ScanQr(token: state.token)); } if (state is ScanFailed) { - Future.delayed(const Duration(seconds: 1), ()async { - await player?.play(AssetSource("fail.mp3")); + Future.delayed(const Duration(seconds: 1), () async { + await player?.play(AssetSource("fail.mp3")); }); - + context.read().add(ScanQr(token: state.token)); } if (state is IncomingScanState) { - CoolAlert.show( - barrierDismissible: false, - context: context, - type: CoolAlertType.loading, - text: "Enter Temperature", - widget: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24), - child: FormBuilder( - key: formKey, - child: Column( - children: [ - const SizedBox( - height: 24, + AwesomeDialog( + dismissOnBackKeyPress: false, + context: context, + dialogType: DialogType.info, + dismissOnTouchOutside: false, + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24), + child: FormBuilder( + key: formKey, + child: Column( + children: [ + const Text("Enter Temperature",style: TextStyle(color: Colors.black),), + const SizedBox( + height: 24, + ), + FormBuilderTextField( + keyboardType: TextInputType.number, + name: "temp", + decoration: + normalTextFieldStyle("Temperature", ""), + validator: numericRequired), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.infinity, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + child: const Text(submit), + onPressed: () { + if (formKey.currentState!.saveAndValidate()) { + double temperature = double.parse( + formKey.currentState!.value['temp']); + context.read().add( + PerformIncomingPostLog( + temp: temperature)); + Navigator.of(context).pop(); + } + }, ), - FormBuilderTextField( - keyboardType: TextInputType.number, - name: "temp", - decoration: - normalTextFieldStyle("Temperature", ""), - validator: numericRequired), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.infinity, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - child: const Text(submit), - onPressed: () { - if (formKey.currentState!.saveAndValidate()) { - double temperature = double.parse( - formKey.currentState!.value['temp']); - context.read().add( - PerformIncomingPostLog( - temp: temperature)); - Navigator.of(context).pop(); - } - }, - ), - ) - ], - )), - )); + ) + ], + )), + ), + ).show(); } if (state is OutGoingScanState) { - CoolAlert.show( - barrierDismissible: false, - context: context, - type: CoolAlertType.loading, - text: "Enter Destination", - widget: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24), + AwesomeDialog( + dismissOnBackKeyPress: false, + context: context, + dialogType: DialogType.info, + dismissOnTouchOutside: false, + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24,vertical: 24), child: FormBuilder( key: formKey, child: Column( children: [ + const Text("Enter Destination"), const SizedBox( height: 24, ), @@ -185,7 +189,8 @@ class _QRCodeScannerState extends State { ) ], )), - )); + )).show(); + } }, builder: (context, state) { @@ -302,28 +307,56 @@ class _QRCodeScannerState extends State { children: [ SelectedState( //TODO add api data - title: state.roleIdRoleName.roleName.toLowerCase() == "41" || - state.roleIdRoleName.roleName.toLowerCase() == 'qr code scanner' || - state.roleIdRoleName.roleName.toLowerCase() == 'office/branch chief' || - state.roleIdRoleName.roleName.toLowerCase() == 'registration in-charge' + title: state.roleIdRoleName.roleName + .toLowerCase() == + "41" || + state.roleIdRoleName.roleName + .toLowerCase() == + 'qr code scanner' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'office/branch chief' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'registration in-charge' ? state.assignedArea.stationName - : state.roleIdRoleName.roleName.toLowerCase() == 'barangay chairperson' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'barangay chairperson' ? state.assignedArea.brgydesc - : state.roleIdRoleName.roleName.toLowerCase() == 'purok president' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'purok president' ? state.assignedArea.purokdesc - : state.roleIdRoleName.roleName.toLowerCase() == 'establishment point-person' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'establishment point-person' ? "Agency" : "", - subtitle: state.roleIdRoleName.roleName.toLowerCase() == "41" || - state.roleIdRoleName.roleName.toLowerCase() == 'qr code scanner' || - state.roleIdRoleName.roleName.toLowerCase() == 'office/branch chief' || - state.roleIdRoleName.roleName.toLowerCase() == 'registration in-charge' + subtitle: state.roleIdRoleName.roleName + .toLowerCase() == + "41" || + state.roleIdRoleName.roleName + .toLowerCase() == + 'qr code scanner' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'office/branch chief' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'registration in-charge' ? "Station" - : state.roleIdRoleName.roleName.toLowerCase() == 'barangay chairperson' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'barangay chairperson' ? "Barangay" - : state.roleIdRoleName.roleName.toLowerCase() == 'purok president' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'purok president' ? "Purok" - : state.roleIdRoleName.roleName.toLowerCase() == 'establishment point-person' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'establishment point-person' ? "Agency" : "", ), diff --git a/lib/screens/unit2/roles/rbac/rbac.dart b/lib/screens/unit2/roles/rbac/rbac.dart index 12fe372..60a39de 100644 --- a/lib/screens/unit2/roles/rbac/rbac.dart +++ b/lib/screens/unit2/roles/rbac/rbac.dart @@ -222,7 +222,7 @@ class _RBACScreenState extends State { builder: (context, setState) { return SearchField( itemHeight: 40, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), suggestions: state.role .map((RBAC role) => SearchFieldListItem( @@ -305,7 +305,7 @@ class _RBACScreenState extends State { builder: (context, setState) { return SearchField( itemHeight: 40, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), suggestions: state.modules .map((RBAC module) => SearchFieldListItem( @@ -602,7 +602,7 @@ class _RBACScreenState extends State { ), SearchField( itemHeight: 40, - suggestionsDecoration: box1(), + suggestionsDecoration: searchFieldDecoration(), suggestions: state.objects .map((RBAC object) => SearchFieldListItem(object.name!, item: object, diff --git a/lib/sevices/roles/rbac_operations/agency_services.dart b/lib/sevices/roles/rbac_operations/agency_services.dart index 5445652..380223a 100644 --- a/lib/sevices/roles/rbac_operations/agency_services.dart +++ b/lib/sevices/roles/rbac_operations/agency_services.dart @@ -1,6 +1,5 @@ import 'dart:convert'; - -import 'package:unit2/screens/profile/components/other_information/org_membership/add_modal.dart'; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import 'package:unit2/utils/urls.dart'; @@ -10,17 +9,15 @@ import 'package:http/http.dart' as http; class AgencyServices { static final AgencyServices _instance = AgencyServices(); static AgencyServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; + String path = Url.instance.agencies(); + Future> getAgencies() async { List agencies = []; - String path = Url.instance.agencies(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance .getRequest(path: path, headers: headers, param: {}); @@ -38,34 +35,30 @@ class AgencyServices { } return agencies; } - Future>add({required Agency agency})async{ - Map statusResponse = {}; - String path = Url.instance.postAgencies(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; + + Future> add({required Agency agency}) async { + Map statusResponse = {}; Map body = { - "name":agency.name, - "category_id":agency.category!.id, - "private_entity":agency.privateEntity, - "contact_info":null, + "name": agency.name, + "category_id": agency.category!.id, + "private_entity": agency.privateEntity, + "contact_info": null, }; - try{ - http.Response response = await Request.instance.postRequest(param: {},path: path, body: body,headers: headers); - if(response.statusCode == 201){ + try { + http.Response response = await Request.instance + .postRequest(param: {}, path: path, body: body, headers: headers); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { Map data = jsonDecode(response.body); - statusResponse = data; - }else{ - Map data = jsonDecode(response.body); String message = data['message']; statusResponse.addAll({'message': message}); statusResponse.addAll( {'success': false}, ); } - }catch(e){ + } catch (e) { throw e.toString(); } return statusResponse; diff --git a/lib/sevices/roles/rbac_operations/assigned_area_services.dart b/lib/sevices/roles/rbac_operations/assigned_area_services.dart index 7dd4962..07972d2 100644 --- a/lib/sevices/roles/rbac_operations/assigned_area_services.dart +++ b/lib/sevices/roles/rbac_operations/assigned_area_services.dart @@ -1,24 +1,22 @@ import 'dart:convert'; import 'package:unit2/model/profile/assigned_area.dart'; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/urls.dart'; import 'package:http/http.dart' as http; - import '../../../utils/request.dart'; class RbacAssignedAreaServices { static final RbacAssignedAreaServices _instance = RbacAssignedAreaServices(); static RbacAssignedAreaServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; + String path = Url.instance.getAssignAreas(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; Future> getAssignedArea({required int id}) async { List userAssignedAreas = []; - String path = Url.instance.getAssignAreas(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map param = { "assigned_role__user__id": id.toString(), }; @@ -39,20 +37,18 @@ class RbacAssignedAreaServices { } return userAssignedAreas; } - Future deleteAssignedArea({required int areaId}) async { + + Future deleteAssignedArea({required int areaId}) async { bool success = false; - String path = "${Url.instance.getAssignAreas()}$areaId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { - http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + http.Response response = await Request.instance.deleteRequest( + path: "${path + areaId.toString()}/", + headers: headers, + body: {}, + param: {}); if (response.statusCode == 200) { success = true; - }else{ + } else { success = false; } } catch (e) { @@ -60,28 +56,30 @@ class RbacAssignedAreaServices { } return success; } - Future> add ({required int userId, required int roleId, required int areaTypeId, required String areaId}) async{ - String path = Url.instance.getAssignAreas(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; - Map? responseStatus = {}; + + Future> add( + {required int userId, + required int roleId, + required int areaTypeId, + required String areaId}) async { + Map? responseStatus = {}; Map body = { - "user_id":userId, - "role_id":roleId, - "assigned_areas": [{"areatypeid":areaTypeId,"areaid":areaId}] + "user_id": userId, + "role_id": roleId, + "assigned_areas": [ + {"areatypeid": areaTypeId, "areaid": areaId} + ] }; - try{ - http.Response response = await Request.instance.postRequest(path: path, headers: headers, body: body, param: {}); - if(response.statusCode == 201){ - Map data = jsonDecode(response.body); + try { + http.Response response = await Request.instance + .postRequest(path: path, headers: headers, body: body, param: {}); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); responseStatus = data; } else { responseStatus.addAll({'success': false}); } - }catch(e){ + } catch (e) { throw e.toString(); } return responseStatus; diff --git a/lib/sevices/roles/rbac_operations/module_objects_services.dart b/lib/sevices/roles/rbac_operations/module_objects_services.dart index 87e9890..5652367 100644 --- a/lib/sevices/roles/rbac_operations/module_objects_services.dart +++ b/lib/sevices/roles/rbac_operations/module_objects_services.dart @@ -1,7 +1,6 @@ import 'dart:convert'; - -import 'package:unit2/model/login_data/user_info/module.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import '../../../model/rbac/rbac_rbac.dart'; import '../../../utils/request.dart'; import '../../../utils/urls.dart'; @@ -10,16 +9,14 @@ class RbacModuleObjectsServices { static final RbacModuleObjectsServices _instance = RbacModuleObjectsServices(); static RbacModuleObjectsServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - Future> getModuleObjects() async { - List moduleObjects = []; - String path = Url.instance.getModuleObjects(); - Map headers = { + Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret':xClientSecret }; + String path = Url.instance.getModuleObjects(); + Future> getModuleObjects() async { + List moduleObjects = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -38,19 +35,12 @@ class RbacModuleObjectsServices { return moduleObjects; } - ////Add Future> add({ required int assignerId, required int? moduleId, required List objectsId, }) async { - String path = Url.instance.getModuleObjects(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map body = { "module_id": moduleId, "objects": objectsId, @@ -76,17 +66,11 @@ class RbacModuleObjectsServices { return statusResponse; } - Future deleteRbacModuleObject({required int moduleObjectId}) async { + Future delete({required int moduleObjectId}) async { bool success = false; - String path = "${Url.instance.getModuleObjects()}$moduleObjectId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: "${path+moduleObjectId.toString()}/", headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/module_services.dart b/lib/sevices/roles/rbac_operations/module_services.dart index 76ea4a1..1020b70 100644 --- a/lib/sevices/roles/rbac_operations/module_services.dart +++ b/lib/sevices/roles/rbac_operations/module_services.dart @@ -1,24 +1,21 @@ import 'dart:convert'; - import 'package:unit2/model/rbac/rbac.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import '../../../utils/urls.dart'; class RbacModuleServices { static final RbacModuleServices _instance = RbacModuleServices(); static RbacModuleServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getRbacModule() async { - List modules = []; String path = Url.instance.getModules(); Map headers = { 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Key':xClientKey, + 'X-Client-Secret':xClientSecret }; + Future> getRbacModule() async { + List modules = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -43,13 +40,7 @@ class RbacModuleServices { required String? slug, required String? short, required int id}) async { - String path = Url.instance.getModules(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -88,13 +79,7 @@ class RbacModuleServices { required int? createdBy, required int updatedBy, }) async { - String path = "${Url.instance.getModules()}$moduleId/"; Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -106,7 +91,7 @@ class RbacModuleServices { }; try { http.Response response = await Request.instance - .putRequest(path: path, body: body, headers: headers, param: {}); + .putRequest(path: "${path+moduleId.toString()}/", body: body, headers: headers, param: {}); if (response.statusCode == 200) { Map data = jsonDecode(response.body); statusResponse = data; @@ -126,15 +111,9 @@ class RbacModuleServices { Future deleteRbacModule({required int moduleId}) async { bool success = false; - String path = "${Url.instance.getModules()}$moduleId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: '${path+moduleId.toString()}/', headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/object_services.dart b/lib/sevices/roles/rbac_operations/object_services.dart index 7e61543..8995600 100644 --- a/lib/sevices/roles/rbac_operations/object_services.dart +++ b/lib/sevices/roles/rbac_operations/object_services.dart @@ -1,24 +1,21 @@ import 'dart:convert'; - import 'package:unit2/model/rbac/rbac.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import '../../../utils/urls.dart'; class RbacObjectServices { static final RbacObjectServices _instance = RbacObjectServices(); static RbacObjectServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getRbacObjects() async { - List objects = []; - String path = Url.instance.getObject(); - Map headers = { + String path = Url.instance.getObject(); + Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getRbacObjects() async { + List objects = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -43,13 +40,7 @@ class RbacObjectServices { required String? slug, required String? short, required int id}) async { - String path = Url.instance.getObject(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -67,7 +58,7 @@ class RbacObjectServices { } else { Map data = jsonDecode(response.body); String message = data['message']; - statusResponse.addAll({'message': "Error Adding Object"}); + statusResponse.addAll({'message': message}); statusResponse.addAll( {'success': false}, ); @@ -87,13 +78,8 @@ class RbacObjectServices { required int? createdBy, required int updatedBy, }) async { - String path = "${Url.instance.getObject()}$objectId/"; Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; + String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -104,14 +90,14 @@ class RbacObjectServices { }; try { http.Response response = await Request.instance - .putRequest(path: path, body: body, headers: headers, param: {}); + .putRequest(path: "${path+objectId.toString()}/", body: body, headers: headers, param: {}); if (response.statusCode == 200) { Map data = jsonDecode(response.body); statusResponse = data; } else { Map data = jsonDecode(response.body); String message = data['message']; - statusResponse.addAll({'message': "Error Updating Object"}); + statusResponse.addAll({'message': message}); statusResponse.addAll( {'success': false}, ); @@ -124,15 +110,9 @@ class RbacObjectServices { Future deleteRbacRole({required int objectId}) async { bool success = false; - String path = "${Url.instance.getObject()}$objectId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: "${path+objectId.toString()}/", headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/operation_services.dart b/lib/sevices/roles/rbac_operations/operation_services.dart index f737dc7..7c97b76 100644 --- a/lib/sevices/roles/rbac_operations/operation_services.dart +++ b/lib/sevices/roles/rbac_operations/operation_services.dart @@ -1,24 +1,21 @@ import 'dart:convert'; - import 'package:unit2/model/rbac/rbac.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import '../../../utils/urls.dart'; class RbacOperationServices { static final RbacOperationServices _instance = RbacOperationServices(); static RbacOperationServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getRbacOperations() async { - List roles = []; String path = Url.instance.getOperations(); - Map headers = { + Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getRbacOperations() async { + List roles = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -43,13 +40,7 @@ class RbacOperationServices { required String? slug, required String? short, required int id}) async { - String path = Url.instance.getOperations(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -87,13 +78,7 @@ class RbacOperationServices { required int? createdBy, required int updatedBy, }) async { - String path = "${Url.instance.getRbacOperations()}$operationId/"; Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -104,7 +89,7 @@ class RbacOperationServices { }; try { http.Response response = await Request.instance - .putRequest(path: path, body: body, headers: headers, param: {}); + .putRequest(path: '${path+operationId.toString()}/', body: body, headers: headers, param: {}); if (response.statusCode == 200) { Map data = jsonDecode(response.body); statusResponse = data; @@ -124,15 +109,9 @@ class RbacOperationServices { Future delete({required int operation}) async { bool success = false; - String path = "${Url.instance.getRbacOperations()}$operation/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: '${path+operation.toString()}/', headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/permission_assignment_services.dart b/lib/sevices/roles/rbac_operations/permission_assignment_services.dart new file mode 100644 index 0000000..135dbf5 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/permission_assignment_services.dart @@ -0,0 +1,83 @@ +import 'dart:convert'; + +import 'package:unit2/model/rbac/permission_assignment.dart'; +import 'package:unit2/utils/global.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; +import 'package:http/http.dart' as http; + +class RbacPermissionAssignmentServices { + static final RbacPermissionAssignmentServices _instance = + RbacPermissionAssignmentServices(); + static RbacPermissionAssignmentServices get instance => _instance; + String path = Url.instance.getPermissionAssignment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; + Future> getPermissionAssignment() async { + List permissionAssignments = []; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var rbac in data['data']) { + PermissionAssignment permissionAssignment = + PermissionAssignment.fromJson(rbac); + permissionAssignments.add(permissionAssignment); + } + } + } + } catch (e) { + e.toString(); + } + return permissionAssignments; + } + + Future deletePermissionAssignment({required int id}) async { + bool success = false; + try { + http.Response response = await Request.instance + .deleteRequest(path: "${path+id.toString()}/", headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } + + Future> addPermissionAssignment( + {required int assignerId, + required List opsId, + required int roleId}) async { + Map statusResponse = {}; + Map body = { + "role_id": roleId, + "permissions": opsId, + "assigner_user_id": assignerId + }; + try { + http.Response response = await Request.instance + .postRequest(param: {}, path: path, body: body, headers: headers); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } +} diff --git a/lib/sevices/roles/rbac_operations/permission_service.dart b/lib/sevices/roles/rbac_operations/permission_service.dart index aa49ba5..544bf13 100644 --- a/lib/sevices/roles/rbac_operations/permission_service.dart +++ b/lib/sevices/roles/rbac_operations/permission_service.dart @@ -1,25 +1,21 @@ import 'dart:convert'; - import 'package:unit2/model/rbac/permission.dart'; -import 'package:unit2/model/rbac/rbac.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import '../../../utils/urls.dart'; class RbacPermissionServices { static final RbacPermissionServices _instance = RbacPermissionServices(); static RbacPermissionServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - + String path = Url.instance.getPersmissions(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key':xClientKey, + 'X-Client-Secret': xClientSecret + }; Future> getRbacPermission() async { List permissions = []; - String path = Url.instance.getPersmissions(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -46,13 +42,7 @@ class RbacPermissionServices { required int? objectId, required List operationsId, }) async { - String path = Url.instance.getPersmissions(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map body = { "object_id": objectId, "operations": operationsId, @@ -80,15 +70,9 @@ class RbacPermissionServices { Future deletePermission ({required int permissionId}) async { bool success = false; - String path = "${Url.instance.getPersmissions()}$permissionId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: "${path+permissionId.toString()}/", headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/role_assignment_services.dart b/lib/sevices/roles/rbac_operations/role_assignment_services.dart index b9d6eae..e8aceca 100644 --- a/lib/sevices/roles/rbac_operations/role_assignment_services.dart +++ b/lib/sevices/roles/rbac_operations/role_assignment_services.dart @@ -1,30 +1,27 @@ import 'dart:convert'; import 'package:unit2/model/rbac/assigned_role.dart'; -import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import 'package:unit2/utils/urls.dart'; - import 'package:http/http.dart' as http; - import '../../../model/profile/basic_information/primary-information.dart'; class RbacRoleAssignmentServices { static final RbacRoleAssignmentServices _instance = RbacRoleAssignmentServices(); static RbacRoleAssignmentServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getAssignedRoles( - {required String firstname, required String lastname}) async { - List assignedRoles = []; - String path = Url.instance.getRoleAssignment(); + String path = Url.instance.getRoleAssignment(); Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getAssignedRoles( + {required String firstname, required String lastname}) async { + List assignedRoles = []; + + Map param = { "user__first_name__icontains": firstname, "user__last_name__icontains": lastname @@ -49,15 +46,9 @@ class RbacRoleAssignmentServices { Future deleteAssignedRole({required int roleId}) async { bool success = false; - String path = "${Url.instance.getRoleAssignment()}$roleId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: '${path+roleId.toString()}/', headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } @@ -72,13 +63,7 @@ class RbacRoleAssignmentServices { required int? assignerId, required List roles, }) async { - String path = Url.instance.getRoleAssignment(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map body = { "user_id": userId, "roles": roles, diff --git a/lib/sevices/roles/rbac_operations/role_extend_services.dart b/lib/sevices/roles/rbac_operations/role_extend_services.dart index b5c0fc9..8200111 100644 --- a/lib/sevices/roles/rbac_operations/role_extend_services.dart +++ b/lib/sevices/roles/rbac_operations/role_extend_services.dart @@ -1,26 +1,23 @@ import 'dart:convert'; import 'package:unit2/model/rbac/role_extend.dart'; -import 'package:unit2/model/rbac/role_under.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import '../../../utils/request.dart'; import '../../../utils/urls.dart'; class RbacRoleExtendServices { static final RbacRoleExtendServices _instance = RbacRoleExtendServices(); static RbacRoleExtendServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - + String path = Url.instance.getRoleExtend(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; Future> getRolesExtend() async { List rolesextend = []; - String path = Url.instance.getRoleExtend(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; - // try { + try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); if (response.statusCode == 200) { @@ -32,9 +29,9 @@ class RbacRoleExtendServices { } } } - // } catch (e) { - // throw e.toString(); - // } + } catch (e) { + throw e.toString(); + } return rolesextend; } @@ -43,13 +40,7 @@ class RbacRoleExtendServices { required int? roleId, required List rolesExtendsId, }) async { - String path = Url.instance.getRoleExtend(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map body = { "role_main_id": roleId, "roles_extend": rolesExtendsId, @@ -76,15 +67,12 @@ class RbacRoleExtendServices { Future delete({required int roleExtendId}) async { bool success = false; - String path = "${Url.instance.getRoleExtend()}$roleExtendId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { - http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + http.Response response = await Request.instance.deleteRequest( + path: '${path + roleExtendId.toString()}/', + headers: headers, + body: {}, + param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/role_module_services.dart b/lib/sevices/roles/rbac_operations/role_module_services.dart index 27a0779..760a265 100644 --- a/lib/sevices/roles/rbac_operations/role_module_services.dart +++ b/lib/sevices/roles/rbac_operations/role_module_services.dart @@ -1,9 +1,8 @@ import 'dart:convert'; -import 'package:unit2/model/login_data/user_info/module.dart'; import 'package:http/http.dart' as http; import 'package:unit2/model/rbac/role_module.dart'; -import '../../../model/rbac/rbac_rbac.dart'; +import 'package:unit2/utils/global.dart'; import '../../../utils/request.dart'; import '../../../utils/urls.dart'; @@ -11,17 +10,14 @@ class RbacRoleModuleServices { static final RbacRoleModuleServices _instance = RbacRoleModuleServices(); static RbacRoleModuleServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getRoleModules() async { - List roleModules = []; String path = Url.instance.getRoleModules(); - Map headers = { + Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getRoleModules() async { + List roleModules = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -46,13 +42,7 @@ class RbacRoleModuleServices { required int? roleId, required List moduleIds, }) async { - String path = Url.instance.getRoleModules(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map body = { "role_id": roleId, "modules": moduleIds, @@ -80,15 +70,9 @@ class RbacRoleModuleServices { Future deleteRbacRoleModule({required int moduleObjectId}) async { bool success = false; - String path = "${Url.instance.getRoleModules()}$moduleObjectId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: "${path+moduleObjectId.toString()}/", headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/role_services.dart b/lib/sevices/roles/rbac_operations/role_services.dart index 08a689c..b7609ba 100644 --- a/lib/sevices/roles/rbac_operations/role_services.dart +++ b/lib/sevices/roles/rbac_operations/role_services.dart @@ -1,25 +1,21 @@ import 'dart:convert'; - import 'package:unit2/model/rbac/rbac.dart'; -import 'package:unit2/sevices/profile/education_services.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import '../../../utils/urls.dart'; class RbacRoleServices { static final RbacRoleServices _instance = RbacRoleServices(); static RbacRoleServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - + String path = Url.instance.getRbacRoles(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; Future> getRbacRoles() async { List roles = []; - String path = Url.instance.getRbacRoles(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -45,13 +41,7 @@ class RbacRoleServices { required String? slug, required String? short, required int id}) async { - String path = Url.instance.getRbacRoles(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -67,7 +57,7 @@ class RbacRoleServices { Map data = jsonDecode(response.body); statusResponse = data; } else { - Map data = jsonDecode(response.body); + Map data = jsonDecode(response.body); String message = data['message']; statusResponse.addAll({'message': message}); statusResponse.addAll( @@ -89,13 +79,7 @@ class RbacRoleServices { required int? createdBy, required int updatedBy, }) async { - String path = "${Url.instance.getRbacRoles()}$roleId/"; Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -105,8 +89,11 @@ class RbacRoleServices { "updated_by_id": updatedBy }; try { - http.Response response = await Request.instance - .putRequest(path: path, body: body, headers: headers, param: {}); + http.Response response = await Request.instance.putRequest( + path: "${path + roleId.toString()}/", + body: body, + headers: headers, + param: {}); if (response.statusCode == 200) { Map data = jsonDecode(response.body); statusResponse = data; @@ -126,15 +113,12 @@ class RbacRoleServices { Future deleteRbacRole({required int roleId}) async { bool success = false; - String path = "${Url.instance.getRbacRoles()}$roleId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { - http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + http.Response response = await Request.instance.deleteRequest( + path: "${path + roleId.toString()}/", + headers: headers, + body: {}, + param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/roles_under_services.dart b/lib/sevices/roles/rbac_operations/roles_under_services.dart index 719dab4..e0bacd7 100644 --- a/lib/sevices/roles/rbac_operations/roles_under_services.dart +++ b/lib/sevices/roles/rbac_operations/roles_under_services.dart @@ -2,23 +2,21 @@ import 'dart:convert'; import 'package:unit2/model/rbac/role_under.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import '../../../utils/request.dart'; import '../../../utils/urls.dart'; class RbacRoleUnderServices { static final RbacRoleUnderServices _instance = RbacRoleUnderServices(); static RbacRoleUnderServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getRolesUnder() async { - List rolesUnder = []; - String path = Url.instance.getRolesUnder(); + String path = Url.instance.getRolesUnder(); Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getRolesUnder() async { + List rolesUnder = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -42,13 +40,8 @@ class RbacRoleUnderServices { required int? roleId, required List rolesId, }) async { - String path = Url.instance.getRolesUnder(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; + Map body = { "role_main_id": roleId, "roles_under": rolesId, @@ -76,15 +69,9 @@ class RbacRoleUnderServices { Future deleteRbacRoleUnder({required int roleUnderId}) async { bool success = false; - String path = "${Url.instance.getRolesUnder ()}$roleUnderId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: "${path+roleUnderId.toString()}/", headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/station_services.dart b/lib/sevices/roles/rbac_operations/station_services.dart index 977a1ee..ce06b18 100644 --- a/lib/sevices/roles/rbac_operations/station_services.dart +++ b/lib/sevices/roles/rbac_operations/station_services.dart @@ -1,27 +1,24 @@ import 'dart:convert'; import 'package:unit2/model/utils/position.dart'; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import 'package:unit2/utils/urls.dart'; import 'package:http/http.dart' as http; import '../../../model/rbac/rbac_station.dart'; import '../../../model/rbac/station_type.dart'; -import '../../../model/roles/pass_check/station_assign_area.dart'; class RbacStationServices { static final RbacStationServices _instance = RbacStationServices(); static RbacStationServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getStations({required String agencyId}) async { - List stations = []; String path = Url.instance.getStation(); - Map param = {"government_agency_id": agencyId.toString()}; Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getStations({required String agencyId}) async { + List stations = []; + Map param = {"government_agency_id": agencyId.toString()}; try { http.Response response = await Request.instance .getRequest(param: param, path: path, headers: headers); @@ -42,9 +39,6 @@ class RbacStationServices { Future> getStationTypes() async { String path = Url.instance.getStationType(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - }; List stationTypes = []; try { @@ -67,11 +61,7 @@ class RbacStationServices { Future> getPositionTitle() async { String path = Url.instance.getPositionTitle(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - }; List positions = []; - try { http.Response response = await Request.instance .getRequest(path: path, param: {}, headers: headers); @@ -93,13 +83,7 @@ class RbacStationServices { Future> addStation( {required RbacStation station}) async { Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String path = Url.instance.postStation(); - try { Map body = { "station_name": station.stationName, diff --git a/lib/theme-data.dart/box_shadow.dart b/lib/theme-data.dart/box_shadow.dart index 1df168d..97e4585 100644 --- a/lib/theme-data.dart/box_shadow.dart +++ b/lib/theme-data.dart/box_shadow.dart @@ -1,8 +1,15 @@ import 'package:flutter/material.dart'; +import 'package:searchfield/searchfield.dart'; BoxDecoration box1(){ return const BoxDecoration( boxShadow: [BoxShadow(color: Colors.black12,spreadRadius: 5,blurRadius: 5)] , color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(3))); +} +SuggestionDecoration searchFieldDecoration(){ + return SuggestionDecoration( + boxShadow:const [BoxShadow(color: Colors.black12,spreadRadius: 5,blurRadius: 5)] , + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(3))); } \ No newline at end of file diff --git a/lib/utils/cpu_architecture.dart b/lib/utils/cpu_architecture.dart index d0245da..f3ff1a1 100644 --- a/lib/utils/cpu_architecture.dart +++ b/lib/utils/cpu_architecture.dart @@ -13,7 +13,7 @@ Future getCPUArchitecture() async { try { Response response = await dio.get(apkUrl, options: Options( - receiveTimeout: 20000, + receiveTimeout:const Duration(seconds: 25), receiveDataWhenStatusError: true, responseType: ResponseType.json, followRedirects: false, @@ -37,8 +37,8 @@ Future getCPUArchitecture() async { throw TimeoutException("Connection timeout"); } on SocketException catch (_) { throw const SocketException("Connection timeout"); - } on DioError catch (_) { - throw DioErrorType.connectTimeout; + } on DioException catch (e) { + throw e.toString(); } return downloadURL; } \ No newline at end of file diff --git a/lib/utils/formatters.dart b/lib/utils/formatters.dart index 4db4cd8..154e478 100644 --- a/lib/utils/formatters.dart +++ b/lib/utils/formatters.dart @@ -3,7 +3,8 @@ import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; var mobileFormatter = MaskTextInputFormatter( mask: "+63 (###) ###-####", - filter: {"#": RegExp(r"^[1-9][0-9]*$")}, + filter: {"#": RegExp(r'^[0-9][0-9]*$') +}, type: MaskAutoCompletionType.lazy, initialText: "0"); diff --git a/lib/utils/global.dart b/lib/utils/global.dart index adb63a6..49b3b28 100644 --- a/lib/utils/global.dart +++ b/lib/utils/global.dart @@ -10,7 +10,6 @@ double safeAreaHorizontal = 0; double safeAreaVertical = 0; double safeBlockHorizontal = 0; double safeBlockVertical = 0; - const xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; const xClientSecret = "unitcYqAN7GGalyz"; String? globalFistname; @@ -20,6 +19,18 @@ const xClientSecret = "unitcYqAN7GGalyz"; String? globalSex; Profile? globalCurrentProfile; + +const String urlDownloadArmeabiv7aAPK = + "https://agusandelnorte.gov.ph/media/public/transparency/downloadables/UniT-App/v1.0.1/beta/unit_app_v1_0_1_beta_armeabi-v7a-release.apk?download"; + +const String urlDownloadX8664APK = +"https://agusandelnorte.gov.ph/media/public/transparency/downloadables/UniT-App/v1.0.1/beta/unit_app_v1_0_1_beta_x86_64-release.apk?download"; + +const String urlDownloadarm64v8aAPK = + "https://agusandelnorte.gov.ph/media/public/transparency/downloadables/UniT-App/v1.0.1/beta/unit_app_v1_0_1_beta_arm64-v8a-release.apk?download"; + + + //// hive boxes Box? CREDENTIALS; Box? SOS; \ No newline at end of file diff --git a/lib/utils/request.dart b/lib/utils/request.dart index 562a9fb..80d771f 100644 --- a/lib/utils/request.dart +++ b/lib/utils/request.dart @@ -2,7 +2,6 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; -import 'package:fluttertoast/fluttertoast.dart'; import 'package:http/http.dart'; import 'package:unit2/utils/text_container.dart'; import 'package:unit2/utils/urls.dart'; @@ -19,7 +18,7 @@ class Request { Map? param}) async { Response response; try { - response = await get(Uri.http(host, path!, param), headers: headers) + response = await get(Uri.https(host, path!, param), headers: headers) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { // Fluttertoast.showToast( @@ -61,7 +60,7 @@ class Request { Map? param}) async { Response response; try { - response = await post(Uri.http(host, path!, param), + response = await post(Uri.https(host, path!, param), headers: headers, body: jsonEncode(body)) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { @@ -104,7 +103,7 @@ class Request { required Map? param}) async { Response response; try { - response = await put(Uri.http(host, path, param), + response = await put(Uri.https(host, path, param), headers: headers, body: jsonEncode(body)); } on TimeoutException catch (_) { // Fluttertoast.showToast( @@ -188,7 +187,7 @@ class Request { required Map? param}) async { Response response; try { - response = await delete(Uri.http(host, path, param), + response = await delete(Uri.https(host, path, param), headers: headers, body: jsonEncode(body)) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { diff --git a/lib/utils/urls.dart b/lib/utils/urls.dart index 4816b5a..db21be2 100644 --- a/lib/utils/urls.dart +++ b/lib/utils/urls.dart @@ -281,7 +281,7 @@ class Url { } String agencies() { - return "/api/jobnet_app/agencies/"; + return "/api/jobnet_app/agencies/"; } String postAgencies() { @@ -309,7 +309,10 @@ class Url { } String getRoleAssignment() { - return "api/account/auth/role_assignment/"; + return "/api/account/auth/role_assignment/"; + } + String getPermissionAssignment(){ + return "/api/account/auth/permission_assignment/"; } String getStationType() { @@ -334,7 +337,7 @@ class Url { } String getProvinces() { - return "api/web_app/location/province/"; + return "/api/web_app/location/province/"; } String getCities() { diff --git a/pubspec.lock b/pubspec.lock index e336cb5..ff780b9 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -21,18 +21,10 @@ packages: dependency: "direct main" description: name: animate_do - sha256: "9aeacc1a7238f971c039bdf45d13c628be554a242e0251c4ddda09d19a1a923f" + sha256: "91b3e0306ba2096c7a7e1ee1ba96f491e25e92034c215f4bf8de6a7251c4bef1" url: "https://pub.dev" source: hosted - version: "3.0.2" - animated_splash_screen: - dependency: "direct main" - description: - name: animated_splash_screen - sha256: f45634db6ec4e8cf034c53e03f3bd83898a16fe3c9286bf5510b6831dfcf2124 - url: "https://pub.dev" - source: hosted - version: "1.3.0" + version: "3.1.2" app_popup_menu: dependency: "direct main" description: @@ -85,58 +77,58 @@ packages: dependency: "direct main" description: name: audioplayers - sha256: "61583554386721772f9309f509e17712865b38565a903c761f96b1115a979282" + sha256: "8e94499b5c123df14cf17c16639de5ff3373e57e537f727e367487fbb7491363" url: "https://pub.dev" source: hosted - version: "4.1.0" + version: "5.1.0" audioplayers_android: dependency: transitive description: name: audioplayers_android - sha256: dbdc9b7f2aa2440314c638aa55aadd45c7705e8340d5eddf2e3fb8da32d4ae2c + sha256: "1c12b60cc10a3b8617ca3f88b927e7e03768f470d9b4f747efd3d58a8a07ee1b" url: "https://pub.dev" source: hosted - version: "3.0.2" + version: "4.0.1" audioplayers_darwin: dependency: transitive description: name: audioplayers_darwin - sha256: "6aea96df1d12f7ad5a71d88c6d1b22a216211a9564219920124c16768e456e9d" + sha256: "2fb6133ffcf28fb3f9d3e11f8a3ef190e5fedb2b7b95ea865b56a21d1163e670" url: "https://pub.dev" source: hosted - version: "4.1.0" + version: "5.0.1" audioplayers_linux: dependency: transitive description: name: audioplayers_linux - sha256: "396b62ac62c92dd26c3bc5106583747f57a8b325ebd2b41e5576f840cfc61338" + sha256: cca3f272c7186dd2e0025b8864e1413ac5e081d74b17e28b02ceb2df4c110235 url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "3.0.0" audioplayers_platform_interface: dependency: transitive description: name: audioplayers_platform_interface - sha256: f7daaed4659143094151ecf6bacd927d29ab8acffba98c110c59f0b81ae51143 + sha256: "47eae55e99ced11589998cf27e4eaabf5b475a7bd8bea7516ee6c2536a2e1abf" url: "https://pub.dev" source: hosted - version: "5.0.1" + version: "6.0.0" audioplayers_web: dependency: transitive description: name: audioplayers_web - sha256: ec84fd46eed1577148ed4113f5998a36a18da4fce7170c37ce3e21b631393339 + sha256: "9f155590c6ba9ba469df637f4729264e4234dc3941ece4690dad63ffac19b5af" url: "https://pub.dev" source: hosted - version: "3.1.0" + version: "4.0.0" audioplayers_windows: dependency: transitive description: name: audioplayers_windows - sha256: "1d3aaac98a192b8488167711ba1e67d8b96333e8d0572ede4e2912e5bbce69a3" + sha256: "8813b712ba919bb324bde5e3ba97edc81bface945953a54a3dea70b5608bcc70" url: "https://pub.dev" source: hosted - version: "2.0.2" + version: "3.0.0" auto_size_text: dependency: "direct main" description: @@ -165,10 +157,10 @@ packages: dependency: "direct main" description: name: badges - sha256: "6e7f3ec561ec08f47f912cfe349d4a1707afdc8dda271e17b046aa6d42c89e77" + sha256: a7b6bbd60dce418df0db3058b53f9d083c22cdb5132a052145dc267494df0b84 url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "3.1.2" barcode_scan2: dependency: "direct main" description: @@ -177,6 +169,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.2.4" + better_open_file: + dependency: "direct main" + description: + name: better_open_file + sha256: aa67d9bc38160401e48023833f93c789b4e2b1c0eb8b6643bd5816d0c1c65dbd + url: "https://pub.dev" + source: hosted + version: "3.6.4" bloc: dependency: transitive description: @@ -341,10 +341,10 @@ packages: dependency: "direct main" description: name: cool_alert - sha256: "48a0b6c04914b6dc7e8d7eaccf2adf21bace6533a3eda0aeb412e0d7a03dc00a" + sha256: "080a6c3503a4cded8f626cdead23f17ea40ff066ff50847d71a7a264032ab092" url: "https://pub.dev" source: hosted - version: "1.1.0" + version: "2.0.1" cross_file: dependency: transitive description: @@ -394,13 +394,13 @@ packages: source: hosted version: "2.0.1" device_info_plus: - dependency: transitive + dependency: "direct main" description: name: device_info_plus - sha256: f52ab3b76b36ede4d135aab80194df8925b553686f0fa12226b4e2d658e45903 + sha256: "86add5ef97215562d2e090535b0a16f197902b10c369c558a100e74ea06e8659" url: "https://pub.dev" source: hosted - version: "8.2.2" + version: "9.0.3" device_info_plus_platform_interface: dependency: transitive description: @@ -413,10 +413,10 @@ packages: dependency: "direct main" description: name: dio - sha256: "7d328c4d898a61efc3cd93655a0955858e29a0aa647f0f9e02d59b3bb275e2e8" + sha256: "417e2a6f9d83ab396ec38ff4ea5da6c254da71e4db765ad737a42af6930140b7" url: "https://pub.dev" source: hosted - version: "4.0.6" + version: "5.3.3" easy_app_installer: dependency: "direct main" description: @@ -477,10 +477,10 @@ packages: dependency: "direct main" description: name: file_picker - sha256: "9d6e95ec73abbd31ec54d0e0df8a961017e165aba1395e462e5b31ea0c165daf" + sha256: be325344c1f3070354a1d84a231a1ba75ea85d413774ec4bdf444c023342e030 url: "https://pub.dev" source: hosted - version: "5.3.1" + version: "5.5.0" file_utils: dependency: transitive description: @@ -562,10 +562,10 @@ packages: dependency: "direct main" description: name: flutter_form_builder - sha256: "9551c7379adc01a3a3a1100057396407c9534ea8adc937d14a0edd96fcd9e1dc" + sha256: "8973beed34b6d951d36bf688b52e9e3040b47b763c35c320bd6f4c2f6b13f3a2" url: "https://pub.dev" source: hosted - version: "7.8.0" + version: "9.1.1" flutter_lints: dependency: "direct dev" description: @@ -607,10 +607,10 @@ packages: dependency: "direct main" description: name: flutter_speed_dial - sha256: "41d7ad0bc224248637b3a5e0b9083e912a75445bdb450cf82b8ed06d7af7c61d" + sha256: "698a037274a66dbae8697c265440e6acb6ab6cae9ac5f95c749e7944d8f28d41" url: "https://pub.dev" source: hosted - version: "6.2.0" + version: "7.0.0" flutter_spinkit: dependency: "direct main" description: @@ -631,10 +631,10 @@ packages: dependency: "direct main" description: name: flutter_svg - sha256: "6ff9fa12892ae074092de2fa6a9938fb21dbabfdaa2ff57dc697ff912fc8d4b2" + sha256: "8c5d68a82add3ca76d792f058b186a0599414f279f00ece4830b9b231b570338" url: "https://pub.dev" source: hosted - version: "1.1.6" + version: "2.0.7" flutter_test: dependency: "direct dev" description: flutter @@ -673,10 +673,10 @@ packages: dependency: "direct main" description: name: form_builder_validators - sha256: f2d90439c56345c23ad8d0c2912e4002cd02563d816f4387c9495051c10d3321 + sha256: "19aa5282b7cede82d0025ab031a98d0554b84aa2ba40f12013471a3b3e22bf02" url: "https://pub.dev" source: hosted - version: "8.6.1" + version: "9.1.0" frontend_server_client: dependency: transitive description: @@ -737,18 +737,18 @@ packages: dependency: "direct dev" description: name: hive_generator - sha256: "81fd20125cb2ce8fd23623d7744ffbaf653aae93706c9bd3bf7019ea0ace3938" + sha256: "06cb8f58ace74de61f63500564931f9505368f45f98958bd7a6c35ba24159db4" url: "https://pub.dev" source: hosted - version: "1.1.3" + version: "2.0.1" http: dependency: transitive description: name: http - sha256: "5895291c13fa8a3bd82e76d5627f69e0d85ca6a30dcac95c4ea19a5d555879c2" + sha256: "759d1a329847dd0f39226c688d3e06a6b8679668e350e2891a6474f8b4bb8525" url: "https://pub.dev" source: hosted - version: "0.13.6" + version: "1.1.0" http_multi_server: dependency: transitive description: @@ -777,10 +777,10 @@ packages: dependency: transitive description: name: image - sha256: "8e9d133755c3e84c73288363e6343157c383a0c6c56fc51afcc5d4d7180306d6" + sha256: a72242c9a0ffb65d03de1b7113bc4e189686fc07c7147b8b41811d0dd0e0d9bf url: "https://pub.dev" source: hosted - version: "3.3.0" + version: "4.0.17" intl: dependency: "direct main" description: @@ -825,26 +825,26 @@ packages: dependency: "direct main" description: name: location - sha256: "9051959f6f2ccadd887b28b66e9cbbcc25b6838e37cf9e894c421ccc0ebf80b5" + sha256: "06be54f682c9073cbfec3899eb9bc8ed90faa0e17735c9d9fa7fe426f5be1dd1" url: "https://pub.dev" source: hosted - version: "4.4.0" + version: "5.0.3" location_platform_interface: dependency: transitive description: name: location_platform_interface - sha256: "62eeaf1658e92e4459b727f55a3c328eccbac8ba043fa6d262ac5286ad48384c" + sha256: "8aa1d34eeecc979d7c9fe372931d84f6d2ebbd52226a54fe1620de6fdc0753b1" url: "https://pub.dev" source: hosted - version: "2.3.0" + version: "3.1.2" location_web: dependency: transitive description: name: location_web - sha256: "6c08c408a040534c0269c4ff9fe17eebb5a36dea16512fbaf116b9c8bc21545b" + sha256: ec484c66e8a4ff1ee5d044c203f4b6b71e3a0556a97b739a5bc9616de672412b url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "4.2.0" logging: dependency: transitive description: @@ -857,10 +857,10 @@ packages: dependency: transitive description: name: lottie - sha256: "893da7a0022ec2fcaa616f34529a081f617e86cc501105b856e5a3184c58c7c2" + sha256: b8bdd54b488c54068c57d41ae85d02808da09e2bee8b8dd1f59f441e7efa60cd url: "https://pub.dev" source: hosted - version: "1.4.3" + version: "2.6.0" mask_text_input_formatter: dependency: "direct main" description: @@ -905,18 +905,18 @@ packages: dependency: "direct main" description: name: modal_progress_hud_nsn - sha256: "408b9bcce97567de94637de932260e50be48db1842edc761aeea61670e5ec30c" + sha256: "0b0d95e5ce3e1884390624fbe79fcf90d7de10abe05d26c0e276c25e7130e3e0" url: "https://pub.dev" source: hosted - version: "0.3.0" + version: "0.4.0" multi_dropdown: dependency: "direct main" description: name: multi_dropdown - sha256: "65b8f505b251c5173e8eff64c09cd37460d8f8be906c2069a03815ad2641dcd1" + sha256: "2db9b41ae543a9277defc2b5ba95622acb72ed0fb49d6dead357a1639371bee3" url: "https://pub.dev" source: hosted - version: "1.0.9" + version: "2.1.0" multi_select_flutter: dependency: "direct main" description: @@ -969,10 +969,10 @@ packages: dependency: "direct main" description: name: package_info_plus - sha256: "10259b111176fba5c505b102e3a5b022b51dd97e30522e906d6922c745584745" + sha256: "6ff267fcd9d48cb61c8df74a82680e8b82e940231bb5f68356672fde0397334a" url: "https://pub.dev" source: hosted - version: "3.1.2" + version: "4.1.0" package_info_plus_platform_interface: dependency: transitive description: @@ -981,14 +981,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.1" - page_transition: - dependency: transitive - description: - name: page_transition - sha256: dee976b1f23de9bbef5cd512fe567e9f6278caee11f5eaca9a2115c19dc49ef6 - url: "https://pub.dev" - source: hosted - version: "2.1.0" path: dependency: transitive description: @@ -1065,18 +1057,18 @@ packages: dependency: "direct main" description: name: permission_handler - sha256: "63e5216aae014a72fe9579ccd027323395ce7a98271d9defa9d57320d001af81" + sha256: ad65ba9af42a3d067203641de3fd9f547ded1410bad3b84400c2b4899faede70 url: "https://pub.dev" source: hosted - version: "10.4.3" + version: "11.0.0" permission_handler_android: dependency: transitive description: name: permission_handler_android - sha256: d74e77a5ecd38649905db0a7d05ef16bed42ff263b9efb73ed794317c5764ec3 + sha256: f2543a236584a5e8be79076f858022f100ce690e31530e6fa4c32ac94f276d3a url: "https://pub.dev" source: hosted - version: "10.3.4" + version: "11.0.3" permission_handler_apple: dependency: transitive description: @@ -1089,10 +1081,10 @@ packages: dependency: transitive description: name: permission_handler_platform_interface - sha256: "7c6b1500385dd1d2ca61bb89e2488ca178e274a69144d26bbd65e33eae7c02a9" + sha256: f2343e9fa9c22ae4fd92d4732755bfe452214e7189afcc097380950cf567b4b2 url: "https://pub.dev" source: hosted - version: "3.11.3" + version: "3.11.5" permission_handler_windows: dependency: transitive description: @@ -1105,10 +1097,10 @@ packages: dependency: transitive description: name: petitparser - sha256: "49392a45ced973e8d94a85fdb21293fbb40ba805fc49f2965101ae748a3683b4" + sha256: cb3798bef7fc021ac45b308f4b51208a152792445cce0448c9a4ba5879dd8750 url: "https://pub.dev" source: hosted - version: "5.1.0" + version: "5.4.0" platform: dependency: transitive description: @@ -1241,18 +1233,18 @@ packages: dependency: transitive description: name: rive - sha256: f3b8af0898c987d68019e91d92257edd902c28c816e49de033a7272e86bd5425 + sha256: f2117a96a189758bc79bf7933865625c7a44a420ae537d2a8f6c492900136a71 url: "https://pub.dev" source: hosted - version: "0.11.4" + version: "0.11.17" rive_common: dependency: transitive description: name: rive_common - sha256: f6687f9d70e6fd3888a9b0e9c0b307966d2ce74cf00cfb01dce906c3bbada52f + sha256: e41f12917cb58e0c9376836490ebaa431e12744da0c67e19dad8d4bee9fedd46 url: "https://pub.dev" source: hosted - version: "0.1.0" + version: "0.2.7" rxdart: dependency: transitive description: @@ -1289,10 +1281,10 @@ packages: dependency: "direct main" description: name: searchfield - sha256: "62b6653d7194de5a7ea724124846b996d0d211cd3eeeec2e5ca84423650f66f8" + sha256: ea1eccae9f6d07dbbfef0bf341dd93b22df453b939461c5473a0be6186f2d720 url: "https://pub.dev" source: hosted - version: "0.7.8" + version: "0.8.4" share_plus: dependency: "direct main" description: @@ -1385,10 +1377,10 @@ packages: dependency: "direct main" description: name: signature - sha256: ad23383717dfa926204695ef6928ff513a77387be1b4a8c685099ce3ec35e5f8 + sha256: d95143b8e310b395ea0be59a46bb69fa24106cb6ec79815fc56fd320268e24e6 url: "https://pub.dev" source: hosted - version: "5.3.0" + version: "5.4.0" simple_chips_input: dependency: "direct main" description: @@ -1486,58 +1478,66 @@ packages: dependency: transitive description: name: syncfusion_flutter_core - sha256: "8db8f55c77f56968681447d3837c10f27a9e861e238a898fda116c7531def979" + sha256: aea119c8117953fa5decf4a313b431e556b0959cd35ff88f8fbdc0eda9bedb06 url: "https://pub.dev" source: hosted - version: "21.2.10" + version: "23.1.36" syncfusion_flutter_pdf: dependency: transitive description: name: syncfusion_flutter_pdf - sha256: a42186922a416c2c9634a8f221aee261101babc2d30b1a1e908a7f034e743046 + sha256: "76a50a1d580714c078e2827adbd8b00d5f5c606879d07c44c5d99f0e864edda1" url: "https://pub.dev" source: hosted - version: "21.2.4" + version: "23.1.36" syncfusion_flutter_pdfviewer: dependency: "direct main" description: name: syncfusion_flutter_pdfviewer - sha256: "2dc016f251c675f8e4923135c485356473b4d89c677670164292159cd1dd4f45" + sha256: e5eaabd0a31fff16caead0d6d66d4c9946de7e46c89da7736de23cd4b2e6f676 url: "https://pub.dev" source: hosted - version: "21.2.3" + version: "23.1.36" + syncfusion_flutter_signaturepad: + dependency: transitive + description: + name: syncfusion_flutter_signaturepad + sha256: ea6b218d127e0315b3309ee072a1d304c76aa7c497a196b3474f9c6b38c01f82 + url: "https://pub.dev" + source: hosted + version: "23.1.36" syncfusion_pdfviewer_macos: dependency: transitive description: name: syncfusion_pdfviewer_macos - sha256: "8cc925cae532c0fa17e849165796d962107f45b86e66ee334dcaabf6b7305c82" + sha256: "6f928bee1f786b8d1939d3c4142c5cc2de2c13d19262d302878935a2bc33850c" url: "https://pub.dev" source: hosted - version: "21.2.10" + version: "23.1.36" syncfusion_pdfviewer_platform_interface: dependency: transitive description: name: syncfusion_pdfviewer_platform_interface - sha256: "08039ecdb8f79454fb367c6bf5a833846a666039415d2b5d76a7e59a5b3ff710" + sha256: "0251864fb82e2bd92a1b17e8562fe342e78cd530e26b0d2f54e94a441ccb4584" url: "https://pub.dev" source: hosted - version: "21.2.10" + version: "23.1.36" syncfusion_pdfviewer_web: dependency: transitive description: name: syncfusion_pdfviewer_web - sha256: "8e5ed0d313a1aa3869e4f2e8d079bc9bfa37ce79d91be7bb328e456f37b7995f" + sha256: eb224f52e86326dbf08ea12978c3db0b4e376866a84d4fcb131fc06ec93cbe20 url: "https://pub.dev" source: hosted - version: "21.2.10" + version: "23.1.36" syncfusion_pdfviewer_windows: dependency: transitive description: name: syncfusion_pdfviewer_windows - sha256: "3e93f281135fb0562f7e6c343d2db741cf3cbd78c5b04884eef9af414408bc77" + sha256: aca74797a97512f4d3ca2be0ed49193fae7e5fd29a9b1b1139429d39c9216bf9 url: "https://pub.dev" source: hosted - version: "21.2.10" + version: "23.1.36" synchronized: dependency: transitive description: @@ -1598,12 +1598,12 @@ packages: dependency: "direct main" description: name: url_launcher - sha256: eb1e00ab44303d50dd487aab67ebc575456c146c6af44422f9c13889984c00f3 + sha256: "47e208a6711459d813ba18af120d9663c20bdf6985d6ad39fe165d2538378d27" url: "https://pub.dev" source: hosted - version: "6.1.11" + version: "6.1.14" url_launcher_android: - dependency: "direct main" + dependency: transitive description: name: url_launcher_android sha256: b04af59516ab45762b2ca6da40fa830d72d0f6045cd97744450b73493fa76330 @@ -1666,6 +1666,30 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.7" + vector_graphics: + dependency: transitive + description: + name: vector_graphics + sha256: "670f6e07aca990b4a2bcdc08a784193c4ccdd1932620244c3a86bb72a0eac67f" + url: "https://pub.dev" + source: hosted + version: "1.1.7" + vector_graphics_codec: + dependency: transitive + description: + name: vector_graphics_codec + sha256: "7451721781d967db9933b63f5733b1c4533022c0ba373a01bdd79d1a5457f69f" + url: "https://pub.dev" + source: hosted + version: "1.1.7" + vector_graphics_compiler: + dependency: transitive + description: + name: vector_graphics_compiler + sha256: "80a13c613c8bde758b1464a1755a7b3a8f2b6cec61fbf0f5a53c94c30f03ba2e" + url: "https://pub.dev" + source: hosted + version: "1.1.7" vector_math: dependency: transitive description: @@ -1702,10 +1726,18 @@ packages: dependency: transitive description: name: win32 - sha256: "5a751eddf9db89b3e5f9d50c20ab8612296e4e8db69009788d6c8b060a84191c" + sha256: f2add6fa510d3ae152903412227bda57d0d5a8da61d2c39c1fb022c9429a41c0 url: "https://pub.dev" source: hosted - version: "4.1.4" + version: "5.0.6" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: e4506d60b7244251bc59df15656a3093501c37fb5af02105a944d73eb95be4c9 + url: "https://pub.dev" + source: hosted + version: "1.1.1" xdg_directories: dependency: transitive description: @@ -1718,10 +1750,10 @@ packages: dependency: transitive description: name: xml - sha256: "979ee37d622dec6365e2efa4d906c37470995871fe9ae080d967e192d88286b5" + sha256: "5bc72e1e45e941d825fd7468b9b4cc3b9327942649aeb6fc5cdbf135f0a86e84" url: "https://pub.dev" source: hosted - version: "6.2.2" + version: "6.3.0" yaml: dependency: transitive description: @@ -1731,5 +1763,10 @@ packages: source: hosted version: "3.1.2" sdks: +<<<<<<< HEAD dart: ">=3.1.0-185.0.dev <4.0.0" flutter: ">=3.7.0" +======= + dart: ">=3.1.0 <4.0.0" + flutter: ">=3.10.0" +>>>>>>> develop diff --git a/pubspec.yaml b/pubspec.yaml index e19d2bf..23e8c68 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -36,15 +36,15 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. flutter_custom_clippers: ^2.0.0 - flutter_svg: ^1.1.6 - flutter_form_builder: ^7.7.0 - form_builder_validators: any + flutter_svg: ^2.0.7 + flutter_form_builder: ^9.1.1 + form_builder_validators: ^9.1.0 fluttericon: ^2.0.0 fluttertoast: ^8.1.1 flutter_zoom_drawer: ^3.0.3 cached_network_image: ^3.2.3 auto_size_text: ^3.0.0 - animate_do: ^3.0.2 + animate_do: ^3.1.2 flutter_spinkit: ^5.1.0 toggle_switch: ^2.0.1 convex_bottom_bar: ^3.1.0+1 @@ -54,34 +54,34 @@ dependencies: flutter_progress_hud: ^2.0.2 barcode_scan2: ^4.2.1 qr_flutter: ^4.0.0 - signature: ^5.3.0 + signature: ^5.4.0 awesome_dialog: ^3.0.2 system_info2: ^2.0.4 flutter_bloc: ^8.0.0 equatable: ^2.0.5 - package_info_plus: ^3.0.2 + package_info_plus: 4.1.0 easy_app_installer: ^1.0.0 path_provider: ^2.0.14 - dio: ^4.0.6 - cool_alert: ^1.1.0 - permission_handler: ^10.2.0 + dio: ^5.3.3 + cool_alert: ^2.0.1 + permission_handler: ^11.0.0 expandable_group: ^0.0.8 - badges: ^3.0.2 + badges: ^3.1.2 app_popup_menu: ^1.0.0 - modal_progress_hud_nsn: ^0.3.0 - searchfield: ^0.7.5 + modal_progress_hud_nsn: ^0.4.0 + searchfield: ^0.8.4 filter_list: ^1.0.2 simple_chips_input: ^1.0.0 hive: ^2.0.5 hive_flutter: ^1.1.0 mask_text_input_formatter: ^2.4.0 - location: ^4.3.0 + location: ^5.0.3 platform_device_id: ^1.0.1 - multi_dropdown: ^1.0.9 + multi_dropdown: ^2.1.0 searchable_paginated_dropdown: ^1.2.0 - audioplayers: ^4.1.0 + audioplayers: ^5.1.0 assets_audio_player: ^3.0.6 - flutter_speed_dial: ^6.2.0 + flutter_speed_dial: ^7.0.0 im_stepper: ^1.0.1+1 shared_preferences: ^2.0.20 multiselect: any @@ -90,16 +90,17 @@ dependencies: flutter_staggered_animations: ^1.1.1 group_list_view: ^1.1.1 search_page: ^2.3.0 - file_picker: ^5.3.1 + file_picker: ^5.5.0 expandable: ^5.0.1 flutter_simple_treeview: ^3.0.2 - syncfusion_flutter_pdfviewer: ^21.2.3 - url_launcher: ^6.1.11 - url_launcher_android: ^6.0.38 + syncfusion_flutter_pdfviewer: ^23.1.36 + url_launcher: ^6.1.14 share_plus: ^7.1.0 animated_splash_screen: ^1.3.0 sqflite: ^2.3.0 + device_info_plus: ^9.0.3 + better_open_file: ^3.6.4 dependency_overrides: intl: ^0.18.0 @@ -116,7 +117,7 @@ dev_dependencies: # rules and activating additional ones. flutter_lints: ^2.0.0 build_runner: ^2.1.7 - hive_generator: ^1.1.2 + hive_generator: ^2.0.1 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 7af50e4..fe3ce53 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -7,7 +7,7 @@ #include "generated_plugin_registrant.h" #include -#include +#include #include #include #include @@ -18,8 +18,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) { AudioplayersWindowsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin")); - ModalProgressHudNsnPluginRegisterWithRegistrar( - registry->GetRegistrarForPlugin("ModalProgressHudNsnPlugin")); + ModalProgressHudNsnPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ModalProgressHudNsnPluginCApi")); PermissionHandlerWindowsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin")); PlatformDeviceIdWindowsPluginRegisterWithRegistrar(